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
70,405
<p>I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it?</p>
[ { "answer_id": 70413, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 2, "selected": false, "text": "<p>I think the nearest in the .NET Framework is </p>\n\n<pre>\nstring.Split()\n</pre>\n" }, { "answer_id": 70425, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 4, "selected": false, "text": "<p>The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.</p>\n" }, { "answer_id": 70436, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 8, "selected": true, "text": "<p>You could use <a href=\"http://msdn.microsoft.com/en-us/library/system.string.split.aspx\" rel=\"noreferrer\" title=\"String.Split method msdn reference\">String.Split method</a>.</p>\n\n<pre><code>class ExampleClass\n{\n public ExampleClass()\n {\n string exampleString = \"there is a cat\";\n // Split string on spaces. This will separate all the words in a string\n string[] words = exampleString.Split(' ');\n foreach (string word in words)\n {\n Console.WriteLine(word);\n // there\n // is\n // a\n // cat\n }\n }\n}\n</code></pre>\n\n<p>For more information see <a href=\"http://www.dotnetperls.com/split\" rel=\"noreferrer\" title=\"C# Split String Examples by Sam Allen\">Sam Allen's article about splitting strings in c#</a> (Performance, Regex)</p>\n" }, { "answer_id": 70449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For complex splitting you could use a regex creating a match collection.</p>\n" }, { "answer_id": 70463, "author": "Paul Shannon", "author_id": 11503, "author_profile": "https://Stackoverflow.com/users/11503", "pm_score": -1, "selected": false, "text": "<p>If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:</p>\n\n<pre><code>string.SplitByMyTokens();\n</code></pre>\n\n<p>More info and a useful example from MS here <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb383977.aspx</a></p>\n" }, { "answer_id": 1205918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>use <code>Regex.Split(string,\"#|#\");</code></p>\n" }, { "answer_id": 1720739, "author": "Musa", "author_id": 209393, "author_profile": "https://Stackoverflow.com/users/209393", "pm_score": 0, "selected": false, "text": "<p>read this, split function has an overload takes an array consist of seperators\n<a href=\"http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx</a></p>\n" }, { "answer_id": 18905125, "author": "demongolem", "author_id": 236247, "author_profile": "https://Stackoverflow.com/users/236247", "pm_score": 5, "selected": false, "text": "<p>I just want to highlight the power of C#'s Split method and give a more detailed comparison, particularly from someone who comes from a Java background.</p>\n\n<p>Whereas StringTokenizer in Java only allows a single delimiter, we can actually split on multiple delimiters making regular expressions less necessary (although if one needs regex, use regex by all means!) Take for example this:</p>\n\n<pre><code>str.Split(new char[] { ' ', '.', '?' })\n</code></pre>\n\n<p>This splits on three different delimiters returning an array of tokens. We can also remove empty arrays with what would be a second parameter for the above example:</p>\n\n<pre><code>str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries)\n</code></pre>\n\n<p>One thing Java's String tokenizer does have that I believe C# is lacking (at least Java 7 has this feature) is the ability to keep the delimiter(s) as tokens. C#'s Split will discard the tokens. This could be important in say some NLP applications, but for more general purpose applications this might not be a problem.</p>\n" }, { "answer_id": 30768986, "author": "Skyler", "author_id": 4997033, "author_profile": "https://Stackoverflow.com/users/4997033", "pm_score": 2, "selected": false, "text": "<pre><code>_words = new List&lt;string&gt;(YourText.ToLower().Trim('\\n', '\\r').Split(' ').\n Select(x =&gt; new string(x.Where(Char.IsLetter).ToArray()))); \n</code></pre>\n\n<p>Or </p>\n\n<pre><code>_words = new List&lt;string&gt;(YourText.Trim('\\n', '\\r').Split(' ').\n Select(x =&gt; new string(x.Where(Char.IsLetterOrDigit).ToArray()))); \n</code></pre>\n" }, { "answer_id": 39299866, "author": "neronovs", "author_id": 5771796, "author_profile": "https://Stackoverflow.com/users/5771796", "pm_score": 2, "selected": false, "text": "<p>The similar to Java's method is:</p>\n\n<pre><code>Regex.Split(string, pattern);\n</code></pre>\n\n<p>where</p>\n\n<ul>\n<li><code>string</code> - the text you need to split</li>\n<li><code>pattern</code> - string type pattern, what is splitting the text</li>\n</ul>\n" }, { "answer_id": 41133477, "author": "Nigel Thomas", "author_id": 5221568, "author_profile": "https://Stackoverflow.com/users/5221568", "pm_score": -1, "selected": false, "text": "<p>If you're trying to do something like splitting command line arguments in a .NET Console app, you're going to have issues because .NET is either broken or is trying to be clever (which means it's as good as broken). I needed to be able to split arguments by the space character, preserving any literals that were quoted so they didn't get split in the middle. This is the code I wrote to do the job:</p>\n\n<pre><code>private static List&lt;String&gt; Tokenise(string value, char seperator)\n{\n List&lt;string&gt; result = new List&lt;string&gt;();\n value = value.Replace(\" \", \" \").Replace(\" \", \" \").Trim();\n StringBuilder sb = new StringBuilder();\n bool insideQuote = false;\n foreach(char c in value.ToCharArray())\n {\n if(c == '\"')\n {\n insideQuote = !insideQuote;\n }\n if((c == seperator) &amp;&amp; !insideQuote)\n {\n if (sb.ToString().Trim().Length &gt; 0)\n {\n result.Add(sb.ToString().Trim());\n sb.Clear();\n }\n }\n else\n {\n sb.Append(c);\n }\n }\n if (sb.ToString().Trim().Length &gt; 0)\n {\n result.Add(sb.ToString().Trim());\n }\n\n return result;\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it?
You could use [String.Split method](http://msdn.microsoft.com/en-us/library/system.string.split.aspx "String.Split method msdn reference"). ``` class ExampleClass { public ExampleClass() { string exampleString = "there is a cat"; // Split string on spaces. This will separate all the words in a string string[] words = exampleString.Split(' '); foreach (string word in words) { Console.WriteLine(word); // there // is // a // cat } } } ``` For more information see [Sam Allen's article about splitting strings in c#](http://www.dotnetperls.com/split "C# Split String Examples by Sam Allen") (Performance, Regex)
70,417
<p>I have the following code:</p> <pre><code>Dim obj As New Access.Application obj.OpenCurrentDatabase (CurrentProject.Path &amp; "\Working.mdb") obj.Run "Routine" obj.CloseCurrentDatabase Set obj = Nothing </code></pre> <p>The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.</p> <p>I'm working with MS Access 2003.</p> <p>This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.</p> <p>I suspect this may occur when someone is working with this or the other database.</p> <p>The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.</p> <p>Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If</p> <p>I'll make another subroutine without the MsgBox.</p> <p>I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.</p> <hr> <p>This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.</p> <p>I suspect this may occur when someone is working with this or the other database.</p> <p>The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.</p> <p>Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If</p> <p>I'll make another subroutine without the MsgBox.</p> <hr> <p>I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.</p>
[ { "answer_id": 70413, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 2, "selected": false, "text": "<p>I think the nearest in the .NET Framework is </p>\n\n<pre>\nstring.Split()\n</pre>\n" }, { "answer_id": 70425, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 4, "selected": false, "text": "<p>The split method of a string is what you need. In fact the tokenizer class in Java is deprecated in favor of Java's string split method.</p>\n" }, { "answer_id": 70436, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 8, "selected": true, "text": "<p>You could use <a href=\"http://msdn.microsoft.com/en-us/library/system.string.split.aspx\" rel=\"noreferrer\" title=\"String.Split method msdn reference\">String.Split method</a>.</p>\n\n<pre><code>class ExampleClass\n{\n public ExampleClass()\n {\n string exampleString = \"there is a cat\";\n // Split string on spaces. This will separate all the words in a string\n string[] words = exampleString.Split(' ');\n foreach (string word in words)\n {\n Console.WriteLine(word);\n // there\n // is\n // a\n // cat\n }\n }\n}\n</code></pre>\n\n<p>For more information see <a href=\"http://www.dotnetperls.com/split\" rel=\"noreferrer\" title=\"C# Split String Examples by Sam Allen\">Sam Allen's article about splitting strings in c#</a> (Performance, Regex)</p>\n" }, { "answer_id": 70449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For complex splitting you could use a regex creating a match collection.</p>\n" }, { "answer_id": 70463, "author": "Paul Shannon", "author_id": 11503, "author_profile": "https://Stackoverflow.com/users/11503", "pm_score": -1, "selected": false, "text": "<p>If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:</p>\n\n<pre><code>string.SplitByMyTokens();\n</code></pre>\n\n<p>More info and a useful example from MS here <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb383977.aspx</a></p>\n" }, { "answer_id": 1205918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>use <code>Regex.Split(string,\"#|#\");</code></p>\n" }, { "answer_id": 1720739, "author": "Musa", "author_id": 209393, "author_profile": "https://Stackoverflow.com/users/209393", "pm_score": 0, "selected": false, "text": "<p>read this, split function has an overload takes an array consist of seperators\n<a href=\"http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx</a></p>\n" }, { "answer_id": 18905125, "author": "demongolem", "author_id": 236247, "author_profile": "https://Stackoverflow.com/users/236247", "pm_score": 5, "selected": false, "text": "<p>I just want to highlight the power of C#'s Split method and give a more detailed comparison, particularly from someone who comes from a Java background.</p>\n\n<p>Whereas StringTokenizer in Java only allows a single delimiter, we can actually split on multiple delimiters making regular expressions less necessary (although if one needs regex, use regex by all means!) Take for example this:</p>\n\n<pre><code>str.Split(new char[] { ' ', '.', '?' })\n</code></pre>\n\n<p>This splits on three different delimiters returning an array of tokens. We can also remove empty arrays with what would be a second parameter for the above example:</p>\n\n<pre><code>str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries)\n</code></pre>\n\n<p>One thing Java's String tokenizer does have that I believe C# is lacking (at least Java 7 has this feature) is the ability to keep the delimiter(s) as tokens. C#'s Split will discard the tokens. This could be important in say some NLP applications, but for more general purpose applications this might not be a problem.</p>\n" }, { "answer_id": 30768986, "author": "Skyler", "author_id": 4997033, "author_profile": "https://Stackoverflow.com/users/4997033", "pm_score": 2, "selected": false, "text": "<pre><code>_words = new List&lt;string&gt;(YourText.ToLower().Trim('\\n', '\\r').Split(' ').\n Select(x =&gt; new string(x.Where(Char.IsLetter).ToArray()))); \n</code></pre>\n\n<p>Or </p>\n\n<pre><code>_words = new List&lt;string&gt;(YourText.Trim('\\n', '\\r').Split(' ').\n Select(x =&gt; new string(x.Where(Char.IsLetterOrDigit).ToArray()))); \n</code></pre>\n" }, { "answer_id": 39299866, "author": "neronovs", "author_id": 5771796, "author_profile": "https://Stackoverflow.com/users/5771796", "pm_score": 2, "selected": false, "text": "<p>The similar to Java's method is:</p>\n\n<pre><code>Regex.Split(string, pattern);\n</code></pre>\n\n<p>where</p>\n\n<ul>\n<li><code>string</code> - the text you need to split</li>\n<li><code>pattern</code> - string type pattern, what is splitting the text</li>\n</ul>\n" }, { "answer_id": 41133477, "author": "Nigel Thomas", "author_id": 5221568, "author_profile": "https://Stackoverflow.com/users/5221568", "pm_score": -1, "selected": false, "text": "<p>If you're trying to do something like splitting command line arguments in a .NET Console app, you're going to have issues because .NET is either broken or is trying to be clever (which means it's as good as broken). I needed to be able to split arguments by the space character, preserving any literals that were quoted so they didn't get split in the middle. This is the code I wrote to do the job:</p>\n\n<pre><code>private static List&lt;String&gt; Tokenise(string value, char seperator)\n{\n List&lt;string&gt; result = new List&lt;string&gt;();\n value = value.Replace(\" \", \" \").Replace(\" \", \" \").Trim();\n StringBuilder sb = new StringBuilder();\n bool insideQuote = false;\n foreach(char c in value.ToCharArray())\n {\n if(c == '\"')\n {\n insideQuote = !insideQuote;\n }\n if((c == seperator) &amp;&amp; !insideQuote)\n {\n if (sb.ToString().Trim().Length &gt; 0)\n {\n result.Add(sb.ToString().Trim());\n sb.Clear();\n }\n }\n else\n {\n sb.Append(c);\n }\n }\n if (sb.ToString().Trim().Length &gt; 0)\n {\n result.Add(sb.ToString().Trim());\n }\n\n return result;\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11498/" ]
I have the following code: ``` Dim obj As New Access.Application obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb") obj.Run "Routine" obj.CloseCurrentDatabase Set obj = Nothing ``` The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated. I'm working with MS Access 2003. This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened. I suspect this may occur when someone is working with this or the other database. The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database. Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If I'll make another subroutine without the MsgBox. I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user. --- This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened. I suspect this may occur when someone is working with this or the other database. The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database. Maybe, it's because of the first line in the 'Routines' code: If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then Exit Function End If I'll make another subroutine without the MsgBox. --- I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.
You could use [String.Split method](http://msdn.microsoft.com/en-us/library/system.string.split.aspx "String.Split method msdn reference"). ``` class ExampleClass { public ExampleClass() { string exampleString = "there is a cat"; // Split string on spaces. This will separate all the words in a string string[] words = exampleString.Split(' '); foreach (string word in words) { Console.WriteLine(word); // there // is // a // cat } } } ``` For more information see [Sam Allen's article about splitting strings in c#](http://www.dotnetperls.com/split "C# Split String Examples by Sam Allen") (Performance, Regex)
70,455
<p>I want to port data from one server's database to another server's database. The databases are both on a different mssql 2005 server. Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis.</p> <p>Preferebly I would do something like</p> <pre><code>insert * from db1/table1 into db2/table2 where rule1 = true </code></pre> <p>It's obvious that connection credentials would go in somehwere in this script.</p>
[ { "answer_id": 70464, "author": "Thomas Rushton", "author_id": 6977, "author_profile": "https://Stackoverflow.com/users/6977", "pm_score": 0, "selected": false, "text": "<p>Can you use the Data Transformation Services to do the job? This provides all sorts of bolt-together tools for doing this kind of thing.</p>\n\n<p>You can download the SQL Server 2005 feature pack from Microsoft's website\n<a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&amp;DisplayLang=en\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 70476, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "<p>Are SQL Server Integration Services (SSIS) an option? If so, I'd use that.</p>\n" }, { "answer_id": 70525, "author": "Matthew Pelser", "author_id": 6331, "author_profile": "https://Stackoverflow.com/users/6331", "pm_score": 6, "selected": true, "text": "<p>I think what you want to do is create a linked server as per <a href=\"http://web.archive.org/web/20150628090613/https://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx\" rel=\"nofollow noreferrer\">this webarchive snapshot of msdn article from 2015</a> or <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15\" rel=\"nofollow noreferrer\">this article from learn.microsoft.com</a>. You would then select using a 4 part object name eg:</p>\n<pre><code>Select * From ServerName.DbName.SchemaName.TableName\n</code></pre>\n" }, { "answer_id": 70817, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 1, "selected": false, "text": "<p>Would you be transferring the whole content of the database from one server to another or just some data from a couple of tables?</p>\n\n<p>For both options SSIS would do the job especially if you are planning to to the transfer on a regular basis. </p>\n\n<p>If you simply want to copy some data from 1 or 2 tables and prefer to do it using TSQL in SQL Management Studio then you can use linked server as suggested by pelser</p>\n\n<ol>\n<li>Set up the source database server as a linked server</li>\n<li>Use the following syntax to access data</li>\n</ol>\n\n<pre><code>select columnName1, columnName2, etc from serverName.databaseName.schemaName.tableName</code></pre>\n" }, { "answer_id": 72214, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 1, "selected": false, "text": "<p>Well I don't agree with your comment on replication. You can start a replication by creating a database from scratch, and you can control either the updates will be done by updating the available client database or simply recreating the database. </p>\n\n<p>Automated replication will ease your work by automatically managing keys and relations.</p>\n\n<p>I think the easiest thing to do is to start a snapshot replication through MSSQL Server Studio, get the T-SQL corresponding scripts (ie the corresponding T-SQL instructions for both publication and subscriptions), and record these scripts as part of a job in the Jobs list of the SQL Agent or as a replication job in the replications folder. </p>\n" }, { "answer_id": 76953, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could go the linked server route. </p>\n\n<p>you just can't use the select * into you have to do an insert into select. </p>\n\n<p>I would avoid replication if you don't have experience with it as it can be difficult to fix if it breaks and can be prone to other problems if not properly managed. </p>\n\n<p>Keep it simple especially if the databases are small.</p>\n" }, { "answer_id": 18659242, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 3, "selected": false, "text": "<p>You can use Open Data Source Like this : </p>\n\n<pre><code>EXEC sp_configure 'show advanced options', 1\nGO\nRECONFIGURE\nGO\n\nEXEC sp_configure 'Ad Hoc Distributed Queries', 1\nGO\nRECONFIGURE\nGO\n\n\nSELECT *\nFROM OPENDATASOURCE('SQLOLEDB',\n 'Data Source=&lt;Ip Of Your Server&gt;;\n User ID=&lt;SQL User Name&gt;;Password=&lt;SQL password&gt;').&lt;DataBase name&gt;.&lt;SchemaName&gt;.&lt;Table Or View Name&gt;\n\nGo\n</code></pre>\n" }, { "answer_id": 39628957, "author": "Ahmed Tambe", "author_id": 6861533, "author_profile": "https://Stackoverflow.com/users/6861533", "pm_score": -1, "selected": false, "text": "<pre><code>CREATE VIEW newR1 \nAS\nSELECT * from OPENQUERY ([INSTANCE_NAME], 'select * from DbName.SchemaName.TableName')\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
I want to port data from one server's database to another server's database. The databases are both on a different mssql 2005 server. Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis. Preferebly I would do something like ``` insert * from db1/table1 into db2/table2 where rule1 = true ``` It's obvious that connection credentials would go in somehwere in this script.
I think what you want to do is create a linked server as per [this webarchive snapshot of msdn article from 2015](http://web.archive.org/web/20150628090613/https://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx) or [this article from learn.microsoft.com](https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15). You would then select using a 4 part object name eg: ``` Select * From ServerName.DbName.SchemaName.TableName ```
70,471
<p>So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!</p> <p>Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?</p>
[ { "answer_id": 70519, "author": "Mark Embling", "author_id": 6844, "author_profile": "https://Stackoverflow.com/users/6844", "pm_score": 2, "selected": false, "text": "<p>My Java experience is not that high either, so anyone feel free to correct me. But AFAIK, the general convention is to write two methods like so:</p>\n\n<pre><code>public string getMyString() {\n // return it here\n}\n\npublic void setMyString(string myString) {\n // set it here\n}\n</code></pre>\n" }, { "answer_id": 70527, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 1, "selected": false, "text": "<p>If you're using eclipse then it has the capabilities to auto generate the getter and setter method for the internal attributes, it can be a usefull and timesaving tool.</p>\n" }, { "answer_id": 70530, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "<p>The bean convention is to write code like this:</p>\n\n<pre><code>private int foo;\npublic int getFoo() {\n return foo;\n}\npublic void setFoo(int newFoo) {\n foo = newFoo;\n}\n</code></pre>\n\n<p>In some of the other languages on the JVM, e.g., Groovy, you get overridable properties similar to C#, e.g.,</p>\n\n<pre><code>int foo\n</code></pre>\n\n<p>which is accessed with a simple <code>.foo</code> and leverages default <code>getFoo</code> and <code>setFoo</code> implementations that you can override as necessary.</p>\n" }, { "answer_id": 70535, "author": "Calum", "author_id": 8434, "author_profile": "https://Stackoverflow.com/users/8434", "pm_score": 7, "selected": true, "text": "<p>There is a &quot;standard&quot; pattern for getters and setters in Java, called <a href=\"http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html\" rel=\"nofollow noreferrer\">Bean properties</a>. Basically any method starting with <code>get</code>, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise <code>set</code> creates a setter of a void method with a single argument.</p>\n<p>For example:</p>\n<pre><code>// Getter for &quot;awesomeString&quot;\npublic String getAwesomeString() {\n return awesomeString;\n}\n\n// Setter for &quot;awesomeString&quot;\npublic void setAwesomeString( String awesomeString ) {\n this.awesomeString = awesomeString;\n}\n</code></pre>\n<p>Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting <kbd>Ctrl</kbd>-<kbd>1</kbd>, then selecting the option from the list).</p>\n<p>For what it's worth, for readability you can actually use <code>is</code> and <code>has</code> in place of <code>get</code> for boolean-type properties too, as in:</p>\n<pre><code>public boolean isAwesome();\n\npublic boolean hasAwesomeStuff();\n</code></pre>\n" }, { "answer_id": 70548, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 2, "selected": false, "text": "<p>Most IDEs for Java will automatically generate getter and setter code for you if you want them to. There are a number of different conventions, and an IDE like Eclipse will allow you to choose which one you want to use, and even let you define your own.</p>\n\n<p>Eclipse even includes automated refactoring that will allow you to wrap a property up in a getter and setter and it will modify all the code that accesses the property directly, to make it use the getter and/or setter.</p>\n\n<p>Of course, Eclipse can only modify code that it knows about - any external dependencies you have could be broken by such a refactoring.</p>\n" }, { "answer_id": 70987, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 4, "selected": false, "text": "<p>\"Java Property Support\" was proposed for Java 7, but did not make it into the language.</p>\n\n<p>See <a href=\"http://tech.puredanger.com/java7#property\" rel=\"noreferrer\">http://tech.puredanger.com/java7#property</a> for more links and info, if interested.</p>\n" }, { "answer_id": 72826, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 1, "selected": false, "text": "<p>I'm just releasing Java 5/6 annotations and an annotation processor to help this.</p>\n\n<p>Check out <a href=\"http://code.google.com/p/javadude/wiki/Annotations\" rel=\"nofollow noreferrer\">http://code.google.com/p/javadude/wiki/Annotations</a></p>\n\n<p>The documentation is a bit light right now, but the quickref should get the idea across.</p>\n\n<p>Basically it generates a superclass with the getters/setters (and many other code generation options).</p>\n\n<p>A sample class might look like</p>\n\n<pre><code>@Bean(properties = {\n @Property(name=\"name\", bound=true),\n @Property(name=\"age,type=int.class)\n})\npublic class Person extends PersonGen {\n}\n</code></pre>\n\n<p>There are many more samples available, and there are no runtime dependencies in the generated code.</p>\n\n<p>Send me an email if you try it out and find it useful!\n-- Scott</p>\n" }, { "answer_id": 18496921, "author": "dantuch", "author_id": 575659, "author_profile": "https://Stackoverflow.com/users/575659", "pm_score": 3, "selected": false, "text": "<pre><code>public class Animal {\n\n @Getter @Setter private String name;\n @Getter @Setter private String gender;\n @Getter @Setter private String species;\n}\n</code></pre>\n\n<p>This is something like C# properties. It's <a href=\"http://projectlombok.org/\">http://projectlombok.org/</a></p>\n" }, { "answer_id": 18496962, "author": "Aleks-Daniel Jakimenko-A.", "author_id": 2698019, "author_profile": "https://Stackoverflow.com/users/2698019", "pm_score": 5, "selected": false, "text": "<p>I am surprised that no one mentioned <a href=\"http://projectlombok.org/\" rel=\"noreferrer\">project lombok</a></p>\n\n<p>Yes, currently there are no properties in java. There are some other missing features as well.<br>\nBut luckily we have <a href=\"http://projectlombok.org/\" rel=\"noreferrer\">project lombok</a> that is trying to improve the situation. It is also getting more and more popular every day.</p>\n\n<p>So, if you're using lombok:</p>\n\n<pre><code>@Getter @Setter int awesomeInteger = 5;\n</code></pre>\n\n<p>This code is going to generate <code>getAwesomeInteger</code> and <code>setAwesomeInteger</code> as well. So it is quite similar to <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"noreferrer\">C# auto-implemented properties</a>.</p>\n\n<p>You can get more info about lombok getters and setters <a href=\"http://projectlombok.org/features/GetterSetter.html\" rel=\"noreferrer\">here</a>.<br>\nYou should definitely check out <a href=\"http://projectlombok.org/features/index.html\" rel=\"noreferrer\">other features</a> as well.\nMy favorites are: </p>\n\n<ul>\n<li><a href=\"http://projectlombok.org/features/val.html\" rel=\"noreferrer\">val</a></li>\n<li><a href=\"http://projectlombok.org/features/Constructor.html\" rel=\"noreferrer\">NoArgsConstructor, RequiredArgsConstructor, AllArgsConstructor</a></li>\n<li><a href=\"http://projectlombok.org/features/Log.html\" rel=\"noreferrer\">Logs!</a></li>\n</ul>\n\n<p>Lombok is well-integrated with IDEs, so it is going to show generated methods like if they existed (suggestions, class contents, go to declaration and refactoring).<br>\nThe only problem with lombok is that other programmers might not know about it. You can always <a href=\"http://projectlombok.org/features/delombok.html\" rel=\"noreferrer\">delombok</a> the code but that is rather a workaround than a solution.</p>\n" }, { "answer_id": 20781926, "author": "th1rdey3", "author_id": 1682148, "author_profile": "https://Stackoverflow.com/users/1682148", "pm_score": 2, "selected": false, "text": "<p>From <strong>Jeffrey Richter's</strong> book <strong>CLR via C#</strong>: (I think these might be the reasons why properties are still not added in JAVA)</p>\n\n<ul>\n<li>A property method may throw an exception; field access never throws an exception.</li>\n<li>A property cannot be passed as an <code>out</code> or <code>ref</code> parameter to a method; a field can. </li>\n<li>A property method can take a long time to execute; field access always completes\nimmediately. A common reason to use properties is to perform thread synchronization,\nwhich can stop the thread forever, and therefore, a property should not be\nused if thread synchronization is required. In that situation, a method is preferred.\nAlso, if your class can be accessed remotely (for example, your class is derived from\n<code>System.MarshalByRefObject</code>), calling the property method will be very slow, and\ntherefore, a method is preferred to a property. In my opinion, classes derived from\n<code>MarshalByRefObject</code> should never use properties.</li>\n<li>If called multiple times in a row, a property method may return a different value each\ntime; a field returns the same value each time. The <code>System.DateTime</code> class has a readonly\n<code>Now</code> property that returns the current date and time. Each time you query this\nproperty, it will return a different value. This is a mistake, and Microsoft wishes that\nthey could fix the class by making Now a method instead of a property. <code>Environment</code>’s\n<code>TickCount</code> property is another example of this mistake.</li>\n<li>A property method may cause observable side effects; field access never does. In other\nwords, a user of a type should be able to set various properties defined by a type in\nany order he or she chooses without noticing any different behavior in the type.</li>\n<li>A property method may require additional memory or return a reference to something\nthat is not actually part of the object’s state, so modifying the returned object has no\neffect on the original object; querying a field always returns a reference to an object\nthat is guaranteed to be part of the original object’s state. Working with a property\nthat returns a copy can be very confusing to developers, and this characteristic is frequently\nnot documented.</li>\n</ul>\n" }, { "answer_id": 28183669, "author": "LEMUEL ADANE", "author_id": 1347816, "author_profile": "https://Stackoverflow.com/users/1347816", "pm_score": 2, "selected": false, "text": "<p>You may not need for \"get\" and \"set\" prefixes, to make it look more like properties, you may do it like this:</p>\n\n<pre><code>public class Person {\n private String firstName = \"\";\n private Integer age = 0;\n\n public String firstName() { return firstName; } // getter\n public void firstName(String val) { firstName = val; } // setter\n\n public Integer age() { return age; } // getter\n public void age(Integer val) { age = val; } //setter\n\n public static void main(String[] args) {\n Person p = new Person();\n\n //set\n p.firstName(\"Lemuel\");\n p.age(40);\n\n //get\n System.out.println(String.format(\"I'm %s, %d yearsold\",\n p.firstName(),\n p.age());\n }\n}\n</code></pre>\n" }, { "answer_id": 48844944, "author": "Patrick PIGNOL", "author_id": 9254419, "author_profile": "https://Stackoverflow.com/users/9254419", "pm_score": 1, "selected": false, "text": "<p>There is no property keyword in java (like you could find it in C#) the nearest way to have 1 word getter/setter is to do like in C++:</p>\n\n<pre><code>public class MyClass\n{\n private int aMyAttribute;\n public MyClass()\n {\n this.aMyAttribute = 0;\n }\n public void mMyAttribute(int pMyAttributeParameter)\n {\n this.aMyAttribute = pMyAttributeParameter;\n }\n public int mMyAttribute()\n {\n return this.aMyAttribute;\n }\n}\n//usage :\nint vIndex = 1;\nMyClass vClass = new MyClass();\nvClass.mMyAttribute(vIndex);\nvIndex = 0;\nvIndex = vClass.mMyAttribute();\n// vIndex == 1\n</code></pre>\n" }, { "answer_id": 54066621, "author": "Mario Levesque", "author_id": 543584, "author_profile": "https://Stackoverflow.com/users/543584", "pm_score": 0, "selected": false, "text": "<p>As previously mentioned for eclipse, integrated development environment (IDE) often can create accessor methods automatically.</p>\n\n<p>You can also do it using NetBeans. </p>\n\n<p>To create accessor methods for your class, open a class file, then Right-click anywhere in the source code editor and choose the menu command Refactor, Encapsulate Fields. \nA dialog opens. Click Select All, then click Refactor.\nVoilà,</p>\n\n<p>Good luck,</p>\n" }, { "answer_id": 59087540, "author": "Bradley Willcott", "author_id": 12349591, "author_profile": "https://Stackoverflow.com/users/12349591", "pm_score": 0, "selected": false, "text": "<p>For me the problem is two fold:<br></p>\n<ol>\n<li>All these extra methods {get*/set*} cluttering up the class code.<br></li>\n<li>NOT being able to treat them like properties:</li>\n</ol>\n<pre><code> public class Test {\n private String _testField;\n\n public String testProperty {\n get {\n return _testField;\n }\n set {\n _testField = value;\n }\n }\n }\n\n public class TestUser {\n private Test test;\n\n public TestUser() {\n test = new Test();\n\n test.testProperty = &quot;Just something to store&quot;;\n System.out.printLn(test.testProperty);\n }\n }\n</code></pre>\n<p>This is the sort of easy assignment I would like to get back to using. NOT having to use 'method' calling syntax. Can anyone provide some answers as to what happened to Java?</p>\n<p>I think that the issue is also about the unnecessary clutter in the code, and not the 'difficulty' of creating the setters/getters. I consider them as ugly-code. I like what C# has. I don't understand the resistance to adding that capability to Java.</p>\n<p>My current solution is to use 'public' members when protection is not required:</p>\n<pre><code>public class IntReturn {\n public int val;\n}\n\npublic class StringReturn {\n public String val;\n}\n</code></pre>\n<p>These would be used to return value from say a Lambda:</p>\n<pre><code>StringReturn sRtn = new StringReturn()\n\nif(add(2, 3, sRtn)){\n System.out.println(&quot;Value greater than zero&quot;);\n}\n\npublic boolean add(final int a, final int b, final StringReturn sRtn){\n int rtn = a + b;\n sRtn.val = &quot;&quot; + rtn;\n return rtn &gt; 0; // Just something to use the return for.\n}\n</code></pre>\n<p>I also really don't like using a method call to set or get an internal value from a class.</p>\n<p>If your information is being transferred as 'immutable', then the new Java <strong>record</strong> could be a solution. However, it still uses the setter/getter methodology, just without the set/get prefixes.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227/" ]
So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties! Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?
There is a "standard" pattern for getters and setters in Java, called [Bean properties](http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html). Basically any method starting with `get`, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise `set` creates a setter of a void method with a single argument. For example: ``` // Getter for "awesomeString" public String getAwesomeString() { return awesomeString; } // Setter for "awesomeString" public void setAwesomeString( String awesomeString ) { this.awesomeString = awesomeString; } ``` Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting `Ctrl`-`1`, then selecting the option from the list). For what it's worth, for readability you can actually use `is` and `has` in place of `get` for boolean-type properties too, as in: ``` public boolean isAwesome(); public boolean hasAwesomeStuff(); ```
70,501
<p>I have a method in .NET (C#) which returns <code>string[][]</code>. When using RegAsm or TlbExp (from the .NET 2.0 SDK) to create a COM type library for the containing assembly, I get the following warning:</p> <blockquote> <p>WARNING: There is no marshaling support for nested arrays.</p> </blockquote> <p>This warning results in the method in question not being exported into the generated type library. I've been told there's ways around this using Variant as the COM return type, and then casting/etc on the COM client side. For this particular assembly, the target client audience is VB6. <b>But how do you actually do this on the .NET side?</b></p> <p><i>Note</i>: I have an existing legacy DLL (with its exported type library) where the return type is Variant, but this DLL (and the .tlb) is generated using pre-.NET legacy tools, so I can't use them. </p> <p>Would it help at all if the assembly was written in VB.NET instead?</p>
[ { "answer_id": 71395, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The equivalent of variant in C# is System.Object. So you might want to try to return the result cast to object and pick it back up on the other side as a variant.</p>\n\n<p>VB doesn't have any facilities that C# lacks, so I doubt it would be better or easier if the .NET side was written in VB.</p>\n" }, { "answer_id": 74711, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 3, "selected": true, "text": "<p>Even if you were to return an Object (which maps to a Variant in COM Interop), that doesn't solve your problem. VB will be able to \"hold\" onto it and \"pass it around\", but it won't be able to do anything with it.</p>\n\n<p>Technically, there is no exact equivalent in VB for a string[][]. However, if your array is not \"jagged\" (that is, all the sub-arrays are the same length), you should be able to use a two-dimensional array as your return type. COM Interop should be able to translate that.</p>\n\n<pre><code>string [,] myReturnValue = new string[rowCount,colCount];\n</code></pre>\n\n<p>Whether your method formally returns an Object (which will look like a Variant to VB), or a string[,] (which will look like an Array of Strings in VB), is somewhat immaterial. The String array is a nicer return, but not a requirement.</p>\n\n<p>If you array <em>is</em> jagged, then you are going to have to come up with a different method. For example, you could choose to make your return 2D array as big as the biggest of the sub-arrays, and then pass the length information in a separate [out] int[] parameter, so that VB can know which elements are used.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724/" ]
I have a method in .NET (C#) which returns `string[][]`. When using RegAsm or TlbExp (from the .NET 2.0 SDK) to create a COM type library for the containing assembly, I get the following warning: > > WARNING: There is no marshaling support for nested arrays. > > > This warning results in the method in question not being exported into the generated type library. I've been told there's ways around this using Variant as the COM return type, and then casting/etc on the COM client side. For this particular assembly, the target client audience is VB6. **But how do you actually do this on the .NET side?** *Note*: I have an existing legacy DLL (with its exported type library) where the return type is Variant, but this DLL (and the .tlb) is generated using pre-.NET legacy tools, so I can't use them. Would it help at all if the assembly was written in VB.NET instead?
Even if you were to return an Object (which maps to a Variant in COM Interop), that doesn't solve your problem. VB will be able to "hold" onto it and "pass it around", but it won't be able to do anything with it. Technically, there is no exact equivalent in VB for a string[][]. However, if your array is not "jagged" (that is, all the sub-arrays are the same length), you should be able to use a two-dimensional array as your return type. COM Interop should be able to translate that. ``` string [,] myReturnValue = new string[rowCount,colCount]; ``` Whether your method formally returns an Object (which will look like a Variant to VB), or a string[,] (which will look like an Array of Strings in VB), is somewhat immaterial. The String array is a nicer return, but not a requirement. If you array *is* jagged, then you are going to have to come up with a different method. For example, you could choose to make your return 2D array as big as the biggest of the sub-arrays, and then pass the length information in a separate [out] int[] parameter, so that VB can know which elements are used.
70,528
<p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p> <pre><code>&gt;&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() &gt;&gt;&gt; obj.myPublicMethod() public method &gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' &gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] &gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>What's the deal?!</p> <p>I'll explain this a little for those who didn't quite get that.</p> <pre><code>&gt;&gt;&gt; class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... &gt;&gt;&gt; obj = MyClass() </code></pre> <p>I create a class with a public method and a private method and instantiate it.</p> <p>Next, I call its public method.</p> <pre><code>&gt;&gt;&gt; obj.myPublicMethod() public method </code></pre> <p>Next, I try and call its private method.</p> <pre><code>&gt;&gt;&gt; obj.__myPrivateMethod() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; AttributeError: MyClass instance has no attribute '__myPrivateMethod' </code></pre> <p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <code>dir()</code> on the object reveals a new magical method that Python creates magically for all of your 'private' methods.</p> <pre><code>&gt;&gt;&gt; dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] </code></pre> <p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p> <pre><code>&gt;&gt;&gt; obj._MyClass__myPrivateMethod() this is private!! </code></pre> <p>So much for encapsulation, eh?</p> <p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
[ { "answer_id": 70555, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 7, "selected": false, "text": "<p>From <em><a href=\"http://www.faqs.org/docs/diveintopython/fileinfo_private.html\" rel=\"noreferrer\">Dive Into Python, 3.9. Private functions</a></em>:</p>\n<blockquote>\n<p>Strictly speaking, private methods are\naccessible outside their class, just\nnot easily accessible. Nothing in\nPython is truly private; internally,\nthe names of private methods and\nattributes are mangled and unmangled\non the fly to make them seem\ninaccessible by their given names. You\ncan access the __parse method of the\nMP3FileInfo class by the name\n_MP3FileInfo__parse. Acknowledge that this is interesting, then promise to\nnever, ever do it in real code.\nPrivate methods are private for a\nreason, but like many other things in\nPython, their privateness is\nultimately a matter of convention, not\nforce.</p>\n</blockquote>\n" }, { "answer_id": 70562, "author": "Maximilian", "author_id": 1733, "author_profile": "https://Stackoverflow.com/users/1733", "pm_score": 5, "selected": false, "text": "<p>It's not like you absolutely can't get around privateness of members in any language (pointer arithmetics in C++ and reflections in .NET/Java).</p>\n<p>The point is that you get an error if you try to call the private method by accident. But if you want to shoot yourself in the foot, go ahead and do it.</p>\n<p>You don't try to secure your stuff by OO-encapsulation, do you?</p>\n" }, { "answer_id": 70583, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 4, "selected": false, "text": "<p>It's just one of those language design choices. On some level they are justified. They make it so you need to go pretty far out of your way to try and call the method, and if you really need it that badly, you must have a pretty good reason!</p>\n\n<p>Debugging hooks and testing come to mind as possible applications, used responsibly of course.</p>\n" }, { "answer_id": 70736, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 7, "selected": false, "text": "<p>The phrase commonly used is &quot;we're all consenting adults here&quot;. By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g., debuggers and code completion).</p>\n<p>If you truly must have something that is private, then you can implement it in an extension (e.g., in C for <a href=\"https://en.wikipedia.org/wiki/CPython\" rel=\"noreferrer\">CPython</a>). In most cases, however, you simply learn the <a href=\"https://en.wiktionary.org/wiki/Pythonic#Adjective\" rel=\"noreferrer\">Pythonic</a> way of doing things.</p>\n" }, { "answer_id": 70900, "author": "Alya", "author_id": 9464, "author_profile": "https://Stackoverflow.com/users/9464", "pm_score": 10, "selected": true, "text": "<p>The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.</p>\n\n<p>For example:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo(object):\n... def __init__(self):\n... self.__baz = 42\n... def foo(self):\n... print self.__baz\n... \n&gt;&gt;&gt; class Bar(Foo):\n... def __init__(self):\n... super(Bar, self).__init__()\n... self.__baz = 21\n... def bar(self):\n... print self.__baz\n...\n&gt;&gt;&gt; x = Bar()\n&gt;&gt;&gt; x.foo()\n42\n&gt;&gt;&gt; x.bar()\n21\n&gt;&gt;&gt; print x.__dict__\n{'_Bar__baz': 21, '_Foo__baz': 42}\n</code></pre>\n\n<p>Of course, it breaks down if two different classes have the same name.</p>\n" }, { "answer_id": 80000, "author": "Ross", "author_id": 14794, "author_profile": "https://Stackoverflow.com/users/14794", "pm_score": 4, "selected": false, "text": "<p>Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).</p>\n\n<p>Module attributes named as such will not be copied into an importing module when using the <code>from*</code> method, e.g.:</p>\n\n<pre><code>from bar import *\n</code></pre>\n\n<p>However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.</p>\n" }, { "answer_id": 1949874, "author": "Thomas Ahle", "author_id": 205521, "author_profile": "https://Stackoverflow.com/users/205521", "pm_score": 8, "selected": false, "text": "<p>When I first came from Java to Python I <strong>hated</strong> this. It scared me to death.</p>\n\n<p>Today it might just be the one thing <strong>I love most</strong> about Python.</p>\n\n<p>I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: \"sure\". If you think you understand the situation, perhaps you have even read it, then all we can say is \"good luck!\".</p>\n\n<p>Remember, encapsulation is not even weakly related to \"security\", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.</p>\n" }, { "answer_id": 3147548, "author": "arun", "author_id": 379816, "author_profile": "https://Stackoverflow.com/users/379816", "pm_score": 8, "selected": false, "text": "<h3>Example of a private function</h3>\n<pre><code>import re\nimport inspect\n\nclass MyClass:\n\n def __init__(self):\n pass\n\n def private_function(self):\n try:\n function_call = inspect.stack()[1][4][0].strip()\n\n # See if the function_call has &quot;self.&quot; in the beginning\n matched = re.match( '^self\\.', function_call)\n if not matched:\n print 'This is a private function. Go away.'\n return\n except:\n print 'This is a private function. Go away.'\n return\n\n # This is the real function, only accessible inside the class #\n print 'Hey, welcome in to the function.'\n\n def public_function(self):\n # I can call a private function from inside the class\n self.private_function()\n\n### End ###\n</code></pre>\n" }, { "answer_id": 39123423, "author": "Alberto", "author_id": 1735667, "author_profile": "https://Stackoverflow.com/users/1735667", "pm_score": 2, "selected": false, "text": "<p>With Python 3.4, this is the behaviour:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; class Foo:\n def __init__(self):\n pass\n def __privateMethod(self):\n return 3\n def invoke(self):\n return self.__privateMethod()\n\n\n&gt;&gt;&gt; help(Foo)\nHelp on class Foo in module __main__:\n\nclass Foo(builtins.object)\n | Methods defined here:\n |\n | __init__(self)\n |\n | invoke(self)\n |\n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n |\n | __dict__\n | dictionary for instance variables (if defined)\n |\n | __weakref__\n | list of weak references to the object (if defined)\n\n &gt;&gt;&gt; f = Foo()\n &gt;&gt;&gt; f.invoke()\n 3\n &gt;&gt;&gt; f.__privateMethod()\n Traceback (most recent call last):\n File &quot;&lt;pyshell#47&gt;&quot;, line 1, in &lt;module&gt;\n f.__privateMethod()\n AttributeError: 'Foo' object has no attribute '__privateMethod'\n</code></pre>\n<p>From <em><a href=\"https://docs.python.org/3/tutorial/classes.html#tut-private\" rel=\"nofollow noreferrer\">9.6. Private Variables</a></em>:</p>\n<blockquote>\n<p>Note that the mangling rules are designed mostly to avoid accidents; <strong>it still is possible to access or modify a variable that is considered private.</strong> This can even be useful in special circumstances, such as in the debugger.</p>\n</blockquote>\n" }, { "answer_id": 50052800, "author": "Afshin Amiri", "author_id": 6244155, "author_profile": "https://Stackoverflow.com/users/6244155", "pm_score": 3, "selected": false, "text": "<p>The most important concern about private methods and attributes is to tell developers not to call it outside the class and this is encapsulation. One may misunderstand security from encapsulation. When one deliberately uses syntax like that (below) you mentioned, you do not want encapsulation.</p>\n<pre><code>obj._MyClass__myPrivateMethod()\n</code></pre>\n<p>I have migrated from C# and at first it was weird for me too but after a while I came to the idea that only the way that Python code designers think about OOP is different.</p>\n" }, { "answer_id": 54179468, "author": "user200783", "author_id": 200783, "author_profile": "https://Stackoverflow.com/users/200783", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>Why are Python's 'private' methods not actually private?</p>\n</blockquote>\n<p>As I understand it, they <em>can't</em> be private. How could privacy be enforced?</p>\n<p>The obvious answer is &quot;private members can only be accessed through <code>self</code>&quot;, but that wouldn't work - <code>self</code> is not special in Python. It is nothing more than a commonly-used name for the first parameter of a function.</p>\n" }, { "answer_id": 64985332, "author": "Moradnejad", "author_id": 2419960, "author_profile": "https://Stackoverflow.com/users/2419960", "pm_score": 4, "selected": false, "text": "<h1>Important note:</h1>\n<p>Any identifier of the form <code>__name</code> (at least two leading underscores, at most one trailing underscore) is publicly replaced with <code>_classname__name</code>, where <code>classname</code> is the current class name with a leading underscore(s) stripped.</p>\n<p><strong>Therefore, <code>__name</code> is not accessible directly, but can be accessed as<code>_classname__name</code>.</strong></p>\n<p>This does not mean that you can protect your private data as it is easily accessible by changing the name of the variable.</p>\n<h4>Source:</h4>\n<p>&quot;Private Variables&quot; section in official documentation: <a href=\"https://docs.python.org/3/tutorial/classes.html#tut-private\" rel=\"nofollow noreferrer\">https://docs.python.org/3/tutorial/classes.html#tut-private</a></p>\n<h2>Example</h2>\n<pre class=\"lang-py prettyprint-override\"><code>class Cat:\n def __init__(self, name='unnamed'):\n self.name = name\n def __print_my_name(self):\n print(self.name)\n \n \ntom = Cat()\ntom.__print_my_name() #Error\ntom._Cat__print_my_name() #Prints name\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943957/" ]
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this ``` >>>> class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... >>> obj = MyClass() >>> obj.myPublicMethod() public method >>> obj.__myPrivateMethod() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: MyClass instance has no attribute '__myPrivateMethod' >>> dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] >>> obj._MyClass__myPrivateMethod() this is private!! ``` What's the deal?! I'll explain this a little for those who didn't quite get that. ``` >>> class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self): ... print 'this is private!!' ... >>> obj = MyClass() ``` I create a class with a public method and a private method and instantiate it. Next, I call its public method. ``` >>> obj.myPublicMethod() public method ``` Next, I try and call its private method. ``` >>> obj.__myPrivateMethod() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: MyClass instance has no attribute '__myPrivateMethod' ``` Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running `dir()` on the object reveals a new magical method that Python creates magically for all of your 'private' methods. ``` >>> dir(obj) ['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod'] ``` This new method's name is always an underscore, followed by the class name, followed by the method name. ``` >>> obj._MyClass__myPrivateMethod() this is private!! ``` So much for encapsulation, eh? In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside. For example: ``` >>> class Foo(object): ... def __init__(self): ... self.__baz = 42 ... def foo(self): ... print self.__baz ... >>> class Bar(Foo): ... def __init__(self): ... super(Bar, self).__init__() ... self.__baz = 21 ... def bar(self): ... print self.__baz ... >>> x = Bar() >>> x.foo() 42 >>> x.bar() 21 >>> print x.__dict__ {'_Bar__baz': 21, '_Foo__baz': 42} ``` Of course, it breaks down if two different classes have the same name.
70,529
<p>In order to know how many times a pattern exists in current buffer, I do:</p> <pre><code>:%s/pattern-here/pattern-here/g </code></pre> <p>It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.</p> <p>Is there a more elegant way to count?</p>
[ { "answer_id": 70657, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 8, "selected": true, "text": "<p>To avoid the substitution, leave the second pattern empty, and add the “n” flag:</p>\n\n<pre><code>:%s/pattern-here//gn\n</code></pre>\n\n<p>This is described as <a href=\"http://vimdoc.sourceforge.net/htmldoc/tips.html#count-items\" rel=\"noreferrer\">an official tip</a>.</p>\n" }, { "answer_id": 70690, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 3, "selected": false, "text": "<pre><code>:!cat %| grep -c \"pattern\"\n</code></pre>\n\n<p>It's not exactly vim command, but it will give you what you need from vim.<br>\nYou can map it to the command if you need to use it frequently.</p>\n" }, { "answer_id": 1168304, "author": "redacted", "author_id": 53726, "author_profile": "https://Stackoverflow.com/users/53726", "pm_score": 2, "selected": false, "text": "<p>The vimscript <a href=\"http://www.vim.org/scripts/script.php?script_id=1682\" rel=\"nofollow noreferrer\">IndexedSearch</a> enhances the Vim search commands to display \"At match #N out of M matches\".</p>\n" }, { "answer_id": 8073228, "author": "rdeits", "author_id": 641846, "author_profile": "https://Stackoverflow.com/users/641846", "pm_score": -1, "selected": false, "text": "<p>vimgrep is your friend here:</p>\n\n<pre><code>vimgrep pattern %\n</code></pre>\n\n<p>Shows:</p>\n\n<pre><code>(1 of 37)\n</code></pre>\n" }, { "answer_id": 14635785, "author": "konyak", "author_id": 1408866, "author_profile": "https://Stackoverflow.com/users/1408866", "pm_score": 3, "selected": false, "text": "<pre><code>:help count-items\n</code></pre>\n\n<p>In VIM 6.3, here's how you do it.</p>\n\n<pre><code>:set report=0\n:%s/your_word/&amp;/g # returns the count without substitution\n</code></pre>\n\n<p>In VIM 7.2, here's how you'd do it:</p>\n\n<pre><code>:%s/your_word/&amp;/gn # returns the count, n flag avoids substitution\n</code></pre>\n" }, { "answer_id": 32634262, "author": "Sagar Jain", "author_id": 3345302, "author_profile": "https://Stackoverflow.com/users/3345302", "pm_score": 1, "selected": false, "text": "<p>Put the cursor on the word you want to count and execute the following.</p>\n\n<pre><code>:%s/&lt;c-r&gt;&lt;c-w&gt;//gn\n</code></pre>\n\n<p>See <code>:h c_ctrl-r_ctrl-w</code></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6984/" ]
In order to know how many times a pattern exists in current buffer, I do: ``` :%s/pattern-here/pattern-here/g ``` It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status. Is there a more elegant way to count?
To avoid the substitution, leave the second pattern empty, and add the “n” flag: ``` :%s/pattern-here//gn ``` This is described as [an official tip](http://vimdoc.sourceforge.net/htmldoc/tips.html#count-items).
70,560
<p>When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that.</p> <p>The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results.</p> <p>Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ...</p> <p>No, seriously, what are the common ways to solve this problem?</p>
[ { "answer_id": 70656, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 5, "selected": true, "text": "<p>One approach is the so called bag-of-words model.</p>\n\n<p>As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as \"the\", \"a\", \"or\" and so on.</p>\n\n<p>You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words:\n\"aardvark\" is 1, \"apple\" is 2, ..., \"z-index\" is 70092. </p>\n\n<p>Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this:</p>\n\n<pre><code>[2 0 0 ... 70k zeroes ... 0].\n</code></pre>\n\n<p>After this you can count the \"angle\" between the two vectors with <a href=\"http://en.wikipedia.org/wiki/Dot_product\" rel=\"noreferrer\">a dot product</a>. The smaller the angle, the closer the documents are.</p>\n\n<p>This is a simple version and there other more advanced techniques. May the <a href=\"http://en.wikipedia.org/wiki/Document_classification\" rel=\"noreferrer\">Wikipedia be with you</a>.</p>\n" }, { "answer_id": 70708, "author": "Sergey Volegov", "author_id": 9024, "author_profile": "https://Stackoverflow.com/users/9024", "pm_score": 2, "selected": false, "text": "<p>From my (rather small) experience developing full-text search engines: I would look up questions which contain some words from query (in your case, query is your question).\nSure, noise words should be ignored and we might want to check query for 'strong' words like 'ASP.Net' to narrow down search scope.\nhttp://en.wikipedia.org/wiki/Index_(search_engine)#Inverted_indices'>Inverted indexes are commonly used to find questions with words we are interested in.</p>\n\n<p>After finding questions with words from query, we might want to calculate distance between words we are interested in in questions, so question with 'phrases similarity' text ranks higher than question with 'discussing similarity, you hear following phrases...' text.</p>\n" }, { "answer_id": 70929, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>@Hanno you should try the Levenshtein distance algorithm. Given an input string <strong>s</strong> and a list of of strings <strong>t</strong> iterate for each string <strong>u</strong> in <strong>t</strong> and return the one with the minimum Levenshtein distance.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Levenshtein_distance</a></p>\n\n<p>See a Java implementation example in <a href=\"http://www.javalobby.org/java/forums/t15908.html\" rel=\"nofollow noreferrer\">http://www.javalobby.org/java/forums/t15908.html</a></p>\n" }, { "answer_id": 72006, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 2, "selected": false, "text": "<p>To augment the bag-of-words idea:</p>\n\n<p>There are a few ways you can also pay some attention to n-grams, strings of two or more words kept in order. You might want to do this because a search for \"space complexity\" is much more than a search for things with \"space\" AND \"complexity\" in them, since the meaning of this phrase is more than the sum of its parts; that is, if you get a result that talks about the complexity of outer space and the universe, this is probably not what the search for \"space complexity\" really meant.</p>\n\n<p>A key idea from natural language processing here is that of <a href=\"http://en.wikipedia.org/wiki/Mutual_information\" rel=\"nofollow noreferrer\">mutual information</a>, which allows you (algorithmically) to judge whether or not a phrase is really a specific phrase (such as \"space complexity\") or just words which are coincidentally adjacent. Mathematically, the main idea is to ask, probabilistically, if these words appear next to each other more often than you would guess by their frequencies alone. If you see a phrase with a high mutual information score in your search query (or while indexing), you can get better results by trying to keep these words in sequence.</p>\n" }, { "answer_id": 73842199, "author": "Subhradeep Biswas", "author_id": 20080779, "author_profile": "https://Stackoverflow.com/users/20080779", "pm_score": 0, "selected": false, "text": "<p>Here is the bag of words solution with tfidfvectorizer in python 3</p>\n<pre><code>#from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport nltk\nnltk.download('stopwords')\ns=set(stopwords.words('english'))\n\ntrain_x_cleaned = []\nfor i in train_x:\n sentence = filter(lambda w: not w in s,i.split(&quot;,&quot;))\n train_x_cleaned.append(' '.join(sentence))\n\nvectorizer = TfidfVectorizer(binary=True)\ntrain_x_vectors = vectorizer.fit_transform(train_x_cleaned)\n\nprint(vectorizer.get_feature_names_out())\nprint(train_x_vectors.toarray())\n\nfrom sklearn import svm\n\nclf_svm = svm.SVC(kernel='linear')\nclf_svm.fit(train_x_vectors, train_y)\n\ntest_x = vectorizer.transform([&quot;test phrase 1&quot;, &quot;test phrase 2&quot;, &quot;test phrase 3&quot;])\nprint (type(test_x))\nclf_svm.predict(test_x)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that. The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results. Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ... No, seriously, what are the common ways to solve this problem?
One approach is the so called bag-of-words model. As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as "the", "a", "or" and so on. You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words: "aardvark" is 1, "apple" is 2, ..., "z-index" is 70092. Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this: ``` [2 0 0 ... 70k zeroes ... 0]. ``` After this you can count the "angle" between the two vectors with [a dot product](http://en.wikipedia.org/wiki/Dot_product). The smaller the angle, the closer the documents are. This is a simple version and there other more advanced techniques. May the [Wikipedia be with you](http://en.wikipedia.org/wiki/Document_classification).
70,575
<p>Is there any need of Virtual Constructors? If so can any one post a scenario?</p>
[ { "answer_id": 70589, "author": "grigy", "author_id": 1692070, "author_profile": "https://Stackoverflow.com/users/1692070", "pm_score": 1, "selected": false, "text": "<p>In what language? In C++ for example the constructors can not be virtual.</p>\n" }, { "answer_id": 70597, "author": "Marcin Gil", "author_id": 5731, "author_profile": "https://Stackoverflow.com/users/5731", "pm_score": 2, "selected": false, "text": "<p>As always: look up at <a href=\"http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8\" rel=\"nofollow noreferrer\">C++ FAQ lite: virtual functions</a>.</p>\n\n<p>It will explain not only \"virtual constructor\" but destructors/functions too!</p>\n\n<p>This of course, if you wanted C++ in the first place...</p>\n" }, { "answer_id": 70618, "author": "grigy", "author_id": 1692070, "author_profile": "https://Stackoverflow.com/users/1692070", "pm_score": 0, "selected": false, "text": "<p>The constructor can not be virtual by definition. At the time of constructor call there is no object created yet, so the polymorphism does not make any sense.</p>\n" }, { "answer_id": 70634, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 3, "selected": false, "text": "<p>If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.</p>\n\n<pre><code>class A\n{\n ~A();\n}\n\nclass B : public A\n{\n ~B();\n}\n\nA* pB = new B();\ndelete pB; // NOTE: WILL NOT CALL B's destructor\n\nclass A\n{\n virtual ~A();\n}\n\nclass B : public A\n{\n virtual ~B();\n}\n\nA* pB = new B();\ndelete pB; // NOTE: WILL CALL B's destructor\n</code></pre>\n\n<p><strong>Edit:</strong> Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx</a></p>\n" }, { "answer_id": 70693, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 2, "selected": false, "text": "<p>Delphi is one language that supports virtual constructors.</p>\n\n<p>Typically they would be used in a class factory type scenario where you create a meta type i.e. that is a type that describes a type. You would then use that meta type to construct a concrete example of your descendant class</p>\n\n<p>Code would be something like....</p>\n\n<pre><code>type\n MyMetaTypeRef = class of MyBaseClass;\n\nvar\n theRef : MyMetaTypeRef;\n inst : MyBaseClass;\nbegin \n theRef := GetTheMetaTypeFromAFactory(); \n inst := theRef.Create(); // Use polymorphic behaviour to create the class\n</code></pre>\n" }, { "answer_id": 70697, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>There are plenty of scenarios, for example if you want to create GUIs for more than one environment. Let's say you have classes for controls (“widgets”) but each environment actually has its own widget set. It's therefore logical to subclass the creation of these widgets for each environment. The way to do this (since, as has been unhelpfully pointed out, constructors can't actually be virtual in most languages), is to employ an <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow noreferrer\">abstract factory</a> and the above example is actually the standard example used to describe this design pattern.</p>\n" }, { "answer_id": 70822, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 0, "selected": false, "text": "<p>In C++, there's no reason for constructors to ever be virtual, because they are static functions. That means they're statically bound, so you have to identify the very constructor function you're calling in order to call it at all. There's no uncertainty and nothing virtual about it.</p>\n\n<p>This also means that, no matter what, you need to know the class that your object is going to be. What you can do, however, is something like this:</p>\n\n<pre><code>Superclass *object = NULL;\nif (condition) {\n object = new Subclass1();\n}\nelse {\n object = new Subclass2();\n}\nobject.setMeUp(args);\n</code></pre>\n\n<p>... have a virtual function and call it after constructon. This is a standard pattern in Objective-C, in which first you call the class's \"alloc\" method to get an instance, and then you call the initilializer that suits your use.</p>\n\n<p>The person who mentioned the Abstract Factory pattern is probably more correct for C++ and Java though.</p>\n" }, { "answer_id": 11664488, "author": "Homer6", "author_id": 278976, "author_profile": "https://Stackoverflow.com/users/278976", "pm_score": -1, "selected": false, "text": "<p>In C++, all constructors are implicitly virtual (with a little extra). That is, the constructor of the base class is called before that of the derived class. So, it's like they're sort of virtual. Because, in a virtual method, if the derived class implements a method of the same signature, only the method in the derived class is invoked.</p>\n\n<p>However, <strong>in a constructor, BOTH METHODS ARE INVOKED</strong> (see example below).</p>\n\n<p>For a more complete explanation of why this is so, please see Item 9 of Effective C++, Third Edition, By Scott Meyers (Never call a virtual function during construction or destruction). The title of the item may be misleading in relation to the question, but if you read the explanation, it'll make perfect sense.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass Animal {\n\n public:\n\n Animal(){\n std::cout &lt;&lt; \"Animal Constructor Invoked.\" &lt;&lt; std::endl;\n }\n\n virtual void eat() {\n std::cout &lt;&lt; \"I eat like a generic animal.\\n\";\n }\n\n //always make destructors virtual in base classes\n virtual ~Animal() {\n\n }\n\n};\n\nclass Wolf : public Animal {\n\n public:\n\n Wolf(){\n std::cout &lt;&lt; \"Wolf Constructor Invoked.\" &lt;&lt; std::endl;\n }\n\n void eat() {\n std::cout &lt;&lt; \"I eat like a wolf!\" &lt;&lt; std::endl;\n }\n\n};\n\n\nint main() {\n\n Wolf wolf;\n std::cout &lt;&lt; \"-------------\" &lt;&lt; std::endl;\n wolf.eat();\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Animal Constructor Invoked.\nWolf Constructor Invoked.\n-------------\nI eat like a wolf!\n</code></pre>\n" }, { "answer_id": 14971562, "author": "rockstar", "author_id": 803649, "author_profile": "https://Stackoverflow.com/users/803649", "pm_score": -1, "selected": false, "text": "<p>Virtual constructors dont make sense in C++ . THis is because in C++ constructors do not have a return value . In some other programming languages this is not the case . In those languages the constructor can be called directly and the constructor has a return value . This makes them useful in implementing certain types of desgin patterns . In C++ however this is not the case . </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11554/" ]
Is there any need of Virtual Constructors? If so can any one post a scenario?
If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically. ``` class A { ~A(); } class B : public A { ~B(); } A* pB = new B(); delete pB; // NOTE: WILL NOT CALL B's destructor class A { virtual ~A(); } class B : public A { virtual ~B(); } A* pB = new B(); delete pB; // NOTE: WILL CALL B's destructor ``` **Edit:** Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well <http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx>
70,600
<p>I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.</p>
[ { "answer_id": 70633, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 0, "selected": false, "text": "<p>You need a gateway script, like ImageDownload.php?picture=me.jpg, or something like that.</p>\n\n<p>That page whould return the image bytes, as well as logging that the image is downloaded.</p>\n" }, { "answer_id": 70639, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 0, "selected": false, "text": "<p>Because the images being saved are on their computer locally there would be no way to get that kind of information as they have already retrieved the image from your system. Even with javascript the best I know that you could do is to log each time a user presses the second mousebutton using some kind of ajax'y stuff.</p>\n\n<p>I don't really like the idea, but if you wanted to log everytime someone downloaded an image you could host the images inside a flash or java app that made it a requirement to click a download image button. That way the only way for them to get the image without doing that would be to either capture packets as they came into their side or take a screenshot.</p>\n" }, { "answer_id": 70664, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Yes, my preferred way of doing this would be via PHP. You'd have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database).</p>\n\n<p>For example - in very rough pseudo-code:</p>\n\n<p>download.php</p>\n\n<pre><code>$file = $_GET['file'];\nupdateFileCount($file);\nheader('Content-Type: image/jpeg');\nsendFile($file);\n</code></pre>\n\n<p>Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - <a href=\"http://elouai.com/force-download.php\" rel=\"nofollow noreferrer\">this script</a> is an example of a download script which you could use)</p>\n\n<p>Note: I highly recommend avoiding the use of $_GET['file'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question.</p>\n" }, { "answer_id": 70669, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>Your server access logs should already have the request for the non-thumbnailed version of the file, so you just need to modify the log format to include the sessionid, which I presume you can map back to a user.</p>\n" }, { "answer_id": 96582, "author": "Laith", "author_id": 5961, "author_profile": "https://Stackoverflow.com/users/5961", "pm_score": 0, "selected": false, "text": "<p>I agree strongly with the suggestion put forward by Phill Sacre. For what you are looking for this is the way to go. </p>\n\n<p>It also has the benefit of being potentially able to keep the tracked files out of the direct web path so that they can't be direct linked to.</p>\n\n<p>I use this method in a client site where the images are paid content so must be restricted access.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.
Yes, my preferred way of doing this would be via PHP. You'd have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database). For example - in very rough pseudo-code: download.php ``` $file = $_GET['file']; updateFileCount($file); header('Content-Type: image/jpeg'); sendFile($file); ``` Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - [this script](http://elouai.com/force-download.php) is an example of a download script which you could use) Note: I highly recommend avoiding the use of $\_GET['file'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question.
70,614
<p>I've just introduced a friend to <strong>GNU Screen</strong> and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent <strong>Screen</strong> utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?</p> <p>It would be awesome.</p>
[ { "answer_id": 70683, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 5, "selected": false, "text": "<p>If your friend is in the habit of pressing <code>^A</code> to get to the beginning of the line in Bash, he/she is in for some surprises, since <code>^A</code> is the screen command key binding. Usually I end up with a frozen screen, possibly because of some random key I pressed after <code>^A</code> :-) </p>\n\n<p>In those cases I try</p>\n\n<p><code>^A s</code> and <code>^A q</code> block/unblock terminal scrolling</p>\n\n<p>to fix that. To go to the beginning of a line inside screen, the key sequence is <code>^A a</code>.</p>\n" }, { "answer_id": 70716, "author": "tadeusz", "author_id": 7593, "author_profile": "https://Stackoverflow.com/users/7593", "pm_score": 3, "selected": false, "text": "<p><kbd>Ctrl</kbd>+<kbd>a</kbd> is a special key.</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>d</kbd> - [d]etach, leave programs (irssi?) in background, go home.</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>c</kbd> [c]reate a new window\n<kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>0-9</kbd> switch between windows by number</p>\n\n<p>screen -r - get back to detached session</p>\n\n<p>That covers 90% of use cases. Do not try to show all the functionality at the single time.</p>\n" }, { "answer_id": 70735, "author": "Niko Gunadi", "author_id": 4499, "author_profile": "https://Stackoverflow.com/users/4499", "pm_score": 3, "selected": false, "text": "<p><kbd>Ctrl</kbd>+<kbd>A</kbd> is the base command</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>N</kbd> = go to the ***N***ext screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>P</kbd> = go to the ***P***revious screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>C</kbd> = ***C***reate new screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>D</kbd> = ***D***etach your screen</p>\n" }, { "answer_id": 70765, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "<p>I've been using <code>Screen</code> for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are:</p>\n\n<pre><code>^A ^W - window list, where am I\n^A ^C - create new window\n^A space - next window\n^A p - previous window\n^A ^A - switch to previous screen (toggle)\n^A [0-9] - go to window [0-9]\n^A esc - copy mode, which I use for scrollback\n</code></pre>\n\n<p>I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both <code>^Q</code> and <code>^A ^Q</code> to try to unlock it.</p>\n" }, { "answer_id": 70801, "author": "James Muscat", "author_id": 11643, "author_profile": "https://Stackoverflow.com/users/11643", "pm_score": 5, "selected": false, "text": "<p><kbd>Ctrl</kbd>+<kbd>A</kbd> ? - show the help screen!</p>\n" }, { "answer_id": 70882, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 5, "selected": false, "text": "<p>I couldn't get used to screen until I found a way to set a 'status bar' at the bottom of the screen that shows what 'tab' or 'virtual screen' you're on and which other ones there are. Here is my setup:</p>\n\n<pre><code>[roel@roel ~]$ cat .screenrc\n# Here comes the pain...\ncaption always \"%{=b dw}:%{-b dw}:%{=b dk}[ %{-b dw}%{-b dg}$USER%{-b dw}@%{-b dg}%H %{=b dk}] [ %= %?%{-b dg}%-Lw%?%{+b dk}(%{+b dw}%n:%t%{+b dk})%?(%u)%?%{-b dw}%?%{-b dg}%+Lw%? %{=b dk}]%{-b dw}:%{+b dw}:\"\n\nbacktick 2 5 5 $HOME/scripts/meminfo\nhardstatus alwayslastline \"%{+b dw}:%{-b dw}:%{+b dk}[%{-b dg} %0C:%s%a %{=b dk}]-[ %{-b dw}Load%{+b dk}:%{-b dg}%l %{+b dk}] [%{-b dg}%2`%{+b dk}] %=[ %{-b dg}%1`%{=b dk} ]%{-b dw}:%{+b dw}:%&lt;\"\n\nsorendition \"-b dw\"\n[roel@roel ~]$ cat ~/scripts/meminfo\n#!/bin/sh\nRAM=`cat /proc/meminfo | grep \"MemFree\" | awk -F\" \" '{print $2}'`\nSWAP=`cat /proc/meminfo | grep \"SwapFree\" | awk -F\" \" '{print $2}'`\necho -n \"${RAM}kb/ram ${SWAP}kb/swap\"\n[roel@roel ~]$\n</code></pre>\n" }, { "answer_id": 70985, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 4, "selected": false, "text": "<p>You can remap the escape key from <kbd>Ctrl</kbd> + <kbd>A</kbd> to be another key of your choice, so if you do use it for something else, e.g. to go to the beginning of the line in bash, you just need to add a line to your ~/.screenrc file. To make it ^b or ^B, use:</p>\n\n<pre><code>escape ^bB\n</code></pre>\n\n<p>From the command line, use names sessions to keep multiple sessions under control. I use one session per task, each with multiple tabs:</p>\n\n<pre>\n screen -ls # Lists your current screen sessions\n screen -S &lt;name&gt; # Creates a new screen session called name\n screen -r &lt;name&gt; # Connects to the named screen sessions\n</pre>\n\n<p>When using screen you only need a few commands:</p>\n\n<pre>\n ^A c Create a new shell\n ^A [0-9] Switch shell\n ^A k Kill the current shell\n ^A d Disconnect from screen\n ^A ? Show the help\n</pre>\n\n<p>An excellent quick reference can be found <a href=\"http://aperiodic.net/screen/quick_reference\" rel=\"nofollow noreferrer\">here</a>. It is worth bookmarking.</p>\n" }, { "answer_id": 71055, "author": "dummy", "author_id": 6297, "author_profile": "https://Stackoverflow.com/users/6297", "pm_score": 0, "selected": false, "text": "<p>^A A switches back to the screen you just came from.</p>\n" }, { "answer_id": 106158, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "<p>Not really essential not solely related to screen, but <a href=\"https://web.archive.org/web/20130313011037/http://www.frexx.de/xterm-256-notes/\" rel=\"nofollow noreferrer\">enabling 256 colors in my terminal, GNU Screen and Vim</a> improved my screen experience big time (especially since I code in Vim about 8h a day - there are some great eye-friendly colorschemes).</p>\n" }, { "answer_id": 117008, "author": "innaM", "author_id": 7498, "author_profile": "https://Stackoverflow.com/users/7498", "pm_score": 2, "selected": false, "text": "<p>I like to set up a screen session with descriptive names for the windows. ^a A will let you give a name to the current window and ^a \" will give you a list of your windows.\nWhen done, detach the screen with ^a d and re-attach with screen -R</p>\n" }, { "answer_id": 117072, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.debian-administration.org/articles/34\" rel=\"noreferrer\">http://www.debian-administration.org/articles/34</a></p>\n\n<p>I wrote that a couple of years ago, but it is still a good introduction that gets a lot of positive feedback.</p>\n" }, { "answer_id": 157174, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 3, "selected": false, "text": "<p>I \"must\" add this: add</p>\n\n<pre><code>bind s\n</code></pre>\n\n<p>to your <code>.screenrc</code>, if You - like me - used to use split windows, as <code>C-a S</code> splits the actual window, but <code>C-a s</code> freezes it. So I just disabled the freeze shortcut.</p>\n" }, { "answer_id": 563876, "author": "David Dean", "author_id": 67829, "author_profile": "https://Stackoverflow.com/users/67829", "pm_score": 2, "selected": false, "text": "<p>There is some <a href=\"http://blog.dustinkirkland.com/2008/12/ubuntu-server-includes-window-manager.html\" rel=\"nofollow noreferrer\">interesting work</a> being done on getting a good GNU screen setup happening by default in the next version of Ubuntu Server, which includes using the bottom of the screen to show all the windows as well as other useful machine details (like number of updates available and whether the machine needs a reboot). You can probably grab their <code>.screenrc</code> and customise it to your needs.</p>\n\n<p>The most useful commands I have in my <code>.screenrc</code> are the following:</p>\n\n<pre><code>shelltitle \"$ |bash\" # Make screen assign window titles automatically\nhardstatus alwayslastline \"%w\" # Show all window titles at bottom line of term\n</code></pre>\n\n<p>This way I always know what windows are open, and what is running in them at the moment, too.</p>\n" }, { "answer_id": 894140, "author": "Gary Chambers", "author_id": 103072, "author_profile": "https://Stackoverflow.com/users/103072", "pm_score": 2, "selected": false, "text": "<p>The first modification I make to .screenrc is to change the escape command. Not unlike many of you, I do not like the default Ctrl-A sequence because of its interference with that fundamental functionality in almost every other context. In my .screenrc file, I add:</p>\n\n<p>escape `e</p>\n\n<p>That's backtick-e.</p>\n\n<p>This enables me to use the backtick as the escape key (e.g. to create a new screen, I press backtick-c, detach is backtick-d, backtick-? is help, backtick-backtick is previous screen, etc.). The only way it interferes (and I had to break myself of the habit) is using backtick on the command line to capture execution output, or pasting anything that contains a backtick. For the former, I've modified my habit by using the BASH $(command) convention. For the latter, I usually just pop open another xterm or detach from screen then paste the content containing the backtick. Finally, if I wish to insert a literal backtick, I simply press backtick-e.</p>\n" }, { "answer_id": 1236687, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "<p>Some tips for those sorta familiar with screen, but who tend to not remember things they read in the man page:</p>\n\n<ul>\n<li>To change the name of a screen window is very easy: <kbd>ctrl</kbd>+<kbd>A</kbd> <kbd>shift</kbd>+<kbd>A</kbd>. </li>\n<li>Did you miss the last message from screen? <kbd>ctrl</kbd>+<kbd>a</kbd> <kbd>ctrl</kbd>+<kbd>m</kbd> will show it again for you.</li>\n<li>If you want to run something (like tailing a file) and have screen tell you when there's a change, use <kbd>ctrl</kbd>+<kbd>A</kbd> <kbd>shift</kbd>+<kbd>m</kbd> on the target window. Warning: it will let you know if <em>anything</em> changes.</li>\n<li>Want to select window 15 directly? Try these in your <code>.screenrc</code> file:</li>\n</ul>\n\n<blockquote>\n<pre><code>bind ! select 11\nbind @ select 12\nbind \\# select 13\nbind $ select 14\nbind % select 15\nbind \\^ select 16\nbind &amp; select 17\nbind * select 18\nbind ( select 19\nbind ) select 10\n</code></pre>\n</blockquote>\n\n<p>That assigns <kbd>ctrl</kbd>+<kbd>a</kbd> <kbd>shift</kbd>+<kbd>0 through 9</kbd> for windows 10 through 19.</p>\n" }, { "answer_id": 1680589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I use the following for <code>ssh</code>:</p>\n\n<pre><code>#!/bin/sh\n# scr - Runs a command in a fresh screen\n#\n# Get the current directory and the name of command\n\nwd=`pwd`\ncmd=$1\nshift\n\n# We can tell if we are running inside screen by looking\n# for the STY environment variable. If it is not set we\n# only need to run the command, but if it is set then\n# we need to use screen.\n\nif [ -z \"$STY\" ]; then\n $cmd $*\nelse\n # Screen needs to change directory so that\n # relative file names are resolved correctly.\n screen -X chdir $wd\n\n # Ask screen to run the command\n if [ $cmd == \"ssh\" ]; then\n screen -X screen -t \"\"${1##*@}\"\" $cmd $*\n else\n screen -X screen -t \"$cmd $*\" $cmd $*\n fi\nfi\n</code></pre>\n\n<p>Then I set the following bash aliases:</p>\n\n<pre><code>vim() {\n scr vim $*\n}\n\nman() {\n scr man $*\n}\n\ninfo() {\n scr info $*\n}\n\nwatch() {\n scr watch $*\n}\n\nssh() {\n scr ssh $*\n}\n</code></pre>\n\n<p>It opens a new screen for the above aliases and iff using ssh, it renames the screen title with the ssh hostname.</p>\n" }, { "answer_id": 4651572, "author": "bambams", "author_id": 149184, "author_profile": "https://Stackoverflow.com/users/149184", "pm_score": 1, "selected": false, "text": "<p>I like to use <code>screen -d -RR</code> to automatically create/attach to a given screen. I created bash functions to make it easier...</p>\n\n<pre><code>function mkscreen\n{\n local add=n\n\n if [ \"$1\" == '-a' ]; then\n add=y\n shift;\n fi\n\n local name=$1;\n shift;\n local command=\"$*\";\n\n if [ -z \"$name\" -o -z \"$command\" ]; then\n echo 'Usage: mkscreen [ -a ] name command\n\n -a Add to .bashrc.' 1&gt;&amp;2;\n return 1;\n fi\n\n if [ $add == y ]; then\n echo \"mkscreen $name $command\" &gt;&gt; $HOME/.bashrc;\n fi\n\n alias $name=\"/usr/bin/screen -d -RR -S $name $command\";\n\n return 0;\n}\n\nfunction rmscreen\n{\n local delete=n\n\n if [ \"$1\" == '-d' ]; then\n delete=y\n shift;\n fi\n\n local name=$1;\n\n if [ -z \"$name\" ]; then\n echo 'Usage: rmscreen [ -d ] name\n\n -d Delete from .bashrc.' 1&gt;&amp;2;\n return 1;\n fi\n\n if [ $delete == y ]; then\n sed -i -r \"/^mkscreen $name .*/d\" $HOME/.bashrc;\n fi\n\n unalias $name;\n\n return 0;\n}\n</code></pre>\n\n<p>They create an alias to <code>/usr/bin/screen -d -RR -S $name $command</code>. For example, I like to use irssi in a screen session, so in my .bashrc (beneath those functions), I have:</p>\n\n<pre><code>mkscreen irc /usr/bin/irssi\n</code></pre>\n\n<p>Then I can just type <code>irc</code> in a terminal to get into irssi. If the screen 'irc' doesn't exist yet then it is created and /usr/bin/irssi is run from it (which connects automatically, of course). If it's already running then I just reattach to it, forcibly detaching any other instance that is already attached to it. It's quite nice.</p>\n\n<p>Another example is creating temporary screen aliases for perldocs as I come across them:</p>\n\n<pre><code>mkscreen perlipc perldoc perlipc\nperlipc # Start reading the perldoc, ^A d to detach.\n...\n# Later, when I'm done reading it, or at least finished\n# with the alias, I remove it.\nrmscreen perlipc \n</code></pre>\n\n<p>The -a option (must be first argument) appends the screen alias to .bashrc (so it's persistent) and -d removes it (these can potentially be destructive, so use at own risk). xD</p>\n\n<p>Append:</p>\n\n<p>Another bash-ism that I find convenient when working a lot with screen:</p>\n\n<pre><code>alias sls='/usr/bin/screen -ls'\n</code></pre>\n\n<p>That way you can list your screens with a lot fewer keystrokes. I don't know if <code>sls</code> collides with any existing utilities, but it didn't at the time on my system so I went for it.</p>\n" }, { "answer_id": 15283793, "author": "user2146463", "author_id": 2146463, "author_profile": "https://Stackoverflow.com/users/2146463", "pm_score": 0, "selected": false, "text": "<p><kbd>Ctrl</kbd> + <kbd>A</kbd> is a great special character for Unix people, but if you're using screen to talk to <a href=\"https://en.wikipedia.org/wiki/OpenVMS\" rel=\"nofollow noreferrer\">OpenVMS</a>, then not being able to ^A is going to make you bald prematurely.</p>\n\n<p>In <a href=\"https://en.wikipedia.org/wiki/OpenVMS#Origin_and_name_changes\" rel=\"nofollow noreferrer\">VMS</a>, if you're editing a <a href=\"https://en.wikipedia.org/wiki/DIGITAL_Command_Language\" rel=\"nofollow noreferrer\">DCL</a> command prior to execution from the history buffer, Insert mode is off (it has to be for a few reasons I won't get into here) ... to turn it on so you don't over-type your command rather than space things out, you have to hit `^A.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
I've just introduced a friend to **GNU Screen** and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent **Screen** utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.? It would be awesome.
I've been using `Screen` for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are: ``` ^A ^W - window list, where am I ^A ^C - create new window ^A space - next window ^A p - previous window ^A ^A - switch to previous screen (toggle) ^A [0-9] - go to window [0-9] ^A esc - copy mode, which I use for scrollback ``` I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both `^Q` and `^A ^Q` to try to unlock it.
70,625
<p>How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?</p> <pre><code>public class LanguageCode { /// &lt;summary&gt; /// Get the lowercase two-character ISO 639-1 language code. /// &lt;/summary&gt; public readonly string Value; public LanguageCode(string language) { this.Value = new CultureInfo(language).TwoLetterISOLanguageName; } public static LanguageCode TryParse(string language) { if (language == null) { return null; } if (language.Length &gt; 2) { language = language.Substring(0, 2); } try { return new LanguageCode(language); } catch (ArgumentException) { return null; } } } public class RegionCode { /// &lt;summary&gt; /// Get the uppercase two-character ISO 3166 region/country code. /// &lt;/summary&gt; public readonly string Value; public RegionCode(string region) { this.Value = new RegionInfo(region).TwoLetterISORegionName; } public static RegionCode TryParse(string region) { if (region == null) { return null; } if (region.Length &gt; 2) { region = region.Substring(0, 2); } try { return new RegionCode(region); } catch (ArgumentException) { return null; } } } </code></pre>
[ { "answer_id": 70645, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 2, "selected": false, "text": "<p>It depends, if they are not going to do much more, then I would probably leave them as is - IMHO factoring out stuff is likely to be more complex, in this case.</p>\n" }, { "answer_id": 70662, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 0, "selected": false, "text": "<p>This is a rather simple question and to me smells awefully like a homework assignment.</p>\n\n<p>You can obviously see the common bits in the code and I'm pretty sure you can make an attempt at it yourself by putting such things into a super-class.</p>\n" }, { "answer_id": 70667, "author": "Ben", "author_id": 5005, "author_profile": "https://Stackoverflow.com/users/5005", "pm_score": 0, "selected": false, "text": "<p>You could maybe combine them into a <code>Locale</code> class, which stores both Language code and Region code, has accessors for Region and Language plus one parse function which also allows for strings like \"en_gb\"...</p>\n\n<p>That's how I've seen locales be handled in various frameworks.</p>\n" }, { "answer_id": 70671, "author": "Steve Morgan", "author_id": 5806, "author_profile": "https://Stackoverflow.com/users/5806", "pm_score": 0, "selected": false, "text": "<p>These two, as they stand, aren't going to refactor well because of the static methods.</p>\n\n<p>You'd either end up with some kind of factory method on a base class that returns an a type of that base class (which would subsequently need casting) or you'd need some kind of additional helper class.</p>\n\n<p>Given the amount of extra code and subsequent casting to the appropriate type, it's not worth it.</p>\n" }, { "answer_id": 70673, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>I'm sure there is a better generics based solution. But still gave it a shot. </p>\n\n<p>EDIT: As the comment says, static methods can't be overridden so one option would be to retain it and use TwoLetterCode objects around and cast them, but, as some other person has already pointed out, that is rather useless. </p>\n\n<p>How about this?</p>\n\n<pre><code>public class TwoLetterCode {\n public readonly string Value;\n public static TwoLetterCode TryParseSt(string tlc) {\n if (tlc == null)\n {\n return null;\n }\n\n if (tlc.Length &gt; 2)\n {\n tlc = tlc.Substring(0, 2);\n }\n\n try\n {\n return new TwoLetterCode(tlc);\n }\n catch (ArgumentException)\n {\n return null;\n }\n }\n}\n//Likewise for Region\npublic class LanguageCode : TwoLetterCode {\n public LanguageCode(string language)\n {\n this.Value = new CultureInfo(language).TwoLetterISOLanguageName;\n }\n public static LanguageCode TryParse(string language) {\n return (LanguageCode)TwoLetterCode.TryParseSt(language);\n }\n}\n</code></pre>\n" }, { "answer_id": 70684, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Create a generic base class (eg <code>AbstractCode&lt;T&gt;</code>)</li>\n<li><p>add abstract methods like</p>\n\n<pre><code>protected T GetConstructor(string code);\n</code></pre></li>\n<li><p>override in base classes like</p>\n\n<pre><code>protected override RegionCode GetConstructor(string code)\n{\n return new RegionCode(code);\n}\n</code></pre></li>\n<li><p>Finally, do the same with <code>string GetIsoName(string code)</code>, eg</p>\n\n<pre><code>protected override GetIsoName(string code)\n{\n return new RegionCode(code).TowLetterISORegionName;\n}\n</code></pre></li>\n</ol>\n\n<p>That will refactor the both. Chris Kimpton does raise the important question as to whether the effort is worth it. </p>\n" }, { "answer_id": 70777, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 1, "selected": true, "text": "<p>Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions.</p>\n\n<pre><code>public class TwoLetterCode&lt;T&gt;\n{\n private readonly string value;\n\n public TwoLetterCode(string value, Func&lt;string, string&gt; predicate)\n {\n this.value = predicate(value);\n }\n\n public static T TryParse(string value, Func&lt;string, T&gt; predicate)\n {\n if (value == null)\n {\n return default(T);\n }\n\n if (value.Length &gt; 2)\n {\n value = value.Substring(0, 2);\n }\n\n try\n {\n return predicate(value);\n }\n catch (ArgumentException)\n {\n return default(T);\n }\n }\n\n public string Value { get { return this.value; } }\n}\n\npublic class LanguageCode : TwoLetterCode&lt;LanguageCode&gt; {\n public LanguageCode(string language)\n : base(language, v =&gt; new CultureInfo(v).TwoLetterISOLanguageName)\n {\n }\n\n public static LanguageCode TryParse(string language)\n {\n return TwoLetterCode&lt;LanguageCode&gt;.TryParse(language, v =&gt; new LanguageCode(v));\n }\n}\n\npublic class RegionCode : TwoLetterCode&lt;RegionCode&gt;\n{\n public RegionCode(string language)\n : base(language, v =&gt; new CultureInfo(v).TwoLetterISORegionName)\n {\n }\n\n public static RegionCode TryParse(string language)\n {\n return TwoLetterCode&lt;RegionCode&gt;.TryParse(language, v =&gt; new RegionCode(v));\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like? ``` public class LanguageCode { /// <summary> /// Get the lowercase two-character ISO 639-1 language code. /// </summary> public readonly string Value; public LanguageCode(string language) { this.Value = new CultureInfo(language).TwoLetterISOLanguageName; } public static LanguageCode TryParse(string language) { if (language == null) { return null; } if (language.Length > 2) { language = language.Substring(0, 2); } try { return new LanguageCode(language); } catch (ArgumentException) { return null; } } } public class RegionCode { /// <summary> /// Get the uppercase two-character ISO 3166 region/country code. /// </summary> public readonly string Value; public RegionCode(string region) { this.Value = new RegionInfo(region).TwoLetterISORegionName; } public static RegionCode TryParse(string region) { if (region == null) { return null; } if (region.Length > 2) { region = region.Substring(0, 2); } try { return new RegionCode(region); } catch (ArgumentException) { return null; } } } ```
Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions. ``` public class TwoLetterCode<T> { private readonly string value; public TwoLetterCode(string value, Func<string, string> predicate) { this.value = predicate(value); } public static T TryParse(string value, Func<string, T> predicate) { if (value == null) { return default(T); } if (value.Length > 2) { value = value.Substring(0, 2); } try { return predicate(value); } catch (ArgumentException) { return default(T); } } public string Value { get { return this.value; } } } public class LanguageCode : TwoLetterCode<LanguageCode> { public LanguageCode(string language) : base(language, v => new CultureInfo(v).TwoLetterISOLanguageName) { } public static LanguageCode TryParse(string language) { return TwoLetterCode<LanguageCode>.TryParse(language, v => new LanguageCode(v)); } } public class RegionCode : TwoLetterCode<RegionCode> { public RegionCode(string language) : base(language, v => new CultureInfo(v).TwoLetterISORegionName) { } public static RegionCode TryParse(string language) { return TwoLetterCode<RegionCode>.TryParse(language, v => new RegionCode(v)); } } ```
70,653
<p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears.</p> <p>I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
[ { "answer_id": 70712, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 2, "selected": false, "text": "<p>I think you should make your own authentication method as you can make it fit your application best but use a library for encryption, such as <a href=\"http://www.pycrypto.org\" rel=\"nofollow noreferrer\">pycrypto</a> or some other more lightweight library.</p>\n\n<p>btw, if you need windows binaries for pycrypto you can get them <a href=\"http://www.voidspace.org.uk/python/modules.shtml#pycrypto\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 70832, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 0, "selected": false, "text": "<p>If you want simple, then use a dictionary where the keys are the usernames and the values are the passwords (encrypted with something like SHA256). <a href=\"http://docs.python.org/lib/module-pickle.html\" rel=\"nofollow noreferrer\">Pickle</a> it to/from disk (as this is a desktop application, I'm assuming the overhead of keeping it in memory will be negligible).</p>\n\n<p>For example:</p>\n\n<pre><code>import pickle\nimport hashlib\n\n# Load from disk\npwd_file = \"mypasswords\"\nif os.path.exists(pwd_file):\n pwds = pickle.load(open(pwd_file, \"rb\"))\nelse:\n pwds = {}\n\n# Save to disk\npickle.dump(pwds, open(pwd_file, \"wb\"))\n\n# Add password\npwds[username] = hashlib.sha256(password).hexdigest()\n\n# Check password\nif pwds[username] = hashlib.sha256(password).hexdigest():\n print \"Good\"\nelse:\n print \"No match\"\n</code></pre>\n\n<p>Note that this stores the passwords as a <a href=\"http://docs.python.org/lib/module-hashlib.html\" rel=\"nofollow noreferrer\">hash</a> - so they are essentially unrecoverable. If you lose your password, you'd get allocated a new one, not get the old one back.</p>\n" }, { "answer_id": 70915, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": true, "text": "<p>Treat the following as pseudo-code..</p>\n\n<pre><code>try:\n from hashlib import sha as hasher\nexcept ImportError:\n # You could probably exclude the try/except bit,\n # but older Python distros dont have hashlib.\n try:\n import sha as hasher\n except ImportError:\n import md5 as hasher\n\n\ndef hash_password(password):\n \"\"\"Returns the hashed version of a string\n \"\"\"\n return hasher.new( str(password) ).hexdigest()\n\ndef load_auth_file(path):\n \"\"\"Loads a comma-seperated file.\n Important: make sure the username\n doesn't contain any commas!\n \"\"\"\n # Open the file, or return an empty auth list.\n try:\n f = open(path)\n except IOError:\n print \"Warning: auth file not found\"\n return {}\n\n ret = {}\n for line in f.readlines():\n split_line = line.split(\",\")\n if len(split_line) &gt; 2:\n print \"Warning: Malformed line:\"\n print split_line\n continue # skip it..\n else:\n username, password = split_line\n ret[username] = password\n #end if\n #end for\n return ret\n\ndef main():\n auth_file = \"/home/blah/.myauth.txt\"\n u = raw_input(\"Username:\")\n p = raw_input(\"Password:\") # getpass is probably better..\n if auth_file.has_key(u.strip()):\n if auth_file[u] == hash_password(p):\n # The hash matches the stored one\n print \"Welcome, sir!\"\n</code></pre>\n\n<p>Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.</p>\n\n<p>Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the <code>~/.myauth.txt</code> file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful.</p>\n" }, { "answer_id": 80008, "author": "tim.tadh", "author_id": 14107, "author_profile": "https://Stackoverflow.com/users/14107", "pm_score": 4, "selected": false, "text": "<p>dbr said:</p>\n\n<blockquote>\n<pre><code>def hash_password(password):\n \"\"\"Returns the hashed version of a string\n \"\"\"\n return hasher.new( str(password) ).hexdigest()\n</code></pre>\n</blockquote>\n\n<p>This is a really insecure way to hash passwords. You <em>don't</em> want to do this. If you want to know why read the <a href=\"http://www.openbsd.org/papers/bcrypt-paper.pdf\" rel=\"noreferrer\" title=\"&quot;B-Crypt Paper\">Bycrypt Paper</a> by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out <a href=\"http://www.securityfocus.com/columnists/388\" rel=\"noreferrer\">this interview</a> with the author of Jack the Ripper (the popular unix password cracker).</p>\n\n<p>Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times.</p>\n\n<p>If that didn't make sense here is the code: </p>\n\n<pre><code>#note I am using the Python Cryptography Toolkit\nfrom Crypto.Hash import SHA256\n\nHASH_REPS = 50000\n\ndef __saltedhash(string, salt):\n sha256 = SHA256.new()\n sha256.update(string)\n sha256.update(salt)\n for x in xrange(HASH_REPS): \n sha256.update(sha256.digest())\n if x % 10: sha256.update(salt)\n return sha256\n\ndef saltedhash_bin(string, salt):\n \"\"\"returns the hash in binary format\"\"\"\n return __saltedhash(string, salt).digest()\n\ndef saltedhash_hex(string, salt):\n \"\"\"returns the hash in hex format\"\"\"\n return __saltedhash(string, salt).hexdigest()\n</code></pre>\n\n<p>For deploying a system like this the key thing to consider is the HASH_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file. </p>\n\n<p>Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there.</p>\n\n<p>hope this helps,\nTim</p>\n" }, { "answer_id": 1992484, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 0, "selected": false, "text": "<pre><code>import hashlib\nimport random\n\ndef gen_salt():\n salt_seed = str(random.getrandbits(128))\n salt = hashlib.sha256(salt_seed).hexdigest()\n return salt\n\ndef hash_password(password, salt):\n h = hashlib.sha256()\n h.update(salt)\n h.update(password)\n return h.hexdigest()\n\n#in datastore\npassword_stored_hash = \"41e2282a9c18a6c051a0636d369ad2d4727f8c70f7ddeebd11e6f49d9e6ba13c\"\nsalt_stored = \"fcc64c0c2bc30156f79c9bdcabfadcd71030775823cb993f11a4e6b01f9632c3\"\n\npassword_supplied = 'password'\n\npassword_supplied_hash = hash_password(password_supplied, salt_stored)\nauthenticated = (password_supplied_hash == password_stored_hash)\nprint authenticated #True\n</code></pre>\n\n<p>see also <a href=\"https://stackoverflow.com/questions/1990722/gae-authenticate-to-a-3rd-party-site\">gae-authenticate-to-a-3rd-party-site</a></p>\n" }, { "answer_id": 10495626, "author": "Anoop Augustine", "author_id": 1322161, "author_profile": "https://Stackoverflow.com/users/1322161", "pm_score": -1, "selected": false, "text": "<p>Use \" md5 \" it's much better than base64</p>\n\n<pre><code>&gt;&gt;&gt; import md5\n&gt;&gt;&gt; hh = md5.new()\n&gt;&gt;&gt; hh.update('anoop')\n&gt;&gt;&gt; hh.digest\n&lt;built-in method digest of _hashlib.HASH object at 0x01FE1E40&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11563/" ]
I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears. I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).
Treat the following as pseudo-code.. ``` try: from hashlib import sha as hasher except ImportError: # You could probably exclude the try/except bit, # but older Python distros dont have hashlib. try: import sha as hasher except ImportError: import md5 as hasher def hash_password(password): """Returns the hashed version of a string """ return hasher.new( str(password) ).hexdigest() def load_auth_file(path): """Loads a comma-seperated file. Important: make sure the username doesn't contain any commas! """ # Open the file, or return an empty auth list. try: f = open(path) except IOError: print "Warning: auth file not found" return {} ret = {} for line in f.readlines(): split_line = line.split(",") if len(split_line) > 2: print "Warning: Malformed line:" print split_line continue # skip it.. else: username, password = split_line ret[username] = password #end if #end for return ret def main(): auth_file = "/home/blah/.myauth.txt" u = raw_input("Username:") p = raw_input("Password:") # getpass is probably better.. if auth_file.has_key(u.strip()): if auth_file[u] == hash_password(p): # The hash matches the stored one print "Welcome, sir!" ``` Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such. Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the `~/.myauth.txt` file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful.
70,668
<p>What is the best way to backup VMWare Servers (1.0.x)? The virtual machines in question are our development environment, and run isololated from the main network (so you can't just copy data from virtual to real servers).</p> <p>The image files are normally in use and locked when the server is running, so it is difficult to back these up with the machines running.</p> <p>Currently: I manually pause the servers when I leave and have a scheduled task that runs at midnight to robocopy the images to a remote NAS. </p> <p>Is there a better way to do this, ideally without having to remember to pause the virtual machines?</p>
[ { "answer_id": 70692, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to use that to automatically pause the VMs before running the backup.</p>\n\n<p>If your backup software was shadow-copy aware, that might work, too.</p>\n" }, { "answer_id": 70740, "author": "John Stauffer", "author_id": 5874, "author_profile": "https://Stackoverflow.com/users/5874", "pm_score": 4, "selected": true, "text": "<p>VMWare server includes the command line tool \"vmware-cmd\", which can be used to perform virtually any operation that can be performed through the console.</p>\n\n<p>In this case you would simply add a \"vmware-cmd susepend\" to your script before starting your backup, and a \"vmware-cmd start\" after the backup is completed.</p>\n\n<p>We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.</p>\n\n<pre><code>Usage: /usr/bin/vmware-cmd &lt;options&gt; &lt;vm-cfg-path&gt; &lt;vm-action&gt; &lt;arguments&gt;\n /usr/bin/vmware-cmd -s &lt;options&gt; &lt;server-action&gt; &lt;arguments&gt;\n\n Options:\n Connection Options:\n -H &lt;host&gt; specifies an alternative host (if set, -U and -P must also be set)\n -O &lt;port&gt; specifies an alternative port\n -U &lt;username&gt; specifies a user\n -P &lt;password&gt; specifies a password\n General Options:\n -h More detailed help.\n -q Quiet. Minimal output\n -v Verbose.\n\n Server Operations:\n /usr/bin/vmware-cmd -l \n /usr/bin/vmware-cmd -s register &lt;config_file_path&gt;\n /usr/bin/vmware-cmd -s unregister &lt;config_file_path&gt;\n /usr/bin/vmware-cmd -s getresource &lt;variable&gt;\n /usr/bin/vmware-cmd -s setresource &lt;variable&gt; &lt;value&gt;\n\n VM Operations:\n /usr/bin/vmware-cmd &lt;cfg&gt; getconnectedusers\n /usr/bin/vmware-cmd &lt;cfg&gt; getstate\n /usr/bin/vmware-cmd &lt;cfg&gt; start &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; stop &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; reset &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; suspend &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setconfig &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getconfig &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setguestinfo &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getguestinfo &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getid\n /usr/bin/vmware-cmd &lt;cfg&gt; getpid\n /usr/bin/vmware-cmd &lt;cfg&gt; getproductinfo &lt;prodinfo&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; connectdevice &lt;device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; disconnectdevice &lt;device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getconfigfile\n /usr/bin/vmware-cmd &lt;cfg&gt; getheartbeat\n /usr/bin/vmware-cmd &lt;cfg&gt; getuptime\n /usr/bin/vmware-cmd &lt;cfg&gt; getremoteconnections\n /usr/bin/vmware-cmd &lt;cfg&gt; gettoolslastactive\n /usr/bin/vmware-cmd &lt;cfg&gt; getresource &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setresource &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setrunasuser &lt;username&gt; &lt;password&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getrunasuser\n /usr/bin/vmware-cmd &lt;cfg&gt; getcapabilities\n /usr/bin/vmware-cmd &lt;cfg&gt; addredo &lt;disk_device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; commit &lt;disk_device_name&gt; &lt;level&gt; &lt;freeze&gt; &lt;wait&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; answer\n</code></pre>\n" }, { "answer_id": 129123, "author": "seisyll", "author_id": 21815, "author_profile": "https://Stackoverflow.com/users/21815", "pm_score": 0, "selected": false, "text": "<p>There is a tool called (ahem) Hobocopy which will copy locked VM files. I would recommend taking a snapshot of the VM and then backing up the VMDK. Then merge the snapshot after the copy is complete. </p>\n" }, { "answer_id": 551985, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>Worth looking at rsync? If only part of a large image file is changing then rsync might be the fastest way to copy any changes.</p>\n" }, { "answer_id": 2129965, "author": "MadCAt", "author_id": 258119, "author_profile": "https://Stackoverflow.com/users/258119", "pm_score": 1, "selected": false, "text": "<p>I found an easy to follow guide for backing up VM's in vmware server 2 here: <a href=\"http://www.bdts.com.au/tips/46-vmware/57-backing-up-vmware-server-2-.html\" rel=\"nofollow noreferrer\">Backup VMware Server 2</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
What is the best way to backup VMWare Servers (1.0.x)? The virtual machines in question are our development environment, and run isololated from the main network (so you can't just copy data from virtual to real servers). The image files are normally in use and locked when the server is running, so it is difficult to back these up with the machines running. Currently: I manually pause the servers when I leave and have a scheduled task that runs at midnight to robocopy the images to a remote NAS. Is there a better way to do this, ideally without having to remember to pause the virtual machines?
VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console. In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed. We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid. ``` Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments> /usr/bin/vmware-cmd -s <options> <server-action> <arguments> Options: Connection Options: -H <host> specifies an alternative host (if set, -U and -P must also be set) -O <port> specifies an alternative port -U <username> specifies a user -P <password> specifies a password General Options: -h More detailed help. -q Quiet. Minimal output -v Verbose. Server Operations: /usr/bin/vmware-cmd -l /usr/bin/vmware-cmd -s register <config_file_path> /usr/bin/vmware-cmd -s unregister <config_file_path> /usr/bin/vmware-cmd -s getresource <variable> /usr/bin/vmware-cmd -s setresource <variable> <value> VM Operations: /usr/bin/vmware-cmd <cfg> getconnectedusers /usr/bin/vmware-cmd <cfg> getstate /usr/bin/vmware-cmd <cfg> start <powerop_mode> /usr/bin/vmware-cmd <cfg> stop <powerop_mode> /usr/bin/vmware-cmd <cfg> reset <powerop_mode> /usr/bin/vmware-cmd <cfg> suspend <powerop_mode> /usr/bin/vmware-cmd <cfg> setconfig <variable> <value> /usr/bin/vmware-cmd <cfg> getconfig <variable> /usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value> /usr/bin/vmware-cmd <cfg> getguestinfo <variable> /usr/bin/vmware-cmd <cfg> getid /usr/bin/vmware-cmd <cfg> getpid /usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo> /usr/bin/vmware-cmd <cfg> connectdevice <device_name> /usr/bin/vmware-cmd <cfg> disconnectdevice <device_name> /usr/bin/vmware-cmd <cfg> getconfigfile /usr/bin/vmware-cmd <cfg> getheartbeat /usr/bin/vmware-cmd <cfg> getuptime /usr/bin/vmware-cmd <cfg> getremoteconnections /usr/bin/vmware-cmd <cfg> gettoolslastactive /usr/bin/vmware-cmd <cfg> getresource <variable> /usr/bin/vmware-cmd <cfg> setresource <variable> <value> /usr/bin/vmware-cmd <cfg> setrunasuser <username> <password> /usr/bin/vmware-cmd <cfg> getrunasuser /usr/bin/vmware-cmd <cfg> getcapabilities /usr/bin/vmware-cmd <cfg> addredo <disk_device_name> /usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait> /usr/bin/vmware-cmd <cfg> answer ```
70,681
<p>Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:</p> <pre><code>results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....} for item in sorted(results): try: cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item])) print item, results[item] # conn.commit() except: # conn=psycopg2.connect(user='bvm', database='wdb', password='redacted') # cur=conn.cursor() print 'choked on', item continue </code></pre> <p>This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:</p> <pre><code>agreement 19 agreements 1 agrees 1 agrippa 9 choked on agrippa's choked on agrippina </code></pre>
[ { "answer_id": 70692, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to use that to automatically pause the VMs before running the backup.</p>\n\n<p>If your backup software was shadow-copy aware, that might work, too.</p>\n" }, { "answer_id": 70740, "author": "John Stauffer", "author_id": 5874, "author_profile": "https://Stackoverflow.com/users/5874", "pm_score": 4, "selected": true, "text": "<p>VMWare server includes the command line tool \"vmware-cmd\", which can be used to perform virtually any operation that can be performed through the console.</p>\n\n<p>In this case you would simply add a \"vmware-cmd susepend\" to your script before starting your backup, and a \"vmware-cmd start\" after the backup is completed.</p>\n\n<p>We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.</p>\n\n<pre><code>Usage: /usr/bin/vmware-cmd &lt;options&gt; &lt;vm-cfg-path&gt; &lt;vm-action&gt; &lt;arguments&gt;\n /usr/bin/vmware-cmd -s &lt;options&gt; &lt;server-action&gt; &lt;arguments&gt;\n\n Options:\n Connection Options:\n -H &lt;host&gt; specifies an alternative host (if set, -U and -P must also be set)\n -O &lt;port&gt; specifies an alternative port\n -U &lt;username&gt; specifies a user\n -P &lt;password&gt; specifies a password\n General Options:\n -h More detailed help.\n -q Quiet. Minimal output\n -v Verbose.\n\n Server Operations:\n /usr/bin/vmware-cmd -l \n /usr/bin/vmware-cmd -s register &lt;config_file_path&gt;\n /usr/bin/vmware-cmd -s unregister &lt;config_file_path&gt;\n /usr/bin/vmware-cmd -s getresource &lt;variable&gt;\n /usr/bin/vmware-cmd -s setresource &lt;variable&gt; &lt;value&gt;\n\n VM Operations:\n /usr/bin/vmware-cmd &lt;cfg&gt; getconnectedusers\n /usr/bin/vmware-cmd &lt;cfg&gt; getstate\n /usr/bin/vmware-cmd &lt;cfg&gt; start &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; stop &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; reset &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; suspend &lt;powerop_mode&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setconfig &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getconfig &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setguestinfo &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getguestinfo &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getid\n /usr/bin/vmware-cmd &lt;cfg&gt; getpid\n /usr/bin/vmware-cmd &lt;cfg&gt; getproductinfo &lt;prodinfo&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; connectdevice &lt;device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; disconnectdevice &lt;device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getconfigfile\n /usr/bin/vmware-cmd &lt;cfg&gt; getheartbeat\n /usr/bin/vmware-cmd &lt;cfg&gt; getuptime\n /usr/bin/vmware-cmd &lt;cfg&gt; getremoteconnections\n /usr/bin/vmware-cmd &lt;cfg&gt; gettoolslastactive\n /usr/bin/vmware-cmd &lt;cfg&gt; getresource &lt;variable&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setresource &lt;variable&gt; &lt;value&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; setrunasuser &lt;username&gt; &lt;password&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; getrunasuser\n /usr/bin/vmware-cmd &lt;cfg&gt; getcapabilities\n /usr/bin/vmware-cmd &lt;cfg&gt; addredo &lt;disk_device_name&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; commit &lt;disk_device_name&gt; &lt;level&gt; &lt;freeze&gt; &lt;wait&gt;\n /usr/bin/vmware-cmd &lt;cfg&gt; answer\n</code></pre>\n" }, { "answer_id": 129123, "author": "seisyll", "author_id": 21815, "author_profile": "https://Stackoverflow.com/users/21815", "pm_score": 0, "selected": false, "text": "<p>There is a tool called (ahem) Hobocopy which will copy locked VM files. I would recommend taking a snapshot of the VM and then backing up the VMDK. Then merge the snapshot after the copy is complete. </p>\n" }, { "answer_id": 551985, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 2, "selected": false, "text": "<p>Worth looking at rsync? If only part of a large image file is changing then rsync might be the fastest way to copy any changes.</p>\n" }, { "answer_id": 2129965, "author": "MadCAt", "author_id": 258119, "author_profile": "https://Stackoverflow.com/users/258119", "pm_score": 1, "selected": false, "text": "<p>I found an easy to follow guide for backing up VM's in vmware server 2 here: <a href=\"http://www.bdts.com.au/tips/46-vmware/57-backing-up-vmware-server-2-.html\" rel=\"nofollow noreferrer\">Backup VMware Server 2</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11596/" ]
Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2: ``` results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....} for item in sorted(results): try: cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item])) print item, results[item] # conn.commit() except: # conn=psycopg2.connect(user='bvm', database='wdb', password='redacted') # cur=conn.cursor() print 'choked on', item continue ``` This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?: ``` agreement 19 agreements 1 agrees 1 agrippa 9 choked on agrippa's choked on agrippina ```
VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console. In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed. We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid. ``` Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments> /usr/bin/vmware-cmd -s <options> <server-action> <arguments> Options: Connection Options: -H <host> specifies an alternative host (if set, -U and -P must also be set) -O <port> specifies an alternative port -U <username> specifies a user -P <password> specifies a password General Options: -h More detailed help. -q Quiet. Minimal output -v Verbose. Server Operations: /usr/bin/vmware-cmd -l /usr/bin/vmware-cmd -s register <config_file_path> /usr/bin/vmware-cmd -s unregister <config_file_path> /usr/bin/vmware-cmd -s getresource <variable> /usr/bin/vmware-cmd -s setresource <variable> <value> VM Operations: /usr/bin/vmware-cmd <cfg> getconnectedusers /usr/bin/vmware-cmd <cfg> getstate /usr/bin/vmware-cmd <cfg> start <powerop_mode> /usr/bin/vmware-cmd <cfg> stop <powerop_mode> /usr/bin/vmware-cmd <cfg> reset <powerop_mode> /usr/bin/vmware-cmd <cfg> suspend <powerop_mode> /usr/bin/vmware-cmd <cfg> setconfig <variable> <value> /usr/bin/vmware-cmd <cfg> getconfig <variable> /usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value> /usr/bin/vmware-cmd <cfg> getguestinfo <variable> /usr/bin/vmware-cmd <cfg> getid /usr/bin/vmware-cmd <cfg> getpid /usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo> /usr/bin/vmware-cmd <cfg> connectdevice <device_name> /usr/bin/vmware-cmd <cfg> disconnectdevice <device_name> /usr/bin/vmware-cmd <cfg> getconfigfile /usr/bin/vmware-cmd <cfg> getheartbeat /usr/bin/vmware-cmd <cfg> getuptime /usr/bin/vmware-cmd <cfg> getremoteconnections /usr/bin/vmware-cmd <cfg> gettoolslastactive /usr/bin/vmware-cmd <cfg> getresource <variable> /usr/bin/vmware-cmd <cfg> setresource <variable> <value> /usr/bin/vmware-cmd <cfg> setrunasuser <username> <password> /usr/bin/vmware-cmd <cfg> getrunasuser /usr/bin/vmware-cmd <cfg> getcapabilities /usr/bin/vmware-cmd <cfg> addredo <disk_device_name> /usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait> /usr/bin/vmware-cmd <cfg> answer ```
70,682
<p>I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects. </p> <p>Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance.</p> <p>References to external documentation would also be appreciated</p> <p>Documentation of GCC 4.0x class layout is <a href="http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html#virtual" rel="noreferrer">here</a> and the Itanium, and more broadly GNU, ABI layout documents are <a href="http://www.codesourcery.com/public/cxx-abi/abi.html#general" rel="noreferrer">here</a>. </p>
[ { "answer_id": 25674843, "author": "GlGuru", "author_id": 497840, "author_profile": "https://Stackoverflow.com/users/497840", "pm_score": -1, "selected": false, "text": "<p>Most of the compiler implementations that I have seen just \"embed\" the base object into the derived object. It becomes irrelevant where the vtable is kept because the relative offset into the object will just be added at compile time as references are evaluated. </p>\n\n<p>Multiple and virtual inheritance are more complicated and can require a different offset depending on what is being accessed. </p>\n\n<p>I highly recommend reading this article on Code Project: <a href=\"http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible\" rel=\"nofollow\">The Impossibly Fast C++ Delegates</a></p>\n\n<p>It brilliantly gives a broad picture of how different compilers handle various aspects of inheritance. Fantastic read if you are interested in the low level workings of different compilers. </p>\n\n<p>Edit: I linked the wrong article over there. Corrected. </p>\n" }, { "answer_id": 28155780, "author": "LThode", "author_id": 3657206, "author_profile": "https://Stackoverflow.com/users/3657206", "pm_score": 4, "selected": false, "text": "<p>A virtual table is generally treated as an array of function pointers, although compilers are free to put data pointers (in MI and VI scenarios, or to typeinfos), integers (for fixups), or sentinel elements (such as NULL pointers) into it as well. The layout is generally compiler-specific (or ABI-specific where multiple C++ compilers share an ABI), but stable provided the classes being compiled have stable interfaces (otherwise you'd have to recompile your code all the time, and that's a drag). There are also additional tables that are needed to handle corner cases involving virtual and multiple inheritance, and to make sure that virtual calls during derived class construction behave as the Standard says they should under those circumstances (those are what the VTTs and construction tables in the output below are for).</p>\n\n<p>As to the specific case of GCC 4.x: the <code>-fdump-class-hierarchy</code> switch indeed acts as described (and then some). I tested it on <a href=\"http://coliru.stacked-crooked.com/a/16d53eb062d38bec\" rel=\"noreferrer\">Coliru</a> using the sample code below:</p>\n\n<pre><code>struct Base\n{\n virtual ~Base() {}\n virtual void f() = 0;\n};\n\nstruct OtherBase\n{\n virtual ~OtherBase() {}\n virtual void g() {}\n};\n\nstruct Derived: public Base\n{\n virtual ~Derived() {}\n virtual void f() {}\n};\n\nstruct MultiplyDerived: public Base, public OtherBase\n{\n virtual ~MultiplyDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n\nstruct OtherDerived: public Base\n{\n virtual ~OtherDerived() {}\n virtual void f() {}\n};\n\nstruct DiamondDerived: public Derived, public OtherDerived\n{\n virtual ~DiamondDerived() {}\n virtual void f() {}\n};\n\nstruct VirtuallyDerived: virtual public Base\n{\n virtual ~VirtuallyDerived() {}\n virtual void f() {}\n};\n\nstruct OtherVirtuallyDerived: virtual public Base\n{\n virtual ~OtherVirtuallyDerived() {}\n virtual void f() {}\n};\n\nstruct VirtuallyDiamondDerived: public VirtuallyDerived, public OtherVirtuallyDerived\n{\n virtual ~VirtuallyDiamondDerived() {}\n virtual void f() {}\n};\n\nstruct DoublyVirtuallyDiamondDerived: virtual public VirtuallyDerived, virtual public OtherVirtuallyDerived\n{\n virtual ~DoublyVirtuallyDiamondDerived() {}\n virtual void f() {}\n};\n\nstruct MixedVirtuallyDerived: virtual public Base, public OtherBase\n{\n virtual ~MixedVirtuallyDerived() {}\n};\n\nstruct MixedVirtuallyDiamondDerived: public VirtuallyDerived, public MixedVirtuallyDerived\n{\n virtual ~MixedVirtuallyDiamondDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n\nstruct VirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase\n{\n virtual ~VirtuallyMultiplyDerived() {}\n};\n\nstruct OtherVirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase\n{\n virtual ~OtherVirtuallyMultiplyDerived() {}\n};\n\nstruct MultiplyVirtuallyDiamondDerived: public VirtuallyMultiplyDerived, public OtherVirtuallyMultiplyDerived\n{\n virtual ~MultiplyVirtuallyDiamondDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n</code></pre>\n\n<p>and received from G++ (mangled name guide: TI's are typeinfos, TV's are vtables, and Th's and Tv's are thunks used to make correct virtual calls in the presence of multiple and/or virtual inheritance):</p>\n\n<pre>\nVtable for Base\n\nBase::_ZTV4Base: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI4Base)\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))__cxa_pure_virtual\n\n\nClass Base\n\n size=8 align=8\n\n base size=8 base align=8\n\nBase (0x0x7fd42c0355a0) 0 nearly-empty\n\n vptr=((& Base::_ZTV4Base) + 16u)\n\n\nVtable for OtherBase\n\nOtherBase::_ZTV9OtherBase: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI9OtherBase)\n\n16 (int (*)(...))OtherBase::~OtherBase\n\n24 (int (*)(...))OtherBase::~OtherBase\n\n32 (int (*)(...))OtherBase::g\n\n\nClass OtherBase\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherBase (0x0x7fd42c035600) 0 nearly-empty\n\n vptr=((& OtherBase::_ZTV9OtherBase) + 16u)\n\n\nVtable for Derived\n\nDerived::_ZTV7Derived: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI7Derived)\n\n16 (int (*)(...))Derived::~Derived\n\n24 (int (*)(...))Derived::~Derived\n\n32 (int (*)(...))Derived::f\n\n\nClass Derived\n\n size=8 align=8\n\n base size=8 base align=8\n\nDerived (0x0x7fd42c02d138) 0 nearly-empty\n\n vptr=((& Derived::_ZTV7Derived) + 16u)\n\n Base (0x0x7fd42c035660) 0 nearly-empty\n\n primary-for Derived (0x0x7fd42c02d138)\n\n\nVtable for MultiplyDerived\n\nMultiplyDerived::_ZTV15MultiplyDerived: 11u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI15MultiplyDerived)\n\n16 (int (*)(...))MultiplyDerived::~MultiplyDerived\n\n24 (int (*)(...))MultiplyDerived::~MultiplyDerived\n\n32 (int (*)(...))MultiplyDerived::f\n\n40 (int (*)(...))MultiplyDerived::g\n\n48 (int (*)(...))-8\n\n56 (int (*)(...))(& _ZTI15MultiplyDerived)\n\n64 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD1Ev\n\n72 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD0Ev\n\n80 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerived1gEv\n\n\nClass MultiplyDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nMultiplyDerived (0x0x7fd42c04aaf0) 0\n\n vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 16u)\n\n Base (0x0x7fd42c0356c0) 0 nearly-empty\n\n primary-for MultiplyDerived (0x0x7fd42c04aaf0)\n\n OtherBase (0x0x7fd42c035720) 8 nearly-empty\n\n vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 64u)\n\n\nVtable for OtherDerived\n\nOtherDerived::_ZTV12OtherDerived: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI12OtherDerived)\n\n16 (int (*)(...))OtherDerived::~OtherDerived\n\n24 (int (*)(...))OtherDerived::~OtherDerived\n\n32 (int (*)(...))OtherDerived::f\n\n\nClass OtherDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherDerived (0x0x7fd42c02d1a0) 0 nearly-empty\n\n vptr=((& OtherDerived::_ZTV12OtherDerived) + 16u)\n\n Base (0x0x7fd42c035780) 0 nearly-empty\n\n primary-for OtherDerived (0x0x7fd42c02d1a0)\n\n\nVtable for DiamondDerived\n\nDiamondDerived::_ZTV14DiamondDerived: 10u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI14DiamondDerived)\n\n16 (int (*)(...))DiamondDerived::~DiamondDerived\n\n24 (int (*)(...))DiamondDerived::~DiamondDerived\n\n32 (int (*)(...))DiamondDerived::f\n\n40 (int (*)(...))-8\n\n48 (int (*)(...))(& _ZTI14DiamondDerived)\n\n56 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD1Ev\n\n64 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD0Ev\n\n72 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerived1fEv\n\n\nClass DiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nDiamondDerived (0x0x7fd42c0625b0) 0\n\n vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 16u)\n\n Derived (0x0x7fd42c02d208) 0 nearly-empty\n\n primary-for DiamondDerived (0x0x7fd42c0625b0)\n\n Base (0x0x7fd42c0357e0) 0 nearly-empty\n\n primary-for Derived (0x0x7fd42c02d208)\n\n OtherDerived (0x0x7fd42c02d270) 8 nearly-empty\n\n vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 56u)\n\n Base (0x0x7fd42c035840) 8 nearly-empty\n\n primary-for OtherDerived (0x0x7fd42c02d270)\n\n\nVtable for VirtuallyDerived\n\nVirtuallyDerived::_ZTV16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 (int (*)(...))VirtuallyDerived::~VirtuallyDerived\n\n48 (int (*)(...))VirtuallyDerived::~VirtuallyDerived\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nVTT for VirtuallyDerived\n\nVirtuallyDerived::_ZTT16VirtuallyDerived: 2u entries\n\n0 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n8 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n\nClass VirtuallyDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nVirtuallyDerived (0x0x7fd42c02d2d8) 0 nearly-empty\n\n vptridx=0u vptr=((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n Base (0x0x7fd42c0358a0) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d2d8)\n\n vptridx=8u vbaseoffset=-40\n\n\nVtable for OtherVirtuallyDerived\n\nOtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived\n\n48 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n\nVTT for OtherVirtuallyDerived\n\nOtherVirtuallyDerived::_ZTT21OtherVirtuallyDerived: 2u entries\n\n0 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n8 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n\nClass OtherVirtuallyDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherVirtuallyDerived (0x0x7fd42c02d340) 0 nearly-empty\n\n vptridx=0u vptr=((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n Base (0x0x7fd42c035900) 0 nearly-empty virtual\n\n primary-for OtherVirtuallyDerived (0x0x7fd42c02d340)\n\n vptridx=8u vbaseoffset=-40\n\n\nVtable for VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived: 16u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)\n\n40 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived\n\n48 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived\n\n56 (int (*)(...))VirtuallyDiamondDerived::f\n\n64 18446744073709551608u\n\n72 18446744073709551608u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)\n\n104 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD1Ev\n\n112 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD0Ev\n\n120 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerived1fEv\n\n\nConstruction vtable for VirtuallyDerived (0x0x7fd42c02d3a8 instance) in VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for OtherVirtuallyDerived (0x0x7fd42c02d410 instance) in VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries\n\n0 18446744073709551608u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n64 8u\n\n72 8u\n\n80 (int (*)(...))8\n\n88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n96 0u\n\n104 0u\n\n112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv\n\n\nVTT for VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTT23VirtuallyDiamondDerived: 7u entries\n\n0 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n8 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n16 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n24 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)\n\n32 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)\n\n40 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n48 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)\n\n\nClass VirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nVirtuallyDiamondDerived (0x0x7fd42c07e460) 0\n\n vptridx=0u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n VirtuallyDerived (0x0x7fd42c02d3a8) 0 nearly-empty\n\n primary-for VirtuallyDiamondDerived (0x0x7fd42c07e460)\n\n subvttidx=8u\n\n Base (0x0x7fd42c035960) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d3a8)\n\n vptridx=40u vbaseoffset=-40\n\n OtherVirtuallyDerived (0x0x7fd42c02d410) 8 nearly-empty\n\n lost-primary\n\n subvttidx=24u vptridx=48u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)\n\n Base (0x0x7fd42c035960) alternative-path\n\n\nVtable for DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived: 18u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))0\n\n48 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)\n\n56 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived\n\n64 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived\n\n72 (int (*)(...))DoublyVirtuallyDiamondDerived::f\n\n80 18446744073709551608u\n\n88 18446744073709551608u\n\n96 18446744073709551608u\n\n104 (int (*)(...))-8\n\n112 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)\n\n120 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD1Ev\n\n128 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD0Ev\n\n136 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n32_N29DoublyVirtuallyDiamondDerived1fEv\n\n\nConstruction vtable for VirtuallyDerived in DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for OtherVirtuallyDerived in DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries\n\n0 18446744073709551608u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n64 8u\n\n72 8u\n\n80 (int (*)(...))8\n\n88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n96 0u\n\n104 0u\n\n112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv\n\n\nVTT for DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTT29DoublyVirtuallyDiamondDerived: 8u entries\n\n0 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n8 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n16 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n24 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)\n\n32 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n40 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n48 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)\n\n56 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)\n\n\nClass DoublyVirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nDoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10) 0 nearly-empty\n\n vptridx=0u vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n VirtuallyDerived (0x0x7fd42c02d478) 0 nearly-empty virtual\n\n primary-for DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10)\n\n subvttidx=32u vptridx=8u vbaseoffset=-48\n\n Base (0x0x7fd42c035a80) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d478)\n\n vptridx=16u vbaseoffset=-40\n\n OtherVirtuallyDerived (0x0x7fd42c02d4e0) 8 nearly-empty virtual\n\n lost-primary\n\n subvttidx=48u vptridx=24u vbaseoffset=-56 vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)\n\n Base (0x0x7fd42c035a80) alternative-path\n\n\nVtable for MixedVirtuallyDerived\n\nMixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived: 13u entries\n\n0 8u\n\n8 (int (*)(...))0\n\n16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))OtherBase::g\n\n48 0u\n\n56 18446744073709551608u\n\n64 (int (*)(...))-8\n\n72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n80 0u\n\n88 0u\n\n96 (int (*)(...))__cxa_pure_virtual\n\n\nVTT for MixedVirtuallyDerived\n\nMixedVirtuallyDerived::_ZTT21MixedVirtuallyDerived: 2u entries\n\n0 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)\n\n8 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)\n\n\nClass MixedVirtuallyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nMixedVirtuallyDerived (0x0x7fd42c07eee0) 0 nearly-empty\n\n vptridx=0u vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)\n\n Base (0x0x7fd42c035c60) 8 nearly-empty virtual\n\n vptridx=8u vbaseoffset=-24 vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)\n\n OtherBase (0x0x7fd42c035cc0) 0 nearly-empty\n\n primary-for MixedVirtuallyDerived (0x0x7fd42c07eee0)\n\n\nVtable for MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived: 15u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)\n\n40 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived\n\n48 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived\n\n56 (int (*)(...))MixedVirtuallyDiamondDerived::f\n\n64 (int (*)(...))MixedVirtuallyDiamondDerived::g\n\n72 18446744073709551608u\n\n80 (int (*)(...))-8\n\n88 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)\n\n96 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD1Ev\n\n104 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD0Ev\n\n112 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerived1gEv\n\n\nConstruction vtable for VirtuallyDerived (0x0x7fd42c02d750 instance) in MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for MixedVirtuallyDerived (0x0x7fd42c0b5380 instance) in MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived: 13u entries\n\n0 18446744073709551608u\n\n8 (int (*)(...))0\n\n16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))OtherBase::g\n\n48 0u\n\n56 8u\n\n64 (int (*)(...))8\n\n72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n80 0u\n\n88 0u\n\n96 (int (*)(...))__cxa_pure_virtual\n\n\nVTT for MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTT28MixedVirtuallyDiamondDerived: 7u entries\n\n0 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n8 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n16 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n24 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 24u)\n\n32 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 80u)\n\n40 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n48 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)\n\n\nClass MixedVirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nMixedVirtuallyDiamondDerived (0x0x7fd42c0b5310) 0\n\n vptridx=0u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n VirtuallyDerived (0x0x7fd42c02d750) 0 nearly-empty\n\n primary-for MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310)\n\n subvttidx=8u\n\n Base (0x0x7fd42c035d20) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d750)\n\n vptridx=40u vbaseoffset=-40\n\n MixedVirtuallyDerived (0x0x7fd42c0b5380) 8 nearly-empty\n\n subvttidx=24u vptridx=48u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)\n\n Base (0x0x7fd42c035d20) alternative-path\n\n OtherBase (0x0x7fd42c035d80) 8 nearly-empty\n\n primary-for MixedVirtuallyDerived (0x0x7fd42c0b5380)\n\n\nVtable for VirtuallyMultiplyDerived\n\nVirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived: 16u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nVTT for VirtuallyMultiplyDerived\n\nVirtuallyMultiplyDerived::_ZTT24VirtuallyMultiplyDerived: 3u entries\n\n0 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n8 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n16 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)\n\n\nClass VirtuallyMultiplyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nVirtuallyMultiplyDerived (0x0x7fd42c0b59a0) 0 nearly-empty\n\n vptridx=0u vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n Base (0x0x7fd42c035e40) 0 nearly-empty virtual\n\n primary-for VirtuallyMultiplyDerived (0x0x7fd42c0b59a0)\n\n vptridx=8u vbaseoffset=-40\n\n OtherBase (0x0x7fd42c035ea0) 8 nearly-empty virtual\n\n vptridx=16u vbaseoffset=-48 vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)\n\n\nVtable for OtherVirtuallyMultiplyDerived\n\nOtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived: 16u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nVTT for OtherVirtuallyMultiplyDerived\n\nOtherVirtuallyMultiplyDerived::_ZTT29OtherVirtuallyMultiplyDerived: 3u entries\n\n0 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n8 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n16 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)\n\n\nClass OtherVirtuallyMultiplyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nOtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90) 0 nearly-empty\n\n vptridx=0u vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n Base (0x0x7fd42c035f00) 0 nearly-empty virtual\n\n primary-for OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90)\n\n vptridx=8u vbaseoffset=-40\n\n OtherBase (0x0x7fd42c035f60) 8 nearly-empty virtual\n\n vptridx=16u vbaseoffset=-48 vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)\n\n\nVtable for MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived: 26u entries\n\n0 16u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n48 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived\n\n56 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived\n\n64 (int (*)(...))MultiplyVirtuallyDiamondDerived::f\n\n72 (int (*)(...))MultiplyVirtuallyDiamondDerived::g\n\n80 8u\n\n88 18446744073709551608u\n\n96 18446744073709551608u\n\n104 18446744073709551608u\n\n112 (int (*)(...))-8\n\n120 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n128 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD1Ev\n\n136 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD0Ev\n\n144 0u\n\n152 18446744073709551600u\n\n160 18446744073709551600u\n\n168 (int (*)(...))-16\n\n176 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n184 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD1Ev\n\n192 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD0Ev\n\n200 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n32_N31MultiplyVirtuallyDiamondDerived1gEv\n\n\nConstruction vtable for VirtuallyMultiplyDerived (0x0x7fd42bcdf230 instance) in MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived: 16u entries\n\n0 16u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551600u\n\n88 (int (*)(...))-16\n\n96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nConstruction vtable for OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0 instance) in MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived: 23u entries\n\n0 8u\n\n8 18446744073709551608u\n\n16 18446744073709551608u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 8u\n\n88 (int (*)(...))8\n\n96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))__cxa_pure_virtual\n\n128 0u\n\n136 18446744073709551608u\n\n144 (int (*)(...))-8\n\n152 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n160 0u\n\n168 0u\n\n176 (int (*)(...))OtherBase::g\n\n\nVTT for MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTT31MultiplyVirtuallyDiamondDerived: 10u entries\n\n0 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n8 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)\n\n16 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)\n\n24 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 104u)\n\n32 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 48u)\n\n40 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 104u)\n\n48 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 160u)\n\n56 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n64 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)\n\n72 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)\n\n\nClass MultiplyVirtuallyDiamondDerived\n\n size=24 align=8\n\n base size=16 base align=8\n\nMultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0) 0\n\n vptridx=0u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n VirtuallyMultiplyDerived (0x0x7fd42bcdf230) 0 nearly-empty\n\n primary-for MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0)\n\n subvttidx=8u\n\n Base (0x0x7fd42bce2000) 0 nearly-empty virtual\n\n primary-for VirtuallyMultiplyDerived (0x0x7fd42bcdf230)\n\n vptridx=56u vbaseoffset=-40\n\n OtherBase (0x0x7fd42bce2060) 16 nearly-empty virtual\n\n vptridx=64u vbaseoffset=-48 vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)\n\n OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0) 8 nearly-empty\n\n lost-primary\n\n subvttidx=32u vptridx=72u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)\n\n Base (0x0x7fd42bce2000) alternative-path\n\n OtherBase (0x0x7fd42bce2060) alternative-path\n</pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8516/" ]
I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects. Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance. References to external documentation would also be appreciated Documentation of GCC 4.0x class layout is [here](http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html#virtual) and the Itanium, and more broadly GNU, ABI layout documents are [here](http://www.codesourcery.com/public/cxx-abi/abi.html#general).
A virtual table is generally treated as an array of function pointers, although compilers are free to put data pointers (in MI and VI scenarios, or to typeinfos), integers (for fixups), or sentinel elements (such as NULL pointers) into it as well. The layout is generally compiler-specific (or ABI-specific where multiple C++ compilers share an ABI), but stable provided the classes being compiled have stable interfaces (otherwise you'd have to recompile your code all the time, and that's a drag). There are also additional tables that are needed to handle corner cases involving virtual and multiple inheritance, and to make sure that virtual calls during derived class construction behave as the Standard says they should under those circumstances (those are what the VTTs and construction tables in the output below are for). As to the specific case of GCC 4.x: the `-fdump-class-hierarchy` switch indeed acts as described (and then some). I tested it on [Coliru](http://coliru.stacked-crooked.com/a/16d53eb062d38bec) using the sample code below: ``` struct Base { virtual ~Base() {} virtual void f() = 0; }; struct OtherBase { virtual ~OtherBase() {} virtual void g() {} }; struct Derived: public Base { virtual ~Derived() {} virtual void f() {} }; struct MultiplyDerived: public Base, public OtherBase { virtual ~MultiplyDerived() {} virtual void f() {} virtual void g() {} }; struct OtherDerived: public Base { virtual ~OtherDerived() {} virtual void f() {} }; struct DiamondDerived: public Derived, public OtherDerived { virtual ~DiamondDerived() {} virtual void f() {} }; struct VirtuallyDerived: virtual public Base { virtual ~VirtuallyDerived() {} virtual void f() {} }; struct OtherVirtuallyDerived: virtual public Base { virtual ~OtherVirtuallyDerived() {} virtual void f() {} }; struct VirtuallyDiamondDerived: public VirtuallyDerived, public OtherVirtuallyDerived { virtual ~VirtuallyDiamondDerived() {} virtual void f() {} }; struct DoublyVirtuallyDiamondDerived: virtual public VirtuallyDerived, virtual public OtherVirtuallyDerived { virtual ~DoublyVirtuallyDiamondDerived() {} virtual void f() {} }; struct MixedVirtuallyDerived: virtual public Base, public OtherBase { virtual ~MixedVirtuallyDerived() {} }; struct MixedVirtuallyDiamondDerived: public VirtuallyDerived, public MixedVirtuallyDerived { virtual ~MixedVirtuallyDiamondDerived() {} virtual void f() {} virtual void g() {} }; struct VirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase { virtual ~VirtuallyMultiplyDerived() {} }; struct OtherVirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase { virtual ~OtherVirtuallyMultiplyDerived() {} }; struct MultiplyVirtuallyDiamondDerived: public VirtuallyMultiplyDerived, public OtherVirtuallyMultiplyDerived { virtual ~MultiplyVirtuallyDiamondDerived() {} virtual void f() {} virtual void g() {} }; ``` and received from G++ (mangled name guide: TI's are typeinfos, TV's are vtables, and Th's and Tv's are thunks used to make correct virtual calls in the presence of multiple and/or virtual inheritance): ``` Vtable for Base Base::_ZTV4Base: 5u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI4Base) 16 0u 24 0u 32 (int (*)(...))__cxa_pure_virtual Class Base size=8 align=8 base size=8 base align=8 Base (0x0x7fd42c0355a0) 0 nearly-empty vptr=((& Base::_ZTV4Base) + 16u) Vtable for OtherBase OtherBase::_ZTV9OtherBase: 5u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI9OtherBase) 16 (int (*)(...))OtherBase::~OtherBase 24 (int (*)(...))OtherBase::~OtherBase 32 (int (*)(...))OtherBase::g Class OtherBase size=8 align=8 base size=8 base align=8 OtherBase (0x0x7fd42c035600) 0 nearly-empty vptr=((& OtherBase::_ZTV9OtherBase) + 16u) Vtable for Derived Derived::_ZTV7Derived: 5u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI7Derived) 16 (int (*)(...))Derived::~Derived 24 (int (*)(...))Derived::~Derived 32 (int (*)(...))Derived::f Class Derived size=8 align=8 base size=8 base align=8 Derived (0x0x7fd42c02d138) 0 nearly-empty vptr=((& Derived::_ZTV7Derived) + 16u) Base (0x0x7fd42c035660) 0 nearly-empty primary-for Derived (0x0x7fd42c02d138) Vtable for MultiplyDerived MultiplyDerived::_ZTV15MultiplyDerived: 11u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI15MultiplyDerived) 16 (int (*)(...))MultiplyDerived::~MultiplyDerived 24 (int (*)(...))MultiplyDerived::~MultiplyDerived 32 (int (*)(...))MultiplyDerived::f 40 (int (*)(...))MultiplyDerived::g 48 (int (*)(...))-8 56 (int (*)(...))(& _ZTI15MultiplyDerived) 64 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD1Ev 72 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD0Ev 80 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerived1gEv Class MultiplyDerived size=16 align=8 base size=16 base align=8 MultiplyDerived (0x0x7fd42c04aaf0) 0 vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 16u) Base (0x0x7fd42c0356c0) 0 nearly-empty primary-for MultiplyDerived (0x0x7fd42c04aaf0) OtherBase (0x0x7fd42c035720) 8 nearly-empty vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 64u) Vtable for OtherDerived OtherDerived::_ZTV12OtherDerived: 5u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI12OtherDerived) 16 (int (*)(...))OtherDerived::~OtherDerived 24 (int (*)(...))OtherDerived::~OtherDerived 32 (int (*)(...))OtherDerived::f Class OtherDerived size=8 align=8 base size=8 base align=8 OtherDerived (0x0x7fd42c02d1a0) 0 nearly-empty vptr=((& OtherDerived::_ZTV12OtherDerived) + 16u) Base (0x0x7fd42c035780) 0 nearly-empty primary-for OtherDerived (0x0x7fd42c02d1a0) Vtable for DiamondDerived DiamondDerived::_ZTV14DiamondDerived: 10u entries 0 (int (*)(...))0 8 (int (*)(...))(& _ZTI14DiamondDerived) 16 (int (*)(...))DiamondDerived::~DiamondDerived 24 (int (*)(...))DiamondDerived::~DiamondDerived 32 (int (*)(...))DiamondDerived::f 40 (int (*)(...))-8 48 (int (*)(...))(& _ZTI14DiamondDerived) 56 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD1Ev 64 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD0Ev 72 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerived1fEv Class DiamondDerived size=16 align=8 base size=16 base align=8 DiamondDerived (0x0x7fd42c0625b0) 0 vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 16u) Derived (0x0x7fd42c02d208) 0 nearly-empty primary-for DiamondDerived (0x0x7fd42c0625b0) Base (0x0x7fd42c0357e0) 0 nearly-empty primary-for Derived (0x0x7fd42c02d208) OtherDerived (0x0x7fd42c02d270) 8 nearly-empty vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 56u) Base (0x0x7fd42c035840) 8 nearly-empty primary-for OtherDerived (0x0x7fd42c02d270) Vtable for VirtuallyDerived VirtuallyDerived::_ZTV16VirtuallyDerived: 8u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI16VirtuallyDerived) 40 (int (*)(...))VirtuallyDerived::~VirtuallyDerived 48 (int (*)(...))VirtuallyDerived::~VirtuallyDerived 56 (int (*)(...))VirtuallyDerived::f VTT for VirtuallyDerived VirtuallyDerived::_ZTT16VirtuallyDerived: 2u entries 0 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u) 8 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u) Class VirtuallyDerived size=8 align=8 base size=8 base align=8 VirtuallyDerived (0x0x7fd42c02d2d8) 0 nearly-empty vptridx=0u vptr=((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u) Base (0x0x7fd42c0358a0) 0 nearly-empty virtual primary-for VirtuallyDerived (0x0x7fd42c02d2d8) vptridx=8u vbaseoffset=-40 Vtable for OtherVirtuallyDerived OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived: 8u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived) 40 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived 48 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived 56 (int (*)(...))OtherVirtuallyDerived::f VTT for OtherVirtuallyDerived OtherVirtuallyDerived::_ZTT21OtherVirtuallyDerived: 2u entries 0 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u) 8 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u) Class OtherVirtuallyDerived size=8 align=8 base size=8 base align=8 OtherVirtuallyDerived (0x0x7fd42c02d340) 0 nearly-empty vptridx=0u vptr=((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u) Base (0x0x7fd42c035900) 0 nearly-empty virtual primary-for OtherVirtuallyDerived (0x0x7fd42c02d340) vptridx=8u vbaseoffset=-40 Vtable for VirtuallyDiamondDerived VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived: 16u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived) 40 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived 48 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived 56 (int (*)(...))VirtuallyDiamondDerived::f 64 18446744073709551608u 72 18446744073709551608u 80 18446744073709551608u 88 (int (*)(...))-8 96 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived) 104 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD1Ev 112 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD0Ev 120 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerived1fEv Construction vtable for VirtuallyDerived (0x0x7fd42c02d3a8 instance) in VirtuallyDiamondDerived VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI16VirtuallyDerived) 40 0u 48 0u 56 (int (*)(...))VirtuallyDerived::f Construction vtable for OtherVirtuallyDerived (0x0x7fd42c02d410 instance) in VirtuallyDiamondDerived VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries 0 18446744073709551608u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived) 40 0u 48 0u 56 (int (*)(...))OtherVirtuallyDerived::f 64 8u 72 8u 80 (int (*)(...))8 88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived) 96 0u 104 0u 112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv VTT for VirtuallyDiamondDerived VirtuallyDiamondDerived::_ZTT23VirtuallyDiamondDerived: 7u entries 0 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u) 8 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 16 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 24 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u) 32 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u) 40 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u) 48 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u) Class VirtuallyDiamondDerived size=16 align=8 base size=16 base align=8 VirtuallyDiamondDerived (0x0x7fd42c07e460) 0 vptridx=0u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u) VirtuallyDerived (0x0x7fd42c02d3a8) 0 nearly-empty primary-for VirtuallyDiamondDerived (0x0x7fd42c07e460) subvttidx=8u Base (0x0x7fd42c035960) 0 nearly-empty virtual primary-for VirtuallyDerived (0x0x7fd42c02d3a8) vptridx=40u vbaseoffset=-40 OtherVirtuallyDerived (0x0x7fd42c02d410) 8 nearly-empty lost-primary subvttidx=24u vptridx=48u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u) Base (0x0x7fd42c035960) alternative-path Vtable for DoublyVirtuallyDiamondDerived DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived: 18u entries 0 8u 8 0u 16 0u 24 0u 32 0u 40 (int (*)(...))0 48 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived) 56 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived 64 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived 72 (int (*)(...))DoublyVirtuallyDiamondDerived::f 80 18446744073709551608u 88 18446744073709551608u 96 18446744073709551608u 104 (int (*)(...))-8 112 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived) 120 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD1Ev 128 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD0Ev 136 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n32_N29DoublyVirtuallyDiamondDerived1fEv Construction vtable for VirtuallyDerived in DoublyVirtuallyDiamondDerived DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI16VirtuallyDerived) 40 0u 48 0u 56 (int (*)(...))VirtuallyDerived::f Construction vtable for OtherVirtuallyDerived in DoublyVirtuallyDiamondDerived DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries 0 18446744073709551608u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived) 40 0u 48 0u 56 (int (*)(...))OtherVirtuallyDerived::f 64 8u 72 8u 80 (int (*)(...))8 88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived) 96 0u 104 0u 112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv VTT for DoublyVirtuallyDiamondDerived DoublyVirtuallyDiamondDerived::_ZTT29DoublyVirtuallyDiamondDerived: 8u entries 0 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u) 8 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u) 16 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u) 24 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u) 32 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 40 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 48 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u) 56 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u) Class DoublyVirtuallyDiamondDerived size=16 align=8 base size=8 base align=8 DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10) 0 nearly-empty vptridx=0u vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u) VirtuallyDerived (0x0x7fd42c02d478) 0 nearly-empty virtual primary-for DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10) subvttidx=32u vptridx=8u vbaseoffset=-48 Base (0x0x7fd42c035a80) 0 nearly-empty virtual primary-for VirtuallyDerived (0x0x7fd42c02d478) vptridx=16u vbaseoffset=-40 OtherVirtuallyDerived (0x0x7fd42c02d4e0) 8 nearly-empty virtual lost-primary subvttidx=48u vptridx=24u vbaseoffset=-56 vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u) Base (0x0x7fd42c035a80) alternative-path Vtable for MixedVirtuallyDerived MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived: 13u entries 0 8u 8 (int (*)(...))0 16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived) 24 0u 32 0u 40 (int (*)(...))OtherBase::g 48 0u 56 18446744073709551608u 64 (int (*)(...))-8 72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived) 80 0u 88 0u 96 (int (*)(...))__cxa_pure_virtual VTT for MixedVirtuallyDerived MixedVirtuallyDerived::_ZTT21MixedVirtuallyDerived: 2u entries 0 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u) 8 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u) Class MixedVirtuallyDerived size=16 align=8 base size=8 base align=8 MixedVirtuallyDerived (0x0x7fd42c07eee0) 0 nearly-empty vptridx=0u vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u) Base (0x0x7fd42c035c60) 8 nearly-empty virtual vptridx=8u vbaseoffset=-24 vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u) OtherBase (0x0x7fd42c035cc0) 0 nearly-empty primary-for MixedVirtuallyDerived (0x0x7fd42c07eee0) Vtable for MixedVirtuallyDiamondDerived MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived: 15u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived) 40 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived 48 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived 56 (int (*)(...))MixedVirtuallyDiamondDerived::f 64 (int (*)(...))MixedVirtuallyDiamondDerived::g 72 18446744073709551608u 80 (int (*)(...))-8 88 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived) 96 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD1Ev 104 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD0Ev 112 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerived1gEv Construction vtable for VirtuallyDerived (0x0x7fd42c02d750 instance) in MixedVirtuallyDiamondDerived MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries 0 0u 8 0u 16 0u 24 (int (*)(...))0 32 (int (*)(...))(& _ZTI16VirtuallyDerived) 40 0u 48 0u 56 (int (*)(...))VirtuallyDerived::f Construction vtable for MixedVirtuallyDerived (0x0x7fd42c0b5380 instance) in MixedVirtuallyDiamondDerived MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived: 13u entries 0 18446744073709551608u 8 (int (*)(...))0 16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived) 24 0u 32 0u 40 (int (*)(...))OtherBase::g 48 0u 56 8u 64 (int (*)(...))8 72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived) 80 0u 88 0u 96 (int (*)(...))__cxa_pure_virtual VTT for MixedVirtuallyDiamondDerived MixedVirtuallyDiamondDerived::_ZTT28MixedVirtuallyDiamondDerived: 7u entries 0 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u) 8 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 16 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u) 24 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 24u) 32 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 80u) 40 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u) 48 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u) Class MixedVirtuallyDiamondDerived size=16 align=8 base size=16 base align=8 MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310) 0 vptridx=0u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u) VirtuallyDerived (0x0x7fd42c02d750) 0 nearly-empty primary-for MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310) subvttidx=8u Base (0x0x7fd42c035d20) 0 nearly-empty virtual primary-for VirtuallyDerived (0x0x7fd42c02d750) vptridx=40u vbaseoffset=-40 MixedVirtuallyDerived (0x0x7fd42c0b5380) 8 nearly-empty subvttidx=24u vptridx=48u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u) Base (0x0x7fd42c035d20) alternative-path OtherBase (0x0x7fd42c035d80) 8 nearly-empty primary-for MixedVirtuallyDerived (0x0x7fd42c0b5380) Vtable for VirtuallyMultiplyDerived VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived: 16u entries 0 8u 8 0u 16 0u 24 0u 32 (int (*)(...))0 40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived) 48 0u 56 0u 64 (int (*)(...))__cxa_pure_virtual 72 0u 80 18446744073709551608u 88 (int (*)(...))-8 96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived) 104 0u 112 0u 120 (int (*)(...))OtherBase::g VTT for VirtuallyMultiplyDerived VirtuallyMultiplyDerived::_ZTT24VirtuallyMultiplyDerived: 3u entries 0 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u) 8 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u) 16 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u) Class VirtuallyMultiplyDerived size=16 align=8 base size=8 base align=8 VirtuallyMultiplyDerived (0x0x7fd42c0b59a0) 0 nearly-empty vptridx=0u vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u) Base (0x0x7fd42c035e40) 0 nearly-empty virtual primary-for VirtuallyMultiplyDerived (0x0x7fd42c0b59a0) vptridx=8u vbaseoffset=-40 OtherBase (0x0x7fd42c035ea0) 8 nearly-empty virtual vptridx=16u vbaseoffset=-48 vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u) Vtable for OtherVirtuallyMultiplyDerived OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived: 16u entries 0 8u 8 0u 16 0u 24 0u 32 (int (*)(...))0 40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived) 48 0u 56 0u 64 (int (*)(...))__cxa_pure_virtual 72 0u 80 18446744073709551608u 88 (int (*)(...))-8 96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived) 104 0u 112 0u 120 (int (*)(...))OtherBase::g VTT for OtherVirtuallyMultiplyDerived OtherVirtuallyMultiplyDerived::_ZTT29OtherVirtuallyMultiplyDerived: 3u entries 0 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u) 8 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u) 16 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u) Class OtherVirtuallyMultiplyDerived size=16 align=8 base size=8 base align=8 OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90) 0 nearly-empty vptridx=0u vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u) Base (0x0x7fd42c035f00) 0 nearly-empty virtual primary-for OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90) vptridx=8u vbaseoffset=-40 OtherBase (0x0x7fd42c035f60) 8 nearly-empty virtual vptridx=16u vbaseoffset=-48 vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u) Vtable for MultiplyVirtuallyDiamondDerived MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived: 26u entries 0 16u 8 0u 16 0u 24 0u 32 (int (*)(...))0 40 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived) 48 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived 56 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived 64 (int (*)(...))MultiplyVirtuallyDiamondDerived::f 72 (int (*)(...))MultiplyVirtuallyDiamondDerived::g 80 8u 88 18446744073709551608u 96 18446744073709551608u 104 18446744073709551608u 112 (int (*)(...))-8 120 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived) 128 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD1Ev 136 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD0Ev 144 0u 152 18446744073709551600u 160 18446744073709551600u 168 (int (*)(...))-16 176 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived) 184 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD1Ev 192 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD0Ev 200 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n32_N31MultiplyVirtuallyDiamondDerived1gEv Construction vtable for VirtuallyMultiplyDerived (0x0x7fd42bcdf230 instance) in MultiplyVirtuallyDiamondDerived MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived: 16u entries 0 16u 8 0u 16 0u 24 0u 32 (int (*)(...))0 40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived) 48 0u 56 0u 64 (int (*)(...))__cxa_pure_virtual 72 0u 80 18446744073709551600u 88 (int (*)(...))-16 96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived) 104 0u 112 0u 120 (int (*)(...))OtherBase::g Construction vtable for OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0 instance) in MultiplyVirtuallyDiamondDerived MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived: 23u entries 0 8u 8 18446744073709551608u 16 18446744073709551608u 24 0u 32 (int (*)(...))0 40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived) 48 0u 56 0u 64 (int (*)(...))__cxa_pure_virtual 72 0u 80 8u 88 (int (*)(...))8 96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived) 104 0u 112 0u 120 (int (*)(...))__cxa_pure_virtual 128 0u 136 18446744073709551608u 144 (int (*)(...))-8 152 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived) 160 0u 168 0u 176 (int (*)(...))OtherBase::g VTT for MultiplyVirtuallyDiamondDerived MultiplyVirtuallyDiamondDerived::_ZTT31MultiplyVirtuallyDiamondDerived: 10u entries 0 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u) 8 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u) 16 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u) 24 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 104u) 32 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 48u) 40 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 104u) 48 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 160u) 56 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u) 64 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u) 72 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u) Class MultiplyVirtuallyDiamondDerived size=24 align=8 base size=16 base align=8 MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0) 0 vptridx=0u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u) VirtuallyMultiplyDerived (0x0x7fd42bcdf230) 0 nearly-empty primary-for MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0) subvttidx=8u Base (0x0x7fd42bce2000) 0 nearly-empty virtual primary-for VirtuallyMultiplyDerived (0x0x7fd42bcdf230) vptridx=56u vbaseoffset=-40 OtherBase (0x0x7fd42bce2060) 16 nearly-empty virtual vptridx=64u vbaseoffset=-48 vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u) OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0) 8 nearly-empty lost-primary subvttidx=32u vptridx=72u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u) Base (0x0x7fd42bce2000) alternative-path OtherBase (0x0x7fd42bce2060) alternative-path ```
70,689
<p>What is an efficient way to implement a singleton design pattern in Java?</p>
[ { "answer_id": 70737, "author": "Neil Burroughs", "author_id": 5166, "author_profile": "https://Stackoverflow.com/users/5166", "pm_score": 6, "selected": false, "text": "<p>Make sure that you really need it. Do a google search for &quot;singleton anti-pattern&quot; to see some arguments against it.</p>\n<p>There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.</p>\n" }, { "answer_id": 70749, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 4, "selected": false, "text": "<p>Wikipedia has some <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"noreferrer\">examples</a> of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).</p>\n" }, { "answer_id": 70821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.</p>\n<p>Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting &quot;global&quot; data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">inversion of control</a> (IoC) or <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) for a nice middle ground.</p>\n<p>If you really need one then Wikipedia has a good example of a proper implementation of a singleton.</p>\n" }, { "answer_id": 70824, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 7, "selected": false, "text": "<p>Forget <a href=\"https://en.wikipedia.org/wiki/Lazy_initialization\" rel=\"nofollow noreferrer\">lazy initialization</a>; it's too problematic. This is the simplest solution:</p>\n<pre><code>public class A { \n\n private static final A INSTANCE = new A();\n\n private A() {}\n\n public static A getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n" }, { "answer_id": 70829, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 4, "selected": false, "text": "<p>If you do not need lazy loading then simply try:</p>\n<pre><code>public class Singleton {\n private final static Singleton INSTANCE = new Singleton();\n\n private Singleton() {}\n\n public static Singleton getInstance() { return Singleton.INSTANCE; }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:</p>\n<pre><code>public class Singleton {\n private static Singleton instance = null;\n\n private Singleton() {}\n\n public static Singleton getInstance() {\n if(null == instance) {\n synchronized(Singleton.class) {\n if(null == instance) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.</p>\n" }, { "answer_id": 70835, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 7, "selected": false, "text": "<p>Thread safe in Java 5+:</p>\n<pre><code>class Foo {\n private static volatile Bar bar = null;\n public static Bar getBar() {\n if (bar == null) {\n synchronized(Foo.class) {\n if (bar == null)\n bar = new Bar();\n }\n }\n return bar;\n }\n}\n</code></pre>\n<hr />\n<p>Pay attention to the <code>volatile</code> modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization <em>does not</em> take care of that--it only serializes access to that block of code.</p>\n<p>@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.</p>\n" }, { "answer_id": 71399, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 11, "selected": true, "text": "<p>Use an enum:</p>\n\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n\n<p>Joshua Bloch explained this approach in his <a href=\"http://sites.google.com/site/io/effective-java-reloaded\" rel=\"noreferrer\">Effective Java Reloaded</a> talk at Google I/O 2008: <a href=\"http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s\" rel=\"noreferrer\">link to video</a>. Also see slides 30-32 of his presentation (<a href=\"https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&amp;attredirects=0\" rel=\"noreferrer\">effective_java_reloaded.pdf</a>):</p>\n\n<blockquote>\n <h3>The Right Way to Implement a Serializable Singleton</h3>\n\n<pre><code>public enum Elvis {\n INSTANCE;\n private final String[] favoriteSongs =\n { \"Hound Dog\", \"Heartbreak Hotel\" };\n public void printFavorites() {\n System.out.println(Arrays.toString(favoriteSongs));\n }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Edit:</strong> An <a href=\"http://www.ddj.com/java/208403883?pgno=3\" rel=\"noreferrer\">online portion of \"Effective Java\"</a> says: </p>\n\n<blockquote>\n <p>\"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>.\"</p>\n</blockquote>\n" }, { "answer_id": 71574, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 4, "selected": false, "text": "<p>I'm mystified by some of the answers that suggest <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.</p>\n<p>So my answer to the OP would be (in all but the most trivial sample code) to:</p>\n<ol>\n<li>Use a DI framework like <a href=\"https://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring Framework</a>, then</li>\n<li>Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.</li>\n</ol>\n<p>This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).</p>\n" }, { "answer_id": 71683, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 7, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/70835#70835\">The solution posted by Stu Thompson</a> is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.</p>\n<p>It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of <a href=\"http://jcip.net/\" rel=\"nofollow noreferrer\" title=\"Java Concurrency in Practice\">Java Concurrency in Practice</a>. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.</p>\n<p>This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.</p>\n<pre><code>class Bar {\n private static class BarHolder {\n public static Bar bar = new Bar();\n }\n\n public static Bar getBar() {\n return BarHolder.bar;\n }\n}\n</code></pre>\n" }, { "answer_id": 73763, "author": "Roel Spilker", "author_id": 12634, "author_profile": "https://Stackoverflow.com/users/12634", "pm_score": 8, "selected": false, "text": "<p>Depending on the usage, there are several &quot;correct&quot; answers.</p>\n<p>Since Java 5, the best way to do it is to use an enum:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Pre Java 5, the most simple case is:</p>\n<pre><code>public final class Foo {\n\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n\n public Object clone() throws CloneNotSupportedException{\n throw new CloneNotSupportedException(&quot;Cannot clone instance of this class&quot;);\n }\n}\n</code></pre>\n<p>Let's go over the code. First, you want the class to be final. In this case, I've used the <code>final</code> keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a <code>private static final Foo</code> field to hold the only instance, and a <code>public static Foo getInstance()</code> method to return it. The Java specification makes sure that the constructor is only called when the class is first used.</p>\n<p>When you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.</p>\n<p>You can use a <code>private static class</code> to load the instance. The code would then look like:</p>\n<pre><code>public final class Foo {\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>\n<p>When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n @SuppressWarnings(&quot;unused&quot;)\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.</p>\n" }, { "answer_id": 74905, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": -1, "selected": false, "text": "<p>Sometimes a simple \"<strong><code>static Foo foo = new Foo();</code></strong>\" is not enough. Just think of some basic data insertion you want to do.</p>\n\n<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>\n\n<pre><code>public class Singleton {\n\n private static Singleton instance = null;\n\n static {\n instance = new Singleton();\n // do some of your instantiation stuff here\n }\n\n private Singleton() {\n if(instance!=null) {\n throw new ErrorYouWant(\"Singleton double-instantiation, should never happen!\");\n }\n }\n\n public static getSingleton() {\n return instance;\n }\n\n}\n</code></pre>\n\n<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>\n" }, { "answer_id": 117516, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 4, "selected": false, "text": "<p>I use the <a href=\"https://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring Framework</a> to manage my singletons.</p>\n<p>It doesn't enforce the &quot;singleton-ness&quot; of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.</p>\n" }, { "answer_id": 6918352, "author": "Onur", "author_id": 776658, "author_profile": "https://Stackoverflow.com/users/776658", "pm_score": 2, "selected": false, "text": "<p>You need the <a href=\"http://en.wikipedia.org/wiki/Double-checked_locking\" rel=\"nofollow noreferrer\">double-checking</a> idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the <a href=\"http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom\" rel=\"nofollow noreferrer\">initialization on demand holder</a> idiom.</p>\n<p>In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.</p>\n<pre><code>public static final INSTANCE == ....\nprivate Object readResolve() {\n return INSTANCE; // Original singleton instance.\n} \n</code></pre>\n" }, { "answer_id": 14372745, "author": "NullPoiиteя", "author_id": 1723893, "author_profile": "https://Stackoverflow.com/users/1723893", "pm_score": 3, "selected": false, "text": "<p>I would say an enum singleton.</p>\n<p>Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity's sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.</p>\n<p>The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.</p>\n<pre><code>/**\n* Singleton pattern example using a Java Enum\n*/\npublic enum Singleton {\n INSTANCE;\n public void execute (String arg) {\n // Perform operation here\n }\n}\n</code></pre>\n<p>You can access it by <code>Singleton.INSTANCE</code>, and it is much easier than calling the <code>getInstance()</code> method on Singleton.</p>\n<blockquote>\n<p>1.12 Serialization of Enum Constants</p>\n<p>Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, <code>ObjectOutputStream</code> writes the value returned by the enum constant's name method. To deserialize an enum constant, <code>ObjectInputStream</code> reads the constant name from the stream; the deserialized constant is then obtained by calling the <code>java.lang.Enum.valueOf</code> method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.</p>\n<p>The process by which enum constants are serialized cannot be customized: any class-specific <code>writeObject</code>, <code>readObject</code>, <code>readObjectNoData</code>, <code>writeReplace</code>, and <code>readResolve</code> methods defined by enum types are ignored during serialization and deserialization. Similarly, any <code>serialPersistentFields</code> or <code>serialVersionUID</code> field declarations are also ignored--all enum types have a fixed <code>serialVersionUID</code> of <code>0L</code>. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.</p>\n<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum\" rel=\"nofollow noreferrer\">Quoted from Oracle documentation</a></p>\n</blockquote>\n<p>Another problem with conventional Singletons are that once you implement the <code>Serializable</code> interface, they no longer remain singleton because the <code>readObject()</code> method always return a new instance, like a constructor in Java. This can be avoided by using <code>readResolve()</code> and discarding the newly created instance by replacing with a singleton like below:</p>\n<pre><code> // readResolve to prevent another instance of Singleton\n private Object readResolve(){\n return INSTANCE;\n }\n</code></pre>\n<p>This can become even more complex if your <em>singleton class</em> maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.</p>\n<hr />\n<p><strong>Good Read</strong></p>\n<ol>\n<li><a href=\"http://www.oodesign.com/singleton-pattern.html\" rel=\"nofollow noreferrer\">Singleton Pattern</a></li>\n<li><a href=\"https://stackoverflow.com/questions/13219678/enums-singletons-and-deserialization\">Enums, Singletons and Deserialization</a></li>\n<li><a href=\"http://www.ibm.com/developerworks/java/library/j-dcl/index.html\" rel=\"nofollow noreferrer\">Double-checked locking and the Singleton pattern</a></li>\n</ol>\n" }, { "answer_id": 14917772, "author": "Abhijit Gaikwad", "author_id": 403872, "author_profile": "https://Stackoverflow.com/users/403872", "pm_score": 4, "selected": false, "text": "<p>Following are three different approaches</p>\n<ol>\n<li><p>Enum</p>\n<pre><code> /**\n * Singleton pattern example using Java Enum\n */\n public enum EasySingleton {\n INSTANCE;\n }\n</code></pre>\n</li>\n<li><p>Double checked locking / lazy loading</p>\n<pre><code> /**\n * Singleton pattern example with Double checked Locking\n */\n public class DoubleCheckedLockingSingleton {\n private static volatile DoubleCheckedLockingSingleton INSTANCE;\n\n private DoubleCheckedLockingSingleton() {}\n\n public static DoubleCheckedLockingSingleton getInstance() {\n if(INSTANCE == null) {\n synchronized(DoubleCheckedLockingSingleton.class) {\n // Double checking Singleton instance\n if(INSTANCE == null) {\n INSTANCE = new DoubleCheckedLockingSingleton();\n }\n }\n }\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n<li><p>Static factory method</p>\n<pre><code> /**\n * Singleton pattern example with static factory method\n */\n\n public class Singleton {\n // Initialized during class loading\n private static final Singleton INSTANCE = new Singleton();\n\n // To prevent creating another instance of 'Singleton'\n private Singleton() {}\n\n public static Singleton getSingleton() {\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 16580366, "author": "Ajinkya", "author_id": 705773, "author_profile": "https://Stackoverflow.com/users/705773", "pm_score": 7, "selected": false, "text": "<p><strong>Disclaimer:</strong> I have just summarized all of the awesome answers and wrote it in my own words.</p>\n<hr />\n<p>While implementing Singleton we have two options:</p>\n<ol>\n<li>Lazy loading</li>\n<li>Early loading</li>\n</ol>\n<p>Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.</p>\n<p>The most simple way of implementing a singleton is:</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>Everything is good except it's an early loaded singleton. Lets try lazy loaded singleton</p>\n<pre><code>class Foo {\n\n // Our now_null_but_going_to_be sole hero\n private static Foo INSTANCE = null;\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n // Creating only when required.\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo let’s protect it from evil multi threading:</p>\n<pre><code>class Foo {\n\n private static Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n // No more tension of threads\n synchronized (Foo.class) {\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:</p>\n<pre><code>class Foo {\n\n // Pay attention to volatile\n private static volatile Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n if (INSTANCE == null) { // Check 1\n synchronized (Foo.class) {\n if (INSTANCE == null) { // Check 2\n INSTANCE = new Foo();\n }\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is called the &quot;double-checked locking idiom&quot;. It's easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details: <em><a href=\"http://www.cs.umd.edu/%7Epugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"noreferrer\">The &quot;Double-Checked Locking is Broken&quot; Declaration</a></em></p>\n<p>Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:</p>\n<pre><code>class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static volatile Foo INSTANCE = null;\n\n // The rest of the things are same as above\n\n // No more fear of serialization\n @SuppressWarnings(&quot;unused&quot;)\n private Object readResolve() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.</p>\n<p>Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n // Wrapped in a inner static class so that loaded only when required\n private static class FooLoader {\n\n // And no more fear of threads\n private static final Foo INSTANCE = new Foo();\n }\n\n // TODO add private shouting construcor\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n // Damn you serialization\n @SuppressWarnings(&quot;unused&quot;)\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Yes, this is our very same hero :)</p>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class <code>FooLoader</code> is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.</p>\n<p>And we have come so far. Here is the best way to achieve everything we did is best possible way:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Which internally will be treated like</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n}\n</code></pre>\n<p>That's it! No more fear of serialization, threads and ugly code. Also <a href=\"https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized\"><strong>ENUMS singleton are lazily initialized</strong></a>.</p>\n<blockquote>\n<p>This approach is functionally equivalent to the public field approach,\nexcept that it is more concise, provides the serialization machinery\nfor free, and provides an ironclad guarantee against multiple\ninstantiation, even in the face of sophisticated serialization or\nreflection attacks. While this approach has yet to be widely adopted,\na single-element enum type is the best way to implement a singleton.</p>\n</blockquote>\n<p>-Joshua Bloch in &quot;Effective Java&quot;</p>\n<p>Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)</p>\n<p>Updated it on my <a href=\"http://ajinkyaparakh.blogspot.in/2013/05/implementing-singleton-in-java.html\" rel=\"noreferrer\"><strong>blog</strong></a>.</p>\n" }, { "answer_id": 16699497, "author": "raoadnan", "author_id": 2392052, "author_profile": "https://Stackoverflow.com/users/2392052", "pm_score": 2, "selected": false, "text": "<p>For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).</p>\n" }, { "answer_id": 19562324, "author": "rohan kamat", "author_id": 2335562, "author_profile": "https://Stackoverflow.com/users/2335562", "pm_score": 1, "selected": false, "text": "<p>Simplest singleton class:</p>\n<pre><code>public class Singleton {\n private static Singleton singleInstance = new Singleton();\n private Singleton() {}\n public static Singleton getSingleInstance() {\n return singleInstance;\n }\n}\n</code></pre>\n" }, { "answer_id": 19849576, "author": "somenath mukhopadhyay", "author_id": 873952, "author_profile": "https://Stackoverflow.com/users/873952", "pm_score": -1, "selected": false, "text": "<pre><code>public class Singleton {\n\n private static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n if (INSTANCE != null)\n throw new IllegalStateException(“Already instantiated...”);\n }\n\n\n public synchronized static Singleton getInstance() {\n return INSTANCE;\n }\n\n}\n</code></pre>\n<p>As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.</p>\n" }, { "answer_id": 27793921, "author": "shikjohari", "author_id": 2595642, "author_profile": "https://Stackoverflow.com/users/2595642", "pm_score": 0, "selected": false, "text": "<p>I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.</p>\n<pre><code>public enum Singleton {\n INSTANCE;\n}\n</code></pre>\n<p>And you are done!</p>\n" }, { "answer_id": 29389322, "author": "coderz", "author_id": 3275167, "author_profile": "https://Stackoverflow.com/users/3275167", "pm_score": 4, "selected": false, "text": "<p><strong>Version 1:</strong></p>\n\n<pre><code>public class MySingleton {\n private static MySingleton instance = null;\n private MySingleton() {}\n public static synchronized MySingleton getInstance() {\n if(instance == null) {\n instance = new MySingleton();\n }\n return instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with blocking, low performance because of <code>synchronized</code>.</p>\n\n<p><strong>Version 2:</strong></p>\n\n<pre><code>public class MySingleton {\n private MySingleton() {}\n private static class MySingletonHolder {\n public final static MySingleton instance = new MySingleton();\n }\n public static MySingleton getInstance() {\n return MySingletonHolder.instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with non-blocking, high performance.</p>\n" }, { "answer_id": 32130663, "author": "kenju", "author_id": 2775013, "author_profile": "https://Stackoverflow.com/users/2775013", "pm_score": 0, "selected": false, "text": "<p>Have a look at this post.</p>\n<p><a href=\"https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries\">Examples of GoF Design Patterns in Java&#39;s core libraries</a></p>\n<p>From the best answer's &quot;Singleton&quot; section,</p>\n<blockquote>\n<h3>Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)</h3>\n<ul>\n<li>java.lang.Runtime#getRuntime()</li>\n<li>java.awt.Desktop#getDesktop()</li>\n<li>java.lang.System#getSecurityManager()</li>\n</ul>\n</blockquote>\n<p>You can also learn the example of Singleton from Java native classes themselves.</p>\n" }, { "answer_id": 32286179, "author": "Shailendra Singh", "author_id": 2550410, "author_profile": "https://Stackoverflow.com/users/2550410", "pm_score": 2, "selected": false, "text": "<p>Various ways to make a singleton object:</p>\n<ol>\n<li><p>As per <a href=\"https://en.wikipedia.org/wiki/Joshua_Bloch\" rel=\"nofollow noreferrer\">Joshua Bloch</a> - Enum would be the best.</p>\n</li>\n<li><p>You can use double check locking also.</p>\n</li>\n<li><p>Even an inner static class can be used.</p>\n</li>\n</ol>\n" }, { "answer_id": 32906229, "author": "Dan Moldovan", "author_id": 2725534, "author_profile": "https://Stackoverflow.com/users/2725534", "pm_score": 2, "selected": false, "text": "<p><strong>Enum singleton</strong></p>\n<p>The simplest way to implement a singleton that is thread-safe is using an Enum:</p>\n<pre><code>public enum SingletonEnum {\n INSTANCE;\n public void doSomething(){\n System.out.println(&quot;This is a singleton&quot;);\n }\n}\n</code></pre>\n<p>This code works since the introduction of Enum in Java 1.5</p>\n<p><strong>Double checked locking</strong></p>\n<p>If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.</p>\n<pre><code>public class Singleton {\n\n private static volatile Singleton instance = null;\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class){\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}\n</code></pre>\n<p>This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.</p>\n<p><strong>Early loading singleton (works even before Java 1.5)</strong></p>\n<p>This implementation instantiates the singleton when the class is loaded and provides thread safety.</p>\n<pre><code>public class Singleton {\n\n private static final Singleton instance = new Singleton();\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n return instance;\n }\n\n public void doSomething(){\n System.out.println(&quot;This is a singleton&quot;);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 37305099, "author": "Nicolas Filotto", "author_id": 1997376, "author_profile": "https://Stackoverflow.com/users/1997376", "pm_score": 2, "selected": false, "text": "<p>This is how to implement a simple <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a>:</p>\n<pre><code>public class Singleton {\n // It must be static and final to prevent later modification\n private static final Singleton INSTANCE = new Singleton();\n /** The constructor must be private to prevent external instantiation */\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is how to properly lazy create your singleton:</p>\n<pre><code>public class Singleton {\n // The constructor must be private to prevent external instantiation\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n /**\n * The static inner class responsible for creating your instance only on demand,\n * because the static fields of a class are only initialized when the class\n * is explicitly called and a class initialization is synchronized such that only\n * one thread can perform it, this rule is also applicable to inner static class\n * So here INSTANCE will be created only when SingletonHolder.INSTANCE\n * will be called\n */\n private static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n}\n</code></pre>\n" }, { "answer_id": 38942086, "author": "user3792852", "author_id": 3792852, "author_profile": "https://Stackoverflow.com/users/3792852", "pm_score": 2, "selected": false, "text": "<p>Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:</p>\n<pre><code>public class SingletonImpl {\n\n private static SingletonImpl instance;\n\n public static SingletonImpl getInstance() {\n if (instance == null) {\n instance = new SingletonImpl();\n }\n return instance;\n }\n\n public static void setInstance(SingletonImpl impl) {\n instance = impl;\n }\n\n public void a() {\n System.out.println(&quot;Default Method&quot;);\n }\n}\n</code></pre>\n<p>The added <code>setInstance</code> method allows setting a mockup implementation of the singleton class during testing:</p>\n<pre><code>public class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println(&quot;Mock Method&quot;);\n }\n\n}\n</code></pre>\n<p>This also works with early initialization approaches:</p>\n<pre><code>public class SingletonImpl {\n\n private static final SingletonImpl instance = new SingletonImpl();\n\n private static SingletonImpl alt;\n\n public static void setInstance(SingletonImpl inst) {\n alt = inst;\n }\n\n public static SingletonImpl getInstance() {\n if (alt != null) {\n return alt;\n }\n return instance;\n }\n\n public void a() {\n System.out.println(&quot;Default Method&quot;);\n }\n}\n\npublic class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println(&quot;Mock Method&quot;);\n }\n\n}\n</code></pre>\n<p>This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.</p>\n<p>Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.</p>\n" }, { "answer_id": 39098595, "author": "Dheeraj Sachan", "author_id": 3314058, "author_profile": "https://Stackoverflow.com/users/3314058", "pm_score": 3, "selected": false, "text": "<p>There are four ways to create a singleton in Java.</p>\n<ol>\n<li><p>Eager initialization singleton</p>\n<pre><code> public class Test {\n private static final Test test = new Test();\n\n private Test() {\n }\n\n public static Test getTest() {\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Lazy initialization singleton (thread safe)</p>\n<pre><code> public class Test {\n private static volatile Test test;\n\n private Test() {\n }\n\n public static Test getTest() {\n if(test == null) {\n synchronized(Test.class) {\n if(test == null) {\n test = new Test();\n }\n }\n }\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Bill Pugh singleton with holder pattern (preferably the best one)</p>\n<pre><code> public class Test {\n\n private Test() {\n }\n\n private static class TestHolder {\n private static final Test test = new Test();\n }\n\n public static Test getInstance() {\n return TestHolder.test;\n }\n }\n</code></pre>\n</li>\n<li><p>Enum singleton</p>\n<pre><code> public enum MySingleton {\n INSTANCE;\n\n private MySingleton() {\n System.out.println(&quot;Here&quot;);\n }\n }\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 45062746, "author": "Michael Andrews", "author_id": 1829927, "author_profile": "https://Stackoverflow.com/users/1829927", "pm_score": 4, "selected": false, "text": "<p>There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.</p>\n<hr />\n<p>The first attempt might look something like this:</p>\n<pre><code>public class MySingleton {\n\n private static MySingleton INSTANCE;\n\n public static MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n }\n ...\n}\n</code></pre>\n<p>Here we have the MySingleton class which has a private static member called <em>INSTANCE</em>, and a public static method called getInstance(). The first time getInstance() is called, the <em>INSTANCE</em> member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the <em>INSTANCE</em> variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().</p>\n<p>But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the <em>INSTANCE</em> member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the <em>INSTANCE</em> member.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static synchronized MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of <em>INSTANCE</em>. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronize(MySingleton.class) {\n INSTANCE = new MySingleton();\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the <em>INSTANCE</em> member as null.</p>\n<p>They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we issue another check from <em>inside</em> the block. If the <em>INSTANCE</em> member has already been set, we’ll skip initialization. This is called double-checked locking.</p>\n<p>This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the <em>INSTANCE</em> member has been updated. This is because of how Java optimizes memory operations.</p>\n<p>Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the <em>INSTANCE</em> member as null forcing a new instance of our singleton to be created.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>We solve this by using the <em>volatile</em> keyword on the declaration of the <em>INSTANCE</em> member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.</p>\n<p>But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile <em>INSTANCE</em> member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n MySingleton result = INSTANCE;\n if (result == null) {\n synchronized(MySingleton.class) {\n result = INSTANCE;\n if (result == null) {\n INSTANCE = result = createInstance();\n }\n }\n }\n return result;\n}\n</code></pre>\n<p>Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.</p>\n<p>I wrote an article about this recently. <a href=\"https://medium.com/@michael.andrews/deconstructing-the-singleton-b5f881f85f5\" rel=\"noreferrer\">Deconstructing The Singleton</a>. You can find more information on these examples and an example of the &quot;holder&quot; pattern there. There is also a real-world example showcasing the double-checked volatile approach.</p>\n" }, { "answer_id": 52265460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The best singleton pattern I've ever seen uses the Supplier interface.</p>\n\n<ul>\n<li>It's generic and reusable</li>\n<li>It supports lazy initialization</li>\n<li>It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>public class Singleton&lt;T&gt; implements Supplier&lt;T&gt; {\n\n private boolean initialized;\n private Supplier&lt;T&gt; singletonSupplier;\n\n public Singleton(T singletonValue) {\n this.singletonSupplier = () -&gt; singletonValue;\n }\n\n public Singleton(Supplier&lt;T&gt; supplier) {\n this.singletonSupplier = () -&gt; {\n // The initial supplier is temporary; it will be replaced after initialization\n synchronized (supplier) {\n if (!initialized) {\n T singletonValue = supplier.get();\n // Now that the singleton value has been initialized,\n // replace the blocking supplier with a non-blocking supplier\n singletonSupplier = () -&gt; singletonValue;\n initialized = true;\n }\n return singletonSupplier.get();\n }\n };\n }\n\n @Override\n public T get() {\n return singletonSupplier.get();\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11581/" ]
What is an efficient way to implement a singleton design pattern in Java?
Use an enum: ``` public enum Foo { INSTANCE; } ``` Joshua Bloch explained this approach in his [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded) talk at Google I/O 2008: [link to video](http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s). Also see slides 30-32 of his presentation ([effective\_java\_reloaded.pdf](https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0)): > > ### The Right Way to Implement a Serializable Singleton > > > > ``` > public enum Elvis { > INSTANCE; > private final String[] favoriteSongs = > { "Hound Dog", "Heartbreak Hotel" }; > public void printFavorites() { > System.out.println(Arrays.toString(favoriteSongs)); > } > } > > ``` > > **Edit:** An [online portion of "Effective Java"](http://www.ddj.com/java/208403883?pgno=3) says: > > "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, **a single-element enum type is the best way to implement a singleton**." > > >
70,694
<p>I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage.</p> <p>I created a task to run under my admin user, and to start the program, <em>cmd</em> with the arguments <em>/c net start mssqlserver</em>. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:</p> <p><em>action "C:\Windows\system32\cmd.EXE" with return code 2</em>.</p> <p>Any suggestions?</p>
[ { "answer_id": 70737, "author": "Neil Burroughs", "author_id": 5166, "author_profile": "https://Stackoverflow.com/users/5166", "pm_score": 6, "selected": false, "text": "<p>Make sure that you really need it. Do a google search for &quot;singleton anti-pattern&quot; to see some arguments against it.</p>\n<p>There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.</p>\n" }, { "answer_id": 70749, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 4, "selected": false, "text": "<p>Wikipedia has some <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"noreferrer\">examples</a> of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).</p>\n" }, { "answer_id": 70821, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.</p>\n<p>Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting &quot;global&quot; data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">inversion of control</a> (IoC) or <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) for a nice middle ground.</p>\n<p>If you really need one then Wikipedia has a good example of a proper implementation of a singleton.</p>\n" }, { "answer_id": 70824, "author": "Jonathan", "author_id": 1772, "author_profile": "https://Stackoverflow.com/users/1772", "pm_score": 7, "selected": false, "text": "<p>Forget <a href=\"https://en.wikipedia.org/wiki/Lazy_initialization\" rel=\"nofollow noreferrer\">lazy initialization</a>; it's too problematic. This is the simplest solution:</p>\n<pre><code>public class A { \n\n private static final A INSTANCE = new A();\n\n private A() {}\n\n public static A getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n" }, { "answer_id": 70829, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 4, "selected": false, "text": "<p>If you do not need lazy loading then simply try:</p>\n<pre><code>public class Singleton {\n private final static Singleton INSTANCE = new Singleton();\n\n private Singleton() {}\n\n public static Singleton getInstance() { return Singleton.INSTANCE; }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:</p>\n<pre><code>public class Singleton {\n private static Singleton instance = null;\n\n private Singleton() {}\n\n public static Singleton getInstance() {\n if(null == instance) {\n synchronized(Singleton.class) {\n if(null == instance) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.</p>\n" }, { "answer_id": 70835, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 7, "selected": false, "text": "<p>Thread safe in Java 5+:</p>\n<pre><code>class Foo {\n private static volatile Bar bar = null;\n public static Bar getBar() {\n if (bar == null) {\n synchronized(Foo.class) {\n if (bar == null)\n bar = new Bar();\n }\n }\n return bar;\n }\n}\n</code></pre>\n<hr />\n<p>Pay attention to the <code>volatile</code> modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization <em>does not</em> take care of that--it only serializes access to that block of code.</p>\n<p>@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.</p>\n" }, { "answer_id": 71399, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 11, "selected": true, "text": "<p>Use an enum:</p>\n\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n\n<p>Joshua Bloch explained this approach in his <a href=\"http://sites.google.com/site/io/effective-java-reloaded\" rel=\"noreferrer\">Effective Java Reloaded</a> talk at Google I/O 2008: <a href=\"http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s\" rel=\"noreferrer\">link to video</a>. Also see slides 30-32 of his presentation (<a href=\"https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&amp;attredirects=0\" rel=\"noreferrer\">effective_java_reloaded.pdf</a>):</p>\n\n<blockquote>\n <h3>The Right Way to Implement a Serializable Singleton</h3>\n\n<pre><code>public enum Elvis {\n INSTANCE;\n private final String[] favoriteSongs =\n { \"Hound Dog\", \"Heartbreak Hotel\" };\n public void printFavorites() {\n System.out.println(Arrays.toString(favoriteSongs));\n }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Edit:</strong> An <a href=\"http://www.ddj.com/java/208403883?pgno=3\" rel=\"noreferrer\">online portion of \"Effective Java\"</a> says: </p>\n\n<blockquote>\n <p>\"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>.\"</p>\n</blockquote>\n" }, { "answer_id": 71574, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 4, "selected": false, "text": "<p>I'm mystified by some of the answers that suggest <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.</p>\n<p>So my answer to the OP would be (in all but the most trivial sample code) to:</p>\n<ol>\n<li>Use a DI framework like <a href=\"https://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring Framework</a>, then</li>\n<li>Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.</li>\n</ol>\n<p>This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).</p>\n" }, { "answer_id": 71683, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 7, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/70835#70835\">The solution posted by Stu Thompson</a> is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.</p>\n<p>It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of <a href=\"http://jcip.net/\" rel=\"nofollow noreferrer\" title=\"Java Concurrency in Practice\">Java Concurrency in Practice</a>. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.</p>\n<p>This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.</p>\n<pre><code>class Bar {\n private static class BarHolder {\n public static Bar bar = new Bar();\n }\n\n public static Bar getBar() {\n return BarHolder.bar;\n }\n}\n</code></pre>\n" }, { "answer_id": 73763, "author": "Roel Spilker", "author_id": 12634, "author_profile": "https://Stackoverflow.com/users/12634", "pm_score": 8, "selected": false, "text": "<p>Depending on the usage, there are several &quot;correct&quot; answers.</p>\n<p>Since Java 5, the best way to do it is to use an enum:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Pre Java 5, the most simple case is:</p>\n<pre><code>public final class Foo {\n\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n\n public Object clone() throws CloneNotSupportedException{\n throw new CloneNotSupportedException(&quot;Cannot clone instance of this class&quot;);\n }\n}\n</code></pre>\n<p>Let's go over the code. First, you want the class to be final. In this case, I've used the <code>final</code> keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a <code>private static final Foo</code> field to hold the only instance, and a <code>public static Foo getInstance()</code> method to return it. The Java specification makes sure that the constructor is only called when the class is first used.</p>\n<p>When you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.</p>\n<p>You can use a <code>private static class</code> to load the instance. The code would then look like:</p>\n<pre><code>public final class Foo {\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>\n<p>When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n @SuppressWarnings(&quot;unused&quot;)\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.</p>\n" }, { "answer_id": 74905, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": -1, "selected": false, "text": "<p>Sometimes a simple \"<strong><code>static Foo foo = new Foo();</code></strong>\" is not enough. Just think of some basic data insertion you want to do.</p>\n\n<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>\n\n<pre><code>public class Singleton {\n\n private static Singleton instance = null;\n\n static {\n instance = new Singleton();\n // do some of your instantiation stuff here\n }\n\n private Singleton() {\n if(instance!=null) {\n throw new ErrorYouWant(\"Singleton double-instantiation, should never happen!\");\n }\n }\n\n public static getSingleton() {\n return instance;\n }\n\n}\n</code></pre>\n\n<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>\n" }, { "answer_id": 117516, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 4, "selected": false, "text": "<p>I use the <a href=\"https://en.wikipedia.org/wiki/Spring_Framework\" rel=\"nofollow noreferrer\">Spring Framework</a> to manage my singletons.</p>\n<p>It doesn't enforce the &quot;singleton-ness&quot; of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.</p>\n" }, { "answer_id": 6918352, "author": "Onur", "author_id": 776658, "author_profile": "https://Stackoverflow.com/users/776658", "pm_score": 2, "selected": false, "text": "<p>You need the <a href=\"http://en.wikipedia.org/wiki/Double-checked_locking\" rel=\"nofollow noreferrer\">double-checking</a> idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the <a href=\"http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom\" rel=\"nofollow noreferrer\">initialization on demand holder</a> idiom.</p>\n<p>In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.</p>\n<pre><code>public static final INSTANCE == ....\nprivate Object readResolve() {\n return INSTANCE; // Original singleton instance.\n} \n</code></pre>\n" }, { "answer_id": 14372745, "author": "NullPoiиteя", "author_id": 1723893, "author_profile": "https://Stackoverflow.com/users/1723893", "pm_score": 3, "selected": false, "text": "<p>I would say an enum singleton.</p>\n<p>Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity's sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.</p>\n<p>The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.</p>\n<pre><code>/**\n* Singleton pattern example using a Java Enum\n*/\npublic enum Singleton {\n INSTANCE;\n public void execute (String arg) {\n // Perform operation here\n }\n}\n</code></pre>\n<p>You can access it by <code>Singleton.INSTANCE</code>, and it is much easier than calling the <code>getInstance()</code> method on Singleton.</p>\n<blockquote>\n<p>1.12 Serialization of Enum Constants</p>\n<p>Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, <code>ObjectOutputStream</code> writes the value returned by the enum constant's name method. To deserialize an enum constant, <code>ObjectInputStream</code> reads the constant name from the stream; the deserialized constant is then obtained by calling the <code>java.lang.Enum.valueOf</code> method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.</p>\n<p>The process by which enum constants are serialized cannot be customized: any class-specific <code>writeObject</code>, <code>readObject</code>, <code>readObjectNoData</code>, <code>writeReplace</code>, and <code>readResolve</code> methods defined by enum types are ignored during serialization and deserialization. Similarly, any <code>serialPersistentFields</code> or <code>serialVersionUID</code> field declarations are also ignored--all enum types have a fixed <code>serialVersionUID</code> of <code>0L</code>. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.</p>\n<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum\" rel=\"nofollow noreferrer\">Quoted from Oracle documentation</a></p>\n</blockquote>\n<p>Another problem with conventional Singletons are that once you implement the <code>Serializable</code> interface, they no longer remain singleton because the <code>readObject()</code> method always return a new instance, like a constructor in Java. This can be avoided by using <code>readResolve()</code> and discarding the newly created instance by replacing with a singleton like below:</p>\n<pre><code> // readResolve to prevent another instance of Singleton\n private Object readResolve(){\n return INSTANCE;\n }\n</code></pre>\n<p>This can become even more complex if your <em>singleton class</em> maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.</p>\n<hr />\n<p><strong>Good Read</strong></p>\n<ol>\n<li><a href=\"http://www.oodesign.com/singleton-pattern.html\" rel=\"nofollow noreferrer\">Singleton Pattern</a></li>\n<li><a href=\"https://stackoverflow.com/questions/13219678/enums-singletons-and-deserialization\">Enums, Singletons and Deserialization</a></li>\n<li><a href=\"http://www.ibm.com/developerworks/java/library/j-dcl/index.html\" rel=\"nofollow noreferrer\">Double-checked locking and the Singleton pattern</a></li>\n</ol>\n" }, { "answer_id": 14917772, "author": "Abhijit Gaikwad", "author_id": 403872, "author_profile": "https://Stackoverflow.com/users/403872", "pm_score": 4, "selected": false, "text": "<p>Following are three different approaches</p>\n<ol>\n<li><p>Enum</p>\n<pre><code> /**\n * Singleton pattern example using Java Enum\n */\n public enum EasySingleton {\n INSTANCE;\n }\n</code></pre>\n</li>\n<li><p>Double checked locking / lazy loading</p>\n<pre><code> /**\n * Singleton pattern example with Double checked Locking\n */\n public class DoubleCheckedLockingSingleton {\n private static volatile DoubleCheckedLockingSingleton INSTANCE;\n\n private DoubleCheckedLockingSingleton() {}\n\n public static DoubleCheckedLockingSingleton getInstance() {\n if(INSTANCE == null) {\n synchronized(DoubleCheckedLockingSingleton.class) {\n // Double checking Singleton instance\n if(INSTANCE == null) {\n INSTANCE = new DoubleCheckedLockingSingleton();\n }\n }\n }\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n<li><p>Static factory method</p>\n<pre><code> /**\n * Singleton pattern example with static factory method\n */\n\n public class Singleton {\n // Initialized during class loading\n private static final Singleton INSTANCE = new Singleton();\n\n // To prevent creating another instance of 'Singleton'\n private Singleton() {}\n\n public static Singleton getSingleton() {\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 16580366, "author": "Ajinkya", "author_id": 705773, "author_profile": "https://Stackoverflow.com/users/705773", "pm_score": 7, "selected": false, "text": "<p><strong>Disclaimer:</strong> I have just summarized all of the awesome answers and wrote it in my own words.</p>\n<hr />\n<p>While implementing Singleton we have two options:</p>\n<ol>\n<li>Lazy loading</li>\n<li>Early loading</li>\n</ol>\n<p>Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.</p>\n<p>The most simple way of implementing a singleton is:</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>Everything is good except it's an early loaded singleton. Lets try lazy loaded singleton</p>\n<pre><code>class Foo {\n\n // Our now_null_but_going_to_be sole hero\n private static Foo INSTANCE = null;\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException(&quot;Already instantiated&quot;);\n }\n }\n\n public static Foo getInstance() {\n // Creating only when required.\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo let’s protect it from evil multi threading:</p>\n<pre><code>class Foo {\n\n private static Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n // No more tension of threads\n synchronized (Foo.class) {\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:</p>\n<pre><code>class Foo {\n\n // Pay attention to volatile\n private static volatile Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n if (INSTANCE == null) { // Check 1\n synchronized (Foo.class) {\n if (INSTANCE == null) { // Check 2\n INSTANCE = new Foo();\n }\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is called the &quot;double-checked locking idiom&quot;. It's easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details: <em><a href=\"http://www.cs.umd.edu/%7Epugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"noreferrer\">The &quot;Double-Checked Locking is Broken&quot; Declaration</a></em></p>\n<p>Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:</p>\n<pre><code>class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static volatile Foo INSTANCE = null;\n\n // The rest of the things are same as above\n\n // No more fear of serialization\n @SuppressWarnings(&quot;unused&quot;)\n private Object readResolve() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.</p>\n<p>Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n // Wrapped in a inner static class so that loaded only when required\n private static class FooLoader {\n\n // And no more fear of threads\n private static final Foo INSTANCE = new Foo();\n }\n\n // TODO add private shouting construcor\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n // Damn you serialization\n @SuppressWarnings(&quot;unused&quot;)\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Yes, this is our very same hero :)</p>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class <code>FooLoader</code> is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.</p>\n<p>And we have come so far. Here is the best way to achieve everything we did is best possible way:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Which internally will be treated like</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n}\n</code></pre>\n<p>That's it! No more fear of serialization, threads and ugly code. Also <a href=\"https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized\"><strong>ENUMS singleton are lazily initialized</strong></a>.</p>\n<blockquote>\n<p>This approach is functionally equivalent to the public field approach,\nexcept that it is more concise, provides the serialization machinery\nfor free, and provides an ironclad guarantee against multiple\ninstantiation, even in the face of sophisticated serialization or\nreflection attacks. While this approach has yet to be widely adopted,\na single-element enum type is the best way to implement a singleton.</p>\n</blockquote>\n<p>-Joshua Bloch in &quot;Effective Java&quot;</p>\n<p>Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)</p>\n<p>Updated it on my <a href=\"http://ajinkyaparakh.blogspot.in/2013/05/implementing-singleton-in-java.html\" rel=\"noreferrer\"><strong>blog</strong></a>.</p>\n" }, { "answer_id": 16699497, "author": "raoadnan", "author_id": 2392052, "author_profile": "https://Stackoverflow.com/users/2392052", "pm_score": 2, "selected": false, "text": "<p>For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).</p>\n" }, { "answer_id": 19562324, "author": "rohan kamat", "author_id": 2335562, "author_profile": "https://Stackoverflow.com/users/2335562", "pm_score": 1, "selected": false, "text": "<p>Simplest singleton class:</p>\n<pre><code>public class Singleton {\n private static Singleton singleInstance = new Singleton();\n private Singleton() {}\n public static Singleton getSingleInstance() {\n return singleInstance;\n }\n}\n</code></pre>\n" }, { "answer_id": 19849576, "author": "somenath mukhopadhyay", "author_id": 873952, "author_profile": "https://Stackoverflow.com/users/873952", "pm_score": -1, "selected": false, "text": "<pre><code>public class Singleton {\n\n private static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n if (INSTANCE != null)\n throw new IllegalStateException(“Already instantiated...”);\n }\n\n\n public synchronized static Singleton getInstance() {\n return INSTANCE;\n }\n\n}\n</code></pre>\n<p>As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.</p>\n" }, { "answer_id": 27793921, "author": "shikjohari", "author_id": 2595642, "author_profile": "https://Stackoverflow.com/users/2595642", "pm_score": 0, "selected": false, "text": "<p>I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.</p>\n<pre><code>public enum Singleton {\n INSTANCE;\n}\n</code></pre>\n<p>And you are done!</p>\n" }, { "answer_id": 29389322, "author": "coderz", "author_id": 3275167, "author_profile": "https://Stackoverflow.com/users/3275167", "pm_score": 4, "selected": false, "text": "<p><strong>Version 1:</strong></p>\n\n<pre><code>public class MySingleton {\n private static MySingleton instance = null;\n private MySingleton() {}\n public static synchronized MySingleton getInstance() {\n if(instance == null) {\n instance = new MySingleton();\n }\n return instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with blocking, low performance because of <code>synchronized</code>.</p>\n\n<p><strong>Version 2:</strong></p>\n\n<pre><code>public class MySingleton {\n private MySingleton() {}\n private static class MySingletonHolder {\n public final static MySingleton instance = new MySingleton();\n }\n public static MySingleton getInstance() {\n return MySingletonHolder.instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with non-blocking, high performance.</p>\n" }, { "answer_id": 32130663, "author": "kenju", "author_id": 2775013, "author_profile": "https://Stackoverflow.com/users/2775013", "pm_score": 0, "selected": false, "text": "<p>Have a look at this post.</p>\n<p><a href=\"https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries\">Examples of GoF Design Patterns in Java&#39;s core libraries</a></p>\n<p>From the best answer's &quot;Singleton&quot; section,</p>\n<blockquote>\n<h3>Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)</h3>\n<ul>\n<li>java.lang.Runtime#getRuntime()</li>\n<li>java.awt.Desktop#getDesktop()</li>\n<li>java.lang.System#getSecurityManager()</li>\n</ul>\n</blockquote>\n<p>You can also learn the example of Singleton from Java native classes themselves.</p>\n" }, { "answer_id": 32286179, "author": "Shailendra Singh", "author_id": 2550410, "author_profile": "https://Stackoverflow.com/users/2550410", "pm_score": 2, "selected": false, "text": "<p>Various ways to make a singleton object:</p>\n<ol>\n<li><p>As per <a href=\"https://en.wikipedia.org/wiki/Joshua_Bloch\" rel=\"nofollow noreferrer\">Joshua Bloch</a> - Enum would be the best.</p>\n</li>\n<li><p>You can use double check locking also.</p>\n</li>\n<li><p>Even an inner static class can be used.</p>\n</li>\n</ol>\n" }, { "answer_id": 32906229, "author": "Dan Moldovan", "author_id": 2725534, "author_profile": "https://Stackoverflow.com/users/2725534", "pm_score": 2, "selected": false, "text": "<p><strong>Enum singleton</strong></p>\n<p>The simplest way to implement a singleton that is thread-safe is using an Enum:</p>\n<pre><code>public enum SingletonEnum {\n INSTANCE;\n public void doSomething(){\n System.out.println(&quot;This is a singleton&quot;);\n }\n}\n</code></pre>\n<p>This code works since the introduction of Enum in Java 1.5</p>\n<p><strong>Double checked locking</strong></p>\n<p>If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.</p>\n<pre><code>public class Singleton {\n\n private static volatile Singleton instance = null;\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class){\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}\n</code></pre>\n<p>This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.</p>\n<p><strong>Early loading singleton (works even before Java 1.5)</strong></p>\n<p>This implementation instantiates the singleton when the class is loaded and provides thread safety.</p>\n<pre><code>public class Singleton {\n\n private static final Singleton instance = new Singleton();\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n return instance;\n }\n\n public void doSomething(){\n System.out.println(&quot;This is a singleton&quot;);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 37305099, "author": "Nicolas Filotto", "author_id": 1997376, "author_profile": "https://Stackoverflow.com/users/1997376", "pm_score": 2, "selected": false, "text": "<p>This is how to implement a simple <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a>:</p>\n<pre><code>public class Singleton {\n // It must be static and final to prevent later modification\n private static final Singleton INSTANCE = new Singleton();\n /** The constructor must be private to prevent external instantiation */\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is how to properly lazy create your singleton:</p>\n<pre><code>public class Singleton {\n // The constructor must be private to prevent external instantiation\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n /**\n * The static inner class responsible for creating your instance only on demand,\n * because the static fields of a class are only initialized when the class\n * is explicitly called and a class initialization is synchronized such that only\n * one thread can perform it, this rule is also applicable to inner static class\n * So here INSTANCE will be created only when SingletonHolder.INSTANCE\n * will be called\n */\n private static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n}\n</code></pre>\n" }, { "answer_id": 38942086, "author": "user3792852", "author_id": 3792852, "author_profile": "https://Stackoverflow.com/users/3792852", "pm_score": 2, "selected": false, "text": "<p>Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:</p>\n<pre><code>public class SingletonImpl {\n\n private static SingletonImpl instance;\n\n public static SingletonImpl getInstance() {\n if (instance == null) {\n instance = new SingletonImpl();\n }\n return instance;\n }\n\n public static void setInstance(SingletonImpl impl) {\n instance = impl;\n }\n\n public void a() {\n System.out.println(&quot;Default Method&quot;);\n }\n}\n</code></pre>\n<p>The added <code>setInstance</code> method allows setting a mockup implementation of the singleton class during testing:</p>\n<pre><code>public class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println(&quot;Mock Method&quot;);\n }\n\n}\n</code></pre>\n<p>This also works with early initialization approaches:</p>\n<pre><code>public class SingletonImpl {\n\n private static final SingletonImpl instance = new SingletonImpl();\n\n private static SingletonImpl alt;\n\n public static void setInstance(SingletonImpl inst) {\n alt = inst;\n }\n\n public static SingletonImpl getInstance() {\n if (alt != null) {\n return alt;\n }\n return instance;\n }\n\n public void a() {\n System.out.println(&quot;Default Method&quot;);\n }\n}\n\npublic class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println(&quot;Mock Method&quot;);\n }\n\n}\n</code></pre>\n<p>This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.</p>\n<p>Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.</p>\n" }, { "answer_id": 39098595, "author": "Dheeraj Sachan", "author_id": 3314058, "author_profile": "https://Stackoverflow.com/users/3314058", "pm_score": 3, "selected": false, "text": "<p>There are four ways to create a singleton in Java.</p>\n<ol>\n<li><p>Eager initialization singleton</p>\n<pre><code> public class Test {\n private static final Test test = new Test();\n\n private Test() {\n }\n\n public static Test getTest() {\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Lazy initialization singleton (thread safe)</p>\n<pre><code> public class Test {\n private static volatile Test test;\n\n private Test() {\n }\n\n public static Test getTest() {\n if(test == null) {\n synchronized(Test.class) {\n if(test == null) {\n test = new Test();\n }\n }\n }\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Bill Pugh singleton with holder pattern (preferably the best one)</p>\n<pre><code> public class Test {\n\n private Test() {\n }\n\n private static class TestHolder {\n private static final Test test = new Test();\n }\n\n public static Test getInstance() {\n return TestHolder.test;\n }\n }\n</code></pre>\n</li>\n<li><p>Enum singleton</p>\n<pre><code> public enum MySingleton {\n INSTANCE;\n\n private MySingleton() {\n System.out.println(&quot;Here&quot;);\n }\n }\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 45062746, "author": "Michael Andrews", "author_id": 1829927, "author_profile": "https://Stackoverflow.com/users/1829927", "pm_score": 4, "selected": false, "text": "<p>There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.</p>\n<hr />\n<p>The first attempt might look something like this:</p>\n<pre><code>public class MySingleton {\n\n private static MySingleton INSTANCE;\n\n public static MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n }\n ...\n}\n</code></pre>\n<p>Here we have the MySingleton class which has a private static member called <em>INSTANCE</em>, and a public static method called getInstance(). The first time getInstance() is called, the <em>INSTANCE</em> member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the <em>INSTANCE</em> variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().</p>\n<p>But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the <em>INSTANCE</em> member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the <em>INSTANCE</em> member.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static synchronized MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of <em>INSTANCE</em>. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronize(MySingleton.class) {\n INSTANCE = new MySingleton();\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the <em>INSTANCE</em> member as null.</p>\n<p>They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we issue another check from <em>inside</em> the block. If the <em>INSTANCE</em> member has already been set, we’ll skip initialization. This is called double-checked locking.</p>\n<p>This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the <em>INSTANCE</em> member has been updated. This is because of how Java optimizes memory operations.</p>\n<p>Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the <em>INSTANCE</em> member as null forcing a new instance of our singleton to be created.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>We solve this by using the <em>volatile</em> keyword on the declaration of the <em>INSTANCE</em> member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.</p>\n<p>But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile <em>INSTANCE</em> member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n MySingleton result = INSTANCE;\n if (result == null) {\n synchronized(MySingleton.class) {\n result = INSTANCE;\n if (result == null) {\n INSTANCE = result = createInstance();\n }\n }\n }\n return result;\n}\n</code></pre>\n<p>Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.</p>\n<p>I wrote an article about this recently. <a href=\"https://medium.com/@michael.andrews/deconstructing-the-singleton-b5f881f85f5\" rel=\"noreferrer\">Deconstructing The Singleton</a>. You can find more information on these examples and an example of the &quot;holder&quot; pattern there. There is also a real-world example showcasing the double-checked volatile approach.</p>\n" }, { "answer_id": 52265460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The best singleton pattern I've ever seen uses the Supplier interface.</p>\n\n<ul>\n<li>It's generic and reusable</li>\n<li>It supports lazy initialization</li>\n<li>It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>public class Singleton&lt;T&gt; implements Supplier&lt;T&gt; {\n\n private boolean initialized;\n private Supplier&lt;T&gt; singletonSupplier;\n\n public Singleton(T singletonValue) {\n this.singletonSupplier = () -&gt; singletonValue;\n }\n\n public Singleton(Supplier&lt;T&gt; supplier) {\n this.singletonSupplier = () -&gt; {\n // The initial supplier is temporary; it will be replaced after initialization\n synchronized (supplier) {\n if (!initialized) {\n T singletonValue = supplier.get();\n // Now that the singleton value has been initialized,\n // replace the blocking supplier with a non-blocking supplier\n singletonSupplier = () -&gt; singletonValue;\n initialized = true;\n }\n return singletonSupplier.get();\n }\n };\n }\n\n @Override\n public T get() {\n return singletonSupplier.get();\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage. I created a task to run under my admin user, and to start the program, *cmd* with the arguments */c net start mssqlserver*. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped: *action "C:\Windows\system32\cmd.EXE" with return code 2*. Any suggestions?
Use an enum: ``` public enum Foo { INSTANCE; } ``` Joshua Bloch explained this approach in his [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded) talk at Google I/O 2008: [link to video](http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s). Also see slides 30-32 of his presentation ([effective\_java\_reloaded.pdf](https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0)): > > ### The Right Way to Implement a Serializable Singleton > > > > ``` > public enum Elvis { > INSTANCE; > private final String[] favoriteSongs = > { "Hound Dog", "Heartbreak Hotel" }; > public void printFavorites() { > System.out.println(Arrays.toString(favoriteSongs)); > } > } > > ``` > > **Edit:** An [online portion of "Effective Java"](http://www.ddj.com/java/208403883?pgno=3) says: > > "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, **a single-element enum type is the best way to implement a singleton**." > > >
70,732
<p>Lasty, I tried to implements an hybrid structure in Java, something that looks like:</p> <pre><code>public class MapOfSet&lt;K, V extends HasKey&lt;K&gt;&gt; implements Set&lt;V&gt;, Map&lt;K, Set&lt;V&gt;&gt; </code></pre> <p>Where HasKey is the following interface:</p> <pre><code>public interface HasKey&lt;K&gt; { public K getKey(); } </code></pre> <p>Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.</p> <p>Do you see a nicer solution?</p> <p>In response to the first comments, here is my goal:</p> <blockquote> <p>Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value. At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.</p> </blockquote>
[ { "answer_id": 70760, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 0, "selected": false, "text": "<p>I would say that something that is meant to be sometimes used as a Map and sometimes as a Set should implement Map, since that can be viewed as a set of keys or values as well as a mapping between keys and values. That is what the Map.containsKey() and Map.containsValue() methods are for.</p>\n" }, { "answer_id": 70772, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>What are you trying to accomplish? <code>Map</code> already exposes its keys as a <code>Set</code> via its [keySet()](<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())</a> method. If you want a reliable iteratior order, there's <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html\" rel=\"nofollow noreferrer\">LinkedHashMap</a> and <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\">TreeMap</a>.</p>\n\n<p>UPDATE: If you want to ensure that a value has only been inserted once, you can extend one of the classes I mentioned above to create something like a <code>SingleEntryMap</code> and override the implementation of <code>put(K key, V value)</code> to do a uniqueness check and throw an Exception when the value has already been inserted.</p>\n\n<p>UPDATE: Will something like this work? (I don't have my editor up, so this may not compile)</p>\n\n<pre><code>public final class KeyedSets&lt;K, V&gt; implements Map&lt;K,Set&lt;V&gt;&gt; {\n private final Map&lt;K, Set&lt;V&gt;&gt; internalMap = new TreeMap&lt;K, Set&lt;V&gt;&gt;;\n // delegate methods go here\n public Set&lt;V&gt; getSortedSuperset() {\n final Set&lt;V&gt; superset = new TreeSet&lt;V&gt;();\n for (final Map.Entry&lt;K, V&gt; entry : internalMap.entrySet()) {\n superset.addAll(entry.getValue());\n }\n return superset;\n }\n}\n</code></pre>\n" }, { "answer_id": 70962, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 2, "selected": true, "text": "<p>Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that:</p>\n\n<pre><code>public interface GroupedSet&lt;K, V extends HasKey&lt;K&gt;&gt; extends Set&lt;V&gt;{\n Set&lt;V&gt; havingKey(K k);\n}\n</code></pre>\n\n<p>If you want to be able to use the Set as map you can add another method</p>\n\n<pre><code>Map&lt;K,Set&lt;V&gt;&gt; asMap();\n</code></pre>\n\n<p>That avoids the use of multiple interface inheritance and the resulting problems.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730/" ]
Lasty, I tried to implements an hybrid structure in Java, something that looks like: ``` public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>> ``` Where HasKey is the following interface: ``` public interface HasKey<K> { public K getKey(); } ``` Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface. Do you see a nicer solution? In response to the first comments, here is my goal: > > Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value. > At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances. > > >
Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that: ``` public interface GroupedSet<K, V extends HasKey<K>> extends Set<V>{ Set<V> havingKey(K k); } ``` If you want to be able to use the Set as map you can add another method ``` Map<K,Set<V>> asMap(); ``` That avoids the use of multiple interface inheritance and the resulting problems.
70,758
<p>I know you can put &lt;% if %> statements in the ItemTemplate to hide controls but the column is still there. You cannot put &lt;% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem. Does anyone know of a better way?</p>
[ { "answer_id": 70955, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 0, "selected": false, "text": "<p>You can always set the column width to 0 (zero) if you don't find a better way.</p>\n" }, { "answer_id": 71015, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 0, "selected": false, "text": "<p>The listview doesn't really have a concept of 'column' since it is intended just to be, well, a list.</p>\n\n<p>I'm going to assume that you are using databinding to attach a list of 'somethings' to the ListView. If that is the case then you will just have a list of items and the html in the LayoutTemplate will decide on just how those items are displayed. If you are then talking about creating a table-style array of columns and rows then maybe a DataGrid would be a better choice since this gives much more programmatic control of specific columns.</p>\n\n<p>It may be that you are hoping to create the table layout entirely through CSS, which is an admirable decision <strong>if</strong> it is purely for layout purposes. However, your requirement to specifically hide one column indicates to me that a table is better placed to suit your needs. It's fine to use tables for tabular data...IMHO...</p>\n\n<p>If you really do need to use a ListView then you could always try binding against something in your data which determines whether an element should be shown or not, e.g.:</p>\n\n<pre><code>style='display: &lt;%#Eval(\"DisplayStyle\") %&gt;;'\n</code></pre>\n\n<p>Place this code within the html element that you want to control (in the LayoutTemplate). Then in the object you are binding to you would need a property 'DisplayStyle' which was either set to 'block' or 'none'.</p>\n" }, { "answer_id": 71261, "author": "Dean Poulin", "author_id": 5462, "author_profile": "https://Stackoverflow.com/users/5462", "pm_score": 1, "selected": false, "text": "<p>The ListView gives you full control about how the data is rendered to the client. You specify the Layout Template, and give a placeholder which will be where each item is injected.</p>\n\n<p>The output of the below will give you a table, and each item will be a new TR.</p>\n\n<p>Notice the use of runat='server' and <code>visible ='&lt;%# %&gt;'</code></p>\n\n<pre><code>&lt;asp:ListView ID=\"ListView1\" runat=\"server\" DataSourceID=\"MyDataSource\" ItemPlaceholderID=\"itemPlaceHolder\"&gt;\n &lt;LayoutTemplate&gt;\n &lt;table&gt;\n &lt;asp:PlaceHolder ID=\"itemPlaceHolder\" runat=\"server\" /&gt;\n &lt;/table&gt;\n &lt;/LayoutTemplate&gt;\n &lt;ItemTemplate&gt;\n &lt;tr&gt;\n &lt;td runat=\"server\" id=\"myCol\" visible='&lt;%# (bool)Eval(\"IsSuperCool\") %&gt;'&gt;\n &lt;%# Eval(\"SuperCoolIcon\") %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%# Eval(\"Name\") %&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;%# Eval(\"Age\") %&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:ListView&gt;\n</code></pre>\n" }, { "answer_id": 76264, "author": "Dean Poulin", "author_id": 5462, "author_profile": "https://Stackoverflow.com/users/5462", "pm_score": 5, "selected": true, "text": "<p>Here's another solution that I just did, seeing that I understand what you want to do:</p>\n\n<p><strong>Here's your ASCX / ASPX</strong></p>\n\n<pre><code> &lt;asp:ListView ID=\"ListView1\" runat=\"server\" DataSourceID=\"MyDataSource\" ItemPlaceholderID=\"itemPlaceHolder\" OnDataBound=\"ListView1_DataBound\"&gt;\n &lt;LayoutTemplate&gt;\n &lt;table border=\"1\"&gt;\n &lt;tr&gt;\n &lt;td&gt;Name&lt;/td&gt;\n &lt;td&gt;Age&lt;/td&gt;\n &lt;td runat=\"server\" id=\"tdIsSuperCool\"&gt;IsSuperCool&lt;/td&gt;\n &lt;/tr&gt;\n &lt;asp:PlaceHolder ID=\"itemPlaceHolder\" runat=\"server\" /&gt;\n &lt;/table&gt;\n &lt;/LayoutTemplate&gt;\n &lt;ItemTemplate&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;%# Eval(\"Name\") %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%# Eval(\"Age\") %&gt;&lt;/td&gt;\n &lt;td runat=\"server\" id=\"myCol\" visible='&lt;%# (bool)Eval(\"IsSuperCool\") %&gt;'&gt;true&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:ListView&gt;\n &lt;asp:ObjectDataSource \n ID=\"MyDataSource\" \n runat=\"server\" \n DataObjectTypeName=\"BusinessLogicLayer.Thing\" \n SelectMethod=\"SelectThings\"\n TypeName=\"BusinessLogicLayer.MyObjectDataSource\" /&gt;\n</code></pre>\n\n<p><strong>Here's the code behind</strong></p>\n\n<pre><code>/// &lt;summary&gt;\n/// Handles the DataBound event of the ListView1 control.\n/// &lt;/summary&gt;\n/// &lt;param name=\"sender\"&gt;The source of the event.&lt;/param&gt;\n/// &lt;param name=\"e\"&gt;The &lt;see cref=\"System.EventArgs\"/&gt; instance containing the event data.&lt;/param&gt;\nprotected void ListView1_DataBound(object sender, EventArgs e)\n{\n ListView1.FindControl(\"tdIsSuperCool\").Visible = false;\n}\n</code></pre>\n\n<p>Do whatever you want in the databound. Because the column is now runat server, and you're handling the DataBound of the control, when you do ListView1.FindControl(\"tdIsSuperCool\") you're in the Layout template so that works like a champ.</p>\n\n<p>Put whatever business logic that you want to control the visibility of the td and you're good.</p>\n" }, { "answer_id": 118758, "author": "Fred", "author_id": 9012, "author_profile": "https://Stackoverflow.com/users/9012", "pm_score": 2, "selected": false, "text": "<p>Try Using a Panel and you can turn it on / Off</p>\n\n<pre><code> foreach (ListViewItem item in ListView1.Items)\n {\n ((Panel)item.FindControl(\"myPanel\")).Visible= False;\n }\n</code></pre>\n" }, { "answer_id": 5425699, "author": "yaktipper", "author_id": 675730, "author_profile": "https://Stackoverflow.com/users/675730", "pm_score": 0, "selected": false, "text": "<p>To access the layout template column header text, I made them labels in the template, and did a findcontrol in the prerender of the listview, then made the labels blank text if the column should be \"off\". This might not work for your intentions, but for me I still wanted the column space to be used, just appear blank.</p>\n\n<p>The further you go try to make a listview bend over backwards, the more you will wish you used a grid instead.</p>\n" }, { "answer_id": 41151941, "author": "jason", "author_id": 1709186, "author_profile": "https://Stackoverflow.com/users/1709186", "pm_score": 1, "selected": false, "text": "<p>I know it's a very old question, but I'm actually having to do this and think I found a fairly nice way to do it through jquery and css.</p>\n\n<p>Add the following to the header:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"Scripts/jquery-1.7.1.min.js\" &gt;&lt;/script&gt;\n &lt;style&gt;\n .hide {\n display:none;\n }\n .show {\n display:block;\n }\n &lt;/style&gt;\n</code></pre>\n\n<p>For all columns that you want to hide, add a custom property to the td/th.</p>\n\n<pre><code>&lt;th runat=\"server\" data-prop='authcheck' id=\"tdcommentsHeader\" &gt;Comments&lt;/th&gt;\n</code></pre>\n\n<p>I'm advising to use a custom property because, long story short, it can kill a bunch of birds with one stone. You won't even need to change the value for each column, as you would if we based this on the id property.</p>\n\n<p>Next, ensure you have a hidden field that tells lets you know whether or not to hide the column. This can be an asp:HiddenField or any other so long as it's on the form.</p>\n\n<pre><code>&lt;asp:HiddenField runat=\"server\" ID=\"IsAuthorized\" Value=\"false\" /&gt;\n</code></pre>\n\n<p>Finally, at the bottom of the page, do:</p>\n\n<pre><code> &lt;script type=\"text/javascript\"&gt;\n $(document).ready(function () {\n var isauth = $(\"[id='IsAuthorized']\").val();\n if (isauth===\"false\") {\n $(\"[data-prop='authcheck']\").addClass('hide');\n //$(\"[id*='tdcomments']\").addClass('hide'); \n }\n });\n &lt;/script&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10186/" ]
I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there. You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem. Does anyone know of a better way?
Here's another solution that I just did, seeing that I understand what you want to do: **Here's your ASCX / ASPX** ``` <asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder" OnDataBound="ListView1_DataBound"> <LayoutTemplate> <table border="1"> <tr> <td>Name</td> <td>Age</td> <td runat="server" id="tdIsSuperCool">IsSuperCool</td> </tr> <asp:PlaceHolder ID="itemPlaceHolder" runat="server" /> </table> </LayoutTemplate> <ItemTemplate> <tr> <td><%# Eval("Name") %></td> <td><%# Eval("Age") %></td> <td runat="server" id="myCol" visible='<%# (bool)Eval("IsSuperCool") %>'>true</td> </tr> </ItemTemplate> </asp:ListView> <asp:ObjectDataSource ID="MyDataSource" runat="server" DataObjectTypeName="BusinessLogicLayer.Thing" SelectMethod="SelectThings" TypeName="BusinessLogicLayer.MyObjectDataSource" /> ``` **Here's the code behind** ``` /// <summary> /// Handles the DataBound event of the ListView1 control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void ListView1_DataBound(object sender, EventArgs e) { ListView1.FindControl("tdIsSuperCool").Visible = false; } ``` Do whatever you want in the databound. Because the column is now runat server, and you're handling the DataBound of the control, when you do ListView1.FindControl("tdIsSuperCool") you're in the Layout template so that works like a champ. Put whatever business logic that you want to control the visibility of the td and you're good.
70,773
<p>What are the pros / cons of using <code>pthread_cond_wait</code> or using a semaphore ? I am waiting for a state change like this :</p> <pre><code>pthread_mutex_lock(&amp;cam-&gt;video_lock); while(cam-&gt;status == WAIT_DISPLAY) { pthread_cond_wait(&amp;cam-&gt;video_cond, &amp;cam-&gt;video_lock); } pthread_mutex_unlock(&amp;cam-&gt;video_lock); </code></pre> <p>Using a properly initialised semaphore, I think I could do it like this :</p> <pre><code>while(cam-&gt;status == WAIT_DISPLAY) { sem_wait(&amp;some_semaphore); } </code></pre> <p>What are the pros and cons of each method ?</p>
[ { "answer_id": 70924, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>In your second snippet, you're getting the lock multitude of times, never releasing it.</p>\n\n<p>In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that. A lock structure is smaller in size, and it requires less atomic operations to check/set/release.</p>\n\n<p>Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x&lt;10; there you want y>x), use cond_wait.</p>\n" }, { "answer_id": 71301, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 4, "selected": false, "text": "<p>Conditionals let you do some things that semaphores won't.</p>\n\n<p>For example, suppose you have some code which requires a mutex, called <code>m</code>. It however needs to wait until some other thread has finish their task, so it waits on a semaphore called <code>s</code>. Now any thread which needs <code>m</code> is blocked from running, even though the thread which has <code>m</code> is waiting on <code>s</code>. These kind of situations can be resolved using conditionals. When you wait on a conditional, the mutex currently held is released, so other threads can acquire the mutex. So back to our example, and suppose conditional <code>c</code> was used instead of <code>s</code>. Our thread now acquires <code>m</code>, and then conditional waits on <code>c</code>. This releases <code>m</code> so other threads can proceed. When <code>c</code> becomes available, <code>m</code> is reacquired, and our original thread can continue merrily along its way.</p>\n\n<p>Conditional variables also allows you to let <em>all</em> threads waiting on a conditional variable to proceed via <code>pthread_cond_broadcast</code>. Additionally it also allows you to perform a <em>timed wait</em> so you don't end up waiting forever.</p>\n\n<p>Of course, sometimes you don't need conditional variables, so depending on your requirements, one or the other may be better. </p>\n" }, { "answer_id": 108918, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 7, "selected": true, "text": "<p>A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore.</p>\n\n<p>A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never).</p>\n\n<p>So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again.</p>\n\n<p>It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions.</p>\n\n<p>Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns.</p>\n\n<p>IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.</p>\n" }, { "answer_id": 434872, "author": "Blaisorblade", "author_id": 53974, "author_profile": "https://Stackoverflow.com/users/53974", "pm_score": 3, "selected": false, "text": "<p>The 2nd snippet is racy, don't do that.</p>\n\n<p>The other answers have a nice discussion of the relative merits; I'll just add that <code>pthread_cond_broadcast</code> is a clear advantage of condition variables.</p>\n\n<p>Beyond that, I'm just more used to condition variables for that, as they are what you use in Java, even because they help you to avoid races when checking the shared flags.</p>\n\n<p>Indeed, in the 2nd snippet you don't have any lock protecting the read of cam->status, so it is accessed through a data race. Most platforms will let you get away with that in this particular example, but that has undefined semantics, by POSIX and by the memory model of the next C/C++ standards.</p>\n\n<p>In fact, a real race condition is possible if another thread allocates a new cam structure and overwrites cam; the waiting thread might see the update to the 'cam' pointer without seeing the initialization of cam->status. Indeed, the 2nd snippet is asking for trouble, in this case and in general.</p>\n\n<p><a href=\"http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/\" rel=\"noreferrer\">http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/</a></p>\n" }, { "answer_id": 71291384, "author": "Abhishek Sagar", "author_id": 756120, "author_profile": "https://Stackoverflow.com/users/756120", "pm_score": 0, "selected": false, "text": "<pre><code>while(cam-&gt;status == WAIT_DISPLAY) {\n sem_wait(&amp;some_semaphore);\n}\n</code></pre>\n<p>This is completely wrong. This is prone to race condition. By the time the thread blocks on sem_Wait, the condition cam-&gt;status == WAIT_DISPLAY may not hold good in the system as some other thread may have modified it. So, your thread is now sleeping for all wrong reasons.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
What are the pros / cons of using `pthread_cond_wait` or using a semaphore ? I am waiting for a state change like this : ``` pthread_mutex_lock(&cam->video_lock); while(cam->status == WAIT_DISPLAY) { pthread_cond_wait(&cam->video_cond, &cam->video_lock); } pthread_mutex_unlock(&cam->video_lock); ``` Using a properly initialised semaphore, I think I could do it like this : ``` while(cam->status == WAIT_DISPLAY) { sem_wait(&some_semaphore); } ``` What are the pros and cons of each method ?
A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore. A condition variable is a bit more forgiving in some respects. You can for example use cond\_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond\_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never). So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again. It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions. Condition variables escape this problem, because calling cond\_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond\_wait returns. IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.
70,779
<p>I need to be able to quickly convert an image (inside a rails controller) so that the hosting company using managing our application can quickly test at any time to ensure that rmagick is not only successfully installed, but can be called throgh the rails stiack, what is the quickest clean code I can use to do this?</p>
[ { "answer_id": 70932, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 0, "selected": false, "text": "<p>I'd log on to the server and try out your code in script/console. This will still go through the rails stack, but will allow you to quickly check that your code works the way you expect and that RMagick and ImageMagick are correctly installed without having to deploy anything.</p>\n\n<p>When the time comes to write your actual code, I'd suggest putting the image conversion code inside a model, so you can call it outside the context of a controller.</p>\n" }, { "answer_id": 70952, "author": "Asaf Bartov", "author_id": 7483, "author_profile": "https://Stackoverflow.com/users/7483", "pm_score": 0, "selected": false, "text": "<p>Use script/console, and call code in a model or a controller that does something like the following:</p>\n\n<pre><code>require 'RMagick'\ninclude Magick\nimg = ImageList.new('myfile.jpg')\nimg.crop(0,0,10,10) # or whatever\nimg.write('mycroppedfile.jpg')\n</code></pre>\n" }, { "answer_id": 71527, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 3, "selected": true, "text": "<p>I wanted to do this so that I can easily hit it with a web browser, as I'm deployng to managed servers, which I do not have shell access onto (for increased security).</p>\n\n<p>So this is what I did</p>\n\n<pre><code>class DiagnosticsController &lt; ApplicationController\n require 'RMagick'\n\n def rmagick\n images_path = \"public/images\"\n file_name = \"rmagick_generated_thumb.jpg\"\n file_path = images_path + \"/\"+ file_name\n\n File.delete file_path if File.exists? file_path\n img = Magick::Image.read(\"lib/sample_images/magic.jpg\").first\n thumb = img.scale(0.25)\n @path = file_name\n thumb.write file_path\n end\nend #------\n</code></pre>\n\n<p>and then in rmagick.html.erb</p>\n\n<pre><code>&lt;%= image_tag @path %&gt;\n</code></pre>\n\n<p>Now I can hit the controller, and if I see an image, I know rmagic is installed.</p>\n" }, { "answer_id": 72582, "author": "Scott", "author_id": 7399, "author_profile": "https://Stackoverflow.com/users/7399", "pm_score": 4, "selected": false, "text": "<pre><code>require 'RMagick'\n\nimage = Magick::Image.new(110, 30){ self.background_color = 'white' }\nimage.write('/tmp/test.jpg')\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
I need to be able to quickly convert an image (inside a rails controller) so that the hosting company using managing our application can quickly test at any time to ensure that rmagick is not only successfully installed, but can be called throgh the rails stiack, what is the quickest clean code I can use to do this?
I wanted to do this so that I can easily hit it with a web browser, as I'm deployng to managed servers, which I do not have shell access onto (for increased security). So this is what I did ``` class DiagnosticsController < ApplicationController require 'RMagick' def rmagick images_path = "public/images" file_name = "rmagick_generated_thumb.jpg" file_path = images_path + "/"+ file_name File.delete file_path if File.exists? file_path img = Magick::Image.read("lib/sample_images/magic.jpg").first thumb = img.scale(0.25) @path = file_name thumb.write file_path end end #------ ``` and then in rmagick.html.erb ``` <%= image_tag @path %> ``` Now I can hit the controller, and if I see an image, I know rmagic is installed.
70,782
<p>How to get a file's creation date or file size, for example this Hello.jpg at <a href="http://www.mywebsite.com/now/Hello.jpg(note" rel="nofollow noreferrer">http://www.mywebsite.com/now/Hello.jpg(note</a>: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?</p>
[ { "answer_id": 70803, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<p>If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date. </p>\n\n<pre><code>$ telnet www.google.com 80\nTrying 216.239.59.103...\nConnected to www.l.google.com.\nEscape character is '^]'.\nHEAD /intl/en_ALL/images/logo.gif HTTP/1.0\n\nHTTP/1.0 200 OK\nContent-Type: image/gif\nLast-Modified: Wed, 07 Jun 2006 19:38:24 GMT\nExpires: Sun, 17 Jan 2038 19:14:07 GMT\nCache-Control: public\nDate: Tue, 16 Sep 2008 09:45:42 GMT\nServer: gws\nContent-Length: 8558\nConnection: Close\n\nConnection closed by foreign host.\n</code></pre>\n\n<p>Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test.</p>\n" }, { "answer_id": 70804, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 1, "selected": false, "text": "<p>The webserver might send a last-modified and/or etag header for that purpose.\nAnd you might send an if-modified-since header in your request.</p>\n\n<p>see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\" rel=\"nofollow noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a>\nsections 14.19, 14.25 and 14.29</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How to get a file's creation date or file size, for example this Hello.jpg at <http://www.mywebsite.com/now/Hello.jpg(note>: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?
If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date. ``` $ telnet www.google.com 80 Trying 216.239.59.103... Connected to www.l.google.com. Escape character is '^]'. HEAD /intl/en_ALL/images/logo.gif HTTP/1.0 HTTP/1.0 200 OK Content-Type: image/gif Last-Modified: Wed, 07 Jun 2006 19:38:24 GMT Expires: Sun, 17 Jan 2038 19:14:07 GMT Cache-Control: public Date: Tue, 16 Sep 2008 09:45:42 GMT Server: gws Content-Length: 8558 Connection: Close Connection closed by foreign host. ``` Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test.
70,797
<p>How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?</p>
[ { "answer_id": 70814, "author": "lbz", "author_id": 11530, "author_profile": "https://Stackoverflow.com/users/11530", "pm_score": 9, "selected": false, "text": "<pre><code>var = raw_input(\"Please enter something: \")\nprint \"you entered\", var\n</code></pre>\n\n<p>Or for Python 3:</p>\n\n<pre><code>var = input(\"Please enter something: \")\nprint(\"You entered: \" + var)\n</code></pre>\n" }, { "answer_id": 70818, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 5, "selected": false, "text": "<p>The best way to process command line arguments is the <a href=\"https://docs.python.org/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code> module.</a></p>\n\n<p>Use <code>raw_input()</code> to get user input. If you import the <a href=\"https://docs.python.org/library/readline.html\" rel=\"noreferrer\"><code>readline module</code></a> your users will have line editing and history.</p>\n" }, { "answer_id": 70833, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 10, "selected": true, "text": "<p>To read user input you can try <a href=\"https://docs.python.org/dev/library/cmd.html\" rel=\"noreferrer\">the <code>cmd</code> module</a> for easily creating a mini-command line interpreter (with help texts and autocompletion) and <a href=\"https://docs.python.org/2/library/functions.html#raw_input\" rel=\"noreferrer\"><code>raw_input</code></a> (<a href=\"https://docs.python.org/dev/library/functions.html#input\" rel=\"noreferrer\"><code>input</code></a> for Python 3+) for reading a line of text from the user.</p>\n\n<pre><code>text = raw_input(\"prompt\") # Python 2\ntext = input(\"prompt\") # Python 3\n</code></pre>\n\n<p>Command line inputs are in <code>sys.argv</code>. Try this in your script:</p>\n\n<pre><code>import sys\nprint (sys.argv)\n</code></pre>\n\n<p>There are two modules for parsing command line options: <a href=\"https://docs.python.org/dev/library/optparse.html\" rel=\"noreferrer\"><s><code>optparse</code></s></a> (deprecated since Python 2.7, use <a href=\"https://docs.python.org/dev/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a> instead) and <a href=\"https://docs.python.org/dev/library/getopt.html\" rel=\"noreferrer\"><code>getopt</code></a>. If you just want to input files to your script, behold the power of <a href=\"https://docs.python.org/dev/library/fileinput.html\" rel=\"noreferrer\"><code>fileinput</code></a>.</p>\n\n<p>The <a href=\"https://docs.python.org/dev/library/\" rel=\"noreferrer\">Python library reference</a> is your friend.</p>\n" }, { "answer_id": 70841, "author": "Simon Peverett", "author_id": 6063, "author_profile": "https://Stackoverflow.com/users/6063", "pm_score": 4, "selected": false, "text": "<p>Use 'raw_input' for input from a console/terminal.</p>\n\n<p>if you just want a command line argument like a file name or something e.g. </p>\n\n<pre><code>$ python my_prog.py file_name.txt\n</code></pre>\n\n<p>then you can use sys.argv...</p>\n\n<pre><code>import sys\nprint sys.argv\n</code></pre>\n\n<p>sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be \"file_name.txt\"</p>\n\n<p>If you want to have full on command line options use the optparse module.</p>\n\n<p>Pev</p>\n" }, { "answer_id": 70869, "author": "Vhaerun", "author_id": 11234, "author_profile": "https://Stackoverflow.com/users/11234", "pm_score": 4, "selected": false, "text": "<p>Careful not to use the <code>input</code> function, unless you know what you're doing. Unlike <code>raw_input</code>, <code>input</code> will accept any python expression, so it's kinda like <code>eval</code></p>\n" }, { "answer_id": 3427325, "author": "GreenMatt", "author_id": 197011, "author_profile": "https://Stackoverflow.com/users/197011", "pm_score": 3, "selected": false, "text": "<p>As of Python <del>3.2</del> 2.7, there is now <a href=\"http://docs.python.org/dev/library/argparse.html\" rel=\"noreferrer\">argparse</a> for processing command line arguments.</p>\n" }, { "answer_id": 8334188, "author": "steampowered", "author_id": 404699, "author_profile": "https://Stackoverflow.com/users/404699", "pm_score": 8, "selected": false, "text": "<p><code>raw_input</code> is no longer available in Python 3.x. But <code>raw_input</code> was renamed <code>input</code>, so the same functionality exists.</p>\n\n<pre><code>input_var = input(\"Enter something: \")\nprint (\"you entered \" + input_var) \n</code></pre>\n\n<p><a href=\"http://docs.python.org/py3k/whatsnew/3.0.html#builtins\" rel=\"noreferrer\">Documentation of the change</a></p>\n" }, { "answer_id": 13089887, "author": "Matt Olan", "author_id": 1776131, "author_profile": "https://Stackoverflow.com/users/1776131", "pm_score": 3, "selected": false, "text": "<p>If you are running Python &lt;2.7, you need <a href=\"http://docs.python.org/library/optparse.html\" rel=\"noreferrer\">optparse</a>, which as the doc explains will create an interface to the command line arguments that are called when your application is run.</p>\n\n<p>However, in Python ≥2.7, optparse has been deprecated, and was replaced with the <a href=\"http://docs.python.org/library/argparse.html\" rel=\"noreferrer\">argparse</a> as shown above. A quick example from the docs...</p>\n\n<blockquote>\n <p>The following code is a Python program that takes a list of integers\n and produces either the sum or the max:</p>\n</blockquote>\n\n<pre><code>import argparse\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('integers', metavar='N', type=int, nargs='+',\n help='an integer for the accumulator')\nparser.add_argument('--sum', dest='accumulate', action='store_const',\n const=sum, default=max,\n help='sum the integers (default: find the max)')\n\nargs = parser.parse_args()\nprint args.accumulate(args.integers)\n</code></pre>\n" }, { "answer_id": 30341035, "author": "Viswesn", "author_id": 527813, "author_profile": "https://Stackoverflow.com/users/527813", "pm_score": 4, "selected": false, "text": "<p>This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.</p>\n\n<pre><code>import argparse\nimport sys\n\ntry:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"square\", help=\"display a square of a given number\",\n type=int)\n args = parser.parse_args()\n\n #print the square of user input from cmd line.\n print args.square**2\n\n #print all the sys argument passed from cmd line including the program name.\n print sys.argv\n\n #print the second argument passed from cmd line; Note it starts from ZERO\n print sys.argv[1]\nexcept:\n e = sys.exc_info()[0]\n print e\n</code></pre>\n\n<p>1) To find the square root of 5</p>\n\n<pre><code>C:\\Users\\Desktop&gt;python -i emp.py 5\n25\n['emp.py', '5']\n5\n</code></pre>\n\n<p>2) Passing invalid argument other than number</p>\n\n<pre><code>C:\\Users\\bgh37516\\Desktop&gt;python -i emp.py five\nusage: emp.py [-h] square\nemp.py: error: argument square: invalid int value: 'five'\n&lt;type 'exceptions.SystemExit'&gt;\n</code></pre>\n" }, { "answer_id": 42305071, "author": "CorpseDead", "author_id": 5539337, "author_profile": "https://Stackoverflow.com/users/5539337", "pm_score": 3, "selected": false, "text": "<p>If it's a 3.x version then just simply use:</p>\n\n<pre><code>variantname = input()\n</code></pre>\n\n<p>For example, you want to input 8:</p>\n\n<pre><code>x = input()\n8\n</code></pre>\n\n<p>x will equal 8 but it's going to be a string except if you define it otherwise.</p>\n\n<p>So you can use the convert command, like:</p>\n\n<pre><code>a = int(x) * 1.1343\nprint(round(a, 2)) # '9.07'\n9.07\n</code></pre>\n" }, { "answer_id": 44314236, "author": "Mark", "author_id": 8075198, "author_profile": "https://Stackoverflow.com/users/8075198", "pm_score": 2, "selected": false, "text": "<p>In Python 2:</p>\n\n<pre><code>data = raw_input('Enter something: ')\nprint data\n</code></pre>\n\n<p>In Python 3:</p>\n\n<pre><code>data = input('Enter something: ')\nprint(data)\n</code></pre>\n" }, { "answer_id": 54241008, "author": "Will Charlton", "author_id": 2517989, "author_profile": "https://Stackoverflow.com/users/2517989", "pm_score": 2, "selected": false, "text": "<pre><code>import six\n\nif six.PY2:\n input = raw_input\n\nprint(input(\"What's your name? \"))\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?
To read user input you can try [the `cmd` module](https://docs.python.org/dev/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) ([`input`](https://docs.python.org/dev/library/functions.html#input) for Python 3+) for reading a line of text from the user. ``` text = raw_input("prompt") # Python 2 text = input("prompt") # Python 3 ``` Command line inputs are in `sys.argv`. Try this in your script: ``` import sys print (sys.argv) ``` There are two modules for parsing command line options: [~~`optparse`~~](https://docs.python.org/dev/library/optparse.html) (deprecated since Python 2.7, use [`argparse`](https://docs.python.org/dev/library/argparse.html) instead) and [`getopt`](https://docs.python.org/dev/library/getopt.html). If you just want to input files to your script, behold the power of [`fileinput`](https://docs.python.org/dev/library/fileinput.html). The [Python library reference](https://docs.python.org/dev/library/) is your friend.
70,842
<p>How should I run another program from within my <code>C</code> program? I need to be able to write data into <code>STDIN</code> of the launched program (and maybe read from it's <code>STDOUT</code>)</p> <p>I am not sure if this is a standard C function. I need the solution that should work under Linux.</p>
[ { "answer_id": 70848, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 5, "selected": true, "text": "<p>You want to use <code>popen</code>. It gives you a unidirectional pipe with which you can access stdin and stdout of the program.</p>\n\n<p>popen is standard on modern unix and unix-like OS, of which Linux is one :-)</p>\n\n<p>Type</p>\n\n<pre><code>man popen\n</code></pre>\n\n<p>in a terminal to read more about it.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Whether <code>popen</code> produces unidirectional or bidirectional pipes depends on the implementation. In <a href=\"https://manpages.debian.org/jessie/manpages-dev/popen.3.en.html\" rel=\"nofollow noreferrer\">Linux</a> and <a href=\"http://man.openbsd.org/OpenBSD-current/man3/popen.3\" rel=\"nofollow noreferrer\">OpenBSD</a>, <code>popen</code> produces unidirectional pipes, which are read-only or write-only. On <a href=\"https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/popen.3.html\" rel=\"nofollow noreferrer\">OS X</a>, <a href=\"https://www.freebsd.org/cgi/man.cgi?query=popen&amp;apropos=0&amp;sektion=0&amp;manpath=FreeBSD+11.0-RELEASE+and+Ports&amp;arch=default&amp;format=html\" rel=\"nofollow noreferrer\">FreeBSD</a> and <a href=\"http://netbsd.gw.com/cgi-bin/man-cgi?popen++NetBSD-current\" rel=\"nofollow noreferrer\">NetBSD</a> <code>popen</code> produces bidirectional pipes.</p>\n" }, { "answer_id": 70857, "author": "Vhaerun", "author_id": 11234, "author_profile": "https://Stackoverflow.com/users/11234", "pm_score": 0, "selected": false, "text": "<p>I think you can use </p>\n\n<blockquote>\n <p><code>freopen</code></p>\n</blockquote>\n\n<p>for this .</p>\n" }, { "answer_id": 70858, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Create two pipes with <code>pipe(...)</code>, one for <code>stdin</code>, one for <code>stdout</code>. </li>\n<li><code>fork(...)</code> the process.</li>\n<li>In the child process (the one where <code>fork(...)</code> returns 0) <code>dup (...)</code> the pipes to <code>stdin</code>/<code>stdout</code>.</li>\n<li><code>exec[v][e]</code> the to be started programm file in the child process.</li>\n<li>In the parent process (the one where <code>fork</code>) returns the PID of the child) do a loop that reads from the child's <code>stdout</code> (<code>select(...)</code> or <code>poll(...)</code>, <code>read(...)</code> ) into a buffer, until the\nchild terminates (<code>waitpid(...)</code>). </li>\n<li>Eventually supply the child with input on <code>stdin</code> if it expects some.</li>\n<li>When done <code>close(...)</code> the pipes.</li>\n</ol>\n" }, { "answer_id": 70954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can use the system call, read <a href=\"http://www.linuxmanpages.com/man3/system.3.php\" rel=\"nofollow noreferrer\">manpage for system(3)</a></p>\n" }, { "answer_id": 80866, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>For simple unidirectional communication, popen() is a decent solution. It is no use for bi-directional communication, though.</p>\n<p>IMO, imjorge (Jorge Ferreira) gave most of the answer (80%?) for bi-directional communication - but omitted a few key details.</p>\n<ol>\n<li>It is crucial that the parent process close the read end of the pipe that is used to send messages to the child process.</li>\n<li>It is crucial that the child process close the write end of the pipe that is used to send messages to the child process.</li>\n<li>It is crucial that the parent process close the write end of the pipe that is used to send messages to the parent process.</li>\n<li>It is crucial that the child process close the read end of the pipe that is used to send messages to the parent process.</li>\n</ol>\n<p>If you do not close the unused ends of the pipes, you do not get sensible behaviour when one of the programs terminates; for example, the child might be reading from its standard input, but unless the write end of the pipe is closed in the child, it will never get EOF (zero bytes from read) because it still has the pipe open and the system thinks it might sometime get around to writing to that pipe, even though it is currently hung waiting for something to read from it.</p>\n<p>The writing processes should consider whether to handle the SIGPIPE signal that is given when you write on a pipe where there is no reading process.</p>\n<p>You have to be aware of pipe capacity (platform dependent, and might be as little as 4KB) and design the programs to avoid deadlock.</p>\n" }, { "answer_id": 83456, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 4, "selected": false, "text": "<p>I wrote some example C code for someone else a while back that shows how to do this. Here it is for you:</p>\n\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid error(char *s);\nchar *data = \"Some input data\\n\";\n\nmain()\n{\n int in[2], out[2], n, pid;\n char buf[255];\n\n /* In a pipe, xx[0] is for reading, xx[1] is for writing */\n if (pipe(in) &lt; 0) error(\"pipe in\");\n if (pipe(out) &lt; 0) error(\"pipe out\");\n\n if ((pid=fork()) == 0) {\n /* This is the child process */\n\n /* Close stdin, stdout, stderr */\n close(0);\n close(1);\n close(2);\n /* make our pipes, our new stdin,stdout and stderr */\n dup2(in[0],0);\n dup2(out[1],1);\n dup2(out[1],2);\n\n /* Close the other ends of the pipes that the parent will use, because if\n * we leave these open in the child, the child/parent will not get an EOF\n * when the parent/child closes their end of the pipe.\n */\n close(in[1]);\n close(out[0]);\n\n /* Over-write the child process with the hexdump binary */\n execl(\"/usr/bin/hexdump\", \"hexdump\", \"-C\", (char *)NULL);\n error(\"Could not exec hexdump\");\n }\n\n printf(\"Spawned 'hexdump -C' as a child process at pid %d\\n\", pid);\n\n /* This is the parent process */\n /* Close the pipe ends that the child uses to read from / write to so\n * the when we close the others, an EOF will be transmitted properly.\n */\n close(in[0]);\n close(out[1]);\n\n printf(\"&lt;- %s\", data);\n /* Write some data to the childs input */\n write(in[1], data, strlen(data));\n\n /* Because of the small amount of data, the child may block unless we\n * close it's input stream. This sends an EOF to the child on it's\n * stdin.\n */\n close(in[1]);\n\n /* Read back any output */\n n = read(out[0], buf, 250);\n buf[n] = 0;\n printf(\"-&gt; %s\",buf);\n exit(0);\n}\n\nvoid error(char *s)\n{\n perror(s);\n exit(1);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6974/" ]
How should I run another program from within my `C` program? I need to be able to write data into `STDIN` of the launched program (and maybe read from it's `STDOUT`) I am not sure if this is a standard C function. I need the solution that should work under Linux.
You want to use `popen`. It gives you a unidirectional pipe with which you can access stdin and stdout of the program. popen is standard on modern unix and unix-like OS, of which Linux is one :-) Type ``` man popen ``` in a terminal to read more about it. **EDIT** Whether `popen` produces unidirectional or bidirectional pipes depends on the implementation. In [Linux](https://manpages.debian.org/jessie/manpages-dev/popen.3.en.html) and [OpenBSD](http://man.openbsd.org/OpenBSD-current/man3/popen.3), `popen` produces unidirectional pipes, which are read-only or write-only. On [OS X](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/popen.3.html), [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=popen&apropos=0&sektion=0&manpath=FreeBSD+11.0-RELEASE+and+Ports&arch=default&format=html) and [NetBSD](http://netbsd.gw.com/cgi-bin/man-cgi?popen++NetBSD-current) `popen` produces bidirectional pipes.
70,850
<p>What advantage, if any, is provided by formatting C code as follows:</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>versus something more typical such as</p> <pre><code>while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); </code></pre> <p>I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.</p> <p>Only advantage I can see is just to be different and leave your fingerprints on code that you've written.</p> <p>I notice vim formatting would have to be hand-rolled to handle the top case.</p>
[ { "answer_id": 70862, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 3, "selected": false, "text": "<p>Nothing. Indentation and other coding standards are a matter of preference.</p>\n" }, { "answer_id": 70863, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "<p>Personal Preference I would have thought? I guess it has the code block in one vertical line so possibly easier to work out at a glance? Personally I prefer the brace to start directly under the previous line</p>\n" }, { "answer_id": 70865, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>Its just another style--people code how they like to code, and that is one accepted style (though not my preferred). I don't think it has much of a disadvantage or advantage over the more common style in which brackets are not indented but the code within them is. Perhaps one could justify it by saying that it more clearly delimits code blocks.</p>\n" }, { "answer_id": 70867, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 2, "selected": false, "text": "<p>Code formatting is personal taste. As long as it is easy to read, it would pay for maintenance!</p>\n" }, { "answer_id": 70873, "author": "benefactual", "author_id": 6445, "author_profile": "https://Stackoverflow.com/users/6445", "pm_score": 1, "selected": false, "text": "<p>In order for this format to have \"advantage\", we really need some equivalent C code in another format to compare to!</p>\n\n<p>Where I work, this indentation scheme is used in order to facilitate a home-grown folding editor mechanism.</p>\n\n<p>Thus, I see nothing fundamentally wrong with this format - within certain rational limits, formatting is a matter of personal preference. </p>\n" }, { "answer_id": 70893, "author": "Andreas Bakurov", "author_id": 7400, "author_profile": "https://Stackoverflow.com/users/7400", "pm_score": 2, "selected": false, "text": "<p>By following some formatting and commenting standards, first of all you show your respect to other people that will read and edit code written by you. If you don't accept rules and write somehow esoteric code the most probable result is that you will not be able communicate with other people (programmers) effectively. Code format is personal choice if software is written only by you and for you and nobody is expected to read it, but how many modern software is written only by one person ?</p>\n" }, { "answer_id": 70923, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": 2, "selected": false, "text": "<p>It looks pretty standard to me. The only personal change I'd make is aligning the curly-braces with the start of the previous line, rather than the start of the next line, but that's just a personal choice.</p>\n\n<p>Anyway, the style of formatting you're looking at there is a standard one for C and C++, and is used because it makes the code easier to read, and in particular by looking at the level of indentation you can tell where you are with nested loops, conditionals, etc. E.g.:</p>\n\n<pre><code>if (x == 0) \n{\n if (y == 2)\n {\n if (z == 3)\n {\n do_something (x);\n }\n }\n}\n</code></pre>\n\n<p>OK in that example it's pretty easy to see what's happening, but if you put a lot of code inside those if statements, it can sometimes be hard to tell where you are without consistent indentation.</p>\n\n<p>In your example, have a look at the position of the exit(1) statement -- if it weren't indented like that, it would be hard to tell where this was. As it is, you can tell it's at the end of that big if statement.</p>\n" }, { "answer_id": 271627, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 6, "selected": true, "text": "<p>The top example is know as \"Whitesmiths style\". <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"noreferrer\">Wikipedia's entry on Indent Styles</a> explains several styles along with their advantages and disadvantages.</p>\n" }, { "answer_id": 272759, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 3, "selected": false, "text": "<p>The indentation you're seeing is <a href=\"http://en.wikipedia.org/wiki/Indent_style#Whitesmiths_style\" rel=\"noreferrer\">Whitesmiths style</a>. It's described in the first edition of <em>Code Complete</em> as \"begin-end Block Boundaries\". The basic argument for this style is that in languages like C (and Pascal) an <code>if</code> governs either a single statement or a block. Thus the whole block, not just its contents should be shown subordinate to the <code>if</code>-statement by being indented consistently.</p>\n\n<pre><code>XXXXXXXXXXXXXXX if (test)\n XXXXXXXXXXXX one_thing();\n\nXXXXXXXXXXXXXXX if (test)\n X {\n XXXXX one_thing();\n XXXXX another_thing();\n X }\n</code></pre>\n\n<p>Back when I first read this book (in the 90s) I found the argument for \"begin-end Block Boundaries\" to be convincing, though I didn't like it much when I put it into practice (in Pascal). I like it even less in C and find it confusing to read. I end up using what Steve McConnel calls \"Emulating Pure Blocks\" (<a href=\"http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#15395\" rel=\"noreferrer\">Sun's Java Style</a>, which is almost <a href=\"http://en.wikipedia.org/wiki/Indent_style#K.26R_style\" rel=\"noreferrer\">K&amp;R</a>).</p>\n\n<pre><code>XXXXXXXXXXXXXX X if (test) {\n XXXXXX one_thing();\n XXXXXX another_thing();\nX }\n</code></pre>\n\n<p>This is the most common style used to program in Java (which is what I do all day). It's also most similar to my <a href=\"http://www-old.oberon.ethz.ch/oreport.html\" rel=\"noreferrer\">previous language</a> which was a \"pure block\" language, requiring no \"emulation\". There are no single-statement bodies, blocks are inherent in the control structure syntax.</p>\n\n<pre><code>IF test THEN\n oneThing;\n anotherThing\nEND\n</code></pre>\n" }, { "answer_id": 58456821, "author": "foo", "author_id": 448779, "author_profile": "https://Stackoverflow.com/users/448779", "pm_score": 2, "selected": false, "text": "<p>The \"advantage\" of Whitesmiths style (as the top one in your example is called) is that it mirrors the actual logical structure of the code:</p>\n\n<ul>\n<li>indent if there is a logical dependency</li>\n<li>place corresponding brackets on the same column so they are easy to find</li>\n<li>opening and closing of a context (which may open/close a stack frame etc) are visible, not hidden</li>\n</ul>\n\n<p>So, less if/else errors, loops gone wrong, and catches at the wrong level, and overall logical consistency.</p>\n\n<p>But as benefactual wrote: within certain rational limits, formatting is a matter of personal preference. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974/" ]
What advantage, if any, is provided by formatting C code as follows: ``` while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); ``` versus something more typical such as ``` while(lock_file(lockdir)==0) { count++; if(count==20) { fprintf(stderr,"Can't lock dir %s\n",lockdir); exit(1); } sleep(3); } if(rmdir(serverdir)!=0) { switch(errno) { case EEXIST: fprintf(stderr,"Server dir %s not empty\n",serverdir); break; default: fprintf(stderr,"Can't delete dir %s\n",serverdir); } exit(1); } unlock_file(lockdir); ``` I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks. Only advantage I can see is just to be different and leave your fingerprints on code that you've written. I notice vim formatting would have to be hand-rolled to handle the top case.
The top example is know as "Whitesmiths style". [Wikipedia's entry on Indent Styles](http://en.wikipedia.org/wiki/Indent_style) explains several styles along with their advantages and disadvantages.
70,855
<p>Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.</p> <p>The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?</p>
[ { "answer_id": 71043, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 4, "selected": false, "text": "<p>While you can't thread, you do have some degree of process control in php. The two function sets that are useful here are:</p>\n\n<p>Process control functions\n<a href=\"http://www.php.net/manual/en/ref.pcntl.php\" rel=\"noreferrer\">http://www.php.net/manual/en/ref.pcntl.php</a></p>\n\n<p>POSIX functions\n<a href=\"http://www.php.net/manual/en/ref.posix.php\" rel=\"noreferrer\">http://www.php.net/manual/en/ref.posix.php</a></p>\n\n<p>You could fork your process with pcntl_fork - returning the PID of the child. Then you can use posix_kill to despose of that PID.</p>\n\n<p>That said, if you kill a parent process a signal should be sent to the child process telling it to die. If php itself isn't recognising this you could register a function to manage it and do a clean exit using pcntl_signal.</p>\n" }, { "answer_id": 72605, "author": "Adam Hopkinson", "author_id": 12280, "author_profile": "https://Stackoverflow.com/users/12280", "pm_score": 4, "selected": false, "text": "<p>You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won't wait for the command to finish.</p>\n\n<p>I can't quite remember the php CLI syntax, but you'd want something like:</p>\n\n<pre><code>exec(\"/path/to/php -f '/path/to/file.php' | '/path/to/output.txt'\");\n</code></pre>\n\n<p>I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.</p>\n" }, { "answer_id": 1079624, "author": "Ricardo", "author_id": 132841, "author_profile": "https://Stackoverflow.com/users/132841", "pm_score": 5, "selected": false, "text": "<p>Threading isn't available in stock PHP, but concurrent programming is possible by using HTTP requests as asynchronous calls.</p>\n\n<p>With the curl's timeout setting set to 1 and using the same session_id for the processes you want to be associated with each other, you can communicate with session variables as in my example below. With this method you can even close your browser and the concurrent process still exists on the server.</p>\n\n<p>Don't forget to verify the correct session ID like this:</p>\n\n<blockquote>\n <p><a href=\"http://localhost/test/verifysession.php?sessionid=[the\" rel=\"noreferrer\">http://localhost/test/verifysession.php?sessionid=[the</a> correct id]</p>\n</blockquote>\n\n<h3>startprocess.php</h3>\n\n<pre><code>$request = \"http://localhost/test/process1.php?sessionid=\".$_REQUEST[\"PHPSESSID\"];\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL, $request);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_TIMEOUT, 1);\ncurl_exec($ch);\ncurl_close($ch);\necho $_REQUEST[\"PHPSESSID\"];\n</code></pre>\n\n<h3>process1.php</h3>\n\n<pre><code>set_time_limit(0);\n\nif ($_REQUEST[\"sessionid\"])\n session_id($_REQUEST[\"sessionid\"]);\n\nfunction checkclose()\n{\n global $_SESSION;\n if ($_SESSION[\"closesession\"])\n {\n unset($_SESSION[\"closesession\"]);\n die();\n }\n}\n\nwhile(!$close)\n{\n session_start();\n $_SESSION[\"test\"] = rand();\n checkclose();\n session_write_close();\n sleep(5);\n}\n</code></pre>\n\n<h3>verifysession.php</h3>\n\n<pre><code>if ($_REQUEST[\"sessionid\"])\n session_id($_REQUEST[\"sessionid\"]);\n\nsession_start();\nvar_dump($_SESSION);\n</code></pre>\n\n<h3>closeprocess.php</h3>\n\n<pre><code>if ($_REQUEST[\"sessionid\"])\n session_id($_REQUEST[\"sessionid\"]);\n\nsession_start();\n$_SESSION[\"closesession\"] = true;\nvar_dump($_SESSION);\n</code></pre>\n" }, { "answer_id": 3579723, "author": "Pete", "author_id": 432373, "author_profile": "https://Stackoverflow.com/users/432373", "pm_score": 3, "selected": false, "text": "<p>You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get. </p>\n" }, { "answer_id": 4350418, "author": "masterb", "author_id": 529958, "author_profile": "https://Stackoverflow.com/users/529958", "pm_score": 6, "selected": false, "text": "<p>why don't you use <a href=\"https://secure.php.net/manual/en/function.popen.php\" rel=\"noreferrer\">popen</a>?</p>\n<pre><code>for ($i=0; $i&lt;10; $i++) {\n // open ten processes\n for ($j = 0; $j &lt; 10; $j++) {\n $pipe[$j] = popen('script2.php', 'w');\n }\n\n // wait for them to finish\n for ($j = 0; $j &lt; 10; ++$j) {\n pclose($pipe[$j]);\n }\n}\n</code></pre>\n" }, { "answer_id": 4790074, "author": "Sheldmandu", "author_id": 2641644, "author_profile": "https://Stackoverflow.com/users/2641644", "pm_score": 3, "selected": false, "text": "<p>Depending on what you're trying to do you could also use curl_multi to achieve it.</p>\n" }, { "answer_id": 5946750, "author": "Manoj Donga", "author_id": 746369, "author_profile": "https://Stackoverflow.com/users/746369", "pm_score": 3, "selected": false, "text": "<p>You can have option of:</p>\n\n<ol>\n<li>multi_curl</li>\n<li>One can use system command for the same</li>\n<li>Ideal scenario is, create a threading function in C language and compile/configure in PHP. Now that function will be the function of PHP.</li>\n</ol>\n" }, { "answer_id": 8844548, "author": "Jarrod", "author_id": 577306, "author_profile": "https://Stackoverflow.com/users/577306", "pm_score": 3, "selected": false, "text": "<p>How about pcntl_fork?</p>\n\n<p>check our the manual page for examples: <a href=\"http://php.net/manual/en/function.pcntl-fork.php\" rel=\"nofollow noreferrer\">PHP pcntl_fork</a></p>\n\n<pre><code>&lt;?php\n\n $pid = pcntl_fork();\n if ($pid == -1) {\n die('could not fork');\n } else if ($pid) {\n // we are the parent\n pcntl_wait($status); //Protect against Zombie children\n } else {\n // we are the child\n }\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 9107047, "author": "Stilero", "author_id": 1180559, "author_profile": "https://Stackoverflow.com/users/1180559", "pm_score": 2, "selected": false, "text": "<p><code>pcntl_fork</code> won't work in a web server environment if it has <em>safe mode</em> turned on. In this case, it will only work in the CLI version of PHP.</p>\n" }, { "answer_id": 12487840, "author": "JasonDavis", "author_id": 143030, "author_profile": "https://Stackoverflow.com/users/143030", "pm_score": 4, "selected": false, "text": "<p>I know this is an old question but for people searching, there is a PECL extension written in C that gives PHP multi-threading capability now, it's located here <a href=\"https://github.com/krakjoe/pthreads\" rel=\"noreferrer\">https://github.com/krakjoe/pthreads</a></p>\n" }, { "answer_id": 15501449, "author": "Baba", "author_id": 1226894, "author_profile": "https://Stackoverflow.com/users/1226894", "pm_score": 9, "selected": false, "text": "<h1>Multi-threading is possible in php</h1>\n\n<p>Yes you can do multi-threading in PHP with <a href=\"https://github.com/krakjoe/pthreads\" rel=\"noreferrer\">pthreads</a> </p>\n\n<p>From <a href=\"http://www.php.net/manual/en/intro.pthreads.php\" rel=\"noreferrer\">the PHP documentation</a>:</p>\n\n<blockquote>\n <p>pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.</p>\n \n <p><strong>Warning</strong>:\n The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.</p>\n</blockquote>\n\n<p><strong>Simple Test</strong></p>\n\n<pre><code>#!/usr/bin/php\n&lt;?php\nclass AsyncOperation extends Thread {\n\n public function __construct($arg) {\n $this-&gt;arg = $arg;\n }\n\n public function run() {\n if ($this-&gt;arg) {\n $sleep = mt_rand(1, 10);\n printf('%s: %s -start -sleeps %d' . \"\\n\", date(\"g:i:sa\"), $this-&gt;arg, $sleep);\n sleep($sleep);\n printf('%s: %s -finish' . \"\\n\", date(\"g:i:sa\"), $this-&gt;arg);\n }\n }\n}\n\n// Create a array\n$stack = array();\n\n//Initiate Multiple Thread\nforeach ( range(\"A\", \"D\") as $i ) {\n $stack[] = new AsyncOperation($i);\n}\n\n// Start The Threads\nforeach ( $stack as $t ) {\n $t-&gt;start();\n}\n\n?&gt;\n</code></pre>\n\n<p>First Run</p>\n\n<pre><code>12:00:06pm: A -start -sleeps 5\n12:00:06pm: B -start -sleeps 3\n12:00:06pm: C -start -sleeps 10\n12:00:06pm: D -start -sleeps 2\n12:00:08pm: D -finish\n12:00:09pm: B -finish\n12:00:11pm: A -finish\n12:00:16pm: C -finish\n</code></pre>\n\n<p>Second Run </p>\n\n<pre><code>12:01:36pm: A -start -sleeps 6\n12:01:36pm: B -start -sleeps 1\n12:01:36pm: C -start -sleeps 2\n12:01:36pm: D -start -sleeps 1\n12:01:37pm: B -finish\n12:01:37pm: D -finish\n12:01:38pm: C -finish\n12:01:42pm: A -finish\n</code></pre>\n\n<p><strong>Real World Example</strong></p>\n\n<pre><code>error_reporting(E_ALL);\nclass AsyncWebRequest extends Thread {\n public $url;\n public $data;\n\n public function __construct($url) {\n $this-&gt;url = $url;\n }\n\n public function run() {\n if (($url = $this-&gt;url)) {\n /*\n * If a large amount of data is being requested, you might want to\n * fsockopen and read using usleep in between reads\n */\n $this-&gt;data = file_get_contents($url);\n } else\n printf(\"Thread #%lu was not provided a URL\\n\", $this-&gt;getThreadId());\n }\n}\n\n$t = microtime(true);\n$g = new AsyncWebRequest(sprintf(\"http://www.google.com/?q=%s\", rand() * 10));\n/* starting synchronization */\nif ($g-&gt;start()) {\n printf(\"Request took %f seconds to start \", microtime(true) - $t);\n while ( $g-&gt;isRunning() ) {\n echo \".\";\n usleep(100);\n }\n if ($g-&gt;join()) {\n printf(\" and %f seconds to finish receiving %d bytes\\n\", microtime(true) - $t, strlen($g-&gt;data));\n } else\n printf(\" and %f seconds to finish, request failed\\n\", microtime(true) - $t);\n}\n</code></pre>\n" }, { "answer_id": 19713701, "author": "pinkal vansia", "author_id": 1606631, "author_profile": "https://Stackoverflow.com/users/1606631", "pm_score": 4, "selected": false, "text": "<p>using threads is made possible by the pthreads PECL extension</p>\n\n<p><a href=\"http://www.php.net/manual/en/book.pthreads.php\">http://www.php.net/manual/en/book.pthreads.php</a></p>\n" }, { "answer_id": 19789433, "author": "Pir Abdul", "author_id": 665485, "author_profile": "https://Stackoverflow.com/users/665485", "pm_score": -1, "selected": false, "text": "<p>Multithreading means performing multiple tasks or processes simultaneously, we can achieve this in php by using following code,although there is no direct way to achieve multithreading in php but we can achieve almost same results by following way.</p>\n\n<pre><code>chdir(dirname(__FILE__)); //if you want to run this file as cron job\n for ($i = 0; $i &lt; 2; $i += 1){\n exec(\"php test_1.php $i &gt; test.txt &amp;\");\n //this will execute test_1.php and will leave this process executing in the background and will go \n\n //to next iteration of the loop immediately without waiting the completion of the script in the \n\n //test_1.php , $i is passed as argument .\n</code></pre>\n\n<p>}</p>\n\n<p>Test_1.php</p>\n\n<pre><code>$conn=mysql_connect($host,$user,$pass);\n$db=mysql_select_db($db);\n$i = $argv[1]; //this is the argument passed from index.php file\nfor($j = 0;$j&lt;5000; $j ++)\n{\nmysql_query(\"insert into test set\n\n id='$i',\n\n comment='test',\n\n datetime=NOW() \");\n\n}\n</code></pre>\n\n<p>This will execute test_1.php two times simultaneously and both process will run in the background simultaneously ,so in this way you can achieve multithreading in php.</p>\n\n<p>This guy done really good work <a href=\"https://github.com/krakjoe/pthreads\" rel=\"nofollow\">Multithreading in php</a></p>\n" }, { "answer_id": 52125027, "author": "Martin Vahi", "author_id": 855783, "author_profile": "https://Stackoverflow.com/users/855783", "pm_score": -1, "selected": false, "text": "<p>As of the writing of my current comment, I don't know about the PHP threads. I came to look for the answer here myself, but one workaround is that the PHP program that receives the request from the web server delegates the whole answer formulation to a console application that stores its output, the answer to the request, to a binary file and the PHP program that launched the console application returns that binary file byte-by-byte as the answer to the received request. The console application can be written in any programming language that runs on the server, including those that have proper threading support, including C++ programs that use OpenMP.</p>\n\n<p>One unreliable, dirty, trick is to use PHP for executing a console application, \"uname\",</p>\n\n<pre><code>uname -a\n</code></pre>\n\n<p>and print the output of that console command to the HTML output to find out the exact version of the server software. Then install the exact same version of the software to a VirtualBox instance, compile/assemble whatever fully self-contained, preferably static, binaries that one wants and then upload those to the server. From that point onwards the PHP application can use those binaries in the role of the console application that has proper multi-threading. It's a dirty, unreliable, workaround to a situation, when the server administrator has not installed all needed programming language implementations to the server. The thing to watch out for is that at every request that the PHP application receives the console application(s) terminates/exit/get_killed. </p>\n\n<p>As to what the hosting service administrators think of such server usage patterns, I guess it boils down to culture. In Northern Europe the service provider HAS TO DELIVER WHAT WAS ADVERTISED and if execution of console commands was allowed and uploading of non-malware files was allowed and the service provider has a right to kill any server process after a few minutes or even after 30 seconds, then the hosting service administrators lack any arguments for forming a proper complaint. In United States and Western Europe the situation/culture is very different and I believe that there's a great chance that in U.S. and/or Western Europe the hosting service provider will \n refuse to serve hosting service clients that use the above described trick. That's just my guess, given my personal experience with U.S. hosting services and given what I have heard from others about Western European hosting services. As of the writing of my current comment(2018_09_01) I do not know anything about the cultural norms of the Southern-European hosting service providers, Southern-European network administrators.</p>\n" }, { "answer_id": 61505176, "author": "Юрий Ярвинен", "author_id": 10738019, "author_profile": "https://Stackoverflow.com/users/10738019", "pm_score": 3, "selected": false, "text": "<p>If you are using a Linux server, you can use </p>\n\n<pre><code>exec(\"nohup $php_path path/script.php &gt; /dev/null 2&gt;/dev/null &amp;\")\n</code></pre>\n\n<p>If you need pass some args </p>\n\n<pre><code>exec(\"nohup $php_path path/script.php $args &gt; /dev/null 2&gt;/dev/null &amp;\")\n</code></pre>\n\n<p>In script.php</p>\n\n<pre><code>$args = $argv[1];\n</code></pre>\n\n<p>Or use Symfony\n<a href=\"https://symfony.com/doc/current/components/process.html\" rel=\"noreferrer\">https://symfony.com/doc/current/components/process.html</a></p>\n\n<pre><code>$process = Process::fromShellCommandline(\"php \".base_path('script.php'));\n$process-&gt;setTimeout(0); \n$process-&gt;disableOutput(); \n$process-&gt;start();\n</code></pre>\n" }, { "answer_id": 71617864, "author": "Justin Jack", "author_id": 1678210, "author_profile": "https://Stackoverflow.com/users/1678210", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question, but this will undoubtedly be useful to many: <a href=\"https://github.com/justincjack/phpthreads\" rel=\"nofollow noreferrer\">PHPThreads</a></p>\n<p>Code Example:</p>\n<pre><code>function threadproc($thread, $param) {\n \n echo &quot;\\tI'm a PHPThread. In this example, I was given only one parameter: \\&quot;&quot;. print_r($param, true) .&quot;\\&quot; to work with, but I can accept as many as you'd like!\\n&quot;;\n \n for ($i = 0; $i &lt; 10; $i++) {\n usleep(1000000);\n echo &quot;\\tPHPThread working, very busy...\\n&quot;;\n }\n \n return &quot;I'm a return value!&quot;;\n}\n \n\n$thread_id = phpthread_create($thread, array(), &quot;threadproc&quot;, null, array(&quot;123456&quot;));\n \necho &quot;I'm the main thread doing very important work!\\n&quot;;\n \nfor ($n = 0; $n &lt; 5; $n++) {\n usleep(1000000);\n echo &quot;Main thread...working!\\n&quot;;\n}\n \necho &quot;\\nMain thread done working. Waiting on our PHPThread...\\n&quot;;\n \nphpthread_join($thread_id, $retval);\n \necho &quot;\\n\\nOur PHPThread returned: &quot; . print_r($retval, true) . &quot;!\\n&quot;;\n</code></pre>\n<p>Requires PHP extensions:</p>\n<ul>\n<li>posix</li>\n<li>pcntl</li>\n<li>sockets</li>\n</ul>\n<p>I've been using this library in production now for months. I put a LOT of effort into making it feel like using POSIX pthreads. If you're comfortable with pthreads, you can pick this up and use it very effectively in no time.</p>\n<p>Computationally, the inner workings are quite different, but practically, the functionality is nearly the same including semantics and syntax.</p>\n<p>I've used it to write an extremely efficient WebSocket server that supports high throughput rates. Sorry, I'm rambling. I'm just excited that I finally got it released and I want to see who it will help!</p>\n" }, { "answer_id": 74086559, "author": "gzhegow", "author_id": 2119205, "author_profile": "https://Stackoverflow.com/users/2119205", "pm_score": 0, "selected": false, "text": "<p>popen()/proc_open() works parallel even in Windows.</p>\n<p>Most often pitfall is &quot;fread/stream_get_contents&quot; without while loop. Once you try to fread() from running process it will block output for processes that run after it (cause of fread() waits until at least one byte arrives)</p>\n<p>Add stream_select(). Closest analogy is &quot;foreach with timeout but for streams&quot;, you pass few arrays to read and write and each call of stream_select() one or more streams will be selected. Function updates original arrays by reference, so dont forget to restore it to all streams before next call. Function gives them some time to read or write. If no content - control returns allowing us to retry cycle.</p>\n<pre class=\"lang-php prettyprint-override\"><code>// sleep.php\nset_error_handler(function ($severity, $error, $file, $line) {\n throw new ErrorException($error, -1, $severity, $file, $line);\n});\n\n$sleep = $argv[ 1 ];\n\nsleep($sleep);\n\necho $sleep . PHP_EOL;\n\nexit(0);\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>// run.php\n&lt;?php\n\n$procs = [];\n$pipes = [];\n\n$cmd = 'php %cd%/sleep.php';\n\n$desc = [\n 0 =&gt; [ 'pipe', 'r' ],\n 1 =&gt; [ 'pipe', 'w' ],\n 2 =&gt; [ 'pipe', 'a' ],\n];\n\nfor ( $i = 0; $i &lt; 10; $i++ ) {\n $iCmd = $cmd . ' ' . ( 10 - $i ); // add SLEEP argument to each command 10, 9, ... etc.\n\n $proc = proc_open($iCmd, $desc, $pipes[ $i ], __DIR__);\n\n $procs[ $i ] = $proc;\n}\n\n$stdins = array_column($pipes, 0);\n$stdouts = array_column($pipes, 1);\n$stderrs = array_column($pipes, 2);\n\nwhile ( $procs ) {\n foreach ( $procs as $i =&gt; $proc ) {\n // @gzhegow &gt; [OR] you can output while script is running (if child never finishes)\n $read = [ $stdins[ $i ] ];\n $write = [ $stdouts[ $i ], $stderrs[ $i ] ];\n $except = [];\n if (stream_select($read, $write, $except, $seconds = 0, $microseconds = 1000)) {\n foreach ( $write as $stream ) {\n echo stream_get_contents($stream);\n }\n }\n\n $status = proc_get_status($proc);\n\n if (false === $status[ 'running' ]) {\n $status = proc_close($proc);\n unset($procs[ $i ]);\n\n echo 'STATUS: ' . $status . PHP_EOL;\n }\n\n // @gzhegow &gt; [OR] you can output once command finishes\n // $status = proc_get_status($proc);\n //\n // if (false === $status[ 'running' ]) {\n // if ($content = stream_get_contents($stderrs[ $i ])) {\n // echo '[ERROR]' . $content . PHP_EOL;\n // }\n //\n // echo stream_get_contents($stdouts[ $i ]) . PHP_EOL;\n //\n // $status = proc_close($proc);\n // unset($procs[ $i ]);\n //\n // echo 'STATUS: ' . $status . PHP_EOL;\n // }\n }\n\n usleep(1); // give your computer one tick to decide what thread should be used\n}\n\n// ensure you receive 1,2,3... but you've just run it 10,9,8...\n\nexit(0);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11190/" ]
Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes. The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?
Multi-threading is possible in php ================================== Yes you can do multi-threading in PHP with [pthreads](https://github.com/krakjoe/pthreads) From [the PHP documentation](http://www.php.net/manual/en/intro.pthreads.php): > > pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects. > > > **Warning**: > The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only. > > > **Simple Test** ``` #!/usr/bin/php <?php class AsyncOperation extends Thread { public function __construct($arg) { $this->arg = $arg; } public function run() { if ($this->arg) { $sleep = mt_rand(1, 10); printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep); sleep($sleep); printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg); } } } // Create a array $stack = array(); //Initiate Multiple Thread foreach ( range("A", "D") as $i ) { $stack[] = new AsyncOperation($i); } // Start The Threads foreach ( $stack as $t ) { $t->start(); } ?> ``` First Run ``` 12:00:06pm: A -start -sleeps 5 12:00:06pm: B -start -sleeps 3 12:00:06pm: C -start -sleeps 10 12:00:06pm: D -start -sleeps 2 12:00:08pm: D -finish 12:00:09pm: B -finish 12:00:11pm: A -finish 12:00:16pm: C -finish ``` Second Run ``` 12:01:36pm: A -start -sleeps 6 12:01:36pm: B -start -sleeps 1 12:01:36pm: C -start -sleeps 2 12:01:36pm: D -start -sleeps 1 12:01:37pm: B -finish 12:01:37pm: D -finish 12:01:38pm: C -finish 12:01:42pm: A -finish ``` **Real World Example** ``` error_reporting(E_ALL); class AsyncWebRequest extends Thread { public $url; public $data; public function __construct($url) { $this->url = $url; } public function run() { if (($url = $this->url)) { /* * If a large amount of data is being requested, you might want to * fsockopen and read using usleep in between reads */ $this->data = file_get_contents($url); } else printf("Thread #%lu was not provided a URL\n", $this->getThreadId()); } } $t = microtime(true); $g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10)); /* starting synchronization */ if ($g->start()) { printf("Request took %f seconds to start ", microtime(true) - $t); while ( $g->isRunning() ) { echo "."; usleep(100); } if ($g->join()) { printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data)); } else printf(" and %f seconds to finish, request failed\n", microtime(true) - $t); } ```
70,880
<p>Say I have the following C++:</p> <pre><code>char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; </code></pre> <p>Is this safe according to the C++ standard? Do I need to cast back to a <code>char*</code> and then use <code>delete[]</code>? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?</p>
[ { "answer_id": 70904, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 3, "selected": false, "text": "<p>No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that <a href=\"https://stackoverflow.com/questions/70880/deleting-a-buffer-through-a-different-type-of-pointer#70905\">thudbang</a> linked to says, <code>operator delete[]</code> might be overloaded to do something different to <code>operator delete</code>. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't.</p>\n" }, { "answer_id": 70905, "author": "thudbang", "author_id": 11661, "author_profile": "https://Stackoverflow.com/users/11661", "pm_score": 4, "selected": true, "text": "<p>It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:</p>\n\n<p>[16.13] Can I drop the <code>[]</code> when deleting array of some built-in type (<code>char</code>, <code>int</code>, etc.)?</p>\n\n<p><a href=\"https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins\" rel=\"nofollow noreferrer\">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13</a></p>\n" }, { "answer_id": 70910, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>While this <em>should</em> work, I don't think you can guarantee it to be safe because the SOME_STRUCT is not a char* (unless it's merely a typedef).</p>\n\n<p>Additionally, since you're using different types of references, if you continue to use the *p access, and the memory has been deleted, you will get a runtime error.</p>\n" }, { "answer_id": 70941, "author": "Igor Semenov", "author_id": 11401, "author_profile": "https://Stackoverflow.com/users/11401", "pm_score": 2, "selected": false, "text": "<p>C++ Standard [5.3.5.2] declares:</p>\n\n<blockquote>\n <p>If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion\n function, and the converted operand is used in place of the original operand for the remainder of this section. In either\n alternative, the value of the operand of delete may be a null pointer value. <strong>If it is not a null pointer value, in the first\n alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a\n subobject (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second\n alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous\n array new-expression.77) If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression\n must match the type of the object allocated by new, not the syntax of the new-expression. —end note ]</strong> [ Note: a pointer\n to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the\n pointer expression before it is used as the operand of the delete-expression. —end note ]</p>\n</blockquote>\n" }, { "answer_id": 70942, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 2, "selected": false, "text": "<p>I highly doubt it.</p>\n\n<p>There are a lot of questionable ways of freeing memory, for example you can use <code>delete</code> on your <code>char</code> array (rather than <code>delete[]</code>) and it will likely work fine. I <a href=\"http://www.byteclub.net/blog/zooba/?p=77\" rel=\"nofollow noreferrer\">blogged</a> in detail about this (apologies for the self-link, but it's easier than rewriting it all).</p>\n\n<p>The compiler is not so much the issue as the platform. Most libraries will use the allocation methods of the underlying operating system, which means the same code could behave differently on Mac vs. Windows vs. Linux. I have seen examples of this and every single one was questionable code.</p>\n\n<p>The safest approach is to always allocate and free memory using the same data type. If you are allocating <code>char</code>s and returning them to other code, you may be better off providing specific allocate/deallocate methods:</p>\n\n<pre><code>SOME_STRUCT* Allocate()\n{\n size_t cb; // Initialised to something\n return (SOME_STRUCT*)(new char[cb]);\n}\n</code></pre>\n\n<p>&nbsp;</p>\n\n<pre><code>void Free(SOME_STRUCT* obj)\n{\n delete[] (char*)obj;\n}\n</code></pre>\n\n<p>(Overloading the <code>new</code> and <code>delete</code> operators may also be an option, but I have never liked doing this.)</p>\n" }, { "answer_id": 71090, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 0, "selected": false, "text": "<p>This will work OK if the memory being pointed to <strong>and</strong> the pointer you are pointing with are both POD. In this case, no destructor would be called anyhow, and the memory allocator does not know or care about the type stored within the memory.</p>\n\n<p>The only case this is OK with non-POD types, is if the pointee is a subtype of the pointer, (e.g. You are pointing at a Car with a Vehicle*) and the pointer's destructor has been declared virtual.</p>\n" }, { "answer_id": 71442, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This isn't safe, and non of the responses so far have emphasized enough the madness of doing this. Simply don't do it, if you consider yourself a real programmer, or ever want to work as a professional programmer in a team. You can only say that your struct contains non destructor <em>at the moment</em>, however you are laying a nasty possibly compiler and system specific trap for the future. Also, your code is unlikely to work as expected. The very best you can hope for is it doesn't crash. However I suspect you will slowly get a memory leak, as array allocations via new very often allocate extra memory in the bytes <em>prior</em> to the returned pointer. You won't be freeing the memory you think you are. A good memory allocation routine should pick up this mismatch, as would tools like Lint etc. </p>\n\n<p>Simply don't do that, and purge from your mind whatever thinking process led you to even consider such nonsense.</p>\n" }, { "answer_id": 72444, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "<p>I've changed the code to use malloc/free. While I know how MSVC implements new/delete for plain-old-data (and SOME_STRUCT in this case was a Win32 structure, so simple C), I just wanted to know if it was a portable technique.</p>\n\n<p>It's not, so I'll use something that is.</p>\n" }, { "answer_id": 78368, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "<p>If you use malloc/free instead of new/delete, malloc and free won't care about the type.</p>\n\n<p>So if you're using a C-like POD (plain old data, like a build-in type, or a struct), you can malloc some type, and free another. <strong>note that this is poor style even if it works</strong>.</p>\n" }, { "answer_id": 108579, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 2, "selected": false, "text": "<p>This is a very similar question to the one that I answered here: <a href=\"https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#108454\">link text</a></p>\n\n<p>In short, no, it's not safe according to the C++ standard. If, for some reason, you need a SOME_STRUCT object allocated in an area of memory that has a size difference from <code>size_of(SOME_STRUCT)</code> (and it had better be bigger!), then you are better off using a raw allocation function like global <code>operator new</code> to perform the allocation and then creating the object instance in raw memory with a placement <code>new</code>. Placement <code>new</code> will be extremely cheap if the object type has no constructor.</p>\n\n<pre><code>void* p = ::operator new( cb );\nSOME_STRUCT* pSS = new (p) SOME_STRUCT;\n\n// ...\n\ndelete pSS;\n</code></pre>\n\n<p>This will work most of the time. It should always work if <code>SOME_STRUCT</code> is a POD-struct. It will also work in other cases if <code>SOME_STRUCT</code>'s constructor does not throw and if <code>SOME_STRUCT</code> does not have a custom operator delete. This technique also removes the need for any casts.</p>\n\n<p><code>::operator new</code> and <code>::operator delete</code> are C++'s closest equivalent to <code>malloc</code> and <code>free</code> and as these (in the absence of class overrides) are called as appropriate by <code>new</code> and <code>delete</code> expressions they can (with care!) be used in combination.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446/" ]
Say I have the following C++: ``` char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; ``` Is this safe according to the C++ standard? Do I need to cast back to a `char*` and then use `delete[]`? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?
It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite: [16.13] Can I drop the `[]` when deleting array of some built-in type (`char`, `int`, etc.)? [http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins)
70,947
<p>I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?</p>
[ { "answer_id": 70976, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 9, "selected": true, "text": "<p>Yes.</p>\n\n<pre><code>ThisWorkbook.RefreshAll\n</code></pre>\n\n<p>Or, if your Excel version is old enough,</p>\n\n<pre><code>Dim Sheet as WorkSheet, Pivot as PivotTable\nFor Each Sheet in ThisWorkbook.WorkSheets\n For Each Pivot in Sheet.PivotTables\n Pivot.RefreshTable\n Pivot.Update\n Next\nNext\n</code></pre>\n" }, { "answer_id": 71002, "author": "LohanJ", "author_id": 11286, "author_profile": "https://Stackoverflow.com/users/11286", "pm_score": 1, "selected": false, "text": "<p>You have a <em>PivotTables</em> collection on a the VB <em>Worksheet</em> object. So, a quick loop like this will work:</p>\n\n<pre><code>Sub RefreshPivotTables()\n Dim pivotTable As PivotTable\n For Each pivotTable In ActiveSheet.PivotTables\n pivotTable.RefreshTable\n Next\nEnd Sub\n</code></pre>\n\n<p>Notes from the trenches:</p>\n\n<ol>\n<li>Remember to unprotect any protected sheets before updating the PivotTable.</li>\n<li><strong>Save often</strong>.</li>\n<li>I'll think of more and update in due course... :)</li>\n</ol>\n\n<p>Good luck!</p>\n" }, { "answer_id": 71084, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 5, "selected": false, "text": "<p>This VBA code will refresh all pivot tables/charts in the workbook.</p>\n\n<pre><code>Sub RefreshAllPivotTables()\n\nDim PT As PivotTable\nDim WS As Worksheet\n\n For Each WS In ThisWorkbook.Worksheets\n\n For Each PT In WS.PivotTables\n PT.RefreshTable\n Next PT\n\n Next WS\n\nEnd Sub\n</code></pre>\n\n<p>Another non-programatic option is:</p>\n\n<ul>\n<li>Right click on each pivot table</li>\n<li>Select Table options</li>\n<li>Tick the <strong>'Refresh on open'</strong> option.</li>\n<li>Click on the OK button</li>\n</ul>\n\n<p>This will refresh the pivot table each time the workbook is opened.</p>\n" }, { "answer_id": 359227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>There is a refresh all option in the Pivot Table tool bar. That is enough. Dont have to do anything else.</p>\n\n<p>Press ctrl+alt+F5</p>\n" }, { "answer_id": 8432023, "author": "Steve WahWah Weeks", "author_id": 1087868, "author_profile": "https://Stackoverflow.com/users/1087868", "pm_score": 3, "selected": false, "text": "<p>In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.</p>\n\n<p>The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.</p>\n" }, { "answer_id": 10434668, "author": "Karuna", "author_id": 1372934, "author_profile": "https://Stackoverflow.com/users/1372934", "pm_score": -1, "selected": false, "text": "<p>If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.</p>\n" }, { "answer_id": 12478754, "author": "RBhandal", "author_id": 1680524, "author_profile": "https://Stackoverflow.com/users/1680524", "pm_score": -1, "selected": false, "text": "<p>I have use the command listed below in the recent past and it seems to work fine.</p>\n\n<pre><code>ActiveWorkbook.RefreshAll\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 12592078, "author": "Kevin", "author_id": 1698696, "author_profile": "https://Stackoverflow.com/users/1698696", "pm_score": 5, "selected": false, "text": "<p><code>ActiveWorkbook.RefreshAll</code> refreshes everything, not only the pivot tables but also the ODBC queries. I have a couple of VBA queries that refer to Data connections and using this option crashes as the command runs the Data connections without the detail supplied from the VBA</p>\n\n<p>I recommend the option if you only want the pivots refreshed</p>\n\n<pre><code>Sub RefreshPivotTables() \n Dim pivotTable As PivotTable \n For Each pivotTable In ActiveSheet.PivotTables \n pivotTable.RefreshTable \n Next \nEnd Sub \n</code></pre>\n" }, { "answer_id": 29474211, "author": "user3564681", "author_id": 3564681, "author_profile": "https://Stackoverflow.com/users/3564681", "pm_score": 0, "selected": false, "text": "<p>The code </p>\n\n<pre><code>Private Sub Worksheet_Activate()\n Dim PvtTbl As PivotTable\n Cells.EntireColumn.AutoFit\n For Each PvtTbl In Worksheets(\"Sales Details\").PivotTables\n PvtTbl.RefreshTable\n Next\nEnd Sub \n</code></pre>\n\n<p>works fine.</p>\n\n<p>The code is used in the activate sheet module, thus it displays a flicker/glitch when the sheet is activated.</p>\n" }, { "answer_id": 34544128, "author": "Rajiv Singh", "author_id": 1527856, "author_profile": "https://Stackoverflow.com/users/1527856", "pm_score": 0, "selected": false, "text": "<p>Even <strong>we can refresh particular connection</strong> and in turn it will refresh all the pivots linked to it.</p>\n\n<p><strong>For this code I have created slicer from table present in Excel</strong>:</p>\n\n<pre><code>Sub UpdateConnection()\n Dim ServerName As String\n Dim ServerNameRaw As String\n Dim CubeName As String\n Dim CubeNameRaw As String\n Dim ConnectionString As String\n\n ServerNameRaw = ActiveWorkbook.SlicerCaches(\"Slicer_ServerName\").VisibleSlicerItemsList(1)\n ServerName = Replace(Split(ServerNameRaw, \"[\")(3), \"]\", \"\")\n\n CubeNameRaw = ActiveWorkbook.SlicerCaches(\"Slicer_CubeName\").VisibleSlicerItemsList(1)\n CubeName = Replace(Split(CubeNameRaw, \"[\")(3), \"]\", \"\")\n\n If CubeName = \"All\" Or ServerName = \"All\" Then\n MsgBox \"Please Select One Cube and Server Name\", vbOKOnly, \"Slicer Info\"\n Else\n ConnectionString = GetConnectionString(ServerName, CubeName)\n UpdateAllQueryTableConnections ConnectionString, CubeName\n End If\n End Sub\n\n Function GetConnectionString(ServerName As String, CubeName As String)\n Dim result As String\n result = \"OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=\" &amp; CubeName &amp; \";Data Source=\" &amp; ServerName &amp; \";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2\"\n '\"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=\" &amp; CubeName &amp; \";Data Source=\" &amp; ServerName &amp; \";Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False\"\n GetConnectionString = result\n End Function\n\n Function GetConnectionString(ServerName As String, CubeName As String)\n Dim result As String\n result = \"OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=\" &amp; CubeName &amp; \";Data Source=\" &amp; ServerName &amp; \";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2\"\n GetConnectionString = result\nEnd Function\n\nSub UpdateAllQueryTableConnections(ConnectionString As String, CubeName As String)\n Dim cn As WorkbookConnection\n Dim oledbCn As OLEDBConnection\n Dim Count As Integer, i As Integer\n Dim DBName As String\n DBName = \"Initial Catalog=\" + CubeName\n\n Count = 0\n For Each cn In ThisWorkbook.Connections\n If cn.Name = \"ThisWorkbookDataModel\" Then\n Exit For\n End If\n\n oTmp = Split(cn.OLEDBConnection.Connection, \";\")\n For i = 0 To UBound(oTmp) - 1\n If InStr(1, oTmp(i), DBName, vbTextCompare) = 1 Then\n Set oledbCn = cn.OLEDBConnection\n oledbCn.SavePassword = True\n oledbCn.Connection = ConnectionString\n oledbCn.Refresh\n Count = Count + 1\n End If\n Next\n Next\n\n If Count = 0 Then\n MsgBox \"Nothing to update\", vbOKOnly, \"Update Connection\"\n ElseIf Count &gt; 0 Then\n MsgBox \"Update &amp; Refresh Connection Successfully\", vbOKOnly, \"Update Connection\"\n End If\nEnd Sub\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8418/" ]
I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?
Yes. ``` ThisWorkbook.RefreshAll ``` Or, if your Excel version is old enough, ``` Dim Sheet as WorkSheet, Pivot as PivotTable For Each Sheet in ThisWorkbook.WorkSheets For Each Pivot in Sheet.PivotTables Pivot.RefreshTable Pivot.Update Next Next ```
70,956
<p>Is there a good way to exclude certain pages from using a HTTP module?</p> <p>I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:</p> <pre><code>&lt;system.web&gt; &lt;!-- ... --&gt; &lt;httpModules&gt; &lt;add name="SessionValidationModule" type="SessionValidationModule, SomeNamespace" /&gt; &lt;/httpModules&gt; &lt;/system.web&gt; </code></pre> <p>To exclude the module from the page, I tried doing this (without success):</p> <pre><code>&lt;location path="ToBeExcluded"&gt; &lt;system.web&gt; &lt;!-- ... --&gt; &lt;httpModules&gt; &lt;remove name="SessionValidationModule" /&gt; &lt;/httpModules&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>Any thoughts?</p>
[ { "answer_id": 71790, "author": "Crob", "author_id": 2460, "author_profile": "https://Stackoverflow.com/users/2460", "pm_score": 5, "selected": true, "text": "<p>You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config. </p>\n\n<pre><code>&lt;add verb=\"*\" path=\"/validate/*.aspx\" type=\"Handler,Assembly\"/&gt;\n</code></pre>\n\n<p>If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation. </p>\n" }, { "answer_id": 72823, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>HttpModules attach to the ASP.NET request processing pipeline itself. The httpModule itself must take care of figuring out which requests it wants to act on and which requests it wants to ignore. </p>\n\n<p>This can, for example, be achieved by looking at the context.Request.Path property.</p>\n" }, { "answer_id": 18411217, "author": "Mr. Pumpkin", "author_id": 524605, "author_profile": "https://Stackoverflow.com/users/524605", "pm_score": 3, "selected": false, "text": "<p>Here is some simple example how to filter requests by extension... the example below exclude from the processing files with the specific extensions. Filtering by file name will look almost the same with some small changes...</p>\n\n<pre><code>public class AuthenticationModule : IHttpModule\n{\n private static readonly List&lt;string&gt; extensionsToSkip = AuthenticationConfig.ExtensionsToSkip.Split('|').ToList();\n\n // In the Init function, register for HttpApplication \n // events by adding your handlers.\n public void Init(HttpApplication application)\n {\n application.BeginRequest += new EventHandler(this.Application_BeginRequest);\n application.EndRequest += new EventHandler(this.Application_EndRequest);\n }\n\n private void Application_BeginRequest(Object source, EventArgs e)\n {\n // we don't have to process all requests...\n if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))\n return;\n\n Trace.WriteLine(\"Application_BeginRequest: \" + HttpContext.Current.Request.Url.AbsoluteUri);\n }\n\n private void Application_EndRequest(Object source, EventArgs e)\n {\n // we don't have to process all requests...\n if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))\n return;\n\n Trace.WriteLine(\"Application_BeginRequest: \" + HttpContext.Current.Request.Url.AbsoluteUri);\n }\n}\n</code></pre>\n\n<p>General idea is to specify in config file what exactly should be processed (or excluded from the processing) and use that config parameter in the module.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6308/" ]
Is there a good way to exclude certain pages from using a HTTP module? I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config: ``` <system.web> <!-- ... --> <httpModules> <add name="SessionValidationModule" type="SessionValidationModule, SomeNamespace" /> </httpModules> </system.web> ``` To exclude the module from the page, I tried doing this (without success): ``` <location path="ToBeExcluded"> <system.web> <!-- ... --> <httpModules> <remove name="SessionValidationModule" /> </httpModules> </system.web> </location> ``` Any thoughts?
You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config. ``` <add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/> ``` If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation.
70,964
<p>Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time. </p> <p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p>
[ { "answer_id": 154765, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 2, "selected": false, "text": "<p>There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.</p>\n\n<p>In Java you could use the <code>inDaylightTime</code> method of the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html\" rel=\"nofollow noreferrer\">TimeZone</a> class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use <a href=\"http://joda-time.sourceforge.net/\" rel=\"nofollow noreferrer\">Joda Time</a>. I can't see a clean way of finding this out using just the standard libraries.</p>\n\n<p>The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)</p>\n\n<pre><code>import org.joda.time.DateTime;\nimport org.joda.time.DateTimeZone;\n\npublic class App {\n public static void main(String[] args) {\n DateTimeZone dtz = DateTimeZone.forID(\"Europe/Amsterdam\");\n\n System.out.println(startDST(dtz, 2008));\n System.out.println(endDST(dtz, 2008));\n }\n\n public static DateTime startDST(DateTimeZone zone, int year) {\n return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis()));\n }\n\n public static DateTime endDST(DateTimeZone zone, int year) {\n return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis()));\n }\n}\n</code></pre>\n" }, { "answer_id": 50499119, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://stackoverflow.com/a/154765/642706\">Answer by Richters</a> is correct and should be accepted.</p>\n\n<p>As Richters noted, there is no logic to <a href=\"https://en.wikipedia.org/wiki/Daylight_saving_time\" rel=\"nofollow noreferrer\">Daylight Saving Time (DST)</a> or other anomalies. Politicians arbitrarily redefine the <a href=\"https://en.wikipedia.org/wiki/UTC_offset\" rel=\"nofollow noreferrer\">offset-from-UTC</a> used in their <a href=\"https://en.wikipedia.org/wiki/Time_zone\" rel=\"nofollow noreferrer\">time zones</a>. They make these changes often with little forewarning, or even no warning at all as <a href=\"http://www.bbc.com/news/world-asia-44010705\" rel=\"nofollow noreferrer\">North Korea did</a> a few weeks ago.</p>\n\n<h1>java.time</h1>\n\n<p>Here are some further thoughts, and example code using the modern <em>java.time</em> classes that succeeded the Joda-Time classes shown in his Answer.</p>\n\n<p>These changes are tracked in a list maintained by <a href=\"https://en.wikipedia.org/wiki/ICANN\" rel=\"nofollow noreferrer\">ICANN</a>, known as <a href=\"https://en.wikipedia.org/wiki/Tz_database\" rel=\"nofollow noreferrer\"><em>tzdata</em></a>, formerly known as the Olson Database. Your Java implementation, host operating system, and database system likely all have their own copies of this data which must be replaced as needed when changes are mode to zones you care about. There is no logic to these changes, so there is no way to predict the changes programmatically. Your code must call upon a fresh copy of <em>tzdata</em>.</p>\n\n<blockquote>\n <p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p>\n</blockquote>\n\n<p>Actually, you need not determine the point of the cut-over. A good date-time library handles that for you automatically. </p>\n\n<p>Java has the best such library, the industry-leading <em>java.time</em> classes. When you ask for a time-of-day on a certain date in a certain region (time zone), if that time-of-day is no valid an adjustment is made automatically. Read the documentation for the <code>ZonedDateTime</code> to understand the algorithm used in that adjustment.</p>\n\n<pre><code>ZoneId z = ZoneId.of( \"America/Montreal\" );\nLocalDate ld = LocalDate.of( 2018 , Month.MARCH , 11 ); // 2018-03-11.\nLocalTime lt = LocalTime.of( 2 , 0 ); // 2 AM.\nZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );\n</code></pre>\n\n<p>Notice the result is 3 AM rather than the 2 AM requested. There was no 2 AM on that date in that zone. So java.time adjusted to 3 AM as the clock “Springs ahead” an hour.</p>\n\n<blockquote>\n <p>zdt.toString(): 2018-03-11T03:00-04:00[America/Montreal]</p>\n</blockquote>\n\n<p>If you feel the need to investigate the rules defined for a time zone, use the <a href=\"https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneRules.html\" rel=\"nofollow noreferrer\"><code>ZoneRules</code></a> class.</p>\n\n<p>Get the amount of DST shift used in the present moment.</p>\n\n<pre><code>Duration d = z.getRules().getDaylightSavings​( Instant.now() ) ;\n</code></pre>\n\n<p>Get the next planned change, represented as a <a href=\"https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneOffsetTransition.html\" rel=\"nofollow noreferrer\"><code>ZoneOffsetTransition</code></a> object.</p>\n\n<pre><code>ZoneId z = ZoneId.of( \"America/Montreal\" );\nZoneOffsetTransition t = z.getRules().nextTransition( Instant.now() );\nString output = \"For zone: \" + z + \", on \" + t.getDateTimeBefore() + \" duration change: \" + t.getDuration() + \" to \" + t.getDateTimeAfter();\n</code></pre>\n\n<blockquote>\n <p>For zone: America/Montreal, on 2018-11-04T02:00 duration change: PT-1H to 2018-11-04T01:00</p>\n</blockquote>\n\n<p>Specify a <a href=\"https://en.wikipedia.org/wiki/List_of_tz_zones_by_name\" rel=\"nofollow noreferrer\">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href=\"https://en.wikipedia.org/wiki/America/Montreal\" rel=\"nofollow noreferrer\"><code>America/Montreal</code></a>, <a href=\"https://en.wikipedia.org/wiki/Africa/Casablanca\" rel=\"nofollow noreferrer\"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href=\"https://en.wikipedia.org/wiki/Legacy_system\" rel=\"nofollow noreferrer\">legacy</a> date-time classes such as <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Date.html\" rel=\"nofollow noreferrer\"><code>java.util.Date</code></a>, <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html\" rel=\"nofollow noreferrer\"><code>Calendar</code></a>, &amp; <a href=\"http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href=\"http://www.joda.org/joda-time/\" rel=\"nofollow noreferrer\"><em>Joda-Time</em></a> project, now in <a href=\"https://en.wikipedia.org/wiki/Maintenance_mode\" rel=\"nofollow noreferrer\">maintenance mode</a>, advises migration to the <a href=\"http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href=\"https://jcp.org/en/jsr/detail?id=310\" rel=\"nofollow noreferrer\">JSR 310</a>.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href=\"https://en.wikipedia.org/wiki/JDBC_driver\" rel=\"nofollow noreferrer\">JDBC driver</a> compliant with <a href=\"http://openjdk.java.net/jeps/170\" rel=\"nofollow noreferrer\">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\"><strong>Java SE 8</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9\" rel=\"nofollow noreferrer\"><strong>Java SE 9</strong></a>, <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10\" rel=\"nofollow noreferrer\"><strong>Java SE 10</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6\" rel=\"nofollow noreferrer\"><strong>Java SE 6</strong></a> and <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Android_(operating_system)\" rel=\"nofollow noreferrer\"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android (&lt;26), the <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href=\"http://stackoverflow.com/q/38922754/642706\"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href=\"http://www.threeten.org/threeten-extra/\" rel=\"nofollow noreferrer\"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html\" rel=\"nofollow noreferrer\"><code>Interval</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html\" rel=\"nofollow noreferrer\"><code>YearWeek</code></a>, <a href=\"http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html\" rel=\"nofollow noreferrer\"><code>YearQuarter</code></a>, and <a href=\"http://www.threeten.org/threeten-extra/apidocs/index.html\" rel=\"nofollow noreferrer\">more</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time. So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...
There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language. In Java you could use the `inDaylightTime` method of the [TimeZone](http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html) class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use [Joda Time](http://joda-time.sourceforge.net/). I can't see a clean way of finding this out using just the standard libraries. The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year) ``` import org.joda.time.DateTime; import org.joda.time.DateTimeZone; public class App { public static void main(String[] args) { DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam"); System.out.println(startDST(dtz, 2008)); System.out.println(endDST(dtz, 2008)); } public static DateTime startDST(DateTimeZone zone, int year) { return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis())); } public static DateTime endDST(DateTimeZone zone, int year) { return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis())); } } ```
70,992
<p>Relating to my <a href="https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload">earlier question</a>, I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:</p> <pre><code>select distinct o from Order o left join fetch o.orderLines </code></pre> <p>Assuming a model with an <code>Order</code> class which has a set of <code>OrderLines</code> in it.</p> <p>My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an <code>Order</code> for each <code>OrderLine</code>. Am I doing the right thing?</p> <p>Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using <code>FetchType.EAGER</code> as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?</p>
[ { "answer_id": 71172, "author": "Jeremy", "author_id": 4419, "author_profile": "https://Stackoverflow.com/users/4419", "pm_score": 3, "selected": false, "text": "<p>I'm not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation...</p>\n\n<p>Have you tried adding the FetchType property to your relationship attribute?</p>\n\n<p>@OneToMany(fetch=FetchType.EAGER)?</p>\n\n<p>See: </p>\n\n<p><a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html\" rel=\"noreferrer\">http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html</a>\n<a href=\"http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple\" rel=\"noreferrer\">http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple</a></p>\n" }, { "answer_id": 71316, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 0, "selected": false, "text": "<p>That would only work for ManyToOne relations and for them @ManyToOne(fetch=FetchType.EAGER) would probably appropriate.</p>\n\n<p>Fetching more than one OneToMany relation eagerly is discouraged and/or does not work as you can read in the link Jeremy posted. Just think about the SQL statement that would be needed to do such a fetch...</p>\n" }, { "answer_id": 71499, "author": "James Law", "author_id": 11855, "author_profile": "https://Stackoverflow.com/users/11855", "pm_score": 5, "selected": true, "text": "<p>Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed.</p>\n\n<p>I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.</p>\n" }, { "answer_id": 73267, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>What I have done is to refactor the code to keep a map of objects to entity managers and each time I need to refresh, close the old entitymanager for the object and open a new one. I used the above query without the <strong>fetch</strong> as that is going too deep for my needs - just doing a plain join pulls in the OrderLines - the <strong>fetch</strong> makes it go even deeper. </p>\n\n<p>There are only a few objects that I need this for, around 20, so I think the resource overhead in having 20 open entitymanagers is not an issue - although the DBAs may have a different view when this goes live...</p>\n\n<p>I also re-worked things so that the db work is on the main thread and has the entity manager. </p>\n\n<p>Chris</p>\n" }, { "answer_id": 74284, "author": "ncgz", "author_id": 12905, "author_profile": "https://Stackoverflow.com/users/12905", "pm_score": -1, "selected": false, "text": "<p>If the problem is just LazyInitializationExceptions, you can avoid that by adding an OpenSessionInViewFilter.<br>\nThis will allow the objects to be loaded in the view, but will not help with the speed issue.</p>\n\n<pre><code> &lt;filter&gt;\n &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt;\n &lt;filter-class&gt; org.springframework.orm.hibernate3.support.OpenSessionInViewFilter\n &lt;/filter-class&gt;\n &lt;/filter&gt;\n &lt;filter-mapping&gt;\n &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt;\n &lt;url-pattern&gt;/*&lt;/url-pattern&gt;\n &lt;/filter-mapping&gt;\n</code></pre>\n" }, { "answer_id": 75459, "author": "Mike Desjardins", "author_id": 10466, "author_profile": "https://Stackoverflow.com/users/10466", "pm_score": 2, "selected": false, "text": "<p>You might be able to do something like that using a (detached) criteria query, and setting the fetch mode. E.g.,</p>\n\n<pre><code>Session s = ((HibernateEntityManager) em).getSession().getSessionFactory().openSession();\nDetachedCriteria dc = DetachedCriteria.forClass(MyEntity.class).add(Expression.idEq(id));\ndc.setFetchMode(\"innerTable\", FetchMode.JOIN);\nCriteria c = dc.getExecutableCriteria(s);\nMyEntity a = (MyEntity)c.uniqueResult();\n</code></pre>\n" }, { "answer_id": 227780, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 2, "selected": false, "text": "<p>Have you tried using a result transformer? If you use Criteria queries, you can apply a result transformer (although <a href=\"http://www.jroller.com/RickHigh/entry/hibernate_query_getting_rid_of\" rel=\"nofollow noreferrer\">there are some problems with pagination and result transformer</a>):</p>\n\n<pre><code>Criteria c = ((Session)em.getDelegate()).createCriteria(Order.class);\nc.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\nc.list();\n</code></pre>\n\n<p>the <code>em.getDelegate()</code> is a hack that only works if you are using hibernate.</p>\n\n<blockquote>\n <p>Perhaps more importantly, is there a\n way to pull in all child objects, no\n matter how deep? We have around 10-15\n classes and for the server we will\n need everything loaded... I was\n avoiding using FetchType.EAGER as that\n meant its always eager and in\n particular the web front end loads\n everything - but perhaps that is the\n way to go - is that what you do? I\n seem to remember us trying this before\n and then getting really slow webpages\n - but perhaps that means we should be using a second-level cache?</p>\n</blockquote>\n\n<p>If you are still interested, I responded a similar question in this thread <a href=\"https://stackoverflow.com/questions/182323/how-to-serialize-hibernate-collections-properly#182955\">how to serialize hibernate collections</a>.</p>\n\n<p>Basically you use a utility called <a href=\"http://dozer.sf.net\" rel=\"nofollow noreferrer\">dozer</a> that maps beans onto another beans, and by doing this you trigger all your lazy loads. As you can imagine, this works better if all collections are eagerly fetched.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48310/" ]
Relating to my [earlier question](https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload), I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this: ``` select distinct o from Order o left join fetch o.orderLines ``` Assuming a model with an `Order` class which has a set of `OrderLines` in it. My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an `Order` for each `OrderLine`. Am I doing the right thing? Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using `FetchType.EAGER` as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?
Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed. I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.
70,993
<p>We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.</p> <p>The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.</p>
[ { "answer_id": 71105, "author": "jbdavid", "author_id": 6314, "author_profile": "https://Stackoverflow.com/users/6314", "pm_score": 4, "selected": true, "text": "<p>The verification of \"logical\" systems in the IC design arena is known as \"Design Verification\", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality. </p>\n\n<p>Ladder logic can be transformed to one of the modern HDL's like Verilog.. \ntransform each ladder </p>\n\n<pre><code>|---|R15|---+---|/R16|---------(R18)--------|\n| |\n|---|R12|---+\n</code></pre>\n\n<p>to an expression like </p>\n\n<pre><code>always @(*) R18 = !R16 &amp;&amp; ( R15 | R12);\n</code></pre>\n\n<p>or you could use an assign statement</p>\n\n<pre><code>assign R18 = R16 &amp;&amp; (R15 | R12); \n</code></pre>\n\n<p>a latching relay</p>\n\n<pre><code>assign R18 = (set condition) || R18 &amp;&amp; !(break condition);\n</code></pre>\n\n<p>Then use a free verilog simulator like <a href=\"http://www.icarus.com/eda/verilog/\" rel=\"nofollow noreferrer\">Icarus</a> to develop a testbench and test your system. \nMake sure you're testcases give good CODE coverage of your logic! And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn. </p>\n\n<p>(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.</p>\n\n<p>Verilog will be an easier language to develop your tests and testbenches in!</p>\n\n<p>It may be helpful to program in some unit delays.</p>\n\n<p>Sorry, I have never looked for ladder logic to/from verilog translators.. \nbut ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!</p>\n\n<p>Good luck. \njbd</p>\n\n<p>There are a couple of ladder logic editors (with simultors) available for free.. \nhere is one that runs on windows supposedly:</p>\n\n<p><a href=\"http://cq.cx/ladder.pl\" rel=\"nofollow noreferrer\">http://cq.cx/ladder.pl</a></p>\n" }, { "answer_id": 693089, "author": "rlbond", "author_id": 72631, "author_profile": "https://Stackoverflow.com/users/72631", "pm_score": 0, "selected": false, "text": "<p>There is a program called LogixPro which has an IO simulator for ladder logic, you can try that.</p>\n" }, { "answer_id": 1365819, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 2, "selected": false, "text": "<p>We've experimented with test coverage tools for Rockwell Control Logix controllers. Most procedural language test coverage tools do branch coverage or some such; because Relay Ladder Logic typically doesn't branch, this doesn't work very well. </p>\n\n<p>What we have prototyped is <a href=\"http://en.wikipedia.org/wiki/Modified_Condition/Decision_Coverage\" rel=\"nofollow noreferrer\">MC/DC</a> (modified/condition/decision coverage) for RLL code for Rockwell controllers.. This tells, for each condition in rung, whether that condition has been tested as TRUE, tested as FALSE, and more importantly, if there the condition controlled the output of the decision in the rung (well at least the action controlled by the decision) in both true and false directions under some test.</p>\n\n<p>This work is done using a general purpose program analysis and transformation tool called\n<a href=\"http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow noreferrer\">DMS</a> used to instrument the RLL code with additional logic to collect the necessary data.</p>\n\n<p>You still have to code unit tests. The easiest way to do that is to get another PLC to act as a replacement for the mechanical hardware you intend to control, and simply write another RLL program to exercise the first one.</p>\n" }, { "answer_id": 7591379, "author": "daniel", "author_id": 866502, "author_profile": "https://Stackoverflow.com/users/866502", "pm_score": 0, "selected": false, "text": "<p>Sometimes on small PLC programs a test program (or subroutine, or ladder file) is written in the project, which is only run when the project is being emulated. The file has some simple logic that says when an output is energised, turn on the input associated with the feedback. You can then control your PLC through whatever HMI is wired up to it and see that the code behaves as expected. Its very important to disable or delete the test program when the software is downloaded to a real site as it can do very strange things in the real world.</p>\n\n<p>On larger projects each device has a simulation mode that does something slightly similar. <a href=\"http://www.batchcontrol.com/s88/01_tutorial/06-modules.shtml\" rel=\"nofollow\">http://www.batchcontrol.com/s88/01_tutorial/06-modules.shtml</a> </p>\n\n<p>This is nothing like using test frameworks for OO languages, but I haven't really seen any test driven development for PLCs, or even much automated testing.</p>\n" }, { "answer_id": 56534301, "author": "Chris Johnson", "author_id": 6228010, "author_profile": "https://Stackoverflow.com/users/6228010", "pm_score": 0, "selected": false, "text": "<p>My boss on a constant basis tells me that the testing is built in the logic itself . PLC’s are in fact deterministic so you should practically be able to follow logic and not need to simulate testing. However we’re not perfect. Having framework would really only allow us to step through what we already know, ladder logic really just takes practice to understand how PLCS work.</p>\n\n<p>That being said I did have some good success with a program I made that essentially flipped on and off IO , it could even simulate the counts of an encoder to test what happens when an object gets to a position. Their were assert statements that could get tripped and inform me where my logic faulted. It did catch a few bugs, and that implementation went very well for a system I’ve never touched. It itself was very beneficial and I do think that it could be useful but I’ve gotten a lot better so I find myself not needing it because of my experience.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/70993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909/" ]
We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system. The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.
The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality. Ladder logic can be transformed to one of the modern HDL's like Verilog.. transform each ladder ``` |---|R15|---+---|/R16|---------(R18)--------| | | |---|R12|---+ ``` to an expression like ``` always @(*) R18 = !R16 && ( R15 | R12); ``` or you could use an assign statement ``` assign R18 = R16 && (R15 | R12); ``` a latching relay ``` assign R18 = (set condition) || R18 && !(break condition); ``` Then use a free verilog simulator like [Icarus](http://www.icarus.com/eda/verilog/) to develop a testbench and test your system. Make sure you're testcases give good CODE coverage of your logic! And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn. (Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials. Verilog will be an easier language to develop your tests and testbenches in! It may be helpful to program in some unit delays. Sorry, I have never looked for ladder logic to/from verilog translators.. but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!! Good luck. jbd There are a couple of ladder logic editors (with simultors) available for free.. here is one that runs on windows supposedly: <http://cq.cx/ladder.pl>
71,000
<p>I'm trying to create a Zip file from .Net that can be read from Java code.</p> <p>I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.</p> <p>Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <a href="http://community.sharpdevelop.net/forums/t/8272.aspx" rel="nofollow noreferrer">http://community.sharpdevelop.net/forums/t/8272.aspx</a> for info) but with no result.</p> <p>Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?</p> <p>Regards Massimo</p>
[ { "answer_id": 71060, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Can't help with SharpZipLib, but you can try to create zip file using <a href=\"http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx\" rel=\"nofollow noreferrer\">ZipPackage</a> class <a href=\"http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx\" rel=\"nofollow noreferrer\">System.IO.Packaging</a> without using 3rd part libraries (requires .NET 3+).</p>\n" }, { "answer_id": 71072, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 4, "selected": true, "text": "<p>I have used <a href=\"http://www.codeplex.com/DotNetZip\" rel=\"noreferrer\">DotNetZip library</a> and it seems to work properly. Typical code:</p>\n\n<pre><code>using (ZipFile zipFile = new ZipFile())\n{\n zipFile.AddDirectory(sourceFolderPath);\n zipFile.Save(archiveFolderName);\n}\n</code></pre>\n" }, { "answer_id": 71890, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>To judge whether it's really a conformant ZIP file, see PKZIP's <a href=\"http://www.pkware.com/documents/casestudies/APPNOTE.TXT\" rel=\"nofollow noreferrer\">.ZIP File Format Specification</a>.</p>\n\n<p>For what it's worth I have had no trouble using SharpZipLib to create ZIPs on a Windows Mobile device and open them with WinZip or Windows XP's built-in Compressed Folders feature, and also no trouble producing ZIPs on the desktop with SharpZipLib and processing them with my own ZIP extraction utility (basically a wrapper around zlib) on the mobile device.</p>\n" }, { "answer_id": 410383, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "<p>You don't wanna use the ZipPackage class in .NET - it isn't quite a standard zip model. Well it is, but it presumes a particular structure in the file, with a manifest with a well-known name, and so on. ZipPackage seems to have been optimized for Office docs and XPS docs. </p>\n\n<p>A third-party library, like <a href=\"http://www.codeplex.com/DotNetZip\" rel=\"nofollow noreferrer\">http://www.codeplex.com/DotNetZip</a>, is probably a better bet if you are doing general-purpose ZIP files and want good interoperability. </p>\n\n<p>DotNetZip builds files that are very interoperable with just about everything, including Java's java.utils.zip. But be careful using features that Java does not support, like ZIP64 or Unicode. ZIP64 is useful only for very large archives, which Java does not support well at this time, I think. Java supports Unicode in a particular way, so if you produce a Unicode-based ZIP file with DotNetZip, you just have to follow a few rules and it will work fine. </p>\n" }, { "answer_id": 487038, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem with unzipping SharpZipLib-zipped files on Linux. I think I solved it (well I works on Linux and Mac now, I tested it), check out my blog post: <a href=\"http://igorbrejc.net/development/c/sharpziplib-making-it-work-for-linuxmac\" rel=\"nofollow noreferrer\">http://igorbrejc.net/development/c/sharpziplib-making-it-work-for-linuxmac</a></p>\n" }, { "answer_id": 659397, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I had the same problem creating zips with SharpZipLib (latest version) and extracting with java.utils.zip.</p>\n\n<p>Here is what fixed the problem for me. I had to force the exclusion of the zip64 usage:</p>\n\n<pre><code>ZipOutputStream s = new ZipOutputStream(File.Create(someZipFileName))\n\ns.UseZip64 = UseZip64.Off;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673/" ]
I'm trying to create a Zip file from .Net that can be read from Java code. I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java. Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <http://community.sharpdevelop.net/forums/t/8272.aspx> for info) but with no result. Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class? Regards Massimo
I have used [DotNetZip library](http://www.codeplex.com/DotNetZip) and it seems to work properly. Typical code: ``` using (ZipFile zipFile = new ZipFile()) { zipFile.AddDirectory(sourceFolderPath); zipFile.Save(archiveFolderName); } ```
71,022
<p>How do you return 1 value per row of the max of several columns:</p> <p><strong>TableName</strong></p> <pre><code>[Number, Date1, Date2, Date3, Cost] </code></pre> <p>I need to return something like this:</p> <pre><code>[Number, Most_Recent_Date, Cost] </code></pre> <p>Query?</p>
[ { "answer_id": 71045, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 9, "selected": true, "text": "<p>This is an old answer and broken in many way.</p>\n<p>See <a href=\"https://stackoverflow.com/a/6871572/194653\">https://stackoverflow.com/a/6871572/194653</a> which has way more upvotes and works with sql server 2008+ and handles nulls, etc.</p>\n<p><strong>Original but problematic answer</strong>:</p>\n<p>Well, you can use the CASE statement:</p>\n<pre><code>SELECT\n CASE\n WHEN Date1 &gt;= Date2 AND Date1 &gt;= Date3 THEN Date1\n WHEN Date2 &gt;= Date1 AND Date2 &gt;= Date3 THEN Date2\n WHEN Date3 &gt;= Date1 AND Date3 &gt;= Date2 THEN Date3\n ELSE Date1\n END AS MostRecentDate\n</code></pre>\n" }, { "answer_id": 71147, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": 4, "selected": false, "text": "<p>Either of the two samples below will work:</p>\n\n<pre><code>SELECT MAX(date_columns) AS max_date\nFROM ( (SELECT date1 AS date_columns\n FROM data_table )\n UNION\n ( SELECT date2 AS date_columns\n FROM data_table\n )\n UNION\n ( SELECT date3 AS date_columns\n FROM data_table\n )\n ) AS date_query\n</code></pre>\n\n<p>The second is an add-on to <a href=\"https://stackoverflow.com/users/267/lassevk\">lassevk's</a> answer.</p>\n\n<pre><code>SELECT MAX(MostRecentDate)\nFROM ( SELECT CASE WHEN date1 &gt;= date2\n AND date1 &gt;= date3 THEN date1\n WHEN date2 &gt;= date1\n AND date2 &gt;= date3 THEN date2\n WHEN date3 &gt;= date1\n AND date3 &gt;= date2 THEN date3\n ELSE date1\n END AS MostRecentDate\n FROM data_table\n ) AS date_query \n</code></pre>\n" }, { "answer_id": 331873, "author": "bajafresh4life", "author_id": 21339, "author_profile": "https://Stackoverflow.com/users/21339", "pm_score": 8, "selected": false, "text": "<p>If you're using MySQL or PostgreSQL or Oracle or BigQuery, you can use</p>\n<pre><code>SELECT GREATEST(col1, col2 ...) FROM table\n</code></pre>\n" }, { "answer_id": 331933, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 2, "selected": false, "text": "<p>If you are using SQL Server 2005, you can use the UNPIVOT feature. Here is a complete example:</p>\n\n<pre><code>create table dates \n(\n number int,\n date1 datetime,\n date2 datetime,\n date3 datetime \n)\n\ninsert into dates values (1, '1/1/2008', '2/4/2008', '3/1/2008')\ninsert into dates values (1, '1/2/2008', '2/3/2008', '3/3/2008')\ninsert into dates values (1, '1/3/2008', '2/2/2008', '3/2/2008')\ninsert into dates values (1, '1/4/2008', '2/1/2008', '3/4/2008')\n\nselect max(dateMaxes)\nfrom (\n select \n (select max(date1) from dates) date1max, \n (select max(date2) from dates) date2max,\n (select max(date3) from dates) date3max\n) myTable\nunpivot (dateMaxes For fieldName In (date1max, date2max, date3max)) as tblPivot\n\ndrop table dates\n</code></pre>\n" }, { "answer_id": 1398019, "author": "Niikola", "author_id": 130904, "author_profile": "https://Stackoverflow.com/users/130904", "pm_score": 6, "selected": false, "text": "<p>There are 3 more methods where <code>UNPIVOT</code> (1) is the fastest by far, followed by Simulated Unpivot (3) which is much slower than (1) but still faster than (2)</p>\n\n<pre><code>CREATE TABLE dates\n (\n number INT PRIMARY KEY ,\n date1 DATETIME ,\n date2 DATETIME ,\n date3 DATETIME ,\n cost INT\n )\n\nINSERT INTO dates\nVALUES ( 1, '1/1/2008', '2/4/2008', '3/1/2008', 10 )\nINSERT INTO dates\nVALUES ( 2, '1/2/2008', '2/3/2008', '3/3/2008', 20 )\nINSERT INTO dates\nVALUES ( 3, '1/3/2008', '2/2/2008', '3/2/2008', 30 )\nINSERT INTO dates\nVALUES ( 4, '1/4/2008', '2/1/2008', '3/4/2008', 40 )\nGO\n</code></pre>\n\n<h2>Solution 1 (<code>UNPIVOT</code>)</h2>\n\n<pre><code>SELECT number ,\n MAX(dDate) maxDate ,\n cost\nFROM dates UNPIVOT ( dDate FOR nDate IN ( Date1, Date2,\n Date3 ) ) as u\nGROUP BY number ,\n cost \nGO\n</code></pre>\n\n<h2>Solution 2 (Sub query per row)</h2>\n\n<pre><code>SELECT number ,\n ( SELECT MAX(dDate) maxDate\n FROM ( SELECT d.date1 AS dDate\n UNION\n SELECT d.date2\n UNION\n SELECT d.date3\n ) a\n ) MaxDate ,\n Cost\nFROM dates d\nGO\n</code></pre>\n\n<h2>Solution 3 (Simulated <code>UNPIVOT</code>)</h2>\n\n<pre><code>;WITH maxD\n AS ( SELECT number ,\n MAX(CASE rn\n WHEN 1 THEN Date1\n WHEN 2 THEN date2\n ELSE date3\n END) AS maxDate\n FROM dates a\n CROSS JOIN ( SELECT 1 AS rn\n UNION\n SELECT 2\n UNION\n SELECT 3\n ) b\n GROUP BY Number\n )\n SELECT dates.number ,\n maxD.maxDate ,\n dates.cost\n FROM dates\n INNER JOIN MaxD ON dates.number = maxD.number\nGO\n\nDROP TABLE dates\nGO\n</code></pre>\n" }, { "answer_id": 4308539, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT \n CASE \n WHEN Date1 &gt;= Date2 AND Date1 &gt;= Date3 THEN Date1 \n WHEN Date2 &gt;= Date3 THEN Date2 \n ELSE Date3\n END AS MostRecentDate \n</code></pre>\n\n<p>This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.</p>\n" }, { "answer_id": 4308905, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 3, "selected": false, "text": "<pre><code>DECLARE @TableName TABLE (Number INT, Date1 DATETIME, Date2 DATETIME, Date3 DATETIME, Cost MONEY)\n\nINSERT INTO @TableName \nSELECT 1, '20000101', '20010101','20020101',100 UNION ALL\nSELECT 2, '20000101', '19900101','19980101',99 \n\nSELECT Number,\n Cost ,\n (SELECT MAX([Date])\n FROM (SELECT Date1 AS [Date]\n UNION ALL\n SELECT Date2\n UNION ALL\n SELECT Date3\n )\n D\n )\n [Most Recent Date]\nFROM @TableName\n</code></pre>\n" }, { "answer_id": 4695172, "author": "DrYodo", "author_id": 576121, "author_profile": "https://Stackoverflow.com/users/576121", "pm_score": 0, "selected": false, "text": "<p>You could create a function where you pass the dates and then add the function to the select statement like below.\nselect Number, dbo.fxMost_Recent_Date(Date1,Date2,Date3), Cost</p>\n\n<pre><code>create FUNCTION fxMost_Recent_Date \n</code></pre>\n\n<p>(\n @Date1 smalldatetime, \n @Date2 smalldatetime,\n @Date3 smalldatetime\n)\nRETURNS smalldatetime\nAS\nBEGIN\n DECLARE @Result smalldatetime</p>\n\n<pre><code>declare @MostRecent smalldatetime\n\nset @MostRecent='1/1/1900'\n\nif @Date1&gt;@MostRecent begin set @MostRecent=@Date1 end\nif @Date2&gt;@MostRecent begin set @MostRecent=@Date2 end\nif @Date3&gt;@MostRecent begin set @MostRecent=@Date3 end\nRETURN @MostRecent\n</code></pre>\n\n<p>END</p>\n" }, { "answer_id": 4922103, "author": "MartinC", "author_id": 606510, "author_profile": "https://Stackoverflow.com/users/606510", "pm_score": 4, "selected": false, "text": "<p>Scalar Function cause all sorts of performance issues, so its better to wrap the logic into an Inline Table Valued Function if possible. This is the function I used to replace some User Defined Functions which selected the Min/Max dates from a list of upto ten dates. When tested on my dataset of 1 Million rows the Scalar Function took over 15 minutes before I killed the query the Inline TVF took 1 minute which is the same amount of time as selecting the resultset into a temporary table. To use this call the function from either a subquery in the the SELECT or a CROSS APPLY.</p>\n\n<pre><code>CREATE FUNCTION dbo.Get_Min_Max_Date\n(\n @Date1 datetime,\n @Date2 datetime,\n @Date3 datetime,\n @Date4 datetime,\n @Date5 datetime,\n @Date6 datetime,\n @Date7 datetime,\n @Date8 datetime,\n @Date9 datetime,\n @Date10 datetime\n)\nRETURNS TABLE\nAS\nRETURN\n(\n SELECT Max(DateValue) Max_Date,\n Min(DateValue) Min_Date\n FROM (\n VALUES (@Date1),\n (@Date2),\n (@Date3),\n (@Date4),\n (@Date5),\n (@Date6),\n (@Date7),\n (@Date8),\n (@Date9),\n (@Date10)\n ) AS Dates(DateValue)\n)\n</code></pre>\n" }, { "answer_id": 6650238, "author": "Michael Freidgeim", "author_id": 52277, "author_profile": "https://Stackoverflow.com/users/52277", "pm_score": 1, "selected": false, "text": "<p>Based on the <a href=\"http://www.experts-exchange.com/M_664986.html\" rel=\"nofollow noreferrer\">ScottPletcher</a>'s solution from <a href=\"http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24204894.html\" rel=\"nofollow noreferrer\">http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24204894.html</a>\nI’ve created a set of functions (e.g. GetMaxOfDates3 , GetMaxOfDates13 )to find max of up to 13 Date values using UNION ALL.\nSee <a href=\"https://mfreidge.wordpress.com/2011/07/11/t-sql-function-to-get-maximum-of-values-from-the-same-row/\" rel=\"nofollow noreferrer\">T-SQL function to Get Maximum of values from the same row</a>\nHowever I haven't considered UNPIVOT solution at the time of writing these functions</p>\n<pre><code>CREATE FUNCTION GetMaxOfDates13 (\n@value01 DateTime = NULL, \n@value02 DateTime = NULL,\n@value03 DateTime = NULL,\n@value04 DateTime = NULL,\n@value05 DateTime = NULL,\n@value06 DateTime = NULL,\n@value07 DateTime = NULL,\n@value08 DateTime = NULL,\n@value09 DateTime = NULL,\n@value10 DateTime = NULL,\n@value11 DateTime = NULL,\n@value12 DateTime = NULL,\n@value13 DateTime = NULL\n)\nRETURNS DateTime\nAS\nBEGIN\nRETURN (\nSELECT TOP 1 value\nFROM (\nSELECT @value01 AS value UNION ALL\nSELECT @value02 UNION ALL\nSELECT @value03 UNION ALL\nSELECT @value04 UNION ALL\nSELECT @value05 UNION ALL\nSELECT @value06 UNION ALL\nSELECT @value07 UNION ALL\nSELECT @value08 UNION ALL\nSELECT @value09 UNION ALL\nSELECT @value10 UNION ALL\nSELECT @value11 UNION ALL\nSELECT @value12 UNION ALL\nSELECT @value13\n) AS [values]\nORDER BY value DESC \n)\nEND –FUNCTION\nGO\nCREATE FUNCTION GetMaxOfDates3 (\n@value01 DateTime = NULL, \n@value02 DateTime = NULL,\n@value03 DateTime = NULL\n)\nRETURNS DateTime\nAS\nBEGIN\nRETURN dbo.GetMaxOfDates13(@value01,@value02,@value03,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)\nEND –FUNCTION\n</code></pre>\n" }, { "answer_id": 6871572, "author": "Sven", "author_id": 442204, "author_profile": "https://Stackoverflow.com/users/442204", "pm_score": 10, "selected": false, "text": "<p>Here is another nice solution for the <code>Max</code> functionality using T-SQL and SQL Server</p>\n<pre><code>SELECT [Other Fields],\n (SELECT Max(v) \n FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]\nFROM [YourTableName]\n</code></pre>\n<p>Values is the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql?view=sql-server-ver15\" rel=\"noreferrer\">Table Value Constructor</a>.</p>\n<p>&quot;Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. The table value constructor can be specified either as the VALUES clause of an INSERT ... VALUES statement, or as a derived table in either the USING clause of the MERGE statement or the FROM clause.&quot;</p>\n" }, { "answer_id": 8971789, "author": "Disillusioned", "author_id": 224704, "author_profile": "https://Stackoverflow.com/users/224704", "pm_score": 3, "selected": false, "text": "<p>Unfortunately <a href=\"https://stackoverflow.com/a/71045/224704\">Lasse's answer</a>, though seemingly obvious, has a crucial flaw. It cannot handle NULL values. Any single NULL value results in Date1 being returned. Unfortunately any attempt to fix that problem tends to get extremely messy and doesn't scale to 4 or more values very nicely.</p>\n\n<p><a href=\"https://stackoverflow.com/a/71147/224704\">databyss's first answer</a> looked (and is) good. However, it wasn't clear whether the answer would easily extrapolate to 3 values from a multi-table join instead of the simpler 3 values from a single table. I wanted to avoid turning such a query into a sub-query just to get the max of 3 columns, also I was pretty sure databyss's excellent idea could be cleaned up a bit.</p>\n\n<p>So without further ado, here's my solution (derived from databyss's idea).<br>\nIt uses cross-joins selecting constants to simulate the effect of a multi-table join. The important thing to note is that all the necessary aliases carry through correctly (which is not always the case) and this keeps the pattern quite simple and fairly scalable through additional columns.</p>\n\n<pre><code>DECLARE @v1 INT ,\n @v2 INT ,\n @v3 INT\n--SET @v1 = 1 --Comment out SET statements to experiment with \n --various combinations of NULL values\nSET @v2 = 2\nSET @v3 = 3\n\nSELECT ( SELECT MAX(Vals)\n FROM ( SELECT v1 AS Vals\n UNION\n SELECT v2\n UNION\n SELECT v3\n ) tmp\n WHERE Vals IS NOT NULL -- This eliminates NULL warning\n\n ) AS MaxVal\nFROM ( SELECT @v1 AS v1\n ) t1\n CROSS JOIN ( SELECT @v2 AS v2\n ) t2\n CROSS JOIN ( SELECT @v3 AS v3\n ) t3\n</code></pre>\n" }, { "answer_id": 10831815, "author": "Luis Miguel Rosa", "author_id": 1428154, "author_profile": "https://Stackoverflow.com/users/1428154", "pm_score": 2, "selected": false, "text": "<p>Problem: choose the minimum rate value given to an entity\nRequirements: Agency rates can be null</p>\n\n<pre><code>[MinRateValue] = \nCASE \n WHEN ISNULL(FitchRating.RatingValue, 100) &lt; = ISNULL(MoodyRating.RatingValue, 99) \n AND ISNULL(FitchRating.RatingValue, 100) &lt; = ISNULL(StandardPoorsRating.RatingValue, 99) \n THEN FitchgAgency.RatingAgencyName\n\n WHEN ISNULL(MoodyRating.RatingValue, 100) &lt; = ISNULL(StandardPoorsRating.RatingValue , 99)\n THEN MoodyAgency.RatingAgencyName\n\n ELSE ISNULL(StandardPoorsRating.RatingValue, 'N/A') \nEND \n</code></pre>\n\n<p>Inspired by <a href=\"https://stackoverflow.com/a/4308539\">this answer</a> from <a href=\"https://stackoverflow.com/users/13813/nat\">Nat</a></p>\n" }, { "answer_id": 23864329, "author": "TechDo", "author_id": 1367256, "author_profile": "https://Stackoverflow.com/users/1367256", "pm_score": 1, "selected": false, "text": "<p>Please try using <code>UNPIVOT</code>:</p>\n\n<pre><code>SELECT MAX(MaxDt) MaxDt\n FROM tbl \nUNPIVOT\n (MaxDt FOR E IN \n (Date1, Date2, Date3)\n)AS unpvt;\n</code></pre>\n" }, { "answer_id": 23888942, "author": "EarlOfEnnui", "author_id": 3442468, "author_profile": "https://Stackoverflow.com/users/3442468", "pm_score": 2, "selected": false, "text": "<p>Using CROSS APPLY (for 2005+) ....</p>\n\n<pre><code>SELECT MostRecentDate \nFROM SourceTable\n CROSS APPLY (SELECT MAX(d) MostRecentDate FROM (VALUES (Date1), (Date2), (Date3)) AS a(d)) md\n</code></pre>\n" }, { "answer_id": 24527258, "author": "abdulbasit", "author_id": 3678700, "author_profile": "https://Stackoverflow.com/users/3678700", "pm_score": 2, "selected": false, "text": "<p>From SQL Server 2012 we can use <a href=\"http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx\" rel=\"nofollow\">IIF</a>.</p>\n\n<pre><code> DECLARE @Date1 DATE='2014-07-03';\n DECLARE @Date2 DATE='2014-07-04';\n DECLARE @Date3 DATE='2014-07-05';\n\n SELECT IIF(@Date1&gt;@Date2,\n IIF(@Date1&gt;@Date3,@Date1,@Date3),\n IIF(@Date2&gt;@Date3,@Date2,@Date3)) AS MostRecentDate\n</code></pre>\n" }, { "answer_id": 29385881, "author": "jjaskulowski", "author_id": 2053494, "author_profile": "https://Stackoverflow.com/users/2053494", "pm_score": 4, "selected": false, "text": "<p>For T-SQL (MSSQL 2008+)</p>\n\n<pre><code>SELECT\n (SELECT\n MAX(MyMaxName) \n FROM ( VALUES \n (MAX(Field1)), \n (MAX(Field2)) \n ) MyAlias(MyMaxName)\n ) \nFROM MyTable1\n</code></pre>\n" }, { "answer_id": 31914496, "author": "danvasiloiu", "author_id": 4424087, "author_profile": "https://Stackoverflow.com/users/4424087", "pm_score": -1, "selected": false, "text": "<p>here is a good solution:</p>\n\n<pre><code>CREATE function [dbo].[inLineMax] (@v1 float,@v2 float,@v3 float,@v4 float)\nreturns float\nas\nbegin\ndeclare @val float\nset @val = 0 \ndeclare @TableVal table\n(value float )\ninsert into @TableVal select @v1\ninsert into @TableVal select @v2\ninsert into @TableVal select @v3\ninsert into @TableVal select @v4\n\nselect @val= max(value) from @TableVal\n\nreturn @val\nend \n</code></pre>\n" }, { "answer_id": 37784473, "author": "claudio", "author_id": 6458642, "author_profile": "https://Stackoverflow.com/users/6458642", "pm_score": -1, "selected": false, "text": "<p>I do not know if it is on SQL, etc... on M$ACCESS help there is a function called <code>MAXA(Value1;Value2;...)</code> that is supposed to do such.</p>\n\n<p>Hope can help someone.</p>\n\n<p>P.D.: Values can be columns or calculated ones, etc.</p>\n" }, { "answer_id": 49515362, "author": "M.A.Bell", "author_id": 8889436, "author_profile": "https://Stackoverflow.com/users/8889436", "pm_score": 0, "selected": false, "text": "<p>Another way to use <strong>CASE WHEN</strong> </p>\n\n<pre><code>SELECT CASE true \n WHEN max(row1) &gt;= max(row2) THEN CASE true WHEN max(row1) &gt;= max(row3) THEN max(row1) ELSE max(row3) end ELSE\n CASE true WHEN max(row2) &gt;= max(row3) THEN max(row2) ELSE max(row3) END END\nFROM yourTable\n</code></pre>\n" }, { "answer_id": 54612018, "author": "Robert Lujo", "author_id": 565525, "author_profile": "https://Stackoverflow.com/users/565525", "pm_score": 1, "selected": false, "text": "<p>I prefer solutions based on case-when, my assumption is that it should have the least impact on possible performance drop compared to other possible solutions like those with cross-apply, values(), custom functions etc.</p>\n\n<p>Here is the case-when version that handles null values with most of possible test cases:</p>\n\n<pre><code>SELECT\n CASE \n WHEN Date1 &gt; coalesce(Date2,'0001-01-01') AND Date1 &gt; coalesce(Date3,'0001-01-01') THEN Date1 \n WHEN Date2 &gt; coalesce(Date3,'0001-01-01') THEN Date2 \n ELSE Date3\n END AS MostRecentDate\n , *\nfrom \n(values\n ( 1, cast('2001-01-01' as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))\n ,( 2, cast('2001-01-01' as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))\n ,( 3, cast('2002-01-01' as Date), cast('2001-01-01' as Date), cast('2003-01-01' as Date))\n ,( 4, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast('2001-01-01' as Date))\n ,( 5, cast('2003-01-01' as Date), cast('2001-01-01' as Date), cast('2002-01-01' as Date))\n ,( 6, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast('2001-01-01' as Date))\n ,( 11, cast(NULL as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))\n ,( 12, cast(NULL as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))\n ,( 13, cast('2003-01-01' as Date), cast(NULL as Date), cast('2002-01-01' as Date))\n ,( 14, cast('2002-01-01' as Date), cast(NULL as Date), cast('2003-01-01' as Date))\n ,( 15, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast(NULL as Date))\n ,( 16, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast(NULL as Date))\n ,( 21, cast('2003-01-01' as Date), cast(NULL as Date), cast(NULL as Date))\n ,( 22, cast(NULL as Date), cast('2003-01-01' as Date), cast(NULL as Date))\n ,( 23, cast(NULL as Date), cast(NULL as Date), cast('2003-01-01' as Date))\n ,( 31, cast(NULL as Date), cast(NULL as Date), cast(NULL as Date))\n\n) as demoValues(id, Date1,Date2,Date3)\norder by id\n;\n</code></pre>\n\n<p>and the result is:</p>\n\n<pre><code>MostRecent id Date1 Date2 Date3\n2003-01-01 1 2001-01-01 2002-01-01 2003-01-01\n2003-01-01 2 2001-01-01 2003-01-01 2002-01-01\n2003-01-01 3 2002-01-01 2001-01-01 2002-01-01\n2003-01-01 4 2002-01-01 2003-01-01 2001-01-01\n2003-01-01 5 2003-01-01 2001-01-01 2002-01-01\n2003-01-01 6 2003-01-01 2002-01-01 2001-01-01\n2003-01-01 11 NULL 2002-01-01 2003-01-01\n2003-01-01 12 NULL 2003-01-01 2002-01-01\n2003-01-01 13 2003-01-01 NULL 2002-01-01\n2003-01-01 14 2002-01-01 NULL 2003-01-01\n2003-01-01 15 2003-01-01 2002-01-01 NULL\n2003-01-01 16 2002-01-01 2003-01-01 NULL\n2003-01-01 21 2003-01-01 NULL NULL\n2003-01-01 22 NULL 2003-01-01 NULL\n2003-01-01 23 NULL NULL 2003-01-01\nNULL 31 NULL NULL NULL\n</code></pre>\n" }, { "answer_id": 60684209, "author": "Brijesh Ray", "author_id": 5284448, "author_profile": "https://Stackoverflow.com/users/5284448", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/peyNn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/peyNn.png\" alt=\"enter image description here\"></a>Above table is an employee salary table with salary1,salary2,salary3,salary4 as columns.Query below will return the max value out of four columns</p>\n\n<pre><code>select \n (select Max(salval) from( values (max(salary1)),(max(salary2)),(max(salary3)),(max(Salary4)))alias(salval)) as largest_val\n from EmployeeSalary\n</code></pre>\n\n<p>Running above query will give output as largest_val(10001)</p>\n\n<p>Logic of above query is as below:</p>\n\n<pre><code>select Max(salvalue) from(values (10001),(5098),(6070),(7500))alias(salvalue)\n</code></pre>\n\n<p>output will be 10001</p>\n" }, { "answer_id": 66815967, "author": "Hemendr", "author_id": 5139020, "author_profile": "https://Stackoverflow.com/users/5139020", "pm_score": 0, "selected": false, "text": "<p>My solution can handle null value comparison as well. It can be simplified by writing as one single query but for an explanation, I am using CTE. The idea is to reduce the comparison from 3 number to 2 number in step 1 and then from 2 number to 1 number in step 2.</p>\n<pre><code>with x1 as\n(\n select 1 as N1, null as N2, 3 as N3\n union\n select 1 as N1, null as N2, null as N3\n union\n select null as N1, null as N2, null as N3\n)\n,x2 as\n(\nselect \nN1,N2,N3,\nIIF(Isnull(N1,0)&gt;=Isnull(N2,0),N1,N2) as max1,\nIIF(Isnull(N2,0)&gt;=Isnull(N3,0),N2,N3) as max2\nfrom x1\n)\n,x3 as\n(\n select N1,N2,N3,max1,max2,\n IIF(IsNull(max1,0)&gt;=IsNull(max2,0),max1,max2) as MaxNo\n from x2\n)\nselect * from x3\n</code></pre>\n<p>Output:</p>\n<p><a href=\"https://i.stack.imgur.com/XcI1W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XcI1W.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 72403229, "author": "gotqn", "author_id": 1080354, "author_profile": "https://Stackoverflow.com/users/1080354", "pm_score": 1, "selected": false, "text": "<p>Finally, for the following:</p>\n<ul>\n<li>SQL Server 2022 (16.x) Preview</li>\n<li>Azure SQL Database</li>\n<li>Azure SQL Managed Instance</li>\n</ul>\n<p>we can use <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=azure-sqldw-latest\" rel=\"nofollow noreferrer\">GREATEST</a>, too. Similar to other T-SQL functions, here are few important notes:</p>\n<ul>\n<li>if all arguments have the same data type and the type is supported for comparison, GREATEST will return that type;</li>\n<li>otherwise, the function will implicitly convert all arguments to the data type of the highest precedence before comparison and use this type as the return type;</li>\n<li>if one or more arguments are not NULL, then NULL arguments will be ignored during comparison; if all arguments are NULL, then GREATEST will return NULL;</li>\n</ul>\n<p>The following types are not supported for comparison in GREATEST: varchar(max), varbinary(max) or nvarchar(max) exceeding 8,000 bytes, cursor, geometry, geography, image, non-byte-ordered user-defined types, ntext, table, text, and xml.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11703/" ]
How do you return 1 value per row of the max of several columns: **TableName** ``` [Number, Date1, Date2, Date3, Cost] ``` I need to return something like this: ``` [Number, Most_Recent_Date, Cost] ``` Query?
This is an old answer and broken in many way. See <https://stackoverflow.com/a/6871572/194653> which has way more upvotes and works with sql server 2008+ and handles nulls, etc. **Original but problematic answer**: Well, you can use the CASE statement: ``` SELECT CASE WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1 WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2 WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3 ELSE Date1 END AS MostRecentDate ```
71,030
<p>I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:</p> <pre><code>mvn install -Dmaven.repository=http://example.com/maven2 </code></pre> <p>The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.</p>
[ { "answer_id": 71132, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>I am not sure if you can do it using the command line. You can on the other hand add repositories in the <strong>pom.xml</strong> as in the following example. Using this approach you do not need to change the <strong>~/.m2/settings.xml</strong> file.</p>\n\n<pre><code> &lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"&gt;\n ...\n &lt;repositories&gt;\n &lt;repository&gt;\n &lt;id&gt;MavenCentral&lt;/id&gt;\n &lt;name&gt;Maven repository&lt;/name&gt;\n &lt;url&gt;http://repo1.maven.org/maven2&lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/snapshots&gt;\n &lt;/repository&gt;\n...\n &lt;repository&gt;\n &lt;id&gt;Codehaus Snapshots&lt;/id&gt;\n &lt;url&gt;http://snapshots.repository.codehaus.org/&lt;/url&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/snapshots&gt;\n &lt;releases&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;/repository&gt;\n &lt;/repositories&gt;\n\n ...\n\n &lt;pluginRepositories&gt;\n &lt;pluginRepository&gt;\n &lt;id&gt;apache.snapshots&lt;/id&gt;\n &lt;name&gt;Apache Snapshot Repository&lt;/name&gt;\n &lt;url&gt;\n http://people.apache.org/repo/m2-snapshot-repository\n &lt;/url&gt;\n &lt;releases&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;/pluginRepository&gt;\n &lt;pluginRepository&gt;\n &lt;id&gt;Codehaus Snapshots&lt;/id&gt;\n &lt;url&gt;http://snapshots.repository.codehaus.org/&lt;/url&gt;\n &lt;snapshots&gt;\n &lt;enabled&gt;true&lt;/enabled&gt;\n &lt;/snapshots&gt;\n &lt;releases&gt;\n &lt;enabled&gt;false&lt;/enabled&gt;\n &lt;/releases&gt;\n &lt;/pluginRepository&gt;\n &lt;/pluginRepositories&gt;\n\n ...\n\n &lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 71179, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 2, "selected": false, "text": "<p>I haven't really used maven 2 before, our system is still working on maven 1.x because of some issues with maven 2.</p>\n\n<p>However, looking at the documentation for maven 2 it seems that there aren't any specific System properties like that. However, you could probably build one into your poms/settings using the System properties. See System properties part of this <a href=\"http://maven.apache.org/settings.html\" rel=\"nofollow noreferrer\">http://maven.apache.org/settings.html</a></p>\n\n<p>So you'd have ${maven.repository} in your settings file and then use the -Dmaven.repository like you do above.</p>\n\n<p>I am unsure as to if this would work, but with some tweaking I am sure you can come up with something.</p>\n" }, { "answer_id": 95559, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 2, "selected": false, "text": "<p>As\n@Jorge Ferreira\nalready said put your repository definitions in the pom.xml. Use <a href=\"http://maven.apache.org/pom.html#Profiles\" rel=\"nofollow noreferrer\">profiles</a> adittionally to select the repository to use via command line:</p>\n\n<pre><code>mvn deploy -P MyRepo2\n\nmvn deploy -P MyRepo1\n</code></pre>\n" }, { "answer_id": 95711, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 1, "selected": false, "text": "<p>Create a POM that has the repository settings that you want and then use a parent element in your project POMs to inherit the additional repositories. The use of an \"organization\" POM has several other benefits when a group of projects belong to one team.</p>\n" }, { "answer_id": 96765, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "<p>One of the goals for Maven't Project Object Model (POM) is to capture all information needed to reliably reproduce an artifact, thus passing settings impacting the artifact creation is strongly discouraged.</p>\n\n<p>To achieve your goal, you can check in your user-level settings.xml file with each project and use the -s (or --settings) option to pass it to the build. </p>\n" }, { "answer_id": 1193664, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 7, "selected": true, "text": "<p>You can do this but you're probably better off doing it in the POM as others have said.</p>\n\n<p>On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though</p>\n\n<p>The example below specifies two remote repositories and a custom local repository.</p>\n\n<pre><code>mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo \n -Dmaven.repo.local=\"c:\\test\\repo\"\n</code></pre>\n" }, { "answer_id": 2031913, "author": "Kevin Wright", "author_id": 165009, "author_profile": "https://Stackoverflow.com/users/165009", "pm_score": 2, "selected": false, "text": "<p>I'll assume here that you're asking this because you occasionally want to add a new 3rd-party repository to your builds. I may be wrong of course... :)</p>\n\n<p>Your best bet in this case is to use a managed proxy such as artifactory or nexus. Then make a one-time change in settings.xml to set this up as a mirror for the world.</p>\n\n<p>Any 3rd party repos that you need to add from that point on can be handled via the proxy.</p>\n" }, { "answer_id": 73148984, "author": "YGXXII", "author_id": 6102698, "author_profile": "https://Stackoverflow.com/users/6102698", "pm_score": 0, "selected": false, "text": "<p>I am using <code>xmlstarlet</code> to achieve this. Tested for Maven 3 on CentOS 7, Maven 2 was not tested yet.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>XML_FULLPATH=&quot;$HOME/.m2/settings.xml&quot;\nMIRROR_ID='example'\nMIRROR_MIRROROF='*'\nMIRROR_NAME='Example Mirror'\nMIRROR_URL='http://example.com/maven2'\n\n\n## Preview settings without comment:\nxmlstarlet ed -d '//comment()' &quot;$XML_FULLPATH&quot;\n\n\n## Add Mirror settings:\nxmlstarlet ed -L \\\n --subnode &quot;/_:settings/_:mirrors&quot; --type elem --name &quot;mirrorTMP&quot; --value &quot;&quot; \\\n --subnode &quot;/_:settings/_:mirrors/mirrorTMP&quot; --type elem --name &quot;id&quot; --value &quot;$MIRROR_ID&quot; \\\n --subnode &quot;/_:settings/_:mirrors/mirrorTMP&quot; --type elem --name &quot;mirrorOf&quot; --value &quot;$MIRROR_MIRROROF&quot; \\\n --subnode &quot;/_:settings/_:mirrors/mirrorTMP&quot; --type elem --name &quot;name&quot; --value &quot;$MIRROR_NAME&quot; \\\n --subnode &quot;/_:settings/_:mirrors/mirrorTMP&quot; --type elem --name &quot;url&quot; --value &quot;$MIRROR_URL&quot; \\\n --rename &quot;/_:settings/_:mirrors/mirrorTMP&quot; --value &quot;mirror&quot; \\\n &quot;$XML_FULLPATH&quot;\n\n\n## Remove Mirror settings by id:\nxmlstarlet ed -L \\\n --delete &quot;/_:settings/_:mirrors/_:mirror[_:id=\\&quot;$MIRROR_ID\\&quot;]&quot; \\\n &quot;$XML_FULLPATH&quot;\n</code></pre>\n<p>The idea is from: <a href=\"https://stackoverflow.com/a/9172796/6102698\">How to insert a new element under another with xmlstarlet?</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113/" ]
I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like: ``` mvn install -Dmaven.repository=http://example.com/maven2 ``` The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.
You can do this but you're probably better off doing it in the POM as others have said. On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though The example below specifies two remote repositories and a custom local repository. ``` mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo -Dmaven.repo.local="c:\test\repo" ```
71,074
<p>I can make Firefox not display the ugly dotted focus outlines on <b>links</b> with this:</p> <pre class="lang-css prettyprint-override"><code>a:focus { outline: none; } </code></pre> <p>But how can I do this for <code>&lt;button&gt;</code> tags as well? When I do this:</p> <pre class="lang-css prettyprint-override"><code>button:focus { outline: none; } </code></pre> <p>the buttons still have the dotted focus outline when I click on them.</p> <p>(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)</p>
[ { "answer_id": 71251, "author": "Vitaly Sharovatov", "author_id": 6647, "author_profile": "https://Stackoverflow.com/users/6647", "pm_score": 3, "selected": false, "text": "<p>There's no way to remove these dotted focus in Firefox using CSS.</p>\n\n<p>If you have access to the computers where your webapplication works, go to about:config in Firefox and set <code>browser.display.focus_ring_width</code> to 0. Then Firefox won't show any dotted borders at all.</p>\n\n<p>The following bug explains the topic: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=74225\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=74225</a></p>\n" }, { "answer_id": 71260, "author": "AlexWilson", "author_id": 2240, "author_profile": "https://Stackoverflow.com/users/2240", "pm_score": 2, "selected": false, "text": "<p>It looks like the only way to achieve this is by setting</p>\n\n<pre><code>browser.display.focus_ring_width = 0\n</code></pre>\n\n<p>in about:config on a per browser basis.</p>\n" }, { "answer_id": 199319, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "<pre class=\"lang-css prettyprint-override\"><code>button::-moz-focus-inner {\n border: 0;\n}\n</code></pre>\n" }, { "answer_id": 857360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You might want to intensify the focus rather than get rid of it.</p>\n\n<pre><code>button::-moz-focus-inner {border: 2px solid transparent;}\n\nbutton:focus::-moz-focus-inner {border-color: blue} \n</code></pre>\n" }, { "answer_id": 1095624, "author": "Flatline", "author_id": 134628, "author_profile": "https://Stackoverflow.com/users/134628", "pm_score": 2, "selected": false, "text": "<p>I think you should really know what you're doing by removing the focus outline, because it can mess it up for keyboard navigation and accessibility.</p>\n\n<p>If you need to take it out because of a design issue, add a <code>:focus</code> state to the button that replaces this with some other visual cue, like, changing the border to a brighter color or something like that.</p>\n\n<p>Sometimes I feel the need to take that annoying outline out, but I always prepare an alternate focus visual cue.</p>\n\n<p>And <strong>never</strong> use the <code>blur()</code> js function. Use the <code>::-moz-focus-inner</code> pseudo class.</p>\n" }, { "answer_id": 1622384, "author": "chinkchink", "author_id": 196344, "author_profile": "https://Stackoverflow.com/users/196344", "pm_score": 6, "selected": false, "text": "<p>If you prefer to use CSS to get rid of the dotted outline:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/*for FireFox*/\n input[type=\"submit\"]::-moz-focus-inner, input[type=\"button\"]::-moz-focus-inner\n { \n border : 0;\n } \n/*for IE8 and below */\n input[type=\"submit\"]:focus, input[type=\"button\"]:focus\n { \n outline : none; \n }\n</code></pre>\n" }, { "answer_id": 1750468, "author": "wavded", "author_id": 47158, "author_profile": "https://Stackoverflow.com/users/47158", "pm_score": 2, "selected": false, "text": "<pre><code>button::-moz-focus-inner { border: 0; }\n</code></pre>\n\n<p>Where <code>button</code> can be whatever CSS selector for which you want to disable the behavior.</p>\n" }, { "answer_id": 2021783, "author": "usual", "author_id": 245688, "author_profile": "https://Stackoverflow.com/users/245688", "pm_score": 0, "selected": false, "text": "<p>You can try <code>button::-moz-focus-inner {border: 0px solid transparent;}</code> in your CSS.</p>\n" }, { "answer_id": 3129247, "author": "blizzyx", "author_id": 377621, "author_profile": "https://Stackoverflow.com/users/377621", "pm_score": 5, "selected": false, "text": "<pre class=\"lang-css prettyprint-override\"><code>:focus, :active {\n outline: 0;\n border: 0;\n}\n</code></pre>\n" }, { "answer_id": 3844452, "author": "Anderson Custódio", "author_id": 464428, "author_profile": "https://Stackoverflow.com/users/464428", "pm_score": 8, "selected": false, "text": "<p>No need to define a selector.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>:focus {outline:none;}\n::-moz-focus-inner {border:0;}\n</code></pre>\n\n<p>However, this violates accessibility best practices from the W3C. The outline is there to help those navigating with keyboards.</p>\n\n<p><a href=\"https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples\" rel=\"noreferrer\">https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples</a></p>\n" }, { "answer_id": 6635075, "author": "Dave Everitt", "author_id": 123033, "author_profile": "https://Stackoverflow.com/users/123033", "pm_score": 2, "selected": false, "text": "<p>If you have a border on a button and want to hide the dotted outline in Firefox <em>without</em> removing the border (and hence it's extra width on the button) you can use:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.button::-moz-focus-inner {\n border-color: transparent;\n}\n</code></pre>\n" }, { "answer_id": 7628310, "author": "foxybagga", "author_id": 95350, "author_profile": "https://Stackoverflow.com/users/95350", "pm_score": 5, "selected": false, "text": "<p>The below worked for me in case of LINKS, thought of sharing - in case someone is interested. </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>a, a:visited, a:focus, a:active, a:hover{\n outline:0 none !important;\n}\n</code></pre>\n\n<p>Cheers!</p>\n" }, { "answer_id": 15608143, "author": "Shannon Hochkins", "author_id": 1683943, "author_profile": "https://Stackoverflow.com/users/1683943", "pm_score": 3, "selected": false, "text": "<p>There is many solutions found on the web for this, many of which work, but to force this, so that absolutely nothing can highlight/focus once a use the following:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>::-moz-focus-inner, :active, :focus {\n outline:none;\n border:0;\n -moz-outline-style: none;\n}\n</code></pre>\n\n<p>This just adds that little bit extra security &amp; seals the deal!</p>\n" }, { "answer_id": 18993053, "author": "Renato Carvalho", "author_id": 925560, "author_profile": "https://Stackoverflow.com/users/925560", "pm_score": 3, "selected": false, "text": "<p>[Update] This solution doesn't work anymore. The solution that worked for me is this one <a href=\"https://stackoverflow.com/a/3844452/925560\">https://stackoverflow.com/a/3844452/925560</a></p>\n\n<p><strong>The answer marked as correct didn't work with Firefox 24.0.</strong></p>\n\n<p>To remove Firefox's dotted outline on buttons and anchor tags I added the code below:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>a:focus, a:active, \nbutton::-moz-focus-inner,\ninput[type=\"reset\"]::-moz-focus-inner,\ninput[type=\"button\"]::-moz-focus-inner,\ninput[type=\"submit\"]::-moz-focus-inner,\nselect::-moz-focus-inner,\ninput[type=\"file\"] &gt; input[type=\"button\"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n\n<p>I found the solution here: <a href=\"http://aghoshb.com/articles/css-how-to-remove-firefoxs-dotted-outline-on-buttons-and-anchor-tags.html\" rel=\"nofollow noreferrer\">http://aghoshb.com/articles/css-how-to-remove-firefoxs-dotted-outline-on-buttons-and-anchor-tags.html</a></p>\n" }, { "answer_id": 20731378, "author": "Fizer Khan", "author_id": 1154350, "author_profile": "https://Stackoverflow.com/users/1154350", "pm_score": 2, "selected": false, "text": "<p>Remove dotted outline from links, button and input element.</p>\n\n<pre><code>a:focus, a:active,\nbutton::-moz-focus-inner,\ninput[type=\"reset\"]::-moz-focus-inner,\ninput[type=\"button\"]::-moz-focus-inner,\ninput[type=\"submit\"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n" }, { "answer_id": 20833484, "author": "DPP", "author_id": 1766855, "author_profile": "https://Stackoverflow.com/users/1766855", "pm_score": 1, "selected": false, "text": "<p>This works on firefox v-27.0</p>\n\n<pre><code> .buttonClassName:focus {\n outline:none;\n}\n</code></pre>\n" }, { "answer_id": 24791473, "author": "Vartox", "author_id": 2366511, "author_profile": "https://Stackoverflow.com/users/2366511", "pm_score": 3, "selected": false, "text": "<p>Tried most of the answers here, but none of them worked for me. When I realized that I have to get rid of the blue outline on buttons on Chrome too, I found another solution. <a href=\"https://stackoverflow.com/questions/20340138/remove-blue-border-from-css-custom-styled-button-in-chrome\">Remove blue border from css custom-styled button in Chrome</a></p>\n\n<p>This code worked for me on Firefox version 30 on Windows 7. Perhaps it might help somebody else out there :)</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>button:focus {outline:0 !important;}\n</code></pre>\n" }, { "answer_id": 31893576, "author": "herci", "author_id": 3294466, "author_profile": "https://Stackoverflow.com/users/3294466", "pm_score": 2, "selected": false, "text": "<p>In most cases without adding the <strong><code>!important</code></strong> to the CSS code, it won't work.</p>\n\n<h2>So, do not forget to add <code>!important</code></h2>\n\n<pre><code>a, a:active, a:focus{\n outline: none !important; /* Works in Firefox, Chrome, IE8 and above */\n}\n</code></pre>\n\n<p><br>\nOr any other code:</p>\n\n<pre><code>button::-moz-focus-inner {\n border: 0 !important;\n}\n</code></pre>\n" }, { "answer_id": 36897437, "author": "Madan Sapkota", "author_id": 782535, "author_profile": "https://Stackoverflow.com/users/782535", "pm_score": 3, "selected": false, "text": "<p>Tested on Firefox 46 and Chrome 49 using this code.</p>\n<pre><code>input:focus, textarea:focus, button:focus {\n outline: none !important;\n}\n</code></pre>\n<p><strong>Before</strong> (white dots are visible )</p>\n<p><a href=\"https://i.stack.imgur.com/1hP1m.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1hP1m.png\" alt=\"input with white dots\" /></a></p>\n<p><strong>After</strong> ( White dots are invisible )\n<a href=\"https://i.stack.imgur.com/62tZV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/62tZV.png\" alt=\"enter image description here\" /></a></p>\n<p>If you want to apply only on few input fields, buttons etc. Use the more specific code.</p>\n<pre><code>input[type=text] {\n outline: none !important;\n}\n</code></pre>\n" }, { "answer_id": 37482092, "author": "Syed Waqas Bukhary", "author_id": 3633267, "author_profile": "https://Stackoverflow.com/users/3633267", "pm_score": 1, "selected": false, "text": "<p>After trying many options from the above only the following worked for me.</p>\n\n<pre><code>*:focus, *:visited, *:active, *:hover { outline:0 !important;}\n*::-moz-focus-inner {border:0;}\n</code></pre>\n" }, { "answer_id": 37717454, "author": "Ehsan88", "author_id": 2571422, "author_profile": "https://Stackoverflow.com/users/2571422", "pm_score": 1, "selected": false, "text": "<p>Along with Bootstrap 3 I used this code. The second set of rules just <em>undo</em> what bootstrap does for focus/active buttons:</p>\n\n<pre><code>button::-moz-focus-inner {\n border: 0; /*removes dotted lines around buttons*/\n}\n\n.btn.active.focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn:active:focus, .btn:focus{\n outline:0;\n}\n</code></pre>\n\n<p><strong>NOTE that your custom css file should come after Bootstrap css file in your html code to override it.</strong></p>\n" }, { "answer_id": 38766296, "author": "kurumkan", "author_id": 5714544, "author_profile": "https://Stackoverflow.com/users/5714544", "pm_score": 2, "selected": false, "text": "<p>The CSS code below works to remove this:</p>\n\n<pre><code>a:focus, a:active, \nbutton::-moz-focus-inner,\ninput[type=\"reset\"]::-moz-focus-inner,\ninput[type=\"button\"]::-moz-focus-inner,\ninput[type=\"submit\"]::-moz-focus-inner,\nselect::-moz-focus-inner,\ninput[type=\"file\"] &gt; input[type=\"button\"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n" }, { "answer_id": 41631535, "author": "Abhay Singh", "author_id": 2063930, "author_profile": "https://Stackoverflow.com/users/2063930", "pm_score": 3, "selected": false, "text": "<p>Simply add this css for select box </p>\n\n<pre><code>select:-moz-focusring {\n color: transparent;\n text-shadow: 0 0 0 #000;\n}\n</code></pre>\n\n<p>This is working fine for me.</p>\n" }, { "answer_id": 47195132, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": 3, "selected": false, "text": "<p>This will get the range control:</p>\n\n<pre><code>:focus {\n outline:none;\n}\n::-moz-focus-inner {\n border:0;\n}\ninput[type=range]::-moz-focus-outer {\n border: 0;\n}\n</code></pre>\n\n<p>From: <a href=\"https://stackoverflow.com/questions/18794026/remove-dotted-outline-from-range-input-element-in-firefox\">Remove dotted outline from range input element in Firefox</a></p>\n" }, { "answer_id": 55434025, "author": "Riwaj Chalise", "author_id": 10003098, "author_profile": "https://Stackoverflow.com/users/10003098", "pm_score": 1, "selected": false, "text": "<p>Yep don't miss <strong>!important</strong></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>button::-moz-focus-inner {\n border: 0 !important;\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
I can make Firefox not display the ugly dotted focus outlines on **links** with this: ```css a:focus { outline: none; } ``` But how can I do this for `<button>` tags as well? When I do this: ```css button:focus { outline: none; } ``` the buttons still have the dotted focus outline when I click on them. (and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)
```css button::-moz-focus-inner { border: 0; } ```
71,108
<p>Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in <code>Foo **</code>) in C++?</p>
[ { "answer_id": 71143, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "<p>IMO most common usage is to pass reference to pointer variable</p>\n\n<pre><code>void test(int ** var)\n{\n ...\n}\n\nint *foo = ...\ntest(&amp;foo);\n</code></pre>\n\n<p>You can create multidimensional jagged array using double pointers: </p>\n\n<pre><code>int ** array = new *int[2];\narray[0] = new int[2];\narray[1] = new int[3];\n</code></pre>\n" }, { "answer_id": 71154, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 2, "selected": false, "text": "<p>If you pass a pointer in as output parameter, you might want to pass it as <code>Foo**</code> and set its value as <code>*ppFoo = pSomeOtherFoo</code>.</p>\n\n<p>And from the algorithms-and-data-structures department, you can use that double indirection to update pointers, which can be faster than for instance swapping actual objects.</p>\n" }, { "answer_id": 71160, "author": "dudico", "author_id": 11089, "author_profile": "https://Stackoverflow.com/users/11089", "pm_score": 1, "selected": false, "text": "<p>A simple example would be using <code>int** foo_mat</code> as a 2d array of integers.\nOr you may also use pointers to pointers - lets say that you have a pointer <code>void* foo</code> and you have 2 different objects that have a reference to it with the following members: <code>void** foo_pointer1</code> and <code>void** foo_pointer2</code>, by having a pointer to a pointer you can actually check whether <code>*foo_pointer1 == NULL</code> which indicates that foo is NULL. You wouldn't be able to check whether foo is NULL if foo_pointer1 was a regular pointer.\nI hope that my explanation wasn't too messy :)</p>\n" }, { "answer_id": 71164, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "<p>Usually when you pass a pointer to a function as a return value:</p>\n\n<pre><code>ErrorCode AllocateObject (void **object);\n</code></pre>\n\n<p>where the function returns a success/failure error code and fills in the object parameter with a pointer to the new object:</p>\n\n<pre><code>*object = new Object;\n</code></pre>\n\n<p>This is used a lot in COM programming in Win32.</p>\n\n<p>This is more of a C thing to do, in C++ you can often wrap this type of system into a class to make the code more readable.</p>\n" }, { "answer_id": 71175, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 1, "selected": false, "text": "<p>Carl: Your example should be:</p>\n\n<pre><code>*p = x;\n</code></pre>\n\n<p>(You have two stars.) :-)</p>\n" }, { "answer_id": 71250, "author": "John B", "author_id": 11773, "author_profile": "https://Stackoverflow.com/users/11773", "pm_score": 3, "selected": false, "text": "<p>One common scenario is where you need to pass a <strong>null</strong> pointer to a function, and have it initialized within that function, and used outside the function. Without multplie indirection, the calling function would never have access to the initialized object.</p>\n\n<p>Consider the following function:</p>\n\n<pre><code>initialize(foo* my_foo)\n{\n my_foo = new Foo();\n}\n</code></pre>\n\n<p>Any function that calls 'initialize(foo*)' will not have access to the initialized instance of <strong>Foo</strong>, beacuse the pointer that's passed to this function is a copy. (The pointer is just an integer after all, and integers are passed by value.)</p>\n\n<p>However, if the function was defined like this:</p>\n\n<pre><code>initialize(foo** my_foo)\n{\n *my_foo = new Foo();\n}\n</code></pre>\n\n<p>...and it was called like this...</p>\n\n<pre><code>Foo* my_foo;\n\ninitialize(&amp;my_foo);\n</code></pre>\n\n<p>...then the caller would have access to the initialized instance, via 'my_foo' - because it's the <em>address</em> of the pointer that was passed to 'initialize'. </p>\n\n<p>Of course, in my simplified example, the 'initialize' function could simply return the newly created instance via the return keyword, but that does not always suit - maybe the function needs to return something else.</p>\n" }, { "answer_id": 71298, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "<p>Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nstruct Foo {\n int a;\n};\n\nvoid CreateFoo(Foo** p) {\n *p = new Foo();\n (*p)-&gt;a = 12;\n}\n\nint main(int argc, char* argv[])\n{\n Foo* p = NULL;\n CreateFoo(&amp;p);\n cout &lt;&lt; p-&gt;a &lt;&lt; endl;\n delete p;\n return 0;\n}\n</code></pre>\n\n<p>This will print</p>\n\n<pre><code>12\n</code></pre>\n\n<p>But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n const char* words[] = { \"first\", \"second\", NULL };\n for (const char** p = words; *p != NULL; ++p) {\n cout &lt;&lt; *p &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 73382, "author": "mlbrock", "author_id": 9966, "author_profile": "https://Stackoverflow.com/users/9966", "pm_score": 1, "selected": false, "text": "<p>In C, the idiom is absolutely required. Consider the problem in which you want a function to add a string (pure C, so a char *) to an array of pointers to char *. The function prototype requires three levels of indirection:</p>\n\n<pre><code>int AddStringToList(unsigned int *count_ptr, char ***list_ptr, const char *string_to_add);\n</code></pre>\n\n<p>We call it as follows:</p>\n\n<pre><code>unsigned int the_count = 0;\nchar **the_list = NULL;\n\nAddStringToList(&amp;the_count, &amp;the_list, \"The string I'm adding\");\n</code></pre>\n\n<p>In C++ we have the option of using references instead, which would yield a different signature. But we still need the two levels of indirection you asked about in your original question:</p>\n\n<pre><code>int AddStringToList(unsigned int &amp;count_ptr, char **&amp;list_ptr, const char *string_to_add);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in `Foo **`) in C++?
Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns. ``` #include <iostream> using namespace std; struct Foo { int a; }; void CreateFoo(Foo** p) { *p = new Foo(); (*p)->a = 12; } int main(int argc, char* argv[]) { Foo* p = NULL; CreateFoo(&p); cout << p->a << endl; delete p; return 0; } ``` This will print ``` 12 ``` But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output. ``` #include <iostream> using namespace std; int main(int argc, char* argv[]) { const char* words[] = { "first", "second", NULL }; for (const char** p = words; *p != NULL; ++p) { cout << *p << endl; } return 0; } ```
71,118
<p>I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like,</p> <pre><code>'guid' is null or not an object on line 1834 </code></pre> <p>Do you have any idea ?</p>
[ { "answer_id": 71269, "author": "Wouter Lievens", "author_id": 7927, "author_profile": "https://Stackoverflow.com/users/7927", "pm_score": 0, "selected": false, "text": "<p>Maybe you're using the parentNode or parentElement property? There are some issues with that in IE vs other browsers.</p>\n" }, { "answer_id": 71477, "author": "jatanp", "author_id": 959, "author_profile": "https://Stackoverflow.com/users/959", "pm_score": 2, "selected": false, "text": "<p>Thanks guys for your messages.</p>\n\n<p>The error was on my part. For hover event, I was not passing function for \"out\". Therefore the handler was passed as undefined in jQuery.event function and that causing error for statement ,</p>\n\n<p>if ( !handler.guid )</p>\n\n<p>written at 1834 line of jquery-1.2.6.js file.</p>\n\n<p>While using I thought that out handler is not mandatory to specify, but I guess I am wrong.</p>\n\n<p>Strangely, FF / Chrome does not prompt error but IE does :) which is bit different than what it used to be.</p>\n\n<p>Regards,\nJatan</p>\n" }, { "answer_id": 71511, "author": "jatanp", "author_id": 959, "author_profile": "https://Stackoverflow.com/users/959", "pm_score": 0, "selected": false, "text": "<p>Sorry, FF / Chrome both report this error but in very silent way. You need to go to Firefox 3.0 Javascript errors dialog to see if is there any error and for Chrome you need to go to Javascript console.</p>\n\n<p>In my view, there should be at least some UI indications (like icon would turn RED), for such errors in FF 3.0 as well as Chrome. In FF 2.0, I guess the icon was turning to RED CROSS if any error is there but it does not happen in FF 3.0 !</p>\n" }, { "answer_id": 71675, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 2, "selected": false, "text": "<p>Firefox removed the javascript error indication by default because there are a lot of pages that throw javascript errors. To an average user, the error messages aren't useful - only confusing. If you are a web developer, you should definitely install <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">Firebug</a>.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like, ``` 'guid' is null or not an object on line 1834 ``` Do you have any idea ?
Thanks guys for your messages. The error was on my part. For hover event, I was not passing function for "out". Therefore the handler was passed as undefined in jQuery.event function and that causing error for statement , if ( !handler.guid ) written at 1834 line of jquery-1.2.6.js file. While using I thought that out handler is not mandatory to specify, but I guess I am wrong. Strangely, FF / Chrome does not prompt error but IE does :) which is bit different than what it used to be. Regards, Jatan
71,151
<p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html" rel="noreferrer">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
[ { "answer_id": 71161, "author": "1077", "author_id": 10776, "author_profile": "https://Stackoverflow.com/users/10776", "pm_score": 5, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>import HTMLParser\n</code></pre>\n\n<p>In Python 3.0, the HTMLParser module has been renamed to html.parser\nyou can check about this <a href=\"http://docs.python.org/library/htmlparser.html\" rel=\"noreferrer\">here</a></p>\n\n<p>Python 3.0</p>\n\n<pre><code>import html.parser\n</code></pre>\n\n<p>Python 2.2 and above</p>\n\n<pre><code>import HTMLParser\n</code></pre>\n" }, { "answer_id": 71168, "author": "Vytautas Šaltenis", "author_id": 6763, "author_profile": "https://Stackoverflow.com/users/6763", "pm_score": 1, "selected": false, "text": "<p>There's a link to an example on the bottom of (<a href=\"http://docs.python.org/2/library/htmlparser.html\" rel=\"nofollow noreferrer\">http://docs.python.org/2/library/htmlparser.html</a>) , it just doesn't work with the original python or python3. It has to be python2 as it says on the top.</p>\n" }, { "answer_id": 71174, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "<p>You probably really want <a href=\"https://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424\">BeautifulSoup</a>, check the link for an example. </p>\n\n<p>But in any case</p>\n\n<pre><code>&gt;&gt;&gt; import HTMLParser\n&gt;&gt;&gt; h = HTMLParser.HTMLParser()\n&gt;&gt;&gt; h.feed('&lt;html&gt;&lt;/html&gt;')\n&gt;&gt;&gt; h.get_starttag_text()\n'&lt;html&gt;'\n&gt;&gt;&gt; h.close()\n</code></pre>\n" }, { "answer_id": 71176, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 2, "selected": false, "text": "<p>I would recommend using <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">Beautiful Soup</a> module instead and it has <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html\" rel=\"nofollow noreferrer\">good documentation</a>.</p>\n" }, { "answer_id": 71186, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 1, "selected": false, "text": "<p>For real world HTML processing I'd recommend <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a>. It is great and takes away much of the pain. Installation is easy.</p>\n" }, { "answer_id": 71614, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 2, "selected": false, "text": "<p>You should also look at <a href=\"http://code.google.com/p/html5lib/\" rel=\"nofollow noreferrer\">html5lib</a> for Python as it tries to parse HTML in a way that very much resembles what web browsers do, especially when dealing with invalid HTML (which is more than 90% of today's web).</p>\n" }, { "answer_id": 72100, "author": "1077", "author_id": 10776, "author_profile": "https://Stackoverflow.com/users/10776", "pm_score": 2, "selected": false, "text": "<p>I don't recommend BeautifulSoup if you want speed. lxml is much, much faster, and you can fall back in lxml's BS soupparser if the default parser doesn't work.</p>\n" }, { "answer_id": 82117, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 2, "selected": false, "text": "<p>You may be interested in <a href=\"http://codespeak.net/lxml/\" rel=\"nofollow noreferrer\">lxml</a>. It is a separate package and has C components, but is the fastest. It has also very nice API, allowing you to easily list links in HTML documents, or list forms, sanitize HTML, and more. It also has capabilities to parse not well-formed HTML (it's configurable).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).
Try: ``` import HTMLParser ``` In Python 3.0, the HTMLParser module has been renamed to html.parser you can check about this [here](http://docs.python.org/library/htmlparser.html) Python 3.0 ``` import html.parser ``` Python 2.2 and above ``` import HTMLParser ```
71,157
<p>I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'.</p> <p>However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra).</p> <p>"Google may know, but if it does, it ain't telling, or I'm not looking in the right place"</p> <p><strong>UPDATE:</strong></p> <p>It seems to work with latest CTP <a href="http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&amp;displaylang=en" rel="nofollow noreferrer">update 1.9.6.2</a></p> <p><strong>UPDATE2:</strong></p> <p>I have since experienced another error: </p> <pre><code>FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities. </code></pre> <p>If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project.</p>
[ { "answer_id": 71200, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>F# manual: <a href=\"http://research.microsoft.com/fsharp/manual/compiler.aspx#Standalone\" rel=\"nofollow noreferrer\">Statically linking the F# library using \"--standalone\"</a></p>\n\n<p>Did you try to run peverify.exe utility?</p>\n" }, { "answer_id": 71938, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 3, "selected": true, "text": "<p>Answer from MS:</p>\n\n<p><em>There is a CTP update 1.9.6.2 that fixed some --standalone bugs.</em></p>\n\n<p>I'm reinstalling now...</p>\n\n<p>UPDATE:\nWorks for me - so the my accepted answer is <strong>download CTP update 1.9.6.2</strong>.</p>\n" }, { "answer_id": 901597, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 1, "selected": false, "text": "<p>This has been a pet hatred of mine for a long time (it has been broken in every CTP release ever including the latest 1.9.6.16 May 2009 release). The \"solution\" is essentially to write your own build system that is not broken.</p>\n\n<p>This is a real problem for me because I have accumulated hundreds of great F# programs that I would like to put on our site but it takes hours to build each one into a standalone executable.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'. However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra). "Google may know, but if it does, it ain't telling, or I'm not looking in the right place" **UPDATE:** It seems to work with latest CTP [update 1.9.6.2](http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&displaylang=en) **UPDATE2:** I have since experienced another error: ``` FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities. ``` If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project.
Answer from MS: *There is a CTP update 1.9.6.2 that fixed some --standalone bugs.* I'm reinstalling now... UPDATE: Works for me - so the my accepted answer is **download CTP update 1.9.6.2**.
71,180
<p>How can I find the last row that contains data in a specific column and on a specific sheet?</p>
[ { "answer_id": 71197, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": -1, "selected": false, "text": "<pre><code>Function LastRow(rng As Range) As Long\n Dim iRowN As Long\n Dim iRowI As Long\n Dim iColN As Integer\n Dim iColI As Integer\n iRowN = 0\n iColN = rng.Columns.count\n For iColI = 1 To iColN\n iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row\n If iRowI &gt; iRowN Then iRowN = iRowI\n Next\n LastRow = iRowN\nEnd Function \n</code></pre>\n" }, { "answer_id": 71296, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 3, "selected": false, "text": "<pre><code>function LastRowIndex(byval w as worksheet, byval col as variant) as long\n dim r as range\n\n set r = application.intersect(w.usedrange, w.columns(col))\n if not r is nothing then\n set r = r.cells(r.cells.count)\n\n if isempty(r.value) then\n LastRowIndex = r.end(xlup).row\n else\n LastRowIndex = r.row\n end if\n end if\nend function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>? LastRowIndex(ActiveSheet, 5)\n? LastRowIndex(ActiveSheet, \"AI\")\n</code></pre>\n" }, { "answer_id": 71310, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 7, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>Function GetLastRow(strSheet, strColumn) As Long\n Dim MyRange As Range\n\n Set MyRange = Worksheets(strSheet).Range(strColumn &amp; \"1\")\n GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row\nEnd Function\n</code></pre>\n\n<p>Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:</p>\n\n<pre><code>Cells.Find(\"*\", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row\n</code></pre>\n" }, { "answer_id": 71349, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": -1, "selected": false, "text": "<p>The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.</p>\n\n<pre><code>Selection.End(xlDown).Select\nMsgBox(ActiveCell.Row)\n</code></pre>\n" }, { "answer_id": 73489, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 4, "selected": false, "text": "<p>You should use the <code>.End(xlup)</code> but instead of using 65536 you might want to use:</p>\n\n<pre><code>sheetvar.Rows.Count\n</code></pre>\n\n<p>That way it works for Excel 2007 which I believe has more than 65536 rows</p>\n" }, { "answer_id": 74282, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 2, "selected": false, "text": "<pre><code>Public Function LastData(rCol As Range) As Range \n Set LastData = rCol.Find(\"*\", rCol.Cells(1), , , , xlPrevious) \nEnd Function\n</code></pre>\n\n<p>Usage: <code>?lastdata(activecell.EntireColumn).Address</code></p>\n" }, { "answer_id": 962530, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here's a solution for finding the last row, last column, or last cell. It addresses the A1 R1C1 Reference Style dilemma for the column it finds. Wish I could give credit, but can't find/remember where I got it from, so \"Thanks!\" to whoever it was that posted the original code somewhere out there.</p>\n\n<pre><code>Sub Macro1\n Sheets(\"Sheet1\").Select\n MsgBox \"The last row found is: \" &amp; Last(1, ActiveSheet.Cells)\n MsgBox \"The last column (R1C1) found is: \" &amp; Last(2, ActiveSheet.Cells)\n MsgBox \"The last cell found is: \" &amp; Last(3, ActiveSheet.Cells)\n MsgBox \"The last column (A1) found is: \" &amp; Last(4, ActiveSheet.Cells)\nEnd Sub\n\nFunction Last(choice As Integer, rng As Range)\n' 1 = last row\n' 2 = last column (R1C1)\n' 3 = last cell\n' 4 = last column (A1)\n Dim lrw As Long\n Dim lcol As Integer\n\n Select Case choice\n Case 1:\n On Error Resume Next\n Last = rng.Find(What:=\"*\", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Row\n On Error GoTo 0\n\n Case 2:\n On Error Resume Next\n Last = rng.Find(What:=\"*\", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n On Error GoTo 0\n\n Case 3:\n On Error Resume Next\n lrw = rng.Find(What:=\"*\", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Row\n lcol = rng.Find(What:=\"*\", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n Last = Cells(lrw, lcol).Address(False, False)\n If Err.Number &gt; 0 Then\n Last = rng.Cells(1).Address(False, False)\n Err.Clear\n End If\n On Error GoTo 0\n Case 4:\n On Error Resume Next\n Last = rng.Find(What:=\"*\", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n On Error GoTo 0\n Last = R1C1converter(\"R1C\" &amp; Last, 1)\n For i = 1 To Len(Last)\n s = Mid(Last, i, 1)\n If Not s Like \"#\" Then s1 = s1 &amp; s\n Next i\n Last = s1\n\n End Select\n\nEnd Function\n\nFunction R1C1converter(Address As String, Optional R1C1_output As Integer, Optional RefCell As Range) As String\n 'Converts input address to either A1 or R1C1 style reference relative to RefCell\n 'If R1C1_output is xlR1C1, then result is R1C1 style reference.\n 'If R1C1_output is xlA1 (or missing), then return A1 style reference.\n 'If RefCell is missing, then the address is relative to the active cell\n 'If there is an error in conversion, the function returns the input Address string\n Dim x As Variant\n If RefCell Is Nothing Then Set RefCell = ActiveCell\n If R1C1_output = xlR1C1 Then\n x = Application.ConvertFormula(Address, xlA1, xlR1C1, , RefCell) 'Convert A1 to R1C1\n Else\n x = Application.ConvertFormula(Address, xlR1C1, xlA1, , RefCell) 'Convert R1C1 to A1\n End If\n If IsError(x) Then\n R1C1converter = Address\n Else\n 'If input address is A1 reference and A1 is requested output, then Application.ConvertFormula\n 'surrounds the address in single quotes.\n If Right(x, 1) = \"'\" Then\n R1C1converter = Mid(x, 2, Len(x) - 2)\n Else\n x = Application.Substitute(x, \"$\", \"\")\n R1C1converter = x\n End If\n End If\nEnd Function\n</code></pre>\n" }, { "answer_id": 25509398, "author": "user2988717", "author_id": 2988717, "author_profile": "https://Stackoverflow.com/users/2988717", "pm_score": 3, "selected": false, "text": "<p>Simple and quick:</p>\n\n<pre><code>Dim lastRow as long\nRange(\"A1\").select\nlastRow = Cells.Find(\"*\",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code>cells(lastRow,1)=\"Ultima Linha, Last Row. Youpi!!!!\"\n\n'or \n\nRange(\"A\" &amp; lastRow).Value = \"FIM, THE END\"\n</code></pre>\n" }, { "answer_id": 33434570, "author": "Ashwith Ullal", "author_id": 1534035, "author_profile": "https://Stackoverflow.com/users/1534035", "pm_score": -1, "selected": false, "text": "<pre><code>Sub test()\n MsgBox Worksheets(\"sheet_name\").Range(\"A65536\").End(xlUp).Row\nEnd Sub\n</code></pre>\n\n<p>This is looking for a value in column <code>A</code> because of <code>\"A65536\"</code>.</p>\n" }, { "answer_id": 35975280, "author": "Stupid_Intern", "author_id": 5398127, "author_profile": "https://Stackoverflow.com/users/5398127", "pm_score": 0, "selected": false, "text": "<p>I would like to add one more reliable way using <code>UsedRange</code> to find the last used row:</p>\n\n<pre><code>lastRow = Sheet1.UsedRange.Row + Sheet1.UsedRange.Rows.Count - 1\n</code></pre>\n\n<p>Similarly to find the last used column you can <a href=\"https://stackoverflow.com/questions/11926972/excel-vba-finding-the-last-column-with-data/35945397#35945397\">see this</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/46aa0.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/46aa0.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Result in Immediate Window:</p>\n\n<pre><code>?Sheet1.UsedRange.Row+Sheet1.UsedRange.Rows.Count-1\n 21 \n</code></pre>\n" }, { "answer_id": 46419169, "author": "Phaithoon Jariyanantakul", "author_id": 8674380, "author_profile": "https://Stackoverflow.com/users/8674380", "pm_score": 0, "selected": false, "text": "<pre><code>Public Function GetLastRow(ByVal SheetName As String) As Integer\n Dim sht As Worksheet\n Dim FirstUsedRow As Integer 'the first row of UsedRange\n Dim UsedRows As Integer ' number of rows used\n\n Set sht = Sheets(SheetName)\n ''UsedRange.Rows.Count for the empty sheet is 1\n UsedRows = sht.UsedRange.Rows.Count\n FirstUsedRow = sht.UsedRange.Row\n GetLastRow = FirstUsedRow + UsedRows - 1\n\n Set sht = Nothing\nEnd Function\n</code></pre>\n\n<p>sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used</p>\n\n<p>if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.</p>\n\n<p>This function calculate the first row number of UsedRange plus number of UsedRange rows.</p>\n" }, { "answer_id": 49971492, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 2, "selected": false, "text": "<p>All the solutions relying on built-in behaviors (like <code>.Find</code> and <code>.End</code>) have limitations that are not well-documented (see <a href=\"https://stackoverflow.com/a/49971540/1026\">my other answer</a> for details).</p>\n\n<p>I needed something that:</p>\n\n<ul>\n<li>Finds the last <strong>non-empty</strong> cell (i.e. that has <em>any formula or value</em>, even if it's an empty string) in a <strong>specific column</strong></li>\n<li>Relies on primitives with well-defined behavior</li>\n<li>Works reliably with autofilters and user modifications</li>\n<li>Runs as fast as possible on 10,000 rows (to be run in a <code>Worksheet_Change</code> handler without feeling sluggish)</li>\n<li>...with performance not falling off a cliff with accidental data or formatting put at the very end of the sheet (at ~1M rows)</li>\n</ul>\n\n<p>The solution below:</p>\n\n<ul>\n<li>Uses <code>UsedRange</code> to find the upper bound for the row number (to make the search for the true \"last row\" fast in the common case where it's close to the end of the used range);</li>\n<li>Goes backwards to find the row with data in the given column;</li>\n<li>...using VBA arrays to avoid accessing each row individually (in case there are many rows in the <code>UsedRange</code> we need to skip)</li>\n</ul>\n\n<p>(No tests, sorry)</p>\n\n<pre><code>' Returns the 1-based row number of the last row having a non-empty value in the given column (0 if the whole column is empty)\nPrivate Function getLastNonblankRowInColumn(ws As Worksheet, colNo As Integer) As Long\n ' Force Excel to recalculate the \"last cell\" (the one you land on after CTRL+END) / \"used range\"\n ' and get the index of the row containing the \"last cell\". This is reasonably fast (~1 ms/10000 rows of a used range)\n Dim lastRow As Long: lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row - 1 ' 0-based\n\n ' Since the \"last cell\" is not necessarily the one we're looking for (it may be in a different column, have some\n ' formatting applied but no value, etc), we loop backward from the last row towards the top of the sheet).\n Dim wholeRng As Range: Set wholeRng = ws.Columns(colNo)\n\n ' Since accessing cells one by one is slower than reading a block of cells into a VBA array and looping through the array,\n ' we process in chunks of increasing size, starting with 1 cell and doubling the size on each iteration, until MAX_CHUNK_SIZE is reached.\n ' In pathological cases where Excel thinks all the ~1M rows are in the used range, this will take around 100ms.\n ' Yet in a normal case where one of the few last rows contains the cell we're looking for, we don't read too many cells.\n Const MAX_CHUNK_SIZE = 2 ^ 10 ' (using large chunks gives no performance advantage, but uses more memory)\n Dim chunkSize As Long: chunkSize = 1\n Dim startOffset As Long: startOffset = lastRow + 1 ' 0-based\n Do ' Loop invariant: startOffset&gt;=0 and all rows after startOffset are blank (i.e. wholeRng.Rows(i+1) for i&gt;=startOffset)\n startOffset = IIf(startOffset - chunkSize &gt;= 0, startOffset - chunkSize, 0)\n ' Fill `vals(1 To chunkSize, 1 To 1)` with column's rows indexed `[startOffset+1 .. startOffset+chunkSize]` (1-based, inclusive)\n Dim chunkRng As Range: Set chunkRng = wholeRng.Resize(chunkSize).Offset(startOffset)\n Dim vals() As Variant\n If chunkSize &gt; 1 Then\n vals = chunkRng.Value2\n Else ' reading a 1-cell range requires special handling &lt;http://www.cpearson.com/excel/ArraysAndRanges.aspx&gt;\n ReDim vals(1 To 1, 1 To 1)\n vals(1, 1) = chunkRng.Value2\n End If\n\n Dim i As Long\n For i = UBound(vals, 1) To LBound(vals, 1) Step -1\n If Not IsEmpty(vals(i, 1)) Then\n getLastNonblankRowInColumn = startOffset + i\n Exit Function\n End If\n Next i\n\n If chunkSize &lt; MAX_CHUNK_SIZE Then chunkSize = chunkSize * 2\n Loop While startOffset &gt; 0\n\n getLastNonblankRowInColumn = 0\nEnd Function\n</code></pre>\n" }, { "answer_id": 55383256, "author": "Sumit Pokhrel", "author_id": 2690723, "author_profile": "https://Stackoverflow.com/users/2690723", "pm_score": 0, "selected": false, "text": "<pre><code>Last_Row = Range(\"A1\").End(xlDown).Row\n</code></pre>\n\n<p>Just to verify, let's say you want to print the row number of the last row with the data in cell C1. </p>\n\n<pre><code>Range(\"C1\").Select\nLast_Row = Range(\"A1\").End(xlDown).Row\nActiveCell.FormulaR1C1 = Last_Row\n</code></pre>\n" }, { "answer_id": 71204877, "author": "Potocpe1", "author_id": 8867339, "author_profile": "https://Stackoverflow.com/users/8867339", "pm_score": 0, "selected": false, "text": "<p>get last non-empty row using <i>binary search</i></p>\n<ul>\n<li>returns correct value event though there are hidden values</li>\n<li>may returns incorrect value if there are empty cells before last non-empty cells (e.g. row 5 is empty, but row 10 is last non-empty row)</li>\n</ul>\n<pre><code>Function getLastRow(col As String, ws As Worksheet) As Long\n Dim lastNonEmptyRow As Long\n lastNonEmptyRow = 1\n Dim lastEmptyRow As Long\n\n lastEmptyRow = ws.Rows.Count + 1\n Dim nextTestedRow As Long\n \n Do While (lastEmptyRow - lastNonEmptyRow &gt; 1)\n nextTestedRow = Application.WorksheetFunction.Ceiling _\n (lastNonEmptyRow + (lastEmptyRow - lastNonEmptyRow) / 2, 1)\n If (IsEmpty(ws.Range(col &amp; nextTestedRow))) Then\n lastEmptyRow = nextTestedRow\n Else\n lastNonEmptyRow = nextTestedRow\n End If\n Loop\n \n getLastRow = lastNonEmptyRow\n \n\nEnd Function\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8418/" ]
How can I find the last row that contains data in a specific column and on a specific sheet?
How about: ``` Function GetLastRow(strSheet, strColumn) As Long Dim MyRange As Range Set MyRange = Worksheets(strSheet).Range(strColumn & "1") GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row End Function ``` Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data: ``` Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row ```
71,257
<p>How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.</p> <p>I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.</p>
[ { "answer_id": 71290, "author": "Dave Moore", "author_id": 6996, "author_profile": "https://Stackoverflow.com/users/6996", "pm_score": 1, "selected": false, "text": "<p>See this CodeProject article for the win32 basics : <a href=\"http://www.codeproject.com/KB/threads/pausep.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/threads/pausep.aspx</a>. This sample code makes use of the ToolHelp32 library from the SDK, so I would recommend turning this sample code into an unmanaged C++/CLI library with a simple interface like \"SuspendProcess(uint processID).</p>\n\n<p>Process.Start will return you a Process object, from which you can get the process id, and then pass this to your new library based on the above.</p>\n\n<p>Dave</p>\n" }, { "answer_id": 71457, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 6, "selected": true, "text": "<p>Here's my suggestion:</p>\n\n<pre><code> [Flags]\n public enum ThreadAccess : int\n {\n TERMINATE = (0x0001),\n SUSPEND_RESUME = (0x0002),\n GET_CONTEXT = (0x0008),\n SET_CONTEXT = (0x0010),\n SET_INFORMATION = (0x0020),\n QUERY_INFORMATION = (0x0040),\n SET_THREAD_TOKEN = (0x0080),\n IMPERSONATE = (0x0100),\n DIRECT_IMPERSONATION = (0x0200)\n }\n\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);\n [DllImport(\"kernel32.dll\")]\n static extern uint SuspendThread(IntPtr hThread);\n [DllImport(\"kernel32.dll\")]\n static extern int ResumeThread(IntPtr hThread);\n [DllImport(\"kernel32\", CharSet = CharSet.Auto,SetLastError = true)]\n static extern bool CloseHandle(IntPtr handle);\n\n\nprivate static void SuspendProcess(int pid)\n{\n var process = Process.GetProcessById(pid); // throws exception if process does not exist\n\n foreach (ProcessThread pT in process.Threads)\n {\n IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);\n\n if (pOpenThread == IntPtr.Zero)\n {\n continue;\n }\n\n SuspendThread(pOpenThread);\n\n CloseHandle(pOpenThread);\n }\n}\n\npublic static void ResumeProcess(int pid)\n{\n var process = Process.GetProcessById(pid);\n\n if (process.ProcessName == string.Empty)\n return;\n\n foreach (ProcessThread pT in process.Threads)\n {\n IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);\n\n if (pOpenThread == IntPtr.Zero)\n {\n continue;\n }\n\n var suspendCount = 0;\n do\n {\n suspendCount = ResumeThread(pOpenThread);\n } while (suspendCount &gt; 0);\n\n CloseHandle(pOpenThread);\n }\n}\n</code></pre>\n" }, { "answer_id": 1073037, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 2, "selected": false, "text": "<p>So really, what the other answer's are showing is suspending thread's in the process, there is no way to really suspend the process (i.e. in one call).... </p>\n\n<p>A bit of a different solution would be to actually debug the target process which you are starting, see <a href=\"http://blogs.msdn.com/jmstall/archive/2006/07/03/managed-Vs-native-apis.aspx\" rel=\"nofollow noreferrer\">Mike Stall's blog</a> for some advice how to implement this from a managed context. </p>\n\n<p>If you implement a debugger, you will be able to scan memory or what other snap-shotting you would like.</p>\n\n<p>However, I would like to point out, that technically, there is now way to really do this. Even if you do debugbreak a target debuggee process, another process on your system may inject a thread and will be given some ability to execute code regardless of the state of the target process (even let's say if it's hit a breakpoint due to an access violation), if you have all thread's suspended up to a super high suspend count, are currently at a break point in the main process thread and any other such presumed-frozen status, it is still possible for the system to inject another thread into that process and execute some instructions. You could also go through the trouble of modifying or replacing all of the entry point's the <a href=\"http://www.nynaeve.net/?p=205\" rel=\"nofollow noreferrer\">kernel usually calls</a> and so on, but you've now entered the viscous arm's race of MALWARE ;)...</p>\n\n<p>In any case, using the managed interfaces for debugging seems' a fair amount easier than p/invoke'ng a lot of native API call's which will do a poor job of emulating what you probably really want to be doing... using debug api's ;)</p>\n" }, { "answer_id": 13109774, "author": "Sarath", "author_id": 353241, "author_profile": "https://Stackoverflow.com/users/353241", "pm_score": 4, "selected": false, "text": "<p>Thanks to Magnus</p>\n\n<p>After including the Flags, I modified the code a bit to be an extension method in my project. I could now use</p>\n\n<pre><code>var process = Process.GetProcessById(param.PId);\nprocess.Suspend();\n</code></pre>\n\n<p>Here is the code for those who might be interested.</p>\n\n<pre><code>public static class ProcessExtension\n{\n [DllImport(\"kernel32.dll\")]\n static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);\n [DllImport(\"kernel32.dll\")]\n static extern uint SuspendThread(IntPtr hThread);\n [DllImport(\"kernel32.dll\")]\n static extern int ResumeThread(IntPtr hThread);\n\n public static void Suspend(this Process process)\n {\n foreach (ProcessThread thread in process.Threads)\n {\n var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);\n if (pOpenThread == IntPtr.Zero)\n {\n break;\n }\n SuspendThread(pOpenThread);\n }\n }\n public static void Resume(this Process process)\n {\n foreach (ProcessThread thread in process.Threads)\n {\n var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);\n if (pOpenThread == IntPtr.Zero)\n {\n break;\n }\n ResumeThread(pOpenThread);\n }\n }\n}\n</code></pre>\n\n<p>I have a utility done which I use to generally suspend/kill/list a process. Full source is <a href=\"https://github.com/SarathR/ProcessUtil.git\" rel=\"noreferrer\">on Git</a></p>\n" }, { "answer_id": 61282905, "author": "gerrard", "author_id": 13148843, "author_profile": "https://Stackoverflow.com/users/13148843", "pm_score": 1, "selected": false, "text": "<pre><code>[DllImport(\"ntdll.dll\", PreserveSig = false)]\n public static extern void NtSuspendProcess(IntPtr processHandle);\n static IntPtr handle;\n\n string p = \"\";\n foreach (Process item in Process.GetProcesses())\n {\n if (item.ProcessName == \"GammaVPN\")\n {\n p = item.ProcessName;\n handle = item.Handle;\n NtSuspendProcess(handle);\n }\n }\n Console.WriteLine(p);\n Console.WriteLine(\"done\");\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9632/" ]
How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#. I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.
Here's my suggestion: ``` [Flags] public enum ThreadAccess : int { TERMINATE = (0x0001), SUSPEND_RESUME = (0x0002), GET_CONTEXT = (0x0008), SET_CONTEXT = (0x0010), SET_INFORMATION = (0x0020), QUERY_INFORMATION = (0x0040), SET_THREAD_TOKEN = (0x0080), IMPERSONATE = (0x0100), DIRECT_IMPERSONATION = (0x0200) } [DllImport("kernel32.dll")] static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId); [DllImport("kernel32.dll")] static extern uint SuspendThread(IntPtr hThread); [DllImport("kernel32.dll")] static extern int ResumeThread(IntPtr hThread); [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)] static extern bool CloseHandle(IntPtr handle); private static void SuspendProcess(int pid) { var process = Process.GetProcessById(pid); // throws exception if process does not exist foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } SuspendThread(pOpenThread); CloseHandle(pOpenThread); } } public static void ResumeProcess(int pid) { var process = Process.GetProcessById(pid); if (process.ProcessName == string.Empty) return; foreach (ProcessThread pT in process.Threads) { IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id); if (pOpenThread == IntPtr.Zero) { continue; } var suspendCount = 0; do { suspendCount = ResumeThread(pOpenThread); } while (suspendCount > 0); CloseHandle(pOpenThread); } } ```
71,309
<p>for example this code</p> <pre><code>var html = "&lt;p&gt;This text is &lt;a href=#&gt; good&lt;/a&gt;&lt;/p&gt;"; var newNode = Builder.node('div',{className: 'test'},[html]); $('placeholder').update(newNode); </code></pre> <p>casues the p and a tags to be shown, how do I prevent them from being escaped?</p>
[ { "answer_id": 71371, "author": "Leo Lännenmäki", "author_id": 2451, "author_profile": "https://Stackoverflow.com/users/2451", "pm_score": 3, "selected": true, "text": "<p>The last parameter to Builder.node is \"Array, List of other nodes to be appended as children\" according to the <a href=\"http://github.com/madrobby/scriptaculous/wikis/builder\" rel=\"nofollow noreferrer\">Wiki</a>. So when you pass it a string it is treated like text.</p>\n\n<p>You could use:</p>\n\n<pre><code>var a = Builder.node('div').update(\"&lt;a href='#'&gt;foo&lt;/a&gt;\")\n</code></pre>\n\n<p>Where the link is text or:</p>\n\n<pre><code>var a = Builder.node('div', {'class':'cool'}, \n [Builder.node('div', {'class': 'another_div'})]\n );\n</code></pre>\n\n<p>And you could use just Prototypes <a href=\"http://www.prototypejs.org/api/element\" rel=\"nofollow noreferrer\">new Element()</a> (Available as of version 1.6).</p>\n\n<pre><code>var a = new Element('div').insert(\n new Element('div', {'class': 'inner_div'}).update(\"Text in the inner div\")\n );\n</code></pre>\n" }, { "answer_id": 1360798, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use this solution: <a href=\"http://sviudes.blogspot.com/2009/08/como-usar-etiquetas-html-con.html\" rel=\"nofollow noreferrer\">http://sviudes.blogspot.com/2009/08/como-usar-etiquetas-html-con.html</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6892/" ]
for example this code ``` var html = "<p>This text is <a href=#> good</a></p>"; var newNode = Builder.node('div',{className: 'test'},[html]); $('placeholder').update(newNode); ``` casues the p and a tags to be shown, how do I prevent them from being escaped?
The last parameter to Builder.node is "Array, List of other nodes to be appended as children" according to the [Wiki](http://github.com/madrobby/scriptaculous/wikis/builder). So when you pass it a string it is treated like text. You could use: ``` var a = Builder.node('div').update("<a href='#'>foo</a>") ``` Where the link is text or: ``` var a = Builder.node('div', {'class':'cool'}, [Builder.node('div', {'class': 'another_div'})] ); ``` And you could use just Prototypes [new Element()](http://www.prototypejs.org/api/element) (Available as of version 1.6). ``` var a = new Element('div').insert( new Element('div', {'class': 'inner_div'}).update("Text in the inner div") ); ```
71,323
<p>I'm trying to replace each <code>,</code> in the current file by a new line:</p> <pre><code>:%s/,/\n/g </code></pre> <p>But it inserts what looks like a <code>^@</code> instead of an actual newline. The file is not in DOS mode or anything.</p> <p>What should I do?</p> <p>If you are curious, like me, check the question <em><a href="https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim">Why is \r a newline for Vim?</a></em> as well.</p>
[ { "answer_id": 71334, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 13, "selected": true, "text": "<h2>Use <code>\\r</code> instead of <code>\\n</code>.</h2>\n<p>Substituting by <code>\\n</code> inserts a null character into the text. To get a newline, use <code>\\r</code>. When <em>searching</em> for a newline, you’d still use <code>\\n</code>, however. This asymmetry is due to the fact that <code>\\n</code> and <code>\\r</code> <a href=\"http://vim.wikia.com/wiki/Search_and_replace\" rel=\"noreferrer\">do slightly different things</a>:</p>\n<p><code>\\n</code> matches an end of line (newline), whereas <code>\\r</code> matches a carriage return. On the other hand, in substitutions <code>\\n</code> inserts a null character whereas <code>\\r</code> inserts a newline (more precisely, it’s treated as the input <kbd>CR</kbd>). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). <code>xxd</code> shows a hexdump of the resulting file.</p>\n<pre><code>echo bar &gt; test\n(echo 'Before:'; xxd test) &gt; output.txt\nvim test '+s/b/\\n/' '+s/a/\\r/' +wq\n(echo 'After:'; xxd test) &gt;&gt; output.txt\nmore output.txt\n</code></pre>\n\n<pre><code>Before:\n0000000: 6261 720a bar.\nAfter:\n0000000: 000a 720a ..r.\n</code></pre>\n<p>In other words, <code>\\n</code> has inserted the byte 0x00 into the text; <code>\\r</code> has inserted the byte 0x0a.</p>\n" }, { "answer_id": 71342, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 5, "selected": false, "text": "<p><code>\\r</code> can do the work here for you. </p>\n" }, { "answer_id": 71388, "author": "dogbane", "author_id": 7412, "author_profile": "https://Stackoverflow.com/users/7412", "pm_score": 6, "selected": false, "text": "<p>You need to use:</p>\n\n<pre><code>:%s/,/^M/g\n</code></pre>\n\n<p>To get the <code>^M</code> character, press <kbd>Ctrl</kbd> + <kbd>v</kbd> followed by <kbd>Enter</kbd>.</p>\n" }, { "answer_id": 71474, "author": "grantc", "author_id": 11845, "author_profile": "https://Stackoverflow.com/users/11845", "pm_score": 5, "selected": false, "text": "<p>With Vim on Windows, use <kbd>Ctrl</kbd> + <kbd>Q</kbd> in place of <kbd>Ctrl</kbd> + <kbd>V</kbd>.</p>\n" }, { "answer_id": 136915, "author": "Logan", "author_id": 1127433, "author_profile": "https://Stackoverflow.com/users/1127433", "pm_score": 8, "selected": false, "text": "<p>Here's the trick:</p>\n<p>First, set your Vi(m) session to allow pattern matching with special characters (i.e.: newline). It's probably worth putting this line in your .vimrc or .exrc file:</p>\n<pre><code>:set magic\n</code></pre>\n<p>Next, do:</p>\n<pre><code>:s/,/,^M/g\n</code></pre>\n<p>To get the <code>^M</code> character, type <kbd>Ctrl</kbd> + <kbd>V</kbd> and hit <kbd>Enter</kbd>. Under Windows, do <kbd>Ctrl</kbd> + <kbd>Q</kbd>, <kbd>Enter</kbd>. The only way I can remember these is by remembering how little sense they make:</p>\n<blockquote>\n<p>A: <em>What would be the worst control-character to use to represent a newline?</em></p>\n<p>B: <em>Either <code>q</code> (because it usually means &quot;Quit&quot;) or <code>v</code> because it would be so easy to type <kbd>Ctrl</kbd> + <kbd>C</kbd> by mistake and kill the editor.</em></p>\n<p>A: <em>Make it so.</em></p>\n</blockquote>\n" }, { "answer_id": 7324063, "author": "rickfoosusa", "author_id": 931265, "author_profile": "https://Stackoverflow.com/users/931265", "pm_score": 4, "selected": false, "text": "<p>From <a href=\"http://en.wikipedia.org/wiki/Eclipse_%28software%29\" rel=\"nofollow noreferrer\">Eclipse</a>, the <code>^M</code> characters can be embedded in a line, and you want to convert them to newlines.</p>\n\n<pre><code>:s/\\r/\\r/g\n</code></pre>\n" }, { "answer_id": 9134411, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Here's the answer that worked for me. From this guy:</p>\n\n<p>----quoting <em><a href=\"http://jaysonlorenzen.wordpress.com/2009/04/28/use-vi-editor-to-insert-newline-char-in-replace/\" rel=\"nofollow noreferrer\">Use the vi editor to insert a newline char in replace</a></em></p>\n\n<hr>\n\n<p>Something else I have to do and cannot remember and then have to look up.</p>\n\n<p>In vi, to insert a newline character in a search and replace, do the following:</p>\n\n<pre><code>:%s/look_for/replace_with^M/g\n</code></pre>\n\n<p>The command above would replace all instances of “look_for” with “replace_with\\n” (with \\n meaning newline).</p>\n\n<p>To get the “^M”, enter the key combination <kbd>Ctrl</kbd> + <kbd>V</kbd>, and then after that (release all keys) press the <kbd>Enter</kbd> key.</p>\n\n<hr>\n" }, { "answer_id": 9172870, "author": "Kiran K Telukunta", "author_id": 888574, "author_profile": "https://Stackoverflow.com/users/888574", "pm_score": 3, "selected": false, "text": "<p>But if one has to substitute, then the following thing works:</p>\n\n<pre><code>:%s/\\n/\\r\\|\\-\\r/g\n</code></pre>\n\n<p>In the above, every next line is substituted with next line, and then <code>|-</code> and again a new line. This is used in wiki tables.</p>\n\n<p>If the text is as follows:</p>\n\n<pre><code>line1\nline2\nline3\n</code></pre>\n\n<p>It is changed to</p>\n\n<pre><code>line1\n|-\nline2\n|-\nline3\n</code></pre>\n" }, { "answer_id": 9220288, "author": "Evan Donovan", "author_id": 263877, "author_profile": "https://Stackoverflow.com/users/263877", "pm_score": 3, "selected": false, "text": "<p>If you need to do it for a whole file, it was also suggested to me that you could try from the command line:</p>\n\n<pre><code>sed 's/\\\\n/\\n/g' file &gt; newfile\n</code></pre>\n" }, { "answer_id": 18961239, "author": "sjas", "author_id": 805284, "author_profile": "https://Stackoverflow.com/users/805284", "pm_score": 7, "selected": false, "text": "<p>In the syntax <code>s/foo/bar</code>, <code>\\r</code> and <code>\\n</code> have different meanings, depending on context.</p>\n<hr />\n<h2>Short:</h2>\n<p>For <code>foo</code>:<br/></p>\n<p><code>\\r</code> == &quot;carriage return&quot; (<code>CR</code> / <code>^M</code>)<br/>\n<code>\\n</code> == matches &quot;line feed&quot; (<code>LF</code>) on Linux/Mac, and <code>CRLF</code> on Windows<br/></p>\n<p>For <code>bar</code>:<br/></p>\n<p><code>\\r</code> == produces <code>LF</code> on Linux/Mac, <code>CRLF</code> on Windows<br/>\n<code>\\n</code> == &quot;null byte&quot; (<code>NUL</code> / <code>^@</code>)<br/></p>\n<p>When editing files in linux (i.e. on a webserver) that were initially created in a windows environment and uploaded (i.e. FTP/SFTP) - all the <code>^M</code>'s you see in vim, are the <code>CR</code>'s which linux does not translate as it uses only <code>LF</code>'s to depict a line break.</p>\n<hr />\n<h2>Longer (with ASCII numbers):</h2>\n<p>\n<code>NUL</code> == 0x00 == 0 == <kbd>Ctrl</kbd> + <kbd>@</kbd> == <code>^@</code> shown in vim<br/>\n<code>LF</code> == 0x0A == 10 == <kbd>Ctrl</kbd> + <kbd>J</kbd><br/>\n<code>CR</code> == 0x0D == 13 == <kbd>Ctrl</kbd> + <kbd>M</kbd> == <code>^M</code> shown in vim</p>\n<p>Here is a list of the <a href=\"http://www.cs.tut.fi/%7Ejkorpela/chars/c0.html\" rel=\"noreferrer\">ASCII control characters</a>. Insert them in Vim via <kbd>Ctrl</kbd> + <kbd>V</kbd>,<kbd>Ctrl</kbd> + <kbd>---key---</kbd>.</p>\n<p>In Bash or the other Unix/Linux shells, just type <kbd>Ctrl</kbd> + <kbd>---key---</kbd>.</p>\n<p>Try <kbd>Ctrl</kbd> + <kbd>M</kbd> in Bash. It's the same as hitting <kbd>Enter</kbd>, as the shell realizes what is meant, even though Linux systems use line feeds for line delimiting.</p>\n<p>To insert literal's in bash, prepending them with <kbd>Ctrl</kbd> + <kbd>V</kbd> will also work.</p>\n<p>Try in Bash:</p>\n<pre><code>echo ^[[33;1mcolored.^[[0mnot colored.\n</code></pre>\n<p>This uses <a href=\"http://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"noreferrer\">ANSI escape sequences</a>. Insert the two <code>^[</code>'s via <kbd>Ctrl</kbd> + <kbd>V</kbd>, <kbd>Esc</kbd>.</p>\n<p>You might also try <kbd>Ctrl</kbd> + <kbd>V</kbd>,<kbd>Ctrl</kbd> + <kbd>M</kbd>, <kbd>Enter</kbd>, which will give you this:</p>\n<pre><code>bash: $'\\r': command not found\n</code></pre>\n<p>Remember the <code>\\r</code> from above? :&gt;</p>\n<p>This <a href=\"http://www.cs.tut.fi/%7Ejkorpela/chars/c0.html\" rel=\"noreferrer\">ASCII control characters</a> list is different from a complete <a href=\"http://ascii-code.com/\" rel=\"noreferrer\">ASCII symbol table</a>, in that the control characters, which are inserted into a console/pseudoterminal/Vim via the <kbd>Ctrl</kbd> key (haha), can be found there.</p>\n<p>Whereas in C and most other languages, you usually use the octal codes to represent these 'characters'.</p>\n<p>If you really want to know where all this comes from: <em><a href=\"http://www.linusakesson.net/programming/tty/\" rel=\"noreferrer\">The TTY demystified</a></em>. This is the best link you will come across about this topic, but beware: There be dragons.</p>\n<hr />\n<p><em>TL;DR</em></p>\n<p>Usually <code>foo</code> = <code>\\n</code>, and <code>bar</code> = <code>\\r</code>.</p>\n" }, { "answer_id": 29514339, "author": "codeshot", "author_id": 962394, "author_profile": "https://Stackoverflow.com/users/962394", "pm_score": 4, "selected": false, "text": "<p>This is the best answer for the way I think, but it would have been nicer in a table:</p>\n\n<p><em><a href=\"https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim/12389839#12389839\">Why is \\r a newline for Vim?</a></em></p>\n\n<p>So, rewording:</p>\n\n<p>You need to use <code>\\r</code> to use a line feed (ASCII <code>0x0A</code>, the Unix newline) in a regex replacement, but that is peculiar to the replacement - you should normally continue to expect to use <code>\\n</code> for line feed and <code>\\r</code> for carriage return.</p>\n\n<p>This is because Vim used <code>\\n</code> in a replacement to mean the NIL character (ASCII <code>0x00</code>). You might have expected NIL to have been <code>\\0</code> instead, freeing <code>\\n</code> for its usual use for line feed, but <code>\\0</code> already has a meaning in regex replacements, so it was shifted to <code>\\n</code>. Hence then going further to also shift the newline from <code>\\n</code> to <code>\\r</code> (which in a regex pattern is the carriage return character, ASCII <code>0x0D</code>).</p>\n\n<pre>\nCharacter | ASCII code | C representation | Regex match | Regex replacement\n-------------------------+------------+------------------+-------------+------------------------\nnil | 0x00 | \\0 | \\0 | \\n\nline feed (Unix newline) | 0x0a | \\n | \\n | \\r\ncarriage return | 0x0d | \\r | \\r | &lt;unknown&gt;\n</pre>\n\n<p>NB: <code>^M</code> (<kbd>Ctrl</kbd> + <kbd>V</kbd> <kbd>Ctrl</kbd> + <kbd>M</kbd> on Linux) inserts a newline when used in a regex replacement rather than a carriage return as others have advised (I just tried it).</p>\n\n<p>Also note that Vim will translate the line feed character when it saves to file based on its file format settings and that might confuse matters.</p>\n" }, { "answer_id": 73473053, "author": "Rajashekhar Meesala", "author_id": 3888182, "author_profile": "https://Stackoverflow.com/users/3888182", "pm_score": 1, "selected": false, "text": "<p>in vim editor the following command successfully replaced \\n with new line</p>\n<pre><code>:%s/\\\\n/\\r/g\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
I'm trying to replace each `,` in the current file by a new line: ``` :%s/,/\n/g ``` But it inserts what looks like a `^@` instead of an actual newline. The file is not in DOS mode or anything. What should I do? If you are curious, like me, check the question *[Why is \r a newline for Vim?](https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim)* as well.
Use `\r` instead of `\n`. ------------------------- Substituting by `\n` inserts a null character into the text. To get a newline, use `\r`. When *searching* for a newline, you’d still use `\n`, however. This asymmetry is due to the fact that `\n` and `\r` [do slightly different things](http://vim.wikia.com/wiki/Search_and_replace): `\n` matches an end of line (newline), whereas `\r` matches a carriage return. On the other hand, in substitutions `\n` inserts a null character whereas `\r` inserts a newline (more precisely, it’s treated as the input `CR`). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). `xxd` shows a hexdump of the resulting file. ``` echo bar > test (echo 'Before:'; xxd test) > output.txt vim test '+s/b/\n/' '+s/a/\r/' +wq (echo 'After:'; xxd test) >> output.txt more output.txt ``` ``` Before: 0000000: 6261 720a bar. After: 0000000: 000a 720a ..r. ``` In other words, `\n` has inserted the byte 0x00 into the text; `\r` has inserted the byte 0x0a.
71,328
<p>I have PHP configured so that magic quotes are on and register globals are off.</p> <p>I do my best to always call htmlentities() for anything I am outputing that is derived from user input.</p> <p>I also occasionally seach my database for common things used in xss attached such as...</p> <pre><code>&lt;script </code></pre> <p>What else should I be doing and how can I make sure that the things I am trying to do are <strong>always</strong> done.</p>
[ { "answer_id": 71358, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>Escaping all user input is enough for most sites. Also make sure that session IDs don't end up in the URL so they can't be stolen from the <code>Referer</code> link to another site. Additionally, if you allow your users to submit links, make sure no <code>javascript:</code> protocol links are allowed; these would execute a script as soon as the user clicks on the link.</p>\n" }, { "answer_id": 71431, "author": "Christian Studer", "author_id": 6260, "author_profile": "https://Stackoverflow.com/users/6260", "pm_score": 4, "selected": false, "text": "<p>There are a lot of ways to do XSS (See <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">http://ha.ckers.org/xss.html</a>) and it's very hard to catch.</p>\n\n<p>I personally delegate this to the current framework I'm using (Code Igniter for example). While not perfect, it might catch more than my hand made routines ever do.</p>\n" }, { "answer_id": 71439, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 2, "selected": false, "text": "<p>If you are concerned about XSS attacks, encoding your output strings to HTML is the solution. If you remember to encode every single output character to HTML format, there is no way to execute a successful XSS attack.</p>\n\n<p>Read more:\n<a href=\"http://www.diovo.com/2008/09/sanitizing-user-data-how-and-where-to-do-it/\" rel=\"nofollow noreferrer\">Sanitizing user data: How and where to do it</a></p>\n" }, { "answer_id": 71444, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 7, "selected": true, "text": "<p>Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use <code>|escape:'htmlall'</code> modifier to convert all sensitive characters to HTML entities (I use own <code>|e</code> modifier which is alias to the above).</p>\n\n<p>My approach to input/output security is:</p>\n\n<ul>\n<li>store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)</li>\n<li>escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)</li>\n</ul>\n" }, { "answer_id": 71541, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 2, "selected": false, "text": "<p>“Magic quotes” is a palliative remedy for some of the worst XSS flaws which works by escaping everything on input, something that's wrong by design. The only case where one would want to use it is when you absolutely must use an existing PHP application known to be written carelessly with regard to XSS. (In this case you're in a serious trouble even with “magic quotes”.) When developing your own application, you should disable “magic quotes” and follow XSS-safe practices instead.</p>\n\n<p>XSS, a cross-site scripting vulnerability, occurs when an application includes strings from external sources (user input, fetched from other websites, etc) in its [X]HTML, CSS, ECMAscript or other browser-parsed output without proper escaping, hoping that special characters like less-than (in [X]HTML), single or double quotes (ECMAscript) will never appear. The proper solution to it is to always escape strings according to the rules of the output language: using entities in [X]HTML, backslashes in ECMAscript etc.</p>\n\n<p>Because it can be hard to keep track of what is untrusted and has to be escaped, it's a good idea to always escape everything that is a “text string” as opposed to “text with markup” in a language like HTML. Some programming environments make it easier by introducing several incompatible string types: “string” (normal text), “HTML string” (HTML markup) and so on. That way, a direct implicit conversion from “string” to “HTML string” would be impossible, and the only way a string could become HTML markup is by passing it through an escaping function.</p>\n\n<p>“Register globals”, though disabling it is definitely a good idea, deals with a problem entirely different from XSS.</p>\n" }, { "answer_id": 71568, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "<p>Use an existing user-input sanitization library to clean <em>all</em> user-input. Unless you put a <em>lot</em> of effort into it, implementing it yourself will never work as well.</p>\n" }, { "answer_id": 71612, "author": "Matt Farina", "author_id": 11910, "author_profile": "https://Stackoverflow.com/users/11910", "pm_score": 3, "selected": false, "text": "<p>This is a great question.</p>\n\n<p>First, don't escape text on input except to make it safe for storage (such as being put into a database). The reason for this is you want to keep what was input so you can contextually present it in different ways and places. Making changes here can compromise your later presentation.</p>\n\n<p>When you go to present your data filter out what shouldn't be there. For example, if there isn't a reason for javascript to be there search for it and remove it. An easy way to do that is to use the <a href=\"http://us.php.net/strip_tags\" rel=\"noreferrer\">strip_tags</a> function and only present the html tags you are allowing.</p>\n\n<p>Next, take what you have and pass it thought htmlentities or htmlspecialchars to change what's there to ascii characters. Do this based on context and what you want to get out.</p>\n\n<p>I'd, also, suggest turning off Magic Quotes. It is has been removed from PHP 6 and is considered bad practice to use it. Details at <a href=\"http://us3.php.net/magic_quotes\" rel=\"noreferrer\">http://us3.php.net/magic_quotes</a></p>\n\n<p>For more details check out <a href=\"http://ha.ckers.org/xss.html\" rel=\"noreferrer\">http://ha.ckers.org/xss.html</a></p>\n\n<p>This isn't a complete answer but, hopefully enough to help you get started.</p>\n" }, { "answer_id": 71635, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 1, "selected": false, "text": "<p>Make you any session cookies (or all cookies) you use HttpOnly. Most browsers will hide the cookie value from JavaScript in that case. User could still manually copy cookies, but this helps prevent direct script access. StackOverflow had this problem durning beta. </p>\n\n<p>This isn't a solution, just another brick in the wall </p>\n" }, { "answer_id": 75839, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Personally, I would disable magic_quotes. In PHP5+ it is disabled by default and it is better to code as if it is not there at all as it does not escape everything and it will be removed from PHP6.</p>\n\n<p>Next, depending on what type of user data you are filtering will dictate what to do next e.g. if it is just text e.g. a name, then <code>strip_tags(trim(stripslashes()));</code> it or to check for ranges use regular expressions.</p>\n\n<p>If you expect a certain range of values, create an array of the valid values and only allow those values through (<code>in_array($userData, array(...))</code>).</p>\n\n<p>If you are checking numbers use is_numeric to enforce whole numbers or cast to a specific type, that should prevent people trying to send strings in stead.</p>\n\n<p>If you have PHP5.2+ then consider looking at <a href=\"http://ca.php.net/filter\" rel=\"nofollow noreferrer\">filter()</a> and making use of that extension which can filter various data types including email addresses. Documentation is not particularly good, but is improving.</p>\n\n<p>If you have to handle HTML then you should consider something like <a href=\"http://cyberai.users.phpclasses.org/browse/package/2189.html\" rel=\"nofollow noreferrer\">PHP Input Filter</a> or <a href=\"http://htmlpurifier.org/\" rel=\"nofollow noreferrer\">HTML Purifier</a>. HTML Purifier will also validate HTML for conformance. I am not sure if Input Filter is still being developed. Both will allow you to define a set of tags that can be used and what attributes are allowed.</p>\n\n<p>Whatever you decide upon, always remember, never ever trust anything coming into your PHP script from a user (including yourself!).</p>\n" }, { "answer_id": 75879, "author": "Mason", "author_id": 8973, "author_profile": "https://Stackoverflow.com/users/8973", "pm_score": 3, "selected": false, "text": "<blockquote>\n<p>rikh Writes:</p>\n<blockquote>\n<p>I do my best to always call htmlentities() for anything I am outputing that is derived from user input.</p>\n</blockquote>\n</blockquote>\n<p>See Joel's essay on <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Making Code Look Wrong</a> for help with this</p>\n" }, { "answer_id": 77290, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 2, "selected": false, "text": "<p>All of these answers are great, but fundamentally, the solution to XSS will be to stop generating HTML documents by string manipulation.</p>\n\n<p>Filtering input is always a good idea for any application.</p>\n\n<p>Escaping your output using htmlentities() and friends should work as long as it's used properly, but this is the HTML equivalent of creating a SQL query by concatenating strings with mysql_real_escape_string($var) - it should work, but fewer things can validate your work, so to speak, compared to an approach like using parameterized queries.</p>\n\n<p>The long-term solution should be for applications to construct the page internally, perhaps using a standard interface like the DOM, and then to use a library (like libxml) to handle the serialization to XHTML/HTML/etc. Of course, we're a long ways away from that being popular and fast enough, but in the meantime we have to build our HTML documents via string operations, and that's inherently more risky.</p>\n" }, { "answer_id": 77320, "author": "Rob", "author_id": 3542, "author_profile": "https://Stackoverflow.com/users/3542", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Don't trust user input</li>\n<li>Escape all free-text output</li>\n<li>Don't use magic_quotes; see if there's a DBMS-specfic variant, or use PDO</li>\n<li>Consider using HTTP-only cookies where possible to avoid any malicious script being able to hijack a session</li>\n</ul>\n" }, { "answer_id": 77349, "author": "Jilles", "author_id": 13864, "author_profile": "https://Stackoverflow.com/users/13864", "pm_score": 4, "selected": false, "text": "<p>I'm of the opinion that one shouldn't escape anything during input, only on output. Since (most of the time) you can not assume that you know where that data is going. Example, if you have form that takes data that later on appears in an email that you send out, you need different escaping (otherwise a malicious user could rewrite your email-headers). </p>\n\n<p>In other words, you can only escape at the very last moment the data is \"leaving\" your application:</p>\n\n<ul>\n<li>List item</li>\n<li>Write to XML file, escape for XML</li>\n<li>Write to DB, escape (for that particular DBMS)</li>\n<li>Write email, escape for emails</li>\n<li>etc</li>\n</ul>\n\n<p>To go short:</p>\n\n<ol>\n<li>You don't know where your data is going</li>\n<li>Data might actually end up in more than one place, needing different escaping mechanism's BUT NOT BOTH</li>\n<li>Data escaped for the wrong target is really not nice. (E.g. get an email with the subject \"Go to Tommy\\'s bar\".)</li>\n</ol>\n\n<p>Esp #3 will occur if you escape data at the input layer (or you need to de-escape it again, etc).</p>\n\n<p>PS: I'll second the advice for not using magic_quotes, those are pure evil!</p>\n" }, { "answer_id": 77376, "author": "barce", "author_id": 13518, "author_profile": "https://Stackoverflow.com/users/13518", "pm_score": 2, "selected": false, "text": "<p>I find that using this function helps to strip out a lot of possible xss attacks:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\nfunction h($string, $esc_type = 'htmlall')\n{\n switch ($esc_type) {\n case 'css':\n $string = str_replace(array('&lt;', '&gt;', '\\\\'), array('&amp;lt;', '&amp;gt;', '&amp;#47;'), $string);\n // get rid of various versions of javascript\n $string = preg_replace(\n '/j\\s*[\\\\\\]*\\s*a\\s*[\\\\\\]*\\s*v\\s*[\\\\\\]*\\s*a\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*c\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*t\\s*[\\\\\\]*\\s*:/i',\n 'blocked', $string);\n $string = preg_replace(\n '/@\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*m\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*o\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*t/i',\n 'blocked', $string);\n $string = preg_replace(\n '/e\\s*[\\\\\\]*\\s*x\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*e\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*o\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*/i',\n 'blocked', $string);\n $string = preg_replace('/b\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*d\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*g:/i', 'blocked', $string);\n return $string;\n\n case 'html':\n //return htmlspecialchars($string, ENT_NOQUOTES);\n return str_replace(array('&lt;', '&gt;'), array('&amp;lt;' , '&amp;gt;'), $string);\n\n case 'htmlall':\n return htmlentities($string, ENT_QUOTES);\n case 'url':\n return rawurlencode($string);\n case 'query':\n return urlencode($string);\n\n case 'quotes':\n // escape unescaped single quotes\n return preg_replace(&quot;%(?&lt;!\\\\\\\\)'%&quot;, &quot;\\\\'&quot;, $string);\n\n case 'hex':\n // escape every character into hex\n $s_return = '';\n for ($x=0; $x &lt; strlen($string); $x++) {\n $s_return .= '%' . bin2hex($string[$x]);\n }\n return $s_return;\n\n case 'hexentity':\n $s_return = '';\n for ($x=0; $x &lt; strlen($string); $x++) {\n $s_return .= '&amp;#x' . bin2hex($string[$x]) . ';';\n }\n return $s_return;\n\n case 'decentity':\n $s_return = '';\n for ($x=0; $x &lt; strlen($string); $x++) {\n $s_return .= '&amp;#' . ord($string[$x]) . ';';\n }\n return $s_return;\n\n case 'javascript':\n // escape quotes and backslashes, newlines, etc.\n return strtr($string, array('\\\\'=&gt;'\\\\\\\\',&quot;'&quot;=&gt;&quot;\\\\'&quot;,'&quot;'=&gt;'\\\\&quot;',&quot;\\r&quot;=&gt;'\\\\r',&quot;\\n&quot;=&gt;'\\\\n','&lt;/'=&gt;'&lt;\\/'));\n\n case 'mail':\n // safe way to display e-mail address on a web page\n return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string);\n\n case 'nonstd':\n // escape non-standard chars, such as ms document quotes\n $_res = '';\n for($_i = 0, $_len = strlen($string); $_i &lt; $_len; $_i++) {\n $_ord = ord($string{$_i});\n // non-standard char, escape it\n if($_ord &gt;= 126){ \n $_res .= '&amp;#' . $_ord . ';'; \n } else {\n $_res .= $string{$_i};\n }\n }\n return $_res;\n\n default:\n return $string;\n }\n}\n \n?&gt;\n</code></pre>\n<p><a href=\"http://www.codebelay.com/killxss.phps\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 77396, "author": "Darren22", "author_id": 13978, "author_profile": "https://Stackoverflow.com/users/13978", "pm_score": 0, "selected": false, "text": "<p>I find the best way is using a class that allows you to bind your code so you never have to worry about manually escaping your data.</p>\n" }, { "answer_id": 77689, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": -1, "selected": false, "text": "<p>It is difficult to implement a thorough sql injection/xss injection prevention on a site that doesn't cause false alarms. In a CMS the end user might want to use <code>&lt;script&gt;</code> or <code>&lt;object&gt;</code> that links to items from another site. </p>\n\n<p>I recommend having all users install FireFox with NoScript ;-)</p>\n" }, { "answer_id": 209743, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "<p>I rely on <a href=\"http://phptal.motion-twin.com/\" rel=\"nofollow noreferrer\">PHPTAL</a> for that.</p>\n\n<p>Unlike Smarty and plain PHP, it escapes all output by default. This is a big win for security, because your site won't become vurnelable if you forget <code>htmlspecialchars()</code> or <code>|escape</code> somewhere.</p>\n\n<p>XSS is HTML-specific attack, so HTML output is the right place to prevent it. You should not try pre-filtering data in the database, because you could need to output data to another medium which doesn't accept HTML, but has its own risks.</p>\n" }, { "answer_id": 2660815, "author": "user319490", "author_id": 319490, "author_profile": "https://Stackoverflow.com/users/319490", "pm_score": 3, "selected": false, "text": "<p><strong>Template library.</strong> Or at least, that is what template libraries should do.\nTo prevent XSS <em>all</em> output should be encoded. This is not the task of the main application / control logic, it should solely be handled by the output methods.</p>\n\n<p>If you sprinkle htmlentities() thorughout your code, the overall design is wrong. And as you suggest, you might miss one or two spots.\nThat's why the only solution is rigorous html encoding <em>-> when</em> output vars get written into a html/xml stream.</p>\n\n<p>Unfortunately, most php template libraries only add their own template syntax, but don't concern themselves with output encoding, or localization, or html validation, or anything important. Maybe someone else knows a proper template library for php?</p>\n" }, { "answer_id": 2671681, "author": "Abeon", "author_id": 320856, "author_profile": "https://Stackoverflow.com/users/320856", "pm_score": 1, "selected": false, "text": "<p>You should at least validate all data going into the database. And try to validate all data leaving the database too.</p>\n\n<p>mysql_real_escape_string is good to prevent SQL injection, but XSS is trickier.\nYou should preg_match, stip_tags, or htmlentities where possible!</p>\n" }, { "answer_id": 5772431, "author": "Night Owl", "author_id": 615686, "author_profile": "https://Stackoverflow.com/users/615686", "pm_score": 1, "selected": false, "text": "<p>The best current method for preventing XSS in a PHP application is HTML Purifier (http://htmlpurifier.org/). One minor drawback to it is that it's a rather large library and is best used with an op code cache like APC. You would use this in any place where untrusted content is being outputted to the screen. It is much more thorough that htmlentities, htmlspecialchars, filter_input, filter_var, strip_tags, etc.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4012/" ]
I have PHP configured so that magic quotes are on and register globals are off. I do my best to always call htmlentities() for anything I am outputing that is derived from user input. I also occasionally seach my database for common things used in xss attached such as... ``` <script ``` What else should I be doing and how can I make sure that the things I am trying to do are **always** done.
Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use `|escape:'htmlall'` modifier to convert all sensitive characters to HTML entities (I use own `|e` modifier which is alias to the above). My approach to input/output security is: * store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements) * escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)
71,413
<p>Given a table of votes (users vote for a choice, and must supply an email address):</p> <pre><code>votes -- id: int choice: int timestamp: timestamp ip: varchar email: varchar </code></pre> <p>What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote <em>twice</em> per hour?</p> <p>It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.</p> <p>I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)</p>
[ { "answer_id": 71430, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<p>Something like </p>\n\n<pre><code>select email, ip, count(choice)\nfrom votes\ngroup by email, ip, datepart(hour, timestamp)\n</code></pre>\n\n<p>If I understand correctly</p>\n" }, { "answer_id": 71489, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>You could rewrite your insert statement to only allow votes to be inserted based on your contrainsts:</p>\n\n<pre><code>Insert Into Votes\n(Choice, Timestamp, IP, Email)\nSelect\nTop 1\n@Choice, @Timestamp, @IP, @Email\nFrom\nVotes\nWhere\n(Select Count(*) From Votes Where\n IP = @IP\n and Email = @Email\n and Timestamp &gt; DateAdd(h, -2, GetDate())) &lt; 3\n</code></pre>\n\n<p>You didn't mention which SQL language you were using so this is in SQL Server 2005.</p>\n" }, { "answer_id": 74262, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<p>I think this would do it: </p>\n\n<pre><code>SELECT choice, count(*) \nFROM votes v \nWHERE \n ( SELECT count(*) \n FROM votes v2\n WHERE v.email = v2.email \n AND v.ip = v2.ip \n AND v2.timestamp BETWEEN dateadd(hour, -1, v.timestamp) AND v.timestamp \n ) &lt; 2 \n</code></pre>\n\n<p>FYI, To count votes where users can only vote once per hour, we could do this: </p>\n\n<pre><code>SELECT choice, count(*) \nFROM votes v \nWHERE NOT EXTISTS \n ( SELECT * \n FROM votes v2\n WHERE v.email = v2.email \n AND v.ip = v2.ip \n AND v2.timestamp BETWEEN dateadd(h,v.timestamp,-1) AND v.timestamp \n ) \n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Given a table of votes (users vote for a choice, and must supply an email address): ``` votes -- id: int choice: int timestamp: timestamp ip: varchar email: varchar ``` What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote *twice* per hour? It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted. I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)
Something like ``` select email, ip, count(choice) from votes group by email, ip, datepart(hour, timestamp) ``` If I understand correctly
71,416
<p>I'm trying to do something like the following:</p> <pre><code>enum E; void Foo(E e); enum E {A, B, C}; </code></pre> <p>which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?</p> <p>Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as</p> <pre><code>enum E { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X } </code></pre> <p>as project X is not something I want my users to know about.</p> <p>So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.</p> <p>As for the compiler - it's GCC.</p>
[ { "answer_id": 71428, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 1, "selected": false, "text": "<p>It seems it can not be forward-declared in GCC!</p>\n<p>An interesting discussion is <a href=\"http://bytes.com/forum/thread62285.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 71436, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 3, "selected": false, "text": "<p>There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.</p>\n\n<p>If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.</p>\n\n<p>If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.</p>\n" }, { "answer_id": 71448, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": -1, "selected": false, "text": "<p>Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).</p>\n\n<p>So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.</p>\n" }, { "answer_id": 71495, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 4, "selected": false, "text": "<p>[My answer is wrong, but I've left it here because the comments are useful].</p>\n\n<p>Forward declaring enums is non-standard, because pointers to different enum types are not guaranteed to be the same size. The compiler may need to see the definition to know what size pointers can be used with this type.</p>\n\n<p>In practice, at least on all the popular compilers, pointers to enums are a consistent size. Forward declaration of enums is provided as a language extension by Visual C++, for example.</p>\n" }, { "answer_id": 71961, "author": "Laurie Cheers", "author_id": 12066, "author_profile": "https://Stackoverflow.com/users/12066", "pm_score": 3, "selected": false, "text": "<p>I'd do it this way:</p>\n\n<p>[in the public header]</p>\n\n<pre><code>typedef unsigned long E;\n\nvoid Foo(E e);\n</code></pre>\n\n<p>[in the internal header]</p>\n\n<pre><code>enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,\n FORCE_32BIT = 0xFFFFFFFF };\n</code></pre>\n\n<p>By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.</p>\n" }, { "answer_id": 72599, "author": "KJAWolf", "author_id": 12302, "author_profile": "https://Stackoverflow.com/users/12302", "pm_score": 9, "selected": true, "text": "<p>The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size has been chosen – it could be a <code>char</code>, or an <code>int</code>, or something else.</p>\n<hr />\n<p>From Section 7.2.5 of the ISO C++ Standard:</p>\n<blockquote>\n<p>The <em>underlying type</em> of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than <code>int</code> unless the value of an enumerator cannot fit in an <code>int</code> or <code>unsigned int</code>. If the <em>enumerator-list</em> is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of <code>sizeof()</code> applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of <code>sizeof()</code> applied to the underlying type.</p>\n</blockquote>\n<p>Since the <em>caller</em> to the function must know the sizes of the parameters to correctly set up the call stack, the number of enumerations in an enumeration list must be known before the function prototype.</p>\n<p>Update:</p>\n<p>In C++0X, a syntax for forward declaring enum types has been proposed and accepted. You can see the proposal at <em><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf\" rel=\"nofollow noreferrer\">Forward declaration of enumerations (rev.3)</a></em></p>\n" }, { "answer_id": 78426, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 0, "selected": false, "text": "<p>My solution to your problem would be to either:</p>\n\n<p>1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):</p>\n\n<pre><code>namespace\n{\n const int FUNCTIONALITY_NORMAL = 0 ;\n const int FUNCTIONALITY_RESTRICTED = 1 ;\n const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;\n}\n</code></pre>\n\n<p>As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:</p>\n\n<pre><code>namespace\n{\n const int FUNCTIONALITY_begin = 0 ;\n const int FUNCTIONALITY_NORMAL = 0 ;\n const int FUNCTIONALITY_RESTRICTED = 1 ;\n const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;\n const int FUNCTIONALITY_end = 3 ;\n\n bool isFunctionalityCorrect(int i)\n {\n return (i &gt;= FUNCTIONALITY_begin) &amp;&amp; (i &lt; FUNCTIONALITY_end) ;\n }\n}\n</code></pre>\n\n<p>2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).</p>\n\n<p>3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.</p>\n\n<p>My guess would be either the solution 3 or 1.</p>\n" }, { "answer_id": 78448, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 2, "selected": false, "text": "<p>If you really don't want your enum to appear in your header file <em>and</em> ensure that it is only used by private methods, then one solution can be to go with the <a href=\"https://cpppatterns.com/patterns/pimpl.html\" rel=\"nofollow noreferrer\">PIMPL</a> principle.</p>\n<p>It's a technique that ensure to hide the class internals in the headers by just declaring:</p>\n<pre><code>class A\n{\npublic:\n ...\nprivate:\n void* pImpl;\n};\n</code></pre>\n<p>Then in your implementation file (.cpp), you declare a class that will be the representation of the internals.</p>\n<pre><code>class AImpl\n{\npublic:\n AImpl(A* pThis): m_pThis(pThis) {}\n\n ... all private methods here ...\nprivate:\n A* m_pThis;\n};\n</code></pre>\n<p>You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:</p>\n<pre><code>((AImpl*)pImpl)-&gt;PrivateMethod();\n</code></pre>\n<p>There are pros for using PIMPL. One is that it decouples your class header from its implementation, and there isn't any need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time, because your headers are so simple.</p>\n<p>But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.</p>\n" }, { "answer_id": 483320, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": -1, "selected": false, "text": "<p>You define an enumeration to restrict the possible values of elements of the type to a limited set. This restriction is to be enforced at compile time.</p>\n\n<p>When forward declaring the fact that you will use a 'limited set' later on doesn't add any value: subsequent code needs to know the possible values in order to benefit from it.</p>\n\n<p>Although the compiler <em>is</em> concerned about the size of the enumerated type, the <em>intent</em> of the enumeration gets lost when you forward declare it.</p>\n" }, { "answer_id": 685239, "author": "Dan Olson", "author_id": 69283, "author_profile": "https://Stackoverflow.com/users/69283", "pm_score": 2, "selected": false, "text": "<p>There's some dissent since this got bumped (sort of), so here's some relevant bits from the standard. Research shows that the standard doesn't really define forward declaration, nor does it explicitly state that enums can or can't be forward declared.</p>\n<p>First, from dcl.enum, section 7.2:</p>\n<blockquote>\n<p>The underlying type of an enumeration\nis an integral type that can represent\nall the enumerator values defined in\nthe enumeration. It is\nimplementation-defined which integral\ntype is used as the underlying type\nfor an enumeration except that the\nunderlying type shall not be larger\nthan int unless the value of an\nenumerator cannot fit in an int or\nunsigned int. If the enumerator-list\nis empty, the underlying type is as if\nthe enumeration had a single\nenumerator with value 0. The value of\nsizeof() applied to an enumeration\ntype, an object of enumeration type,\nor an enumerator, is the value of\nsizeof() applied to the underlying\ntype.</p>\n</blockquote>\n<p>So the underlying type of an enum is implementation-defined, with one minor restriction.</p>\n<p>Next we flip to the section on &quot;incomplete types&quot; (3.9), which is about as close as we come to any standard on forward declarations:</p>\n<blockquote>\n<p>A class that has been declared but not defined, or an array of unknown size or of\nincomplete element type, is an incompletely-defined object type.</p>\n<p>A class type (such as &quot;class X&quot;) might be incomplete at one point in a translation\nunit and complete later on; the type &quot;class X&quot; is the same type at both points. The\ndeclared type of an array object might be an array of incomplete class type and\ntherefore incomplete; if the class type is completed later on in the translation unit,\nthe array type becomes complete; the array type at those two points is the same type.\nThe declared type of an array object might be an array of unknown size and therefore be\nincomplete at one point in a translation unit and complete later on; the array types at\nthose two points (&quot;array of unknown bound of T&quot; and &quot;array of N T&quot;) are different\ntypes. The type of a pointer to array of unknown size, or of a type defined by a typedef\ndeclaration to be an array of unknown size, cannot be completed.</p>\n</blockquote>\n<p>So there, the standard pretty much laid out the types that can be forward declared. Enum wasn't there, so compiler authors generally regard forward declaring as disallowed by the standard due to the variable size of its underlying type.</p>\n<p>It makes sense, too. Enums are usually referenced in by-value situations, and the compiler would indeed need to know the storage size in those situations. Since the storage size is implementation defined, many compilers may just choose to use 32 bit values for the underlying type of every enum, at which point it becomes possible to forward declare them.</p>\n<p>An interesting experiment might be to try forward declaring an enum in Visual Studio, then forcing it to use an underlying type greater than sizeof(int) as explained above to see what happens.</p>\n" }, { "answer_id": 686303, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "<p>I am just noting that the reason actually <em>is</em> that the size of the enum is not yet known after forward declaration. Well, you use forward declaration of a struct to be able to pass a pointer around or refer to an object from a place that's referred to in the forward declared struct definition itself too.</p>\n<p>Forward declaring an enum would not be too useful, because one would wish to be able to pass around the enum by-value. You couldn't even have a pointer to it, because I recently got told some platforms use pointers of different size for <em>char</em> than for <em>int</em> or <em>long</em>. So it all depends on the content of the enum.</p>\n<p>The current C++ Standard explicitly disallows doing something like</p>\n<pre><code>enum X;\n</code></pre>\n<p>(in <code>7.1.5.3/1</code>). But the next C++ Standard due to next year allows the following, which convinced me the problem actually <em>has</em> to do with the underlying type:</p>\n<pre><code>enum X : int;\n</code></pre>\n<p>It's known as an &quot;opaque&quot; enum declaration. You can even use X <em>by value</em> in the following code. And its enumerators can later be defined in a later redeclaration of the enumeration. See <code>7.2</code> in the current working draft.</p>\n" }, { "answer_id": 717633, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 1, "selected": false, "text": "<p>For <a href=\"https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B\" rel=\"nofollow noreferrer\">VC++</a>, here's the test about forward declaration and specifying the underlying type:</p>\n<ol>\n<li>The following code is compiled OK.</li>\n</ol>\n<pre>\n typedef int myint;\n enum T ;\n void foo(T * tp )\n {\n * tp = (T)0x12345678;\n }\n enum T : char\n {\n A\n };\n</pre>\n<p>But I got the warning for <code>/W4</code> (<code>/W3</code> does not incur this warning)</p>\n<blockquote>\n<p>warning C4480: nonstandard extension used: specifying underlying type for enum 'T'</p>\n</blockquote>\n<ol start=\"2\">\n<li>VC++ (Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86) looks buggy in the above case:</li>\n</ol>\n<ul>\n<li>when seeing enum T; VC assumes the enum type T uses default 4 bytes int as underlying type, so the generated assembly code is:</li>\n</ul>\n<pre>\n ?foo@@YAXPAW4T@@@Z PROC ; foo\n ; File e:\\work\\c_cpp\\cpp_snippet.cpp\n ; Line 13\n push ebp\n mov ebp, esp\n ; Line 14\n mov eax, DWORD PTR _tp$[ebp]\n mov DWORD PTR [eax], 305419896 ; 12345678H\n ; Line 15\n pop ebp\n ret 0\n ?foo@@YAXPAW4T@@@Z ENDP ; foo\n</pre>\n<p>The above assembly code is extracted from /Fatest.asm directly, not my personal guess.</p>\n<p>Do you see the</p>\n<pre><code>mov DWORD PTR[eax], 305419896 ; 12345678H\n</code></pre>\n<p>line?</p>\n<p>the following code snippet proves it:</p>\n<pre>\n int main(int argc, char *argv)\n {\n union {\n char ca[4];\n T t;\n }a;\n a.ca[0] = a.ca[1] = a.[ca[2] = a.ca[3] = 1;\n foo( &a.t) ;\n printf(\"%#x, %#x, %#x, %#x\\n\", a.ca[0], a.ca[1], a.ca[2], a.ca[3] );\n return 0;\n }\n</pre>\n<p>The result is:</p>\n<p>0x78, 0x56, 0x34, 0x12</p>\n<ul>\n<li>After removing the forward declaration of enum T and move the definition of function foo after the enum T's definition: the result is OK:</li>\n</ul>\n<p>The above key instruction becomes:</p>\n<p>mov BYTE PTR [eax], 120 ; 00000078H</p>\n<p>The final result is:</p>\n<p>0x78, 0x1, 0x1, 0x1</p>\n<p>Note the value is not being overwritten.</p>\n<p>So using of the forward-declaration of enum in VC++ is considered harmful.</p>\n<p>BTW, to not surprise, the syntax for declaration of the underlying type is same as its in C#. In pratice I found it's worth to save three bytes by specifying the underlying type as char when talking to the embedded system, which is memory limited.</p>\n" }, { "answer_id": 990983, "author": "mavam", "author_id": 1170277, "author_profile": "https://Stackoverflow.com/users/1170277", "pm_score": 1, "selected": false, "text": "<p>In my projects, I adopted the <a href=\"http://www.ddj.com/cpp/184403894\" rel=\"nofollow noreferrer\">Namespace-Bound Enumeration</a> technique to deal with <code>enum</code>s from legacy and 3rd-party components. Here is an example:</p>\n\n<h3>forward.h:</h3>\n\n<pre><code>namespace type\n{\n class legacy_type;\n typedef const legacy_type&amp; type;\n}\n</code></pre>\n\n<h3>enum.h:</h3>\n\n<pre><code>// May be defined here or pulled in via #include.\nnamespace legacy\n{\n enum evil { x , y, z };\n}\n\n\nnamespace type\n{\n using legacy::evil;\n\n class legacy_type\n {\n public:\n legacy_type(evil e)\n : e_(e)\n {}\n\n operator evil() const\n {\n return e_;\n }\n\n private:\n evil e_;\n };\n}\n</code></pre>\n\n<h3>foo.h:</h3>\n\n<pre><code>#include \"forward.h\"\n\nclass foo\n{\npublic:\n void f(type::type t);\n};\n</code></pre>\n\n<h3>foo.cc:</h3>\n\n<pre><code>#include \"foo.h\"\n\n#include &lt;iostream&gt;\n#include \"enum.h\"\n\nvoid foo::f(type::type t)\n{\n switch (t)\n {\n case legacy::x:\n std::cout &lt;&lt; \"x\" &lt;&lt; std::endl;\n break;\n case legacy::y:\n std::cout &lt;&lt; \"y\" &lt;&lt; std::endl;\n break;\n case legacy::z:\n std::cout &lt;&lt; \"z\" &lt;&lt; std::endl;\n break;\n default:\n std::cout &lt;&lt; \"default\" &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<h3>main.cc:</h3>\n\n<pre><code>#include \"foo.h\"\n#include \"enum.h\"\n\nint main()\n{\n foo fu;\n fu.f(legacy::x);\n\n return 0;\n}\n</code></pre>\n\n<p>Note that the <code>foo.h</code> header does not have to know anything about <code>legacy::evil</code>. Only the files that use the legacy type <code>legacy::evil</code> (here: main.cc) need to include <code>enum.h</code>.</p>\n" }, { "answer_id": 1280969, "author": "user119017", "author_id": 119017, "author_profile": "https://Stackoverflow.com/users/119017", "pm_score": 8, "selected": false, "text": "<p>Forward declaration of enums is possible since C++11. Previously, the reason enum types couldn't be forward declared was because the size of the enumeration depended on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared:</p>\n<pre><code>enum Enum1; // Illegal in C++03 and C++11; no size is explicitly specified.\nenum Enum2 : unsigned int; // Legal in C++11.\nenum class Enum3; // Legal in C++11, because enum class declarations have a default type of &quot;int&quot;.\nenum class Enum4: unsigned int; // Legal C++11.\nenum Enum2 : unsigned short; // Illegal in C++11, because Enum2 was previously declared with a different type.\n</code></pre>\n" }, { "answer_id": 1932119, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "<p>Forward declaring things in C++ is very useful because it <a href=\"http://brianbondy.com/blog/id/5/slow-compilation-time\" rel=\"nofollow noreferrer\">dramatically speeds up compilation time</a>. You can forward declare several things in C++ including: <code>struct</code>, <code>class</code>, <code>function</code>, etc...</p>\n<p>But can you forward declare an <code>enum</code> in C++?</p>\n<p>No, you can't.</p>\n<p>But why not allow it? If it were allowed you could define your <code>enum</code> type in your header file, and your <code>enum</code> values in your source file. It sounds like it should be allowed, right?</p>\n<p>Wrong.</p>\n<p>In C++ there is no default type for <code>enum</code> like there is in C# (int). In C++ your <code>enum</code> type will be determined by the compiler to be any type that will fit the range of values you have for your <code>enum</code>.</p>\n<p>What does that mean?</p>\n<p>It means that your <code>enum</code>'s underlying type cannot be fully determined until you have all of the values of the <code>enum</code> defined. Which means you cannot separate the declaration and definition of your <code>enum</code>. And therefore you cannot forward declare an <code>enum</code> in C++.</p>\n<p>The ISO C++ standard S7.2.5:</p>\n<blockquote>\n<p>The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than <code>int</code> unless the value of an enumerator cannot fit in an <code>int</code> or <code>unsigned int</code>. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of <code>sizeof()</code> applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of <code>sizeof()</code> applied to the underlying type.</p>\n</blockquote>\n<p>You can determine the size of an enumerated type in C++ by using the <code>sizeof</code> operator. The size of the enumerated type is the size of its underlying type. In this way you can guess which type your compiler is using for your <code>enum</code>.</p>\n<p>What if you specify the type of your <code>enum</code> explicitly like this:</p>\n<pre><code>enum Color : char { Red=0, Green=1, Blue=2};\nassert(sizeof Color == 1);\n</code></pre>\n<p>Can you then forward declare your <code>enum</code>?</p>\n<p>No. But why not?</p>\n<p>Specifying the type of an <code>enum</code> is not actually part of the current C++ standard. It is a VC++ extension. It will be part of C++0x though.</p>\n<p><a href=\"http://brianbondy.com/blog/id/93/forward-declaring-enums-in-c\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 11382046, "author": "Leszek Swirski", "author_id": 1509804, "author_profile": "https://Stackoverflow.com/users/1509804", "pm_score": 2, "selected": false, "text": "<p>You can wrap the enum in a struct, adding in some constructors and type conversions, and forward declare the struct instead.</p>\n\n<pre><code>#define ENUM_CLASS(NAME, TYPE, VALUES...) \\\nstruct NAME { \\\n enum e { VALUES }; \\\n explicit NAME(TYPE v) : val(v) {} \\\n NAME(e v) : val(v) {} \\\n operator e() const { return e(val); } \\\n private:\\\n TYPE val; \\\n}\n</code></pre>\n\n<p>This appears to work:\n<a href=\"http://ideone.com/TYtP2\" rel=\"nofollow\">http://ideone.com/TYtP2</a></p>\n" }, { "answer_id": 11632184, "author": "Tom", "author_id": 274460, "author_profile": "https://Stackoverflow.com/users/274460", "pm_score": 7, "selected": false, "text": "<p>You can forward-declare an enum in C++11, so long as you declare its storage type at the same time. The syntax looks like this:</p>\n<pre><code>enum E : short;\nvoid foo(E e);\n\n....\n\nenum E : short\n{\n VALUE_1,\n VALUE_2,\n ....\n}\n</code></pre>\n<p>In fact, if the function never refers to the values of the enumeration, you don't need the complete declaration at all at that point.</p>\n<p>This is supported by G++ 4.6 and onwards (<code>-std=c++0x</code> or <code>-std=c++11</code> in more recent versions). Visual C++ 2013 supports this; in earlier versions it has some sort of non-standard support that I haven't figured out yet - I found some suggestion that a simple forward declaration is legal, but your mileage may vary.</p>\n" }, { "answer_id": 64886872, "author": "Pankaj Gaikar", "author_id": 3307233, "author_profile": "https://Stackoverflow.com/users/3307233", "pm_score": 0, "selected": false, "text": "<p>To anyone facing this for iOS/Mac/Xcode,</p>\n<p>If you are facing this while integrating C/C++ headers in XCode with Objective-C, <strong>just change the extension of your file from .mm to .m</strong></p>\n" }, { "answer_id": 74655121, "author": "Sunandan Nandi", "author_id": 2722779, "author_profile": "https://Stackoverflow.com/users/2722779", "pm_score": -1, "selected": false, "text": "<p>This way we can forward declare enum</p>\n<p><code>enum A : int;</code></p>\n<p>please refer the <a href=\"https://learn.microsoft.com/en-us/cpp/cpp/enumerations-cpp?view=msvc-170\" rel=\"nofollow noreferrer\">link</a> for details.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11437/" ]
I'm trying to do something like the following: ``` enum E; void Foo(E e); enum E {A, B, C}; ``` which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain? Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as ``` enum E { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X } ``` as project X is not something I want my users to know about. So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people. As for the compiler - it's GCC.
The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size has been chosen – it could be a `char`, or an `int`, or something else. --- From Section 7.2.5 of the ISO C++ Standard: > > The *underlying type* of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than `int` unless the value of an enumerator cannot fit in an `int` or `unsigned int`. If the *enumerator-list* is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of `sizeof()` applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of `sizeof()` applied to the underlying type. > > > Since the *caller* to the function must know the sizes of the parameters to correctly set up the call stack, the number of enumerations in an enumeration list must be known before the function prototype. Update: In C++0X, a syntax for forward declaring enum types has been proposed and accepted. You can see the proposal at *[Forward declaration of enumerations (rev.3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf)*
71,417
<p>From question <em><a href="https://stackoverflow.com/questions/71323/how-to-replace-a-character-for-a-newline-in-vim">How to replace a character for a newline in Vim?</a></em>. You have to use \r when replacing text for a newline, like this</p> <pre><code>:%s/%/\r/g </code></pre> <p>But when replacing end of lines and newlines for a character, you can do it like:</p> <pre><code>:%s/\n/%/g </code></pre> <p>What section of the manual documents these behaviors, and what's the reasoning behind them?</p>
[ { "answer_id": 71531, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 6, "selected": false, "text": "<h3><a href=\"http://vimdoc.sf.net/htmldoc/pattern.html#NL-used-for-Nul\" rel=\"noreferrer\"><code>:help NL-used-for-Nul</code></a></h3>\n\n<blockquote>\n <h3>Technical detail:</h3>\n \n <p><code>&lt;Nul&gt;</code> characters in the file are stored as <code>&lt;NL&gt;</code> in memory. In the display\n they are shown as \"<code>^@</code>\". The translation is done when reading and writing\n files. To match a <code>&lt;Nul&gt;</code> with a search pattern you can just enter <a href=\"http://www.vim.org/htmldoc/insert.html#i_CTRL-@\" rel=\"noreferrer\">CTRL-@</a> or\n \"<a href=\"http://www.vim.org/htmldoc/insert.html#i_CTRL-V\" rel=\"noreferrer\">CTRL-V</a> 000\". This is probably just what you expect. Internally the\n character is replaced with a <code>&lt;NL&gt;</code> in the search pattern. What is unusual is\n that typing <a href=\"http://www.vim.org/htmldoc/insert.html#i_CTRL-V\" rel=\"noreferrer\">CTRL-V</a> <a href=\"http://www.vim.org/htmldoc/insert.html#i_CTRL-J\" rel=\"noreferrer\">CTRL-J</a> also inserts a <code>&lt;NL&gt;</code>, thus also searches for a <code>&lt;Nul&gt;</code>\n in the file. {Vi cannot handle <code>&lt;Nul&gt;</code> characters in the file at all}</p>\n</blockquote>\n\n<hr>\n" }, { "answer_id": 73438, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 8, "selected": true, "text": "<p>From <a href=\"http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5Cr\" rel=\"noreferrer\">vim docs on patterns</a>:</p>\n\n<blockquote>\n <p><code>\\r</code> matches &lt;CR&gt;</p>\n \n <p><code>\\n</code> matches an end-of-line - \n When matching in a string instead of\n buffer text a literal newline\n character is matched.</p>\n</blockquote>\n" }, { "answer_id": 12388814, "author": "lmat - Reinstate Monica", "author_id": 200985, "author_profile": "https://Stackoverflow.com/users/200985", "pm_score": 8, "selected": false, "text": "<p>From <a href=\"http://vim.wikia.com/wiki/Search_and_replace\" rel=\"noreferrer\">http://vim.wikia.com/wiki/Search_and_replace</a> :</p>\n\n<blockquote>\n <p><strong>When Searching</strong></p>\n \n <p>...</p>\n \n <p><code>\\n</code> is newline, <code>\\r</code> is <code>CR</code> (carriage return = <code>Ctrl-M</code> = <code>^M</code>)</p>\n \n <p><strong>When Replacing</strong></p>\n \n <p>...</p>\n \n <p><code>\\r</code> is newline, <code>\\n</code> is a null byte (<code>0x00</code>).</p>\n</blockquote>\n" }, { "answer_id": 12389839, "author": "rking", "author_id": 1410840, "author_profile": "https://Stackoverflow.com/users/1410840", "pm_score": 7, "selected": false, "text": "<p>Another aspect to this is that <code>\\0</code>, which is traditionally NULL, is taken in\n<code>s//\\0/</code> to mean \"the whole matched pattern\". (Which, by the way, is redundant with, and longer than, <code>&amp;</code>).</p>\n\n<ul>\n<li>So you can't use <code>\\0</code> to mean <code>NULL</code>, so you use <code>\\n</code></li>\n<li>So you can't use <code>\\n</code> to mean <code>\\n</code>, so you use <code>\\r</code>.</li>\n<li>So you can't use <code>\\r</code> to mean <code>\\r</code>, but I don't know who would want to add that char on purpose.</li>\n</ul>\n\n<p>—☈</p>\n" }, { "answer_id": 20491960, "author": "syockit", "author_id": 219229, "author_profile": "https://Stackoverflow.com/users/219229", "pm_score": 4, "selected": false, "text": "<p>First of all, open <a href=\"http://vimdoc.sourceforge.net/htmldoc/change.html#:s\" rel=\"noreferrer\"><code>:h :s</code></a> to see the section \"4.2 Substitute\" of documentation on \"Change\". Here's what the command accepts:</p>\n\n<pre><code>:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]\n</code></pre>\n\n<p>Notice the description about <code>pattern</code> and <code>string</code></p>\n\n<blockquote>\n <p>For the <code>{pattern}</code> see <a href=\"http://vimdoc.sourceforge.net/htmldoc/pattern.html#pattern\" rel=\"noreferrer\"><code>|pattern|</code></a>. <br>\n <code>{string}</code> can be a literal string, or something <br>\n special; see <a href=\"http://vimdoc.sourceforge.net/htmldoc/change.html#sub-replace-special\" rel=\"noreferrer\"><code>|sub-replace-special|</code></a>.</p>\n</blockquote>\n\n<p>So now you know that the search pattern and replacement patterns follow different rules.\nIf you follow the link to <code>|pattern|</code>, it takes you to the section that explains the whole regexp patterns used in Vim.</p>\n\n<p>Meanwhile, <code>|sub-replace-special|</code> takes you to the subsection of \"4.2 Substitute\", which contains the patterns for substitution, among which is <code>\\r</code> for line break/split.</p>\n\n<p>(The shortcut to this part of manual is <a href=\"http://vimdoc.sourceforge.net/htmldoc/change.html#:s%25\" rel=\"noreferrer\"><code>:h :s%</code></a>)</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
From question *[How to replace a character for a newline in Vim?](https://stackoverflow.com/questions/71323/how-to-replace-a-character-for-a-newline-in-vim)*. You have to use \r when replacing text for a newline, like this ``` :%s/%/\r/g ``` But when replacing end of lines and newlines for a character, you can do it like: ``` :%s/\n/%/g ``` What section of the manual documents these behaviors, and what's the reasoning behind them?
From [vim docs on patterns](http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5Cr): > > `\r` matches <CR> > > > `\n` matches an end-of-line - > When matching in a string instead of > buffer text a literal newline > character is matched. > > >
71,419
<p>I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. </p> <p>I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).</p> <p>Here's an example:</p> <pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32); begin with ARect do FillRectS(Left, Top, Right, Bottom, Value); end; </code></pre> <p>I like using <code>with</code>. What's wrong with me?</p>
[ { "answer_id": 71432, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "<p>I do not like it because it makes debbuging a hassle. You cannot read the value of a variable or the like by just hovering over it with a mouse.</p>\n" }, { "answer_id": 71438, "author": "Dan F", "author_id": 11569, "author_profile": "https://Stackoverflow.com/users/11569", "pm_score": 2, "selected": false, "text": "<p>This debate happens in Javascript a lot too.</p>\n\n<p>Basically, that With syntax makes it very hard to tell at a glance which Left/Top/etc property/method you're calling on.You could have a local variable called Left, and a property (it's been a while since I've done delphi, sorry if the name is wrong) called Left, perhaps even a function called Left. Anyone reading the code who isn't super familiar with the ARect structure could be very very lost.</p>\n" }, { "answer_id": 71447, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": false, "text": "<p>There's nothing wrong with it as long as you keep it simple and avoid ambiguities.</p>\n\n<p>As far as I'm aware, it doesn't speed anything up though - it's purely syntactic sugar.</p>\n" }, { "answer_id": 71470, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>I prefer the VB syntax in this case because here, you need to prefix the members inside the with block with a <code>.</code> to avoid ambiguities:</p>\n\n<pre><code>With obj\n .Left = 10\n .Submit()\nEnd With\n</code></pre>\n\n<p>But really, there's nothing wrong with <code>with</code> in general.</p>\n" }, { "answer_id": 71471, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 5, "selected": false, "text": "<p>One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult.</p>\n\n<p>A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer.</p>\n\n<pre><code>procedure TMyForm.ButtonClick(...)\nbegin\n with OtherForm do begin\n Left := 10;\n Top := 20;\n CallThisFunction;\n end;\nend;\n</code></pre>\n\n<p>Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method.</p>\n\n<p>And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't.</p>\n\n<p>Using multiple objects in the with multiplies the problems. See <a href=\"http://blog.marcocantu.com/blog/with_harmful.html\" rel=\"noreferrer\">http://blog.marcocantu.com/blog/with_harmful.html</a></p>\n" }, { "answer_id": 71479, "author": "jedediah", "author_id": 6342, "author_profile": "https://Stackoverflow.com/users/6342", "pm_score": 1, "selected": false, "text": "<p>It permits incompetent or evil programmers to write unreadble code. Therefor, only use this feature if you are neither incompetent nor evil.</p>\n" }, { "answer_id": 71494, "author": "SoftDeveloper", "author_id": 11805, "author_profile": "https://Stackoverflow.com/users/11805", "pm_score": 2, "selected": false, "text": "<p>What you save in typing, you lose in readability.\nMany debuggers won't have a clue what you're referring to either so debugging is more difficult.\nIt doesn't make programs run faster.</p>\n\n<p>Consider making the code within your with statement a method of the object that you're refering to.</p>\n" }, { "answer_id": 71498, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>At work we give points for removing Withs from an existing Win 32 code base because of the extra effort needed to maintain code that uses them. I have found several bugs in a previous job where a local variable called BusinessComponent was masked by being within a With begin block for an object that a published property BusinessComponent of the same type. The compiler chose to use the published property and the code that meant to use the local variable crashed.</p>\n\n<p>I have seen code like</p>\n\n<p>With a,b,c,d do {except they are much longer names, just shortened here)\n begin\n i := xyz;<br>\n end;</p>\n\n<p>It can be a real pain trying to locate where xyz comes from. If it was c, I'd much sooner write it as </p>\n\n<p>i := c.xyz;</p>\n\n<p>You think it's pretty trivial to understand this but not in a function that was 800 lines long that used a with right at the start!</p>\n" }, { "answer_id": 71512, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 3, "selected": false, "text": "<p>It is not likely that \"with\" would make the code run faster, it is more likely that the compiler would compile it to the same executable code.</p>\n\n<p>The main reason people don't like \"with\" is that it can introduce confusion about namespace scope and precedence.</p>\n\n<p>There are cases when this is a real issue, and cases when this is a non-issue (non-issue cases would be as described in the question as \"used sensibly\").</p>\n\n<p>Because of the possible confusion, some developers choose to refrain from using \"with\" completely, even in cases where there may not be such confusion. This may seem dogmatic, however it can be argued that as code changes and grows, the use of \"with\" may remain even after code has been modified to an extent that would make the \"with\" confusing, and thus it is best not to introduce its use in the first place.</p>\n" }, { "answer_id": 71532, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": -1, "selected": false, "text": "<p>We've recently banned it in our Delphi coding stnadards. </p>\n\n<p>The pros were frequently outweighing the cons.</p>\n\n<p>That is bugs were being introduced because of its misuse. These didn't justify the savings in time to write or execute the code.</p>\n\n<p>Yes, using with can led to (mildly) faster code execution.</p>\n\n<p>In the following, foo is only evaluated once:</p>\n\n<pre><code>with foo do\nbegin\n bar := 1;\n bin := x;\n box := 'abc';\nend\n</code></pre>\n\n<p>But, here it is evaluated three times:</p>\n\n<pre><code>foo.bar := 1;\nfoo.bin := x;\nfoo.box := 'abc';\n</code></pre>\n" }, { "answer_id": 71544, "author": "Flint", "author_id": 11877, "author_profile": "https://Stackoverflow.com/users/11877", "pm_score": 1, "selected": false, "text": "<blockquote>... run faster ...</blockquote>\n\n<p>Not necessarily - your compiler/interpreter is generally better at optimizing code than you are.</p>\n\n<p>I think it makes me say \"yuck!\" because it's lazy - when I'm reading code (particularly someone else's) I like to see explicit code. So I'd even write \"this.field\" instead of \"field\" in Java.</p>\n" }, { "answer_id": 2382602, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 2, "selected": false, "text": "<p>It's primarily a maintenance issue.</p>\n\n<p>The idea of WITH makes reasonable sense from a language point of view, and the argument that it keeps code, when used sensibly, smaller and clearer has some validity. However the problem is that most commercial code will be maintained by several different people over it's lifetime, and what starts out as a small, easily parsed, construct when written can easily mutate over time into unwieldy large structures where the scope of the WITH is not easily parsed by the maintainer. This naturally tends to produce bugs, and difficult to find ones at that. </p>\n\n<p>For example say we have a small function foo which contains three or four lines of code which have been wrapped inside a WITH block then there is indeed no issue. However a few years later this function may have expanded, under several programmers, into 40 or 50 lines of code still wrapped inside a WITH. This is now brittle, and is ripe for bugs to be introduced, particularly so if the maintainer stars introducing additional embedded WITH blocks.</p>\n\n<p>WITH has no other benefits - code should be parsed exactly the same and run at the same speed (I did some experiments with this in D6 inside tight loops used for 3D rendering and I could find no difference). The inability of the debugger to handle it is also an issue - but one that should have been fixed a while back and would be worth ignoring if there were any benefit. Unfortunately there isn't.</p>\n" }, { "answer_id": 2384989, "author": "markus_ja", "author_id": 192292, "author_profile": "https://Stackoverflow.com/users/192292", "pm_score": 4, "selected": false, "text": "<p>It would be great if the <code>with</code> statement would be extented the following way:</p>\n\n<pre><code>with x := ARect do\nbegin\n x.Left := 0;\n x.Rigth := 0;\n ...\nend;\n</code></pre>\n\n<p>You wouldn't need to declare a variable 'x'. It will be created by the compiler. It's quick to write and no confusion, which function is used.</p>\n" }, { "answer_id": 3126973, "author": "mmmm", "author_id": 85592, "author_profile": "https://Stackoverflow.com/users/85592", "pm_score": 2, "selected": false, "text": "<p>You can combine with statements, so you end up with </p>\n\n<pre><code>with Object1, Object2, Object3 do\nbegin\n //... Confusing statements here\nend\n</code></pre>\n\n<p>And if you think that the debugger is confused by one with, I don't see how anyone can determine what is going on in the <code>with</code> block</p>\n" }, { "answer_id": 3342110, "author": "ijcro", "author_id": 403174, "author_profile": "https://Stackoverflow.com/users/403174", "pm_score": -1, "selected": false, "text": "<p>For Delphi 2005 is exist hard error in with-do statement - evaluate pointer is lost and repace with pointer up. There have to use a local variable, not object type directly.</p>\n" }, { "answer_id": 12267500, "author": "Arnaud Bouchez", "author_id": 458259, "author_profile": "https://Stackoverflow.com/users/458259", "pm_score": 3, "selected": false, "text": "<p>In fact:</p>\n\n<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);\nbegin\n with ARect do FillRectS(Left, Top, Right, Bottom, Value);\nend;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);\nbegin\n FillRectS(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom, Value);\nend;\n</code></pre>\n\n<p>Will generate exactly the same assembler code.</p>\n\n<p>The performance penalty can exist if the value of the <code>with</code> clause is a function or a method. In this case, if you want to have good maintenance AND good speed, just do what the compiler does behind the scene, i.e. <em>create a temporary variable</em>.</p>\n\n<p>In fact:</p>\n\n<pre><code>with MyRect do\nbegin\n Left := 0;\n Right := 0;\nend;\n</code></pre>\n\n<p>is encoded in pseudo-code as such by the compiler:</p>\n\n<pre><code>var aRect: ^TRect;\n\naRect := @MyRect;\naRect^.Left := 0;\naRect^.Right := 0;\n</code></pre>\n\n<p>Then <code>aRect</code> can be just a CPU register, but can also be a true temporary variable on stack. Of course, I use pointers here since <code>TRect</code> is a <code>record</code>. It is more direct for objects, since they already are pointers.</p>\n\n<p>Personally, I used with sometimes in my code, but I almost check every time the asm generated to ensure that it does what it should. Not everyone is able or has the time to do it, so IMHO a <em>local variable</em> is a good alternative to with.</p>\n\n<p>I really do not like such code:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n for j := 0 to ObjList[i].NestedList.Count-1 do\n begin\n ObjList[i].NestedList[j].Member := 'Toto';\n ObjList[i].NestedList[j].Count := 10;\n end;\n</code></pre>\n\n<p>It is still pretty readable with with:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n for j := 0 to ObjList[i].NestedList.Count-1 do\n with ObjList[i].NestedList[j] do\n begin\n Member := 'Toto';\n Count := 10;\n end;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n with ObjList[i] do\n for j := 0 to NestedList.Count-1 do\n with NestedList[j] do\n begin\n Member := 'Toto';\n Count := 10;\n end;\n</code></pre>\n\n<p>but if the inner loop is huge, a local variable does make sense:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\nbegin\n Obj := ObjList[i];\n for j := 0 to Obj.NestedList.Count-1 do\n begin\n Nested := Obj.NestedList[j];\n Nested.Member := 'Toto';\n Nested.Count := 10;\n end;\nend;\n</code></pre>\n\n<p>This code won't be slower than <code>with</code>: compiler does it in fact behind the scene!</p>\n\n<p>By the way, it will allow easier debugging: you can put a breakpoint, then point your mouse on <code>Obj</code> or <code>Nested</code> directly to get the internal values.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11781/" ]
I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting). Here's an example: ``` procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32); begin with ARect do FillRectS(Left, Top, Right, Bottom, Value); end; ``` I like using `with`. What's wrong with me?
One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult. A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer. ``` procedure TMyForm.ButtonClick(...) begin with OtherForm do begin Left := 10; Top := 20; CallThisFunction; end; end; ``` Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method. And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't. Using multiple objects in the with multiplies the problems. See <http://blog.marcocantu.com/blog/with_harmful.html>
71,423
<p>I want to disable the selection of certain rows in a datagridview.</p> <p>It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)</p> <p>Thankx,</p>
[ { "answer_id": 71665, "author": "szevvy", "author_id": 11437, "author_profile": "https://Stackoverflow.com/users/11437", "pm_score": 5, "selected": true, "text": "<p>If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.</p>\n\n<p>If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>public class MyDataGridView : DataGridView\n{\n protected override void SetSelectedRowCore(int rowIndex, bool selected)\n {\n if (selected &amp;&amp; WantRowSelection(rowIndex))\n {\n base.SetSelectedRowCore(rowIndex, selected);\n }\n }\n\n protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)\n {\n if (selected &amp;&amp; WantRowSelection(rowIndex))\n {\n base.SetSelectedRowCore(rowIndex, selected);\n }\n }\n\n bool WantRowSelection(int rowIndex)\n {\n //return true if you want the row to be selectable, false otherwise\n }\n}\n</code></pre>\n\n<p>If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.</p>\n" }, { "answer_id": 15474300, "author": "Asad Naeem", "author_id": 390163, "author_profile": "https://Stackoverflow.com/users/390163", "pm_score": -1, "selected": false, "text": "<pre><code>Private Sub dgvSomeDataGridView_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgvSomeDataGridView.SelectionChanged\n dgvSomeDataGridView.ClearSelection()\nEnd Sub\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4392/" ]
I want to disable the selection of certain rows in a datagridview. It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition) Thankx,
If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected. If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell. Here's an example: ``` public class MyDataGridView : DataGridView { protected override void SetSelectedRowCore(int rowIndex, bool selected) { if (selected && WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected) { if (selected && WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } bool WantRowSelection(int rowIndex) { //return true if you want the row to be selectable, false otherwise } } ``` If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.
71,440
<p>I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?</p> <pre><code>class MyControl : System.Web.UI.UserControl { // Attribute to prevent property from showing in VS Property Window? public bool SampleProperty { get; set; } // other stuff } </code></pre>
[ { "answer_id": 71454, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 5, "selected": true, "text": "<p>Use the following attribute ...</p>\n\n<pre><code>using System.ComponentModel;\n\n[Browsable(false)]\npublic bool SampleProperty { get; set; }\n</code></pre>\n\n<p>In VB.net, this <a href=\"https://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481\">will be</a>:</p>\n\n<pre><code>&lt;System.ComponentModel.Browsable(False)&gt;\n</code></pre>\n" }, { "answer_id": 71459, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.c-sharpcorner.com/UploadFile/mgold/PropertyGridInCSharp11302005004139AM/PropertyGridInCSharp.aspx\" rel=\"nofollow noreferrer\">Tons of attributes</a> out there to control how the PropertyGrid works.</p>\n\n<pre><code>[Browsable(false)]\npublic bool HiddenProperty {get;set;}\n</code></pre>\n" }, { "answer_id": 71481, "author": "Codeslayer", "author_id": 4021, "author_profile": "https://Stackoverflow.com/users/4021", "pm_score": 2, "selected": false, "text": "<p>Use the <code>System.ComponentModel.Browsable</code> attribute to</p>\n\n<pre><code>&gt; ' VB\n&gt; \n&gt; &lt;System.ComponentModel.Browsable(False)&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// C#\n [System.ComponentModel.Browsable(false)]\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ]
I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up? ``` class MyControl : System.Web.UI.UserControl { // Attribute to prevent property from showing in VS Property Window? public bool SampleProperty { get; set; } // other stuff } ```
Use the following attribute ... ``` using System.ComponentModel; [Browsable(false)] public bool SampleProperty { get; set; } ``` In VB.net, this [will be](https://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481): ``` <System.ComponentModel.Browsable(False)> ```
71,468
<p>Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program </p>
[ { "answer_id": 71674, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 1, "selected": false, "text": "<p>The newpki client claims to be able to do that.\n<a href=\"http://www.newpki.org/\" rel=\"nofollow noreferrer\">http://www.newpki.org/</a></p>\n" }, { "answer_id": 71686, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 0, "selected": false, "text": "<p>Can you test it over HTTP as described in the specs in Appendix A? If so, then you can use any web test util. Since you mentioned Java, <a href=\"http://jakarta.apache.org/jmeter/\" rel=\"nofollow noreferrer\">JMeter</a> comes to mind. With JMeter, you can create your java code to do validation, etc and re-use it in your test cases.</p>\n\n<p>Can you use something other than CMD line, such as a BASH script via <a href=\"http://cygwin.com\" rel=\"nofollow noreferrer\">Cygwin</a>?</p>\n\n<p>You'd still have to script some things to validate the test, perhaps using <a href=\"http://www.openssl.org/docs/apps/ocsp.html\" rel=\"nofollow noreferrer\">openssl</a>?</p>\n\n<pre>\ncurl http://some.ocsp.url/ > resp.der\nopenssl ocsp -respin resp.der -text\n</pre>\n\n<p>See page <a href=\"http://www.ietf.org/rfc/rfc2560.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc2560.txt</a></p>\n" }, { "answer_id": 72957, "author": "JJarava", "author_id": 12344, "author_profile": "https://Stackoverflow.com/users/12344", "pm_score": 3, "selected": true, "text": "<p>Looking a bit more, I think I've found some answers:</p>\n\n<p>a) OpenSSL at the rescue:</p>\n\n<pre><code>openssl ocsp -whatever\n</code></pre>\n\n<p>For more info, <a href=\"http://www.openssl.org/docs/apps/ocsp.html\" rel=\"nofollow noreferrer\">http://www.openssl.org/docs/apps/ocsp.html</a></p>\n\n<p>b) <a href=\"http://www.openvalidation.org/\" rel=\"nofollow noreferrer\">http://www.openvalidation.org/</a> is another way of testing a cert. And via its links, I got to:</p>\n\n<ul>\n<li><a href=\"http://security.polito.it/tools/ocsp/\" rel=\"nofollow noreferrer\">http://security.polito.it/tools/ocsp/</a></li>\n<li>Ascertia OCSP Client tool (<a href=\"http://www.ascertia.com/products/ocsptool/\" rel=\"nofollow noreferrer\">http://www.ascertia.com/products/ocsptool/</a>)</li>\n<li>Ascertia OCSP Crusher tool (an OCSP load generator) (<a href=\"http://www.ascertia.com/products/ocspCrusher/\" rel=\"nofollow noreferrer\">http://www.ascertia.com/products/ocspCrusher/</a>)</li>\n</ul>\n\n<p>Thanks to all the answers!</p>\n" }, { "answer_id": 108678, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>bouncycastle has a Java crypto-provider and support for OCSP requests and responses. The differences between OCSPReq and OCSPRequest and OCSPResp and OCSPResponse class are a little confusing, though.</p>\n" }, { "answer_id": 3910224, "author": "ohe", "author_id": 335247, "author_profile": "https://Stackoverflow.com/users/335247", "pm_score": 1, "selected": false, "text": "<p>Here is a good ressource to have a simple OCSP Client or OCSP Responder with OpenSSL : <a href=\"http://backreference.org/2010/05/09/ocsp-verification-with-openssl/\" rel=\"nofollow\">http://backreference.org/2010/05/09/ocsp-verification-with-openssl/</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program
Looking a bit more, I think I've found some answers: a) OpenSSL at the rescue: ``` openssl ocsp -whatever ``` For more info, <http://www.openssl.org/docs/apps/ocsp.html> b) <http://www.openvalidation.org/> is another way of testing a cert. And via its links, I got to: * <http://security.polito.it/tools/ocsp/> * Ascertia OCSP Client tool (<http://www.ascertia.com/products/ocsptool/>) * Ascertia OCSP Crusher tool (an OCSP load generator) (<http://www.ascertia.com/products/ocspCrusher/>) Thanks to all the answers!
71,469
<p>Let's assume we've got the following Java code:</p> <pre><code>public class Maintainer { private Map&lt;Enum, List&lt;Listener&gt;&gt; map; public Maintainer() { this.map = new java.util.ConcurrentHashMap&lt;Enum, List&lt;Listener&gt;&gt;(); } public void addListener( Listener listener, Enum eventType ) { List&lt;Listener&gt; listeners; if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList&lt;Listener&gt;(); map.put( eventType, listeners ); } listeners.add( listener ); } } </code></pre> <p>This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.</p> <p>Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have <em>java.lang.Enum</em> as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.</p> <p>Could anyone tell me how do I Spring_ify_ this? What I want to achive is:<br> 1. Define <em>Maintainer</em> class as a Spring bean.<br> 2. Make it so that all sorts of listeners would be able to register themselves to <em>Maintainer</em> via XML by using <em>addListener</em> method. Spring doc nor Google are very generous in examples.</p> <p>Is there a way to achieve this easily?</p>
[ { "answer_id": 71504, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>What would be wrong with doing something like the following:</p>\n\n<p>Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.</p>\n\n<p>Create a DefaultMaintainer class (as above) which implements Maintainer.</p>\n\n<p>Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.</p>\n\n<p>other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)</p>\n" }, { "answer_id": 73129, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>You said \"... you can't have java.lang.Enum as\"\n annotation param ...\"</p>\n</blockquote>\n\n<p>I think you are wrong on that. I have recently used on a project something like this :</p>\n\n<pre><code>public @interface MyAnnotation {\n MyEnum value();\n}\n</code></pre>\n" }, { "answer_id": 75192, "author": "flicken", "author_id": 12880, "author_profile": "https://Stackoverflow.com/users/12880", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>1) Define Maintainer class as a Spring bean.</p>\n</blockquote>\n\n<p>Standard Spring syntax applies:</p>\n\n<pre><code>&lt;bean id=\"maintainer\" class=\"com.example.Maintainer\"/&gt;\n</code></pre>\n\n<blockquote>\n <p>2) Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples.</p>\n</blockquote>\n\n<p>This is trickier. You <em>could</em> use <code>MethodInvokingFactoryBean</code> to individually call <code>maintainer#addListener</code>, like so:</p>\n\n<pre><code>&lt;bean id=\"listener\" class=\"com.example.Listener\"/&gt;\n\n&lt;bean id=\"maintainer.addListener\" class=\"org.springframework.beans.factory.config.MethodInvokingFactoryBean\"&gt;\n &lt;property name=\"targetObject\" ref=\"maintainer\"/&gt;\n &lt;property name=\"targetMethod\" value=\"addListener\"/&gt;\n &lt;property name=\"arguments\"&gt;\n &lt;list&gt;\n &lt;ref&gt;listener&lt;/ref&gt;\n &lt;value&gt;com.example.MyEnum&lt;/value&gt;\n &lt;/list&gt;\n &lt;/property&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>However, this is unwieldy, and potentially error-prone. I attempted something similar on a project, and created a Spring utility class to help out instead. I don't have the source code available at the moment, so I'll describe how to implement what I did. </p>\n\n<p>1) Refactor the event types listened to into a <code>MyListener</code> interface</p>\n\n<pre><code>public interface MyListener extends Listener {\n public Enum[] getEventTypes()\n}\n</code></pre>\n\n<p>Which changes the registration method to</p>\n\n<pre><code>public void addListener(MyListener listener)\n</code></pre>\n\n<p>2) Create Spring helper class that finds all relevant listeners in the context, and calls maintainer#addListener for each listener found. I would start with <code>BeanFilteringSupport</code>, and also implement <code>BeanPostProcessor</code> (or <code>ApplicationListener</code>) to register the beans after all beans have been instantiated.</p>\n" }, { "answer_id": 81555, "author": "mindas", "author_id": 7345, "author_profile": "https://Stackoverflow.com/users/7345", "pm_score": 0, "selected": false, "text": "<p>Thank you all for the answers. First, A quick follow up on all answers.<br>\n1. (alexvictor) Yes, you can have concrete <em>enum</em> as annotation param, but not <em>java.lang.Enum</em>.<br>\n2. Answer provided by flicken is correct, but unfortunately a bit scary. I am not a Spring expert but doing things this way (creating methods for easier Spring access) this seems to be a bit overkill, as is the <em>MethodInvokingFactoryBean</em> solution. Although I wanted to express my sincere thanks for your time and effort.<br>\n3. The answer by Phill is a bit unusual (instead of injecting listener bean, inject its maintainer!), but, I believe, the cleanest of all available. I think I will go down this path.</p>\n\n<p>Again, a big thanks you for your help.</p>\n" }, { "answer_id": 93461, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 2, "selected": false, "text": "<p>Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener:</p>\n\n<pre><code> if( ( listeners = map.get( eventType ) ) == null ) {\n listeners = new java.util.concurrent.CopyOnWriteArrayList&lt;Listener&gt;();\n map.put( eventType, listeners );\n }\n listeners.add( listener );\n</code></pre>\n\n<p>If two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten.</p>\n\n<p>To fix this, change:</p>\n\n<pre><code>private Map&lt;Enum, List&lt;Listener&gt;&gt; map;\n\n...\n\nmap.put( eventType, listeners );\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>private ConcurrentMap&lt;Enum, List&lt;Listener&gt;&gt; map;\n\n...\n\nmap.putIfAbsent( eventType, listeners );\nlisteners = map.get( eventType );\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7345/" ]
Let's assume we've got the following Java code: ``` public class Maintainer { private Map<Enum, List<Listener>> map; public Maintainer() { this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>(); } public void addListener( Listener listener, Enum eventType ) { List<Listener> listeners; if( ( listeners = map.get( eventType ) ) == null ) { listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>(); map.put( eventType, listeners ); } listeners.add( listener ); } } ``` This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships. Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have *java.lang.Enum* as annotation param, also there's a set of various classloader issues) therefore decided to use Spring. Could anyone tell me how do I Spring\_ify\_ this? What I want to achive is: 1. Define *Maintainer* class as a Spring bean. 2. Make it so that all sorts of listeners would be able to register themselves to *Maintainer* via XML by using *addListener* method. Spring doc nor Google are very generous in examples. Is there a way to achieve this easily?
What would be wrong with doing something like the following: Defining a 'Maintainer' interface with the addListener(Listener, Enum) method. Create a DefaultMaintainer class (as above) which implements Maintainer. Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer. other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)
71,478
<p>Is it possible in <code>PHP (as it is in C++)</code> to declare a <code>class method</code> OUTSIDE the <code>class definition?</code></p>
[ { "answer_id": 71502, "author": "Silver Dragon", "author_id": 9440, "author_profile": "https://Stackoverflow.com/users/9440", "pm_score": 1, "selected": false, "text": "<p>No. </p>\n\n<p>You can extend previously declared classes, though, if that helps.</p>\n" }, { "answer_id": 71545, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 3, "selected": false, "text": "<p>No, as of PHP 5.2. However, you may use <code>__call</code> magic method to forward call to arbitrary function or method.</p>\n\n<pre><code>class A {\n\n public function __call($method, $args) {\n if ($method == 'foo') {\n return call_user_func_array('bar', $args);\n }\n }\n\n}\n\nfunction bar($x) {\n echo $x;\n}\n\n$a = new A();\n$a-&gt;foo('12345'); // will result in calling bar('12345')\n</code></pre>\n\n<p>In PHP 5.4 there is support for <em>traits</em>. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits <a href=\"http://www.stefan-marr.de/artikel/rfc-traits-for-php.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 71550, "author": "deresh", "author_id": 11851, "author_profile": "https://Stackoverflow.com/users/11851", "pm_score": 0, "selected": false, "text": "<p>No it is not posible. if you define function/method outside class construct it becomes global function.</p>\n" }, { "answer_id": 71551, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>You could perhaps override <a href=\"http://php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">__call or __callStatic</a> to locate a missing method at runtime, but you'd have to make up your own system for locating and calling the code. For example, you could load a \"Delegate\" class to handle the method call.</p>\n\n<p>Here's an example - if you tried to call $foo->bar(), the class would attempt to create a FooDelegate_bar class, and call bar() on it with the same arguments. If you've got class auto-loading set up, the delegate can live in a separate file until required...</p>\n\n<pre><code>class Foo {\n\n public function __call($method, $args) {\n $delegate=\"FooDelegate_\".$method;\n if (class_exists($delegate))\n {\n $handler=new $delegate($this);\n return call_user_func_array(array(&amp;$handler, $method), $args);\n }\n\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 71559, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>C++ can't do this either. Did you mix up declaration with de<em>finition</em>?</p>\n" }, { "answer_id": 71611, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 0, "selected": false, "text": "<p>No, as everyone has said, it is not strictly possible.</p>\n\n<p>However, you can do <a href=\"http://www.symfony-project.org/book/1_0/17-Extending-Symfony\" rel=\"nofollow noreferrer\">something like this</a> to emulate a mixin in PHP or add methods to a class at runtime, which is about as close as you're going to get. Basically, it's just using design patterns to achieve the same functionality. Zope 3 does something similar to emulate mixins in Python, another language that doesn't support them directly.</p>\n" }, { "answer_id": 1267223, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Yes it is possible to add a method to a PHP class after it is defined. You want to use <a href=\"http://www.php.net/manual/en/ref.classkit.php\" rel=\"noreferrer\">classkit</a>, which is an \"experimental\" extension. It appears that this extension isn't enabled by default however, so it depends on if you can compile a custom PHP binary or load PHP DLLs if on windows (for instance Dreamhost does allow custom PHP binaries, and they're pretty easy to setup).</p>\n\n<pre><code>&lt;?php\nclass A { }\nclasskit_method_add('A', 'bar', '$message', 'echo $message;', \n CLASSKIT_ACC_PUBLIC); \n$a = new A();\n$a-&gt;bar('Hello world!');\n</code></pre>\n\n<p>Example from the PHP manual:</p>\n\n<pre><code>&lt;?php\nclass Example {\n function foo() {\n echo \"foo!\\n\";\n }\n}\n\n// create an Example object\n$e = new Example();\n\n// Add a new public method\nclasskit_method_add(\n 'Example',\n 'add',\n '$num1, $num2',\n 'return $num1 + $num2;',\n CLASSKIT_ACC_PUBLIC\n);\n\n// add 12 + 4\necho $e-&gt;add(12, 4);\n</code></pre>\n" }, { "answer_id": 8020459, "author": "jocap", "author_id": 305047, "author_profile": "https://Stackoverflow.com/users/305047", "pm_score": 2, "selected": false, "text": "<p>As PHP 5.3 supports closures, you can dynamically define instance methods as variables holding closures:</p>\n\n<pre><code>$class-&gt;foo = function (&amp;$self, $n) {\n print \"Current \\$var: \" . $self-&gt;var . \"\\n\";\n $self-&gt;var += $n;\n print \"New \\$var: \" .$self-&gt;var . \"\\n\";\n};\n</code></pre>\n\n<p>Taking <code>$self</code> (you can't use <code>$this</code> outside object context) as a reference (<code>&amp;</code>), you can modify the instance.</p>\n\n<p>However, problems occur when you try to call the function normally:</p>\n\n<pre><code>$class-&gt;foo(2);\n</code></pre>\n\n<p>You get a fatal error. PHP thinks <code>foo</code> is a method of <code>$class</code>, because of the syntax. Also, you must pass the instance as the first argument.</p>\n\n<p>There is luckily a special function for calling functions by name called <code>call_user_func</code>:</p>\n\n<pre><code>call_user_func($class-&gt;foo, &amp;$class, 2);\n# =&gt; Current $var: 0\n# =&gt; New $var: 2\n</code></pre>\n\n<p>Just remember to put <code>&amp;</code> before the instance variable.</p>\n\n<p>What's even easier is if you use the <code>__call</code> magic method:</p>\n\n<pre><code>class MyClass {\n public function __call ($method, $arguments) {\n if (isset($this-&gt;$method)) {\n call_user_func_array($this-&gt;$method, array_merge(array(&amp;$this), $arguments));\n }\n }\n}\n</code></pre>\n\n<p>Now you can call <code>$class-&gt;foo(2)</code> instead. The magic <code>__call</code> method catches the call to an unknown method, and calls the closure in the <code>$class-&gt;foo</code> variable with the same name as the called method.</p>\n\n<p>Of course, if <code>$class-&gt;var</code> was private, the closure in stored in the <code>$class-&gt;foo</code> variable wouldn't be able to access it.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible in `PHP (as it is in C++)` to declare a `class method` OUTSIDE the `class definition?`
No, as of PHP 5.2. However, you may use `__call` magic method to forward call to arbitrary function or method. ``` class A { public function __call($method, $args) { if ($method == 'foo') { return call_user_func_array('bar', $args); } } } function bar($x) { echo $x; } $a = new A(); $a->foo('12345'); // will result in calling bar('12345') ``` In PHP 5.4 there is support for *traits*. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits [here](http://www.stefan-marr.de/artikel/rfc-traits-for-php.html).
71,518
<p>I just tried FxCop. It does detect unused private methods, but not unused public. Is there a custom rule that I can download, plug-in that will detect public methods that aren't called from within the same assembly?</p>
[ { "answer_id": 71538, "author": "Loofer", "author_id": 5552, "author_profile": "https://Stackoverflow.com/users/5552", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.ndepend.com/\" rel=\"nofollow noreferrer\">NDepend</a> is your friend for this kind of thing</p>\n" }, { "answer_id": 71587, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 1, "selected": false, "text": "<p>How would it know that the public methods are unused?</p>\n\n<p>By marking a method as public it can be accessed by any application which references your library.</p>\n" }, { "answer_id": 71730, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>If a method is unused and public FxCop assumes that you have made it public for external things to access.</p>\n\n<p>If unused public methods lead to FxCop warnings writing APIs and the like would be a pain - you'd get loads of FxCop warnings for methods you intend others to use.</p>\n\n<p>If you don't need anything external to access your assembly/exe consider find-replacing <code>public</code> with <code>internal</code>. Your application will run the same and FxCop will be able to find the unreferenced internal methods.</p>\n\n<p>If you do need external access find which methods are really needed to be external, and make all the rest internal.</p>\n\n<p>Any methods you make externally visible could have unit tests too.</p>\n" }, { "answer_id": 71929, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 4, "selected": false, "text": "<p>Corey, my answer of using FxCop had assumed you were interested in removing unused private members, however to solve the problem with other cases you can try using <a href=\"http://www.ndepend.com/\" rel=\"nofollow noreferrer\">NDepend</a>. Here is some CQL to detect unused public members (adapted from an article listed below):</p>\n\n<pre><code>// &lt;Name&gt;Potentially unused methods&lt;/Name&gt;\nWARN IF Count &gt; 0 IN SELECT METHODS WHERE\n MethodCa == 0 AND // Ca=0 -&gt; No Afferent Coupling -&gt; The method \n // is not used in the context of this\n // application.\n\n IsPublic AND // Check for unused public methods\n\n !IsEntryPoint AND // Main() method is not used by-design.\n\n !IsExplicitInterfaceImpl AND // The IL code never explicitely calls \n // explicit interface methods implementation.\n\n !IsClassConstructor AND // The IL code never explicitely calls class\n // constructors.\n\n !IsFinalizer // The IL code never explicitely calls\n // finalizers.\n</code></pre>\n\n<p>Source: <a href=\"http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx\" rel=\"nofollow noreferrer\">Patrick Smacchia's \"Code metrics on Coupling, Dead Code, Design flaws and Re-engineering</a>. The article also goes over detecting dead fields and types.</p>\n\n<p><em>(EDIT: made answer more understandable)</em></p>\n\n<hr>\n\n<p>EDIT 11th June 2012: <em>Explain new NDepend facilities concerning unused code. Disclaimer: I am one of the developer of this tool.</em></p>\n\n<p>Since NDepend v4 released in May 2012, the tool proposes to write <a href=\"http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx\" rel=\"nofollow noreferrer\">Code Rule over LINQ Query (CQLinq)</a>. Around <a href=\"http://www.ndepend.com/DefaultRules/webframe.html\" rel=\"nofollow noreferrer\">200 default code rules</a> are proposed, 3 of them being dedicated to <em>unused/dead code</em> detection:</p>\n\n<ul>\n<li><a href=\"http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Types.html\" rel=\"nofollow noreferrer\">Potentially dead Types</a> (hence detect unused class, struct, interface, delegate...)</li>\n<li><strong><a href=\"http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Methods.html\" rel=\"nofollow noreferrer\">Potentially dead Methods</a></strong> (hence detect unused method, ctor, property getter/setter...)</li>\n<li><a href=\"http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Fields.html\" rel=\"nofollow noreferrer\">Potentially dead Fields</a></li>\n</ul>\n\n<p>These CQLinq code rules are more powerful than the previous CQL ones. If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used <em>only</em> by unused dead types and methods (recursive).</p>\n\n<p>This is <em>static analysis</em>, hence the prefix <em>Potentially</em> in the rule names. If a code element is used <em>only</em> through reflection, these rules might consider it as unused which is not the case. </p>\n\n<p>In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually <em>unused/dead</em> code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
I just tried FxCop. It does detect unused private methods, but not unused public. Is there a custom rule that I can download, plug-in that will detect public methods that aren't called from within the same assembly?
Corey, my answer of using FxCop had assumed you were interested in removing unused private members, however to solve the problem with other cases you can try using [NDepend](http://www.ndepend.com/). Here is some CQL to detect unused public members (adapted from an article listed below): ``` // <Name>Potentially unused methods</Name> WARN IF Count > 0 IN SELECT METHODS WHERE MethodCa == 0 AND // Ca=0 -> No Afferent Coupling -> The method // is not used in the context of this // application. IsPublic AND // Check for unused public methods !IsEntryPoint AND // Main() method is not used by-design. !IsExplicitInterfaceImpl AND // The IL code never explicitely calls // explicit interface methods implementation. !IsClassConstructor AND // The IL code never explicitely calls class // constructors. !IsFinalizer // The IL code never explicitely calls // finalizers. ``` Source: [Patrick Smacchia's "Code metrics on Coupling, Dead Code, Design flaws and Re-engineering](http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx). The article also goes over detecting dead fields and types. *(EDIT: made answer more understandable)* --- EDIT 11th June 2012: *Explain new NDepend facilities concerning unused code. Disclaimer: I am one of the developer of this tool.* Since NDepend v4 released in May 2012, the tool proposes to write [Code Rule over LINQ Query (CQLinq)](http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx). Around [200 default code rules](http://www.ndepend.com/DefaultRules/webframe.html) are proposed, 3 of them being dedicated to *unused/dead code* detection: * [Potentially dead Types](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Types.html) (hence detect unused class, struct, interface, delegate...) * **[Potentially dead Methods](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Methods.html)** (hence detect unused method, ctor, property getter/setter...) * [Potentially dead Fields](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Fields.html) These CQLinq code rules are more powerful than the previous CQL ones. If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used *only* by unused dead types and methods (recursive). This is *static analysis*, hence the prefix *Potentially* in the rule names. If a code element is used *only* through reflection, these rules might consider it as unused which is not the case. In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually *unused/dead* code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not.
71,534
<p>I hope I haven't painted myself into a corner. I've gotten what seems to be most of the way through implementing a Makefile and I can't get the last bit to work. I hope someone here can suggest a technique to do what I'm trying to do.</p> <p>I have what I'll call "bills of materials" in version controlled files in a source repository and I build something like:</p> <pre><code>make VER=x </code></pre> <p>I want my Makefile to use $(VER) as a tag to retrieve a BOM from the repository, generate a dependency file to include in the Makefile, rescan including that dependency, and then build the product. </p> <p>More generally, my Makefile may have several targets -- A, B, C, etc. -- and I can build different versions of each so I might do:</p> <pre><code>make A VER=x make B VER=y make C VER=z </code></pre> <p>and the dependency file includes information about all three targets.</p> <p>However, creating the dependency file is somewhat expensive so if I do:</p> <pre><code>make A VER=x ...make source (not BOM) changes... make A VER=x </code></pre> <p>I'd really like the Makefile to not regenerate the dependency. And just to make things as complicated as possible, I might do:</p> <pre><code>make A VER=x .. change version x of A's BOM and check it in make A VER=x </code></pre> <p>so I need to regenerate the dependency on the second build.</p> <p>The check out messes up the timestamps used to regenerate the dependencies so I think I need a way for the dependency file to depend not on the BOM but on some indication that the BOM changed.</p> <p>What I've come to is making the BOM checkout happen in a .PHONY target (so it always gets checked out) and keeping track of the contents of the last checkout in a ".sig" file (if the signature file is missing or the contents are different than the signature of the new file, then the BOM changed), and having the dependency generation depend on the signatures). At the top of my Makefile, I have some setup:</p> <pre><code>BOMS = $(addsuffix .bom,$(MAKECMDGOALS) SIGS = $(subst .bom,.sig,$(BOMS)) DEP = include.d -include $(DEP) </code></pre> <p>And it seems I always need to do:</p> <pre><code>.PHONY: $(BOMS) $(BOMS): ...checkout TAG=$(VER) $@ </code></pre> <p>But, as noted above, if i do just that, and continue:</p> <pre><code>$(DEP) : $(BOMS) ... recreate dependency </code></pre> <p>Then the dependency gets updated every time I invoke make. So I try:</p> <pre><code>$(DEP) : $(SIGS) ... recreate dependency </code></pre> <p>and</p> <pre><code>$(BOMS): ...checkout TAG=$(VER) $@ ...if $(subst .bom,.sig,$@) doesn't exist ... create signature file ...else ... if new signature is different from file contents ... update signature file ... endif ...endif </code></pre> <p>But the dependency generation doesn't get tripped when the signature changes. I think it's because because $(SIGS) isn't a target, so make doesn't notice when the $(BOMS) rule updates a signature.</p> <p>I tried creating a .sig:.bom rule and managing the timestamps of the checked out BOM with touch but that didn't work.</p> <p>Someone suggested something like:</p> <pre><code>$(DEP) : $(SIGS) ... recreate dependency $(BOMS) : $(SIGS) ...checkout TAG=$(VER) $@ $(SIGS) : ...if $(subst .bom,.sig,$(BOMS)) doesn't exist ... create it ...else ... if new signature is different from file contents ... update signature file ... endif ...endif </code></pre> <p>but how can the BOM depend on the SIG when the SIG is created from the BOM? As I read that it says, "create the SIG from the BOM and if the SIG is newer than the BOM then checkout the BOM". How do I bootstrap that process? Where does the first BOM come from?</p>
[ { "answer_id": 71623, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 0, "selected": false, "text": "<p>I'm not a make expert, but I would try have $(BOMS) depend on $(SIGS), and making the $(SIGS) target execute the if/else rules that you currently have under the $(BOMS) target.</p>\n\n<pre><code>$(DEP) : $(SIGS)\n ... recreate dependency\n$(BOMS) : $(SIGS)\n ...checkout TAG=$(VER) $@\n$(SIGS) :\n ...if $(subst .bom,.sig,$(BOMS)) doesn't exist\n ... create it\n ...else\n ... if new signature is different from file contents\n ... update signature file\n ... endif\n ...endif\n</code></pre>\n\n<p><strong>EDIT:</strong> You're right, of course, you can't have $(BOM) depend on $(SIGS). But in order to have $(DEP) recreate, you need to have $(SIG) as a target. Maybe have an intermediate target that depends on both $(BOM) and $(SIG).</p>\n\n<pre><code>$(DEP) : $(SIGS)\n ... recreate dependency\n$(NEWTARGET) : $(BOMS) $(SIGS)\n$(BOMS) : \n ...checkout TAG=$(VER) $@\n$(SIGS) :\n ...if $(subst .bom,.sig,$(BOMS)) doesn't exist\n ... create it\n ...else\n ... if new signature is different from file contents\n ... update signature file\n ... endif\n ...endif\n</code></pre>\n\n<p>$(SIGS) might also need to depend on $(BOMS), I would play with that and see.</p>\n" }, { "answer_id": 87291, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 1, "selected": false, "text": "<p>Make is very bad at being able to detect actual file changes, as opposed to just updated timestamps. </p>\n\n<p>It sounds to me that the root of the problem is that the bom-checkout always modifies the timestamp of the bom, causing the dependencies to be regenerated. I would probably try to solve this problem instead -- try to checkout the bom without messing up the timestamp. A wrapper script around the checkout tool might do the trick; first checkout the bom to a temporary file, compare it to the already checked out version, and replace it only if the new one is different.</p>\n\n<p>If you're not strictly bound to using make, there are other tools which are much better at detecting actual file changes (SCons, for example).</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7685/" ]
I hope I haven't painted myself into a corner. I've gotten what seems to be most of the way through implementing a Makefile and I can't get the last bit to work. I hope someone here can suggest a technique to do what I'm trying to do. I have what I'll call "bills of materials" in version controlled files in a source repository and I build something like: ``` make VER=x ``` I want my Makefile to use $(VER) as a tag to retrieve a BOM from the repository, generate a dependency file to include in the Makefile, rescan including that dependency, and then build the product. More generally, my Makefile may have several targets -- A, B, C, etc. -- and I can build different versions of each so I might do: ``` make A VER=x make B VER=y make C VER=z ``` and the dependency file includes information about all three targets. However, creating the dependency file is somewhat expensive so if I do: ``` make A VER=x ...make source (not BOM) changes... make A VER=x ``` I'd really like the Makefile to not regenerate the dependency. And just to make things as complicated as possible, I might do: ``` make A VER=x .. change version x of A's BOM and check it in make A VER=x ``` so I need to regenerate the dependency on the second build. The check out messes up the timestamps used to regenerate the dependencies so I think I need a way for the dependency file to depend not on the BOM but on some indication that the BOM changed. What I've come to is making the BOM checkout happen in a .PHONY target (so it always gets checked out) and keeping track of the contents of the last checkout in a ".sig" file (if the signature file is missing or the contents are different than the signature of the new file, then the BOM changed), and having the dependency generation depend on the signatures). At the top of my Makefile, I have some setup: ``` BOMS = $(addsuffix .bom,$(MAKECMDGOALS) SIGS = $(subst .bom,.sig,$(BOMS)) DEP = include.d -include $(DEP) ``` And it seems I always need to do: ``` .PHONY: $(BOMS) $(BOMS): ...checkout TAG=$(VER) $@ ``` But, as noted above, if i do just that, and continue: ``` $(DEP) : $(BOMS) ... recreate dependency ``` Then the dependency gets updated every time I invoke make. So I try: ``` $(DEP) : $(SIGS) ... recreate dependency ``` and ``` $(BOMS): ...checkout TAG=$(VER) $@ ...if $(subst .bom,.sig,$@) doesn't exist ... create signature file ...else ... if new signature is different from file contents ... update signature file ... endif ...endif ``` But the dependency generation doesn't get tripped when the signature changes. I think it's because because $(SIGS) isn't a target, so make doesn't notice when the $(BOMS) rule updates a signature. I tried creating a .sig:.bom rule and managing the timestamps of the checked out BOM with touch but that didn't work. Someone suggested something like: ``` $(DEP) : $(SIGS) ... recreate dependency $(BOMS) : $(SIGS) ...checkout TAG=$(VER) $@ $(SIGS) : ...if $(subst .bom,.sig,$(BOMS)) doesn't exist ... create it ...else ... if new signature is different from file contents ... update signature file ... endif ...endif ``` but how can the BOM depend on the SIG when the SIG is created from the BOM? As I read that it says, "create the SIG from the BOM and if the SIG is newer than the BOM then checkout the BOM". How do I bootstrap that process? Where does the first BOM come from?
Make is very bad at being able to detect actual file changes, as opposed to just updated timestamps. It sounds to me that the root of the problem is that the bom-checkout always modifies the timestamp of the bom, causing the dependencies to be regenerated. I would probably try to solve this problem instead -- try to checkout the bom without messing up the timestamp. A wrapper script around the checkout tool might do the trick; first checkout the bom to a temporary file, compare it to the already checked out version, and replace it only if the new one is different. If you're not strictly bound to using make, there are other tools which are much better at detecting actual file changes (SCons, for example).
71,561
<p>In a web interface, I've got a text field. When user enters text and accepts with enter, application performs an action.</p> <p>I wanted to test the behavior with Selenium. Unfortunately, invoking 'keypress' with chr(13) insert representation of the character into the field.</p> <p>Is there a way other then submitting the form? I'd like to mimic intended user interaction, without any shortcuts...</p>
[ { "answer_id": 71580, "author": "Scott Gowell", "author_id": 6943, "author_profile": "https://Stackoverflow.com/users/6943", "pm_score": 0, "selected": false, "text": "<p>Though I haven't tested this I imagine you can use \"\\r\\n\" appended to a string to simulate a new line. If not look for the languages equivalent to \"Environment.NewLine;\" ?</p>\n" }, { "answer_id": 71876, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 0, "selected": false, "text": "<p>It's been a while since I've had to do this, but I seem to recall having to use a javascript snippet to execute the carrage return as opposed to using the Selenium keypress function.</p>\n" }, { "answer_id": 71902, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 4, "selected": true, "text": "<p>This Java code works for me:</p>\n\n<pre><code>selenium.keyDown(id, \"\\\\13\");\n</code></pre>\n\n<p>Notice the escape. You probably need something like chr(\\13)</p>\n" }, { "answer_id": 531011, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I ended up using selenium.keyPress(id, \"\\\\13\");</p>\n" }, { "answer_id": 21807435, "author": "user1710861", "author_id": 1710861, "author_profile": "https://Stackoverflow.com/users/1710861", "pm_score": 0, "selected": false, "text": "<p>you can use\nWebelement.sendkeys(Keys.Enter);</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9622/" ]
In a web interface, I've got a text field. When user enters text and accepts with enter, application performs an action. I wanted to test the behavior with Selenium. Unfortunately, invoking 'keypress' with chr(13) insert representation of the character into the field. Is there a way other then submitting the form? I'd like to mimic intended user interaction, without any shortcuts...
This Java code works for me: ``` selenium.keyDown(id, "\\13"); ``` Notice the escape. You probably need something like chr(\13)
71,562
<p>We're using SQL Server 2005 in a project. The users of the system have the ability to search some objects by using 'keywords'. The way we implement this is by creating a full-text catalog for the significant columns in each table that may contain these 'keywords' and then using CONTAINS to search for the keywords the user inputs in the search box in that index. </p> <p>So, for example, let say you have the Movie object, and you want to let the user search for keywords in the title and body of the article, then we'd index both the Title and Plot column, and then do something like:</p> <pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, keywords) OR CONTAINS(Plot, keywords) </code></pre> <p>(It's actually a bit more advanced than that, but nothing terribly complex)</p> <p>Some users are adding numbers to their search, so for example they want to find 'Terminator 2'. The problem here is that, as far as I know, by default SQL Server won't index short words, thus doing a search like this:</p> <pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator 2"') </code></pre> <p>is actually equivalent to doing this:</p> <pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator"') &lt;-- notice the missing '2' </code></pre> <p>and we are getting a plethora of spurious results.</p> <p>Is there a way to force SQL Server to index small words? Preferably, I'd rather index only <em>numbers</em> like 1, 2, 21, etc. I don't know where to define the indexing criteria, or even if it's possible to be as specific as that.</p> <hr> <p>Well, I did that, removed the "noise-words" from the list, and now the behaviour is a bit different, but still not what you'd expect. </p> <p>A search won't for "Terminator 2" (I'm just making this up, my employer might not be really happy if I disclose what we are doing... anyway, the terms are a bit different but the principle the same), I don't get <em>anything</em>, but I know there are objects containing the two words.</p> <p>Maybe I'm doing something wrong? I removed all numbers 1 ... 9 from my noise configuration for ENG, ENU and NEU (neutral), regenerated the indexes, and tried the search.</p>
[ { "answer_id": 71604, "author": "Darren Gosbell", "author_id": 11860, "author_profile": "https://Stackoverflow.com/users/11860", "pm_score": 3, "selected": true, "text": "<p>These \"small words\" are considered \"noise words\" by the full text index. You can customize the list of noise words. This <a href=\"http://arcanecode.wordpress.com/2008/05/29/creating-and-customizing-noise-words-in-sql-server-2005-full-text-search/\" rel=\"nofollow noreferrer\">blog post</a> provides more details. You need to repopulate your full text index when you change the noise words file.</p>\n" }, { "answer_id": 77553, "author": "Darren Gosbell", "author_id": 11860, "author_profile": "https://Stackoverflow.com/users/11860", "pm_score": 0, "selected": false, "text": "<p>I knew about the noise words file, but I'm not why your \"Terminator 2\" example is still giving you issues. You might want to try asking this on the <a href=\"http://forums.microsoft.com/Forums/ShowForum.aspx?ForumID=93&amp;SiteID=1\" rel=\"nofollow noreferrer\">MSDN Database Engine forum</a> where people that specialize in this sort of thing hang out.</p>\n" }, { "answer_id": 124518, "author": "xnagyg", "author_id": 2622295, "author_profile": "https://Stackoverflow.com/users/2622295", "pm_score": 0, "selected": false, "text": "<p>You can combine CONTAINS (or CONTAINSTABLE) with simple where conditions:</p>\n\n<p>SELECT * FROM Movies WHERE CONTAINS(Title, '\"Terminator 2\"') and Title like '%Terminator 2%'</p>\n\n<p>While the CONTAINS find all Terminator the where will eliminate 'Terminator 1'.</p>\n\n<p>Of course the engine is smart enough to start with the CONTAINS not the like condition.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2384/" ]
We're using SQL Server 2005 in a project. The users of the system have the ability to search some objects by using 'keywords'. The way we implement this is by creating a full-text catalog for the significant columns in each table that may contain these 'keywords' and then using CONTAINS to search for the keywords the user inputs in the search box in that index. So, for example, let say you have the Movie object, and you want to let the user search for keywords in the title and body of the article, then we'd index both the Title and Plot column, and then do something like: ``` SELECT * FROM Movies WHERE CONTAINS(Title, keywords) OR CONTAINS(Plot, keywords) ``` (It's actually a bit more advanced than that, but nothing terribly complex) Some users are adding numbers to their search, so for example they want to find 'Terminator 2'. The problem here is that, as far as I know, by default SQL Server won't index short words, thus doing a search like this: ``` SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator 2"') ``` is actually equivalent to doing this: ``` SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator"') <-- notice the missing '2' ``` and we are getting a plethora of spurious results. Is there a way to force SQL Server to index small words? Preferably, I'd rather index only *numbers* like 1, 2, 21, etc. I don't know where to define the indexing criteria, or even if it's possible to be as specific as that. --- Well, I did that, removed the "noise-words" from the list, and now the behaviour is a bit different, but still not what you'd expect. A search won't for "Terminator 2" (I'm just making this up, my employer might not be really happy if I disclose what we are doing... anyway, the terms are a bit different but the principle the same), I don't get *anything*, but I know there are objects containing the two words. Maybe I'm doing something wrong? I removed all numbers 1 ... 9 from my noise configuration for ENG, ENU and NEU (neutral), regenerated the indexes, and tried the search.
These "small words" are considered "noise words" by the full text index. You can customize the list of noise words. This [blog post](http://arcanecode.wordpress.com/2008/05/29/creating-and-customizing-noise-words-in-sql-server-2005-full-text-search/) provides more details. You need to repopulate your full text index when you change the noise words file.
71,565
<p>If I have the following:</p> <pre><code>Public Class Product Public Id As Integer Public Name As String Public AvailableColours As List(Of Colour) Public AvailableSizes As List(Of Size) End Class </code></pre> <p>and I want to get a list of products from the database and display them on a page along with their available sizes and colours, should I </p> <ol> <li>have one method (GetProducts()) which makes use of a single view that joins the relevant tables, that then loops through each row and creates the objects as required? Or…</li> <li>have several methods which are responsible only for creating one object each? eg. GetProducts(), GetAvailableColoursForProduct(id), etc</li> </ol> <p>I'm currently doing a) but as I add other other properties (multiple images, optional tassels, etc) the code is getting very messy (having to check that this isn't the same product as the previous row, has this colour already been added, etc) so I'm tempted to go with b) however, this will really ramp up the number of round trips to the database.</p>
[ { "answer_id": 71606, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Personally, I'd get more data from the database through fewer methods and then bind the UI against only those parts of the data set that I currently want to display. Managing lots of small methods that get out specific chunks of data is harder than getting out large chunks and using only those parts you need.</p>\n" }, { "answer_id": 71622, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You got it. Solution b won't scale up so solution a is key, as far as performance are of concern. By the same time, why should you constrain GetProductDetails() method to grab every data in a single request (hence the SQL view approach) ? Why not have this method perform 3 requests and say goodbye to your messy logic :</p>\n\n<ul>\n<li>One for id and name retrieval</li>\n<li>One for the colors list</li>\n<li>One for sizes list</li>\n</ul>\n\n<p>Depending on the SQL engine you use, these 3 requests could be grouped in a single batch query (one round trip) or would require 3 reound-trips. When adding additional properties to your class, you will have to decide whether to enhance the first request or to add a new one.</p>\n" }, { "answer_id": 71624, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": 0, "selected": false, "text": "<p>In the case above I would probably just have a single static load method especially if all or most of the properties are normally needed:</p>\n\n<pre><code>Public static function Load(Id as integer) as Product\n\nProduct.Load(Id)\n</code></pre>\n\n<p>If say the color property is rarly used and fairly expensive to load then you may want to still use the above but not load the color property from there but dynamically load it from the getter like so:</p>\n\n<pre><code>private _Colors as list(Of Color)\npublic property Colors() as List(Of Color)\n get\n if _Colors is nothing \n . .. . load colors here\n end if\n end get. . . . .\n</code></pre>\n" }, { "answer_id": 71631, "author": "Josti", "author_id": 11231, "author_profile": "https://Stackoverflow.com/users/11231", "pm_score": 0, "selected": false, "text": "<p>Go for Option b) it makes your attributes independent from the Presentation of the Data (e.g. a table)</p>\n\n<p>I think you would benefit from learning more about the <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">MVC-Architecture</a>. It stands for <b>M</b>odel (Your Data -> Product), <b>V</b>iew (the Presentation -> Table) and <b>C</b>ontroller (a new Class that will gather the Data from the Model and processes it for View output)</p>\n\n<p>Confused? It isn't that complicated. Which language is your code snippet from? Many Frameworks like Ruby on Rails, Java Struts or CakePHP practice this seperation of Program layers.</p>\n" }, { "answer_id": 71645, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 0, "selected": false, "text": "<p>b would be faster (performance wise) while reading your setup but it will require you more maintenance code when you will update your class (updating each function).</p>\n\n<p>Now if performance is your true goal, just benchmark it. Write both a and b, load your DB with a few (hundreds of) thousands record and test. Then select your best solution. :)</p>\n\n<p>/Vey</p>\n" }, { "answer_id": 71658, "author": "Richard Dorman", "author_id": 1199234, "author_profile": "https://Stackoverflow.com/users/1199234", "pm_score": 0, "selected": false, "text": "<p>If you are using any of the agile tenants in your coding practises then \"a\" is fine for now but as the complexity of your query grows you should consider refactoring, that is, build your code based on what you know now and refactor when necessary.</p>\n\n<p>If you do refactor I would suggest introducing the <a href=\"http://www.dofactory.com/Patterns/PatternFactory.aspx\" rel=\"nofollow noreferrer\">factory pattern</a> into your code. The factory pattern manages the creation of complex objects and allows you to hide the details of object construction from the code that consumes the object (your UI in this case). This also means that as your object becomes more complex the consumers will be protected from the changes that you may need to make to manage the complexity.</p>\n" }, { "answer_id": 71896, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": true, "text": "<p>You're probably best off benchmarking both and finding out. I've seen situations where just doing multiple queries (MySQL likes this) is faster than JOINs and one big slow query that takes a lot memory and causes the DB server to thrash. I say benchmark because it's going to depend on your database server, how much memory and concurrent connections it has, sizes of your tables, how your indexes are optimized and the size of your typical recordsets. JOINs on large unindexed columns are very expensive (so you should either not do them or add indexes).</p>\n\n<p>You will probably also learn a bit more/be more satisfied in the end if you write at least a little of both implementations (you don't need to write the methods, just a bunch of test queries) and then benchmark, vs. just going with one or the other. The trickiest (but important) part of testing though is simulating concurrent users hitting the DB at the same time -- realistic production memory and cpu load.</p>\n\n<p>Keep in mind you are dealing with 2 issues: One is the DBA issue, how do I make it fastest and most efficient. The second is the programmer who wants pretty, maintainable code. (b) makes your code more readable and extensible than just having giant queries with complicated JOINs, so you may decide to prefer it over (a) as long as it isn't drastically slower.</p>\n" }, { "answer_id": 72051, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 0, "selected": false, "text": "<p>You should look into <a href=\"http://www.castleproject.org/activerecord/index.html\" rel=\"nofollow noreferrer\">Castle</a>'s ActiveRecord <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM</a>, which works on top of <a href=\"http://www.hibernate.org/343.html\" rel=\"nofollow noreferrer\">NHibernate</a>. You develop a data model (like you've done with 'Product') which inherits from AR's base class, which provides great querying abilities. AR/NHibernate provide aggressive query optimization and caching. Performance and scalability problems may disappear. At the very least you have a decent framework within which to tweak. You could easily split your data models up to test B.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984/" ]
If I have the following: ``` Public Class Product Public Id As Integer Public Name As String Public AvailableColours As List(Of Colour) Public AvailableSizes As List(Of Size) End Class ``` and I want to get a list of products from the database and display them on a page along with their available sizes and colours, should I 1. have one method (GetProducts()) which makes use of a single view that joins the relevant tables, that then loops through each row and creates the objects as required? Or… 2. have several methods which are responsible only for creating one object each? eg. GetProducts(), GetAvailableColoursForProduct(id), etc I'm currently doing a) but as I add other other properties (multiple images, optional tassels, etc) the code is getting very messy (having to check that this isn't the same product as the previous row, has this colour already been added, etc) so I'm tempted to go with b) however, this will really ramp up the number of round trips to the database.
You're probably best off benchmarking both and finding out. I've seen situations where just doing multiple queries (MySQL likes this) is faster than JOINs and one big slow query that takes a lot memory and causes the DB server to thrash. I say benchmark because it's going to depend on your database server, how much memory and concurrent connections it has, sizes of your tables, how your indexes are optimized and the size of your typical recordsets. JOINs on large unindexed columns are very expensive (so you should either not do them or add indexes). You will probably also learn a bit more/be more satisfied in the end if you write at least a little of both implementations (you don't need to write the methods, just a bunch of test queries) and then benchmark, vs. just going with one or the other. The trickiest (but important) part of testing though is simulating concurrent users hitting the DB at the same time -- realistic production memory and cpu load. Keep in mind you are dealing with 2 issues: One is the DBA issue, how do I make it fastest and most efficient. The second is the programmer who wants pretty, maintainable code. (b) makes your code more readable and extensible than just having giant queries with complicated JOINs, so you may decide to prefer it over (a) as long as it isn't drastically slower.
71,578
<p>I have a database in ISO-8859-2 format, but I need to create XML in UTF-8. This means that I must encode the database before prinitng in UTF-8. I know very little about ASP.Net, so I'm hoping someone can help.</p> <p>In PHP I would do something like this:</p> <pre><code>db_connect(); mysql_query("SET NAMES 'UTF8'"); mysql_query("SET character_set_client='UTF8'"); </code></pre> <p>This is my ASP.Net code for database connection:</p> <pre><code> 'CONNECTION TO DATABASE dim dbconn,sql,dbcomm dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" &amp; _ "Data Source=" &amp; Server.MapPath("../baze/test.mdb")) dbconn.Open() sql="SELECT * FROM nekretnine, tipovinekretnina WHERE nekretnine.idtipnekretnine = tipovinekretnina.idtipnekretnine ORDER BY nekretnine.idnekretnine" dbcomm=New OleDbCommand(sql,dbconn) dbread=dbcomm.ExecuteReader() while dbread.Read() </code></pre> <p>Where and how do I encode to UTF-8?</p>
[ { "answer_id": 71639, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>The .NET Framework's internal string type is UTF-16. All database access will convert to UTF-16 so that you can view the data appropriately: the database, or the OLE DB provider, will convert to UTF-16.</p>\n\n<p>The XML writer classes (you <em>are</em> using XmlDocument or XmlWriter, right?) will then convert to UTF-8 on the output.</p>\n\n<p>Basically, you shouldn't need to do anything extra.</p>\n" }, { "answer_id": 71640, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": true, "text": "<p>Assuming you have a value string in <code>str</code>, this is the pure-.NET way of doing this.</p>\n\n<pre><code>var encoding = System.Text.Encoding.GetEncoding(\"iso-8859-2\");\n\nvar bytes = System.Text.Encoding.Convert(encoding, System.Text.Encoding.Default, encoding.GetBytes(str));\n\nvar newString = System.Text.Encoding.Default.GetString(bytes);\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
I have a database in ISO-8859-2 format, but I need to create XML in UTF-8. This means that I must encode the database before prinitng in UTF-8. I know very little about ASP.Net, so I'm hoping someone can help. In PHP I would do something like this: ``` db_connect(); mysql_query("SET NAMES 'UTF8'"); mysql_query("SET character_set_client='UTF8'"); ``` This is my ASP.Net code for database connection: ``` 'CONNECTION TO DATABASE dim dbconn,sql,dbcomm dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("../baze/test.mdb")) dbconn.Open() sql="SELECT * FROM nekretnine, tipovinekretnina WHERE nekretnine.idtipnekretnine = tipovinekretnina.idtipnekretnine ORDER BY nekretnine.idnekretnine" dbcomm=New OleDbCommand(sql,dbconn) dbread=dbcomm.ExecuteReader() while dbread.Read() ``` Where and how do I encode to UTF-8?
Assuming you have a value string in `str`, this is the pure-.NET way of doing this. ``` var encoding = System.Text.Encoding.GetEncoding("iso-8859-2"); var bytes = System.Text.Encoding.Convert(encoding, System.Text.Encoding.Default, encoding.GetBytes(str)); var newString = System.Text.Encoding.Default.GetString(bytes); ```
71,585
<p>Since generics were introduced, Class is parametrized, so that List.class produces Class&lt;List>. This is clear.</p> <p>What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class&lt;List&lt;String>>. Like in this snippet:</p> <pre><code>public class GenTest { static &lt;T&gt; T instantiate(Class&lt;T&gt; clazz) throws Exception { return clazz.newInstance(); } public static void main(String[] args) throws Exception { // Is there a way to avoid waring on the line below // without using @SuppressWarnings("unchecked")? // ArrayList.class is Class&lt;ArrayList&gt;, but I would like to // pass in Class&lt;ArrayList&lt;String&gt;&gt; ArrayList&lt;String&gt; l = GenTest.instantiate(ArrayList.class); } } </code></pre> <p>I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.</p>
[ { "answer_id": 71753, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 4, "selected": true, "text": "<p>The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class&lt;List&lt;Integer>> and Class&lt;List&lt;String>>.</p>\n\n<p>The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2\" rel=\"noreferrer\">Java Language Specification</a> specifically forbids this syntax when the type is parametrized, which is why List&lt;String>.class is not allowed.</p>\n" }, { "answer_id": 71792, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "<p>Classes represent classes loaded by a class loader, which are raw types. To represent a parameterized type, use java.lang.reflect.ParameterizedType.</p>\n" }, { "answer_id": 71795, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 1, "selected": false, "text": "<p>I don't think that you can do what you are trying. Firstly, your instantiate method doesn't know that its dealing with a parameterised type (you could just as easily pass it java.util.Date.class). Secondly, because of erasure, doing anything particularly specific with parameterised types at runtime is difficult or impossible.</p>\n\n<p>If you were to approach the problem in a different way, there are other little tricks that you can do, like type inference:</p>\n\n<pre><code>public class GenTest\n{\n private static &lt;E&gt; List&lt;E&gt; createList()\n {\n return new ArrayList&lt;E&gt;();\n }\n\n public static void main(String[] args)\n {\n List&lt;String&gt; list = createList();\n List&lt;Integer&gt; list2 = createList();\n }\n}\n</code></pre>\n" }, { "answer_id": 13365240, "author": "thSoft", "author_id": 90874, "author_profile": "https://Stackoverflow.com/users/90874", "pm_score": 0, "selected": false, "text": "<p>The only thing you can do is instantiate <code>List&lt;String&gt;</code> <em>directly</em> and call its <code>getClass()</code>:</p>\n\n<pre><code>instantiate(new List&lt;String&gt;() { ... }.getClass());\n</code></pre>\n\n<p>For types with multiple abstract methods like <code>List</code>, this is quite awkward. But unfortunately, calling subclass constructors (like <code>new ArrayList&lt;String&gt;</code>) or factory methods (<code>Collections.&lt;String&gt;emptyList()</code>) don't work.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7135/" ]
Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear. What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet: ``` public class GenTest { static <T> T instantiate(Class<T> clazz) throws Exception { return clazz.newInstance(); } public static void main(String[] args) throws Exception { // Is there a way to avoid waring on the line below // without using @SuppressWarnings("unchecked")? // ArrayList.class is Class<ArrayList>, but I would like to // pass in Class<ArrayList<String>> ArrayList<String> l = GenTest.instantiate(ArrayList.class); } } ``` I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.
The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>. The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2) specifically forbids this syntax when the type is parametrized, which is why List<String>.class is not allowed.
71,590
<p>With this code I can show an animated gif while the server script is running:</p> <pre><code>function calculateTotals() { $('#results').load('getResults.php', null, showStatusFinished); showLoadStatus(); } function showLoadStatus() { $('#status').html(''); } function showStatusFinished() { $('#status').html('Finished.'); } </code></pre> <p>However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished.</p> <p>How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second?</p>
[ { "answer_id": 71648, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 0, "selected": false, "text": "<p>Your server-side script should somehow keep its progress somewhere on server (file, field in database, memcached, etc.). </p>\n\n<p>You should have AJAX function returning current progress. Poll this function once a second and render result accordingly. </p>\n" }, { "answer_id": 71667, "author": "Andrew Wilkinson", "author_id": 2990, "author_profile": "https://Stackoverflow.com/users/2990", "pm_score": 0, "selected": false, "text": "<p>Without knowing how your server side code works it's hard to say. However, there are three stages to the process. Firstly you need to call a job creation script. This returns an id number and sets the server working. Next, every second or so, you need to call a status script which returns an status message that you want to display. That status script also needs to return a value indicating whether the job has finished or not. When the status script says the job has finished you stop polling.</p>\n\n<p>How you get this status script is to know the status of the job depends greatly on how server is set up, but probably involves writing the message to a database table at various points during the job. The status script then reads this message from the database.</p>\n" }, { "answer_id": 71727, "author": "Dan F", "author_id": 11569, "author_profile": "https://Stackoverflow.com/users/11569", "pm_score": 1, "selected": false, "text": "<p>I'm not down with the specifics for jQuery, but a general answer that doesn't involve polling wold be: Use a variation of the <a href=\"http://cometdaily.com/2007/11/05/the-forever-frame-technique/\" rel=\"nofollow noreferrer\">forever frame</a> technique. Basically, create a hidden iframe, and set the src of it to be 'getresults.php'. Inside getresults you \"stream\" back script blocks, which are calls to a javascrpt function in the parent document that actually updates the progress. Here's <a href=\"http://www.codeproject.com/KB/aspnet/ASPNETAJAXPageLoader.aspx\" rel=\"nofollow noreferrer\">an example</a> that shows the basic idea behind a forever frame. (I wouldn't recommend using his actual JS or HTML though, it's reasonably average)</p>\n" }, { "answer_id": 165872, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 3, "selected": true, "text": "<p>After reading your comments to Andrew's answer.</p>\n\n<p>You would read the status like this:</p>\n\n<pre><code>function getStatus() {\n $.getJSON(\"/status.php\",{\"session\":0, \"requestID\":12345}, \n function(data) { //data is the returned JSON object from the server {name:\"value\"}\n setStatus(data.status);\n window.setTimeout(\"getStatus()\",intervalInMS)\n });\n}\n</code></pre>\n\n<p>Using this method you can open several simultaneous XHR request on the server.</p>\n\n<p>all your status.php as to output is :</p>\n\n<pre><code>{\"status\":\"We are done row 1040/45983459\"}\n</code></pre>\n\n<p>You can however output as many information you want in the response and to process it accordingly (feeding a progress bar for example or performing an animation..)</p>\n\n<p>For more information on $.getJSON see <a href=\"http://docs.jquery.com/Ajax/jQuery.getJSON\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Ajax/jQuery.getJSON</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
With this code I can show an animated gif while the server script is running: ``` function calculateTotals() { $('#results').load('getResults.php', null, showStatusFinished); showLoadStatus(); } function showLoadStatus() { $('#status').html(''); } function showStatusFinished() { $('#status').html('Finished.'); } ``` However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished. How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second?
After reading your comments to Andrew's answer. You would read the status like this: ``` function getStatus() { $.getJSON("/status.php",{"session":0, "requestID":12345}, function(data) { //data is the returned JSON object from the server {name:"value"} setStatus(data.status); window.setTimeout("getStatus()",intervalInMS) }); } ``` Using this method you can open several simultaneous XHR request on the server. all your status.php as to output is : ``` {"status":"We are done row 1040/45983459"} ``` You can however output as many information you want in the response and to process it accordingly (feeding a progress bar for example or performing an animation..) For more information on $.getJSON see <http://docs.jquery.com/Ajax/jQuery.getJSON>
71,599
<p>I've downloaded the IKVM sources (<a href="http://www.ikvm.net/" rel="nofollow noreferrer">http://www.ikvm.net/</a>) from <a href="http://sourceforge.net/cvs/?group_id=69637" rel="nofollow noreferrer">http://sourceforge.net/cvs/?group_id=69637</a></p> <p>Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?</p> <p>I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors.</p> <p>As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse.</p> <p>So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio.</p> <p>Let me know if you need any more info. Thanks for any help!</p> <p><strong>Edit:</strong> I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of:</p> <pre><code>JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a re you missing an assembly reference?) JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) </code></pre> <p><strong>Edit #2</strong>: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error:</p> <p>ikvm-native-win32:</p> <pre><code> [mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. [cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. BUILD FAILED C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10): 'cl' failed to start. The system cannot find the file specified Total time: 0.2 seconds. </code></pre> <p><strong>Edit #3</strong>: OK solved that by putting <code>cl.exe</code> in the path, still getting other errors though. <strong><em>Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...</em></strong></p> <p><strong>Edit #4</strong>: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?!</p> <pre><code> [exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java [exec] Usage: javac &lt;options&gt; &lt;source files&gt; [exec] use -help for a list of possible options </code></pre> <p><strong>Edit #5</strong>: Got an answer from the author. See below or at <a href="http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf" rel="nofollow noreferrer">http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf</a> Let's see if it works...</p> <p><strong>Edit #6</strong> As I feared, next problem: "cannot open windows.h", see separate question <a href="https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory">here</a>.</p> <p><strong>Final Edit: Found Solution!</strong> After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me.</p>
[ { "answer_id": 71744, "author": "Ryan Lanciaux", "author_id": 1385358, "author_profile": "https://Stackoverflow.com/users/1385358", "pm_score": 1, "selected": false, "text": "<p>I don't know that this would do it for you but can you try building from the command line?</p>\n\n<p>msbuild ________</p>\n\n<p>I think that's how I built the application due to the same issues.</p>\n" }, { "answer_id": 80481, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 1, "selected": true, "text": "<p>OK just got the following reply from the author: <a href=\"http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf\" rel=\"nofollow noreferrer\">http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf</a></p>\n<blockquote>\n<p>If you want to build from cvs, you're on your own. However, you can more easily build from source if you use an official release.</p>\n<p>If you download ikvm-0.36.0.11.zip, classpath-0.95-stripped.zip and openjdk-b13-stripped.zip from SourceForge (the last two are under the ikvm 0.36.0.5 release) you have all the sources that are needed.</p>\n<p>Now you'll have to open a Visual Studio 2008 Command Prompt (i.e. one that has cl.exe and peverify in the path).</p>\n<p>Then in the ikvm root directory, do a &quot;nant clean&quot; followed by &quot;nant&quot;. That should build the whole project. After you done that, you should be able to build in Visual Studio (debug target only), but you may need to repair the assembly references in the projects (unless you have ikvm installed in c:\\ikvm).</p>\n<p>Regards,\nJeroen</p>\n</blockquote>\n<p><strong>Edit</strong>: After making sure the Platform SDK folders were in the Path and Lib environment variables, this worked for me. Thanks, Jeroen!</p>\n" }, { "answer_id": 43939164, "author": "Owen Pauling", "author_id": 1688439, "author_profile": "https://Stackoverflow.com/users/1688439", "pm_score": 0, "selected": false, "text": "<p>This is how I built IKVM 8.1.5717.0 from source. Visual Studio is not required.</p>\n\n<ul>\n<li><p>Create a folder:\nc:\\ikvm\\</p></li>\n<li><p>Add the above folder to PATH (e.g. set PATH=%PATH%;c:\\ikvm and leave command prompt open for later).</p></li>\n<li><p>Download:\nikvmsrc-8.1.5717.0.zip (<a href=\"http://www.frijters.net/ikvmsrc-8.1.5717.0.zip\" rel=\"nofollow noreferrer\">http://www.frijters.net/ikvmsrc-8.1.5717.0.zip</a>)</p></li>\n<li><p>Unzip and place \"ikvm-8.1.5717.0\" folder in c:\\ikvm\\</p></li>\n<li><p>Download:\nopenjdk-8u45-b14-stripped.zip (<a href=\"http://www.frijters.net/openjdk-8u45-b14-stripped.zip\" rel=\"nofollow noreferrer\">http://www.frijters.net/openjdk-8u45-b14-stripped.zip</a>)</p></li>\n<li><p>Unzip and place \"openjdk-8u45-b14\" folder in c:\\ikvm\\</p></li>\n<li><p>Download:\nJava 8 SDK (<a href=\"http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html</a>)</p></li>\n<li><p>Install and make sure location is added to path</p></li>\n<li><p>Download:\nNAnt 0.92 (<a href=\"https://sourceforge.net/projects/nant/files/nant/0.92/nant-0.92-bin.zip/download\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/nant/files/nant/0.92/nant-0.92-bin.zip/download</a>)</p></li>\n<li><p>Unzip and place \"nant-0.92\" folder in c:\\ikvm\\</p></li>\n<li><p>ICSharpCode.SharpZipLib.dll (<a href=\"http://www.icsharpcode.net/opensource/sharpziplib/Download.aspx\" rel=\"nofollow noreferrer\">http://www.icsharpcode.net/opensource/sharpziplib/Download.aspx</a>)</p></li>\n<li><p>Place \"ICSharpCode.SharpZipLib.dll\" in C:\\ikvm\\ikvm-8.1.5717.0\\bin\\</p></li>\n<li><p>Open the following file in a text editor and change the version number:\nC:\\ikvm\\ikvm-8.1.5717.0\\CommonAssemblyInfo.cs.in</p></li>\n<li><p>Using command prompt from earlier, cd to:\nC:\\ikvm\\ikvm-8.1.5717.0\\ikvm\\</p></li>\n<li><p>Run:\n..\\nant-0.92\\bin\\NAnt.exe</p></li>\n<li><p>If successful all the binaries will be in:\nC:\\ikvm\\ikvm-8.1.5717.0\\bin</p></li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I've downloaded the IKVM sources (<http://www.ikvm.net/>) from <http://sourceforge.net/cvs/?group_id=69637> Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers? I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors. As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse. So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio. Let me know if you need any more info. Thanks for any help! **Edit:** I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of: ``` JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a re you missing an assembly reference?) JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi ssing a using directive or an assembly reference?) ``` **Edit #2**: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error: ikvm-native-win32: ``` [mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. [cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'. BUILD FAILED C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10): 'cl' failed to start. The system cannot find the file specified Total time: 0.2 seconds. ``` **Edit #3**: OK solved that by putting `cl.exe` in the path, still getting other errors though. ***Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...*** **Edit #4**: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?! ``` [exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java [exec] Usage: javac <options> <source files> [exec] use -help for a list of possible options ``` **Edit #5**: Got an answer from the author. See below or at <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf> Let's see if it works... **Edit #6** As I feared, next problem: "cannot open windows.h", see separate question [here](https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory). **Final Edit: Found Solution!** After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me.
OK just got the following reply from the author: <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf> > > If you want to build from cvs, you're on your own. However, you can more easily build from source if you use an official release. > > > If you download ikvm-0.36.0.11.zip, classpath-0.95-stripped.zip and openjdk-b13-stripped.zip from SourceForge (the last two are under the ikvm 0.36.0.5 release) you have all the sources that are needed. > > > Now you'll have to open a Visual Studio 2008 Command Prompt (i.e. one that has cl.exe and peverify in the path). > > > Then in the ikvm root directory, do a "nant clean" followed by "nant". That should build the whole project. After you done that, you should be able to build in Visual Studio (debug target only), but you may need to repair the assembly references in the projects (unless you have ikvm installed in c:\ikvm). > > > Regards, > Jeroen > > > **Edit**: After making sure the Platform SDK folders were in the Path and Lib environment variables, this worked for me. Thanks, Jeroen!
71,608
<p>How do you set up your .NET development tree? I use a structure like this:</p> <pre><code>-projectname --config (where I put the configuration files) --doc (where I put all the document concerning the project: e-mails, documentation) --tools (all the tools I use: Nunit, Moq) --lib (all the libraries used by the solution: ninject or autofac) --src ---app (sourcefiles) ---test (unittests) solutionfile.sln build.csproj </code></pre> <p>The sign "-" marks directories.</p> <p>I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries. </p> <p>Any thoughts on this?</p>
[ { "answer_id": 71676, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 3, "selected": false, "text": "<p>Check out these other StackOverflow questions...</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/16829/structure-of-projects-in-version-control#16915\">Structure of Projects in Version Control</a></li>\n<li><a href=\"https://stackoverflow.com/questions/265/best-practice-collaborative-environment-bin-directory-svn\">Best Practice: Collaborative Environment, Bin Directory, SVN</a></li>\n</ul>\n" }, { "answer_id": 71678, "author": "BigJump", "author_id": 8542, "author_profile": "https://Stackoverflow.com/users/8542", "pm_score": 4, "selected": true, "text": "<p>We use a very similar layout as covered in JP Boodhoo's blog post titled <a href=\"http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/\" rel=\"nofollow noreferrer\">Directory Structure For Projects</a>.</p>\n" }, { "answer_id": 71691, "author": "ARKBAN", "author_id": 11889, "author_profile": "https://Stackoverflow.com/users/11889", "pm_score": 0, "selected": false, "text": "<p>At my place of work we have multiple projects, where each project gets its own sub-directory, like so:\n -proj1<br>\n--proj1.csproj<br>\n-proj2<br>\n--proj2.csproj<br>\n-proj3<br>\n--proj3.csproj<br>\nsolutionfile.sln </p>\n\n<p>The rest of your setup looks okay, but I think you should figure out how you would incorporate multiple projects, for example a shared source library between multiple solutions.</p>\n" }, { "answer_id": 71738, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 0, "selected": false, "text": "<p>If I understand your structure correctly, I think you are going to have many duplicates in your dev tree related to \"tools\" and \"lib\". Most likely these are external tools and libraries that might be shared by different projects.</p>\n\n<p>Something that works well for us is:<br />\n<code>\nsolutionfile.sln<br />\n-src<br />\n--projectname<br />\n---config<br />\n---doc<br />\n---source files (structure representing namespaces)<br />\n-test<br />\n--testprojectname (usually, a test project per source project)<br />\n---unit test files (structure mirroing the structure in the source project)<br />\n-lib<br />\n--libraryname (containing the libraries)<br />\n-tools<br />\n</code></p>\n" }, { "answer_id": 71741, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 0, "selected": false, "text": "<p>I don't have tools within the project. Tools are in a network share. Yes disk space is cheap these days but... come on :)</p>\n\n<p>Also I have a database script folder below projectname (when it's a data driven app) </p>\n\n<p>Of course it doesn't matter so much how you're set-up, but the fact that a logical organised standard is used to suit the project and adhered to with good discipline. This is useful whether you're solo or on a team. </p>\n" }, { "answer_id": 71770, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 1, "selected": false, "text": "<p>We use a structure like this:</p>\n\n<ul>\n <li>CompanyNameOrCoreProjectName\n <ul>\n <li>Branch\n <ul>\n <li>BranchName\n <ul>\n <li>CopyOfTrunk</li>\n </ul>\n </li>\n </ul>\n </li>\n <li>Trunk\n <ul>\n <li>Desktop</li>\n <li>ReferencedAssemblies</li>\n <li>Shared</li>\n <li>Solutions</li>\n <li>Test</li>\n <li>Webs</li>\n </ul>\n </li>\n </ul>\n </li>\n</ul>\n\n<p>Then just make sure that all project/solution files only use relative paths and branching works well. Desktop/Webs are for projects of the respective types, Test is for any unit test projects, Solutions folder has a folder for each solution with only the solution file in it. ReferencedAssemblies holds all of the assemblies that we don't include in the solution (these are sometimes local projects that we just don't want to build every time we build the solution or third party assemblies like rhinomocks or log4net, etc. Shared is for any of the core libraries (data access, business logic, etc) that are used across several solutions.</p>\n" }, { "answer_id": 71917, "author": "Alex Scordellis", "author_id": 12006, "author_profile": "https://Stackoverflow.com/users/12006", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeplex.com/treesurgeon\" rel=\"nofollow noreferrer\">TreeSurgeon</a> is a tool that will set up a directory tree for you, with all the required dependencies and a skeleton nant file. At that link, you can also find a series of blog posts by its original creator, Mike Roberts, explaining some of the deliberate choices behind the structure that TreeSurgeon gives you, e.g. why it's OK to have duplication between lib and tools, why it's important to have all dependencies present etc.</p>\n\n<p>I haven't used it in a while so can't remember if I still agree with all the choices it makes, but I don't think you can go far wrong with it.</p>\n" }, { "answer_id": 72065, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>We also use TreeSurgeon and are quite happy with it. Our structure looks like:</p>\n\n<p>Branch</p>\n\n<ul>\n<li>build</li>\n<li>lib</li>\n<li>src\n\n<ul>\n<li>&lt;\nvarious src directories for apps, tests, db migrations, etc.)</li>\n</ul></li>\n<li>tools</li>\n</ul>\n\n<p>Trunk</p>\n\n<ul>\n<li>Same as above</li>\n</ul>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4093/" ]
How do you set up your .NET development tree? I use a structure like this: ``` -projectname --config (where I put the configuration files) --doc (where I put all the document concerning the project: e-mails, documentation) --tools (all the tools I use: Nunit, Moq) --lib (all the libraries used by the solution: ninject or autofac) --src ---app (sourcefiles) ---test (unittests) solutionfile.sln build.csproj ``` The sign "-" marks directories. I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries. Any thoughts on this?
We use a very similar layout as covered in JP Boodhoo's blog post titled [Directory Structure For Projects](http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/).
71,625
<p>I have just found a static nested interface in our code-base.</p> <pre><code>class Foo { public static interface Bar { /* snip */ } /* snip */ } </code></pre> <p>I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:</p> <p>What are the semantics behind a static interface? What would change, if I remove the <code>static</code>? Why would anyone do this?</p>
[ { "answer_id": 71654, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 3, "selected": false, "text": "<p>An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with <code>Foo.Bar</code>, like so:</p>\n\n<pre><code>public class Baz implements Foo.Bar {\n ...\n}\n</code></pre>\n\n<p>In most ways, this isn't different from a static inner class.</p>\n" }, { "answer_id": 71662, "author": "Henry B", "author_id": 6414, "author_profile": "https://Stackoverflow.com/users/6414", "pm_score": 2, "selected": false, "text": "<p>To answer your question very directly, look at Map.Entry.</p>\n\n<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html\" rel=\"nofollow noreferrer\">Map.Entry</a></p>\n\n<p>also this may be useful</p>\n\n<p><a href=\"http://littletutorials.com/2008/03/06/static-nested-interfaces/\" rel=\"nofollow noreferrer\">Static Nested Inerfaces blog Entry</a></p>\n" }, { "answer_id": 71670, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 0, "selected": false, "text": "<p>Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)</p>\n" }, { "answer_id": 71699, "author": "Vordreller", "author_id": 11795, "author_profile": "https://Stackoverflow.com/users/11795", "pm_score": -1, "selected": false, "text": "<p>Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.</p>\n\n<p>The perfect example of the usefullnes of \"static\" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.</p>\n\n<p>Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.</p>\n\n<p>Static methods are good for one-time returns and quick calculations or easy obtained data.</p>\n" }, { "answer_id": 71708, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": -1, "selected": false, "text": "<p>In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:</p>\n\n<pre><code>class Bob\n{\n void FuncA ()\n {\n Foo.Bar foobar;\n }\n}\n</code></pre>\n\n<p>Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.</p>\n\n<p><a href=\"http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html\" rel=\"nofollow noreferrer\">A description of class types in Java</a>.</p>\n" }, { "answer_id": 74400, "author": "Jesse Glick", "author_id": 12916, "author_profile": "https://Stackoverflow.com/users/12916", "pm_score": 9, "selected": true, "text": "<p>The static keyword in the above example is redundant (a nested interface is automatically \"static\") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for \"public\" on interface methods and \"public final\" on interface fields - the modifiers are redundant and just add clutter to the source code.</p>\n\n<p>Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)</p>\n\n<p>It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:</p>\n\n<pre><code>public class Foo {\n public interface Bar {\n void callback();\n }\n public static void registerCallback(Bar bar) {...}\n}\n// ...elsewhere...\nFoo.registerCallback(new Foo.Bar() {\n public void callback() {...}\n});\n</code></pre>\n" }, { "answer_id": 81569, "author": "Bas Leijdekkers", "author_id": 4510, "author_profile": "https://Stackoverflow.com/users/4510", "pm_score": 4, "selected": false, "text": "<p>Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.5.1\" rel=\"nofollow noreferrer\">8.5.1. Static Member Type Declarations</a></p>\n" }, { "answer_id": 209158, "author": "ColinD", "author_id": 13792, "author_profile": "https://Stackoverflow.com/users/13792", "pm_score": 6, "selected": false, "text": "<p>The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a <code>Listener</code>. If you had a class <code>Foo</code> and you wanted other classes to be able to listen for events on it, you could declare an interface named <code>FooListener</code>, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement <code>Foo.Listener</code> (a nested class <code>Foo.Event</code> isn't bad along with this).</p>\n" }, { "answer_id": 14354017, "author": "user1982892", "author_id": 1982892, "author_profile": "https://Stackoverflow.com/users/1982892", "pm_score": 3, "selected": false, "text": "<p>Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with <b>any</b> class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, <i> an inner interface enables the construction of custom types and improves their encapsulation</i>.</p>\n\n<pre><code>class ConcreteA implements A {\n :\n}\n\nclass ConcreteB implements B {\n :\n}\n\nclass ConcreteC implements C {\n :\n}\n\nclass Zoo implements A, C {\n :\n}\n\nclass DoSomethingAlready {\n interface AC extends A, C { }\n\n private final AC ac;\n\n DoSomethingAlready(AC ac) {\n this.ac = ac;\n }\n}\n</code></pre>\n" }, { "answer_id": 30240388, "author": "Danylo Volokh", "author_id": 1748464, "author_profile": "https://Stackoverflow.com/users/1748464", "pm_score": 0, "selected": false, "text": "<p>If you will change class Foo into interface Foo the \"public\" keyword in the above example will be also redundant as well because </p>\n\n<blockquote>\n <p>interface defined inside another interface will <strong>implicitly public\n static.</strong></p>\n</blockquote>\n" }, { "answer_id": 31952505, "author": "Pindatjuh", "author_id": 252704, "author_profile": "https://Stackoverflow.com/users/252704", "pm_score": 0, "selected": false, "text": "<p>In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.</p>\n\n<blockquote>\n <p>So far as I can see, the only difference in making an\n interface non-static is that it can now include non-static inner\n classes; so the change would not render invalid any existing Java\n programs.</p>\n</blockquote>\n\n<p>For example, he proposed a solution to the <a href=\"https://en.wikipedia.org/wiki/Expression_problem\" rel=\"nofollow\">Expression Problem</a>, which is the mismatch between expression as \"how much can your language express\" on the one hand and expression as \"the terms you are trying to represent in your language\" on the other hand.</p>\n\n<p>An example of the difference between static and non-static nested interfaces can be seen in <a href=\"http://homepages.inf.ed.ac.uk/wadler/papers/expression/expression.txt\" rel=\"nofollow\">his sample code</a>:</p>\n\n<pre><code>// This code does NOT compile\nclass LangF&lt;This extends LangF&lt;This&gt;&gt; {\n interface Visitor&lt;R&gt; {\n public R forNum(int n);\n }\n\n interface Exp {\n // since Exp is non-static, it can refer to the type bound to This\n public &lt;R&gt; R visit(This.Visitor&lt;R&gt; v);\n }\n}\n</code></pre>\n\n<p>His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
I have just found a static nested interface in our code-base. ``` class Foo { public static interface Bar { /* snip */ } /* snip */ } ``` I have never seen this before. The original developer is out of reach. Therefore I have to ask SO: What are the semantics behind a static interface? What would change, if I remove the `static`? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code. Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!) It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example: ``` public class Foo { public interface Bar { void callback(); } public static void registerCallback(Bar bar) {...} } // ...elsewhere... Foo.registerCallback(new Foo.Bar() { public void callback() {...} }); ```
71,643
<p>Currently I monitoring a particular file with a simple shell one-liner:</p> <pre><code>filesize=$(ls -lah somefile | awk '{print $5}') </code></pre> <p>I'm aware that Perl has some nice modules to deal with Excel files so the idea is to, let's say, run that check daily, perhaps with cron, and write the result on a spreadsheet for further statistical use.</p>
[ { "answer_id": 71668, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://p3rl.org/-X\" rel=\"nofollow noreferrer\">the <code>-s</code> operator</a> to obtain the size of a file and the <a href=\"http://search.cpan.org/perldoc?Spreadsheet::ParseExcel\" rel=\"nofollow noreferrer\">Spreadsheet::ParseExcel</a> and <a href=\"http://search.cpan.org/perldoc?Spreadsheet::WriteExcel\" rel=\"nofollow noreferrer\">Spreadsheet::WriteExcel</a> modules to produce an updated spreadsheet with the information. <a href=\"http://search.cpan.org/perldoc?Spreadsheet::ParseExcel::SaveParser\" rel=\"nofollow noreferrer\">Spreadsheet::ParseExcel::SaveParser</a> lets you easily combine the two, in case you want to update an existing file with new information. If you are on Windows, you may want to automate Excel itself instead, probably with the aid of <a href=\"http://search.cpan.org/perldoc?Win32::OLE\" rel=\"nofollow noreferrer\">Win32::OLE</a>.</p>\n" }, { "answer_id": 71679, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>The module you should be using is <a href=\"http://search.cpan.org/~jmcnamara/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm\" rel=\"nofollow noreferrer\">Spreadsheet::WriteExcel</a>.</p>\n" }, { "answer_id": 71716, "author": "szabgab", "author_id": 11827, "author_profile": "https://Stackoverflow.com/users/11827", "pm_score": 4, "selected": true, "text": "<p>You can check the size of the file using the -s operator.</p>\n\n<pre>\nuse strict;\nuse warnings;\n\nuse File::Slurp qw(read_file write_file);\nuse Spreadsheet::ParseExcel;\nuse Spreadsheet::ParseExcel::SaveParser;\nuse Spreadsheet::WriteExcel;\n\nmy $file = 'path_to_file';\nmy $size_file = 'path_to_file_keeping_the_size';\nmy $excel_file = 'path_to_excel_file.xls';\n\nmy $current_size = -s $file;\nmy $old_size = 0;\nif (-e $size_file) {\n $old_size = read_file($size_file);\n}\n\nif ($old_size new;\n my $excel = $parser->Parse($excel_file);\n my $row = 1;\n $row++ while $excel->{Worksheet}[0]->{Cells}[$row][0];\n $excel->AddCell(0, $row, 0, scalar(localtime));\n $excel->AddCell(0, $row, 1, $current_size);\n\n my $workbook = $excel->SaveAs($excel_file);\n $workbook->close;\n\n } else {\n my $workbook = Spreadsheet::WriteExcel->new($excel_file);\n my $worksheet = $workbook->add_worksheet();\n $worksheet->write(0, 0, 'Date');\n $worksheet->write(0, 1, 'Size');\n\n $worksheet->write(1, 0, scalar(localtime));\n $worksheet->write(1, 1, $current_size);\n $workbook->close;\n }\n}\n\nwrite_file($size_file, $current_size);\n</pre>\n\n<p>A simple way to write Excel files would be using\n<a href=\"http://search.cpan.org/dist/Spreadsheet-Write/\" rel=\"noreferrer\">Spreadsheet::Write</a>.\nbut if you need to update an existing Excel file you should look into\n<a href=\"http://search.cpan.org/dist/Spreadsheet-ParseExcel/\" rel=\"noreferrer\">Spreadsheet::ParseExcel</a>.</p>\n" }, { "answer_id": 72229, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 2, "selected": false, "text": "<p>You can also skip the hassle of writing .xls format files and use a more generic (but sufficiently Excel-friendly) format such as CSV:</p>\n\n<pre><code>#!/bin/bash\ndate=`date +%Y/%m/%d:%H:%M:%S`\nsize=$(ls -lah somefile | awk '{print $5}')\necho \"$date,$size\"\n</code></pre>\n\n<p>Then, in your crontab:</p>\n\n<pre><code>0 0 * * * /path/to/script.sh &gt;/data/sizelog.csv\n</code></pre>\n\n<p>Then you import that .csv file into Excel just like any other spreadsheet.</p>\n" }, { "answer_id": 72868, "author": "Darren Meyer", "author_id": 7826, "author_profile": "https://Stackoverflow.com/users/7826", "pm_score": 2, "selected": false, "text": "<p>Perl also has the very nice (and very <em>fast</em>) <a href=\"http://search.cpan.org/search?query=text%3A%3Acsv_xs&amp;mode=module\" rel=\"nofollow noreferrer\">Text::CSV_XS</a> which allows you to easily make Excel-friendly CSV files, which may be a better solution than creating proper XLS files.</p>\n\n<p>For example (over-commented for instructional value):</p>\n\n<pre><code>#!/usr/bin/perl\npackage main;\nuse strict; use warnings; # always!\n\nuse Text::CSV_XS;\nuse IO::File;\n\n# set up the CSV file\nmy $csv = Text::CSV_XS-&gt;new( {eol=&gt;\"\\r\\n\"} );\nmy $io = IO::File-&gt;new( 'report.csv', '&gt;')\n or die \"Cannot create report.csv: $!\\n\";\n\n# for each file specified on command line\nfor my $file (@ARGV) {\n unless ( -f $file ) {\n # file doesn't exist\n warn \"$file doesn't exist, skipping\\n\";\n next;\n }\n\n # get its size\n my $size = -s $file;\n\n # write the filename and size to a row in CSV\n $csv-&gt;print( $io, [ $file, $size ] );\n}\n\n$io-&gt;close; # make sure CSV file is flushed and closed\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
Currently I monitoring a particular file with a simple shell one-liner: ``` filesize=$(ls -lah somefile | awk '{print $5}') ``` I'm aware that Perl has some nice modules to deal with Excel files so the idea is to, let's say, run that check daily, perhaps with cron, and write the result on a spreadsheet for further statistical use.
You can check the size of the file using the -s operator. ``` use strict; use warnings; use File::Slurp qw(read_file write_file); use Spreadsheet::ParseExcel; use Spreadsheet::ParseExcel::SaveParser; use Spreadsheet::WriteExcel; my $file = 'path_to_file'; my $size_file = 'path_to_file_keeping_the_size'; my $excel_file = 'path_to_excel_file.xls'; my $current_size = -s $file; my $old_size = 0; if (-e $size_file) { $old_size = read_file($size_file); } if ($old_size new; my $excel = $parser->Parse($excel_file); my $row = 1; $row++ while $excel->{Worksheet}[0]->{Cells}[$row][0]; $excel->AddCell(0, $row, 0, scalar(localtime)); $excel->AddCell(0, $row, 1, $current_size); my $workbook = $excel->SaveAs($excel_file); $workbook->close; } else { my $workbook = Spreadsheet::WriteExcel->new($excel_file); my $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, 'Date'); $worksheet->write(0, 1, 'Size'); $worksheet->write(1, 0, scalar(localtime)); $worksheet->write(1, 1, $current_size); $workbook->close; } } write_file($size_file, $current_size); ``` A simple way to write Excel files would be using [Spreadsheet::Write](http://search.cpan.org/dist/Spreadsheet-Write/). but if you need to update an existing Excel file you should look into [Spreadsheet::ParseExcel](http://search.cpan.org/dist/Spreadsheet-ParseExcel/).
71,692
<p>I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...).</p> <p>So the question is: Portlets, tiles or some other technology?</p>
[ { "answer_id": 71737, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>Tiles can be a pain. Vast improvement over what came before (i.e. nothing), but rather limiting. </p>\n\n<p><a href=\"http://wicket.apache.org/\" rel=\"nofollow noreferrer\">Wicket</a> might be more what you're looking for, unless you've settled on JSP.</p>\n" }, { "answer_id": 71743, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://tapestry.apache.org\" rel=\"nofollow noreferrer\">Tapestry</a> is a Java web app framework with an emphasis on easily creating reusable components.</p>\n\n<p>I have used sitemesh, and it is good for wrapping a set of pages in standard headers and footers, but Tapestry is better for creating components which are used on many pages, possibly many times per page. Tapestry components can take other components as parameters, which allows the Sitemesh style wrapping.</p>\n" }, { "answer_id": 71807, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 1, "selected": false, "text": "<p>I'm a big fan of <a href=\"http://code.google.com/webtoolkit/\" rel=\"nofollow noreferrer\">GWT</a>. It lets you write your components as normal Java classes and then you can insert them into your pages at will. The whole thing ends up being compiled to Javascript.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>public class MyApplication implements EntryPoint, HistoryListener\n{\n static final String INIT_STATE = \"status\";\n\n /**\n * This is the entry point method. Instantiates the home page.\n */\n public void onModuleLoad ()\n {\n RootPanel.get ().setStyleName (\"root\");\n initHistorySupport ();\n }\n\n private void initHistorySupport ()\n {\n History.addHistoryListener (this);\n\n // check to see if there are any tokens passed at startup via the browser’s URI\n String token = History.getToken ();\n if (token.length () == 0)\n {\n onHistoryChanged (INIT_STATE);\n }\n else\n {\n onHistoryChanged (token);\n }\n }\n\n\n /**\n * Fired when the user clicks the browser's 'back' or 'forward' buttons.\n *\n * @param historyToken the token representing the current history state\n */\n public void onHistoryChanged (String historyToken)\n {\n RootPanel.get ().clear ();\n Page page;\n if (Page1.TOKEN.equalsIgnoreCase (historyToken))\n {\n page = new Page1 ();\n }\n else if (Page2.TOKEN.equalsIgnoreCase (historyToken))\n {\n page = new Page2 ();\n }\n else if (Page3.TOKEN.equalsIgnoreCase (historyToken))\n {\n page = new Page3 ();\n }\n RootPanel.get ().add (page);\n }\n}\n</code></pre>\n" }, { "answer_id": 72118, "author": "pjesi", "author_id": 1296737, "author_profile": "https://Stackoverflow.com/users/1296737", "pm_score": 3, "selected": true, "text": "<p>If you are using Spring MVC, then I would recommend using Portlets. In Spring, portlets are just lightweight controllers since they are only responsible for a fragment of the whole page, and are very easy to write. If you are using Spring 2.5, then you can enjoy all the benefits of the new annotation support, and they fit nicely in the whole Spring application with dependency injection and the other benefits of using Spring.</p>\n\n<p>A portlet controller is pretty much the same as a servlet controller, here is a simple example:</p>\n\n<pre><code>@RequestMapping(\"VIEW\")\n@Controller\npublic class NewsPortlet {\n\n private NewsService newsService;\n\n @Autowired\n public NewsPortlet(NewsService newsService) {\n this.newsService = newsService;\n }\n\n @RequestMapping(method = RequestMethod.GET)\n public String view(Model model) {\n model.addAttribute(newsService.getLatests(10));\n return \"news\"; \n }\n}\n</code></pre>\n\n<p>Here, a NewsService will be automatically injected into the controller. The view method adds a List object to the model, which will be available as ${newsList} in the JSP. Spring will look for a view named news.jsp based on the return value of the method. The RequestMapping tells Spring that this contoller is for the VIEW mode of the portlet.</p>\n\n<p>The XML configuration only needs to specify where the view and controllers are located:</p>\n\n<pre><code>&lt;!-- look for controllers and services here --&gt;\n&lt;context:component-scan base-package=\"com.example.news\"/&gt;\n\n&lt;!-- look for views here --&gt;\n&lt;bean id=\"viewResolver\" class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\"&gt;\n &lt;property name=\"prefix\" value=\"/WEB-INF/jsp/news/\"/&gt;\n &lt;property name=\"suffix\" value=\".jsp\"/&gt;\n&lt;/bean&gt;\n</code></pre>\n\n<p>If you want to simply embed the portlets in your existing application, the you can bundle a portlet container, such as <a href=\"http://www.exoplatform.com\" rel=\"nofollow noreferrer\">eXo</a>, <a href=\"https://portlet-container.dev.java.net/\" rel=\"nofollow noreferrer\">Sun</a>, or <a href=\"http://portals.apache.org/pluto/\" rel=\"nofollow noreferrer\">Apache</a>. If you want to build your application as a set of portlets, the you might want to consider a full blown portlal solution, such as <a href=\"http://liferay.com\" rel=\"nofollow noreferrer\">Liferay Portal</a>.</p>\n" }, { "answer_id": 81311, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 0, "selected": false, "text": "<p>I'm not 100% sure what \"reusable components\" means in this context, but if you mean that you want certain common elements to appear on every page, such as banner, footer, navigation links, etc., then look no further than <a href=\"http://www.opensymphony.com/sitemesh/\" rel=\"nofollow noreferrer\">SiteMesh</a>. My team has used it successfully on a couple of internationalised web applications.</p>\n" }, { "answer_id": 425546, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 2, "selected": false, "text": "<p>I don't recommend using Portlets unless your application is truly a <a href=\"http://en.wikipedia.org/wiki/Web_portal\" rel=\"nofollow noreferrer\">web portal</a>. </p>\n\n<p>If you just want \"reusable components\" use <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html\" rel=\"nofollow noreferrer\">JSP tagfiles</a>, they are dead simple yet extremely powerful, since they are the same as regular JSPs.</p>\n\n<p>I've had experience using tiles and the complexity involved simply isn't worth it. </p>\n" }, { "answer_id": 1159979, "author": "Phil Gounbin", "author_id": 141286, "author_profile": "https://Stackoverflow.com/users/141286", "pm_score": 1, "selected": false, "text": "<p>I had a lot of experience with portlets in conjunction with Ajax JSF (IceFaces) and Liferay Portal and I wouldn't recommend them to anyone - everything looks good when reading tutorial and real hell in practice. Of course I think they are much more convenient and lightweight with Spring MVC and JSP, but anyway, portlets aren't well supported technology imho.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11890/" ]
I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...). So the question is: Portlets, tiles or some other technology?
If you are using Spring MVC, then I would recommend using Portlets. In Spring, portlets are just lightweight controllers since they are only responsible for a fragment of the whole page, and are very easy to write. If you are using Spring 2.5, then you can enjoy all the benefits of the new annotation support, and they fit nicely in the whole Spring application with dependency injection and the other benefits of using Spring. A portlet controller is pretty much the same as a servlet controller, here is a simple example: ``` @RequestMapping("VIEW") @Controller public class NewsPortlet { private NewsService newsService; @Autowired public NewsPortlet(NewsService newsService) { this.newsService = newsService; } @RequestMapping(method = RequestMethod.GET) public String view(Model model) { model.addAttribute(newsService.getLatests(10)); return "news"; } } ``` Here, a NewsService will be automatically injected into the controller. The view method adds a List object to the model, which will be available as ${newsList} in the JSP. Spring will look for a view named news.jsp based on the return value of the method. The RequestMapping tells Spring that this contoller is for the VIEW mode of the portlet. The XML configuration only needs to specify where the view and controllers are located: ``` <!-- look for controllers and services here --> <context:component-scan base-package="com.example.news"/> <!-- look for views here --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/news/"/> <property name="suffix" value=".jsp"/> </bean> ``` If you want to simply embed the portlets in your existing application, the you can bundle a portlet container, such as [eXo](http://www.exoplatform.com), [Sun](https://portlet-container.dev.java.net/), or [Apache](http://portals.apache.org/pluto/). If you want to build your application as a set of portlets, the you might want to consider a full blown portlal solution, such as [Liferay Portal](http://liferay.com).
71,694
<p>Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground).</p>
[ { "answer_id": 71785, "author": "Cory", "author_id": 11870, "author_profile": "https://Stackoverflow.com/users/11870", "pm_score": 1, "selected": false, "text": "<p>Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. You would need to find the handle to the sidebar using FindWindow or an application like WinSpy.</p>\n\n<p>But after that something like.</p>\n\n<p>Sets the window on top, but not top most.</p>\n\n<pre><code>SetWindowPos(sidebarHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);\n</code></pre>\n\n<p>Sets the window at the bottom.</p>\n\n<pre><code>SetWindowPos(sidebarHandle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);\n</code></pre>\n\n<p>This is my best guess on achieving what you asked, hopefully it helps.</p>\n" }, { "answer_id": 71846, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 0, "selected": false, "text": "<p>You probably shouldn't do it at all, since such action may annoy the user when executed at the wrong time (95% of cases*), just like stealing focus with a \"Yes/No\" prompt.</p>\n\n<p>Unless your product's task is to toggle the sidebar of course. ;)</p>\n\n<p>There's no official API for that anyway.</p>\n\n<p>*Purely hypothetical figure</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11930/" ]
Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground).
Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. You would need to find the handle to the sidebar using FindWindow or an application like WinSpy. But after that something like. Sets the window on top, but not top most. ``` SetWindowPos(sidebarHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE); ``` Sets the window at the bottom. ``` SetWindowPos(sidebarHandle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE); ``` This is my best guess on achieving what you asked, hopefully it helps.
71,766
<p>In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use:</p> <pre><code>public class MyObject { private static final MySharedObject mySharedObjectInstance = new MySharedObject(); } </code></pre> <p>Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.</p> <p>(You might have guessed... I know my Java but I'm rather new to Delphi...)</p> <p>Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)</p> <p>What's the neatest way to do something like this in Delphi?</p>
[ { "answer_id": 71811, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 0, "selected": false, "text": "<p>Before version 7, Delphi didn't have static variables, you'd have to use a global variable.</p>\n\n<p>To make it as private as possible, put it in the <code>implementation</code> section of your unit.</p>\n" }, { "answer_id": 71841, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 0, "selected": false, "text": "<p>In Delphi static variables are implemented as <em>variable types constants</em> :)</p>\n\n<p>This could be somewhat misleading.</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject) ;\nconst\n clicks : Integer = 1; //not a true constant\nbegin\n Form1.Caption := IntToStr(clicks) ;\n clicks := clicks + 1;\nend;\n</code></pre>\n\n<p>And yes, another possibility is using global variable in <code>implementation</code> part of your module.</p>\n\n<p>This only works if the compiler switch \"Assignable Consts\" is turned on, globally or with <code>{$J+}</code> syntax (tnx Lars).</p>\n" }, { "answer_id": 71889, "author": "Lars Fosdal", "author_id": 10002, "author_profile": "https://Stackoverflow.com/users/10002", "pm_score": 2, "selected": false, "text": "<pre><code> TMyObject = class\n private\n class var FLogger : TLogLogger;\n procedure SetLogger(value:TLogLogger);\n property Logger : TLogLogger read FLogger write SetLogger;\n end;\n\nprocedure TMyObject.SetLogger(value:TLogLogger);\nbegin\n // sanity checks here\n FLogger := Value;\nend;\n</code></pre>\n\n<p>Note that this class variable will be writable from any class instance, hence you can set it up somewhere else in the code, usually based on some condition (type of logger etc.).</p>\n\n<p>Edit: It will also be the same in all descendants of the class. Change it in one of the children, and it changes for all descendant instances.\nYou could also set up default instance handling.</p>\n\n<pre><code> TMyObject = class\n private\n class var FLogger : TLogLogger;\n procedure SetLogger(value:TLogLogger);\n function GetLogger:TLogLogger;\n property Logger : TLogLogger read GetLogger write SetLogger;\n end;\n\nfunction TMyObject.GetLogger:TLogLogger;\nbegin\n if not Assigned(FLogger)\n then FLogger := TSomeLogLoggerClass.Create;\n Result := FLogger;\nend;\n\nprocedure TMyObject.SetLogger(value:TLogLogger);\nbegin\n // sanity checks here\n FLogger := Value;\nend;\n</code></pre>\n" }, { "answer_id": 71993, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 2, "selected": false, "text": "<p>The keywords you are looking for are \"class var\" - this starts a block of class variables in your class declaration. You need to end the block with \"var\" if you wish to include other fields after it (otherwise the block may be ended by a \"private\", \"public\", \"procedure\" etc specifier). Eg </p>\n\n<p>(Edit: I re-read the question and moved reference count into TMyClass - as you may not be able to edit the TMySharedObjectClass class you want to share, if it comes from someone else's library)</p>\n\n<pre><code> TMyClass = class(TObject)\n strict private\n class var\n FMySharedObjectRefCount: integer;\n FMySharedObject: TMySharedObjectClass;\n var\n FOtherNonClassField1: integer;\n function GetMySharedObject: TMySharedObjectClass;\n public\n constructor Create;\n destructor Destroy; override;\n property MySharedObject: TMySharedObjectClass read GetMySharedObject;\n end;\n\n\n{ TMyClass }\nconstructor TMyClass.Create;\nbegin\n if not Assigned(FMySharedObject) then\n FMySharedObject := TMySharedObjectClass.Create;\n Inc(FMySharedObjectRefCount);\nend;\n\ndestructor TMyClass.Destroy;\nbegin\n Dec(FMySharedObjectRefCount);\n if (FMySharedObjectRefCount &lt; 1) then\n FreeAndNil(FMySharedObject);\n\n inherited;\nend;\n\nfunction TMyClass.GetMySharedObject: TMySharedObjectClass;\nbegin\n Result := FMySharedObject;\nend;\n</code></pre>\n\n<p>Please note the above is not thread-safe, and there may be better ways of reference-counting (such as using Interfaces), but this is a simple example which should get you started. Note the TMySharedObjectClass can be replaced by TLogLogger or whatever you like.</p>\n" }, { "answer_id": 72047, "author": "Pierre-Jean Coudert", "author_id": 8450, "author_profile": "https://Stackoverflow.com/users/8450", "pm_score": 5, "selected": true, "text": "<p>Here is how I'll do that using a class variable, a class procedure and an initialization block:</p>\n\n<pre><code>unit MyObject;\n\ninterface\n\ntype\n\nTMyObject = class\n private\n class var FLogger : TLogLogger;\n public\n class procedure SetLogger(value:TLogLogger);\n class procedure FreeLogger;\n end;\n\nimplementation\n\nclass procedure TMyObject.SetLogger(value:TLogLogger);\nbegin\n // sanity checks here\n FLogger := Value;\nend;\n\nclass procedure TMyObject.FreeLogger;\nbegin\n if assigned(FLogger) then \n FLogger.Free;\nend;\n\ninitialization\n TMyObject.SetLogger(TLogLogger.Create);\nfinalization\n TMyObject.FreeLogger;\nend.\n</code></pre>\n" }, { "answer_id": 72496, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 3, "selected": false, "text": "<p>Last year, Hallvard Vassbotn blogged about a Delphi-hack I had made for this, it became a two-part article:</p>\n\n<ol>\n<li><a href=\"http://hallvards.blogspot.com/2007/05/hack17-virtual-class-variables-part-i.html\" rel=\"noreferrer\">Hack#17: Virtual class variables, Part I</a></li>\n<li><a href=\"http://hallvards.blogspot.com/2007/05/hack17-virtual-class-variables-part-ii.html\" rel=\"noreferrer\">Hack#17: Virtual class variables, Part II</a></li>\n</ol>\n\n<p>Yeah, it's a long read, but very rewarding.</p>\n\n<p>In summary, I've reused the (deprecated) VMT entry called vmtAutoTable as a variable.\nThis slot in the VMT can be used to store any 4-byte value, but if you want to store, you could always allocate a record with all the fields you could wish for.</p>\n" }, { "answer_id": 73486, "author": "MB.", "author_id": 11961, "author_profile": "https://Stackoverflow.com/users/11961", "pm_score": 1, "selected": false, "text": "<p>For what I want to do (a private class constant), the neatest solution that I can come up with (based on responses so far) is:</p>\n\n<pre><code>unit MyObject;\n\ninterface\n\ntype\n\nTMyObject = class\nprivate\n class var FLogger: TLogLogger;\nend;\n\nimplementation\n\ninitialization\n TMyObject.FLogger:= TLogLogger.GetLogger(TMyObject);\nfinalization\n // You'd typically want to free the class objects in the finalization block, but\n // TLogLoggers are actually managed by Log4D.\n\nend.\n</code></pre>\n\n<p>Perhaps a little more object oriented would be something like:</p>\n\n<pre><code>unit MyObject;\n\ninterface\n\ntype\n\nTMyObject = class\nstrict private\n class var FLogger: TLogLogger;\nprivate\n class procedure InitClass;\n class procedure FreeClass;\nend;\n\nimplementation\n\nclass procedure TMyObject.InitClass;\nbegin\n FLogger:= TLogLogger.GetLogger(TMyObject);\nend;\n\nclass procedure TMyObject.FreeClass;\nbegin\n // Nothing to do here for a TLogLogger - it's freed by Log4D.\nend;\n\ninitialization\n TMyObject.InitClass;\nfinalization\n TMyObject.FreeClass;\n\nend.\n</code></pre>\n\n<p>That might make more sense if there were multiple such class constants.</p>\n" }, { "answer_id": 81437, "author": "Graza", "author_id": 11820, "author_profile": "https://Stackoverflow.com/users/11820", "pm_score": 1, "selected": false, "text": "<p>Two questions I think that need to be answered before you come up with a \"perfect\" solution..</p>\n\n<ul>\n<li>The first, is whether TLogLogger is thread-safe. Can the same TLogLogger be called from multiple threads <em>without</em> calls to \"syncronize\"? Even if so, the following may still apply</li>\n<li>Are class variables thread-in-scope or truly global?</li>\n<li>If class variables are truly global, and TLogLogger is not thread safe, you might be best to use a unit-global threadvar to store the TLogLogger (as much as I don't like using \"global\" vars in any form), eg</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>interface\ntype\n TMyObject = class(TObject)\n private\n FLogger: TLogLogger; //NB: pointer to shared threadvar\n public\n constructor Create;\n end;\nimplementation\nthreadvar threadGlobalLogger: TLogLogger = nil;\nconstructor TMyObject.Create;\nbegin\n if not Assigned(threadGlobalLogger) then\n threadGlobalLogger := TLogLogger.GetLogger(TMyObject); //NB: No need to reference count or explicitly free, as it's freed by Log4D\n FLogger := threadGlobalLogger;\nend;\n</code></pre>\n\n<p><em>Edit: It seems that class variables are globally stored, rather than an instance per thread. See <a href=\"https://stackoverflow.com/questions/82113/are-delphi-class-vars-global-or-thread-in-storage\">this question</a> for details.</em></p>\n" }, { "answer_id": 1038253, "author": "Gedean Dias", "author_id": 101900, "author_profile": "https://Stackoverflow.com/users/101900", "pm_score": 2, "selected": false, "text": "<p>Well, it's not beauty, but works fine in Delphi 7:</p>\n\n<pre><code>TMyObject = class\npulic\n class function MySharedObject: TMySharedObject; // I'm lazy so it will be read only\nend;\n\nimplementation\n</code></pre>\n\n<p>...</p>\n\n<pre><code>class function MySharedObject: TMySharedObject;\n{$J+} const MySharedObjectInstance: TMySharedObject = nil; {$J-} // {$J+} Makes the consts writable\nbegin\n // any conditional initialization ...\n if (not Assigned(MySharedObjectInstance)) then\n MySharedObjectInstance = TMySharedOject.Create(...);\n Result := MySharedObjectInstance;\nend;\n</code></pre>\n\n<p>I'm curently using it to build singletons objects.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ]
In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use: ``` public class MyObject { private static final MySharedObject mySharedObjectInstance = new MySharedObject(); } ``` Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block. (You might have guessed... I know my Java but I'm rather new to Delphi...) Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.) What's the neatest way to do something like this in Delphi?
Here is how I'll do that using a class variable, a class procedure and an initialization block: ``` unit MyObject; interface type TMyObject = class private class var FLogger : TLogLogger; public class procedure SetLogger(value:TLogLogger); class procedure FreeLogger; end; implementation class procedure TMyObject.SetLogger(value:TLogLogger); begin // sanity checks here FLogger := Value; end; class procedure TMyObject.FreeLogger; begin if assigned(FLogger) then FLogger.Free; end; initialization TMyObject.SetLogger(TLogLogger.Create); finalization TMyObject.FreeLogger; end. ```
71,775
<p>I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?</p> <p>Is it easy to do the job in shell script or should I go about doing this in Java?</p>
[ { "answer_id": 71789, "author": "Josti", "author_id": 11231, "author_profile": "https://Stackoverflow.com/users/11231", "pm_score": 0, "selected": false, "text": "<p>Can't test it right now, but something like:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>echo \"INSERT INTO foo (b,a,r) VALUES (1,2,3);\" | \n mysql -u user -psecret -h host database\n</code></pre>\n\n<p>in a shell script should work. Don't know about getting Data out of it though</p>\n" }, { "answer_id": 71797, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 2, "selected": false, "text": "<p>it is possible :\nUsing your unix shell script, generate an sql script and use the cli to the database to execute the sql script. </p>\n\n<p>if the amount of information is small enough you could build the SQL in memory, I advise against it though since you never know what the future holds (and it could be very large amount of data). Using one call per request doesn't allow you to benefit from bulk operations which are sometimes available.</p>\n" }, { "answer_id": 71799, "author": "Charles Ma", "author_id": 11708, "author_profile": "https://Stackoverflow.com/users/11708", "pm_score": 2, "selected": false, "text": "<p>You can, but it might be a bit ugly, for example if you're using mysql and suppose you have an SQL string stored in $sql</p>\n\n<pre><code>echo $sql | mysql -u[user] -p[password] -h[host]\n</code></pre>\n\n<p>p.s. it might be a good idea to tell us what database you're using so we can offer more specific help :p</p>\n\n<p>edit: changed the example line so it actually works</p>\n" }, { "answer_id": 71804, "author": "lbz", "author_id": 11530, "author_profile": "https://Stackoverflow.com/users/11530", "pm_score": -1, "selected": false, "text": "<p>Shell scripting (Bash or similar) primary intention is not to deal with databases. Go for Java or even better, ride this opportunity to learn the basics of a scripting language like Python or Ruby.</p>\n" }, { "answer_id": 71834, "author": "Yining", "author_id": 6506, "author_profile": "https://Stackoverflow.com/users/6506", "pm_score": 1, "selected": false, "text": "<p>Pipe is your friend.</p>\n\n<p>For example, in MySQL:\n</p>\n\n<pre><code>echo 'load data infile /path/to/the/file into table table_name ...' | \n mysql -u mysql_user_id -p \n</code></pre>\n\n<p>should do the work.</p>\n\n<p>Provided your file is somehow structured e.g. comma/tab separated etc.</p>\n\n<p>For details, check the manual for your database.</p>\n" }, { "answer_id": 71855, "author": "Mike Desjardins", "author_id": 10466, "author_profile": "https://Stackoverflow.com/users/10466", "pm_score": 2, "selected": false, "text": "<p>Of course you can, assuming that you've got a command-line SQL client handy! I've done it w/ Sybase and the isql command-line client. You can even get clever and send stuff through awk and send scripts to generate commands on the fly. It might not be the most efficient way to do everything, but there's plenty of opportunity to flex your Unix hacker mojo.</p>\n" }, { "answer_id": 72018, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 3, "selected": true, "text": "<p>If the data you are trying to import is in a reasonable format -- comma-delimited, for example -- and your database server has reasonable command line utilities, this should be no problem. MySQL has the \"mysqlimport\" command-line tool that will accept various arguments describing the format of the file:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>mysqlimport \\\n --fields-terminated-by=, \\\n --ignore-lines=1 \\\n --fields-optionally-enclosed-by='\"' &lt; datafile.txt\n</code></pre>\n\n<p>Passing the data through perl/sed/awk one-liners can help with getting it in the proper format, and the shell script can easily handle prompting for filenames, handling arguments, etc.</p>\n\n<p>Using the various command-line tools provided by Unix is the entire point of bash scripting. Perl, mysql, etc. are all part of that toolkit.</p>\n" }, { "answer_id": 75812, "author": "eckes", "author_id": 13189, "author_profile": "https://Stackoverflow.com/users/13189", "pm_score": 0, "selected": false, "text": "<p>It depends on your Database Management System. Most of them have powerfull shell tools for importing data, doing even some ETL functions. Those tools could be even very performant if they support bulk loading - usually Java JDBC can't do that so easily.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job? Is it easy to do the job in shell script or should I go about doing this in Java?
If the data you are trying to import is in a reasonable format -- comma-delimited, for example -- and your database server has reasonable command line utilities, this should be no problem. MySQL has the "mysqlimport" command-line tool that will accept various arguments describing the format of the file: ```sh mysqlimport \ --fields-terminated-by=, \ --ignore-lines=1 \ --fields-optionally-enclosed-by='"' < datafile.txt ``` Passing the data through perl/sed/awk one-liners can help with getting it in the proper format, and the shell script can easily handle prompting for filenames, handling arguments, etc. Using the various command-line tools provided by Unix is the entire point of bash scripting. Perl, mysql, etc. are all part of that toolkit.
71,776
<p>I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this.</p> <p>They are named like so......</p> <p>frame-44558.jpg</p> <p>frame-44559.jpg</p> <p>frame-44560.jpg</p> <p>frame-44561.jpg</p> <p>Thanks from a newb needing help.</p> <hr> <p>Seems to have worked. Couple of errors in my origonal post. There were actually 280,000 images and the naming was. /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163405.jpg /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163505.jpg /home/baldy/Desktop/webcamimages/webcam_2007-05-29_163605.jpg</p> <p>I ran. cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/</p> <p>Which appears to have copied the images. 70-900 per day from the looks of it.</p> <p>Now I'm running mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi</p> <p>I'll let you know how the movie works out.</p> <p>UPDATE: Movie did not work. Only has images from 2007 in it even though the directory has 2008 as well. webcam_2008-02-17_101403.jpg webcam_2008-03-27_192205.jpg webcam_2008-02-17_102403.jpg webcam_2008-03-27_193205.jpg webcam_2008-02-17_103403.jpg webcam_2008-03-27_194205.jpg webcam_2008-02-17_104403.jpg webcam_2008-03-27_195205.jpg</p> <p>How can I modify my mencoder line so that it uses all the images?</p>
[ { "answer_id": 71798, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 1, "selected": false, "text": "<p>An easy way in perl (probably easily adaptable to bash) is to glob the filenames in an array then get the sequence number and remove those that are not divisible by 4</p>\n\n<p>Something like this will print the files you need:</p>\n\n<pre><code>ls -1 /path/to/files/ | perl -e 'while (&lt;STDIN&gt;) {($seq)=/(\\d*)\\.jpg$/; print $_ if $seq &amp;&amp; $seq % 4 ==0}'\n</code></pre>\n\n<p>You can replace the print by a move...</p>\n\n<p>This will work if the files are numbered in sequence even if the number of digits is not constant like <code>file_9.jpg</code> followed by <code>file_10.jpg</code> )</p>\n" }, { "answer_id": 71808, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 5, "selected": true, "text": "<p>One simple way is: </p>\n\n<pre>\n$ touch a b c d e f g h i j k l m n o p q r s t u v w x y z\n$ mv $(ls | awk '{nr++; if (nr % 4 == 0) print $0}') destdir\n\n</pre>\n" }, { "answer_id": 71819, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 2, "selected": false, "text": "<p>Create a script move.sh which contains this:</p>\n\n<pre><code>#!/bin/sh\nmv $4 ../newdirectory/\n</code></pre>\n\n<p>Make it executable and then do this in the folder:</p>\n\n<pre><code>ls *.jpg | xargs -n 4 ./move.sh\n</code></pre>\n\n<p>This takes the list of filenames, passes four at a time into move.sh, which then ignores the first three and moves the fourth into a new folder.</p>\n\n<p>This will work even if the numbers are not exactly in sequence (e.g. if some frame numbers are missing, then using mod 4 arithmetic won't work).</p>\n" }, { "answer_id": 71835, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 1, "selected": false, "text": "<pre><code>seq -f 'frame-%g.jpg' 1 4 number-of-frames\n</code></pre>\n\n<p>…will print the names of the files you need.</p>\n" }, { "answer_id": 71871, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Just iterate over a list of files:</p>\n\n<pre><code>files=( frame-*.jpg )\ni=0\nwhile [[ $i -lt ${#files} ]] ; do\n cur_file=${files[$i]}\n mungle_frame $cur_file\n i=$( expr $i + 4 )\ndone\n</code></pre>\n" }, { "answer_id": 71918, "author": "masto", "author_id": 11974, "author_profile": "https://Stackoverflow.com/users/11974", "pm_score": 0, "selected": false, "text": "<p>This is pretty cheesy, but it should get the job done. Assuming you're currently cd'd into the directory containing all of your files:</p>\n\n<pre><code>mkdir ../outdir\nls | sort -n | while read fname; do mv \"$fname\" ../outdir/; read; read; read; done\n</code></pre>\n\n<p>The <code>sort -n</code> is there assuming your filenames don't all have the same number of digits; otherwise <code>ls</code> will sort in lexical order where <code>frame-123.jpg</code> comes before <code>frame-4.jpg</code> and I don't think that's what you want.</p>\n\n<p>Please be careful, back up your files before trying my solution, etc. I don't want to be responsible for you losing a year's worth of data.</p>\n\n<p>Note that this solution does handle files with spaces in the name, unlike most of the others. I know that wasn't part of the sample filenames, but it's easy to write shell commands that don't handle spaces safely, so I wanted to do that in this example.</p>\n" }, { "answer_id": 73038, "author": "Iain", "author_id": 12060, "author_profile": "https://Stackoverflow.com/users/12060", "pm_score": 1, "selected": false, "text": "<p>Given masto's caveats about sorting:</p>\n\n<p><code>ls | sed -n '1~4 p' | xargs -i mv {} ../destdir/</code></p>\n\n<p>The thing I like about this solution is that everything's doing what it was designed to do, so it feels unixy to me.</p>\n" }, { "answer_id": 73125, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 2, "selected": false, "text": "<p>As suggested, you should use</p>\n\n<pre><code>seq -f 'frame-%g.jpg' 1 4 number-of-frames\n</code></pre>\n\n<p>to generate the list of filenames since 'ls' will fail on 280k files. So the final solution would be something like:</p>\n\n<pre><code>for f in `seq -f 'frame-%g.jpg' 1 4 number-of-frames` ; do\n mv $f destdir/\ndone\n</code></pre>\n" }, { "answer_id": 73146237, "author": "M.Viking", "author_id": 10276092, "author_profile": "https://Stackoverflow.com/users/10276092", "pm_score": 0, "selected": false, "text": "<p>brace expansion {m..n..s} is more efficient than seq. AND it allows a bit of output formatting:</p>\n<pre><code>$ echo {0000..0010..2}\n0000 0002 0004 0006 0008 0010\n</code></pre>\n<p>Postscript: In <code>curl</code> if you only want every fourth (nth) numbered images so you tell curl a step counter too. This example range goes from 0 to 100 with an increment of 4 (n):</p>\n<pre><code>curl -O &quot;http://example.com/[0-100:4].png&quot;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11950/" ]
I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this. They are named like so...... frame-44558.jpg frame-44559.jpg frame-44560.jpg frame-44561.jpg Thanks from a newb needing help. --- Seems to have worked. Couple of errors in my origonal post. There were actually 280,000 images and the naming was. /home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163405.jpg /home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163505.jpg /home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163605.jpg I ran. cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/ Which appears to have copied the images. 70-900 per day from the looks of it. Now I'm running mencoder mf://\*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi I'll let you know how the movie works out. UPDATE: Movie did not work. Only has images from 2007 in it even though the directory has 2008 as well. webcam\_2008-02-17\_101403.jpg webcam\_2008-03-27\_192205.jpg webcam\_2008-02-17\_102403.jpg webcam\_2008-03-27\_193205.jpg webcam\_2008-02-17\_103403.jpg webcam\_2008-03-27\_194205.jpg webcam\_2008-02-17\_104403.jpg webcam\_2008-03-27\_195205.jpg How can I modify my mencoder line so that it uses all the images?
One simple way is: ``` $ touch a b c d e f g h i j k l m n o p q r s t u v w x y z $ mv $(ls | awk '{nr++; if (nr % 4 == 0) print $0}') destdir ```
71,788
<p>I'm writing an Emacs major mode for an APL dialect I use at work. I've gotten basic font locking to work, and after setting comment-start and comment-start-skip, comment/uncomment region and fill paragraph also work.</p> <p>However, comment blocks often contain javadoc style comments and i would like fill-paragraph to avoid glueing together lines starting with such commands.</p> <p>If I have this (\ instead of javadoc @):</p> <pre><code># This is a comment that is long and should be wrapped. # \arg Description of argument # \ret Description of return value </code></pre> <p>M-q gives me:</p> <pre><code># This is a comment that is long and # should be wrapped. \arg Description # of argument \ret Description of # return value </code></pre> <p>But I want:</p> <pre><code># This is a comment that is long and # should be wrapped. # \arg Description of argument # \ret Description of return value </code></pre> <p>I've tried setting up paragraph-start and paragraph-separate to appropriate values, but fill-paragraph still doesn't work inside a comment block. If I remove the comment markers, M-q works as I want to, so the regexp I use for paragraph-start seems to work.</p> <p>Do I have to write a custom fill-paragraph for my major mode? cc-mode has one that handles cases like this, but it's really complex, I'd like to avoid it if possible. </p>
[ { "answer_id": 72637, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 1, "selected": false, "text": "<p>There's other modes that have less complex functions used for <code>fill-paragraph-function</code>. Browsing through my install, it looks like the ones in ada-mode and make-mode are good examples.</p>\n" }, { "answer_id": 73963, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 1, "selected": false, "text": "<p>What I do in these cases is open a blank line between the paragraph lines and the argument lines, then use M-q to wrap the paragraph lines, then kill the blank line between them. Not ideal, but it works and is easy enough to record in a macro if you need to repeat it.</p>\n" }, { "answer_id": 145431, "author": "Joakim Hårsman", "author_id": 11978, "author_profile": "https://Stackoverflow.com/users/11978", "pm_score": 3, "selected": true, "text": "<p>The problem was that the paragraph-start regexp has to match the entire line to work, including the actual comment character. The following elisp works for the example I gave:</p>\n\n<pre><code>(setq paragraph-start \"^\\\\s-*\\\\#\\\\s-*\\\\\\\\\\\\(arg\\\\|ret\\\\).*$\")\n</code></pre>\n\n<p>Here a page that has an example regexp for php-mode that does this:\n<a href=\"http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/\" rel=\"nofollow noreferrer\">http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11978/" ]
I'm writing an Emacs major mode for an APL dialect I use at work. I've gotten basic font locking to work, and after setting comment-start and comment-start-skip, comment/uncomment region and fill paragraph also work. However, comment blocks often contain javadoc style comments and i would like fill-paragraph to avoid glueing together lines starting with such commands. If I have this (\ instead of javadoc @): ``` # This is a comment that is long and should be wrapped. # \arg Description of argument # \ret Description of return value ``` M-q gives me: ``` # This is a comment that is long and # should be wrapped. \arg Description # of argument \ret Description of # return value ``` But I want: ``` # This is a comment that is long and # should be wrapped. # \arg Description of argument # \ret Description of return value ``` I've tried setting up paragraph-start and paragraph-separate to appropriate values, but fill-paragraph still doesn't work inside a comment block. If I remove the comment markers, M-q works as I want to, so the regexp I use for paragraph-start seems to work. Do I have to write a custom fill-paragraph for my major mode? cc-mode has one that handles cases like this, but it's really complex, I'd like to avoid it if possible.
The problem was that the paragraph-start regexp has to match the entire line to work, including the actual comment character. The following elisp works for the example I gave: ``` (setq paragraph-start "^\\s-*\\#\\s-*\\\\\\(arg\\|ret\\).*$") ``` Here a page that has an example regexp for php-mode that does this: <http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/>
71,817
<p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>. Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p> <p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p> <p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
[ { "answer_id": 72126, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 0, "selected": false, "text": "<p>Well the doc-string is stored in <code>__doc__</code> so it wouldn't be too hard to re-assign it based on the doc-string of <code>_execute</code> after the fact.</p>\n\n<p>Basically:</p>\n\n<p><code></p>\n\n<pre>\nclass MyClass(object):\n def execute(self):\n '''original doc-string'''\n self._execute()\n\nclass SubClass(MyClass):\n def _execute(self):\n '''sub-class doc-string'''\n pass\n\n # re-assign doc-string of execute\n def execute(self,*args,**kw):\n return MyClass.execute(*args,**kw)\n execute.__doc__=_execute.__doc__\n\n</pre>\n\n<p></code></p>\n\n<p>Execute has to be re-declared to that the doc string gets attached to the version of execute for the <code>SubClass</code> and not for <code>MyClass</code> (which would otherwise interfere with other sub-classes).</p>\n\n<p>That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result. You could then wrap this up in a meta-class to make it easier for people who are sub-classing.</p>\n" }, { "answer_id": 72192, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 2, "selected": false, "text": "<p>Is there a reason you can't override the base class's <code>execute</code> function directly?</p>\n\n<pre><code>class Base(object):\n def execute(self):\n ...\n\nclass Derived(Base):\n def execute(self):\n \"\"\"Docstring for derived class\"\"\"\n Base.execute(self)\n ...stuff specific to Derived...\n</code></pre>\n\n<p>If you don't want to do the above:</p>\n\n<p>Method objects don't support writing to the <code>__doc__</code> attribute, so you have to change <code>__doc__</code> in the actual function object. Since you don't want to override the one in the base class, you'd have to give each subclass its own copy of <code>execute</code>:</p>\n\n<pre><code>class Derived(Base):\n def execute(self):\n return Base.execute(self)\n\n class _execute(self):\n \"\"\"Docstring for subclass\"\"\"\n ...\n\n execute.__doc__= _execute.__doc__\n</code></pre>\n\n<p>but this is similar to a roundabout way of redefining <code>execute</code>...</p>\n" }, { "answer_id": 72596, "author": "Sylvain Defresne", "author_id": 5353, "author_profile": "https://Stackoverflow.com/users/5353", "pm_score": 3, "selected": true, "text": "<p>Well, if you don't mind copying the original method in the subclass, you can use the following technique.</p>\n\n<pre><code>import new\n\ndef copyfunc(func):\n return new.function(func.func_code, func.func_globals, func.func_name,\n func.func_defaults, func.func_closure)\n\nclass Metaclass(type):\n def __new__(meta, name, bases, attrs):\n for key in attrs.keys():\n if key[0] == '_':\n skey = key[1:]\n for base in bases:\n original = getattr(base, skey, None)\n if original is not None:\n copy = copyfunc(original)\n copy.__doc__ = attrs[key].__doc__\n attrs[skey] = copy\n break\n return type.__new__(meta, name, bases, attrs)\n\nclass Class(object):\n __metaclass__ = Metaclass\n def execute(self):\n '''original doc-string'''\n return self._execute()\n\nclass Subclass(Class):\n def _execute(self):\n '''sub-class doc-string'''\n pass\n</code></pre>\n" }, { "answer_id": 72785, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 0, "selected": false, "text": "<p>I agree that the simplest, most Pythonic way of approaching this is to simply redefine execute in your subclasses and have it call the execute method of the base class:</p>\n\n<pre><code>class Sub(Base):\n def execute(self):\n \"\"\"New docstring goes here\"\"\"\n return Base.execute(self)\n</code></pre>\n\n<p>This is very little code to accomplish what you want; the only downside is that you must repeat this code in every subclass that extends Base. However, this is a small price to pay for the behavior you want.</p>\n\n<p>If you want a sloppy and verbose way of making sure that the docstring for execute is dynamically generated, you can use the descriptor protocol, which would be significantly less code than the other proposals here. This is annoying because you can't just set a descriptor on an existing function, which means that execute must be written as a separate class with a <code>__call__</code> method.</p>\n\n<p>Here's the code to do this, but keep in mind that my above example is much simpler and more Pythonic:</p>\n\n<pre><code>class Executor(object):\n __doc__ = property(lambda self: self.inst._execute.__doc__)\n\n def __call__(self):\n return self.inst._execute()\n\nclass Base(object):\n execute = Executor()\n\nclass Sub(Base):\n def __init__(self):\n self.execute.inst = self\n\n def _execute(self):\n \"\"\"Actually does something!\"\"\"\n return \"Hello World!\"\n\nspam = Sub()\nprint spam.execute.__doc__ # prints \"Actually does something!\"\nhelp(spam) # the execute method says \"Actually does something!\"\n</code></pre>\n" }, { "answer_id": 73473, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Look at the functools.wraps() decorator; it does all of this, but I don't know offhand if you can get it to run in the right context</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11992/" ]
The problem: I have a class which contains a template method `execute` which calls another method `_execute`. Subclasses are supposed to overwrite `_execute` to implement some specific functionality. This functionality should be documented in the docstring of `_execute`. Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use `execute`, so he won't see the correct docstring if he uses `help(execute)`. Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of `execute` is automatically replaced with that of `_execute`. Any ideas how this might be done? I was thinking of metaclasses to do this, to make this completely transparent to the user.
Well, if you don't mind copying the original method in the subclass, you can use the following technique. ``` import new def copyfunc(func): return new.function(func.func_code, func.func_globals, func.func_name, func.func_defaults, func.func_closure) class Metaclass(type): def __new__(meta, name, bases, attrs): for key in attrs.keys(): if key[0] == '_': skey = key[1:] for base in bases: original = getattr(base, skey, None) if original is not None: copy = copyfunc(original) copy.__doc__ = attrs[key].__doc__ attrs[skey] = copy break return type.__new__(meta, name, bases, attrs) class Class(object): __metaclass__ = Metaclass def execute(self): '''original doc-string''' return self._execute() class Subclass(Class): def _execute(self): '''sub-class doc-string''' pass ```
71,820
<p>I need a function called <code>SizeOfPipe()</code> which should return the size of a pipe - I only want to know how much data is in the pipe and not actually read data off the pipe itself. </p> <p>I thought the following code would work:</p> <pre><code>fseek (pPipe, 0 , SEEK_END); *pBytes = ftell (pPipe); rewind (pPipe); </code></pre> <p>but <code>fseek()</code> doesn't work on file descriptors. Another option would be to read the pipe then write the data back but would like to avoid this if possible. Any suggestions?</p>
[ { "answer_id": 71870, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>It's not in general possible to know the amount of data you can read from a pipe just from the pipe handle alone. The data may be coming in across a network, or being dynamically generated by another process. If you need to know up front, you should arrange for the information to be sent to you - through the pipe, or out of band - by whatever process is at the other end of the pipe.</p>\n" }, { "answer_id": 71872, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 2, "selected": false, "text": "<p>There is no generic, portable way to tell how much data is available in a pipe without reading it. At least not under POSIX specifications.</p>\n\n<p>Pipes are not seekable, and neither is it possible to put the data back into the reading end of a pipe.</p>\n\n<p>Platform-specific tricks might be possible, though. If your question is platform-specific, editing your question to say so might improve your chances to get a working answer.</p>\n" }, { "answer_id": 71873, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 0, "selected": false, "text": "<p>I don't think it is possible, isn't the point of a pipe to provide interprocess communication between the two ends (in one direction). If I'm correct in that assertion, the send may not yet have finished pushing data into the pipe -- so it'd be impossible to determine the length.</p>\n\n<p>What platform are you using?</p>\n" }, { "answer_id": 71875, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 2, "selected": false, "text": "<p>Unfortunately the system cannot always know the size of a pipe - for example if you are piping a long-running process into another command, the source process may not have finished running yet. In this case there is no possible way (even in theory) to know how much more data is going to come out of it.</p>\n\n<p>If you want to know the amount of data <em>currently</em> available to read out of the pipe that might be possible, but it will depend on OS buffering and other factors which are hard to control. The most common approach here is just to keep reading until there's nothing left to come (if you don't get an EOF then the source process hasn't finished yet). However I don't think this is what you are looking for.</p>\n\n<p>So I'm afraid there is no general solution.</p>\n" }, { "answer_id": 71925, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 3, "selected": false, "text": "<p>Some UNIX implementations return the number of bytes that can be read in the <code>st_size</code> field after calling <code>fstat()</code>, but this is not portable.</p>\n" }, { "answer_id": 71950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I do not think it's possible. Pipes present stream-oriented protocol rather than packet-oriented one. IOW, if you write to a pipe twice, once with,say, 250 bytes and once with, say, 520 bytes, there is no way to tell how many bytes you'll get from the other end in one read request. You could get 256, 256, and then the rest.</p>\n\n<p>If you need to impose packets on a pipe, you need to do it yourself by writing pre-determined (or delimited) number of bytes as packet length, and then the rest of teh packet. Use <strong>select()</strong> to find out if there is data to read, use read() to get a reasonably-sized buffer. When you have your buffer, it's your responsibility to determine the packet boundary.</p>\n" }, { "answer_id": 71951, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 0, "selected": false, "text": "<p>If you want to know the amount of data that it's expected to arrive, you could always write at the begining of every msg sent by the pipes the size of the msg.\nSo write for example 4 bytes at the start of every msg with the length of your data, and then only read the first 4 bytes.</p>\n" }, { "answer_id": 72020, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 4, "selected": false, "text": "<p>Depending on your unix implementation ioctl/FIONREAD might do the trick</p>\n\n<pre>\nerr = ioctl(pipedesc, FIONREAD, &bytesAvailable);\n</pre>\n\n<p>Unless this returns the error code for \"invalid argument\" (or any other error) bytesAvailable contains the amount of data available for unblocking read operations at that time.</p>\n" }, { "answer_id": 74349, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 2, "selected": false, "text": "<p>It's almost never necessary to know how many bytes are in the pipe: perhaps you just want to do a non-blocking read() on the pipe, ie. to check if there are any bytes ready, and if so, read them, but never stop and <em>wait</em> for the pipe to be ready.</p>\n\n<p>You can do that in two steps. First, use the select() system call to find out whether data is available or not. An example is here: <a href=\"http://www.developerweb.net/forum/showthread.php?t=2933\" rel=\"nofollow noreferrer\">http://www.developerweb.net/forum/showthread.php?t=2933</a></p>\n\n<p>Second, if select tells you data is available, call read() once, and only once, with a large block size. It will read <em>only</em> as many bytes are available, or up to the size of your block, whichever is smaller. If select() returns true, read() will always return right away.</p>\n" }, { "answer_id": 74757, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>There is no portable way to tell the amount of data coming from a pipe.\nThe only thing you could do is to read and process data as it comes.</p>\n\n<p>For that you could use something like a <a href=\"http://en.wikipedia.org/wiki/Circular_buffer\" rel=\"nofollow noreferrer\">circular buffer</a></p>\n" }, { "answer_id": 77381, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": -1, "selected": false, "text": "<p>On Windows you can always use <code>PeekNamedPipe</code>, but I doubt that's what you want to do anyway.</p>\n" }, { "answer_id": 731364, "author": "devdimi", "author_id": 54983, "author_profile": "https://Stackoverflow.com/users/54983", "pm_score": 0, "selected": false, "text": "<p>You can wrap it in object with buffering that can be rewinded. This would be feasible only for small amounts of data.</p>\n\n<p>One way to do this in C is to define stuct and wrap all functions operating on pipes for your struct.</p>\n" }, { "answer_id": 63974916, "author": "Thomas Guyot-Sionnest", "author_id": 969196, "author_profile": "https://Stackoverflow.com/users/969196", "pm_score": 0, "selected": false, "text": "<p>As many have answered, you cannot portably tell how many bytes there is to read, OTOH what you can do is poll the pipe for data to be read. First be sure to open the pipe with <code>O_RDWR|O_NONBLOCK</code> - it's mandated by POSIX that a pipe be open for both read and write to be able poll it.</p>\n<p>Whenever you want to know if there is data available, just select/poll for data to read. You can also know if the pipe is full by checking for write but see the note below, depending on the type or write it may be inaccurate.</p>\n<p>You won't know how much data there is but keep in mind writes up to <code>PIPE_BUF</code> bytes are guaranteed to be atomic, so if you're concerned about having a full message on the pipe, just make sure they fit within that or split them up.</p>\n<p><strong>Note:</strong> When you select for write, even if poll/select says you can write to the pipe a write <code>&lt;= PIPE_BUF</code> will return <code>EAGAIN</code> if there isn't enough room for the full write. I have no ideas how to tell if there is enough room to write... that is what I was looking for (I may end padding with <code>\\0</code>'s to <code>PIPE_BUF</code> size... in my case it's just for testing anyway).</p>\n<p>I have an old example app Perl that can read one or more pipes in non-blocking mode, <a href=\"https://github.com/dermoth/misc-code/blob/master/nagios/OCP_Daemon/OCP_daemon\" rel=\"nofollow noreferrer\">OCP_Daemon</a>. The code is pretty close to what you would do in C using an event loop.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a function called `SizeOfPipe()` which should return the size of a pipe - I only want to know how much data is in the pipe and not actually read data off the pipe itself. I thought the following code would work: ``` fseek (pPipe, 0 , SEEK_END); *pBytes = ftell (pPipe); rewind (pPipe); ``` but `fseek()` doesn't work on file descriptors. Another option would be to read the pipe then write the data back but would like to avoid this if possible. Any suggestions?
Depending on your unix implementation ioctl/FIONREAD might do the trick ``` err = ioctl(pipedesc, FIONREAD, &bytesAvailable); ``` Unless this returns the error code for "invalid argument" (or any other error) bytesAvailable contains the amount of data available for unblocking read operations at that time.
71,853
<p>I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery <strong>contains</strong> method but it seems to search <strong>only</strong> in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also. ¿Is there a simple solution to this problem?</p>
[ { "answer_id": 71908, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p><em><a href=\"http://www.google.ru/search?complete=1&amp;hl=en&amp;newwindow=1&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=MdF&amp;q=Sql+Server+contains+function+xquery+case-insensitive&amp;btnG=%CF%EE%E8%F1%EA&amp;lr=&amp;aq=f&amp;oq=\" rel=\"nofollow noreferrer\">First</a></em> link from google points to MSDN page:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178026.aspx\" rel=\"nofollow noreferrer\">contains Function (XQuery)</a></p>\n\n<blockquote>\n <p>In order to get case-insensitive\n comparisons, the <a href=\"http://msdn.microsoft.com/en-us/library/cc645590.aspx\" rel=\"nofollow noreferrer\">upper-case</a> or\n lower-case functions can be used.</p>\n</blockquote>\n" }, { "answer_id": 74594, "author": "JWHEAT", "author_id": 7079, "author_profile": "https://Stackoverflow.com/users/7079", "pm_score": 3, "selected": true, "text": "<p>If you're using SQL Server 2005, I'm afraid you're out of luck.</p>\n\n<p>If you're using SQL Server 2008, you can use the upper-case function like this :</p>\n\n<pre><code>DECLARE @x xml = N'abcDEF!@4';\nSELECT @x.value('fn:upper-case(/text()[1])', 'nvarchar(10)');\n</code></pre>\n\n<p>Here's a link on MSDN for the upper-case syntax and a couple search examples :</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc645590.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc645590.aspx</a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery **contains** method but it seems to search **only** in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also. ¿Is there a simple solution to this problem?
If you're using SQL Server 2005, I'm afraid you're out of luck. If you're using SQL Server 2008, you can use the upper-case function like this : ``` DECLARE @x xml = N'abcDEF!@4'; SELECT @x.value('fn:upper-case(/text()[1])', 'nvarchar(10)'); ``` Here's a link on MSDN for the upper-case syntax and a couple search examples : <http://msdn.microsoft.com/en-us/library/cc645590.aspx>
71,864
<p>I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?</p>
[ { "answer_id": 71891, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 4, "selected": true, "text": "<pre><code>ls -atrd */ | head --lines=-4 | xargs rm -rf\n</code></pre>\n\n<p><strong>Edit:</strong> added 'a' argument to ls</p>\n" }, { "answer_id": 71897, "author": "Alexey Feldgendler", "author_id": 10682, "author_profile": "https://Stackoverflow.com/users/10682", "pm_score": 1, "selected": false, "text": "<p>Please clarify if you mean “delete all directories but the four newst ones” or “delete everything (files and directories) except for the four newest directories”.</p>\n\n<p>Please also note that creation times are not known for directories. One can only tell when a directory was last modified, that is, had files added, removed or renamed.</p>\n" }, { "answer_id": 71972, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 1, "selected": false, "text": "<p>you could do the following:</p>\n\n<pre><code>#!/bin/bash\n\n#store the listing of current directory in var\nmydir=`ls -t`\nit=1\n\nfor file in $mydir\n do\n if [ $it -gt 5 ]\n then\n echo file $it will be deleted: $file\n #rm -rf $file\n fi\n it=$((it+1))\n done\n</code></pre>\n\n<p>(remove the # before rm to make it really happen ;) )</p>\n" }, { "answer_id": 72115, "author": "mdxi", "author_id": 11164, "author_profile": "https://Stackoverflow.com/users/11164", "pm_score": 0, "selected": false, "text": "<p>Another, BSD-safe, way to do it, with arrays (why not?)</p>\n\n<pre><code>#!/bin/bash\nARRAY=( `ls -td */` )\nELEMENTS=${#ARRAY[@]}\nCOUNTER=4\nwhile [ $COUNTER -lt $ELEMENTS ]; do\n echo ${ARRAY[${COUNTER}]}\n let COUNTER=COUNTER+1\ndone\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12015/" ]
I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?
``` ls -atrd */ | head --lines=-4 | xargs rm -rf ``` **Edit:** added 'a' argument to ls
71,913
<p>Here is a sample from Kernighan &amp; Ritchie's "The C Programming Language":</p> <pre><code>int getline(char s[], int lim) { int c, i = 0; while (--lim &gt; 0; &amp;&amp; (c=getchar()) !=EOF &amp;&amp; c !='\n') { s[i++] = c; } if (c =='\n') { s[i++] = c; } s[i] = '\0'; return i; } </code></pre> <p>Why do we should check if <code>c != '\n'</code>, despite we use <code>s[i++] = c</code> after that?</p>
[ { "answer_id": 71935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You do that just to exit the while loop on new line. Else you would have to check it in while body and use break.</p>\n" }, { "answer_id": 71952, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 1, "selected": false, "text": "<p>The comparison is to ensure readline terminates when it encounters a newline character (the '\\n'). On the iteration where it does, it terminates without adding the newline to the string, so the statement after that ensures that the string is always newline terminated, even if one of the other termination conditions was reached.</p>\n" }, { "answer_id": 71954, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 0, "selected": false, "text": "<p>That ensures that you stop at the end of the line even if it's not the end of the input. Then if there is a newline the \\n is added to the end of the line and i incremented one more time to avoid overwriting it with the \\0.</p>\n" }, { "answer_id": 71988, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<pre><code>int getline(char s[], int lim)\n{\n int c, i;\n i=0;\n /* While staying withing limit and there is a char in stdin and it's not new line sign */\n while (--lim &gt; 0; &amp;&amp; (c=getchar()) !=EOF &amp;&amp; c !='\\n')\n /* Store char at the current position in array, advance current pos by one */\n s[i++] = c;\n /* If While loop stopped on new-line, store it in array, advance current pos by one */\n if (c =='\\n') \n s[i++] = c;\n /* finally terminate string with \\0 */\n s[i] = '\\0';\n return i;\n}\n</code></pre>\n" }, { "answer_id": 71999, "author": "aggergren", "author_id": 7742, "author_profile": "https://Stackoverflow.com/users/7742", "pm_score": 3, "selected": true, "text": "<p>The functions reads characters from the standard input until either EOF or a newline characters is found. </p>\n\n<p>The second check ensures that the only newline character is put into the char array. EOF shouldn't occur in a proper c-string. Also, if the character isn't newline that means that we might have filled up our c-string, in which case we shouldn't put any more characters into it. </p>\n\n<p>Notice we still append the '\\0'. We've ensured that theres still room for one more character in our c-string, as we use the pre-fix decrementor, which evaluates before the comparison.</p>\n" }, { "answer_id": 72017, "author": "auramo", "author_id": 4110, "author_profile": "https://Stackoverflow.com/users/4110", "pm_score": 0, "selected": false, "text": "<p>I'm not sure whether I understand the question. <code>c !='\\n'</code> is used to stop reading the line when the end of line (linefeed) occurs. Otherwise we would always read it until the limit even if it ends before. The first <code>s[i++] = c;</code> in the while-loop doesn't occur if a linefeed has been reached. That's why there is the special test afterwards and the other <code>s[i++] = c;</code> in case it was a linefeed which broke the loop.</p>\n" }, { "answer_id": 72069, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Not answering your question, but I'll write some comments anyway:</p>\n\n<p>I don't remember all K&amp;R rules, but the function you've listed will fail if lim is equal to one. Then you won't run the loop which leaves c unintialised, but you'll still use the variable in the if (c == '\\n') check.</p>\n\n<p>Also the while (--lm > 0; ...) thing will not go through the compiler. Remove the ';' and it does.</p>\n" }, { "answer_id": 83291, "author": "user11211", "author_id": 11211, "author_profile": "https://Stackoverflow.com/users/11211", "pm_score": 1, "selected": false, "text": "<p>There is a bug in the code.</p>\n\n<p>If the size of s is N bytes and the user types a newline as the (N-1)th character, the Nth character will become a '\\n' and the (N+1)th character (which is not allocated) will become a '\\0'.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11972/" ]
Here is a sample from Kernighan & Ritchie's "The C Programming Language": ``` int getline(char s[], int lim) { int c, i = 0; while (--lim > 0; && (c=getchar()) !=EOF && c !='\n') { s[i++] = c; } if (c =='\n') { s[i++] = c; } s[i] = '\0'; return i; } ``` Why do we should check if `c != '\n'`, despite we use `s[i++] = c` after that?
The functions reads characters from the standard input until either EOF or a newline characters is found. The second check ensures that the only newline character is put into the char array. EOF shouldn't occur in a proper c-string. Also, if the character isn't newline that means that we might have filled up our c-string, in which case we shouldn't put any more characters into it. Notice we still append the '\0'. We've ensured that theres still room for one more character in our c-string, as we use the pre-fix decrementor, which evaluates before the comparison.
71,932
<p>I'm missing the boat on something here, kids. This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.</p> <p>When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running. The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#. I'm hoping that there is something blindingly obvious I'm missing. Here's a typical binding that gets crushed:</p> <pre><code>TextBlock tb = new TextBlock(); Binding b = new Binding("FontSize"); b.Source = this; tb.SetBinding(TextBlock.FontSizeProperty, b); </code></pre>
[ { "answer_id": 72129, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I've just tried the exact code you just posted and it worked fine, with some changes. I believe the problem is the element you are using for the SetBinding call is not the textblock you want to bind. It should be:</p>\n\n<pre><code>TextBlock tb = new TextBlock();\nBinding b = new Binding(\"FontSize\");\nb.Source = this;\ntb.SetBinding(TextBlock.FontSizeProperty, b);\n</code></pre>\n\n<p>Make sure you also have a FontSize public property of type double on \"this\". If \"this\" is a user control, I would recommend renaming the property so you don't hide the inherited member.</p>\n" }, { "answer_id": 2186878, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 3, "selected": true, "text": "<p>It looks like as of Silverlight 3.1, at least, this is no longer an issue. I can't reproduce it, at any rate.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ]
I'm missing the boat on something here, kids. This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help. When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running. The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#. I'm hoping that there is something blindingly obvious I'm missing. Here's a typical binding that gets crushed: ``` TextBlock tb = new TextBlock(); Binding b = new Binding("FontSize"); b.Source = this; tb.SetBinding(TextBlock.FontSizeProperty, b); ```
It looks like as of Silverlight 3.1, at least, this is no longer an issue. I can't reproduce it, at any rate.
71,944
<p>I am using <code>&lt;input type="file" id="fileUpload" runat="server"&gt;</code> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions). </p> <p>Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).</p>
[ { "answer_id": 71987, "author": "Chris Roberts", "author_id": 475, "author_profile": "https://Stackoverflow.com/users/475", "pm_score": 1, "selected": false, "text": "<p>Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.</p>\n\n<p>I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called <a href=\"http://www.telerik.com/products/aspnet-ajax/controls/upload/overview.aspx\" rel=\"nofollow noreferrer\">radUpload by Telerik</a>. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.</p>\n\n<p>I'm sure there are open source solutions available, too.</p>\n" }, { "answer_id": 72009, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>Your only option seems to be client-side validation, because server side means the file was already uploaded. Also the MIME type is usually dictated by the file extension. </p>\n\n<p>use a JavaScript Framework like jQuery to overload the onsubmit event of the form. Then check the extension. This will limit most attempts. However if a person changes an image to extension XLS then you will have a problem.</p>\n\n<p>I don't know if this is an option for you, but you have more client side control when using something like Silverlight or Flash to upload. You may consider using one of these technologies for your upload process.</p>\n" }, { "answer_id": 72013, "author": "staktrace", "author_id": 12050, "author_profile": "https://Stackoverflow.com/users/12050", "pm_score": 3, "selected": false, "text": "<p>From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:</p>\n\n<pre><code>&lt;form onsubmit=\"if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }\"&gt;...&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 72031, "author": "AlexWilson", "author_id": 2240, "author_profile": "https://Stackoverflow.com/users/2240", "pm_score": 2, "selected": false, "text": "<p>You could use a regular expression validator on the upload control:</p>\n\n<pre><code> &lt;asp:RegularExpressionValidator id=\"FileUpLoadValidator\" runat=\"server\" ErrorMessage=\"Upload Excel files only.\" ValidationExpression=\"^(([a-zA-Z]:)|(\\\\{2}\\w+)\\$?)(\\\\(\\w[\\w].*))(.xls|.XLS|.xlsx|.XLSX)$\" ControlToValidate=\"fileUpload\"&gt; &lt;/asp:RegularExpressionValidator&gt;\n</code></pre>\n\n<p>There is also the accept attribute of the input tag:</p>\n\n<pre><code>&lt;input type=\"file\" accept=\"application/msexcel\" id=\"fileUpload\" runat=\"server\"&gt;\n</code></pre>\n\n<p>but I did not have much success when I tried this (with FF3 and IE7)</p>\n" }, { "answer_id": 72077, "author": "DeeCee", "author_id": 5895, "author_profile": "https://Stackoverflow.com/users/5895", "pm_score": 1, "selected": false, "text": "<p>I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:</p>\n\n<p>1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers </p>\n\n<p>2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded</p>\n\n<p>hope it helps :)</p>\n" }, { "answer_id": 72221, "author": "Jamie", "author_id": 8391, "author_profile": "https://Stackoverflow.com/users/8391", "pm_score": 6, "selected": true, "text": "<p>Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;input type=\"file\" name=\"FILENAME\" size=\"20\" onchange=\"check_extension(this.value,\"upload\");\"/&gt;\n&lt;input type=\"submit\" id=\"upload\" name=\"upload\" value=\"Attach\" disabled=\"disabled\" /&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>var hash = {\n 'xls' : 1,\n 'xlsx' : 1,\n};\n\nfunction check_extension(filename,submitId) {\n var re = /\\..+$/;\n var ext = filename.match(re);\n var submitEl = document.getElementById(submitId);\n if (hash[ext]) {\n submitEl.disabled = false;\n return true;\n } else {\n alert(\"Invalid filename, please select another file\");\n submitEl.disabled = true;\n\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 72305, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 1, "selected": false, "text": "<p>Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: <a href=\"http://www.brettle.com/neatupload\" rel=\"nofollow noreferrer\">http://www.brettle.com/neatupload</a><br/>\n<br/>\nFaster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.</p>\n" }, { "answer_id": 72608, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 2, "selected": false, "text": "<p>As some people have mentioned, Javascript is the way to go. Bear in mind that the \"validation\" here is only by file extension, it won't validate that the file is a real excel spreadsheet!</p>\n" }, { "answer_id": 72909, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 3, "selected": false, "text": "<p>I agree with Chris, checking the extension is not validation of the type of file any way you look at it. <a href=\"http://www.telerik.com/products/aspnet-ajax/controls/upload/overview.aspx\" rel=\"noreferrer\">Telerik's radUpload</a> is probably your best option, it provides a ContentType property of the file being uploaded, which you can compare to known mime types. You should check for:</p>\n\n<p>application/vnd.ms-excel, </p>\n\n<p>application/excel, </p>\n\n<p>application/x-msexcel </p>\n\n<p>and for the new 2k7 format:</p>\n\n<p>application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet</p>\n\n<p>Telerik used to sell radUpload as an individual component, but now its wrapped into the controls suite, which makes it a little more expensive, but by far its the easiest way to check for the true type</p>\n" }, { "answer_id": 330563, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 2, "selected": false, "text": "<p>Ensure that you always check for the file extension in server-side to ensure that no one can upload a <strong>malicious file</strong> such as .aspx, .asp etc.</p>\n" }, { "answer_id": 2287671, "author": "chillysapien", "author_id": 30297, "author_profile": "https://Stackoverflow.com/users/30297", "pm_score": 1, "selected": false, "text": "<p>As an alternative option, could you use the \"accept\" attribute of HTML File Input which defines which MIME types are acceptable.</p>\n\n<p>Definition <a href=\"http://www.w3schools.com/jsref/dom_obj_fileupload.asp\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 3188902, "author": "shailesh", "author_id": 264813, "author_profile": "https://Stackoverflow.com/users/264813", "pm_score": 5, "selected": false, "text": "<p>It's pretty simple using regulare expression validator. </p>\n\n<pre><code>&lt;asp:RegularExpressionValidator\nid=\"RegularExpressionValidator1\"\nrunat=\"server\"\nErrorMessage=\"Only zip file is allowed!\"\nValidationExpression =\"^.+(.zip|.ZIP)$\"\nControlToValidate=\"FileUpload1\"\n&gt; &lt;/asp:RegularExpressionValidator&gt;\n</code></pre>\n\n<p><a href=\"http://patelshailesh.com/index.php/client-side-validation-of-file-types-permissible-to-upload\" rel=\"noreferrer\">Client-Side Validation of File Types Permissible to Upload</a></p>\n" }, { "answer_id": 17468608, "author": "m_cheung", "author_id": 582032, "author_profile": "https://Stackoverflow.com/users/582032", "pm_score": 2, "selected": false, "text": "<p>Based on kd7's reply suggesting you check for the files content type, here's a wrapper method:</p>\n\n<pre><code>private bool FileIsValid(FileUpload fileUpload)\n{\n if (!fileUpload.HasFile)\n {\n return false;\n }\n if (fileUpload.PostedFile.ContentType == \"application/vnd.ms-excel\" ||\n fileUpload.PostedFile.ContentType == \"application/excel\" ||\n fileUpload.PostedFile.ContentType == \"application/x-msexcel\" ||\n fileUpload.PostedFile.ContentType == \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" //this is xlsx format\n )\n return true;\n\n return false;\n}\n</code></pre>\n\n<p>returning true if the file to upload is .xls or .xlsx</p>\n" }, { "answer_id": 19550823, "author": "Mark_fsg", "author_id": 2864444, "author_profile": "https://Stackoverflow.com/users/2864444", "pm_score": 0, "selected": false, "text": "<p>As another respondent notes, the file type can be spoofed (e.g., .exe renamed .pdf), which checking for the MIME type will not prevent (i.e., the .exe will show a MIME of \"application/pdf\" if renamed as .pdf). I believe a check of the true file type can only be done server side; an easy way to check it using System.IO.BinaryReader is described here:</p>\n\n<p><a href=\"http://forums.asp.net/post/2680667.aspx\" rel=\"nofollow\">http://forums.asp.net/post/2680667.aspx</a></p>\n\n<p>and VB version here: </p>\n\n<p><a href=\"http://forums.asp.net/post/2681036.aspx\" rel=\"nofollow\">http://forums.asp.net/post/2681036.aspx</a></p>\n\n<p>Note that you'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get them by implementing this solution and debugging the code.</p>\n" }, { "answer_id": 54115000, "author": "Rana", "author_id": 1964270, "author_profile": "https://Stackoverflow.com/users/1964270", "pm_score": 0, "selected": false, "text": "<p>Client Side Validation Checking:-</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;asp:FileUpload ID=\"FileUpload1\" runat=\"server\" /&gt;\n&lt;asp:Button ID=\"btnUpload\" runat=\"server\" Text=\"Upload\" OnClientClick = \"return ValidateFile()\" OnClick=\"btnUpload_Click\" /&gt;\n&lt;br /&gt;\n&lt;asp:Label ID=\"Label1\" runat=\"server\" Text=\"\" /&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>&lt;script type =\"text/javascript\"&gt;\n\n var validFilesTypes=[\"bmp\",\"gif\",\"png\",\"jpg\",\"jpeg\",\"doc\",\"xls\"];\n\n function ValidateFile()\n\n {\n\n var file = document.getElementById(\"&lt;%=FileUpload1.ClientID%&gt;\");\n\n var label = document.getElementById(\"&lt;%=Label1.ClientID%&gt;\");\n\n var path = file.value;\n\n var ext=path.substring(path.lastIndexOf(\".\")+1,path.length).toLowerCase();\n\n var isValidFile = false;\n\n for (var i=0; i&lt;validFilesTypes.length; i++) \n { \n if (ext==validFilesTypes[i]) \n { \n isValidFile=true; \n break; \n } \n }\n\n if (!isValidFile) \n { \n label.style.color=\"red\"; \n label.innerHTML=\"Invalid File. Please upload a File with\" + \n \" extension:\\n\\n\"+validFilesTypes.join(\", \"); \n } \n return isValidFile; \n } \n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51/" ]
I am using `<input type="file" id="fileUpload" runat="server">` to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions). Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).
Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash. HTML: ``` <input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/> <input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" /> ``` Javascript: ``` var hash = { 'xls' : 1, 'xlsx' : 1, }; function check_extension(filename,submitId) { var re = /\..+$/; var ext = filename.match(re); var submitEl = document.getElementById(submitId); if (hash[ext]) { submitEl.disabled = false; return true; } else { alert("Invalid filename, please select another file"); submitEl.disabled = true; return false; } } ```
71,959
<p>I have my own class inside the file "Particles.h" and the class's implementation is inside "Particles.cpp"</p> <p>I want the file "Load.h" to recognize my classes inside there, so I've added the line</p> <pre><code>#include "Particles.h" </code></pre> <p>and the file doesn't recognize it and in the past everything was OK (I haven't made any changes inside that class).</p> <p>What should I do?</p>
[ { "answer_id": 71984, "author": "mrgroucho", "author_id": 10870, "author_profile": "https://Stackoverflow.com/users/10870", "pm_score": 2, "selected": false, "text": "<p>It sounds like your include path - the list of directories that the compiler scans in order to locate files that you #include - is set incorrectly. Which compiler are you using?</p>\n" }, { "answer_id": 72019, "author": "Steve Obbayi", "author_id": 11190, "author_profile": "https://Stackoverflow.com/users/11190", "pm_score": 0, "selected": false, "text": "<p>make sure the file \"Particles.cpp\" has also included \"Particles.h\" to start with and the files are in the same folder and they are all part of the same project. it will help if you also share the error message that you are getting from your compiler.</p>\n" }, { "answer_id": 72021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Dev C++,It uses GCC,\nThe line is:</p>\n\n<pre><code>Stone *stone[48];\n</code></pre>\n\n<p>and it says: \"expected constructor, destructor, or type conversion before '*' token \".</p>\n" }, { "answer_id": 72109, "author": "CariElf", "author_id": 12117, "author_profile": "https://Stackoverflow.com/users/12117", "pm_score": 1, "selected": false, "text": "<p>Well, if you listed your error codes, it might help. Off the top of my head, do you have something in Particles.h to make sure that the file is only included once? There are two methods of doing this. The first is to use #pragma once, but I think that might be Microsoft specific. The second is to use a #define.\nExample:</p>\n\n<pre><code>#ifndef PARTICLES_H \n#define PARTICLES_H\n\nclass CParticleWrapper\n{\n...\n};\n\n#endif\n</code></pre>\n\n<p>Also, unless you're deriving from a class in Particles.h or using an instance of a class instead of a pointer, you can use a forward declaration of the class and skip including the header file in a header file, which will save you compile time.</p>\n\n<pre><code>#ifndef LOAD_H\n#define LOAD_H\n\nclass CParticleWrapper;\n\nclass CLoader\n{\n CParticleWrapper * m_pParticle;\n\npublic:\n\n CLoader(CParticleWrapper * pParticle);\n ...\n}; \n\n#endif\n</code></pre>\n\n<p>Then, in the Load.cpp, you would include the particle.h file.</p>\n" }, { "answer_id": 73068, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "<p>It sounds like you need to include the definition of the Stone class, but it would be impossible to say without more details. Can you narrow down the error by removing unrelated code and post that?</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have my own class inside the file "Particles.h" and the class's implementation is inside "Particles.cpp" I want the file "Load.h" to recognize my classes inside there, so I've added the line ``` #include "Particles.h" ``` and the file doesn't recognize it and in the past everything was OK (I haven't made any changes inside that class). What should I do?
It sounds like your include path - the list of directories that the compiler scans in order to locate files that you #include - is set incorrectly. Which compiler are you using?
71,985
<p>How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once?</p> <p>Any ideas before I go and write my own functions.</p>
[ { "answer_id": 72008, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>You will want to kill the line: C-a C-k, and then C-y or ?</p>\n" }, { "answer_id": 72039, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 5, "selected": false, "text": "<p>you can use a keyboard macro for that:-</p>\n\n<p>C-a C-k C-x ( C-y C-j C-x ) C-u 9 C-x e</p>\n\n<p><strong>Explanation:-</strong></p>\n\n<ul>\n<li>C-a : Go to start of line</li>\n<li>C-k : Kill line</li>\n<li>C-x ( : Start recording keyboard macro</li>\n<li>C-y : Yank killed line</li>\n<li>C-j : Move to next line</li>\n<li>C-x ) : Stop recording keyboard macro</li>\n<li>C-u 9 : Repeat 9 times</li>\n<li>C-x e : Execute keyboard macro</li>\n</ul>\n" }, { "answer_id": 72141, "author": "Mike Monette", "author_id": 6166, "author_profile": "https://Stackoverflow.com/users/6166", "pm_score": 0, "selected": false, "text": "<p>I don't know of a direct equivalent (C-y 10 times is the best I know), but you may be interested in Viper, which is a vi emulation package for emacs. It's part of the standard emacs distribution.</p>\n" }, { "answer_id": 72181, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 5, "selected": true, "text": "<p><strong>Copying</strong>:</p>\n\n<p>If you frequently work with lines, you might want to make copy (<code>kill-ring-save</code>) and cut (<code>kill-region</code>) work on lines when no region is selected:</p>\n\n<pre><code>(defadvice kill-ring-save (before slickcopy activate compile)\n \"When called interactively with no active region, copy a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n(defadvice kill-region (before slickcut activate compile)\n \"When called interactively with no active region, kill a single line instead.\"\n (interactive\n (if mark-active (list (region-beginning) (region-end))\n (list (line-beginning-position)\n (line-beginning-position 2)))))\n</code></pre>\n\n<p>Then you can copy the line with just M-w.</p>\n\n<p><strong>Pasting</strong>:</p>\n\n<p>Often a prefix argument just performs an action multiple times, so you'd expect C-u 10 C-y to work, but in this case C-y uses its argument to mean which element of the kill-ring to \"yank\" (paste). The only solution I can think of is what kronoz says: record a macro with C-x ( C-y C-x ) and then let the argument of C-u go to <code>kmacro-end-and-call-macro</code> instead (that's C-u 9 C-x e or even just C-9 C-x e or M-9 C-x e).</p>\n\n<p><strong>Another way</strong>:\nYou can also just stay in <code>M-x viper-mode</code> and use yy10p :)</p>\n" }, { "answer_id": 72202, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "<p>The only way I know to repeat arbitrary commands is to use the \"repeat by argument\" feature of keyboard macros.</p>\n\n<p>C-a C-space down M-w C-x ( C-y C-x ) C-9 C-x e</p>\n\n<ul>\n<li>C-a : Go to start of line</li>\n<li>C-space : Set mark</li>\n<li>down : Go to start of following line</li>\n<li>M-w : Copy region</li>\n<li>C-x ( : Start keyboard macro</li>\n<li>C-y : Yank copied line</li>\n<li>C-x ) : End keyboard macro</li>\n<li>C-9 C-x e : Execute keyboard macro nine times.</li>\n</ul>\n\n<p>That's kind of weak compared to vim. But only because vim is amazingly efficient at this sort of thing.</p>\n\n<p>If you are really pining for modal vi-like interaction, you could use one of the vi emulation modes, such as viper-mode. Check in the section \"Emulation\" of online emacs manual.</p>\n" }, { "answer_id": 72601, "author": "Baxissimo", "author_id": 9631, "author_profile": "https://Stackoverflow.com/users/9631", "pm_score": 4, "selected": false, "text": "<p>You may know this, but for <strong>many</strong> commands a \"C-u 10\" prefix will do the trick. Unfortunately for the C-y yank command, \"C-u\" is redefined to mean \"go back that many items in the kill ring, and yank that item\".</p>\n\n<p>I thought you might be able to use the copy-to-register and insert-register commands with the C-u prefix command, but apparently that doesn't work either.</p>\n\n<p>Also C-x z, \"repeat last command\" seems to be immune to C-u.</p>\n\n<p>Another thought would be to use M-: to get an Eval prompt and type in a bit of elisp. I thought something like (dotimes '10 'yank) might do it, but it doesn't seem to.</p>\n\n<p>So it looks like using C-u on a macro may indeed be the best you can do short of writing your own little function.</p>\n\n<p>Had I a vote, I'd vote for kronoz answer.</p>\n" }, { "answer_id": 73678, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p>Here's a function I took from an OS/2 port of Emacs. (Yes, I've been using Emacs for a while.)</p>\n\n<pre><code>;; Author: Eberhard Mattes &lt;[email protected]&gt;\n(defun emx-dup-line (arg)\n \"Duplicate current line.\nSet mark to the beginning of the new line.\nWith argument, do this that many times.\"\n (interactive \"*p\")\n (setq last-command 'identity) ; Don't append to kill ring\n (let ((s (point)))\n (beginning-of-line)\n (let ((b (point)))\n (forward-line)\n (if (not (eq (preceding-char) ?\\n)) (insert ?\\n))\n (copy-region-as-kill b (point))\n (while (&gt; arg 0)\n (yank)\n (setq arg (1- arg)))\n (goto-char s))))\n</code></pre>\n\n<p>I have that bound to F9 d:</p>\n\n<pre><code>(global-set-key [f9 ?d] 'emx-dup-line)\n</code></pre>\n\n<p>Then I'd use C-u 10 F9 d to duplicate a line 10 times.</p>\n" }, { "answer_id": 75430, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": -1, "selected": false, "text": "<p>You get the line with C-k, you make the next command happen ten times with C-u 10, then you paste the line with C-y. Pretty simple.</p>\n\n<p>If you always want C-k to do the whole line, you can set kill-whole-line to t. No more fiddling with C-a or C-e.</p>\n\n<p>There's a lot you can do with fancy kill rings, registers, and macros, and I encourage you to learn them, but yanking a line ten times doesn't have to be tough or strange.</p>\n" }, { "answer_id": 1567969, "author": "Paul", "author_id": 190056, "author_profile": "https://Stackoverflow.com/users/190056", "pm_score": 3, "selected": false, "text": "<p>You don't need both C-x ) and C-x e in this example.</p>\n\n<p>You can just give the repeat argument straight to C-x ). This stops recording and repeats the macro, in one step. Or you can skip C-x ) and go straight to C-x e, since C-x e will end the recording before doing the repeats.</p>\n\n<p>Which way to choose depends on how you like your repeat count to work. For C-x ) you say how many repeats you wanted in total (so 10 in this case). For C-x e you need to say how many more repeats are left (i.e. 9).</p>\n\n<hr>\n\n<p>C-a C-k C-k will also kill the trailing newline, so you don't have to put it back yourself later. It's quicker than using the mark, and doesn't need you to change any variables.</p>\n\n<p>Even better (unless you're in a terminal), you can use C-S-Backspace* to kill the entire line, regardless of where you are in it.</p>\n\n<p>[* If you're using X windows, make sure to type shift (<strong>not</strong> alt) or you may terminate your session!]</p>\n\n<p>Speaking of terminals, M-9 is a nice alternative if you find you can't type C-9.</p>\n\n<hr>\n\n<p>In Emacs 22 and higher, by default F3 starts a macro and F4 end/repeats a macro. You just hit F3 to start recording, hit F4 when you're done, and hit F4 again to repeat the macro. (F4 also takes an argument.)</p>\n\n<hr>\n\n<p>Putting this all together, to get 10 copies of the current line:</p>\n\n<ul>\n<li>C-S-Backspace : kill this line</li>\n<li>F3 : start macro</li>\n<li>C-y : yank the line</li>\n<li>C-1 C-0 F4 : make that 10 yanks</li>\n</ul>\n\n<p>Not quite as short as y y 10 p, but pretty close. :)</p>\n" }, { "answer_id": 1641331, "author": "quodlibetor", "author_id": 25616, "author_profile": "https://Stackoverflow.com/users/25616", "pm_score": 0, "selected": false, "text": "<p>Based on Baxissimo's answer I defuned this:</p>\n\n<pre><code>(defun yank-n-times (arg)\n \"yank prefix-arg number of times. Not safe in any way.\"\n (interactive \"*p\")\n (dotimes 'arg (yank)))\n</code></pre>\n\n<p>Set that to some key, call it with a prefix argument, and off you go.</p>\n\n<p><strong>edit</strong> (also modified the interactive call above to be less lousy)</p>\n\n<p>Or, here's a version that can sort of replace yank-pop:</p>\n\n<pre><code>(defun yank-n-times (&amp;optional arg)\n \"yank prefix-arg number of times. Call yank-pop if last command was yank.\"\n (interactive \"*p\")\n (if (or (string= last-command \"yank\")\n (string= last-command \"yank-pop\"))\n (yank-pop arg)\n (if (&gt; arg 1)\n (dotimes 'arg (yank))\n (message \"Previous arg was not a yank, and called without a prefix.\"))))\n</code></pre>\n\n<p>the message is kind of a lie, but you shouldn't call it without a prefix of greater than 1 anyway, so.</p>\n\n<p>Not sure if it's a good idea, but I replaced M-y with this, I'll see how that goes.</p>\n" }, { "answer_id": 74419566, "author": "Sergey V", "author_id": 13256934, "author_profile": "https://Stackoverflow.com/users/13256934", "pm_score": 0, "selected": false, "text": "<p>First you need this key binding in your .emacs:</p>\n<pre><code>;; yank n times\n(global-set-key &quot;\\C-y&quot; (lambda (n) (interactive &quot;*p&quot;) (dotimes (i n) (clipboard-yank))))\n</code></pre>\n<p>Then you can do:</p>\n<pre><code>C-a C-SPC C-n M-w C-u 10 C-y\n</code></pre>\n<p>C-a C-SPC C-n M-w - select whole line<br>\nC-u 10 C-y - repeat &quot;clipboard-yank&quot; 10 times</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/71985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9831/" ]
How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once? Any ideas before I go and write my own functions.
**Copying**: If you frequently work with lines, you might want to make copy (`kill-ring-save`) and cut (`kill-region`) work on lines when no region is selected: ``` (defadvice kill-ring-save (before slickcopy activate compile) "When called interactively with no active region, copy a single line instead." (interactive (if mark-active (list (region-beginning) (region-end)) (list (line-beginning-position) (line-beginning-position 2))))) (defadvice kill-region (before slickcut activate compile) "When called interactively with no active region, kill a single line instead." (interactive (if mark-active (list (region-beginning) (region-end)) (list (line-beginning-position) (line-beginning-position 2))))) ``` Then you can copy the line with just M-w. **Pasting**: Often a prefix argument just performs an action multiple times, so you'd expect C-u 10 C-y to work, but in this case C-y uses its argument to mean which element of the kill-ring to "yank" (paste). The only solution I can think of is what kronoz says: record a macro with C-x ( C-y C-x ) and then let the argument of C-u go to `kmacro-end-and-call-macro` instead (that's C-u 9 C-x e or even just C-9 C-x e or M-9 C-x e). **Another way**: You can also just stay in `M-x viper-mode` and use yy10p :)
72,010
<p>Given the following example, why do I have to explicitly use the statement <code>b-&gt;A::DoSomething()</code> rather than just <code>b-&gt;DoSomething()</code>?</p> <p>Shouldn't the compiler's overload resolution figure out which method I'm talking about?</p> <p>I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)</p> <pre><code>class A { public: int DoSomething() {return 0;}; }; class B : public A { public: int DoSomething(int x) {return 1;}; }; int main() { B* b = new B(); b-&gt;A::DoSomething(); //Why this? //b-&gt;DoSomething(); //Why not this? (Gives compiler error.) delete b; return 0; } </code></pre>
[ { "answer_id": 72075, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p>The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done <em>afterwards</em>. In your case this means that the compiler sees <code>B::DoSomething</code>. It then tries to match the argument list, which fails.</p>\n\n<p>One solution would be to pull down the overload from <code>A</code> into <code>B</code>'s scope:</p>\n\n<pre><code>class B : public A {\npublic:\n using A::DoSomething;\n // …\n}\n</code></pre>\n" }, { "answer_id": 72076, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 4, "selected": false, "text": "<p>Overload resolution is one of the ugliest parts of C++</p>\n\n<p>Basically the compiler finds a name match \"DoSomething(int)\" in the scope of B, sees the parameters don't match, and stops with an error.</p>\n\n<p>It can be overcome by using the A::DoSomething in class B</p>\n\n<pre><code>class A \n{ \n public: \n int DoSomething() {return 0;}\n}; \n\nclass B : public A \n{ \n public: \n using A::DoSomething;\n int DoSomething(int x) {return 1;} \n}; \n\n\nint main(int argc, char** argv)\n{\n B* b = new B(); \n // b-&gt;A::DoSomething(); // still works, but...\n b-&gt;DoSomething(); // works now too\n delete b; \n return 0;\n}\n</code></pre>\n" }, { "answer_id": 72081, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 2, "selected": false, "text": "<p>When you define a function in a derived class then it hides all the functions with that name in the base class. If the base class function is virtual and has a compatible signature then the derived class function also overrides the base class function. However, that doesn't affect the visibility.</p>\n\n<p>You can make the base class function visible with a using declaration:</p>\n\n<pre><code>class B : public A \n{ \n public: \n int DoSomething(int x) {return 1;}; \n using A::DoSomething;\n}; \n</code></pre>\n" }, { "answer_id": 72082, "author": "Jono", "author_id": 6552, "author_profile": "https://Stackoverflow.com/users/6552", "pm_score": 1, "selected": false, "text": "<p>When searching up the inheritance tree for the function to use, C++ uses the name without arguments, once it has found any definition it stops, then examines the arguments. In the example given, it stops in class B. In order to be able to do what you are after, class B should be defined like this:</p>\n\n<pre><code>class B : public A \n{ \n public:\n using A::DoSomething;\n int DoSomething(int x) {return 1;}; \n}; \n</code></pre>\n" }, { "answer_id": 72086, "author": "slicedlime", "author_id": 11230, "author_profile": "https://Stackoverflow.com/users/11230", "pm_score": 1, "selected": false, "text": "<p>The function is hidden by the function with the same name in the subclass (but with a different signature). You can unhide it by using the using statement, as in using A::DoSomething();</p>\n" }, { "answer_id": 72142, "author": "Lehane", "author_id": 142, "author_profile": "https://Stackoverflow.com/users/142", "pm_score": 3, "selected": false, "text": "<p>No, this behaviour is present to ensure that you don't get caught out inheriting from distant base classes by mistake.</p>\n\n<p>To get around it, you need to tell the compiler which method you want to call by placing a using A::DoSomething in the B class.</p>\n\n<p>See <a href=\"http://becomeaprogrammerin21years.blogspot.com/2008/03/c-inheritance-oddity.html\" rel=\"noreferrer\">this article</a> for a quick and easy overview of this behaviour.</p>\n" }, { "answer_id": 72172, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This has something to do with the way name resolution works. Basically, we first find the scope from which the name comes, and then we collect all overloads for that name in that scope. However, the scope in your case is class B, and in class B, B::DoSomething <strong>hides</strong> A::DOSomething:</p>\n\n<p>3.3.7 Name hiding [basic.scope.hiding]</p>\n\n<p>...[snip]...</p>\n\n<p>3 In a member function definition, the declaration of a local name hides\n the declaration of a member of the class with the same name; see\n <em>basic.scope.class</em>. The declaration of a member in a derived class\n (<em>class.derived</em>) hides the declaration of a member of a base class of\n the same name; see <em>class.member.lookup</em>.</p>\n\n<p>Because of name hiding, A::DoSomething is not even considered for overload resolution</p>\n" }, { "answer_id": 72535, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": 2, "selected": false, "text": "<p>That's not overloading! That's HIDING!</p>\n" }, { "answer_id": 74749, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>The presence of a method in a derived class hides all methods with the same name (regardless of parameters) in base classes. This is done to avoid problems like this:</p>\n\n<pre><code>class A {} ;\nclass B :public A\n{\n void DoSomething(long) {...}\n}\n\nB b;\nb.DoSomething(1); // calls B::DoSomething((long)1));\n</code></pre>\n\n<p>than later someone changes class A:</p>\n\n<pre><code>class A\n{\n void DoSomething(int ) {...}\n}\n</code></pre>\n\n<p>now suddenly:</p>\n\n<pre><code>B b;\nb.DoSomething(1); // calls A::DoSomething(1);\n</code></pre>\n\n<p>In other words, if it didn't work like this, a unrelated change in a class you don't control (A), could silently affect how your code works.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12083/" ]
Given the following example, why do I have to explicitly use the statement `b->A::DoSomething()` rather than just `b->DoSomething()`? Shouldn't the compiler's overload resolution figure out which method I'm talking about? I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.) ``` class A { public: int DoSomething() {return 0;}; }; class B : public A { public: int DoSomething(int x) {return 1;}; }; int main() { B* b = new B(); b->A::DoSomething(); //Why this? //b->DoSomething(); //Why not this? (Gives compiler error.) delete b; return 0; } ```
The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done *afterwards*. In your case this means that the compiler sees `B::DoSomething`. It then tries to match the argument list, which fails. One solution would be to pull down the overload from `A` into `B`'s scope: ``` class B : public A { public: using A::DoSomething; // … } ```
72,014
<p>What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?</p> <p>I am brand new to this, and I've found that there are significant method attributes like:</p> <pre><code>[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")] </code></pre> <p>I'm also looking for common pitfalls to avoid, etc.</p>
[ { "answer_id": 72113, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": true, "text": "<p>Some that I remember:</p>\n\n<ul>\n<li>Keep its usage to a minimum, only use it when T-SQL proved too complex.</li>\n<li>Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context.</li>\n<li>Only use the SQL-Server native data types unless totally necessary.</li>\n</ul>\n\n<p>Can't remember where I've found the information, but those are some that I do remember.</p>\n\n<p>Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.).</p>\n" }, { "answer_id": 72247, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 1, "selected": false, "text": "<p>Single tip regarding assembly deployment:</p>\n\n<p>Keep functionality isolated across small assemblies. Try not to build a dependency chain, because replacing a base assembly means you need to remove the dependent assemblies <em>first</em>, before you can update the base assembly.</p>\n" }, { "answer_id": 72941, "author": "David Waters", "author_id": 12148, "author_profile": "https://Stackoverflow.com/users/12148", "pm_score": -1, "selected": false, "text": "<p>I would strongly advise against putting .net assemblies in your database server, think n-tier applications. Persistence &lt;- Business Logic &lt;-Presentation Logic &lt;- client\nKeep your Logic in your Business Logic layer. </p>\n\n<p>The only reason I can think of to put .net in your database would to add a new complex data type, I would strongly that this be a dumb class that only holds data and does no processing on it.</p>\n\n<p>Just because you can does not mean you should. \nSorry for not directly answering your question.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11947/" ]
What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005? I am brand new to this, and I've found that there are significant method attributes like: ``` [SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")] ``` I'm also looking for common pitfalls to avoid, etc.
Some that I remember: * Keep its usage to a minimum, only use it when T-SQL proved too complex. * Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context. * Only use the SQL-Server native data types unless totally necessary. Can't remember where I've found the information, but those are some that I do remember. Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.).
72,048
<p>I admit I know enough about COM and IE architecture only to be dangerous. I have a working C# .NET ActiveX control similar to this:</p> <pre><code>using System; using System.Runtime.InteropServices; using BrowseUI; using mshtml; using SHDocVw; using Microsoft.Win32; namespace CTI { public interface CTIActiveXInterface { [DispId(1)] string GetMsg(); } [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)] public class CTIActiveX : CTIActiveXInterface { /*** Where can I get a reference to SHDocVw.WebBrowser? *****/ SHDocVw.WebBrowser browser; public string GetMsg() { return "foo"; } } } </code></pre> <p>I registered and created a type library using regasm:</p> <pre><code>regasm CTIActiveX.dll /tlb:CTIActiveXNet.dll /codebase </code></pre> <p>And can successfully instantiate this in javascript:</p> <pre><code>var CTIAX = new ActiveXObject("CTI.CTIActiveX"); alert(CTIAX.GetMsg()); </code></pre> <p>How can I get a reference to the client site (browser window) within CTIActiveX? I have done this in a BHO by implementing IObjectWithSite, but I don't think this is the correct approach for an ActiveX control. If I implement any interface (I mean COM interface like IObjectWithSite) on CTIActiveX when I try to instantiate in Javascript I get an error that the object does not support automation.</p>
[ { "answer_id": 75086, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 2, "selected": false, "text": "<p>First, your interface needs ComVisible(true) in order to be seen by the calling script (this is probably causing the error). </p>\n\n<p>Second, add a .NETreference in your project to \"Microsoft.mshtml\". This will import the COM interfaces for various IE-related things (windows, HTML documents, etc.)</p>\n\n<p>Then, you need to add a property of type IHtmlDocument2 to your interface:</p>\n\n<pre><code>IHtmlDocument2 Document { set; }\n</code></pre>\n\n<p>...implement it in your class:</p>\n\n<pre><code>public IHtmlDocument2 Document\n{\n set { _doc = value;}\n}\n</code></pre>\n\n<p>...call it from script</p>\n\n<pre><code>CTIAX.Document = document; \n</code></pre>\n\n<p>...once you have stored a reference to the document, you can use it at will to get to the window, other frames, or any part of the HTML DOM that you wish.</p>\n" }, { "answer_id": 75982, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have found a workable solution. It's not ideal because it relies on matching the location URL of the IE window to get the correct container, but it does work. In my case I'm using a special value on the query string to make sure I get the right window.</p>\n\n<p>This gets a reference to SHDocVw.InternetExplorer, which exposes the same GetProperty and PutProperty that SHDocVw.WebBrowser does:</p>\n\n<pre><code>private InternetExplorer GetIEWindow(string url)\n{\n SHDocVw.ShellWindowsClass sh = new ShellWindowsClass();\n InternetExplorer IE;\n\n for (int i = 1; i &lt;= sh.Count; i++)\n {\n IE = (InternetExplorer)sh.Item(i);\n if (IE != null)\n {\n if (IE.LocationURL.Contains(url))\n {\n return IE;\n }\n }\n }\n\n return null;\n}\n</code></pre>\n" }, { "answer_id": 10417056, "author": "MarcoM", "author_id": 1307467, "author_profile": "https://Stackoverflow.com/users/1307467", "pm_score": 0, "selected": false, "text": "<p>There a simple and cleaner way to do it:</p>\n\n<pre><code>public void GetBrowser()\n {\n\n ShellWindows m_IEFoundBrowsers = new ShellWindows();\n\n foreach (InternetExplorer Browser in m_IEFoundBrowsers)\n {\n webBrowser = (SHDocVw.WebBrowser) Browser;\n // do what you want ...\n }\n\n }\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I admit I know enough about COM and IE architecture only to be dangerous. I have a working C# .NET ActiveX control similar to this: ``` using System; using System.Runtime.InteropServices; using BrowseUI; using mshtml; using SHDocVw; using Microsoft.Win32; namespace CTI { public interface CTIActiveXInterface { [DispId(1)] string GetMsg(); } [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)] public class CTIActiveX : CTIActiveXInterface { /*** Where can I get a reference to SHDocVw.WebBrowser? *****/ SHDocVw.WebBrowser browser; public string GetMsg() { return "foo"; } } } ``` I registered and created a type library using regasm: ``` regasm CTIActiveX.dll /tlb:CTIActiveXNet.dll /codebase ``` And can successfully instantiate this in javascript: ``` var CTIAX = new ActiveXObject("CTI.CTIActiveX"); alert(CTIAX.GetMsg()); ``` How can I get a reference to the client site (browser window) within CTIActiveX? I have done this in a BHO by implementing IObjectWithSite, but I don't think this is the correct approach for an ActiveX control. If I implement any interface (I mean COM interface like IObjectWithSite) on CTIActiveX when I try to instantiate in Javascript I get an error that the object does not support automation.
First, your interface needs ComVisible(true) in order to be seen by the calling script (this is probably causing the error). Second, add a .NETreference in your project to "Microsoft.mshtml". This will import the COM interfaces for various IE-related things (windows, HTML documents, etc.) Then, you need to add a property of type IHtmlDocument2 to your interface: ``` IHtmlDocument2 Document { set; } ``` ...implement it in your class: ``` public IHtmlDocument2 Document { set { _doc = value;} } ``` ...call it from script ``` CTIAX.Document = document; ``` ...once you have stored a reference to the document, you can use it at will to get to the window, other frames, or any part of the HTML DOM that you wish.
72,057
<p>I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol.</p>
[ { "answer_id": 72272, "author": "Omer Zak", "author_id": 11886, "author_profile": "https://Stackoverflow.com/users/11886", "pm_score": 2, "selected": false, "text": "<p>The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol when running tests.</p>\n\n<pre>; Define functions for running Guile-written tests under the TAP protocol.\n; Copyright &#169; 2008 by Omer Zak\n; Released under the GNU LGPL 2.1 or (at your option) any later version.\n;;;\n;;; To invoke it:\n;;; (use-modules (guiletap))\n;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n(define-module (guiletap))\n(export plan)\n(export ok)\n(export bail_out)\n(export diag)\n(export is_ok)\n\n(use-modules (ice-9 format))\n\n; n is the number of tests.\n(define plan\n (lambda (n) (display (format \"1..~d~%\" n))))\n\n; n - test number\n; testdesc - test descriptor\n; res - result which is #f at failure, other at success.\n(define ok\n (lambda (n testdesc res)\n (if (not res)(display \"not \"))\n (display (format \"ok ~d - ~a~%\" n testdesc))))\n\n; testdesc - test descriptor\n(define bail_out\n (lambda (testdesc)\n (display (format \"Bail out! - ~a~%\" testdesc))))\n\n; diagmsg - diagnostic message\n(define diag\n (lambda (diagmsg)\n (display (format \"# ~a~%\" diagmsg))))\n\n; n - test number\n; testdesc - test descriptor\n; expres - expected test result\n; actres - actual test result\n(define is_ok\n (lambda (n testdesc expres actres)\n (ok n testdesc (equal? expres actres))))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; !!! TODO:\n; !!! To be implemented also:\n; plan_no_plan\n; plan_skip_all [REASON]\n;\n; is RESULT EXPECTED [NAME]\n; isnt RESULT EXPECTED [NAME]\n; like RESULT PATTERN [NAME]\n; unlike RESULT PATTERN [NAME]\n; pass [NAME]\n; fail [NAME]\n;\n; skip CONDITION [REASON] [NB_TESTS=1]\n; Specify TODO mode by setting $TODO:\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; End of guiletap.scm</pre>\n" }, { "answer_id": 21836368, "author": "Yawar", "author_id": 20371, "author_profile": "https://Stackoverflow.com/users/20371", "pm_score": 2, "selected": false, "text": "<p>There is also now <a href=\"https://github.com/yawaramin/ggspec\" rel=\"nofollow\">ggspec</a>, a Guile unit testing framework which can output results in (a subset of) TAP format. To do so, put all your test (Scheme) scripts in a project subdirectory named <code>spec</code> and run:</p>\n\n<pre><code>$ ggspec -f tap\n</code></pre>\n\n<p>Since ggspec is a full-fledged framework with setups, teardowns, and test skipping, there are more options. See the sample test file that comes with the project (<code>spec/lib-spec.scm</code>) for a good overview.</p>\n\n<p>Disclaimer: I wrote ggspec.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11886/" ]
I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol.
The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol when running tests. ``` ; Define functions for running Guile-written tests under the TAP protocol. ; Copyright © 2008 by Omer Zak ; Released under the GNU LGPL 2.1 or (at your option) any later version. ;;; ;;; To invoke it: ;;; (use-modules (guiletap)) ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-module (guiletap)) (export plan) (export ok) (export bail_out) (export diag) (export is_ok) (use-modules (ice-9 format)) ; n is the number of tests. (define plan (lambda (n) (display (format "1..~d~%" n)))) ; n - test number ; testdesc - test descriptor ; res - result which is #f at failure, other at success. (define ok (lambda (n testdesc res) (if (not res)(display "not ")) (display (format "ok ~d - ~a~%" n testdesc)))) ; testdesc - test descriptor (define bail_out (lambda (testdesc) (display (format "Bail out! - ~a~%" testdesc)))) ; diagmsg - diagnostic message (define diag (lambda (diagmsg) (display (format "# ~a~%" diagmsg)))) ; n - test number ; testdesc - test descriptor ; expres - expected test result ; actres - actual test result (define is_ok (lambda (n testdesc expres actres) (ok n testdesc (equal? expres actres)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; !!! TODO: ; !!! To be implemented also: ; plan_no_plan ; plan_skip_all [REASON] ; ; is RESULT EXPECTED [NAME] ; isnt RESULT EXPECTED [NAME] ; like RESULT PATTERN [NAME] ; unlike RESULT PATTERN [NAME] ; pass [NAME] ; fail [NAME] ; ; skip CONDITION [REASON] [NB_TESTS=1] ; Specify TODO mode by setting $TODO: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; End of guiletap.scm ```
72,070
<p>I'm executing stored procedures using SET FMTONLY ON, in order to emulate what our code generator does. However, it seems that the results are cached when executed like this, as I'm still getting a <em>Conversion failed</em> error from a proc that I have just dropped! This happens even when I execute the proc without SET FMTONLY ON.</p> <p>Can anyone please tell me what's going on here?</p>
[ { "answer_id": 72094, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>This sounds like a client-side error. Do you get the same message when running through SQL Management Studio?</p></li>\n<li><p>Have you confirmed that there isn't another procedure with the same name that's owned by a different schema/user?</p></li>\n</ol>\n" }, { "answer_id": 232380, "author": "Rick", "author_id": 14138, "author_profile": "https://Stackoverflow.com/users/14138", "pm_score": 2, "selected": true, "text": "<p>Some statements will still be executed, even with <strong><code>SET FMTONLY ON</code></strong>. You \"Conversion failed\" error could be from something as simple as a <code>set variable</code> statement in the stored proc. For example, this returns the metadata for the first query, but throws an exception when it runs the last statement:</p>\n\n<pre><code>SET FMTONLY on\n\nselect 1 as a\n\ndeclare @a int\nset @a = 'a'\n</code></pre>\n\n<p>As for running a dropped procedure, that's a new one to me. SQL Server uses the system tables to determine the object to execute, so it doesn't matter if the execution plan is cached for that object. If you drop it, it is deleted from the system tables, and should never be executable. Could you please query sysobjects (or sys.objects) just before you execute the procedure? I expect you'll find that you haven't dropped it.</p>\n" }, { "answer_id": 1145031, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>DDL statements are parsed, but ignored when run if SET FMTONLY ON has been executed on the connection. So if you drop a proc, table, etc when FMTONLY is ON, the statement is parsed, but the action is not executed.</p>\n\n<p>Try this to verify</p>\n\n<pre><code>SET FMTONLY OFF\n</code></pre>\n\n<p>--Create table to test on</p>\n\n<pre><code>CREATE TABLE TestTable (Column1 INT, Column2 INT)\n</code></pre>\n\n<p>--insert 1 record</p>\n\n<pre><code>INSERT INTO TestTable (Column1, Column2)\nVALUES (1,2)\n</code></pre>\n\n<p>--validate the record was inserted</p>\n\n<pre><code>SELECT * FROM TestTable\n</code></pre>\n\n<p>--now set format only to ON</p>\n\n<pre><code>SET FMTONLY ON\n</code></pre>\n\n<p>--columns are returned, but no data</p>\n\n<pre><code>SELECT * FROM TestTable\n</code></pre>\n\n<p>--perform DDL statement with FMTONLY ON</p>\n\n<pre><code>DROP TABLE TestTable\n</code></pre>\n\n<p>--Turn FMTONLY OFF again</p>\n\n<pre><code>SET FMTONLY OFF\n</code></pre>\n\n<p>--The table was dropped above, so this should not work</p>\n\n<pre><code>SELECT * FROM TestTable\n\nDROP TABLE TestTable\n\nSELECT * FROM TestTable\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I'm executing stored procedures using SET FMTONLY ON, in order to emulate what our code generator does. However, it seems that the results are cached when executed like this, as I'm still getting a *Conversion failed* error from a proc that I have just dropped! This happens even when I execute the proc without SET FMTONLY ON. Can anyone please tell me what's going on here?
Some statements will still be executed, even with **`SET FMTONLY ON`**. You "Conversion failed" error could be from something as simple as a `set variable` statement in the stored proc. For example, this returns the metadata for the first query, but throws an exception when it runs the last statement: ``` SET FMTONLY on select 1 as a declare @a int set @a = 'a' ``` As for running a dropped procedure, that's a new one to me. SQL Server uses the system tables to determine the object to execute, so it doesn't matter if the execution plan is cached for that object. If you drop it, it is deleted from the system tables, and should never be executable. Could you please query sysobjects (or sys.objects) just before you execute the procedure? I expect you'll find that you haven't dropped it.
72,090
<p>I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.</p> <p>I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609</p> <p><a href="https://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience">This</a> is the full script that I'm trying to modify, changing:</p> <pre><code>window.addEventListener ("load", doStuff, false); </code></pre> <p>to</p> <pre><code>window.addEventListener ("DOMContentLoaded", doStuff, false); </code></pre>
[ { "answer_id": 72245, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 6, "selected": true, "text": "<p>So I googled <a href=\"http://www.google.com/search?q=greasemonkey%20dom%20ready\" rel=\"noreferrer\">greasemonkey dom ready</a> and the <a href=\"http://www.sitepoint.com/article/beat-website-greasemonkey/\" rel=\"noreferrer\">first result</a> seemed to say that the greasemonkey script is actually running at \"DOM ready\" so you just need to remove the onload call and run the script straight away.</p>\n\n<p>I removed the <em><code>window.addEventListener (\"load\", function() {</code></em> and <em><code>}, false);</code></em> wrapping and it worked perfectly. It's <strong>much</strong> more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea.</p>\n" }, { "answer_id": 72295, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<p>GreaseMonkey scripts are themselves executed on DOMContentLoaded, so it's unnecessary to add a load event handler - just have your script do whatever it needs to to immediately.</p>\n\n<p><a href=\"http://wiki.greasespot.net/DOMContentLoaded\" rel=\"noreferrer\">http://wiki.greasespot.net/DOMContentLoaded</a></p>\n" }, { "answer_id": 72314, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "<p>@Sam: yeah, I was trying the same:</p>\n\n<pre><code>// ==UserScript==\n// @name Stack Overflow highlight viewed questions\n// @namespace *\n// @include http://stackoverflow.com/questions\n// @include http://stackoverflow.com/questions?*\n// @include http://stackoverflow.com/questions\n// @include http://stackoverflow.com/questions?*\n// @version 0.55 (DOM-Ready instead of onload)\n// ==/UserScript==\n\n(function() {\n\n // Customizable items\n // var fav_tags = [\"python\", \"database\", \"mysql\"]; // Your favorite tags\n const UNSEEN_BACK_COLOR = \"rgb(225,210,210)\"; // Backcolor for the question already seen\n const FAV_TAG_BACK_COLOR = \"rgb(210,210,225)\"; // Backcolor for the favorite tags\n\n // Internal to the DOM\n // const QUESTION_URL = \"http:\\/\\/stackoverflow.com\\/questions\\/([0-9]+)\\/\";\n const QUESTION_URL = \"http:\\/\\/stackoverflow.com\\/questions\\/([0-9]+)\\/\";\n const TAG_PREFIX = \"show questions tagged \";\n\n const SEEN_MARK = \"x\";\n //\n\n var seen_q = [];\n var seen_q_str = \"\";\n\n var seen_q_str = GM_getValue (\"seen_q\", \"\");\n var seen_q = seen_q_str.split(\"|\");\n\n var fav_tags_str = GM_getValue (\"fav_tags\", \"\")\n var fav_tags = fav_tags_str.split(\" \")\n\n var already_run = false;\n\n GM_registerMenuCommand (\"Set favorite tags\", askTags);\n\n // window.addEventListener (\"DOMContentLoaded\", doStuff, false);\n if (! doStuff()) {\n window.addEventListener (\"load\", doStuff, false);\n }\n\n function doStuff() {\n\n var elements = window.document.getElementsByTagName('A');\n\n if (! elements || already_run) {\n return false;\n } else {\n already_run = true;\n }\n\n GM_log (\"here\");\n\n for (elem = 0; elem &lt; elements.length; elem++) {\n if (elements[elem].href.match (QUESTION_URL)) {\n curr_q = RegExp.$1;\n\n // Already seen?\n if ((seen_q.length &lt; curr_q) || (seen_q [curr_q] != SEEN_MARK)) {\n elements[elem].style.backgroundColor = UNSEEN_BACK_COLOR;\n seen_q [curr_q] = SEEN_MARK;\n }\n\n // Is a favorite tag?\n node = elements[elem].parentNode.parentNode;\n for (tag = 0; tag &lt;= fav_tags.length; tag++) {\n if (node.innerHTML.match (\"'\" + fav_tags[tag] + \"'\")) {\n node.style.backgroundColor = FAV_TAG_BACK_COLOR;\n break;\n }\n }\n\n // return (0);\n }\n }\n\n seen_q_str = seen_q.join(\"|\");\n GM_setValue (\"seen_q\", seen_q_str);\n\n return true;\n }\n\n\n function askTags() {\n fav_tags_str = prompt(\"Favorite tags (separated by spaces)\", fav_tags_str);\n GM_setValue (\"fav_tags\", fav_tags_str)\n }\n\n})();\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires. I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609 [This](https://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience) is the full script that I'm trying to modify, changing: ``` window.addEventListener ("load", doStuff, false); ``` to ``` window.addEventListener ("DOMContentLoaded", doStuff, false); ```
So I googled [greasemonkey dom ready](http://www.google.com/search?q=greasemonkey%20dom%20ready) and the [first result](http://www.sitepoint.com/article/beat-website-greasemonkey/) seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away. I removed the *`window.addEventListener ("load", function() {`* and *`}, false);`* wrapping and it worked perfectly. It's **much** more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea.
72,098
<p>When using MediaWiki's markup language, the only thing that I hate is creating numbered lists. The only way I know to create a list is to do something like this:</p> <pre><code>#Item1 #Item2 </code></pre> <p>However, if I want to add spaces or some other text between those lines, the numbering gets lost. For example, the following will create text that has two number one items:</p> <pre><code>#Item1 Somestuff #Item2 </code></pre> <p>Is there any way around this, or should I just use bullet points instead? I noticed just now that the stackoverflow system does not allow numbering like this, you have to do it all manually.</p>
[ { "answer_id": 72140, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 5, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>#Item1\n#:Somestuff\n#Item2\n</code></pre>\n" }, { "answer_id": 72222, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 4, "selected": false, "text": "<p>There are a couple of options, but you can start an ordered list from an arbitrary number like this:</p>\n\n<pre>\n#Item1\n\nSomething\n\n&lt;ol start=\"2\"&gt;\n#Item2\n&lt;/ol&gt;\n</pre>\n\n<p>You can also use \"#:\" if you don't mind \"Something\" being indented a lot:</p>\n\n<pre>\n#Item1\n#:\n#: Something\n#:\n#Item2\n</pre>\n\n<p>There are quite a lot of options with lists, you can find more info on <a href=\"http://en.wikipedia.org/wiki/Help:List\" rel=\"noreferrer\">Wiki's Help Pages:List</a>.</p>\n\n<p><strong>update</strong></p>\n\n<p>Newer version work more like regular html markup the old syntax will now give you a double indent and will not adjust the start offset, but the following works well, even with the source/syntaxhighlight tag.</p>\n\n<pre>\n&lt;ol&gt;\n&lt;li&gt;Item1&lt;/li&gt;\nSomething\n&lt;/ol&gt;\n\n&lt;ol start=\"2\"&gt;\n&lt;li&gt;Item2&lt;/li&gt\n&lt;source lang=javascript&gt;\nvar a = 1;\n&lt;/source&gt;\n&lt;/ol&gt;\n</pre>\n\n<p>In short everything within the ol tag will have the same indentation and will not be numbered if it is outside a li tag. The following will now work and it mean you don't have to offset groups manually.</p>\n\n<pre>\n&lt;ol&gt;\n&lt;li&gt;Item1&lt;/li&gt;\nSomething\n&lt;li&gt;Item2&lt;/li&gt\n&lt;source lang=javascript&gt;\nvar a = 1;\n&lt;/source&gt;\n&lt;/ol&gt;\n</pre>\n" }, { "answer_id": 630617, "author": "Adrian Archer", "author_id": 65284, "author_profile": "https://Stackoverflow.com/users/65284", "pm_score": 2, "selected": false, "text": "<p>I'm using Mediawiki 1.13.3 and this works:</p>\n\n<pre><code>#Item1\nSomestuff\n&lt;ol start=\"2\"&gt;\n&lt;li&gt;Item2 &lt;/li&gt;\n&lt;/ol&gt;\n</code></pre>\n" }, { "answer_id": 1540899, "author": "josefwells", "author_id": 72935, "author_profile": "https://Stackoverflow.com/users/72935", "pm_score": 1, "selected": false, "text": "<p>You can do:</p>\n<pre><code># one\n# two&lt;br /&gt;spanning more lines&lt;br /&gt;doesn't break numbering\n# three\n## three point one\n## three point two\n</code></pre>\n<p>Regular old <code>&lt;br&gt;</code> works as well but probably pisses off someone.</p>\n<p>You can put additional HTML formatting in as well to do <code>&lt;pre&gt;</code> formatting and the like without breaking the numbering as well. This also works other list formats.</p>\n<p>From:\n<a href=\"http://www.mediawiki.org/wiki/Help:Formatting\" rel=\"nofollow noreferrer\">http://www.mediawiki.org/wiki/Help:Formatting</a></p>\n<p>edit: Also found that inside a <code>&lt;pre&gt;&lt;/pre&gt;</code> many of my old tricks don't work, but using <code>&amp;#10;</code> works as a newline, and allows multi-line blocks. The cost is that you jam all your lines on one line.</p>\n<pre><code># one\n#: &lt;pre&gt;foo&amp;#10;bar&lt;/pre&gt;\n</code></pre>\n" }, { "answer_id": 2422391, "author": "Sam", "author_id": 291148, "author_profile": "https://Stackoverflow.com/users/291148", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>The #: works, but you cannot create a\n section with spaces, so I would prefer\n the non-working option. Anyone knows a\n similar syntaxis that does the trick\n (start numbering at given value)?</p>\n</blockquote>\n\n<p>This response is probably a bit late, but I figure I'll add it in case anyone stumbles across this, as I have.\nYou can create a section with spaces by doing something like:</p>\n\n<pre>\n# Item 1\n#: \n#: \n# Item 2\n</pre>\n\n<p>This will appear as:</p>\n\n<ol>\n<li><p>Item 1</p></li>\n<li><p>Item 2</p></li>\n</ol>\n\n<p>Now, before you say this doesn't work, the trick is to add an ASCII no-break space after the #: rather than just simply hitting spacebar. You can add this by holding ALT on your keyboard and typing 0160. Doing this should add the usual Wiki paragraph formatting while preserving your numbering between #s.</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 5713294, "author": "Leon", "author_id": 204606, "author_profile": "https://Stackoverflow.com/users/204606", "pm_score": 2, "selected": false, "text": "<p>\"#:\" will not work with other tags like</p>\n\n<pre><code>&lt;source lang=javascript&gt;\n//...\n&lt;/source&gt;\n</code></pre>\n" }, { "answer_id": 7981273, "author": "Yap Chin Hoong", "author_id": 1025742, "author_profile": "https://Stackoverflow.com/users/1025742", "pm_score": 4, "selected": false, "text": "<p>I use <code>&lt;ol&gt;&lt;/ol&gt;</code> and <code>&lt;li&gt;&lt;/li&gt;</code> to embed the <code>&lt;pre&gt;&lt;/pre&gt;</code> code formatting portions. Works great for me! :-)</p>\n" }, { "answer_id": 11763416, "author": "Dirk", "author_id": 451093, "author_profile": "https://Stackoverflow.com/users/451093", "pm_score": 1, "selected": false, "text": "<p>From the <a href=\"http://en.wikipedia.org/wiki/Help%3aList\" rel=\"nofollow\">Wiki Help Page</a> I was able to get the numbering in a list to stay consitant using <code>&lt;p&gt;</code> and <code>&lt;pre&gt;</code>:</p>\n\n<pre><code># Item 1\n# Item 2 &lt;p&gt;&lt;pre&gt;Item 2 Pre Stuff&lt;/pre&gt;&lt;/p&gt;\n# Item 3\n</code></pre>\n\n<p>Would generate </p>\n\n<pre><code>1. Item 1\n2. Item 2\n [ Item 2 Pre Stuff ]\n3. Item 3\n</code></pre>\n" }, { "answer_id": 16310778, "author": "Kory Lovre", "author_id": 1721315, "author_profile": "https://Stackoverflow.com/users/1721315", "pm_score": 2, "selected": false, "text": "<p>And for cases where you want to have some block text within your numbered wiki list try this</p>\n\n<pre><code># one\n#:&lt;pre&gt;\n#:some stuff\n#:some more stuff&lt;/pre&gt;\n# two\n</code></pre>\n\n<p>Which produces:</p>\n\n<p><li>1. one<pre>\n some stuff\n some more stuff</pre>\n<li>2. two</p>\n" }, { "answer_id": 19020003, "author": "Peter", "author_id": 160054, "author_profile": "https://Stackoverflow.com/users/160054", "pm_score": 1, "selected": false, "text": "<p>Following the link to <a href=\"http://en.wikipedia.org/wiki/Help%3aList\" rel=\"nofollow\">Wiki Help,</a> I found an example that meets what I think are the implied requirements</p>\n\n<ol>\n<li>The list needs to keep numbering</li>\n<li>Sometimes the \"Somestuff\" should be on it's own line in the source</li>\n</ol>\n\n<p>To get (1) there are a few solutions proposed. Bug one way is to use paragraph delimiters around the extra \"somestuff\".</p>\n\n<p>Example 1:</p>\n\n<pre>\n# Paragraph 1.&lt;p&gt;Paragraph 2.&lt;/p&gt;&lt;p&gt;Paragraph 3.&lt;/p&gt;\n# Second item.\n</pre>\n\n<p>To meet (2), you use paragraph marking in combination with commenting out the new lines (with &lt;!-- <i>newline</i>--&gt;).</p>\n\n<p>Example 2:</p>\n\n<pre>\n# Paragraph 1.&lt!--\n --&gt;&lt;p&gt;Paragraph 2.&lt;/p&gt;&lt;!--\n --&gt;&lt;p&gt;Paragraph 3.&lt;/p&gt;\n# Second item.\n</pre>\n\n<p>Both examples display as</p>\n\n<p>Result:</p>\n\n<pre>\n\n 1. Paragraph 1.\n Paragraph 2.\n Paragraph 3.\n 2. Second item\n</pre>\n\n<p>Note that the comment eats all of the white space between the end of one element and the start of the next, which seems to be standard practice, and makes sense if you're trying to have whitespace without the \"wiki effects\" of the white space.</p>\n" }, { "answer_id": 49478270, "author": "user1930469", "author_id": 1930469, "author_profile": "https://Stackoverflow.com/users/1930469", "pm_score": 1, "selected": false, "text": "<p>Extension:ComplexList</p>\n\n<p><a href=\"https://www.mediawiki.org/w/index.php?oldid=2126533\" rel=\"nofollow noreferrer\">https://www.mediawiki.org/w/index.php?oldid=2126533</a></p>\n\n<p>was put together but not maintained (for lack of time). It works with 1.26.2 of MediaWiki.</p>\n\n<p>For example.</p>\n\n<pre>&lt;cl>\n1. list item A1\n\n* list item A2\n\ncontinuing list item A2\n\nfurther continuing list item A2\n\n* list item A3\n&lt;/cl></pre>\n\n<p>becomes</p>\n\n<ol>\n<li>list item A1</li>\n<li>list item A2<br/>continuing list item A2<br/>further continuing list item A2</li>\n<li>list item A3</li>\n</ol>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using MediaWiki's markup language, the only thing that I hate is creating numbered lists. The only way I know to create a list is to do something like this: ``` #Item1 #Item2 ``` However, if I want to add spaces or some other text between those lines, the numbering gets lost. For example, the following will create text that has two number one items: ``` #Item1 Somestuff #Item2 ``` Is there any way around this, or should I just use bullet points instead? I noticed just now that the stackoverflow system does not allow numbering like this, you have to do it all manually.
Like this: ``` #Item1 #:Somestuff #Item2 ```
72,103
<p>I'm using a winforms webbrowser control to display some content in a windows forms app. I'm using the DocumentText property to write the generated HTML. That part is working spectacularly. Now I want to use some images in the markup. (I also would prefer to use linked CSS and JavaScript, however, that can be worked around by just embedding it.)</p> <p>I have been googling over the course of several days and can't seem to find an answer to the title question. </p> <p>I tried using a relative reference: the app exe is in the bin\debug. The images live in the "Images" directory at the root of the project. I've set the images to be copied to the output directory on compile, so they end up in bin\debug\Images*. So I then use a reference like this "Images..." thinking it will be relative to the exe. However, when I look at the image properties in the embedded browser window, I see the image URL to be "about:blankImages/*". Everything seems to be relative to "about:blank" when HTML is written to the control. Lacking a location context, I can't figure out what to use for a relative file resource reference.</p> <p>I poked around the properties of the control to see if there is a way to set something to fix this. I created a blank html page, and pointed the browser at it using the "Navigate()" method, using the full local path to the file. This worked fine with the browser reporting the local "file:///..." path to the blank page. Then I again wrote to the browser, this time using Document.Write(). Again, the browser now reports "about:blank" as the URL.</p> <p>Short of writing the dynamic HTML results to a real file, is there no other way to reference a file resource?</p> <p>I am going to try one last thing: constructing absolute file paths to the images and writing those to the HTML. My HTML is being generated using an XSL transform of a serialized object's XML so I'll need to play with some XSL parameters which will take a little extra time as I'm not that familiar with them.</p>
[ { "answer_id": 72339, "author": "Ken Wootton", "author_id": 7357, "author_profile": "https://Stackoverflow.com/users/7357", "pm_score": 4, "selected": true, "text": "<p>Here's what we do, although I should mention that we use a custom web browser to remove such things as the ability to right-click and see the good old IE context menu:</p>\n\n<pre><code>public class HtmlFormatter\n{\n /// &lt;summary&gt;\n /// Indicator that this is a URI referencing the local\n /// file path.\n /// &lt;/summary&gt;\n public static readonly string FILE_URL_PREFIX = \n \"file://\";\n\n /// &lt;summary&gt;\n /// The path separator for HTML paths.\n /// &lt;/summary&gt;\n public const string PATH_SEPARATOR = \"/\";\n}\n\n\n// We need to add the proper paths to each image source\n// designation that match where they are being placed on disk.\nString html = HtmlFormatter.ReplaceImagePath(\n myHtml, \n HtmlFormatter.FILE_URL_PREFIX + ApplicationPath.FullAppPath + \n HtmlFormatter.PATH_SEPARATOR);\n</code></pre>\n\n<p>Basically, you need to have an image path that has a file URI, e.g. </p>\n\n<pre><code>&lt;img src=\"file://ApplicationPath/images/myImage.gif\"&gt;\n</code></pre>\n" }, { "answer_id": 72657, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 1, "selected": false, "text": "<p>I got it figured out.</p>\n\n<p>I just pass the complete resolved url of the exe directory to the XSL transform that contains the HTML output with image tags:</p>\n\n<pre><code>XsltArgumentList lstArgs = new XsltArgumentList();\nlstArgs.AddParam(\"absoluteRoot\", string.Empty, Path.GetFullPath(\".\"));\n</code></pre>\n\n<p>Then I just prefixed all the images with the parameter value:</p>\n\n<pre><code>&lt;img src=\"{$absoluteRoot}/Images/SilkIcons/comment_add.gif\" align=\"middle\" border=\"0\" /&gt;\n</code></pre>\n" }, { "answer_id": 208280, "author": "Peter", "author_id": 5496, "author_profile": "https://Stackoverflow.com/users/5496", "pm_score": 0, "selected": false, "text": "<p>I ended up using something that's basically the same as what Ken suggested. However, instead of manually appending the file prefix, I used the UriBuilder class to build the complete URI with the \"file\" protocol.</p>\n\n<p>This also solved a subsequent problem when we tested the app in a more realistic location, Program Files. The spaces was encoded, but the OS couldn't deal with the encoded characters when the file was referenced using a standard system path (i.e. \"C:\\Program%20Files...\"). Using the true URI value (file:///C:/Program Files/...) worked.</p>\n" }, { "answer_id": 273840, "author": "Roark Fan", "author_id": 25362, "author_profile": "https://Stackoverflow.com/users/25362", "pm_score": 0, "selected": false, "text": "<p>Alternatively, keep your normal style relative links, drop the HTML transforming code and instead embed a C# web server like <a href=\"http://www.codeplex.com/webserver\" rel=\"nofollow noreferrer\">this</a> in your exe, then point your WebControl at your internal URL, like localhost:8199/myapp/</p>\n" }, { "answer_id": 886989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Ken's code was missing a few things that it needed to work. I've revised it, and created a new method that should automate things a little.</p>\n\n<p>Just call the static method as so:</p>\n\n<pre><code>html = HtmlFormatter.ReplaceImagePathAuto(html);\n</code></pre>\n\n<p>and all links in the html that match file://ApplicationPath/ will be swapped with the current working directory. If you want to specify an alternate location, the original static method is included (plus the bits it was missing).</p>\n\n<pre><code>public class HtmlFormatter\n{\n\n public static readonly string FILE_URL_PREFIX = \"file://\";\n public static readonly string PATH_SEPARATOR = \"/\";\n public static String ReplaceImagePath(String html, String path)\n {\n return html.Replace(\"file://ApplicationPath/\", path);\n }\n /// &lt;summary&gt;\n /// Replaces URLs matching file://ApplicationPath/... with Executable Path\n /// &lt;/summary&gt;\n /// &lt;param name=\"html\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static String ReplaceImagePathAuto(String html)\n {\n String executableName = System.Windows.Forms.Application.ExecutablePath;\n System.IO.FileInfo executableFileInfo = new System.IO.FileInfo(executableName);\n String executableDirectoryName = executableFileInfo.DirectoryName;\n String replaceWith = HtmlFormatter.FILE_URL_PREFIX\n + executableDirectoryName\n + HtmlFormatter.PATH_SEPARATOR;\n\n return ReplaceImagePath(html, replaceWith);\n }\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5496/" ]
I'm using a winforms webbrowser control to display some content in a windows forms app. I'm using the DocumentText property to write the generated HTML. That part is working spectacularly. Now I want to use some images in the markup. (I also would prefer to use linked CSS and JavaScript, however, that can be worked around by just embedding it.) I have been googling over the course of several days and can't seem to find an answer to the title question. I tried using a relative reference: the app exe is in the bin\debug. The images live in the "Images" directory at the root of the project. I've set the images to be copied to the output directory on compile, so they end up in bin\debug\Images\*. So I then use a reference like this "Images..." thinking it will be relative to the exe. However, when I look at the image properties in the embedded browser window, I see the image URL to be "about:blankImages/\*". Everything seems to be relative to "about:blank" when HTML is written to the control. Lacking a location context, I can't figure out what to use for a relative file resource reference. I poked around the properties of the control to see if there is a way to set something to fix this. I created a blank html page, and pointed the browser at it using the "Navigate()" method, using the full local path to the file. This worked fine with the browser reporting the local "file:///..." path to the blank page. Then I again wrote to the browser, this time using Document.Write(). Again, the browser now reports "about:blank" as the URL. Short of writing the dynamic HTML results to a real file, is there no other way to reference a file resource? I am going to try one last thing: constructing absolute file paths to the images and writing those to the HTML. My HTML is being generated using an XSL transform of a serialized object's XML so I'll need to play with some XSL parameters which will take a little extra time as I'm not that familiar with them.
Here's what we do, although I should mention that we use a custom web browser to remove such things as the ability to right-click and see the good old IE context menu: ``` public class HtmlFormatter { /// <summary> /// Indicator that this is a URI referencing the local /// file path. /// </summary> public static readonly string FILE_URL_PREFIX = "file://"; /// <summary> /// The path separator for HTML paths. /// </summary> public const string PATH_SEPARATOR = "/"; } // We need to add the proper paths to each image source // designation that match where they are being placed on disk. String html = HtmlFormatter.ReplaceImagePath( myHtml, HtmlFormatter.FILE_URL_PREFIX + ApplicationPath.FullAppPath + HtmlFormatter.PATH_SEPARATOR); ``` Basically, you need to have an image path that has a file URI, e.g. ``` <img src="file://ApplicationPath/images/myImage.gif"> ```
72,116
<p>I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code:</p> <p>GlobalVar.property = 11;</p> <p>(assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?</p>
[ { "answer_id": 72147, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 1, "selected": false, "text": "<p>I would expect the result to be undetermined. As in it would vary from compiler to complier, langauge to language and OS to OS etc. So no, it is not safe</p>\n\n<p>WHy would you want to do this though - adding in a line to obtain a mutex lock is only one or two lines of code (in most languages), and would remove any possibility of problem. If this is going to be two expensive then you need to find an alternate way of solving the problem</p>\n" }, { "answer_id": 72215, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 2, "selected": false, "text": "<p>It depends on the work actually done by that statement. There can still be some cases where Something Bad happens - for example, if a C++ class has overloaded the = operator, and does anything nontrivial within that statement.</p>\n\n<p>I have accidentally written code that did something like this with POD types (builtin primitive types), and it worked fine -- however, it's definitely not good practice, and I'm not confident that it's dependable.</p>\n\n<p>Why not just lock the memory around this variable when you use it? In fact, if you somehow \"know\" this is the only write statement that can occur at some point in your code, why not just use the value 11 directly, instead of writing it to a shared variable?\n(<strong>edit:</strong> I guess it's better to use a constant name instead of the <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic number</a> 11 directly in the code, btw.)</p>\n\n<p>If you're using this to figure out when at least one thread has reached this statement, you could use a semaphore that starts at 1, and is decremented by the first thread that hits it.</p>\n" }, { "answer_id": 72346, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "<p>In General, this is not considered a safe thing to do unless your system provides for atomic operation (operations that are guaranteed to be executed in a single cycle).\nThe reason is that while the \"C\" statement looks simple, often there are a number of underlying assembly operations taking place.</p>\n\n<p>Depending on your OS, there are a few things you could do: </p>\n\n<ul>\n<li>Take a mutual exclusion semaphore (mutex) to protect access </li>\n<li>in some OS, you can temporarily disable preemption, which guarantees your thread will not swap out.</li>\n<li>Some OS provide a writer or reader semaphore which is more performant than a plain old mutex.</li>\n</ul>\n" }, { "answer_id": 72356, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": -1, "selected": false, "text": "<p>If the operation is atomic, you <em>should</em> be able to get by just fine. But I wouldn't do that in practice. It is better just to acquire a lock on the object and write the value.</p>\n" }, { "answer_id": 72571, "author": "Torne", "author_id": 12345, "author_profile": "https://Stackoverflow.com/users/12345", "pm_score": 3, "selected": false, "text": "<p>The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually <strong>read</strong> this value back again?</p>\n\n<p>The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the <strong>use</strong> of the variable, so here's a trivialish example in neutral C-like syntax:</p>\n\n<pre><code>int x = 0, y = 0;\n\n//thread A does:\nx = 1;\ny = 2;\nif (y == 2)\n print(x);\n\n//thread B does, at the same time:\nif (y == 2)\n print(x);\n</code></pre>\n\n<p>Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order.</p>\n\n<p>This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors.</p>\n\n<p>If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not.</p>\n" }, { "answer_id": 111016, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": -1, "selected": false, "text": "<p>Assuming that property will never be assigned anything other than 11, then I don't see a reason for assigment in the first place. Just make it a constant then.</p>\n\n<p>Assigment only makes sense when you intend to change the value <em>unless</em> the act of assigment itself has other side effects - like volatile writes have memory visibility side-effects in Java. And if you change state shared between multiple threads, then you need to synchronize or otherwise \"handle\" the problem of concurrency.</p>\n\n<p>When you assign a value, without proper synchronization, to some state shared between multiple threads, then there's no guarantees for when the other threads will see that change. And no visibility guarantees means that it it possible that the other threads will <em>never</em> see the assignt.</p>\n\n<p>Compilers, JITs, CPU caches. They're all trying to make your code run as fast as possible, and if you don't make any explicit requirements for memory visibility, then they will take advantage of that. If not on your machine, then somebody elses.</p>\n" }, { "answer_id": 111469, "author": "teeks99", "author_id": 17949, "author_profile": "https://Stackoverflow.com/users/17949", "pm_score": 1, "selected": false, "text": "<p>Here's my take on the question.</p>\n\n<p>You have two or more threads running that write to a variable...like a status flag or something, where you only want to know if one or more of them was true. Then in another part of the code (after the threads complete) you want to check and see if at least on thread set that status... for example</p>\n\n<pre><code>bool flag = false\nthreadContainer tc\nthreadInputs inputs\n\ncheck(input)\n{\n ...do stuff to input\n if(success)\n flag = true\n}\n\nstart multiple threads\nforeach(i in inputs) \n t = startthread(check, i)\n tc.add(t) // Keep track of all the threads started\n\nforeach(t in tc)\n t.join( ) // Wait until each thread is done\n\nif(flag)\n print \"One of the threads were successful\"\nelse\n print \"None of the threads were successful\"\n</code></pre>\n\n<p>I believe the above code would be OK, assuming you're fine with not knowing which thread set the status to true, and you can wait for all the multi-threaded stuff to finish before reading that flag. I could be wrong though. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code: GlobalVar.property = 11; (assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?
The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually **read** this value back again? The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the **use** of the variable, so here's a trivialish example in neutral C-like syntax: ``` int x = 0, y = 0; //thread A does: x = 1; y = 2; if (y == 2) print(x); //thread B does, at the same time: if (y == 2) print(x); ``` Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order. This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors. If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not.
72,121
<p>Let me use the following example to explain my question:</p> <pre class="lang-csharp prettyprint-override"><code>public string ExampleFunction(string Variable) { return something; } string WhatIsMyName = &quot;Hello World&quot;; string Hello = ExampleFunction(WhatIsMyName); </code></pre> <p>When I pass the variable <code>WhatIsMyName</code> to the <code>ExampleFunction</code>, I want to be able to get a string of the <em>original</em> variable's name. Perhaps something like:</p> <pre class="lang-csharp prettyprint-override"><code>Variable.OriginalName.ToString() // == &quot;WhatIsMyName&quot; </code></pre> <p>Is there any way to do this?</p>
[ { "answer_id": 72139, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": true, "text": "<p><strong>No.</strong> I don't think so.</p>\n<p>The variable name that you use is for your convenience and readability. The compiler doesn't need it &amp; just chucks it out if I'm not mistaken.</p>\n<p>If it helps, you could define a new class called <code>NamedParameter</code> with attributes <code>Name</code> and <code>Param</code>. You then pass this object around as parameters.</p>\n" }, { "answer_id": 72145, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<p>What you want isn't possible directly but you can use Expressions in C# 3.0:</p>\n\n<pre><code>public void ExampleFunction(Expression&lt;Func&lt;string, string&gt;&gt; f) {\n Console.WriteLine((f.Body as MemberExpression).Member.Name);\n}\n\nExampleFunction(x =&gt; WhatIsMyName);\n</code></pre>\n\n<p>Note that this relies on unspecified behaviour and while it does work in Microsoft’s current C# and VB compilers, <strong>and</strong> in Mono’s C# compiler, there’s no guarantee that this won’t stop working in future versions.</p>\n" }, { "answer_id": 72150, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>The short answer is no ... unless you are really really motivated.</p>\n\n<p>The only way to do this would be via reflection and stack walking. You would have to get a stack frame, work out whereabouts in the calling function you where invoked from and then using the CodeDOM try to find the right part of the tree to see what the expression was.</p>\n\n<p>For example, what if the invocation was ExampleFunction(\"a\" + \"b\")?</p>\n" }, { "answer_id": 72155, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "<p>No. A reference to your string variable gets passed to the funcion--there isn't any inherent metadeta about it included. Even reflection wouldn't get you out of the woods here--working backwards from a single reference type doesn't get you enough info to do what you need to do. </p>\n\n<p>Better go back to the drawing board on this one!</p>\n\n<p>rp</p>\n" }, { "answer_id": 72186, "author": "Adam Vigh", "author_id": 1613872, "author_profile": "https://Stackoverflow.com/users/1613872", "pm_score": 0, "selected": false, "text": "<p>You could use reflection to get all the properties of an object, than loop through it, and get the value of the property where the name (of the property) matches the passed in parameter.</p>\n" }, { "answer_id": 72187, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 0, "selected": false, "text": "<p>Well had a bit of look. <em>of course</em> you can't use any Type information. \nAlso, the name of a local variable is not available at runtime\nbecause their names are not compiled into the assembly's metadata.</p>\n" }, { "answer_id": 72194, "author": "Nate Kohari", "author_id": 1282, "author_profile": "https://Stackoverflow.com/users/1282", "pm_score": 2, "selected": false, "text": "<p>No, but whenever you find yourself doing extremely complex things like this, you might want to re-think your solution. Remember that code should be easier to read than it was to write.</p>\n" }, { "answer_id": 72197, "author": "kevin42", "author_id": 10705, "author_profile": "https://Stackoverflow.com/users/10705", "pm_score": 2, "selected": false, "text": "<p>System.Environment.StackTrace will give you a string that includes the current call stack. You could parse that to get the information, which includes the variable names for each call. </p>\n" }, { "answer_id": 72467, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 1, "selected": false, "text": "<p>Thanks for all the responses. I guess I'll just have to go with what I'm doing now.</p>\n\n<p>For those who wanted to know why I asked the above question. I have the following function:</p>\n\n<pre><code>string sMessages(ArrayList aMessages, String sType) {\n string sReturn = String.Empty;\n if (aMessages.Count &gt; 0) {\n sReturn += \"&lt;p class=\\\"\" + sType + \"\\\"&gt;\";\n for (int i = 0; i &lt; aMessages.Count; i++) {\n sReturn += aMessages[i] + \"&lt;br /&gt;\";\n }\n sReturn += \"&lt;/p&gt;\";\n }\n return sReturn;\n}\n</code></pre>\n\n<p>I send it an array of error messages and a css class which is then returned as a string for a webpage.</p>\n\n<p>Every time I call this function, I have to define sType. Something like:</p>\n\n<pre><code>output += sMessages(aErrors, \"errors\");\n</code></pre>\n\n<p>As you can see, my variables is called aErrors and my css class is called errors. I was hoping my cold could figure out what class to use based on the variable name I sent it.</p>\n\n<p>Again, thanks for all the responses.</p>\n" }, { "answer_id": 72706, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>GateKiller, what's wrong with my workaround? You could rewrite your function trivially to use it (I've taken the liberty to improve the function on the fly):</p>\n\n<pre><code>static string sMessages(Expression&lt;Func&lt;List&lt;string&gt;&gt;&gt; aMessages) {\n var messages = aMessages.Compile()();\n\n if (messages.Count == 0) {\n return \"\";\n }\n\n StringBuilder ret = new StringBuilder();\n string sType = ((MemberExpression)aMessages.Body).Member.Name;\n\n ret.AppendFormat(\"&lt;p class=\\\"{0}\\\"&gt;\", sType);\n foreach (string msg in messages) {\n ret.Append(msg);\n ret.Append(\"&lt;br /&gt;\");\n }\n ret.Append(\"&lt;/p&gt;\");\n return ret.ToString();\n}\n</code></pre>\n\n<p>Call it like this:</p>\n\n<pre><code>var errors = new List&lt;string&gt;() { \"Hi\", \"foo\" };\nvar ret = sMessages(() =&gt; errors);\n</code></pre>\n" }, { "answer_id": 365413, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 5, "selected": false, "text": "<pre><code>static void Main(string[] args)\n{\n Console.WriteLine(\"Name is '{0}'\", GetName(new {args}));\n Console.ReadLine();\n}\n\nstatic string GetName&lt;T&gt;(T item) where T : class\n{\n var properties = typeof(T).GetProperties();\n Enforce.That(properties.Length == 1);\n return properties[0].Name;\n}\n</code></pre>\n\n<p>More details are in <a href=\"http://web.archive.org/web/20130124234247/http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html\" rel=\"noreferrer\">this blog post</a>.</p>\n" }, { "answer_id": 14671261, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 4, "selected": false, "text": "<p>Three ways:</p>\n\n<p>1) Something without reflection at all:</p>\n\n<pre><code>GetParameterName1(new { variable });\n\npublic static string GetParameterName1&lt;T&gt;(T item) where T : class\n{\n if (item == null)\n return string.Empty;\n\n return item.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();\n}\n</code></pre>\n\n<p>2) Uses reflection, but this is way faster than other two.</p>\n\n<pre><code>GetParameterName2(new { variable });\n\npublic static string GetParameterName2&lt;T&gt;(T item) where T : class\n{\n if (item == null)\n return string.Empty;\n\n return typeof(T).GetProperties()[0].Name;\n}\n</code></pre>\n\n<p>3) The slowest of all, don't use.</p>\n\n<pre><code>GetParameterName3(() =&gt; variable);\n\npublic static string GetParameterName3&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expr)\n{\n if (expr == null)\n return string.Empty;\n\n return ((MemberExpression)expr.Body).Member.Name;\n}\n</code></pre>\n\n<p>To get a combo parameter name and value, you can extend these methods. Of course its easy to get value if you pass the parameter separately as another argument, but that's inelegant. Instead:</p>\n\n<p>1)</p>\n\n<pre><code>public static string GetParameterInfo1&lt;T&gt;(T item) where T : class\n{\n if (item == null)\n return string.Empty;\n\n var param = item.ToString().TrimStart('{').TrimEnd('}').Split('=');\n return \"Parameter: '\" + param[0].Trim() +\n \"' = \" + param[1].Trim();\n}\n</code></pre>\n\n<p>2)</p>\n\n<pre><code>public static string GetParameterInfo2&lt;T&gt;(T item) where T : class\n{\n if (item == null)\n return string.Empty;\n\n var param = typeof(T).GetProperties()[0];\n return \"Parameter: '\" + param.Name +\n \"' = \" + param.GetValue(item, null);\n}\n</code></pre>\n\n<p>3)</p>\n\n<pre><code>public static string GetParameterInfo3&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expr)\n{\n if (expr == null)\n return string.Empty;\n\n var param = (MemberExpression)expr.Body;\n return \"Parameter: '\" + param.Member.Name +\n \"' = \" + ((FieldInfo)param.Member).GetValue(((ConstantExpression)param.Expression).Value);\n}\n</code></pre>\n\n<p>1 and 2 are of comparable speed now, 3 is again sluggish.</p>\n" }, { "answer_id": 19835965, "author": "Dipon Roy", "author_id": 2948523, "author_profile": "https://Stackoverflow.com/users/2948523", "pm_score": 2, "selected": false, "text": "<p>Well Try this Utility class,</p>\n\n<pre><code>public static class Utility\n{\n public static Tuple&lt;string, TSource&gt; GetNameAndValue&lt;TSource&gt;(Expression&lt;Func&lt;TSource&gt;&gt; sourceExpression)\n {\n Tuple&lt;String, TSource&gt; result = null;\n Type type = typeof (TSource);\n Func&lt;MemberExpression, Tuple&lt;String, TSource&gt;&gt; process = delegate(MemberExpression memberExpression)\n {\n ConstantExpression constantExpression = (ConstantExpression)memberExpression.Expression;\n var name = memberExpression.Member.Name;\n var value = ((FieldInfo)memberExpression.Member).GetValue(constantExpression.Value);\n return new Tuple&lt;string, TSource&gt;(name, (TSource) value);\n };\n\n Expression exception = sourceExpression.Body;\n if (exception is MemberExpression)\n {\n result = process((MemberExpression)sourceExpression.Body);\n }\n else if (exception is UnaryExpression)\n {\n UnaryExpression unaryExpression = (UnaryExpression)sourceExpression.Body;\n result = process((MemberExpression)unaryExpression.Operand);\n }\n else\n {\n throw new Exception(\"Expression type unknown.\");\n }\n\n return result;\n }\n\n\n}\n</code></pre>\n\n<p>And User It Like</p>\n\n<pre><code> /*ToDo : Test Result*/\n static void Main(string[] args)\n {\n /*Test : primivit types*/\n long maxNumber = 123123;\n Tuple&lt;string, long&gt; longVariable = Utility.GetNameAndValue(() =&gt; maxNumber);\n string longVariableName = longVariable.Item1;\n long longVariableValue = longVariable.Item2;\n\n /*Test : user define types*/\n Person aPerson = new Person() { Id = \"123\", Name = \"Roy\" };\n Tuple&lt;string, Person&gt; personVariable = Utility.GetNameAndValue(() =&gt; aPerson);\n string personVariableName = personVariable.Item1;\n Person personVariableValue = personVariable.Item2;\n\n /*Test : anonymous types*/\n var ann = new { Id = \"123\", Name = \"Roy\" };\n var annVariable = Utility.GetNameAndValue(() =&gt; ann);\n string annVariableName = annVariable.Item1;\n var annVariableValue = annVariable.Item2;\n\n /*Test : Enum tyoes*/\n Active isActive = Active.Yes;\n Tuple&lt;string, Active&gt; isActiveVariable = Utility.GetNameAndValue(() =&gt; isActive);\n string isActiveVariableName = isActiveVariable.Item1;\n Active isActiveVariableValue = isActiveVariable.Item2;\n }\n</code></pre>\n" }, { "answer_id": 21219225, "author": "blooop", "author_id": 951520, "author_profile": "https://Stackoverflow.com/users/951520", "pm_score": 4, "selected": false, "text": "<p><strong>Yes!</strong> It is possible. I have been looking for a solution to this for a long time and have finally come up with a hack that solves it (it's a bit nasty). I would not recommend using this as part of your program and I only think it works in debug mode. For me this doesn't matter as I only use it as a debugging tool in my console class so I can do:</p>\n\n<pre><code>int testVar = 1;\nbool testBoolVar = True;\nmyConsole.Writeline(testVar);\nmyConsole.Writeline(testBoolVar);\n</code></pre>\n\n<p>the output to the console would be:</p>\n\n<pre><code>testVar: 1\ntestBoolVar: True\n</code></pre>\n\n<p>Here is the function I use to do that (not including the wrapping code for my console class.</p>\n\n<pre><code> public Dictionary&lt;string, string&gt; nameOfAlreadyAcessed = new Dictionary&lt;string, string&gt;();\n public string nameOf(object obj, int level = 1)\n {\n StackFrame stackFrame = new StackTrace(true).GetFrame(level);\n string fileName = stackFrame.GetFileName();\n int lineNumber = stackFrame.GetFileLineNumber();\n string uniqueId = fileName + lineNumber;\n if (nameOfAlreadyAcessed.ContainsKey(uniqueId))\n return nameOfAlreadyAcessed[uniqueId];\n else\n {\n System.IO.StreamReader file = new System.IO.StreamReader(fileName);\n for (int i = 0; i &lt; lineNumber - 1; i++)\n file.ReadLine();\n string varName = file.ReadLine().Split(new char[] { '(', ')' })[1];\n nameOfAlreadyAcessed.Add(uniqueId, varName);\n return varName;\n }\n }\n</code></pre>\n" }, { "answer_id": 24078293, "author": "kernowcode", "author_id": 2088673, "author_profile": "https://Stackoverflow.com/users/2088673", "pm_score": 2, "selected": false, "text": "<p>Do this</p>\n\n<pre><code>var myVariable = 123;\nmyVariable.Named(() =&gt; myVariable);\nvar name = myVariable.Name();\n// use name how you like\n</code></pre>\n\n<p>or naming in code by hand</p>\n\n<pre><code>var myVariable = 123.Named(\"my variable\");\nvar name = myVariable.Name();\n</code></pre>\n\n<p>using this class</p>\n\n<pre><code>public static class ObjectInstanceExtensions\n{\n private static Dictionary&lt;object, string&gt; namedInstances = new Dictionary&lt;object, string&gt;();\n\n public static void Named&lt;T&gt;(this T instance, Expression&lt;Func&lt;T&gt;&gt; expressionContainingOnlyYourInstance)\n {\n var name = ((MemberExpression)expressionContainingOnlyYourInstance.Body).Member.Name;\n instance.Named(name); \n }\n\n public static T Named&lt;T&gt;(this T instance, string named)\n {\n if (namedInstances.ContainsKey(instance)) namedInstances[instance] = named;\n else namedInstances.Add(instance, named);\n return instance;\n } \n\n public static string Name&lt;T&gt;(this T instance)\n {\n if (namedInstances.ContainsKey(instance)) return namedInstances[instance];\n throw new NotImplementedException(\"object has not been named\");\n } \n}\n</code></pre>\n\n<p>Code tested and most elegant I can come up with.</p>\n" }, { "answer_id": 32314158, "author": "johnny 5", "author_id": 1938988, "author_profile": "https://Stackoverflow.com/users/1938988", "pm_score": 5, "selected": false, "text": "<p>This isn't exactly possible, the way you would want. C# 6.0 they Introduce the nameof Operator which should help improve and simplify the code. The name of operator resolves the name of the variable passed into it.</p>\n<p>Usage for your case would look like this:</p>\n<pre><code>public string ExampleFunction(string variableName) {\n //Construct your log statement using c# 6.0 string interpolation\n return $&quot;Error occurred in {variableName}&quot;;\n}\n\nstring WhatIsMyName = &quot;Hello World&quot;;\nstring Hello = ExampleFunction(nameof(WhatIsMyName));\n</code></pre>\n<p>A major benefit is that it is done at compile time,</p>\n<blockquote>\n<p>The nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an &quot;unreachable code&quot; warning).</p>\n</blockquote>\n<p>More information can be found <a href=\"https://msdn.microsoft.com/en-us/magazine/Dn802602.aspx\" rel=\"noreferrer\">here</a></p>\n<p><strong>Older Version Of C 3.0 and above</strong><br />\nTo Build on Nawfals answer</p>\n<pre><code>GetParameterName2(new { variable });\n\n//Hack to assure compiler warning is generated specifying this method calling conventions\n[Obsolete(&quot;Note you must use a single parametered AnonymousType When Calling this method&quot;)]\npublic static string GetParameterName&lt;T&gt;(T item) where T : class\n{\n if (item == null)\n return string.Empty;\n\n return typeof(T).GetProperties()[0].Name;\n}\n</code></pre>\n" }, { "answer_id": 57970296, "author": "Bjarne", "author_id": 4964865, "author_profile": "https://Stackoverflow.com/users/4964865", "pm_score": 3, "selected": false, "text": "<p>This would be very useful to do in order to create good exception messages causing people to be able to pinpoint errors better. Line numbers help, but you might not get them in prod, and when you do get them, if there are big statements in code, you typically only get the first line of the whole statement.</p>\n\n<p>For instance, if you call .Value on a nullable that isn't set, you'll get an exception with a failure message, but as this functionality is lacking, you won't see what property was null. If you do this twice in one statement, for instance to set parameters to some method, you won't be able to see what nullable was not set.</p>\n\n<p>Creating code like Verify.NotNull(myvar, nameof(myvar)) is the best workaround I've found so far, but would be great to get rid of the need to add the extra parameter.</p>\n" }, { "answer_id": 67240523, "author": "Serdar", "author_id": 638990, "author_profile": "https://Stackoverflow.com/users/638990", "pm_score": 0, "selected": false, "text": "<p>A way to get it can be reading the code file and splitting it with comma and parenthesis...</p>\n<pre><code>var trace = new StackTrace(true).GetFrame(1);\nvar line = File.ReadAllLines(trace.GetFileName())[trace.GetFileLineNumber()];\nvar argumentNames = line.Split(new[] { &quot;,&quot;, &quot;(&quot;, &quot;)&quot;, &quot;;&quot; }, \n StringSplitOptions.TrimEntries)\n .Where(x =&gt; x.Length &gt; 0)\n .Skip(1).ToList();\n</code></pre>\n" }, { "answer_id": 68652267, "author": "fibriZo raZiel", "author_id": 1934546, "author_profile": "https://Stackoverflow.com/users/1934546", "pm_score": 3, "selected": false, "text": "<p>Continuing with the <code>Caller*</code> attribute series (i.e <code>CallerMemberName</code>, <code>CallerFilePath</code> and <code>CallerLineNumber</code>), <a href=\"https://learn.microsoft.com/es-es/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-5.0\" rel=\"noreferrer\">CallerArgumentExpressionAttribute</a> is available since C# Next (more info <a href=\"https://stackoverflow.com/a/64900663/1934546\">here</a>).</p>\n<p>The following example is inspired by Paul Mcilreavy's <a href=\"https://blog.mcilreavy.com/articles/2018-08/caller-argument-expression-attribute\" rel=\"noreferrer\">The CallerArgumentExpression Attribute in C# 8.0</a>:</p>\n<pre><code>public static void ThrowIfNullOrWhitespace(this string self, \n [CallerArgumentExpression(&quot;self&quot;)] string paramName = default)\n{\n if (self is null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n if (string.IsNullOrWhiteSpace(self))\n {\n throw new ArgumentOutOfRangeException(paramName, self, &quot;Value cannot be whitespace&quot;);\n } \n}\n</code></pre>\n" }, { "answer_id": 68816481, "author": "Tormod", "author_id": 80577, "author_profile": "https://Stackoverflow.com/users/80577", "pm_score": -1, "selected": false, "text": "<p>If I understand you correctly, you want the string &quot;WhatIsMyName&quot; to appear inside the Hello string.</p>\n<pre><code>string Hello = ExampleFunction(WhatIsMyName);\n</code></pre>\n<p>If the use case is that it increases the reusability of ExampleFunction and that Hello shall contain something like &quot;Hello, Peter (from WhatIsMyName)&quot;, then I think a solution would be to expand the ExampleFunction to accept:</p>\n<p>string Hello = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));</p>\n<p>So that the name is passed as a separate string. Yes, it is not exactly what you asked and you will have to type it twice. But it is refactor safe, readable, does not use the debug interface and the chance of Error is minimal because they appear together in the consuming code.</p>\n<pre><code>string Hello1 = ExampleFunction(WhatIsMyName,nameof(WhatIsMyName));\nstring Hello2 = ExampleFunction(SomebodyElse,nameof(SomebodyElse));\nstring Hello3 = ExampleFunction(HerName,nameof(HerName));\n</code></pre>\n" }, { "answer_id": 69441516, "author": "hossein sedighian", "author_id": 10143546, "author_profile": "https://Stackoverflow.com/users/10143546", "pm_score": 1, "selected": false, "text": "<p>thanks to visual studio 2022 , you can use this</p>\n<p>function</p>\n<pre><code> public void showname(dynamic obj) {\n obj.GetType().GetProperties().ToList().ForEach(state =&gt; {\n NameAndValue($&quot;{state.Name}:{state.GetValue(obj, null).ToString()}&quot;);\n });\n }\n</code></pre>\n<p>to use</p>\n<pre><code> var myname = &quot;dddd&quot;;\n showname(new { myname });\n</code></pre>\n" }, { "answer_id": 70038692, "author": "Greg M", "author_id": 17458960, "author_profile": "https://Stackoverflow.com/users/17458960", "pm_score": 5, "selected": false, "text": "<p>I know this post is really old, but since there is now a way in C#10 compiler, I thought I would share so others know.</p>\n<p>You can now use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute?view=net-6.0\" rel=\"noreferrer\">CallerArgumentExpressionAttribute</a> as shown</p>\n<pre><code>// Will throw argument exception if string IsNullOrEmpty returns true\npublic static void ValidateNotNullorEmpty(\n this string str,\n [CallerArgumentExpression(&quot;str&quot;)]string strName = null\n)\n{ \n if (string.IsNullOrEmpty(str))\n {\n throw new ArgumentException($&quot;'{strName}' cannot be null or empty.&quot;, strName);\n }\n}\n</code></pre>\n<p>Now call with:</p>\n<pre><code>param.ValidateNotNullorEmpty();\n</code></pre>\n<p>will throw error: <code>&quot;param cannot be null or empty.&quot;</code></p>\n<p>instead of &quot;str cannot be null or empty&quot;</p>\n" }, { "answer_id": 73902688, "author": "Andy", "author_id": 1204153, "author_profile": "https://Stackoverflow.com/users/1204153", "pm_score": 0, "selected": false, "text": "<p>Extending on <a href=\"https://stackoverflow.com/a/70038692/1204153\">the accepted answer</a> for this question, here is how you'd do it with <code>#nullable enable</code> source files:</p>\n<pre><code>internal static class StringExtensions\n{\n public static void ValidateNotNull(\n [NotNull] this string? theString,\n [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n {\n if (theString is null)\n {\n throw new ArgumentException($&quot;'{theName}' cannot be null.&quot;, theName);\n }\n }\n\n public static void ValidateNotNullOrEmpty(\n [NotNull] this string? theString,\n [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n {\n if (string.IsNullOrEmpty(theString))\n {\n throw new ArgumentException($&quot;'{theName}' cannot be null or empty.&quot;, theName);\n }\n }\n\n public static void ValidateNotNullOrWhitespace(\n [NotNull] this string? theString,\n [CallerArgumentExpression(&quot;theString&quot;)] string? theName = default)\n {\n if (string.IsNullOrWhiteSpace(theString))\n {\n throw new ArgumentException($&quot;'{theName}' cannot be null or whitespace&quot;, theName);\n }\n }\n}\n</code></pre>\n<p>What's nice about this code is that it uses <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.notnullattribute?view=net-6.0\" rel=\"nofollow noreferrer\"><code>[NotNull]</code></a> attribute, so the static analysis will cooperate:</p>\n<p><a href=\"https://i.stack.imgur.com/35I8C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/35I8C.png\" alt=\"static analysis\" /></a></p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Let me use the following example to explain my question: ```csharp public string ExampleFunction(string Variable) { return something; } string WhatIsMyName = "Hello World"; string Hello = ExampleFunction(WhatIsMyName); ``` When I pass the variable `WhatIsMyName` to the `ExampleFunction`, I want to be able to get a string of the *original* variable's name. Perhaps something like: ```csharp Variable.OriginalName.ToString() // == "WhatIsMyName" ``` Is there any way to do this?
**No.** I don't think so. The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken. If it helps, you could define a new class called `NamedParameter` with attributes `Name` and `Param`. You then pass this object around as parameters.
72,125
<p>Lets say that you have websites www.xyz.com and www.abc.com.</p> <p>Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider. </p> <p>Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again.</p> <p>What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice.</p>
[ { "answer_id": 72149, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 0, "selected": false, "text": "<p>Not sure what you'd use for .NET but ordinarily I'd use <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noreferrer\">memcached</a> in a LAMP stack.</p>\n" }, { "answer_id": 72278, "author": "Matej", "author_id": 11457, "author_profile": "https://Stackoverflow.com/users/11457", "pm_score": 0, "selected": false, "text": "<p>The resolution depends on the type of application and environment in which it is running. E.g. on intranet with NT Domain you can use NTLM to pass windows credentials directly to servers in intranet perimeter without any need to duplicate sessions.</p>\n\n<p>The approach how to do this is generally named <em>single sign-on</em> (see <a href=\"http://en.wikipedia.org/wiki/Single_sign-on\" rel=\"nofollow noreferrer\">Wikipedia</a>). </p>\n" }, { "answer_id": 72301, "author": "public static", "author_id": 1368, "author_profile": "https://Stackoverflow.com/users/1368", "pm_score": 1, "selected": false, "text": "<p>If you store user sessions in the database, you could simply check the existance of the Guid in the session table, if it exists, then the user already authenticated on the other domain. For this to work, you would have to included the session guid in the URL when you redirect the user over to the other website.</p>\n" }, { "answer_id": 72517, "author": "Adam Pope", "author_id": 12226, "author_profile": "https://Stackoverflow.com/users/12226", "pm_score": 2, "selected": false, "text": "<p>If you are using the built in membership system you can do cross sub-domain authentication with forms auth by using some like this in each web.config.</p>\n\n<pre><code>&lt;authentication mode=\"Forms\"&gt;\n &lt;forms name=\".ASPXAUTH\" loginUrl=\"~/Login.aspx\" path=\"/\" \n protection=\"All\" \n domain=\"datasharp.co.uk\" \n enableCrossAppRedirects=\"true\" /&gt;\n\n&lt;/authentication&gt;\n</code></pre>\n\n<p>Make sure that name, path, protection and domain are the same in all web.configs. If the sites are on different machines you will also need to ensure that the machineKey and validation and encryption keys are the same.</p>\n" }, { "answer_id": 72676, "author": "Markc", "author_id": 8609, "author_profile": "https://Stackoverflow.com/users/8609", "pm_score": 0, "selected": false, "text": "<p>There are multiple approaches to this problem, which is described as \"Cross-domain Single Sign On\". The wikipedia article pointed to by Matej is particularly helpful if you're looking for an open source solution - however - in a windows environment I belive you're best off with one of 2 approaches:</p>\n\n<ol>\n<li>Buy a commercial SSO product (like SiteMinder or PingIdentity)</li>\n<li>Use MicroSoft's cross-domain SSO solution, called <a href=\"http://technet.microsoft.com/en-us/library/cc786469.aspx\" rel=\"nofollow noreferrer\">ADFS</a> - Active Direcctory Federation Services. (federation is the term for coordinating the behavior of multiple domains)</li>\n</ol>\n\n<p>I have used SiteMinder and it works well, but it's expensive. If you're in an all MicroSoft environment I think ADFS is your best bet. Start with this <a href=\"http://www.microsoft.com/WindowsServer2003/R2/Identity_Management/ADFSwhitepaper.mspx\" rel=\"nofollow noreferrer\">ADFS whitepaper</a>.</p>\n" }, { "answer_id": 72887, "author": "Toby Mills", "author_id": 12377, "author_profile": "https://Stackoverflow.com/users/12377", "pm_score": -1, "selected": false, "text": "<p>Alternatively if you want to roll your own and the sites in question are not on the same servers or don't have access to a shared database (in which case see the above responses) then you could place a <a href=\"http://en.wikipedia.org/wiki/Web_beacon\" rel=\"nofollow noreferrer\">web beacon</a> on each of the sites which would refer back to the other site. </p>\n\n<p>Place a single pixel image (web beacon) on site A which would call site B passing through the users ID (encrypted &amp; time stamped). This would then create a new user session on site B for the user which would be set as logged in. Then when the user visited site B they would already be logged in.</p>\n\n<p>To minimise calls you could only place the web beacon on the home page and or log in confirmation pages. I've used this successfully in the past to pass information between partner sites. </p>\n" }, { "answer_id": 73077, "author": "craigmoliver", "author_id": 12252, "author_profile": "https://Stackoverflow.com/users/12252", "pm_score": 4, "selected": true, "text": "<p>Try using FormAuthentication by setting the web.config authentication section like so:</p>\n\n<pre><code>&lt;authentication mode=\"Forms\"&gt;\n &lt;forms name=\".ASPXAUTH\" requireSSL=\"true\" \n protection=\"All\" \n enableCrossAppRedirects=\"true\" /&gt;\n&lt;/authentication&gt;\n</code></pre>\n\n<p>Generate a machine key. Example: <a href=\"https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/\" rel=\"nofollow noreferrer\">Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS ...</a></p>\n\n<p>When posting to the other application the authentication ticket is passed as a hidden field. While reading the post from the first app, the second app will read the encrypted ticket and authenticate the user. Here's an example of the page that passes that posts the field:</p>\n\n<p>.aspx:</p>\n\n<pre><code>&lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;div&gt;\n &lt;p&gt;&lt;asp:Button ID=\"btnTransfer\" runat=\"server\" Text=\"Go\" PostBackUrl=\"http://otherapp/\" /&gt;&lt;/p&gt;\n &lt;input id=\"hdnStreetCred\" runat=\"server\" type=\"hidden\" /&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>code-behind:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n FormsIdentity cIdentity = Page.User.Identity as FormsIdentity;\n if (cIdentity != null)\n {\n this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName;\n this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket);\n }\n}\n</code></pre>\n\n<p>Also see the cross app form authentication section in Chapter 5 of this <a href=\"http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-2-0-Security-Membership-and-Role-Management.productCd-0764596985.html\" rel=\"nofollow noreferrer\">book</a> from Wrox. It recommends answers like the ones above in addition to providing a homebrew SSO solution. </p>\n" }, { "answer_id": 73116, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would user something like CAS:</p>\n\n<p>[1]: <a href=\"http://www.ja-sig.org/products/cas/\" rel=\"nofollow noreferrer\">http://www.ja-sig.org/products/cas/</a> CAS</p>\n\n<p>This is a solved problem and wouldn't recommend rolling your own. </p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
Lets say that you have websites www.xyz.com and www.abc.com. Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider. Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again. What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice.
Try using FormAuthentication by setting the web.config authentication section like so: ``` <authentication mode="Forms"> <forms name=".ASPXAUTH" requireSSL="true" protection="All" enableCrossAppRedirects="true" /> </authentication> ``` Generate a machine key. Example: [Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS ...](https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/) When posting to the other application the authentication ticket is passed as a hidden field. While reading the post from the first app, the second app will read the encrypted ticket and authenticate the user. Here's an example of the page that passes that posts the field: .aspx: ``` <form id="form1" runat="server"> <div> <p><asp:Button ID="btnTransfer" runat="server" Text="Go" PostBackUrl="http://otherapp/" /></p> <input id="hdnStreetCred" runat="server" type="hidden" /> </div> </form> ``` code-behind: ``` protected void Page_Load(object sender, EventArgs e) { FormsIdentity cIdentity = Page.User.Identity as FormsIdentity; if (cIdentity != null) { this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName; this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket); } } ``` Also see the cross app form authentication section in Chapter 5 of this [book](http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-2-0-Security-Membership-and-Role-Management.productCd-0764596985.html) from Wrox. It recommends answers like the ones above in addition to providing a homebrew SSO solution.
72,151
<p>I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert:</p> <pre><code>insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000) </code></pre> <p>The first insert succeeds but the second one gives an error:</p> <pre><code>ORA-00933: SQL command not properly ended </code></pre> <p>What am I doing wrong?</p>
[ { "answer_id": 72165, "author": "metadave", "author_id": 7237, "author_profile": "https://Stackoverflow.com/users/7237", "pm_score": 2, "selected": false, "text": "<p>semi colon after the first insert?</p>\n" }, { "answer_id": 72170, "author": "ShoeLace", "author_id": 3825, "author_profile": "https://Stackoverflow.com/users/3825", "pm_score": 2, "selected": false, "text": "<p>Oracle SQL uses a semi-colon ; as its end of statement marker.</p>\n\n<p>you will need to add the ; after bother insert statments.</p>\n\n<p>NB: that also assumes ADODB will allow 2 inserts in a single call.</p>\n\n<p>the alternative might be to wrap both calls in a block,</p>\n\n<pre><code>BEGIN\n insert (...) into (...);\n insert (...) into (...);\nEND;\n</code></pre>\n" }, { "answer_id": 72179, "author": "massimogentilini", "author_id": 11673, "author_profile": "https://Stackoverflow.com/users/11673", "pm_score": 3, "selected": true, "text": "<p>To me it seems you're missing a <code>;</code> between the two statements:<br>\n<code>insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)</code><br>\n<strong><code>;</code></strong><br>\n<code>insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)</code><br>\n<strong><code>;</code></strong><br>\nTry adding the <code>;</code> and let us know.</p>\n" }, { "answer_id": 72228, "author": "stevechol", "author_id": 2981, "author_profile": "https://Stackoverflow.com/users/2981", "pm_score": 0, "selected": false, "text": "<p>It's a long shot but in the first insert the sql date format is valid for both uk/us, the second insert is invalid if the Oracle DB is setup for UK date format, I realise you have used the TO_DATE function but I don't see anything else ...</p>\n" }, { "answer_id": 72493, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 0, "selected": false, "text": "<p>The ADO.NET OLE DB provider is for generic data access where you don't have a specific provider for your database. Use OracleConnection et al in preference to OleDbConnection for an Oracle database connection.</p>\n" }, { "answer_id": 72967, "author": "Steve Horn", "author_id": 10589, "author_profile": "https://Stackoverflow.com/users/10589", "pm_score": 1, "selected": false, "text": "<p>In my loop I was not re-initializing my StringBuilder ...thus the multiple insert statement I posted.</p>\n\n<p>Thanks for your help anyway!!</p>\n" }, { "answer_id": 78572, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 0, "selected": false, "text": "<p>In addition to the semicolon problem, I strongly recommend you look into bind variables. Failing to use them can cause database performance problems down the road. The code also tends to be cleaner.</p>\n" }, { "answer_id": 6056951, "author": "taranjeet", "author_id": 760830, "author_profile": "https://Stackoverflow.com/users/760830", "pm_score": 4, "selected": false, "text": "<p>In .net, when we try to execute a single Oracle SQL statement with a semicolon at the end. The result will be an oracle error: ora-00911: invalid character. OK, you figure that one SQL statement doesn't need the semicolon, but what about executing 2 SQL statement in one string for example:</p>\n\n<pre><code>Dim db As Database = DatabaseFactory.CreateDatabase(\"db\")\nDim cmd As System.Data.Common.DbCommand\nDim sql As String = \"\"\n\nsql = \"DELETE FROM iphone_applications WHERE appid = 1; DELETE FROM iphone_applications WHERE appid = 2; \"\n\ncmd = db.GetSqlStringCommand(sql)\ndb.ExecuteNonQuery(cmd)\n</code></pre>\n\n<p>The code above will give you the same Oracle error: ora-00911: invalid character.</p>\n\n<p>The solution to this problem is to wrap your 2 Oracle SQL statements with a <code>BEGIN</code> and <code>END;</code> syntax, for example:</p>\n\n<pre><code>sql = \"BEGIN DELETE FROM iphone_applications WHERE appid = 1; DELETE FROM iphone_applications WHERE appid = 2; END;\"\n</code></pre>\n\n<p>Courtesy: <a href=\"http://www.lazyasscoder.com/Article.aspx?id=89&amp;title=ora-00911%3A+invalid+character+when+executing+multiple+Oracle+SQL+statements\" rel=\"noreferrer\">http://www.lazyasscoder.com/Article.aspx?id=89&amp;title=ora-00911%3A+invalid+character+when+executing+multiple+Oracle+SQL+statements</a></p>\n" }, { "answer_id": 17193880, "author": "CrackMonkeys4Hire", "author_id": 2501607, "author_profile": "https://Stackoverflow.com/users/2501607", "pm_score": 3, "selected": false, "text": "<p>In Oracle the semi-colon ';' is only used in sqlplus. When you are using ODBC/JDBC, OLEDB, etc you don't put a semi-colon at the end of your statement. In the above case you are actually executing 2 different statements so the best way to handle the problem is use 2 statements instead of trying to combine into a single statement since you can't use the semi-colon.</p>\n" }, { "answer_id": 48570003, "author": "Kevin Weinhold", "author_id": 1445190, "author_profile": "https://Stackoverflow.com/users/1445190", "pm_score": 0, "selected": false, "text": "<p>The issue may be that you have a parameter variable that is null being inserted into the query. That was what my problem was. Once I gave the parameter a default value of empty string, it worked.</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert: ``` insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000) ``` The first insert succeeds but the second one gives an error: ``` ORA-00933: SQL command not properly ended ``` What am I doing wrong?
To me it seems you're missing a `;` between the two statements: `insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)` **`;`** `insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)` **`;`** Try adding the `;` and let us know.
72,153
<p>How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got:</p> <pre><code>&lt;ItemGroup&gt; &lt;LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>At the moment, but this does not exclude anything!</p>
[ { "answer_id": 72536, "author": "Kieran Benton", "author_id": 5777, "author_profile": "https://Stackoverflow.com/users/5777", "pm_score": 7, "selected": true, "text": "<p>Thanks for your help, managed to sort it as follows:</p>\n\n<pre><code>&lt;ItemGroup&gt;\n &lt;LibraryFiles Include=\"$(LibrariesReleaseDir)\\**\\*.*\" \n Exclude=\"$(LibrariesReleaseDir)\\**\\.svn\\**\" /&gt;\n&lt;/ItemGroup&gt;\n</code></pre>\n\n<p>Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the <code>.svn</code> directories (<code>.svn\\\\**</code>) for MSBuild to exclude the <code>.svn</code> directory itself.</p>\n" }, { "answer_id": 380954, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "<p>Here's an even better way to do it, truly recursively. I can't seem to get your solution to go more than 1 level deep:</p>\n\n<pre><code>&lt;LibraryFiles \n Include=\"$(LibrariesReleaseDir)**\\*.*\" \n Exclude=\"$(LibrariesReleaseDir)**\\.svn\\**\\*.*\"/&gt;\n</code></pre>\n" }, { "answer_id": 612742, "author": "abombss", "author_id": 31029, "author_profile": "https://Stackoverflow.com/users/31029", "pm_score": 4, "selected": false, "text": "<p>So the issue is with chaining variables for some reason in msbuild. The following works for me, notice that I have to only use relative paths based on the MSBuildProjectDirectory variable.</p>\n\n<pre><code>&lt;CreateItem Include=\"$(MSBuildProjectDirectory)\\..\\Client\\Web\\Foo.Web.UI\\**\\*.*\"\n Exclude=\"$(MSBuildProjectDirectory)\\..\\Client\\Web\\Foo.Web.UI\\**\\.svn\\**\"&gt;\n &lt;Output TaskParameter=\"Include\" ItemName=\"WebFiles\" /&gt;\n&lt;/CreateItem&gt;\n</code></pre>\n\n<p>The following does not work:</p>\n\n<pre><code>&lt;PropertyGroup&gt;\n &lt;WebProjectDir&gt;$(MSBuildProjectDirectory)\\..\\Client\\Web\\Foo.Web.UI&lt;/WebProjectDir&gt;\n&lt;/PropertyGroup&gt;\n&lt;CreateItem Include=\"$(WebProjectDir)\\**\\*.*\"\n Exclude=\"$(WebProjectDir)\\**\\.svn\\**\"&gt;\n &lt;Output TaskParameter=\"Include\" ItemName=\"WebFiles\" /&gt;\n&lt;/CreateItem&gt;\n</code></pre>\n\n<p>Very strange! I just spent like 3 hrs on this one.</p>\n" }, { "answer_id": 10387041, "author": "Anton Backer", "author_id": 419876, "author_profile": "https://Stackoverflow.com/users/419876", "pm_score": 1, "selected": false, "text": "<p>I've run into some glitches using the Include/Exclude approach, so here's something that's worked for me instead:\n</p>\n\n<pre><code>&lt;ItemGroup&gt;\n &lt;MyFiles Include=\".\\PathToYourStuff\\**\" /&gt;\n &lt;MyFiles Remove=\".\\PathToYourStuff\\**\\.svn\\**\" /&gt;\n&lt;/ItemGroup&gt;\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got: ``` <ItemGroup> <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" /> </ItemGroup> ``` At the moment, but this does not exclude anything!
Thanks for your help, managed to sort it as follows: ``` <ItemGroup> <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude="$(LibrariesReleaseDir)\**\.svn\**" /> </ItemGroup> ``` Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the `.svn` directories (`.svn\\**`) for MSBuild to exclude the `.svn` directory itself.
72,167
<p>How do I find out which sound files the user has configured in the control panel?</p> <p>Example: I want to play the sound for "Device connected".</p> <p>Which API can be used to query the control panel sound settings?</p> <p>I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.</p> <p>Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.</p> <p>To play the "Device Conntected" sound:</p> <pre><code>::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC ); </code></pre>
[ { "answer_id": 72250, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 5, "selected": true, "text": "<p><a href=\"https://learn.microsoft.com/en-us/previous-versions/ms712879(v=vs.85)\" rel=\"nofollow noreferrer\"><code>PlaySound</code></a> is the API.</p>\n<p>Also see <a href=\"https://learn.microsoft.com/en-us/windows/win32/multimedia/using-playsound-to-play-system-sounds\" rel=\"nofollow noreferrer\">Play System Sounds</a>.</p>\n" }, { "answer_id": 72488, "author": "Nidonocu", "author_id": 483, "author_profile": "https://Stackoverflow.com/users/483", "pm_score": 4, "selected": false, "text": "<p>Not Win32, but for .net anyway, you can do this using the following in C#:</p>\n\n<pre><code>System.Media.SystemSounds.Asterisk.Play();\n// Plays the Asterisk sound (used for Information (i))\n// Also available:\n// Exclamation (Warning /!\\)\n// Hand (aka Critical Stop - Error (X))\n// Question (?)\n// Beep (aka Default Beep)\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810/" ]
How do I find out which sound files the user has configured in the control panel? Example: I want to play the sound for "Device connected". Which API can be used to query the control panel sound settings? I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings. Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry. To play the "Device Conntected" sound: ``` ::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC ); ```
[`PlaySound`](https://learn.microsoft.com/en-us/previous-versions/ms712879(v=vs.85)) is the API. Also see [Play System Sounds](https://learn.microsoft.com/en-us/windows/win32/multimedia/using-playsound-to-play-system-sounds).
72,176
<p>While there are 100 ways to solve the conversion problem, I am focusing on performance.</p> <p>Give that the string only contains binary data, what is the fastest method, in terms of performance, of converting that data to a byte[] (not char[]) under C#?</p> <p>Clarification: This is not ASCII data, rather binary data that happens to be in a string.</p>
[ { "answer_id": 72191, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getbytes.aspx\" rel=\"nofollow noreferrer\">UTF8Encoding.GetBytes</a></p>\n" }, { "answer_id": 72500, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>There is <em>no such thing</em> as an ASCII string in C#! Strings <em>always</em> contain UTF-16. Not realizing this leads to a lot of problems. That said, the methods mentioned before work because they consider the string as UTF-16 encoded and transform the characters to ASCII symbols.</p>\n\n<p>/EDIT in response to the clarification: how did the binary data get in the string? Strings aren't supposed to contain binary data (use <code>byte[]</code> for that).</p>\n" }, { "answer_id": 72822, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 3, "selected": true, "text": "<p>I'm not sure ASCIIEncoding.GetBytes is going to do it, because it only supports the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding\" rel=\"nofollow noreferrer\">range 0x0000 to 0x007F</a>. </p>\n\n<p>You tell the string contains only bytes. But a .NET string is an array of chars, and 1 char is 2 bytes (because a .NET stores strings as UTF16). So you can either have two situations for storing the bytes 0x42 and 0x98:</p>\n\n<ol>\n<li>The string was an ANSI string and contained bytes and is converted to an unicode string, thus the bytes will be 0x00 0x42 0x00 0x98. (The string is stored as 0x0042 and 0x0098)</li>\n<li>The string was just a byte array which you typecasted or just recieved to an string and thus became the following bytes 0x42 0x98. (The string is stored as 0x9842)</li>\n</ol>\n\n<p>In the first situation on the result would be 0x42 and 0x3F (ascii for \"B?\"). The second situation would result in 0x3F (ascii for \"?\"). This is logical, because the chars are outside of the valid ascii range and the encoder does not know what to do with those values.</p>\n\n<p>So i'm wondering why it's a string with bytes?</p>\n\n<ul>\n<li>Maybe it contains a byte encoded as a string (for instance <a href=\"https://en.wikipedia.org/wiki/Base64\" rel=\"nofollow noreferrer\">Base64</a>)?</li>\n<li>Maybe you should start with an char array or a byte array?</li>\n</ul>\n\n<p>If you realy do have situation 2 and you want to get the bytes out of it you should use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes\" rel=\"nofollow noreferrer\">UnicodeEncoding.GetBytes</a> call. Because that will return 0x42 and 0x98.</p>\n\n<p>If you'd like to go from a char array to byte array, the fastest way would be Marshaling.. But that's not really nice, and uses double memory. </p>\n\n<pre><code>public Byte[] ConvertToBytes(Char[] source)\n{\n Byte[] result = new Byte[source.Length * sizeof(Char)];\n IntPtr tempBuffer = Marshal.AllocHGlobal(result.Length);\n try\n {\n Marshal.Copy(source, 0, tempBuffer, source.Length);\n Marshal.Copy(tempBuffer, result, 0, result.Length);\n }\n finally\n {\n Marshal.FreeHGlobal(tempBuffer);\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 74121, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 0, "selected": false, "text": "<p>If you want to go from a string to binary data, <strong>you must know what encoding was used to convert the binary data to a string in the first place</strong>. Otherwise, you might not end up with the correct binary data. So, the most efficient way is likely GetBytes() on an Encoding subclass (such as UTF8Encoding), but you must know for sure which encoding.</p>\n\n<p>The comment by Kent Boogaart on the original question sums it up pretty well. ;]</p>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113/" ]
While there are 100 ways to solve the conversion problem, I am focusing on performance. Give that the string only contains binary data, what is the fastest method, in terms of performance, of converting that data to a byte[] (not char[]) under C#? Clarification: This is not ASCII data, rather binary data that happens to be in a string.
I'm not sure ASCIIEncoding.GetBytes is going to do it, because it only supports the [range 0x0000 to 0x007F](https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding). You tell the string contains only bytes. But a .NET string is an array of chars, and 1 char is 2 bytes (because a .NET stores strings as UTF16). So you can either have two situations for storing the bytes 0x42 and 0x98: 1. The string was an ANSI string and contained bytes and is converted to an unicode string, thus the bytes will be 0x00 0x42 0x00 0x98. (The string is stored as 0x0042 and 0x0098) 2. The string was just a byte array which you typecasted or just recieved to an string and thus became the following bytes 0x42 0x98. (The string is stored as 0x9842) In the first situation on the result would be 0x42 and 0x3F (ascii for "B?"). The second situation would result in 0x3F (ascii for "?"). This is logical, because the chars are outside of the valid ascii range and the encoder does not know what to do with those values. So i'm wondering why it's a string with bytes? * Maybe it contains a byte encoded as a string (for instance [Base64](https://en.wikipedia.org/wiki/Base64))? * Maybe you should start with an char array or a byte array? If you realy do have situation 2 and you want to get the bytes out of it you should use the [UnicodeEncoding.GetBytes](https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes) call. Because that will return 0x42 and 0x98. If you'd like to go from a char array to byte array, the fastest way would be Marshaling.. But that's not really nice, and uses double memory. ``` public Byte[] ConvertToBytes(Char[] source) { Byte[] result = new Byte[source.Length * sizeof(Char)]; IntPtr tempBuffer = Marshal.AllocHGlobal(result.Length); try { Marshal.Copy(source, 0, tempBuffer, source.Length); Marshal.Copy(tempBuffer, result, 0, result.Length); } finally { Marshal.FreeHGlobal(tempBuffer); } return result; } ```
72,198
<p>This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data -- a description on the left side and a corresponding value displayed on the right side. I haven't worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using tabs would be an easy way to create the second column, but I discovered things just don't work that well.</p> <p>There seems to be two problems with the way I tried to do this (see below). First, I read on numerous websites that the MeasureString function isn't very precise due to how complex fonts are, with kerning issues and all. The second is that I have no idea what the TextBox control is using as its StringFormat underneath.</p> <p>Anyway, the result is that I invariably end up with items in the right column that are off by a tab. I suppose I could roll my own text window and do everything myself, but gee, isn't there a simple way to do this?</p> <pre><code> TextBox textBox = new TextBox(); textBox.Font = new Font("Calibri", 11); textBox.Dock = DockStyle.Fill; textBox.Multiline = true; textBox.WordWrap = false; textBox.ScrollBars = ScrollBars.Vertical; Form form = new Form(); form.Text = "Recipe"; form.Size = new Size(400, 600); form.FormBorderStyle = FormBorderStyle.Sizable; form.StartPosition = FormStartPosition.CenterScreen; form.Controls.Add(textBox); Graphics g = form.CreateGraphics(); float targetWidth = 230; foreach (PropertyInfo property in properties) { string text = String.Format("{0}:\t", Description); while (g.MeasureString(text,textBox.Font).Width &lt; targetWidth) text += "\t"; textBox.AppendText(text + value.ToString() + "\n"); } g.Dispose(); form.ShowDialog(); </code></pre>
[ { "answer_id": 72282, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": -1, "selected": false, "text": "<p>Don't the text boxes allow HTML usage? If that is the case, just use HTML to format the text into a table. Otherwise, try adding the text to a datagrid and then adding that to the form.</p>\n" }, { "answer_id": 72283, "author": "Matt Dawdy", "author_id": 232, "author_profile": "https://Stackoverflow.com/users/232", "pm_score": 1, "selected": true, "text": "<p>If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.</p>\n\n<pre><code>Private Declare Function SendMessage _\n Lib \"user32\" Alias \"SendMessageA\" _\n (ByVal handle As IntPtr, ByVal wMsg As Integer, _\n ByVal wParam As Integer, ByRef lParam As Integer) As Integer\n\n\nPrivate Sub SetTabStops(ByVal ctlTextBox As TextBox)\n\n Const EM_SETTABSTOPS As Integer = &amp;HCBS\n\n Dim tabs() As Integer = {20, 40, 80}\n\n SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _\n tabs.Length, tabs(0))\n\nEnd Sub\n</code></pre>\n\n<p>I converted a version to C# for you, too. Tested and working in VS2005.</p>\n\n<p>Add this using statement to your form: </p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>Put this right after the class declaration:</p>\n\n<pre><code> private const int EM_SETTABSTOPS = 0x00CB;\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);\n</code></pre>\n\n<p>Call this method when you want to set the tabstops:</p>\n\n<pre><code> private void SetTabStops(TextBox ctlTextBox)\n {\n const int EM_SETTABSTOPS = 203;\n int[] tabs = { 100, 40, 80 };\n SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs);\n }\n</code></pre>\n\n<p>To use it, here is all I did:</p>\n\n<pre><code> private void Form1_Load(object sender, EventArgs e)\n {\n SetTabStops(textBox1);\n\n textBox1.Text = \"Hi\\tWorld\";\n }\n</code></pre>\n" }, { "answer_id": 72420, "author": "Ken Wootton", "author_id": 7357, "author_profile": "https://Stackoverflow.com/users/7357", "pm_score": 0, "selected": false, "text": "<p>If you want something truly tabular, Mr. Haren's answer is a good one. The DataGridView will give you a very Excel spreadsheet type of look.</p>\n\n<p>If you just want a two column layout (similar to HTML's table), then try out the TableLayoutPanel. It'll give you the layout you desire with the ability to use standard controls within each table cell.</p>\n" }, { "answer_id": 72627, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": -1, "selected": false, "text": "<p>I believe the only way is to do something similar to what you are doing, but use a fixed font and do your own padding with spaces so that you don't have to worry about tab expansion.</p>\n" }, { "answer_id": 72659, "author": "AZDean", "author_id": 12058, "author_profile": "https://Stackoverflow.com/users/12058", "pm_score": 1, "selected": false, "text": "<p>Thanks Matt, your solution worked great for me. Here's my version of your code...</p>\n\n<pre><code>// This is a better way to pass in what tab stops I want...\nSetTabStops(textBox, new int[] { 12,120 });\n\n// And the code for the SetTabsStops method itself...\nprivate const uint EM_SETTABSTOPS = 0x00CB;\n\n[DllImport(\"User32.dll\")]\nprivate static extern uint SendMessage(IntPtr hWnd, uint wMsg, int wParam, int[] lParam);\n\npublic static void SetTabStops(TextBox textBox, int[] tabs)\n{\n SendMessage(textBox.Handle, EM_SETTABSTOPS, tabs.Length, tabs);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12058/" ]
This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data -- a description on the left side and a corresponding value displayed on the right side. I haven't worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using tabs would be an easy way to create the second column, but I discovered things just don't work that well. There seems to be two problems with the way I tried to do this (see below). First, I read on numerous websites that the MeasureString function isn't very precise due to how complex fonts are, with kerning issues and all. The second is that I have no idea what the TextBox control is using as its StringFormat underneath. Anyway, the result is that I invariably end up with items in the right column that are off by a tab. I suppose I could roll my own text window and do everything myself, but gee, isn't there a simple way to do this? ``` TextBox textBox = new TextBox(); textBox.Font = new Font("Calibri", 11); textBox.Dock = DockStyle.Fill; textBox.Multiline = true; textBox.WordWrap = false; textBox.ScrollBars = ScrollBars.Vertical; Form form = new Form(); form.Text = "Recipe"; form.Size = new Size(400, 600); form.FormBorderStyle = FormBorderStyle.Sizable; form.StartPosition = FormStartPosition.CenterScreen; form.Controls.Add(textBox); Graphics g = form.CreateGraphics(); float targetWidth = 230; foreach (PropertyInfo property in properties) { string text = String.Format("{0}:\t", Description); while (g.MeasureString(text,textBox.Font).Width < targetWidth) text += "\t"; textBox.AppendText(text + value.ToString() + "\n"); } g.Dispose(); form.ShowDialog(); ```
If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control. ``` Private Declare Function SendMessage _ Lib "user32" Alias "SendMessageA" _ (ByVal handle As IntPtr, ByVal wMsg As Integer, _ ByVal wParam As Integer, ByRef lParam As Integer) As Integer Private Sub SetTabStops(ByVal ctlTextBox As TextBox) Const EM_SETTABSTOPS As Integer = &HCBS Dim tabs() As Integer = {20, 40, 80} SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _ tabs.Length, tabs(0)) End Sub ``` I converted a version to C# for you, too. Tested and working in VS2005. Add this using statement to your form: ``` using System.Runtime.InteropServices; ``` Put this right after the class declaration: ``` private const int EM_SETTABSTOPS = 0x00CB; [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam); ``` Call this method when you want to set the tabstops: ``` private void SetTabStops(TextBox ctlTextBox) { const int EM_SETTABSTOPS = 203; int[] tabs = { 100, 40, 80 }; SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs); } ``` To use it, here is all I did: ``` private void Form1_Load(object sender, EventArgs e) { SetTabStops(textBox1); textBox1.Text = "Hi\tWorld"; } ```
72,204
<p>Has anyone used <a href="http://www.ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx" rel="nofollow noreferrer">Rhino igloo</a> in a non-trivial project? I am curious if it's worth, what are its drawbacks, does it enhance testability a lot, is it easy to use. How would you compare it to a pure MVC framework (ASP.NET MVC)? Please share the experience.</p>
[ { "answer_id": 72282, "author": "Nicholas Mancuso", "author_id": 8945, "author_profile": "https://Stackoverflow.com/users/8945", "pm_score": -1, "selected": false, "text": "<p>Don't the text boxes allow HTML usage? If that is the case, just use HTML to format the text into a table. Otherwise, try adding the text to a datagrid and then adding that to the form.</p>\n" }, { "answer_id": 72283, "author": "Matt Dawdy", "author_id": 232, "author_profile": "https://Stackoverflow.com/users/232", "pm_score": 1, "selected": true, "text": "<p>If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.</p>\n\n<pre><code>Private Declare Function SendMessage _\n Lib \"user32\" Alias \"SendMessageA\" _\n (ByVal handle As IntPtr, ByVal wMsg As Integer, _\n ByVal wParam As Integer, ByRef lParam As Integer) As Integer\n\n\nPrivate Sub SetTabStops(ByVal ctlTextBox As TextBox)\n\n Const EM_SETTABSTOPS As Integer = &amp;HCBS\n\n Dim tabs() As Integer = {20, 40, 80}\n\n SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _\n tabs.Length, tabs(0))\n\nEnd Sub\n</code></pre>\n\n<p>I converted a version to C# for you, too. Tested and working in VS2005.</p>\n\n<p>Add this using statement to your form: </p>\n\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n\n<p>Put this right after the class declaration:</p>\n\n<pre><code> private const int EM_SETTABSTOPS = 0x00CB;\n [DllImport(\"User32.dll\", CharSet = CharSet.Auto)]\n public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);\n</code></pre>\n\n<p>Call this method when you want to set the tabstops:</p>\n\n<pre><code> private void SetTabStops(TextBox ctlTextBox)\n {\n const int EM_SETTABSTOPS = 203;\n int[] tabs = { 100, 40, 80 };\n SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs);\n }\n</code></pre>\n\n<p>To use it, here is all I did:</p>\n\n<pre><code> private void Form1_Load(object sender, EventArgs e)\n {\n SetTabStops(textBox1);\n\n textBox1.Text = \"Hi\\tWorld\";\n }\n</code></pre>\n" }, { "answer_id": 72420, "author": "Ken Wootton", "author_id": 7357, "author_profile": "https://Stackoverflow.com/users/7357", "pm_score": 0, "selected": false, "text": "<p>If you want something truly tabular, Mr. Haren's answer is a good one. The DataGridView will give you a very Excel spreadsheet type of look.</p>\n\n<p>If you just want a two column layout (similar to HTML's table), then try out the TableLayoutPanel. It'll give you the layout you desire with the ability to use standard controls within each table cell.</p>\n" }, { "answer_id": 72627, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": -1, "selected": false, "text": "<p>I believe the only way is to do something similar to what you are doing, but use a fixed font and do your own padding with spaces so that you don't have to worry about tab expansion.</p>\n" }, { "answer_id": 72659, "author": "AZDean", "author_id": 12058, "author_profile": "https://Stackoverflow.com/users/12058", "pm_score": 1, "selected": false, "text": "<p>Thanks Matt, your solution worked great for me. Here's my version of your code...</p>\n\n<pre><code>// This is a better way to pass in what tab stops I want...\nSetTabStops(textBox, new int[] { 12,120 });\n\n// And the code for the SetTabsStops method itself...\nprivate const uint EM_SETTABSTOPS = 0x00CB;\n\n[DllImport(\"User32.dll\")]\nprivate static extern uint SendMessage(IntPtr hWnd, uint wMsg, int wParam, int[] lParam);\n\npublic static void SetTabStops(TextBox textBox, int[] tabs)\n{\n SendMessage(textBox.Handle, EM_SETTABSTOPS, tabs.Length, tabs);\n}\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801/" ]
Has anyone used [Rhino igloo](http://www.ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx) in a non-trivial project? I am curious if it's worth, what are its drawbacks, does it enhance testability a lot, is it easy to use. How would you compare it to a pure MVC framework (ASP.NET MVC)? Please share the experience.
If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control. ``` Private Declare Function SendMessage _ Lib "user32" Alias "SendMessageA" _ (ByVal handle As IntPtr, ByVal wMsg As Integer, _ ByVal wParam As Integer, ByRef lParam As Integer) As Integer Private Sub SetTabStops(ByVal ctlTextBox As TextBox) Const EM_SETTABSTOPS As Integer = &HCBS Dim tabs() As Integer = {20, 40, 80} SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _ tabs.Length, tabs(0)) End Sub ``` I converted a version to C# for you, too. Tested and working in VS2005. Add this using statement to your form: ``` using System.Runtime.InteropServices; ``` Put this right after the class declaration: ``` private const int EM_SETTABSTOPS = 0x00CB; [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam); ``` Call this method when you want to set the tabstops: ``` private void SetTabStops(TextBox ctlTextBox) { const int EM_SETTABSTOPS = 203; int[] tabs = { 100, 40, 80 }; SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs); } ``` To use it, here is all I did: ``` private void Form1_Load(object sender, EventArgs e) { SetTabStops(textBox1); textBox1.Text = "Hi\tWorld"; } ```
72,220
<p>I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the <code>File</code> class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter: </p> <pre><code>def initialize(file_class=File) </code></pre> <p>When I need to open files within my class, I can then do this:</p> <pre><code>@file_class.open(filename) </code></pre> <p>And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?</p>
[ { "answer_id": 72248, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 4, "selected": false, "text": "<p>Mocha (<a href=\"http://mocha.rubyforge.org/\" rel=\"noreferrer\">http://mocha.rubyforge.org/</a>) is a very good mocking library for ruby. Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this:</p>\n\n<pre>\n<code>\nrequire 'mocha'\n\nmock_file_obj = mock(\"My Mock File\") do\n stubs(:some_instance_method).returns(\"foo\")\nend\n\nFile.stubs(:new).with(is_a(String)).returns(mock_file_obj)\n</code>\n</pre>\n" }, { "answer_id": 73605, "author": "tomafro", "author_id": 7126, "author_profile": "https://Stackoverflow.com/users/7126", "pm_score": 1, "selected": false, "text": "<p>In the case you've outlined, I'd suggest that what you're doing seems fine. I know that it's a technique that James Mead (the author of Mocha) has advocated. There's no need to do metaprogramming just for the sake of it. <a href=\"http://www.floehopper.org/articles/2007/11/29/mock-object-injection\" rel=\"nofollow noreferrer\">Here's what James has to say about it</a> (and a long list of other techniques you could try)</p>\n" }, { "answer_id": 17243303, "author": "Mulan", "author_id": 633183, "author_profile": "https://Stackoverflow.com/users/633183", "pm_score": 1, "selected": false, "text": "<p>This is a particularly difficult challenge for me. With the help I received on <a href=\"https://stackoverflow.com/questions/17204371/how-to-test-factory-pattern-using-mocha-in-ruby\">this question</a>, and some extra work on my behalf, here's the solution I arrived at.</p>\n\n<pre><code># lib/real_thing.rb\nclass RealThing\n def initialize a, b, c\n # ...\n end\nend\n\n# test/test_real_thing.rb\nclass TestRealThing &lt; MiniTest::Unit::TestCase\n\n class Fake &lt; RealThing; end\n\n def test_real_thing_initializer\n fake = mock()\n Fake.expects(:new).with(1, 2, 3).returns(fake)\n assert_equal fake, Fake.new(1, 2, 3)\n end\n\nend\n</code></pre>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/72220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the `File` class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter: ``` def initialize(file_class=File) ``` When I need to open files within my class, I can then do this: ``` @file_class.open(filename) ``` And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?
Mocha (<http://mocha.rubyforge.org/>) is a very good mocking library for ruby. Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this: ``` require 'mocha' mock_file_obj = mock("My Mock File") do stubs(:some_instance_method).returns("foo") end File.stubs(:new).with(is_a(String)).returns(mock_file_obj) ```