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
243,568
<p>I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the <a href="http://msdn.microsoft.com/en-us/library/14zezc9x.aspx" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.</p> </blockquote> <p>My proposed fix is to use <code>(obj.GetTotalHours()+1)/24</code> instead. I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way. </p> <p>This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.</p>
[ { "answer_id": 243841, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": true, "text": "<p>Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day. Otherwise that \"+1\" in the expression could lead to an off-by-one error.</p>\n\n<p>Sometimes you don't care what time of day the event occured, you just want to know which day. In that case, you need to zero out the hours, minutes, and seconds, then use your formula:</p>\n\n<pre><code>CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);\nCTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);\nint days = ((finishDay - startDay).GetTotalHours() + 1) / 24;\n</code></pre>\n" }, { "answer_id": 16320654, "author": "mjk99", "author_id": 1630774, "author_profile": "https://Stackoverflow.com/users/1630774", "pm_score": 0, "selected": false, "text": "<p>A minor change to what Mark suggested and it works without any reliance on rounding: Just add one more parameter of zero to the <code>CTime</code> constructor. This forces both times to be in standard time (not daylight savings). The default value for that parameter is -1 which means \"Automatically compute if daylight savings time is in effect.\"</p>\n\n<pre><code>// Discard hours, minutes, seconds, and daylight savings time\nCTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0, 0);\nCTime endDay(end.GetYear(), end.GetMonth(), end.GetDay(), 0, 0, 0, 0);\n\n// Get number of days apart\nCTimeSpan span = endDay - startDay;\nint nDays = span.GetDays();\n</code></pre>\n\n<p>Tested and works.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date. We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method. According to the [documentation](http://msdn.microsoft.com/en-us/library/14zezc9x.aspx): > > Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day. > > > My proposed fix is to use `(obj.GetTotalHours()+1)/24` instead. I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way. This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.
Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day. Otherwise that "+1" in the expression could lead to an off-by-one error. Sometimes you don't care what time of day the event occured, you just want to know which day. In that case, you need to zero out the hours, minutes, and seconds, then use your formula: ``` CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0); CTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0); int days = ((finishDay - startDay).GetTotalHours() + 1) / 24; ```
243,569
<p>consider this code block</p> <pre><code>public void ManageInstalledComponentsUpdate() { IUpdateView view = new UpdaterForm(); BackgroundWorker worker = new BackgroundWorker(); Update update = new Update(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(update.DoUpdate); worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback); worker.RunWorkerAsync(); Application.Run(view as UpdaterForm); } </code></pre> <p>It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected</p>
[ { "answer_id": 243600, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited.</p>\n\n<p>Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached.</p>\n\n<p>[edit]\nAs has also been noted; the event handlers on the worker (in your code) will keep the \"view\" and \"update\" objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the \"view\" and \"update\", you don't need to get paranoid about unsubscribing the events. I've edited the code to include a \"SomeTarget\" object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker).</p>\n\n<p>Re worker getting collected when the thread dies: here's the proof; you should see \"worker finalized\" after the worker reports exit:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\nclass Demo : Form\n{\n class ChattyWorker : BackgroundWorker\n {\n ~ChattyWorker()\n {\n Console.WriteLine(\"Worker finalized\");\n }\n }\n class SomeTarget\n {\n ~SomeTarget()\n {\n Console.WriteLine(\"Target finalized\");\n }\n public SomeTarget()\n {\n Console.WriteLine(\"Target created\");\n }\n public void Foo(object sender, EventArgs args)\n {\n Console.WriteLine(\"Foo\");\n }\n }\n static void Collect(object sender, EventArgs args)\n {\n Console.WriteLine(\"Collecting...\");\n GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);\n }\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();\n timer.Interval = 100;\n timer.Tick += Collect;\n timer.Start();\n\n ChattyWorker worker = new ChattyWorker();\n worker.RunWorkerCompleted += new SomeTarget().Foo;\n worker.DoWork += delegate\n {\n Console.WriteLine(\"Worker starting\");\n for (int i = 0; i &lt; 10; i++)\n {\n Thread.Sleep(250);\n Console.WriteLine(i);\n }\n Console.WriteLine(\"Worker exiting\");\n };\n worker.RunWorkerAsync();\n }\n [STAThread]\n static void Main()\n { // using a form to force a sync context\n Application.Run(new Demo());\n }\n}\n</code></pre>\n" }, { "answer_id": 243623, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>Event handlers are references, so until you have event handler attached to the worker, it would not be considered \"unreachable\".</p>\n\n<p>In your ComplitionCallback take care to unhook the event handlers.</p>\n" }, { "answer_id": 245230, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": -1, "selected": false, "text": "<p>Those local variable objects are keep alive until the function exits, which is when the form exits. So null them out before call to Run, or move them to a different context.</p>\n\n<pre><code>public void ManageInstalledComponentsUpdate() {\n UpdaterForm form = new UpdaterForm();\n FireAndForgetWorker( form );\n Application.Run( form ); //does not return until form exits\n}\n\nvoid FireAndForgetWorker( IUpdateView view ) {\n BackgroundWorker worker = new BackgroundWorker();\n Update update = new Update();\n worker.WorkerReportsProgress = true;\n worker.WorkerSupportsCancellation = true;\n worker.DoWork += new DoWorkEventHandler(update.DoUpdate);\n worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);\n worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);\n worker.RunWorkerAsync();\n}\n</code></pre>\n\n<p>A note to vsick:</p>\n\n<p>Try running the following program, you will be surprised that x lives forever.</p>\n\n<p>using System;</p>\n\n<pre><code>class FailsOnGarbageCollection \n{ ~FailsOnGarbageCollection() { throw new NotSupportedException(); } }\n\nclass Program{\n static void WaitForever() { while (true) { var o = new object(); } }\n\n static void Main(string[] args)\n {\n var x = new FailsOnGarbageCollection();\n //x = null; //use this line to release x and cause the above exception\n WaitForever();\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30324/" ]
consider this code block ``` public void ManageInstalledComponentsUpdate() { IUpdateView view = new UpdaterForm(); BackgroundWorker worker = new BackgroundWorker(); Update update = new Update(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(update.DoUpdate); worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback); worker.RunWorkerAsync(); Application.Run(view as UpdaterForm); } ``` It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected
Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited. Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached. [edit] As has also been noted; the event handlers on the worker (in your code) will keep the "view" and "update" objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the "view" and "update", you don't need to get paranoid about unsubscribing the events. I've edited the code to include a "SomeTarget" object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker). Re worker getting collected when the thread dies: here's the proof; you should see "worker finalized" after the worker reports exit: ``` using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; class Demo : Form { class ChattyWorker : BackgroundWorker { ~ChattyWorker() { Console.WriteLine("Worker finalized"); } } class SomeTarget { ~SomeTarget() { Console.WriteLine("Target finalized"); } public SomeTarget() { Console.WriteLine("Target created"); } public void Foo(object sender, EventArgs args) { Console.WriteLine("Foo"); } } static void Collect(object sender, EventArgs args) { Console.WriteLine("Collecting..."); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Interval = 100; timer.Tick += Collect; timer.Start(); ChattyWorker worker = new ChattyWorker(); worker.RunWorkerCompleted += new SomeTarget().Foo; worker.DoWork += delegate { Console.WriteLine("Worker starting"); for (int i = 0; i < 10; i++) { Thread.Sleep(250); Console.WriteLine(i); } Console.WriteLine("Worker exiting"); }; worker.RunWorkerAsync(); } [STAThread] static void Main() { // using a form to force a sync context Application.Run(new Demo()); } } ```
243,572
<p>I am configure log4net to use a composite RollingFileAppender so that the current file is always named <strong>logfile.log</strong> and all subsequent files are named <strong>logfile-YYYY.MM.dd.seq.log</strong> where <strong>seq</strong> is the sequence number if a log exceeds a certain size within a single day. Unfortunately, I have had very little success in configuring such a setup. </p> <p><strong>Edit:</strong></p> <p>My current configuration is pasted below. It has been updated based on several answers which gets me close enough for my needs. This generates files of the format: <strong>logfile_YYYY.MM.dd.log.seq</strong></p> <pre><code>&lt;log4net&gt; &lt;root&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="RollingFileAppender" /&gt; &lt;/root&gt; &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="logs\\logfile"/&gt; &lt;staticLogFileName value="false"/&gt; &lt;appendToFile value="true"/&gt; &lt;rollingStyle value="Composite"/&gt; &lt;datePattern value="_yyyy.MM.dd&amp;quot;.log&amp;quot;"/&gt; &lt;maxSizeRollBackups value="10"/&gt; &lt;maximumFileSize value="75KB"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/&gt; &lt;/layout&gt; &lt;filter type="log4net.Filter.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="DEBUG" /&gt; &lt;param name="LevelMax" value="FATAL" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;/log4net&gt; </code></pre> <p>One interesting note, setting</p> <pre><code>&lt;staticLogFileName value="false"/&gt; </code></pre> <p>to true causes the logger to not write any files.</p>
[ { "answer_id": 243607, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "<p>According to log4net RollingFileAppender source code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected string GetNextOutputFileName(string fileName)\n{\n if (!m_staticLogFileName) \n {\n fileName = fileName.Trim();\n\n if (m_rollDate)\n {\n fileName = fileName + m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);\n }\n\n if (m_countDirection &gt;= 0) \n {\n fileName = fileName + '.' + m_curSizeRollBackups;\n }\n }\n\n return fileName;\n}\n</code></pre>\n\n<p>So I'm guessing it's not possible to generate a log file with the name you need. I think it's something like <code>logfileYYYY-MM-dd.n.log</code> or similar.</p>\n" }, { "answer_id": 243608, "author": "paul", "author_id": 11249, "author_profile": "https://Stackoverflow.com/users/11249", "pm_score": 5, "selected": true, "text": "<p>We use the following (in Log4J):</p>\n\n<pre><code>&lt;appender name=\"roller\" class=\"org.apache.log4j.DailyRollingFileAppender\"&gt;\n &lt;param name=\"File\" value=\"Applog.log\"/&gt;\n &lt;param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/&gt;\n &lt;layout class=\"org.apache.log4j.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"[slf5s.start]%d{DATE}[slf5s.DATE]%n%p[slf5s.PRIORITY]%n%x[slf5s.NDC]%n%t[slf5s.THREAD]%n%c[slf5s.CATEGORY]%n%l[slf5s.LOCATION]%n%m[slf5s.MESSAGE]%n%n\"/&gt;\n &lt;/layout&gt;\n&lt;/appender&gt;\n</code></pre>\n\n<p>This gives us <strong>Applog.log.yyyy-MM-dd</strong> files</p>\n" }, { "answer_id": 243840, "author": "Charley Rathkopf", "author_id": 10119, "author_profile": "https://Stackoverflow.com/users/10119", "pm_score": 1, "selected": false, "text": "<p>Note that is this case the</p>\n\n<pre><code> &lt;maxSizeRollBackups value=\"10\"/&gt;\n</code></pre>\n\n<p>will be ignored. </p>\n\n<p>See this <a href=\"https://stackoverflow.com/questions/95286/log4net-set-max-backup-files-on-rollingfileappender-with-rolling-date#97641\">answer</a> to a similar log4net question</p>\n" }, { "answer_id": 17752662, "author": "Junrui", "author_id": 2562431, "author_profile": "https://Stackoverflow.com/users/2562431", "pm_score": 2, "selected": false, "text": "<p>Try set this property to true:</p>\n\n<p>preserveLogFileNameExtension value=\"true\"</p>\n\n<p>I believe this trick will help you! However, preserveLogFileNameExtension property needs the latest version of log4net, you can find it here: <a href=\"http://logging.apache.org/log4net/download.html\" rel=\"nofollow\">logging.apache.org/log4net/download.html</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19977/" ]
I am configure log4net to use a composite RollingFileAppender so that the current file is always named **logfile.log** and all subsequent files are named **logfile-YYYY.MM.dd.seq.log** where **seq** is the sequence number if a log exceeds a certain size within a single day. Unfortunately, I have had very little success in configuring such a setup. **Edit:** My current configuration is pasted below. It has been updated based on several answers which gets me close enough for my needs. This generates files of the format: **logfile\_YYYY.MM.dd.log.seq** ``` <log4net> <root> <level value="DEBUG" /> <appender-ref ref="RollingFileAppender" /> </root> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs\\logfile"/> <staticLogFileName value="false"/> <appendToFile value="true"/> <rollingStyle value="Composite"/> <datePattern value="_yyyy.MM.dd&quot;.log&quot;"/> <maxSizeRollBackups value="10"/> <maximumFileSize value="75KB"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="FATAL" /> </filter> </appender> </log4net> ``` One interesting note, setting ``` <staticLogFileName value="false"/> ``` to true causes the logger to not write any files.
We use the following (in Log4J): ``` <appender name="roller" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="Applog.log"/> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[slf5s.start]%d{DATE}[slf5s.DATE]%n%p[slf5s.PRIORITY]%n%x[slf5s.NDC]%n%t[slf5s.THREAD]%n%c[slf5s.CATEGORY]%n%l[slf5s.LOCATION]%n%m[slf5s.MESSAGE]%n%n"/> </layout> </appender> ``` This gives us **Applog.log.yyyy-MM-dd** files
243,617
<p>I have a Java based web-application and a new requirement to allow Users to place variables into text fields that are replaced when a document or other output is produced. How have others gone about this?</p> <p>I was thinking of having a pre-defined set of variables such as :<br> <code>@BOOKING_NUMBER@</code><br> <code>@INVOICE_NUMBER@</code> </p> <p>Then when a user enters some text they can specify a variable inline (select it from a modal or similar). For example:</p> <p><em>"This is some text for Booking <code>@BOOKING_NUMBER@</code> that is needed by me"</em> </p> <p>When producing some output (eg. PDF) that uses this text, I would do a regex and find all variables and replace them with the correct value: </p> <p><em>"This is some text for Booking 10001 that is needed by me"</em> </p> <p>My initial thought was something like Freemarker but I think that is too complex for my Users and would require them to know my DataModel (eww).</p> <p>Thanks for reading!</p> <p>D.</p>
[ { "answer_id": 243649, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>I have used a similiar replacement token system before. I personally like something like.</p>\n\n<p>[MYVALUE]</p>\n\n<p>As it is easy for the user to type, and then I just use replacements to swap out the tokens for the real data.</p>\n" }, { "answer_id": 243781, "author": "belugabob", "author_id": 13397, "author_profile": "https://Stackoverflow.com/users/13397", "pm_score": 2, "selected": false, "text": "<p>Have a look at java.text.MessageFormat - particularly the format method - as this is designed for exactly what you are looking for.</p>\n\n<p>i.e.</p>\n\n<pre><code>MessageFormat.format(\"This is some text for booking {0} that is needed by me, for use with invoice {1}\", bookingNumber, invoiceNumber);\n</code></pre>\n\n<p>You may even want to get the template text from a resource bundle, to allow for support of multiple languages, with the added ability to cope with the fact that {0} and {1} may appear in a different order in some languages.</p>\n\n<p>UPDATE:\nI just read your original post properly, and noticed the comment about the PDF.\nThis suggest that the template text is going to be significantly larger than a line or two.</p>\n\n<p>In such cases, you may want to explore something like <a href=\"http://www.stringtemplate.org/\" rel=\"nofollow noreferrer\">StringTemplate</a> which seems better suited for this purpose - this comment is based solely on initial investigations, as I've not used it in anger.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2955/" ]
I have a Java based web-application and a new requirement to allow Users to place variables into text fields that are replaced when a document or other output is produced. How have others gone about this? I was thinking of having a pre-defined set of variables such as : `@BOOKING_NUMBER@` `@INVOICE_NUMBER@` Then when a user enters some text they can specify a variable inline (select it from a modal or similar). For example: *"This is some text for Booking `@BOOKING_NUMBER@` that is needed by me"* When producing some output (eg. PDF) that uses this text, I would do a regex and find all variables and replace them with the correct value: *"This is some text for Booking 10001 that is needed by me"* My initial thought was something like Freemarker but I think that is too complex for my Users and would require them to know my DataModel (eww). Thanks for reading! D.
Have a look at java.text.MessageFormat - particularly the format method - as this is designed for exactly what you are looking for. i.e. ``` MessageFormat.format("This is some text for booking {0} that is needed by me, for use with invoice {1}", bookingNumber, invoiceNumber); ``` You may even want to get the template text from a resource bundle, to allow for support of multiple languages, with the added ability to cope with the fact that {0} and {1} may appear in a different order in some languages. UPDATE: I just read your original post properly, and noticed the comment about the PDF. This suggest that the template text is going to be significantly larger than a line or two. In such cases, you may want to explore something like [StringTemplate](http://www.stringtemplate.org/) which seems better suited for this purpose - this comment is based solely on initial investigations, as I've not used it in anger.
243,644
<p>I have currently more than 100 connections in Sleep state.</p> <p>Some connection must stay in Sleep state (and don't close) because it's permanent connection but some others (with a different user name) are from some php script and I want them to timeout very fast.</p> <p>Is it possible to setup a wait_timeout per user? and if yes, How?</p>
[ { "answer_id": 244291, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 0, "selected": false, "text": "<p>I checked the <code>mysql.user</code> table and it doesn't look like there is a setting there for it:</p>\n\n<pre><code>+-----------------------+-----------------------------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------------------+-----------------------------------+------+-----+---------+-------+\n| Host | char(60) | NO | PRI | | |\n| User | char(16) | NO | PRI | | |\n| Password | char(41) | NO | | | |\n| Select_priv | enum('N','Y') | NO | | N | |\n| Insert_priv | enum('N','Y') | NO | | N | |\n| Update_priv | enum('N','Y') | NO | | N | |\n| Delete_priv | enum('N','Y') | NO | | N | |\n| Create_priv | enum('N','Y') | NO | | N | |\n| Drop_priv | enum('N','Y') | NO | | N | |\n| Reload_priv | enum('N','Y') | NO | | N | |\n| Shutdown_priv | enum('N','Y') | NO | | N | |\n| Process_priv | enum('N','Y') | NO | | N | |\n| File_priv | enum('N','Y') | NO | | N | |\n| Grant_priv | enum('N','Y') | NO | | N | |\n| References_priv | enum('N','Y') | NO | | N | |\n| Index_priv | enum('N','Y') | NO | | N | |\n| Alter_priv | enum('N','Y') | NO | | N | |\n| Show_db_priv | enum('N','Y') | NO | | N | |\n| Super_priv | enum('N','Y') | NO | | N | |\n| Create_tmp_table_priv | enum('N','Y') | NO | | N | |\n| Lock_tables_priv | enum('N','Y') | NO | | N | |\n| Execute_priv | enum('N','Y') | NO | | N | |\n| Repl_slave_priv | enum('N','Y') | NO | | N | |\n| Repl_client_priv | enum('N','Y') | NO | | N | |\n| Create_view_priv | enum('N','Y') | NO | | N | |\n| Show_view_priv | enum('N','Y') | NO | | N | |\n| Create_routine_priv | enum('N','Y') | NO | | N | |\n| Alter_routine_priv | enum('N','Y') | NO | | N | |\n| Create_user_priv | enum('N','Y') | NO | | N | |\n| ssl_type | enum('','ANY','X509','SPECIFIED') | NO | | | |\n| ssl_cipher | blob | NO | | | |\n| x509_issuer | blob | NO | | | |\n| x509_subject | blob | NO | | | |\n| max_questions | int(11) unsigned | NO | | 0 | |\n| max_updates | int(11) unsigned | NO | | 0 | |\n| max_connections | int(11) unsigned | NO | | 0 | |\n| max_user_connections | int(11) unsigned | NO | | 0 | |\n+-----------------------+-----------------------------------+------+-----+---------+-------+\n37 rows in set (0.00 sec)\n</code></pre>\n\n<p>Depending on whether you're using MySQLi or PDO, your PHP MySQL connections should either hang up when the request does, or be shared in a pool for the Apache process. </p>\n\n<p>For example, with PDO, to turn off persistent connections (I think this is the default), connect to your DB with:</p>\n\n<p>$pdo = new PDO($dsn, $user, $pass, Array(PDO::ATTR_PERSISTENT => false));</p>\n\n<p>If you want your scripts to use persistent connections, but you have too many connections open to your database in sleep mode, you should think about configuring your Apache's <code>MaxServers</code>, <code>MaxSpareServers</code>, <code>MinSpareServers</code> and <code>StartServers</code> so that not so many hang around when they aren't needed.</p>\n" }, { "answer_id": 244744, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 6, "selected": true, "text": "<p>There's no per-user timeout configuration, but you can set the <code>wait_timeout</code> value dynamically. That is, after you make a connection as a given user, you can issue a statement to change the timeout value to what you want it to be for that user's session.</p>\n\n<p>Try the following experiment in the mysql command-line client:</p>\n\n<pre><code>mysql&gt; SHOW VARIABLES LIKE 'wait_timeout';\n</code></pre>\n\n<p>...shows 28800 (i.e. 8 hours), which is the default <code>wait_timout</code>.</p>\n\n<pre><code>mysql&gt; SET SESSION wait_timeout = 60;\nmysql&gt; SHOW VARIABLES LIKE 'wait_timeout';\n</code></pre>\n\n<p>...shows 60.</p>\n\n<p>Then you can quit the session, reconnect, and again the default <code>wait_timeout</code> is 28800. So it's limited to the scope of the current session. </p>\n\n<p>You can also open a second window and start a separate mysql client session, to prove that changing the <code>wait_timeout</code> in one session does not affect other concurrent sessions.</p>\n" }, { "answer_id": 244804, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>Another possibility: MySQL supports two different timeout variables, <code>wait_timeout</code> for non-interactive clients, and <code>interactive_timeout</code> for interactive clients.</p>\n\n<p>The difference between interactive and non-interactive clients seems to be simply whether you specified the <code>CLIENT_INTERACTIVE</code> option when connecting.</p>\n\n<p>I don't know if this helps you, because you need to somehow make <code>mysql_real_connect()</code> pass that option in its <code>client_flag</code> parameter. I'm not sure what language or interface you're using, so I don't know if it permits you to specify this connection flag. </p>\n\n<p>Anyway if you can pass that client flag, and you only need two different types of users, then you could configure <code>wait_timeout</code> and <code>interactive_timeout</code> differently in the MySQL server config, and then use the one with the shorter value when you want a given session to time out promptly.</p>\n" }, { "answer_id": 11633830, "author": "ferensick", "author_id": 1549138, "author_profile": "https://Stackoverflow.com/users/1549138", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.percona.com/doc/percona-toolkit/2.1/pt-kill.html\" rel=\"nofollow\">http://www.percona.com/doc/percona-toolkit/2.1/pt-kill.html</a></p>\n\n<p>It is possible to kill connections per user with pt-kill. You can schedule this or set up a background job to handle this. </p>\n" }, { "answer_id": 13345116, "author": "Sych", "author_id": 1818256, "author_profile": "https://Stackoverflow.com/users/1818256", "pm_score": 3, "selected": false, "text": "<p>You should set the following variables in your <code>my.conf</code>:</p>\n\n<pre><code>[mysqld]\ninteractive_timeout=180\nwait_timeout=180\n</code></pre>\n\n<p><code>wait_timeout</code> is a timeout for <strong>automated connections</strong> (<em>in my opinion more than 30 on a web server is too much</em>).<br>\n<code>interactive_timeout</code> is a <strong>console interaction timeout</strong> for idle session.</p>\n" }, { "answer_id": 17174741, "author": "Toddius Zho", "author_id": 451621, "author_profile": "https://Stackoverflow.com/users/451621", "pm_score": 2, "selected": false, "text": "<p>If you use <a href=\"http://dev.mysql.com/doc/refman/5.5/en/connector-j-reference-configuration-properties.html\" rel=\"nofollow\">Connector/J</a>, you can use <strong>sessionVariables</strong> in the client's JDBC URL like so: <code>jdbc:mysql://hostname:3306/schema?sessionVariables=wait_timeout=600</code></p>\n\n<p>Other connectors for other languages will probably allow the same.</p>\n" }, { "answer_id": 41847505, "author": "Karthik Appigatla", "author_id": 1837866, "author_profile": "https://Stackoverflow.com/users/1837866", "pm_score": 2, "selected": false, "text": "<p>init_connect will be executed whenever a user logs in, so we can write small case statement and set the value based on user. Please note that the init_connect won't be executed for super user. </p>\n\n<p><code>mysql&gt; SET GLOBAL init_connect=\"SET @@wait_timeout = CASE WHEN CURRENT_USER() LIKE 'app1@%' THEN '30' ELSE @@wait_timeout END\";</code></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605/" ]
I have currently more than 100 connections in Sleep state. Some connection must stay in Sleep state (and don't close) because it's permanent connection but some others (with a different user name) are from some php script and I want them to timeout very fast. Is it possible to setup a wait\_timeout per user? and if yes, How?
There's no per-user timeout configuration, but you can set the `wait_timeout` value dynamically. That is, after you make a connection as a given user, you can issue a statement to change the timeout value to what you want it to be for that user's session. Try the following experiment in the mysql command-line client: ``` mysql> SHOW VARIABLES LIKE 'wait_timeout'; ``` ...shows 28800 (i.e. 8 hours), which is the default `wait_timout`. ``` mysql> SET SESSION wait_timeout = 60; mysql> SHOW VARIABLES LIKE 'wait_timeout'; ``` ...shows 60. Then you can quit the session, reconnect, and again the default `wait_timeout` is 28800. So it's limited to the scope of the current session. You can also open a second window and start a separate mysql client session, to prove that changing the `wait_timeout` in one session does not affect other concurrent sessions.
243,646
<p>I've got an <code>RSA</code> private key in <code>PEM</code> format, is there a straight forward way to read that from .NET and instantiate an <code>RSACryptoServiceProvider</code> to decrypt data encrypted with the corresponding public key?</p>
[ { "answer_id": 243685, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 5, "selected": false, "text": "<p>You might take a look at <a href=\"http://www.jensign.com/\" rel=\"noreferrer\">JavaScience's</a> source for <a href=\"https://gist.github.com/njmube/edc64bb2f7599d33ca5a\" rel=\"noreferrer\">OpenSSLKey</a></p>\n\n<p>There's code in there that does exactly what you want to do.</p>\n\n<p>In fact, they have a lot of crypto source code <a href=\"http://www.jensign.com/cryptoutils/index.html\" rel=\"noreferrer\">available here</a>.</p>\n\n<hr>\n\n<p>Source code snippet:</p>\n\n<pre><code>//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---\npublic static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)\n{\n byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;\n\n // --------- Set up stream to decode the asn.1 encoded RSA private key ------\n MemoryStream mem = new MemoryStream(privkey) ;\n BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading\n byte bt = 0;\n ushort twobytes = 0;\n int elems = 0;\n try {\n twobytes = binr.ReadUInt16();\n if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)\n binr.ReadByte(); //advance 1 byte\n else if (twobytes == 0x8230)\n binr.ReadInt16(); //advance 2 bytes\n else\n return null;\n\n twobytes = binr.ReadUInt16();\n if (twobytes != 0x0102) //version number\n return null;\n bt = binr.ReadByte();\n if (bt !=0x00)\n return null;\n\n\n //------ all private key components are Integer sequences ----\n elems = GetIntegerSize(binr);\n MODULUS = binr.ReadBytes(elems);\n\n elems = GetIntegerSize(binr);\n E = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n D = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n P = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n Q = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n DP = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n DQ = binr.ReadBytes(elems) ;\n\n elems = GetIntegerSize(binr);\n IQ = binr.ReadBytes(elems) ;\n\n Console.WriteLine(\"showing components ..\");\n if (verbose) {\n showBytes(\"\\nModulus\", MODULUS) ;\n showBytes(\"\\nExponent\", E);\n showBytes(\"\\nD\", D);\n showBytes(\"\\nP\", P);\n showBytes(\"\\nQ\", Q);\n showBytes(\"\\nDP\", DP);\n showBytes(\"\\nDQ\", DQ);\n showBytes(\"\\nIQ\", IQ);\n }\n\n // ------- create RSACryptoServiceProvider instance and initialize with public key -----\n RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();\n RSAParameters RSAparams = new RSAParameters();\n RSAparams.Modulus =MODULUS;\n RSAparams.Exponent = E;\n RSAparams.D = D;\n RSAparams.P = P;\n RSAparams.Q = Q;\n RSAparams.DP = DP;\n RSAparams.DQ = DQ;\n RSAparams.InverseQ = IQ;\n RSA.ImportParameters(RSAparams);\n return RSA;\n }\n catch (Exception) {\n return null;\n }\n finally {\n binr.Close();\n }\n}\n</code></pre>\n" }, { "answer_id": 243787, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 1, "selected": false, "text": "<p>Check <a href=\"http://msdn.microsoft.com/en-us/library/dd203099.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd203099.aspx</a></p>\n\n<p>under Cryptography Application Block.</p>\n\n<p>Don't know if you will get your answer, but it's worth a try.</p>\n\n<p><strong>Edit after Comment</strong>.</p>\n\n<p>Ok then check this code.</p>\n\n<pre><code>using System.Security.Cryptography;\n\n\npublic static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { \n X509Certificate2 myCertificate; \n try{ \n myCertificate = new X509Certificate2(PathToPrivateKeyFile); \n } catch{ \n throw new CryptographicException(\"Unable to open key file.\"); \n } \n\n RSACryptoServiceProvider rsaObj; \n if(myCertificate.HasPrivateKey) { \n rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; \n } else \n throw new CryptographicException(\"Private key not contained within certificate.\"); \n\n if(rsaObj == null) \n return String.Empty; \n\n byte[] decryptedBytes; \n try{ \n decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); \n } catch { \n throw new CryptographicException(\"Unable to decrypt data.\"); \n } \n\n // Check to make sure we decrpyted the string \n if(decryptedBytes.Length == 0) \n return String.Empty; \n else \n return System.Text.Encoding.UTF8.GetString(decryptedBytes); \n} \n</code></pre>\n" }, { "answer_id": 248662, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "<p>The stuff between the </p>\n\n<pre><code>-----BEGIN RSA PRIVATE KEY---- \n</code></pre>\n\n<p>and </p>\n\n<pre><code>-----END RSA PRIVATE KEY----- \n</code></pre>\n\n<p>is the base64 encoding of a PKCS#8 PrivateKeyInfo (unless it says RSA ENCRYPTED PRIVATE KEY in which case it is a EncryptedPrivateKeyInfo).</p>\n\n<p>It is not that hard to decode manually, but otherwise your best bet is to P/Invoke to <a href=\"http://msdn.microsoft.com/en-us/library/aa380208(VS.85).aspx\" rel=\"nofollow noreferrer\">CryptImportPKCS8</a>.</p>\n\n<hr>\n\n<p><strong>Update:</strong> The <strong><a href=\"http://msdn.microsoft.com/en-us/library/aa380208%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">CryptImportPKCS8</a></strong> function is no longer available for use as of Windows Server 2008 and Windows Vista. Instead, use the <strong><a href=\"http://msdn.microsoft.com/en-us/library/aa387314%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">PFXImportCertStore</a></strong> function.</p>\n" }, { "answer_id": 251757, "author": "Simone", "author_id": 32093, "author_profile": "https://Stackoverflow.com/users/32093", "pm_score": 7, "selected": true, "text": "<h3>Update 03/03/2021</h3>\n<p>.NET 5 now supports this out of the box.</p>\n<p>To try the code snippet below, generate a keypair and encrypt some text at <a href=\"http://travistidwell.com/jsencrypt/demo/\" rel=\"noreferrer\">http://travistidwell.com/jsencrypt/demo/</a></p>\n<pre><code>var privateKey = @&quot;-----BEGIN RSA PRIVATE KEY-----\n{ the full PEM private key } \n-----END RSA PRIVATE KEY-----&quot;;\n\nvar rsa = RSA.Create();\nrsa.ImportFromPem(privateKey.ToCharArray());\n\nvar decryptedBytes = rsa.Decrypt(\n Convert.FromBase64String(&quot;{ base64-encoded encrypted string }&quot;), \n RSAEncryptionPadding.Pkcs1\n);\n\n// this will print the original unencrypted string\nConsole.WriteLine(Encoding.UTF8.GetString(decryptedBytes));\n</code></pre>\n<h3>Original answer</h3>\n<p>I solved, thanks. In case anyone's interested, <a href=\"http://www.bouncycastle.org/\" rel=\"noreferrer\">bouncycastle</a> did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:</p>\n<pre><code>var bytesToDecrypt = Convert.FromBase64String(&quot;la0Cz.....D43g==&quot;); // string to decrypt, base64 encoded\n \nAsymmetricCipherKeyPair keyPair; \n \nusing (var reader = File.OpenText(@&quot;c:\\myprivatekey.pem&quot;)) // file containing RSA PKCS1 private key\n keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); \n \nvar decryptEngine = new Pkcs1Encoding(new RsaEngine());\ndecryptEngine.Init(false, keyPair.Private); \n \nvar decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); \n</code></pre>\n" }, { "answer_id": 5394967, "author": "SeventhPath", "author_id": 669498, "author_profile": "https://Stackoverflow.com/users/669498", "pm_score": 5, "selected": false, "text": "<p>With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is \"No, not with a PEM of the private key alone.\"</p>\n\n<p>However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.</p>\n\n<p>To generate the PFX file from the command line:</p>\n\n<pre><code>openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx\n</code></pre>\n\n<p>Then use normally with the .NET certificate class such as:</p>\n\n<pre><code>using System.Security.Cryptography.X509Certificates;\n\nX509Certificate2 combinedCertificate = new X509Certificate2(@\"C:\\path\\to\\file.pfx\");\n</code></pre>\n\n<p>Now you can follow the example from <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.aspx\" rel=\"noreferrer\">MSDN</a> for encrypting and decrypting via RSACryptoServiceProvider:</p>\n\n<p>I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: <a href=\"https://stackoverflow.com/questions/949727/bouncycastle-rsaprivatekey-to-net-rsaprivatekey\">BouncyCastle RSAPrivateKey to .NET RSAPrivateKey</a>)</p>\n\n<pre><code>X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;\nX509Certificate2 cert = new X509Certificate2(\"my.pfx\", \"somepass\", flags);\n\nRSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;\nRSAParameters rsaParam = rsa.ExportParameters(true); \n</code></pre>\n" }, { "answer_id": 19579157, "author": "The Lazy Coder", "author_id": 661229, "author_profile": "https://Stackoverflow.com/users/661229", "pm_score": 2, "selected": false, "text": "<p>ok, Im using mac to generate my self signed keys. Here is the working method I used.</p>\n\n<p>I created a shell script to speed up my key generation.</p>\n\n<p>genkey.sh</p>\n\n<pre><code>#/bin/sh\n\nssh-keygen -f host.key\nopenssl req -new -key host.key -out request.csr\nopenssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt\nopenssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name \"SslCert\"\nopenssl base64 -in private_public.p12 -out Base64.key\n</code></pre>\n\n<p>add the +x execute flag to the script</p>\n\n<pre><code>chmod +x genkey.sh\n</code></pre>\n\n<p>then call genkey.sh</p>\n\n<pre><code>./genkey.sh\n</code></pre>\n\n<p>I enter a password (important to include a password at least for the export at the end)</p>\n\n<pre><code>Enter pass phrase for host.key:\nEnter Export Password: {Important to enter a password here}\nVerifying - Enter Export Password: { Same password here }\n</code></pre>\n\n<p>I then take everything in Base64.Key and put it into a string named sslKey</p>\n\n<pre><code>private string sslKey = \"MIIJiAIBA....................................\" +\n \"......................ETC....................\" +\n \"......................ETC....................\" +\n \"......................ETC....................\" +\n \".............ugICCAA=\";\n</code></pre>\n\n<p>I then used a lazy load Property getter to get my X509 Cert with a private key.</p>\n\n<pre><code>X509Certificate2 _serverCertificate = null;\nX509Certificate2 serverCertificate{\n get\n {\n if (_serverCertificate == null){\n string pass = \"Your Export Password Here\";\n _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);\n }\n return _serverCertificate;\n }\n}\n</code></pre>\n\n<p>I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies. </p>\n\n<p>My final use for this was the SslStream to secure TCP communication to my app </p>\n\n<pre><code>SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);\n</code></pre>\n\n<p>I hope this helps other people.</p>\n\n<p><strong>NOTE</strong></p>\n\n<p>Without a password I was unable to correctly unlock the private key for export.</p>\n" }, { "answer_id": 43711671, "author": "Jack Bond", "author_id": 5875717, "author_profile": "https://Stackoverflow.com/users/5875717", "pm_score": 2, "selected": false, "text": "<p>For people who don't want to use Bouncy, and are trying some of the code included in other answers, I've found that the code works MOST of the time, but trips up on some RSA private strings, such as the one I've included below. By looking at the bouncy code, I tweaked the code provided by wprl to </p>\n\n<pre><code> RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);\n RSAparams.DP = ConvertRSAParametersField(DP, P.Length);\n RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);\n RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);\n\n private static byte[] ConvertRSAParametersField(byte[] bs, int size)\n {\n if (bs.Length == size)\n return bs;\n\n if (bs.Length &gt; size)\n throw new ArgumentException(\"Specified size too small\", \"size\");\n\n byte[] padded = new byte[size];\n Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);\n return padded;\n }\n\n-----BEGIN RSA PRIVATE KEY-----\nMIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb\nfxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ\nUHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR\nk9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y\n5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg\nJhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8\nsgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2\nXKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV\nBhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd\n+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3\noBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+\n1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E\n0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE\nURmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK\nS+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp\nq7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw\nK7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK\n7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA\nJ+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo\nk+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ\nX24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s\npeFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit\nFaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0\nNM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR\nIWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==\n-----END RSA PRIVATE KEY-----\n</code></pre>\n" }, { "answer_id": 51397431, "author": "huysentruitw", "author_id": 1300910, "author_profile": "https://Stackoverflow.com/users/1300910", "pm_score": 2, "selected": false, "text": "<p>I've created the PemUtils library that does exactly that. The code is available on <a href=\"https://github.com/huysentruitw/pem-utils\" rel=\"nofollow noreferrer\">GitHub</a> and can be installed from <a href=\"https://www.nuget.org/packages?q=pemutils\" rel=\"nofollow noreferrer\">NuGet</a>:</p>\n\n<pre><code>PM&gt; Install-Package PemUtils\n</code></pre>\n\n<p>or if you only want a DER converter:</p>\n\n<pre><code>PM&gt; Install-Package DerConverter\n</code></pre>\n\n<p>Usage for reading a RSA key from PEM data:</p>\n\n<pre><code>using (var stream = File.OpenRead(path))\nusing (var reader = new PemReader(stream))\n{\n var rsaParameters = reader.ReadRsaKey();\n // ...\n}\n</code></pre>\n" }, { "answer_id": 60423034, "author": "starteleport", "author_id": 1845402, "author_profile": "https://Stackoverflow.com/users/1845402", "pm_score": 2, "selected": false, "text": "<p>I've tried <a href=\"https://stackoverflow.com/a/251757\">the accepted answer</a> for PEM-encoded PKCS#8 RSA private key and it resulted in <code>PemException</code> with <code>malformed sequence in RSA private key</code> message. The reason is that <code>Org.BouncyCastle.OpenSsl.PemReader</code> seems to only support PKCS#1 private keys.</p>\n\n<p>I was able to get the private key by switching to <code>Org.BouncyCastle.Utilities.IO.Pem.PemReader</code> (note that type names match!) like this</p>\n\n<pre><code>private static RSAParameters GetRsaParameters(string rsaPrivateKey)\n{\n var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);\n using (var ms = new MemoryStream(byteArray))\n {\n using (var sr = new StreamReader(ms))\n {\n var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr);\n var pem = pemReader.ReadPemObject();\n var privateKey = PrivateKeyFactory.CreateKey(pem.Content);\n\n return DotNetUtilities.ToRSAParameters(privateKey as RsaPrivateCrtKeyParameters);\n }\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32093/" ]
I've got an `RSA` private key in `PEM` format, is there a straight forward way to read that from .NET and instantiate an `RSACryptoServiceProvider` to decrypt data encrypted with the corresponding public key?
### Update 03/03/2021 .NET 5 now supports this out of the box. To try the code snippet below, generate a keypair and encrypt some text at <http://travistidwell.com/jsencrypt/demo/> ``` var privateKey = @"-----BEGIN RSA PRIVATE KEY----- { the full PEM private key } -----END RSA PRIVATE KEY-----"; var rsa = RSA.Create(); rsa.ImportFromPem(privateKey.ToCharArray()); var decryptedBytes = rsa.Decrypt( Convert.FromBase64String("{ base64-encoded encrypted string }"), RSAEncryptionPadding.Pkcs1 ); // this will print the original unencrypted string Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes)); ``` ### Original answer I solved, thanks. In case anyone's interested, [bouncycastle](http://www.bouncycastle.org/) did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code: ``` var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); var decryptEngine = new Pkcs1Encoding(new RsaEngine()); decryptEngine.Init(false, keyPair.Private); var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); ```
243,683
<p>How do I extract the value of a property in a PropertyCollection?</p> <p>If I drill down on the 'Properties' in the line below is visual studion I can see the value but how do I read it?</p> <pre><code>foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(ProperyNames[0].Value.ToString()); &lt;--Wrong! } </code></pre>
[ { "answer_id": 243690, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<p>is that propertynames meant to be upper case within function?</p>\n\n<p>Reading again, i have to admit to be a little confused exactly what you're after with all these properties. Is this the class property value or an instance you're after? </p>\n" }, { "answer_id": 243703, "author": "steve", "author_id": 32103, "author_profile": "https://Stackoverflow.com/users/32103", "pm_score": -1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>foreach (string propertyName in result.Properties.PropertyNames)\n{ MessageBox.Show(properyName.ToString()); &lt;--Wrong!\n}\n</code></pre>\n" }, { "answer_id": 243705, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>foreach (string propertyName in result.Properties.PropertyNames)\n{\n MessageBox.Show(result.Properties[propertyName].ToString());\n}\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>foreach (object prop in result.Properties)\n{\n MessageBox.Show(prop.ToString());\n}\n</code></pre>\n\n<p>Also: there are a couple different PropertyCollections classes in the framework. These examples are based on the System.Data class, but you might also be using the System.DirectoryServices class. However, neither of those classes are really \"reflection\". Reflection refers to something different- namely the System.Reflection namespace plus a couple special operators.</p>\n" }, { "answer_id": 243715, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The PropertyNames is not in uppercase elsewhere, the code below works and would show the name of the property but I want to read the value. 'PropertyName' is just a string.</p>\n\n<pre><code>foreach (string propertyName in result.Properties.PropertyNames)\n{\n MessageBox.Show(PropertyName.ToString());\n}\n</code></pre>\n" }, { "answer_id": 243725, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 0, "selected": false, "text": "<p>I'm not certain what you're asking for, but I think the problem is that you're seeing the property names instead of their values?</p>\n\n<p>If so, the reason is that you're enumerating through the PropertyCollection.PropertyNames collection and not the PropertyCollection.Values collection. Try something like this instead:</p>\n\n<pre><code>foreach (object value in result.Properties.Values)\n{ \n MessageBox.Show(property.ToString());\n}\n</code></pre>\n\n<hr>\n\n<p><em>I was assuming that this question referred to the System.DirectoryServices.PropertyCollection class and not System.Data.PropertyCollection because of the reference to PropertyNames, but now I'm not so sure. If the question is about the System.Data version then disregard this answer.</em></p>\n" }, { "answer_id": 243741, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": "<p>Vb.NET</p>\n\n<pre><code>For Each prop As String In result.Properties.PropertyNames\n MessageBox.Show(result.Properties(prop).Item(0), result.Item(i).Properties(prt).Item(0))\nNext\n</code></pre>\n\n<p>I think C# looks like this...</p>\n\n<pre><code>foreach (string property in result.Properties.PropertyNames)\n{\n MessageBox.Show(result.Properties[property].Item[0]);\n}\n</code></pre>\n\n<p>As noted above, there are a few different property collections in the framework.</p>\n" }, { "answer_id": 243785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Using a few hints from above I managed to get what I needed using the code below: </p>\n\n<pre><code> ResultPropertyValueCollection values = result.Properties[propertyName];\n if (propertyName == \"abctest\")\n { \n MessageBox.Show(values[0].ToString());\n }\n</code></pre>\n\n<p>Thanks to all.</p>\n" }, { "answer_id": 243813, "author": "GalacticCowboy", "author_id": 29638, "author_profile": "https://Stackoverflow.com/users/29638", "pm_score": 0, "selected": false, "text": "<p>If you put the value collection inside your \"if\", you would only retrieve it when you actually need it rather than every time through the loop. Just a suggestion... :)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I extract the value of a property in a PropertyCollection? If I drill down on the 'Properties' in the line below is visual studion I can see the value but how do I read it? ``` foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(ProperyNames[0].Value.ToString()); <--Wrong! } ```
Try this: ``` foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(result.Properties[propertyName].ToString()); } ``` Or this: ``` foreach (object prop in result.Properties) { MessageBox.Show(prop.ToString()); } ``` Also: there are a couple different PropertyCollections classes in the framework. These examples are based on the System.Data class, but you might also be using the System.DirectoryServices class. However, neither of those classes are really "reflection". Reflection refers to something different- namely the System.Reflection namespace plus a couple special operators.
243,691
<p>[Error] WARNING. Duplicate resource(s): [Error] Type 2 (BITMAP), ID TWWDBRICHEDITMSWORD: [Error] File C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource kept; file C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource discarded. I have searched the code for same named objects, like objects. Can anyone give me a clue what else I can look for. </p>
[ { "answer_id": 243890, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p>Two units both using the same resource file. Probably looks like this:</p>\n\n<pre><code>{$R wwrichsp.RES}\n</code></pre>\n" }, { "answer_id": 856516, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>wwrichedspellxp, wwrichedspell2000; 这两个同时存在时就出错。Delete wwrichedspellxp 就OK</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[Error] WARNING. Duplicate resource(s): [Error] Type 2 (BITMAP), ID TWWDBRICHEDITMSWORD: [Error] File C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource kept; file C:\Borland\Delphi7\ip4000vcl7\LIB\wwrichsp.RES resource discarded. I have searched the code for same named objects, like objects. Can anyone give me a clue what else I can look for.
Two units both using the same resource file. Probably looks like this: ``` {$R wwrichsp.RES} ```
243,696
<p>MathWorks currently doesn't allow you to use <code>cout</code> from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, <a href="http://www.mathworks.com/support/tech-notes/1600/1605.html" rel="nofollow noreferrer">mexPrintf, that they request you use instead</a>. After googling around a bit, I think that it's possible to extend the <code>std::stringbuf</code> class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use <code>std::cout</code> as normal if this code is not linked against a mex executable)</p> <pre><code>class mstream : public stringbuf { public: virtual streamsize xsputn(const char *s, std::streamsize n) { mexPrintf("*s",s,n); return basic_streambuf&lt;char, std::char_traits&lt;char&gt;&gt;::xsputn(s,n); } }; mstream mout; outbuf = cout.rdbuf(mout.rdbuf()); </code></pre>
[ { "answer_id": 244286, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 0, "selected": false, "text": "<p><code>cout</code> is a particular character output stream. If you want a <code>cout</code> that writes to a file, use an <a href=\"http://www.cplusplus.com/reference/iostream/fstream/\" rel=\"nofollow noreferrer\"><code>fstream</code></a>, particularly an <a href=\"http://www.cplusplus.com/reference/iostream/ofstream/\" rel=\"nofollow noreferrer\"><code>ofstream</code></a>. They have the same interface that <code>cout</code> provides. Additionally, if you want to grab their buffer (with <code>rdbuf</code>) you can.</p>\n" }, { "answer_id": 244584, "author": "Shane Powell", "author_id": 23235, "author_profile": "https://Stackoverflow.com/users/23235", "pm_score": 4, "selected": true, "text": "<p>You don't really want to overload <code>std::stringbuf</code>, you want to overload <code>std::streambuf</code> or <code>std::basic_streambuf</code> (if you want to support multiple character types), also you need to override the overflow method as well.</p>\n\n<p>But I also think you need to rethink your solution to your problem.</p>\n\n<p><code>cout</code> is just an <code>ostream</code>, so if all classes / functions takes an <code>ostream</code> then you can pass in anything you like. e.g. <code>cout</code>, <code>ofstream</code>, etc</p>\n\n<p>If that's too hard then I would create my own version of <code>cout</code>, maybe called <code>mycout</code> that can be defined at either compiler time or runtime time (depending on what you want to do).</p>\n\n<p>A simple solution may be:</p>\n\n<pre><code>#include &lt;streambuf&gt;\n#include &lt;ostream&gt;\n\nclass mystream : public std::streambuf\n{\npublic:\n mystream() {}\n\nprotected:\n virtual int_type overflow(int_type c)\n {\n if(c != EOF)\n {\n char z = c;\n mexPrintf(\"%c\",c);\n return EOF;\n }\n return c;\n }\n\n virtual std::streamsize xsputn(const char* s, std::streamsize num)\n {\n mexPrintf(\"*s\",s,n);\n return num;\n }\n};\n\nclass myostream : public std::ostream\n{\nprotected:\n mystream buf;\n\npublic:\n myostream() : std::ostream(&amp;buf) {}\n};\n\nmyostream mycout;\n</code></pre>\n\n<p>And the cout version could just be:</p>\n\n<pre><code>typedef std::cout mycout;\n</code></pre>\n\n<p>A runtime version is a bit more work but easily doable.</p>\n" }, { "answer_id": 249008, "author": "user27315", "author_id": 27315, "author_profile": "https://Stackoverflow.com/users/27315", "pm_score": 3, "selected": false, "text": "<p>Shane, thanks very much for your help. Here's my final working implementation.</p>\n\n<pre><code>class mstream : public std::streambuf {\npublic:\nprotected:\n virtual std::streamsize xsputn(const char *s, std::streamsize n); \n virtual int overflow(int c = EOF);\n}; \n</code></pre>\n\n<p>...</p>\n\n<pre><code>std::streamsize \nmstream::xsputn(const char *s, std::streamsize n) \n{\n mexPrintf(\"%.*s\",n,s);\n return n;\n}\n\nint \nmstream::overflow(int c) \n{\n if (c != EOF) {\n mexPrintf(\"%.1s\",&amp;c);\n }\n return 1;\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>// Replace the std stream with the 'matlab' stream\n// Put this in the beginning of the mex function\nmstream mout;\nstd::streambuf *outbuf = std::cout.rdbuf(&amp;mout); \n</code></pre>\n\n<p>...</p>\n\n<pre><code>// Restore the std stream buffer \nstd::cout.rdbuf(outbuf); \n</code></pre>\n" }, { "answer_id": 41276477, "author": "Cris Luengo", "author_id": 7328782, "author_profile": "https://Stackoverflow.com/users/7328782", "pm_score": 2, "selected": false, "text": "<p>I have changed the OP's final implementation a little bit, adding a constructor and destructor. Creating an object of this class automatically replaces the stream buffer in <code>std::cout</code>, and when the object goes out of scope, the original stream buffer is restored. RAII!</p>\n\n<pre><code>class mxstreambuf : public std::streambuf {\n public:\n mxstreambuf() {\n stdoutbuf = std::cout.rdbuf( this );\n }\n ~mxstreambuf() {\n std::cout.rdbuf( stdoutbuf );\n }\n protected:\n virtual std::streamsize xsputn( const char* s, std::streamsize n ) override {\n mexPrintf( \"%.*s\", n, s );\n return n;\n }\n virtual int overflow( int c = EOF ) override {\n if( c != EOF ) {\n mexPrintf( \"%.1s\", &amp; c );\n }\n return 1;\n }\n private:\n std::streambuf *stdoutbuf;\n};\n</code></pre>\n\n<p>To use the stream buffer in a MEX-file, simply:</p>\n\n<pre><code>mxstreambuf mout;\nstd::cout &lt;&lt; \"Hello World!\\n\";\n</code></pre>\n\n<p>... and don't worry about forgetting anything.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27315/" ]
MathWorks currently doesn't allow you to use `cout` from a mex file when the MATLAB desktop is open because they have redirected stdout. Their current workaround is providing a function, [mexPrintf, that they request you use instead](http://www.mathworks.com/support/tech-notes/1600/1605.html). After googling around a bit, I think that it's possible to extend the `std::stringbuf` class to do what I need. Here's what I have so far. Is this robust enough, or are there other methods I need to overload or a better way to do this? (Looking for portability in a general UNIX environment and the ability to use `std::cout` as normal if this code is not linked against a mex executable) ``` class mstream : public stringbuf { public: virtual streamsize xsputn(const char *s, std::streamsize n) { mexPrintf("*s",s,n); return basic_streambuf<char, std::char_traits<char>>::xsputn(s,n); } }; mstream mout; outbuf = cout.rdbuf(mout.rdbuf()); ```
You don't really want to overload `std::stringbuf`, you want to overload `std::streambuf` or `std::basic_streambuf` (if you want to support multiple character types), also you need to override the overflow method as well. But I also think you need to rethink your solution to your problem. `cout` is just an `ostream`, so if all classes / functions takes an `ostream` then you can pass in anything you like. e.g. `cout`, `ofstream`, etc If that's too hard then I would create my own version of `cout`, maybe called `mycout` that can be defined at either compiler time or runtime time (depending on what you want to do). A simple solution may be: ``` #include <streambuf> #include <ostream> class mystream : public std::streambuf { public: mystream() {} protected: virtual int_type overflow(int_type c) { if(c != EOF) { char z = c; mexPrintf("%c",c); return EOF; } return c; } virtual std::streamsize xsputn(const char* s, std::streamsize num) { mexPrintf("*s",s,n); return num; } }; class myostream : public std::ostream { protected: mystream buf; public: myostream() : std::ostream(&buf) {} }; myostream mycout; ``` And the cout version could just be: ``` typedef std::cout mycout; ``` A runtime version is a bit more work but easily doable.
243,712
<p>Hey! I was looking at this code at <a href="http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html" rel="noreferrer">http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html</a></p> <p>I noticed that in some situations they used hex numbers, like in line 134:</p> <pre><code>for (j = 1; val &amp;&amp; j &lt;= 0x80; j &lt;&lt;= 1, q++) </code></pre> <p>Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80.</p> <p>Also before line 134, on line 114 they have this:</p> <pre><code>small_n = (n &amp; 0xffff0000) == 0; </code></pre> <p>The hex to decimal gave me 4294901760 for that hex number. So here in this line they are making a bit AND and comparing the result to 0??</p> <p>Why not just use the number? Can anyone please explain and please do give examples of other situations.</p> <p>Also I have seen large lines of code where it's just hex numbers and never really understood why :(</p>
[ { "answer_id": 243727, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 8, "selected": true, "text": "<p>In both cases you cite, the bit pattern of the number is important, not the actual number.</p>\n<p>For example,\nIn the first case,\n<code>j</code> is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses.</p>\n<p>In binary, that is,</p>\n<p><code>0000:0001</code>, <code>0000:0010</code>, <code>0000:0100</code>, <code>0000:1000</code>, <code>0001:0000</code>, <code>0010:0000</code>, <code>0100:0000</code> and <code>1000:0000</code>.</p>\n<p>There's no option for binary constants in C (until C23) or C++ (until C++14), but it's a bit clearer in Hex:\n<code>0x01</code>, <code>0x02</code>, <code>0x04</code>, <code>0x08</code>, <code>0x10</code>, <code>0x20</code>, <code>0x40</code>, and <code>0x80</code>.</p>\n<p>In the second example,\nthe goal was to remove the lower two bytes of the value.\nSo given a value of 1,234,567,890 we want to end up with 1,234,567,168.<br />\nIn hex, it's clearer: start with <code>0x4996:02d2</code>, end with <code>0x4996:0000</code>.</p>\n" }, { "answer_id": 243729, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 4, "selected": false, "text": "<p>its a bit mask. Hex values make it easy to see the underlying binary representation. n &amp; <code>0xffff0000</code> returns the top 16 bits of n. <code>0xffff0000</code> means \"16 1s and 16 0s in binary\"</p>\n\n<p><code>0x80</code> means \"1000000\", so you start with \"00000001\" and continue shifting that bit over to the left \"0000010\", \"0000100\", etc until \"1000000\"</p>\n" }, { "answer_id": 243732, "author": "Jim C", "author_id": 21706, "author_profile": "https://Stackoverflow.com/users/21706", "pm_score": 2, "selected": false, "text": "<p>Hex, or hexadecimal, numbers represent 4 bits of data, 0 to 15 or in HEX 0 to F. Two hex values represent a byte.</p>\n" }, { "answer_id": 243733, "author": "Michał Piaskowski", "author_id": 1534, "author_profile": "https://Stackoverflow.com/users/1534", "pm_score": 4, "selected": false, "text": "<p>0xffff0000 is easy to understand that it's 16 times \"1\" and 16 times \"0\" in a 32 bit value, while 4294901760 is magic.</p>\n" }, { "answer_id": 243745, "author": "Tim", "author_id": 10755, "author_profile": "https://Stackoverflow.com/users/10755", "pm_score": 3, "selected": false, "text": "<p>Sometimes the visual representation of values in HEX makes code more readable or understandable. For instance bitmasking or use of bits becomes non-obvious when looking at decimal representations of numbers. </p>\n\n<p>This can sometimes do with the amount of space a particular value type has to offer, so that may also play a role.</p>\n\n<p>A typical example might be in a binary setting, so instead of using decimal to show some values, we use binary. </p>\n\n<p>let's say an object had a non-exclusive set of properties that had values of either on or off (3 of them) - one way to represent the state of those properties is with 3 bits. </p>\n\n<p>valid representations are 0 through 7 in decimal, but that is not so obvious. more obvious is the binary representation:</p>\n\n<p>000, 001, 010, 011, 100, 101, 110, 111</p>\n\n<p>Also, some people are just very comfortable with hex. Note also that hard-coded magic numbers are just that and it is not all that important no matter numbering system to use</p>\n\n<p>I hope that helps.</p>\n" }, { "answer_id": 243767, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "<p>Looking at the file, that's some pretty groady code. Hope you are good at C and not using it as a tutorial...</p>\n\n<p>Hex is useful when you're directly working at the bit level or just above it. E.g, working on a driver where you're looking directly at the bits coming in from a device and twiddling the results so that someone else can read a coherent result. It's a compact fairly easy-to-read representation of binary.</p>\n" }, { "answer_id": 243772, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "<p>There's a direct mapping between hex (or octal for that matter) digits and the underlying bit patterns, which is not the case with decimal. A decimal '9' represents something different with respect to bit patterns depending on what column it is in and what numbers surround it - it doesn't have a direct relationship to a bit pattern. In hex, a '9' always means '1001', no matter which column. 9 = '1001', 95 = '*1001*0101' and so forth. </p>\n\n<p>As a vestige of my 8-bit days I find hex a convenient shorthand for anything binary. Bit twiddling is a dying skill. Once (about 10 years ago) I saw a third year networking paper at university where only 10% (5 out of 50 or so) of the people in the class could calculate a bit-mask.</p>\n" }, { "answer_id": 243783, "author": "Lucas Gabriel Sánchez", "author_id": 20601, "author_profile": "https://Stackoverflow.com/users/20601", "pm_score": 3, "selected": false, "text": "<p>Generally the use of Hex numbers instead of Decimal it's because the computer works with bits (binary numbers) and when you're working with bits also is more understandable to use Hexadecimal numbers, because is easier going from Hex to binary that from Decimal to binary.</p>\n\n<pre><code>OxFF = 1111 1111 ( F = 1111 )\n</code></pre>\n\n<p>but </p>\n\n<pre><code>255 = 1111 1111 \n</code></pre>\n\n<p>because </p>\n\n<pre><code>255 / 2 = 127 (rest 1)\n127 / 2 = 63 (rest 1)\n63 / 2 = 31 (rest 1)\n... etc\n</code></pre>\n\n<p>Can you see that? It's much more simple to pass from Hex to binary.</p>\n" }, { "answer_id": 244020, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>I find it maddening that the C family of languages have always supported octal and hex but not binary. I have long wished that they would add direct support for binary:</p>\n\n<pre><code>int mask = 0b00001111;\n</code></pre>\n\n<p>Many years/jobs ago, while working on a project that involved an enormous amount of bit-level math, I got fed up and generated a header file that contained defined constants for all possible binary values up to 8 bits:</p>\n\n<pre><code>#define b0 (0x00)\n#define b1 (0x01)\n#define b00 (0x00)\n#define b01 (0x01)\n#define b10 (0x02)\n#define b11 (0x03)\n#define b000 (0x00)\n#define b001 (0x01)\n...\n#define b11111110 (0xFE)\n#define b11111111 (0xFF)\n</code></pre>\n\n<p>It has occasionally made certain bit-level code more readable.</p>\n" }, { "answer_id": 244074, "author": "mkClark", "author_id": 30970, "author_profile": "https://Stackoverflow.com/users/30970", "pm_score": 3, "selected": false, "text": "<p>The single biggest use of hex is probably in embedded programming. Hex numbers are used to mask off individual bits in hardware registers, or split multiple numeric values packed into a single 8, 16, or 32-bit register.</p>\n\n<p>When specifying individual bit masks, a lot of people start out by:</p>\n\n<pre><code>#define bit_0 1\n#define bit_1 2\n#define bit_2 4\n#define bit_3 8\n#define bit_4 16\netc...\n</code></pre>\n\n<p>After a while, they advance to:</p>\n\n<pre><code>#define bit_0 0x01\n#define bit_1 0x02\n#define bit_2 0x04\n#define bit_3 0x08\n#define bit_4 0x10\netc...\n</code></pre>\n\n<p>Then they learn to cheat, and let the compiler generate the values as part of compile time optimization:</p>\n\n<pre><code>#define bit_0 (1&lt;&lt;0)\n#define bit_1 (1&lt;&lt;1)\n#define bit_2 (1&lt;&lt;2)\n#define bit_3 (1&lt;&lt;3)\n#define bit_4 (1&lt;&lt;4)\netc...\n</code></pre>\n" }, { "answer_id": 244233, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 2, "selected": false, "text": "<p>To be more precise, hex and decimal, are all NUMBERS. The radix (base 10, 16, etc) are ways to present those numbers in a manner that is either clearer, or more convenient.</p>\n\n<p>When discussing \"how many of something there are\" we normally use decimal. When we are looking at addresses or bit patterns on computers, hex is usually preferred, because often the meaning of individual bytes might be important. </p>\n\n<p>Hex, (and octal) have the property that they are powers of two, so they map groupings of bit nicely. Hex maps 4 bits to one hex nibble (0-F), so a byte is stored in two nibbles (00-FF). Octal was popular on Digital Equipment (DEC) and other older machines, but one octal digit maps to three bits, so it doesn't cross byte boundaries as nicely.</p>\n\n<p>Overall, the choice of radix is a way to make your programming easier - use the one that matches the domain best.</p>\n" }, { "answer_id": 248849, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 2, "selected": false, "text": "<p>There are 8 bits in a byte. Hex, base 16, is terse. Any possible byte value is expressed using two characters from the collection 0..9, plus a,b,c,d,e,f.</p>\n\n<p>Base 256 would be more terse. Every possible byte could have its own single character, but most human languages don't use 256 characters, so Hex is the winner.</p>\n\n<p>To understand the importance of being terse, consider that back in the 1970's, when you wanted to examine your megabyte of memory, it was printed out in hex. The printout would use several thousand pages of big paper. Octal would have wasted even more trees.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
Hey! I was looking at this code at <http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html> I noticed that in some situations they used hex numbers, like in line 134: ``` for (j = 1; val && j <= 0x80; j <<= 1, q++) ``` Now why would they use the 0x80? I am not that good with hex but I found an online hex to decimal and it gave me 128 for 0x80. Also before line 134, on line 114 they have this: ``` small_n = (n & 0xffff0000) == 0; ``` The hex to decimal gave me 4294901760 for that hex number. So here in this line they are making a bit AND and comparing the result to 0?? Why not just use the number? Can anyone please explain and please do give examples of other situations. Also I have seen large lines of code where it's just hex numbers and never really understood why :(
In both cases you cite, the bit pattern of the number is important, not the actual number. For example, In the first case, `j` is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses. In binary, that is, `0000:0001`, `0000:0010`, `0000:0100`, `0000:1000`, `0001:0000`, `0010:0000`, `0100:0000` and `1000:0000`. There's no option for binary constants in C (until C23) or C++ (until C++14), but it's a bit clearer in Hex: `0x01`, `0x02`, `0x04`, `0x08`, `0x10`, `0x20`, `0x40`, and `0x80`. In the second example, the goal was to remove the lower two bytes of the value. So given a value of 1,234,567,890 we want to end up with 1,234,567,168. In hex, it's clearer: start with `0x4996:02d2`, end with `0x4996:0000`.
243,728
<p>I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?</p>
[ { "answer_id": 243747, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 5, "selected": true, "text": "<p>You should be able to specify your own EntityResolver, or use specific features of your parser? See <a href=\"https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references\">here</a> for some approaches.</p>\n\n<p>A more complete example:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE foo PUBLIC \"//FOO//\" \"foo.dtd\"&gt;\n&lt;foo&gt;\n &lt;bar&gt;Value&lt;/bar&gt;\n&lt;/foo&gt;\n</code></pre>\n\n<p>And xpath usage:</p>\n\n<pre><code>import java.io.File;\nimport java.io.IOException;\nimport java.io.StringReader;\n\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathFactory;\n\nimport org.w3c.dom.Document;\nimport org.xml.sax.EntityResolver;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = factory.newDocumentBuilder();\n\n builder.setEntityResolver(new EntityResolver() {\n\n @Override\n public InputSource resolveEntity(String publicId, String systemId)\n throws SAXException, IOException {\n System.out.println(\"Ignoring \" + publicId + \", \" + systemId);\n return new InputSource(new StringReader(\"\"));\n }\n });\n Document document = builder.parse(new File(\"src/foo.xml\"));\n XPathFactory xpathFactory = XPathFactory.newInstance();\n XPath xpath = xpathFactory.newXPath();\n String content = xpath.evaluate(\"/foo/bar/text()\", document\n .getDocumentElement());\n System.out.println(content);\n }\n}\n</code></pre>\n\n<p>Hope this helps...</p>\n" }, { "answer_id": 243757, "author": "Owen", "author_id": 2109, "author_profile": "https://Stackoverflow.com/users/2109", "pm_score": 2, "selected": false, "text": "<p>I had this problem before. I solved it by downloading and storing a local copy of the DTD and then validating against the local copy. You need to edit the XML file to point to the local copy.</p>\n\n<pre><code>&lt;!DOCTYPE root-element SYSTEM \"filename\"&gt;\n</code></pre>\n\n<p>Little more info here: <a href=\"http://www.w3schools.com/dtd/dtd_intro.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/dtd/dtd_intro.asp</a></p>\n\n<p>I think you can also manually set some sort of validateOnParse property to \"false\" in your parser. Depends on what library you're using to parse the XML.</p>\n\n<p>More info here: <a href=\"http://www.w3schools.com/dtd/dtd_validation.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/dtd/dtd_validation.asp</a></p>\n" }, { "answer_id": 2357979, "author": "David", "author_id": 98109, "author_profile": "https://Stackoverflow.com/users/98109", "pm_score": 4, "selected": false, "text": "<p>This worked for me:</p>\n\n<pre><code> SAXParserFactory saxfac = SAXParserFactory.newInstance();\n saxfac.setValidating(false);\n try {\n saxfac.setFeature(\"http://xml.org/sax/features/validation\", false);\n saxfac.setFeature(\"http://apache.org/xml/features/nonvalidating/load-dtd-grammar\", false);\n saxfac.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n saxfac.setFeature(\"http://xml.org/sax/features/external-general-entities\", false);\n saxfac.setFeature(\"http://xml.org/sax/features/external-parameter-entities\", false);\n }\n catch (Exception e1) {\n e1.printStackTrace();\n }\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30453/" ]
I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?
You should be able to specify your own EntityResolver, or use specific features of your parser? See [here](https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references) for some approaches. A more complete example: ``` <?xml version="1.0"?> <!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd"> <foo> <bar>Value</bar> </foo> ``` And xpath usage: ``` import java.io.File; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Main { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { System.out.println("Ignoring " + publicId + ", " + systemId); return new InputSource(new StringReader("")); } }); Document document = builder.parse(new File("src/foo.xml")); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); String content = xpath.evaluate("/foo/bar/text()", document .getDocumentElement()); System.out.println(content); } } ``` Hope this helps...
243,750
<p>I've searched around a bit for similar questions, but other than running one command or perhaps a few command with items such as:</p> <pre><code>ssh user@host -t sudo su - </code></pre> <p>However, what if I essentially need to run a script on (let's say) 15 servers at once. Is this doable in bash? In a perfect world I need to avoid installing applications if at all possible to pull this off. For argument's sake, let's just say that I need to do the following across 10 hosts:</p> <ol> <li>Deploy a new Tomcat container</li> <li>Deploy an application in the container, and configure it</li> <li>Configure an Apache vhost</li> <li>Reload Apache</li> </ol> <p>I have a script that does all of that, but it relies on me logging into all the servers, pulling a script down from a repo, and then running it. If this isn't doable in bash, what alternatives do you suggest? Do I need a bigger hammer, such as Perl (Python might be preferred since I can guarantee Python is on all boxes in a RHEL environment thanks to yum/up2date)? If anyone can point to me to any useful information it'd be greatly appreciated, especially if it's doable in bash. I'll settle for Perl or Python, but I just don't know those as well (working on that). Thanks!</p>
[ { "answer_id": 243756, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 2, "selected": false, "text": "<p>To give you the structure, without actual code.</p>\n\n<ol>\n<li>Use scp to copy your install/setup script to the target box.</li>\n<li>Use ssh to invoke your script on the remote box.</li>\n</ol>\n" }, { "answer_id": 243770, "author": "m104", "author_id": 4039, "author_profile": "https://Stackoverflow.com/users/4039", "pm_score": 1, "selected": false, "text": "<p>Although it's a complex topic, I can highly recommend <a href=\"http://capistranorb.com/\" rel=\"nofollow noreferrer\">Capistrano</a>.</p>\n" }, { "answer_id": 243792, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 1, "selected": false, "text": "<p>You can do it the same way you did before, just script it instead of doing it manually. The following code remotes to machine named 'loca' and runs two commands there. What you need to do is simply insert commands you want to run there.</p>\n\n<pre>che@ovecka ~ $ ssh loca 'uname -a; echo something_else'\nLinux loca 2.6.25.9 #1 (blahblahblah)\nsomething_else</pre>\n\n<p>Then, to iterate through all the machines, do something like:</p>\n\n<pre>for box in box1_name box2_name box3_name\ndo\n ssh $box 'commmands_to_run_everywhere'\ndone</pre>\n\n<p>In order to make this ssh thing work without entering passwords all the time, you'll need to set up key authentication. You can read about it at <a href=\"http://www.ibm.com/developerworks/library/l-keyc.html\" rel=\"nofollow noreferrer\">IBM developerworks</a>.</p>\n" }, { "answer_id": 243797, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 1, "selected": false, "text": "<p>You can run the same command on several servers at once with a tool like <a href=\"http://debaday.debian.net/2007/12/09/clusterssh-control-serveral-ssh-sessions-via-a-single-interface/\" rel=\"nofollow noreferrer\" title=\"cluster ssh\">cluster ssh</a>. The link is to a discussion of cluster ssh on the Debian package of the day blog.</p>\n" }, { "answer_id": 243803, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 3, "selected": false, "text": "<p>Take a look at Expect (<code>man expect</code>)</p>\n\n<p>I've accomplished similar tasks in the past using Expect.</p>\n" }, { "answer_id": 243818, "author": "Yang Zhao", "author_id": 31095, "author_profile": "https://Stackoverflow.com/users/31095", "pm_score": 3, "selected": false, "text": "<p>You can pipe the local script to the remote server and execute it with one command:</p>\n\n<pre><code>ssh -t user@host 'sh' &lt; path_to_script\n</code></pre>\n\n<p>This can be further automated by using public key authentication and wrapping with scripts to perform parallel execution.</p>\n" }, { "answer_id": 243917, "author": "Bash", "author_id": 16051, "author_profile": "https://Stackoverflow.com/users/16051", "pm_score": 4, "selected": false, "text": "<p>You can run a local script as shown by che and Yang, and/or you can use a Here document:</p>\n\n<pre><code>ssh root@server /bin/sh &lt;&lt;\\EOF \nwget http://server/warfile # Could use NFS here \ncp app.war /location \ncommand 1 \ncommand 2 \n/etc/init.d/httpd restart \nEOF \n</code></pre>\n" }, { "answer_id": 243928, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": true, "text": "<p>Often, I'll just use the original Tcl version of Expect. You only need to have that on the local machine. If I'm inside a program using Perl, I do this with <a href=\"http://search.cpan.org/dist/Net-SSH-Expect/\" rel=\"noreferrer\">Net::SSH::Expect</a>. Other languages have similar \"expect\" tools.</p>\n" }, { "answer_id": 244136, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 1, "selected": false, "text": "<p>Well, for step 1 and 2 isn't there a tomcat manager web interface; you could script that with curl or zsh with the libwww plug in.</p>\n\n<p>For SSH you're looking to:\n1) not get prompted for a password (use keys)\n2) pass the command(s) on SSH's commandline, this is similar to <code>rsh</code> in a trusted network.</p>\n\n<p>Other posts have shown you what to do, and I'd probably use <code>sh</code> too but I'd be tempted to use <code>perl</code> like <code>ssh tomcatuser@server perl -e 'do-everything-on-one-line;'</code> or you could do this:</p>\n\n<p><strong>either</strong> <code>scp the_package.tbz tomcatuser@server:the_place/.</code><br/>\n<code>ssh tomcatuser@server /bin/sh &lt;&lt;\\EOF</code><br/>\n<em>define stuff like</em> <code>TOMCAT_WEBAPPS=/usr/local/share/tomcat/webapps</code><br/>\n<code>tar xj the_package.tbz</code> <strong>or</strong> <code>rsync rsync://repository/the_package_place</code><br/>\n<code>mv $TOMCAT_WEBAPPS/old_war $TOMCAT_WEBAPPS/old_war.old</code><br/>\n<code>mv $THE_PLACE/new_war $TOMCAT_WEBAPPS/new_war</code><br/>\n<code>touch $TOMCAT_WEBAPPS/new_war</code> [you don't normally have to restart tomcat]<br/>\n<code>mv $THE_PLACE/vhost_file $APACHE_VHOST_DIR/vhost_file</code><br/>\n<code>$APACHECTL restart</code> [might need to login as apache user to move that file and restart]<br/>\n<code>EOF</code><br/></p>\n" }, { "answer_id": 245114, "author": "Philip Durbin", "author_id": 19464, "author_profile": "https://Stackoverflow.com/users/19464", "pm_score": 3, "selected": false, "text": "<p>The issue of how to run commands on many servers at once came up on a Perl mailing list the other day and I'll give the same recommendation <a href=\"http://www.nntp.perl.org/group/perl.beginners/2008/10/msg104506.html\" rel=\"nofollow noreferrer\">I gave there</a>, which is to use <code>gsh</code>: </p>\n\n<p><a href=\"http://outflux.net/unix/software/gsh\" rel=\"nofollow noreferrer\">http://outflux.net/unix/software/gsh</a></p>\n\n<p>gsh is similar to the \"<code>for box in box1_name box2_name box3_name</code>\" solution <a href=\"https://stackoverflow.com/a/243792/32453\">already given</a> but I find gsh to be more convenient. You set up a /etc/ghosts file containing your servers in groups such as web, db, RHEL4, x86_64, or whatever (man ghosts) then you use that group when you call gsh.</p>\n\n<pre><code>[pdurbin@beamish ~]$ gsh web \"cat /etc/redhat-release; uname -r\"\nwww-2.foo.com: Red Hat Enterprise Linux AS release 4 (Nahant Update 7)\nwww-2.foo.com: 2.6.9-78.0.1.ELsmp\nwww-3.foo.com: Red Hat Enterprise Linux AS release 4 (Nahant Update 7)\nwww-3.foo.com: 2.6.9-78.0.1.ELsmp\nwww-4.foo.com: Red Hat Enterprise Linux Server release 5.2 (Tikanga)\nwww-4.foo.com: 2.6.18-92.1.13.el5\nwww-5.foo.com: Red Hat Enterprise Linux Server release 5.2 (Tikanga)\nwww-5.foo.com: 2.6.18-92.1.13.el5\n[pdurbin@beamish ~]$\n</code></pre>\n\n<p>You can also combine or split ghost groups, using web+db or web-RHEL4, for example.</p>\n\n<p>I'll also mention that while I have never used shmux, <a href=\"http://web.taranis.org/shmux\" rel=\"nofollow noreferrer\">its website</a> contains a list of software (including gsh) that lets you run commands on many servers at once. <a href=\"http://www.capify.org\" rel=\"nofollow noreferrer\">Capistrano</a> has already been mentioned and (from what I understand) could be on that list as well.</p>\n" }, { "answer_id": 247048, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 1, "selected": false, "text": "<p>You want DSH or distributed shell, which is used in clusters a lot. Here is the link: <a href=\"http://www.netfort.gr.jp/~dancer/software/dsh.html.en\" rel=\"nofollow noreferrer\">dsh</a></p>\n\n<p>You basically have node groups (a file with lists of nodes in them) and you specify which node group you wish to run commands on then you would use dsh, like you would ssh to run commands on them.</p>\n\n<pre><code>dsh -a /path/to/some/command/or/script\n</code></pre>\n\n<p>It will run the command on all the machines at the same time and return the output prefixed with the hostname. The command or script has to be present on the system, so a shared NFS directory can be useful for these sorts of things.</p>\n" }, { "answer_id": 247589, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this method will work for everything that you want, but you can try something like this:</p>\n\n<pre><code>$ cat your_script.sh | ssh your_host bash\n</code></pre>\n\n<p>Which will run the script (which resides locally) on the remote server.</p>\n" }, { "answer_id": 367840, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.theether.org/pssh/\" rel=\"nofollow noreferrer\">pssh</a> may be interesting since, unlike most solutions mentioned here, the commands are run in parallel.</p>\n\n<p>(For my own use, I wrote a simpler small script very similar to GavinCattell's one, it is <a href=\"http://www.bortzmeyer.org/maintenir-plusieurs-machines-identiques.html\" rel=\"nofollow noreferrer\">documented here - in french</a>).</p>\n" }, { "answer_id": 367896, "author": "Keltia", "author_id": 16143, "author_profile": "https://Stackoverflow.com/users/16143", "pm_score": 2, "selected": false, "text": "<p>Have you looked at things like <a href=\"http://reductivelabs.com/trac/puppet\" rel=\"nofollow noreferrer\">Puppet</a> or <a href=\"http://www.cfengine.com/\" rel=\"nofollow noreferrer\">Cfengine</a>. They can do what you want and probably much more.</p>\n" }, { "answer_id": 1699850, "author": "Christopher Mahan", "author_id": 479, "author_profile": "https://Stackoverflow.com/users/479", "pm_score": 2, "selected": false, "text": "<p>You can try <a href=\"http://www.lag.net/paramiko/\" rel=\"nofollow noreferrer\">paramiko</a>. It's a pure-python ssh client. You can program your ssh sessions. Nothing to install on remote machines. </p>\n\n<p>See this <a href=\"http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/\" rel=\"nofollow noreferrer\">great article</a> on how to use it.</p>\n" }, { "answer_id": 10389204, "author": "Brad Montgomery", "author_id": 182778, "author_profile": "https://Stackoverflow.com/users/182778", "pm_score": 2, "selected": false, "text": "<p>For those that stumble across this question, I'll include an answer that uses <a href=\"http://fabfile.org\" rel=\"nofollow\">Fabric</a>, which solves exactly the problem described above: Running arbitrary commands on multiple hosts over ssh.</p>\n\n<p>Once fabric is installed, you'd create a <code>fabfile.py</code>, and implement <em>tasks</em> that can be run on your remote hosts. For example, a task to <em>Reload Apache</em> might look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from fabric.api import env, run\n\nenv.hosts = ['[email protected]', '[email protected]']\n\ndef reload():\n \"\"\" Reload Apache \"\"\"\n run(\"sudo /etc/init.d/apache2 reload\")\n</code></pre>\n\n<p>Then, on your local machine, run <code>fab reload</code> and the <code>sudo /etc/init.d/apache2 reload</code> command would get run on all the hosts specified in <code>env.hosts</code>.</p>\n" }, { "answer_id": 10914809, "author": "Quierati", "author_id": 1439819, "author_profile": "https://Stackoverflow.com/users/1439819", "pm_score": 1, "selected": false, "text": "<p>Creates hostname ssh command of all machines accessed.\nby Quierati\n<a href=\"http://pastebin.com/pddEQWq2\" rel=\"nofollow\">http://pastebin.com/pddEQWq2</a>\n</p>\n\n<pre><code>#Use in .bashrc\n#Use \"HashKnownHosts no\" in ~/.ssh/config or /etc/ssh/ssh_config \n# If known_hosts is encrypted and delete known_hosts\n\n[ ! -d ~/bin ] &amp;&amp; mkdir ~/bin\nfor host in `cut -d, -f1 ~/.ssh/known_hosts|cut -f1 -d \" \"`;\n do\n [ ! -s ~/bin/$host ] &amp;&amp; echo ssh $host '$*' &gt; ~/bin/$host\ndone\n[ -d ~/bin ] &amp;&amp; chmod -R 700 ~/bin\nexport PATH=$PATH:~/bin \n</code></pre>\n\n<p>Ex Execute:</p>\n\n<pre><code>$for i in hostname{1..10}; do $i who;done\n</code></pre>\n" }, { "answer_id": 18859414, "author": "Andy M", "author_id": 2540450, "author_profile": "https://Stackoverflow.com/users/2540450", "pm_score": 1, "selected": false, "text": "<p>There is a tool called <a href=\"http://flattsolutions.com\" rel=\"nofollow\">FLATT (FLexible Automation and Troubleshooting Tool)</a> that allows you to execute scripts on multiple Unix/Linux hosts with a click of a button. It is a desktop GUI app that runs on Mac and Windows but there is also a command line java client.<br>\nYou can create batch jobs and reuse on multiple hosts.<br>\nRequires Java 1.6 or higher.</p>\n" }, { "answer_id": 25556957, "author": "user3438301", "author_id": 3438301, "author_profile": "https://Stackoverflow.com/users/3438301", "pm_score": 0, "selected": false, "text": "<p>Just read a new <a href=\"https://www.exratione.com/2014/08/bash-script-ssh-automation-without-a-password-prompt/\" rel=\"nofollow\">blog</a> using <a href=\"http://linux.die.net/man/2/setsid\" rel=\"nofollow\">setsid</a> without any further installation/configuration besides the mainstream kernel. Tested/Verified under Ubuntu14.04. </p>\n\n<p>While the author has a very clear explanation and sample code as well, here's the magic part for a quick glance:</p>\n\n<pre><code>#----------------------------------------------------------------------\n# Create a temp script to echo the SSH password, used by SSH_ASKPASS\n#----------------------------------------------------------------------\nSSH_ASKPASS_SCRIPT=/tmp/ssh-askpass-script\ncat &gt; ${SSH_ASKPASS_SCRIPT} &lt;&lt;EOL\n#!/bin/bash\necho \"${PASS}\"\nEOL\nchmod u+x ${SSH_ASKPASS_SCRIPT}\n\n# Tell SSH to read in the output of the provided script as the password.\n# We still have to use setsid to eliminate access to a terminal and thus avoid\n# it ignoring this and asking for a password.\nexport SSH_ASKPASS=${SSH_ASKPASS_SCRIPT}\n......\n......\n# Log in to the remote server and run the above command.\n# The use of setsid is a part of the machinations to stop ssh \n# prompting for a password.\nsetsid ssh ${SSH_OPTIONS} ${USER}@${SERVER} \"ls -rlt\"\n</code></pre>\n" }, { "answer_id": 61327005, "author": "Patoshi パトシ", "author_id": 1642231, "author_profile": "https://Stackoverflow.com/users/1642231", "pm_score": 0, "selected": false, "text": "<p>Easiest way I found without installing or configuring much software is using plain old tmux. Say you have 9 linux servers. Pick a box as your main. Start a tmux session:</p>\n\n<pre><code>tmux\n</code></pre>\n\n<p>Then create 9 split tmux panes by doing this 8 times:</p>\n\n<pre><code>ctrl-b + %\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/DCOLh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DCOLh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now SSH into each box in each pane. You'll need to know some tmux shortcuts. To navigate, press: </p>\n\n<pre><code>ctrl+b &lt;arrow-keys&gt;\n</code></pre>\n\n<p>Once your logged in to all your boxes on each pane. Now turn on pane synchronization where it lets you type the same thing into each box:</p>\n\n<pre><code>ctrl+b :setw synchronize-panes on\n</code></pre>\n\n<p>now when you press any keys, it will show up on every pane. to turn it off, just make on to off. to cycle resize panes, press ctrl+b &lt; space-bar >. </p>\n\n<p>This works alot better for me since I need to see each terminal output as sometimes servers crash or hang for whatever reason when downloading or upgrade software. Any issues, you can just isolate and resolve individually. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14838/" ]
I've searched around a bit for similar questions, but other than running one command or perhaps a few command with items such as: ``` ssh user@host -t sudo su - ``` However, what if I essentially need to run a script on (let's say) 15 servers at once. Is this doable in bash? In a perfect world I need to avoid installing applications if at all possible to pull this off. For argument's sake, let's just say that I need to do the following across 10 hosts: 1. Deploy a new Tomcat container 2. Deploy an application in the container, and configure it 3. Configure an Apache vhost 4. Reload Apache I have a script that does all of that, but it relies on me logging into all the servers, pulling a script down from a repo, and then running it. If this isn't doable in bash, what alternatives do you suggest? Do I need a bigger hammer, such as Perl (Python might be preferred since I can guarantee Python is on all boxes in a RHEL environment thanks to yum/up2date)? If anyone can point to me to any useful information it'd be greatly appreciated, especially if it's doable in bash. I'll settle for Perl or Python, but I just don't know those as well (working on that). Thanks!
Often, I'll just use the original Tcl version of Expect. You only need to have that on the local machine. If I'm inside a program using Perl, I do this with [Net::SSH::Expect](http://search.cpan.org/dist/Net-SSH-Expect/). Other languages have similar "expect" tools.
243,752
<p>Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?</p>
[ { "answer_id": 243766, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 6, "selected": true, "text": "<p>No, there is no way to directly convert the list to an observable collection. You must add each item to the collection. However, below is a shortcut to allow the framework to enumerate the values and add them for you. </p>\n\n<pre><code>Dim list as new List(of string)\n...some stuff to fill the list...\nDim observable as new ObservableCollection(of string)(list)\n</code></pre>\n" }, { "answer_id": 1328283, "author": "Junior Mayhé", "author_id": 66708, "author_profile": "https://Stackoverflow.com/users/66708", "pm_score": 4, "selected": false, "text": "<p>I'm late but I want to share this interesting piece for converting a list into a ObservableCollection if you need a loop:</p>\n\n<pre><code>public static ObservableCollection&lt;T&gt; ToObservableCollection&lt;T&gt;(this IEnumerable&lt;T&gt; coll)\n{\n var c = new ObservableCollection&lt;T&gt;();\n foreach (var e in coll) c.Add(e);\n return c;\n}\n</code></pre>\n\n<p>You could pass an collection to the ObservableCollection constructor:</p>\n\n<pre><code>List&lt;Product&gt; myProds = ......\nObservableCollection&lt;Product&gt; oc = new ObservableCollection&lt;Product&gt;(myProds);\n</code></pre>\n\n<p>Now you have to translate these to VB.NET :)</p>\n" }, { "answer_id": 5193871, "author": "Jordan", "author_id": 589774, "author_profile": "https://Stackoverflow.com/users/589774", "pm_score": 2, "selected": false, "text": "<p>to clarify what Junior is saying (with an added example if you're using LINQ that returns an IEnumerable):</p>\n\n<pre><code>//Applications is an Observable Collection of Application in this example\nList&lt;Application&gt; filteredApplications = \n (Applications.Where( i =&gt; i.someBooleanDetail )).ToList();\nApplications = new ObservableCollection&lt;Application&gt;( filteredApplications );\n</code></pre>\n" }, { "answer_id": 7889816, "author": "Joby Mavelikara", "author_id": 1012779, "author_profile": "https://Stackoverflow.com/users/1012779", "pm_score": 2, "selected": false, "text": "<pre><code>//Create an observable collection TObservable.\n\nObservableCollection (TObservable) =new ObservableCollection (TObservable)();\n\n//Convert List items(OldListItems) to collection\n\nOldListItems.ForEach(x =&gt; TObservable.Add(x));\n</code></pre>\n" }, { "answer_id": 14027789, "author": "Zin Min", "author_id": 1927641, "author_profile": "https://Stackoverflow.com/users/1927641", "pm_score": 0, "selected": false, "text": "<pre><code>ObservableCollection&lt;yourobjectname&gt; result = new ObservableCollection&lt;yourobjectname&gt;(yourobjectlist);\n</code></pre>\n" }, { "answer_id": 21455199, "author": "trix", "author_id": 3252456, "author_profile": "https://Stackoverflow.com/users/3252456", "pm_score": 1, "selected": false, "text": "<p>Even though I'm late, I wanna share a quick enhancement to <a href=\"https://stackoverflow.com/users/66708/junior-mayhe\">Junior</a>'s answer: let the developer define the converter function used to convert observable collection objects from the source collection to the destination one.</p>\n\n<p>Like the following:</p>\n\n<pre><code>public static ObservableCollection&lt;TDest&gt; ToObservableCollection&lt;TDest, TSource&gt;(this IEnumerable&lt;TSource&gt; coll, Func&lt;TSource, TDest&gt; converter)\n {\n var c = new ObservableCollection&lt;TDest&gt;();\n foreach (var e in coll)\n {\n c.Add(converter(e));\n }\n return c;\n }\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
Is there a way to do this without iterating through the List and adding the items to the ObservableCollection?
No, there is no way to directly convert the list to an observable collection. You must add each item to the collection. However, below is a shortcut to allow the framework to enumerate the values and add them for you. ``` Dim list as new List(of string) ...some stuff to fill the list... Dim observable as new ObservableCollection(of string)(list) ```
243,782
<p>I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need.</p> <p><strong>Approach 1:</strong></p> <pre><code>SELECT COUNT( my_table.my_col ) AS row_count FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>Then</p> <pre><code>SELECT my_table.my_col FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>Or <strong>Approach 2</strong></p> <pre><code>SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col ) FROM my_table WHERE my_table.foo = 'bar' ) AS row_count FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>I am doing this because my SQL driver (SQL Native Client 9.0) does not allow me to use SQLRowCount on a SELECT statement but I need to know the number of rows in my result in order to allocate an array before assigning information to it. The use of a dynamically allocated container is, unfortunately, not an option in this area of my program.</p> <p>I am concerned that the following scenario might occur:</p> <ul> <li>SELECT for count occurs</li> <li>Another instruction occurs, adding or removing a row</li> <li>SELECT for data occurs and suddenly the array is the wrong size.<br> -In the worse case, this will attempt to write data beyond the arrays limits and crash my program.</li> </ul> <p>Does Approach 2 prohibit this issue?</p> <p>Also, Will one of the two approaches be faster? If so, which?</p> <p>Finally, is there a better approach that I should consider (perhaps a way to instruct the driver to return the number of rows in a SELECT result using SQLRowCount?)</p> <p>For those that asked, I am using Native C++ with the aforementioned SQL driver (provided by Microsoft.)</p>
[ { "answer_id": 243793, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>Why don't you put your results into a vector? That way you don't have to know the size before hand.</p>\n" }, { "answer_id": 243812, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 1, "selected": false, "text": "<p>Here are some ideas:</p>\n\n<ul>\n<li>Go with Approach #1 and resize the array to hold additional results or use a type that automatically resizes as neccessary (you don't mention what language you are using so I can't be more specific).</li>\n<li>You could execute both statements in Approach #1 within a transaction to guarantee the counts are the same both times if your database supports this.</li>\n<li>I'm not sure what you are doing with the data but if it is possible to process the results without storing all of them first this might be the best method.</li>\n</ul>\n" }, { "answer_id": 243903, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>You might want to think about a better pattern for dealing with data of this type.</p>\n\n<p>No self-prespecting SQL driver will tell you how many rows your query will return before returning the rows, because the answer might change (unless you use a Transaction, which creates problems of its own.)</p>\n\n<p>The number of rows won't change - google for ACID and SQL.</p>\n" }, { "answer_id": 243960, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 1, "selected": false, "text": "<p>If you are really concerned that your row count will change between the select count and the select statement, why not select your rows into a temp table first? That way, you know you will be in sync.</p>\n" }, { "answer_id": 243963, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>Approach 2 will always return a count that matches your result set.</p>\n\n<p>I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.</p>\n\n<pre><code>SELECT \n mt.my_row,\n (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt\nFROM my_table mt\nWHERE mt.foo = 'bar';\n</code></pre>\n" }, { "answer_id": 244043, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 2, "selected": false, "text": "<p>If you're concerned the number of rows that meet the condition may change in the few milliseconds since execution of the query and retrieval of results, you could/should execute the queries inside a transaction:</p>\n\n<pre><code>BEGIN TRAN bogus\n\nSELECT COUNT( my_table.my_col ) AS row_count\nFROM my_table\nWHERE my_table.foo = 'bar'\n\nSELECT my_table.my_col\nFROM my_table\nWHERE my_table.foo = 'bar'\nROLLBACK TRAN bogus\n</code></pre>\n\n<p>This would return the correct values, always.</p>\n\n<p>Furthermore, if you're using SQL Server, you can use @@ROWCOUNT to get the number of rows affected by last statement, and redirect the output of <em>real</em> query to a temp table or table variable, so you can return everything altogether, and no need of a transaction:</p>\n\n<pre><code>DECLARE @dummy INT\n\nSELECT my_table.my_col\nINTO #temp_table\nFROM my_table\nWHERE my_table.foo = 'bar'\n\nSET @dummy=@@ROWCOUNT\nSELECT @dummy, * FROM #temp_table\n</code></pre>\n" }, { "answer_id": 244128, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "<p>There are only two ways to be 100% certain that the <code>COUNT(*)</code> and the actual query will give consistent results:</p>\n\n<ul>\n<li>Combined the <code>COUNT(*)</code> with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.</li>\n<li>Use two queries, as in your Approach 1, after starting a transaction in <code>SNAPSHOT</code> or <code>SERIALIZABLE</code> isolation level. </li>\n</ul>\n\n<p>Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on <a href=\"http://msdn.microsoft.com/en-us/library/ms173763.aspx\" rel=\"noreferrer\"><code>SET TRANSACTION ISOLATION</code></a> for more details.</p>\n" }, { "answer_id": 244132, "author": "Adam Porad", "author_id": 21353, "author_profile": "https://Stackoverflow.com/users/21353", "pm_score": 5, "selected": false, "text": "<p>If you're using SQL Server, after your query you can select the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-transact-sql\" rel=\"noreferrer\">@@RowCount</a> function (or if your result set might have more than 2 billion rows use the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/rowcount-big-transact-sql\" rel=\"noreferrer\">RowCount_Big()</a> function). This will return the number of rows selected by the previous statement or number of rows affected by an insert/update/delete statement.</p>\n\n<pre><code>SELECT my_table.my_col\n FROM my_table\n WHERE my_table.foo = 'bar'\n\nSELECT @@Rowcount\n</code></pre>\n\n<p>Or if you want to row count included in the result sent similar to Approach #2, you can use the the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql\" rel=\"noreferrer\">OVER clause</a>. </p>\n\n<pre><code>SELECT my_table.my_col,\n count(*) OVER(PARTITION BY my_table.foo) AS 'Count'\n FROM my_table\n WHERE my_table.foo = 'bar'\n</code></pre>\n\n<p>Using the OVER clause will have much better performance than using a subquery to get the row count. Using the @@RowCount will have the best performance because the there won't be any query cost for the select @@RowCount statement</p>\n\n<p>Update in response to comment: The example I gave would give the # of rows in partition - defined in this case by \"PARTITION BY my_table.foo\". The value of the column in each row is the # of rows with the same value of my_table.foo. Since your example query had the clause \"WHERE my_table.foo = 'bar'\", all rows in the resultset will have the same value of my_table.foo and therefore the value in the column will be the same for all rows and equal (in this case) this the # of rows in the query. </p>\n\n<p>Here is a better/simpler example of how to include a column in each row that is the total # of rows in the resultset. Simply remove the optional Partition By clause.</p>\n\n<pre><code>SELECT my_table.my_col, count(*) OVER() AS 'Count'\n FROM my_table\n WHERE my_table.foo = 'bar'\n</code></pre>\n" }, { "answer_id": 3388687, "author": "Deepfreezed", "author_id": 318089, "author_profile": "https://Stackoverflow.com/users/318089", "pm_score": 0, "selected": false, "text": "<pre><code>IF (@@ROWCOUNT &gt; 0)\nBEGIN\nSELECT my_table.my_col\n FROM my_table\n WHERE my_table.foo = 'bar'\nEND\n</code></pre>\n" }, { "answer_id": 30139525, "author": "Tschallacka", "author_id": 1356107, "author_profile": "https://Stackoverflow.com/users/1356107", "pm_score": 0, "selected": false, "text": "<p>Just to add this because this is the top result in google for this question.\nIn sqlite I used this to get the rowcount.</p>\n\n<pre><code>WITH temptable AS\n (SELECT one,two\n FROM\n (SELECT one, two\n FROM table3\n WHERE dimension=0\n UNION ALL SELECT one, two\n FROM table2\n WHERE dimension=0\n UNION ALL SELECT one, two\n FROM table1\n WHERE dimension=0)\n ORDER BY date DESC)\nSELECT *\nFROM temptable\nLEFT JOIN\n (SELECT count(*)/7 AS cnt,\n 0 AS bonus\n FROM temptable) counter\nWHERE 0 = counter.bonus\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625/" ]
I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need. **Approach 1:** ``` SELECT COUNT( my_table.my_col ) AS row_count FROM my_table WHERE my_table.foo = 'bar' ``` Then ``` SELECT my_table.my_col FROM my_table WHERE my_table.foo = 'bar' ``` Or **Approach 2** ``` SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col ) FROM my_table WHERE my_table.foo = 'bar' ) AS row_count FROM my_table WHERE my_table.foo = 'bar' ``` I am doing this because my SQL driver (SQL Native Client 9.0) does not allow me to use SQLRowCount on a SELECT statement but I need to know the number of rows in my result in order to allocate an array before assigning information to it. The use of a dynamically allocated container is, unfortunately, not an option in this area of my program. I am concerned that the following scenario might occur: * SELECT for count occurs * Another instruction occurs, adding or removing a row * SELECT for data occurs and suddenly the array is the wrong size. -In the worse case, this will attempt to write data beyond the arrays limits and crash my program. Does Approach 2 prohibit this issue? Also, Will one of the two approaches be faster? If so, which? Finally, is there a better approach that I should consider (perhaps a way to instruct the driver to return the number of rows in a SELECT result using SQLRowCount?) For those that asked, I am using Native C++ with the aforementioned SQL driver (provided by Microsoft.)
There are only two ways to be 100% certain that the `COUNT(*)` and the actual query will give consistent results: * Combined the `COUNT(*)` with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus. * Use two queries, as in your Approach 1, after starting a transaction in `SNAPSHOT` or `SERIALIZABLE` isolation level. Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on [`SET TRANSACTION ISOLATION`](http://msdn.microsoft.com/en-us/library/ms173763.aspx) for more details.
243,790
<p>I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?</p>
[ { "answer_id": 243838, "author": "Steve", "author_id": 15470, "author_profile": "https://Stackoverflow.com/users/15470", "pm_score": 2, "selected": false, "text": "<p>If you're just using an integer for a sequence you could update the id with the rownum. e.g.</p>\n\n<pre><code>update\ntable\nset id = rownum\n</code></pre>\n\n<p>You then need to reset the sequence to the next valid id.</p>\n" }, { "answer_id": 244080, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": true, "text": "<p>Once you have created the sequence:</p>\n\n<pre><code>update mytable\nset id = mysequence.nextval;\n</code></pre>\n" }, { "answer_id": 245100, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 2, "selected": false, "text": "<p>Is this what you need?</p>\n\n<pre><code>UPDATE your_table\n SET id = your_seq.nextval;\n</code></pre>\n\n<p>This assumes you don't care what order your primary keys are in.</p>\n" }, { "answer_id": 1120949, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>First you should check your PCTFREE... is there enough room for every row to get longer?</p>\n\n<p>If you chose a very small PCTFREE or your data has lots of lenght-increasing updates, you might begin chaining every row to do this as an update.</p>\n\n<p>You almost certainly better to do this as a CTAS.</p>\n\n<p>Create table t2 as select seq.nextval, t1.* from t1.</p>\n\n<p>drop t1</p>\n\n<p>rename t2 to t1.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101/" ]
I have this table in an Oracle DB which has a primary key defined on 3 of the data columns. I want to drop the primary key constraint to allow rows with duplicate data for those columns, and create a new column, 'id', to contain an auto-incrementing integer ID for these rows. I know how to create a sequence and trigger to add an auto-incrementing ID for new rows added to the table, but is it possible to write a PL/SQL statement to add unique IDs to all the rows that are already in the table?
Once you have created the sequence: ``` update mytable set id = mysequence.nextval; ```
243,794
<p>I'm using the latest version of the <a href="https://jqueryui.com/tabs/" rel="nofollow noreferrer">jQuery UI tabs</a>. I have tabs positioned toward the bottom of the page. </p> <p>Every time I click a tab, the screen jumps toward the top.</p> <p>How can I prevent this from happening?</p> <p>Please see this example:</p> <p><a href="http://5bosses.com/examples/tabs/sample_tabs.html" rel="nofollow noreferrer">http://5bosses.com/examples/tabs/sample_tabs.html</a></p>
[ { "answer_id": 243832, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 4, "selected": false, "text": "<p>If you have something along these lines:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"activateTab('tab1');\"&gt;Tab 1&lt;/a></code></pre>\n\n<p>Try adding <code>return false;</code> after the tab activation command:</p>\n\n<pre><code>&lt;a href=\"#\" onclick=\"activateTab('tab1'); return false;\"&gt;Tab 1&lt;/a></code></pre>\n" }, { "answer_id": 244622, "author": "Edward", "author_id": 31869, "author_profile": "https://Stackoverflow.com/users/31869", "pm_score": 2, "selected": false, "text": "<p>Thanks for your help. Good suggestion, but I tried before with no luck. I think JQuery UI may be overriding my efforts.</p>\n\n<p>Here is the code per tab:</p>\n\n<pre><code>&lt;li class=\"\"&gt;&lt;a href=\"#fragment-2\"&gt;&lt;span&gt;Two&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;\n</code></pre>\n\n<p>I already tried this with no success:</p>\n\n<pre><code>&lt;li class=\"\"&gt;&lt;a href=\"#fragment-2\" onclick=\"return false;\"&gt;&lt;span&gt;Two&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;\n</code></pre>\n\n<p>Here is a simple example (without return false): <a href=\"http://5bosses.com/examples/tabs/sample_tabs.html\" rel=\"nofollow noreferrer\">http://5bosses.com/examples/tabs/sample_tabs.html</a></p>\n\n<p>Any other suggestions?</p>\n" }, { "answer_id": 245099, "author": "Brian Ramsay", "author_id": 3078, "author_profile": "https://Stackoverflow.com/users/3078", "pm_score": 3, "selected": false, "text": "<p>My guess is that you are animating your tab transitions? I am having the same problem, where the page scroll jumps back to the top with every click.</p>\n\n<p>I found this in the jquery source:</p>\n\n<pre><code> // Show a tab, animation prevents browser scrolling to fragment,\n</code></pre>\n\n<p>Sure enough, if I have this:</p>\n\n<pre><code>$('.tab_container &gt; ul').tabs(); \n$('.tab_container &gt; ul').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 'fast' } });\n</code></pre>\n\n<p>my code jumps to the top and is annoying (but there's animation). If I change that to this:</p>\n\n<pre><code>$('.tab_container &gt; ul').tabs(); \n//$('.tab_container &gt; ul').tabs({ fx: { height: 'toggle', opacity: 'toggle', duration: 'fast' } });\n</code></pre>\n\n<p>there is no tab animation, but switching between tabs is smooth.</p>\n\n<p>I found a way to make it scroll back, but it's not a proper fix, as the browser still jumps to the top after clicking a tab. The scroll happens between the events tabsselect and tabsshow, so the following code jumps back to your tab:</p>\n\n<pre><code>var scroll_to_x = 0;\nvar scroll_to_y = 0;\n$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {\n scroll_to_x = window.pageXOffset;\n scroll_to_y = window.pageYOffset;\n});\n$('.ui-tabs-nav').bind('tabsshow', function(event, ui) {\n window.scroll(scroll_to_x, scroll_to_y);\n});\n</code></pre>\n\n<p>I'll post any more progress I make.</p>\n" }, { "answer_id": 245424, "author": "edt", "author_id": 32242, "author_profile": "https://Stackoverflow.com/users/32242", "pm_score": 1, "selected": false, "text": "<pre><code>&gt; var scroll_to_x = 0; var scroll_to_y =\n&gt; 0;\n&gt; $('.ui-tabs-nav').bind('tabsselect',\n&gt; function(event, ui) {\n&gt; scroll_to_x = window.pageXOffset;\n&gt; scroll_to_y = window.pageYOffset; }); $('.ui-tabs-nav').bind('tabsshow',\n&gt; function(event, ui) {\n&gt; window.scroll(scroll_to_x, scroll_to_y); });\n</code></pre>\n\n<p>Thanks for your help! Please let me know what else you find.</p>\n\n<p>The above function works (screen doesn't move permanently)... but, the screen is very wobbly on click. </p>\n\n<p>Here is a simple example showing how clicking a tabs causes the screen to jump toward the top (without the above code):\n <a href=\"http://5bosses.com/examples/tabs/sample_tabs.html\" rel=\"nofollow noreferrer\">http://5bosses.com/examples/tabs/sample_tabs.html</a></p>\n\n<p>Note that there's no animation being used.</p>\n" }, { "answer_id": 259543, "author": "edt", "author_id": 32242, "author_profile": "https://Stackoverflow.com/users/32242", "pm_score": 3, "selected": false, "text": "<p>I was given a solution for this...</p>\n\n<p>How to stop screen from jumping up when tab is clicked:</p>\n\n<p>Wrap the div that contains the tabs in a div with a fixed height.</p>\n\n<p>See example here: <a href=\"http://5bosses.com/examples/tabs/sample_tabs.html\" rel=\"nofollow noreferrer\">http://5bosses.com/examples/tabs/sample_tabs.html</a> </p>\n" }, { "answer_id": 338133, "author": "Sameer Alibhai", "author_id": 2343, "author_profile": "https://Stackoverflow.com/users/2343", "pm_score": 1, "selected": false, "text": "<p>There is a much more simple way which I discovered from the comments on <a href=\"http://blog.movalog.com/a/javascript-toggle-visibility/\" rel=\"nofollow noreferrer\">this page</a> that is to simply remove the href=\"#\" and it will not jump to the top any more! I verified and it works for me. Cheers</p>\n" }, { "answer_id": 372804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I prefer to have an href=\"#\" in my links that do not take the user anywhere, but you can do this as long as you add an onclick=\"return false;\". The key, I guess, is not sending the user to \"#\", which depending on the browser seems to default as the top of the current page.</p>\n" }, { "answer_id": 1498304, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, plus mine were rotating on their own so if you were at the bottom of the page, the browser window would be scrolled up tot he top. Having a fixed height for the tab container worked for me. Kind of a weird thing still is that if you leave the window or tab and go back, it will still scroll. Not the end of the world, though.</p>\n" }, { "answer_id": 1635723, "author": "Mike Petrovich", "author_id": 197895, "author_profile": "https://Stackoverflow.com/users/197895", "pm_score": 6, "selected": false, "text": "<p>If you're animating your tab transitions (ie. <code>.tabs({ fx: { opacity: 'toggle' } });</code>), then here's what's happening:</p>\n\n<p>In most cases, the jumping isn't caused by the browser following the '#' link. The page jumps because at the midpoint of the animation between the two tab panes, both tab panes are fully transparent and hidden (as in display: none), so the effective height of the whole tabbed section becomes momentarily zero.</p>\n\n<p>And if a zero-height tabbed section causes the page to be shorter, then the page will appear to jump up to compensate, when in reality it's simply resizing to fit the (momentarily) shorter content. Makes sense?</p>\n\n<p>The best way to fix this is to set a fixed height for the tabbed section. If this is undesirable (because your tab content varies in height), then use this instead:</p>\n\n<pre><code>jQuery('#tabs').tabs({\n fx: { opacity: 'toggle' },\n select: function(event, ui) {\n jQuery(this).css('height', jQuery(this).height());\n jQuery(this).css('overflow', 'hidden');\n },\n show: function(event, ui) {\n jQuery(this).css('height', 'auto');\n jQuery(this).css('overflow', 'visible');\n }\n});\n</code></pre>\n\n<p>It will set the computed height of the pane before the tab transition. Once the new tab has appeared, the height is set back to 'auto'. Overflow is set to 'hidden' to prevent content from breaking out of the pane when going from a short tab to a taller one.</p>\n\n<p>This is what worked for me. Hope this helps.</p>\n" }, { "answer_id": 3564136, "author": "mike", "author_id": 430452, "author_profile": "https://Stackoverflow.com/users/430452", "pm_score": 0, "selected": false, "text": "<p>replace the href=\"#\" with href=\"javascript:void(0);\" in 'a' element</p>\n\n<p>works 100%</p>\n" }, { "answer_id": 3855437, "author": "FDisk", "author_id": 175404, "author_profile": "https://Stackoverflow.com/users/175404", "pm_score": -1, "selected": false, "text": "<p>Did you tryed:</p>\n\n<pre><code>fx: {opacity:'toggle', duration:100}\n</code></pre>\n" }, { "answer_id": 9856531, "author": "Tomas", "author_id": 684229, "author_profile": "https://Stackoverflow.com/users/684229", "pm_score": 2, "selected": false, "text": "<p>Mike's solution demonstrated the principle greatly but it has a big drawback - if the resultant page is short, the screen will jump to the top anyway! The only solution is to <strong>remember the scrollTop, and restore it</strong> after the tabs are switched. But before the restoration, <strong>enlarge the page (html tag)</strong> appropriatelly: </p>\n\n<p>(edit - modified for new Jquery UI API + small improvement for large pages)</p>\n\n<pre><code>$(...).tabs({\n beforeActivate: function(event, ui) {\n $(this).data('scrollTop', $(window).scrollTop()); // save scrolltop\n },\n activate: function(event, ui) {\n if (!$(this).data('scrollTop')) { // there was no scrolltop before\n jQuery('html').css('height', 'auto'); // reset back to auto...\n // this may not work on page where originally\n // the html tag was of a fixed height...\n return;\n }\n //console.log('activate: scrolltop pred = ' + $(this).data('scrollTop') + ', nyni = ' + $(window).scrollTop());\n if ($(window).scrollTop() == $(this).data('scrollTop')) // the scrolltop was not moved\n return; // nothing to be done\n // scrolltop moved - we need to fix it\n var min_height = $(this).data('scrollTop') + $(window).height();\n // minimum height the document must have to have that scrollTop\n if ($('html').outerHeight() &lt; min_height) { // just a test to be sure\n // but this test should be always true\n /* be sure to use $('html').height() instead of $(document).height()\n because the document height is always &gt;= window height!\n Not what you want. And to handle potential html padding, be sure\n to use outerHeight instead!\n Now enlarge the html tag (unfortunatelly cannot set\n $(document).height()) - we want to set min_height\n as html's outerHeight:\n */\n $('html').height(min_height -\n ($('html').outerHeight() - $('html').height()));\n }\n $(window).scrollTop($(this).data('scrollTop')); // finally, set it back\n }\n});\n</code></pre>\n\n<p>Works with the <code>fx</code> effect too.</p>\n" }, { "answer_id": 13999580, "author": "BlogSiteDev", "author_id": 1922891, "author_profile": "https://Stackoverflow.com/users/1922891", "pm_score": 2, "selected": false, "text": "<p>Try just adding a min-height using css to each of the tab content areas ( not the tabs themselves ). That fixed it for me. :)</p>\n" }, { "answer_id": 17619122, "author": "Zach Johnson", "author_id": 1154738, "author_profile": "https://Stackoverflow.com/users/1154738", "pm_score": 2, "selected": false, "text": "<p>I had the same problem with jquery ui's menu - a preventDefault() on the anchor's click event stops the page from scrolling back to the top:</p>\n\n<pre><code> $(\"ul.ui-menu li a\").click(function(e) {\n e.preventDefault();\n });\n</code></pre>\n" }, { "answer_id": 23339446, "author": "Alexander Georgiev", "author_id": 2604345, "author_profile": "https://Stackoverflow.com/users/2604345", "pm_score": 2, "selected": false, "text": "<p>Try using <code>event.preventDefault();</code>. On the click event which is switching the tabs. My function looks like this:</p>\n\n<pre><code> $(function() {\n var $tabs = $('#measureTabs').tabs();\n $(\".btn-contiue\").click(function (event) {\n event.preventDefault();\n $( \"#measureTabs\" ).tabs( \"option\", \"active\", $(\"#measureTabs\").tabs ('option', 'active')+1 );\n });\n });\n</code></pre>\n" }, { "answer_id": 28317149, "author": "Zeihlis", "author_id": 2866076, "author_profile": "https://Stackoverflow.com/users/2866076", "pm_score": 1, "selected": false, "text": "<p>I had such a problem. My code was:</p>\n\n<pre><code>$(\"#tabs\").tabs({\n hide: {\n effect: \"fade\",\n duration: \"500\"\n },\n show: {\n effect: \"fade\",\n duration: \"500\"\n }\n});\n</code></pre>\n\n<p>I have simply removed <code>show</code> and it worked like a charm!</p>\n\n<pre><code> $(\"#tabs\").tabs({\n hide: {\n effect: \"fade\",\n duration: \"500\"\n }\n });\n</code></pre>\n" }, { "answer_id": 37106368, "author": "Bill Searle", "author_id": 2484389, "author_profile": "https://Stackoverflow.com/users/2484389", "pm_score": 0, "selected": false, "text": "<p>I found in my case the tab <code>href=#example1</code> was causing the page to jump to the position of the <code>id</code>. Adding a fixed height to the tabs made no difference so I just added:</p>\n\n<p><code>$('.nav-tabs li a').click( function(e) {\n e.preventDefault();\n});</code> </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31869/" ]
I'm using the latest version of the [jQuery UI tabs](https://jqueryui.com/tabs/). I have tabs positioned toward the bottom of the page. Every time I click a tab, the screen jumps toward the top. How can I prevent this from happening? Please see this example: <http://5bosses.com/examples/tabs/sample_tabs.html>
If you're animating your tab transitions (ie. `.tabs({ fx: { opacity: 'toggle' } });`), then here's what's happening: In most cases, the jumping isn't caused by the browser following the '#' link. The page jumps because at the midpoint of the animation between the two tab panes, both tab panes are fully transparent and hidden (as in display: none), so the effective height of the whole tabbed section becomes momentarily zero. And if a zero-height tabbed section causes the page to be shorter, then the page will appear to jump up to compensate, when in reality it's simply resizing to fit the (momentarily) shorter content. Makes sense? The best way to fix this is to set a fixed height for the tabbed section. If this is undesirable (because your tab content varies in height), then use this instead: ``` jQuery('#tabs').tabs({ fx: { opacity: 'toggle' }, select: function(event, ui) { jQuery(this).css('height', jQuery(this).height()); jQuery(this).css('overflow', 'hidden'); }, show: function(event, ui) { jQuery(this).css('height', 'auto'); jQuery(this).css('overflow', 'visible'); } }); ``` It will set the computed height of the pane before the tab transition. Once the new tab has appeared, the height is set back to 'auto'. Overflow is set to 'hidden' to prevent content from breaking out of the pane when going from a short tab to a taller one. This is what worked for me. Hope this helps.
243,800
<p><strong>The Situation</strong></p> <p>I have an area of the screen that can be shown and hidden via JavaScript (something like "show/hide advanced search options"). Inside this area there are form elements (select, checkbox, etc). For users using assistive technology like a screen-reader (in this case JAWS), we need to link these form elements with a label or use the "title" attribute to describe the purpose of each element. I'm using the title attribute because there isn't enough space for a label, and the tooltip you get is nice for non-screen-reader users.</p> <p>The code looks something like this:</p> <pre><code>&lt;div id="placeholder" style="display:none;"&gt; &lt;select title="Month"&gt; &lt;option&gt;January&lt;/option&gt; &lt;option&gt;February&lt;/option&gt; ... &lt;/select&gt; &lt;/div&gt; </code></pre> <p><strong>The Problem</strong></p> <p>Normally, JAWS will not read hidden elements... because well, they're hidden and it knows that. However, it seems as though if the element has a title set, JAWS reads it no matter what. If I remove the title, JAWS reads nothing, but obviously this is in-accessible markup.</p> <p><strong>Possible Solutions</strong></p> <p>My first thought was to use a hidden label instead of the title, like this:</p> <pre><code>&lt;div id="placeholder" style="display:none;"&gt; &lt;label for="month" style="display:none"&gt;Month&lt;/label&gt; &lt;select id="month"&gt;...&lt;/select&gt; &lt;/div&gt; </code></pre> <p>This results in the exact same behavior, and now we lose the tool-tips for non-screen-reader users. Also we end up generating twice as much Html.</p> <p>The second option is to still use a label, put position it off the screen. That way it will be read by the screen-reader, but won't be seen by the visual user:</p> <pre><code>&lt;div id="placeholder" style="display:none;"&gt; &lt;label for="month" style="position:absolute;left:-5000px:width:1px;"&gt;Month&lt;/label&gt; &lt;select id="month"&gt;...&lt;/select&gt; &lt;/div&gt; </code></pre> <p>This actually works, but again we lose the tool-tip and still generate additional Html.</p> <p>My third possible solution is to recursively travel through the DOM in JavaScript, removing the title when the area is hidden and adding it back when the area is shown. This also works... but is pretty ugly for obvious reasons and doesn't really scale well to a more general case.</p> <p>Any other ideas anyone? Why is JAWS behaving this way?</p>
[ { "answer_id": 245437, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 1, "selected": false, "text": "<p>This definitely looks like a bug in JAWS as the spec definitively states that display:none should cause an element and its children not to be displayed in any media.</p>\n\n<p>However, playing with the speak: aural property might be useful? I don't know as I don't have JAWS available.</p>\n\n<p><a href=\"http://www.w3.org/TR/CSS2/aural.html#speaking-props\" rel=\"nofollow noreferrer\"><a href=\"http://www.w3.org/TR/CSS2/aural.html#speaking-props\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/aural.html#speaking-props</a></a></p>\n" }, { "answer_id": 29660365, "author": "Noah Herron", "author_id": 2612003, "author_profile": "https://Stackoverflow.com/users/2612003", "pm_score": 0, "selected": false, "text": "<p>Did you try this?</p>\n\n<pre><code>&lt;div id=\"placeholder\" style=\"display:none;\"&gt;\n &lt;select title=\"Month\" style=\"speak:none;\"&gt;\n &lt;option&gt;January&lt;/option&gt;\n &lt;option&gt;February&lt;/option&gt;\n ...\n &lt;/select&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>This has worked for me in the past when I wanted to make JAWS read one thing, and skip over something else that would normally be read.</p>\n" }, { "answer_id": 29811114, "author": "thunderboltz", "author_id": 369034, "author_profile": "https://Stackoverflow.com/users/369034", "pm_score": 2, "selected": false, "text": "<p>Give items the aria-hidden=\"true\" attribute, and it should be hidden from the screenreader.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9960/" ]
**The Situation** I have an area of the screen that can be shown and hidden via JavaScript (something like "show/hide advanced search options"). Inside this area there are form elements (select, checkbox, etc). For users using assistive technology like a screen-reader (in this case JAWS), we need to link these form elements with a label or use the "title" attribute to describe the purpose of each element. I'm using the title attribute because there isn't enough space for a label, and the tooltip you get is nice for non-screen-reader users. The code looks something like this: ``` <div id="placeholder" style="display:none;"> <select title="Month"> <option>January</option> <option>February</option> ... </select> </div> ``` **The Problem** Normally, JAWS will not read hidden elements... because well, they're hidden and it knows that. However, it seems as though if the element has a title set, JAWS reads it no matter what. If I remove the title, JAWS reads nothing, but obviously this is in-accessible markup. **Possible Solutions** My first thought was to use a hidden label instead of the title, like this: ``` <div id="placeholder" style="display:none;"> <label for="month" style="display:none">Month</label> <select id="month">...</select> </div> ``` This results in the exact same behavior, and now we lose the tool-tips for non-screen-reader users. Also we end up generating twice as much Html. The second option is to still use a label, put position it off the screen. That way it will be read by the screen-reader, but won't be seen by the visual user: ``` <div id="placeholder" style="display:none;"> <label for="month" style="position:absolute;left:-5000px:width:1px;">Month</label> <select id="month">...</select> </div> ``` This actually works, but again we lose the tool-tip and still generate additional Html. My third possible solution is to recursively travel through the DOM in JavaScript, removing the title when the area is hidden and adding it back when the area is shown. This also works... but is pretty ugly for obvious reasons and doesn't really scale well to a more general case. Any other ideas anyone? Why is JAWS behaving this way?
Give items the aria-hidden="true" attribute, and it should be hidden from the screenreader.
243,811
<p>Looking through some code I came across the following code</p> <pre><code>trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto)); </code></pre> <p>and I'd like to know if casting this way has any advantages over </p> <pre><code>trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto); </code></pre> <p>I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.</p>
[ { "answer_id": 243825, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": -1, "selected": false, "text": "<p>Both of these statements are identical. Pick whichever one you find more readable. The second method is more common in my experience, and it is the once that I prefer.</p>\n\n<p>I tend to use the cast method solely when I am working with reflection, and it reads nicer in that situation. All other times I find myself using the second way of casting.</p>\n" }, { "answer_id": 243835, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>The main case for doing it (IME) is when you need to safely cast in a generic class/method. Due to type erasure, you can't cast to <code>T</code> but if you've been provided a <code>Class&lt;? extends T&gt;</code> parameter then you can use that to cast and the result will be assignable to a variable of type <code>T</code>.</p>\n" }, { "answer_id": 243862, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "<p>These statements are not identical. The cast method is a normal method invocation (<code>invokevirtual</code> JVM instruction) while the other is a language construct (<code>checkcast</code> instruction). In the case you show above, you should use the second form: <code>(TrTuDocPackTypeDto) packDto</code></p>\n\n<p>The <code>cast</code> method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:</p>\n\n<pre><code>public &lt;T&gt; Set&lt;T&gt; find(Class&lt;T&gt; clz, Filter criteria) {\n List&lt;?&gt; raw = session.find(clz, criteria); /* A legacy, un-generic API. */\n Set&lt;T&gt; safe = new HashSet&lt;T&gt;();\n for (Object o : raw) \n safe.add(clz.cast(o));\n return safe;\n}\n</code></pre>\n\n<p>This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:</p>\n\n<pre><code>/* DO NOT DO THIS! */\nList raw = new ArrayList();\n...\nreturn (List&lt;Widget&gt;) raw;\n</code></pre>\n\n<p>The compiler will warn you, <code>Unchecked cast from List to List&lt;Widget&gt;</code>, meaning that in the ellipsis, someone could have added a <code>Gadget</code> to the raw list, which will eventually cause a <code>ClassCastException</code> when the caller iterates over the returned list of (supposed) <code>Widget</code> instances.</p>\n" }, { "answer_id": 643667, "author": "phtrivier", "author_id": 77804, "author_profile": "https://Stackoverflow.com/users/77804", "pm_score": 0, "selected": false, "text": "<p>I can't find an example where the cast method is possible and the cast syntax not. \nHowever, looking at the code, it seems that in case the cast is not possible, the cast method throws a ClassCastException with no type information attached, whereas the cast syntax will give you some hints (as in, \"could not cast Snoopy to TyrannosorusRex\")\n : </p>\n\n<pre><code>/**\n * Casts an object to the class or interface represented\n * by this &lt;tt&gt;Class&lt;/tt&gt; object.\n *\n * @param obj the object to be cast\n * @return the object after casting, or null if obj is null\n *\n * @throws ClassCastException if the object is not\n * null and is not assignable to the type T.\n *\n * @since 1.5\n */\npublic T cast(Object obj) {\nif (obj != null &amp;&amp; !isInstance(obj))\n throw new ClassCastException();\nreturn (T) obj;\n}\n</code></pre>\n" }, { "answer_id": 643722, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>With the first form</p>\n\n<pre><code>trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));\n</code></pre>\n\n<p>you can do this:</p>\n\n<pre><code>public void dynamicCast( Class clazz, Object o ) { \n this.x = clazz.cast( o );\n}\n</code></pre>\n\n<p>With the second you can't. The casting class should be hard coded.</p>\n\n<p>Why would you use a variable to cast in first place? That's another question. :) The first thing that comes to mind is, you don't know ( at compile time ) the class that will be casted to. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389/" ]
Looking through some code I came across the following code ``` trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto)); ``` and I'd like to know if casting this way has any advantages over ``` trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto); ``` I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.
These statements are not identical. The cast method is a normal method invocation (`invokevirtual` JVM instruction) while the other is a language construct (`checkcast` instruction). In the case you show above, you should use the second form: `(TrTuDocPackTypeDto) packDto` The `cast` method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this: ``` public <T> Set<T> find(Class<T> clz, Filter criteria) { List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */ Set<T> safe = new HashSet<T>(); for (Object o : raw) safe.add(clz.cast(o)); return safe; } ``` This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type: ``` /* DO NOT DO THIS! */ List raw = new ArrayList(); ... return (List<Widget>) raw; ``` The compiler will warn you, `Unchecked cast from List to List<Widget>`, meaning that in the ellipsis, someone could have added a `Gadget` to the raw list, which will eventually cause a `ClassCastException` when the caller iterates over the returned list of (supposed) `Widget` instances.
243,814
<p>I am attempting to deploy .NET 2.0 web services on IIS that has both 1.0 and 2.0 installed. This web server primarily serves a large .NET 1.0 application. </p> <p>I have copied by .NET 2.0 web service project to the server and have created a virtual directory to point to the necessary folder. </p> <p>When I set the ASP.NET version to 2.0 in IIS, The application prompts me for a username and password (when I attempt to open the site in the browser), If I set it back to 1.0, then I am not prompted for a password, but obviously get a full application error. </p> <p>I have anonymous access enabled (with a username / password) and have authenticated access checked as "Integrated Windows Authentication)</p> <p>How can I configure IIS so that I am not prompted for a password while having ASP.NET version set to 2.0?</p> <p>Thanks...</p> <p><strong>EDIT</strong> I had major connection problems and apparently created some duplicate posts...I'll delete the ones with no answers. </p>
[ { "answer_id": 243825, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": -1, "selected": false, "text": "<p>Both of these statements are identical. Pick whichever one you find more readable. The second method is more common in my experience, and it is the once that I prefer.</p>\n\n<p>I tend to use the cast method solely when I am working with reflection, and it reads nicer in that situation. All other times I find myself using the second way of casting.</p>\n" }, { "answer_id": 243835, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>The main case for doing it (IME) is when you need to safely cast in a generic class/method. Due to type erasure, you can't cast to <code>T</code> but if you've been provided a <code>Class&lt;? extends T&gt;</code> parameter then you can use that to cast and the result will be assignable to a variable of type <code>T</code>.</p>\n" }, { "answer_id": 243862, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "<p>These statements are not identical. The cast method is a normal method invocation (<code>invokevirtual</code> JVM instruction) while the other is a language construct (<code>checkcast</code> instruction). In the case you show above, you should use the second form: <code>(TrTuDocPackTypeDto) packDto</code></p>\n\n<p>The <code>cast</code> method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:</p>\n\n<pre><code>public &lt;T&gt; Set&lt;T&gt; find(Class&lt;T&gt; clz, Filter criteria) {\n List&lt;?&gt; raw = session.find(clz, criteria); /* A legacy, un-generic API. */\n Set&lt;T&gt; safe = new HashSet&lt;T&gt;();\n for (Object o : raw) \n safe.add(clz.cast(o));\n return safe;\n}\n</code></pre>\n\n<p>This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:</p>\n\n<pre><code>/* DO NOT DO THIS! */\nList raw = new ArrayList();\n...\nreturn (List&lt;Widget&gt;) raw;\n</code></pre>\n\n<p>The compiler will warn you, <code>Unchecked cast from List to List&lt;Widget&gt;</code>, meaning that in the ellipsis, someone could have added a <code>Gadget</code> to the raw list, which will eventually cause a <code>ClassCastException</code> when the caller iterates over the returned list of (supposed) <code>Widget</code> instances.</p>\n" }, { "answer_id": 643667, "author": "phtrivier", "author_id": 77804, "author_profile": "https://Stackoverflow.com/users/77804", "pm_score": 0, "selected": false, "text": "<p>I can't find an example where the cast method is possible and the cast syntax not. \nHowever, looking at the code, it seems that in case the cast is not possible, the cast method throws a ClassCastException with no type information attached, whereas the cast syntax will give you some hints (as in, \"could not cast Snoopy to TyrannosorusRex\")\n : </p>\n\n<pre><code>/**\n * Casts an object to the class or interface represented\n * by this &lt;tt&gt;Class&lt;/tt&gt; object.\n *\n * @param obj the object to be cast\n * @return the object after casting, or null if obj is null\n *\n * @throws ClassCastException if the object is not\n * null and is not assignable to the type T.\n *\n * @since 1.5\n */\npublic T cast(Object obj) {\nif (obj != null &amp;&amp; !isInstance(obj))\n throw new ClassCastException();\nreturn (T) obj;\n}\n</code></pre>\n" }, { "answer_id": 643722, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>With the first form</p>\n\n<pre><code>trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));\n</code></pre>\n\n<p>you can do this:</p>\n\n<pre><code>public void dynamicCast( Class clazz, Object o ) { \n this.x = clazz.cast( o );\n}\n</code></pre>\n\n<p>With the second you can't. The casting class should be hard coded.</p>\n\n<p>Why would you use a variable to cast in first place? That's another question. :) The first thing that comes to mind is, you don't know ( at compile time ) the class that will be casted to. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I am attempting to deploy .NET 2.0 web services on IIS that has both 1.0 and 2.0 installed. This web server primarily serves a large .NET 1.0 application. I have copied by .NET 2.0 web service project to the server and have created a virtual directory to point to the necessary folder. When I set the ASP.NET version to 2.0 in IIS, The application prompts me for a username and password (when I attempt to open the site in the browser), If I set it back to 1.0, then I am not prompted for a password, but obviously get a full application error. I have anonymous access enabled (with a username / password) and have authenticated access checked as "Integrated Windows Authentication) How can I configure IIS so that I am not prompted for a password while having ASP.NET version set to 2.0? Thanks... **EDIT** I had major connection problems and apparently created some duplicate posts...I'll delete the ones with no answers.
These statements are not identical. The cast method is a normal method invocation (`invokevirtual` JVM instruction) while the other is a language construct (`checkcast` instruction). In the case you show above, you should use the second form: `(TrTuDocPackTypeDto) packDto` The `cast` method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this: ``` public <T> Set<T> find(Class<T> clz, Filter criteria) { List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */ Set<T> safe = new HashSet<T>(); for (Object o : raw) safe.add(clz.cast(o)); return safe; } ``` This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type: ``` /* DO NOT DO THIS! */ List raw = new ArrayList(); ... return (List<Widget>) raw; ``` The compiler will warn you, `Unchecked cast from List to List<Widget>`, meaning that in the ellipsis, someone could have added a `Gadget` to the raw list, which will eventually cause a `ClassCastException` when the caller iterates over the returned list of (supposed) `Widget` instances.
243,831
<p>Is there a way to get the Unicode Block of a character in python? The <a href="http://www.python.org/doc/2.5.2/lib/module-unicodedata.html" rel="noreferrer">unicodedata</a> module doesn't seem to have what I need, and I couldn't find an external library for it.</p> <p>Basically, I need the same functionality as <a href="http://java.sun.com/javase/6/docs/api/java/lang/Character.UnicodeBlock.html#of(char)" rel="noreferrer"><code>Character.UnicodeBlock.of()</code></a> in java.</p>
[ { "answer_id": 245072, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 5, "selected": true, "text": "<p>I couldn't find one either. Strange!</p>\n\n<p>Luckily, the number of Unicode blocks is quite manageably small.</p>\n\n<p>This implementation accepts a one-character Unicode string, just like the functions in <code>unicodedata</code>. If your inputs are mostly ASCII, this linear search might even be faster than binary search using <code>bisect</code> or whatever. If I were submitting this for inclusion in the Python standard library, I'd probably write it as a binary search through an array of statically-initialized <code>struct</code>s in C.</p>\n\n<pre><code>def block(ch):\n '''\n Return the Unicode block name for ch, or None if ch has no block.\n\n &gt;&gt;&gt; block(u'a')\n 'Basic Latin'\n &gt;&gt;&gt; block(unichr(0x0b80))\n 'Tamil'\n &gt;&gt;&gt; block(unichr(0xe0080))\n\n '''\n\n assert isinstance(ch, unicode) and len(ch) == 1, repr(ch)\n cp = ord(ch)\n for start, end, name in _blocks:\n if start &lt;= cp &lt;= end:\n return name\n\ndef _initBlocks(text):\n global _blocks\n _blocks = []\n import re\n pattern = re.compile(r'([0-9A-F]+)\\.\\.([0-9A-F]+);\\ (\\S.*\\S)')\n for line in text.splitlines():\n m = pattern.match(line)\n if m:\n start, end, name = m.groups()\n _blocks.append((int(start, 16), int(end, 16), name))\n\n# retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt\n_initBlocks('''\n# Blocks-12.0.0.txt\n# Date: 2018-07-30, 19:40:00 GMT [KW]\n# © 2018 Unicode®, Inc.\n# For terms of use, see http://www.unicode.org/terms_of_use.html\n#\n# Unicode Character Database\n# For documentation, see http://www.unicode.org/reports/tr44/\n#\n# Format:\n# Start Code..End Code; Block Name\n\n# ================================================\n\n# Note: When comparing block names, casing, whitespace, hyphens,\n# and underbars are ignored.\n# For example, \"Latin Extended-A\" and \"latin extended a\" are equivalent.\n# For more information on the comparison of property values,\n# see UAX #44: http://www.unicode.org/reports/tr44/\n#\n# All block ranges start with a value where (cp MOD 16) = 0,\n# and end with a value where (cp MOD 16) = 15. In other words,\n# the last hexadecimal digit of the start of range is ...0\n# and the last hexadecimal digit of the end of range is ...F.\n# This constraint on block ranges guarantees that allocations\n# are done in terms of whole columns, and that code chart display\n# never involves splitting columns in the charts.\n#\n# All code points not explicitly listed for Block\n# have the value No_Block.\n\n# Property: Block\n#\n# @missing: 0000..10FFFF; No_Block\n\n0000..007F; Basic Latin\n0080..00FF; Latin-1 Supplement\n0100..017F; Latin Extended-A\n0180..024F; Latin Extended-B\n0250..02AF; IPA Extensions\n02B0..02FF; Spacing Modifier Letters\n0300..036F; Combining Diacritical Marks\n0370..03FF; Greek and Coptic\n0400..04FF; Cyrillic\n0500..052F; Cyrillic Supplement\n0530..058F; Armenian\n0590..05FF; Hebrew\n0600..06FF; Arabic\n0700..074F; Syriac\n0750..077F; Arabic Supplement\n0780..07BF; Thaana\n07C0..07FF; NKo\n0800..083F; Samaritan\n0840..085F; Mandaic\n0860..086F; Syriac Supplement\n08A0..08FF; Arabic Extended-A\n0900..097F; Devanagari\n0980..09FF; Bengali\n0A00..0A7F; Gurmukhi\n0A80..0AFF; Gujarati\n0B00..0B7F; Oriya\n0B80..0BFF; Tamil\n0C00..0C7F; Telugu\n0C80..0CFF; Kannada\n0D00..0D7F; Malayalam\n0D80..0DFF; Sinhala\n0E00..0E7F; Thai\n0E80..0EFF; Lao\n0F00..0FFF; Tibetan\n1000..109F; Myanmar\n10A0..10FF; Georgian\n1100..11FF; Hangul Jamo\n1200..137F; Ethiopic\n1380..139F; Ethiopic Supplement\n13A0..13FF; Cherokee\n1400..167F; Unified Canadian Aboriginal Syllabics\n1680..169F; Ogham\n16A0..16FF; Runic\n1700..171F; Tagalog\n1720..173F; Hanunoo\n1740..175F; Buhid\n1760..177F; Tagbanwa\n1780..17FF; Khmer\n1800..18AF; Mongolian\n18B0..18FF; Unified Canadian Aboriginal Syllabics Extended\n1900..194F; Limbu\n1950..197F; Tai Le\n1980..19DF; New Tai Lue\n19E0..19FF; Khmer Symbols\n1A00..1A1F; Buginese\n1A20..1AAF; Tai Tham\n1AB0..1AFF; Combining Diacritical Marks Extended\n1B00..1B7F; Balinese\n1B80..1BBF; Sundanese\n1BC0..1BFF; Batak\n1C00..1C4F; Lepcha\n1C50..1C7F; Ol Chiki\n1C80..1C8F; Cyrillic Extended-C\n1C90..1CBF; Georgian Extended\n1CC0..1CCF; Sundanese Supplement\n1CD0..1CFF; Vedic Extensions\n1D00..1D7F; Phonetic Extensions\n1D80..1DBF; Phonetic Extensions Supplement\n1DC0..1DFF; Combining Diacritical Marks Supplement\n1E00..1EFF; Latin Extended Additional\n1F00..1FFF; Greek Extended\n2000..206F; General Punctuation\n2070..209F; Superscripts and Subscripts\n20A0..20CF; Currency Symbols\n20D0..20FF; Combining Diacritical Marks for Symbols\n2100..214F; Letterlike Symbols\n2150..218F; Number Forms\n2190..21FF; Arrows\n2200..22FF; Mathematical Operators\n2300..23FF; Miscellaneous Technical\n2400..243F; Control Pictures\n2440..245F; Optical Character Recognition\n2460..24FF; Enclosed Alphanumerics\n2500..257F; Box Drawing\n2580..259F; Block Elements\n25A0..25FF; Geometric Shapes\n2600..26FF; Miscellaneous Symbols\n2700..27BF; Dingbats\n27C0..27EF; Miscellaneous Mathematical Symbols-A\n27F0..27FF; Supplemental Arrows-A\n2800..28FF; Braille Patterns\n2900..297F; Supplemental Arrows-B\n2980..29FF; Miscellaneous Mathematical Symbols-B\n2A00..2AFF; Supplemental Mathematical Operators\n2B00..2BFF; Miscellaneous Symbols and Arrows\n2C00..2C5F; Glagolitic\n2C60..2C7F; Latin Extended-C\n2C80..2CFF; Coptic\n2D00..2D2F; Georgian Supplement\n2D30..2D7F; Tifinagh\n2D80..2DDF; Ethiopic Extended\n2DE0..2DFF; Cyrillic Extended-A\n2E00..2E7F; Supplemental Punctuation\n2E80..2EFF; CJK Radicals Supplement\n2F00..2FDF; Kangxi Radicals\n2FF0..2FFF; Ideographic Description Characters\n3000..303F; CJK Symbols and Punctuation\n3040..309F; Hiragana\n30A0..30FF; Katakana\n3100..312F; Bopomofo\n3130..318F; Hangul Compatibility Jamo\n3190..319F; Kanbun\n31A0..31BF; Bopomofo Extended\n31C0..31EF; CJK Strokes\n31F0..31FF; Katakana Phonetic Extensions\n3200..32FF; Enclosed CJK Letters and Months\n3300..33FF; CJK Compatibility\n3400..4DBF; CJK Unified Ideographs Extension A\n4DC0..4DFF; Yijing Hexagram Symbols\n4E00..9FFF; CJK Unified Ideographs\nA000..A48F; Yi Syllables\nA490..A4CF; Yi Radicals\nA4D0..A4FF; Lisu\nA500..A63F; Vai\nA640..A69F; Cyrillic Extended-B\nA6A0..A6FF; Bamum\nA700..A71F; Modifier Tone Letters\nA720..A7FF; Latin Extended-D\nA800..A82F; Syloti Nagri\nA830..A83F; Common Indic Number Forms\nA840..A87F; Phags-pa\nA880..A8DF; Saurashtra\nA8E0..A8FF; Devanagari Extended\nA900..A92F; Kayah Li\nA930..A95F; Rejang\nA960..A97F; Hangul Jamo Extended-A\nA980..A9DF; Javanese\nA9E0..A9FF; Myanmar Extended-B\nAA00..AA5F; Cham\nAA60..AA7F; Myanmar Extended-A\nAA80..AADF; Tai Viet\nAAE0..AAFF; Meetei Mayek Extensions\nAB00..AB2F; Ethiopic Extended-A\nAB30..AB6F; Latin Extended-E\nAB70..ABBF; Cherokee Supplement\nABC0..ABFF; Meetei Mayek\nAC00..D7AF; Hangul Syllables\nD7B0..D7FF; Hangul Jamo Extended-B\nD800..DB7F; High Surrogates\nDB80..DBFF; High Private Use Surrogates\nDC00..DFFF; Low Surrogates\nE000..F8FF; Private Use Area\nF900..FAFF; CJK Compatibility Ideographs\nFB00..FB4F; Alphabetic Presentation Forms\nFB50..FDFF; Arabic Presentation Forms-A\nFE00..FE0F; Variation Selectors\nFE10..FE1F; Vertical Forms\nFE20..FE2F; Combining Half Marks\nFE30..FE4F; CJK Compatibility Forms\nFE50..FE6F; Small Form Variants\nFE70..FEFF; Arabic Presentation Forms-B\nFF00..FFEF; Halfwidth and Fullwidth Forms\nFFF0..FFFF; Specials\n10000..1007F; Linear B Syllabary\n10080..100FF; Linear B Ideograms\n10100..1013F; Aegean Numbers\n10140..1018F; Ancient Greek Numbers\n10190..101CF; Ancient Symbols\n101D0..101FF; Phaistos Disc\n10280..1029F; Lycian\n102A0..102DF; Carian\n102E0..102FF; Coptic Epact Numbers\n10300..1032F; Old Italic\n10330..1034F; Gothic\n10350..1037F; Old Permic\n10380..1039F; Ugaritic\n103A0..103DF; Old Persian\n10400..1044F; Deseret\n10450..1047F; Shavian\n10480..104AF; Osmanya\n104B0..104FF; Osage\n10500..1052F; Elbasan\n10530..1056F; Caucasian Albanian\n10600..1077F; Linear A\n10800..1083F; Cypriot Syllabary\n10840..1085F; Imperial Aramaic\n10860..1087F; Palmyrene\n10880..108AF; Nabataean\n108E0..108FF; Hatran\n10900..1091F; Phoenician\n10920..1093F; Lydian\n10980..1099F; Meroitic Hieroglyphs\n109A0..109FF; Meroitic Cursive\n10A00..10A5F; Kharoshthi\n10A60..10A7F; Old South Arabian\n10A80..10A9F; Old North Arabian\n10AC0..10AFF; Manichaean\n10B00..10B3F; Avestan\n10B40..10B5F; Inscriptional Parthian\n10B60..10B7F; Inscriptional Pahlavi\n10B80..10BAF; Psalter Pahlavi\n10C00..10C4F; Old Turkic\n10C80..10CFF; Old Hungarian\n10D00..10D3F; Hanifi Rohingya\n10E60..10E7F; Rumi Numeral Symbols\n10F00..10F2F; Old Sogdian\n10F30..10F6F; Sogdian\n10FE0..10FFF; Elymaic\n11000..1107F; Brahmi\n11080..110CF; Kaithi\n110D0..110FF; Sora Sompeng\n11100..1114F; Chakma\n11150..1117F; Mahajani\n11180..111DF; Sharada\n111E0..111FF; Sinhala Archaic Numbers\n11200..1124F; Khojki\n11280..112AF; Multani\n112B0..112FF; Khudawadi\n11300..1137F; Grantha\n11400..1147F; Newa\n11480..114DF; Tirhuta\n11580..115FF; Siddham\n11600..1165F; Modi\n11660..1167F; Mongolian Supplement\n11680..116CF; Takri\n11700..1173F; Ahom\n11800..1184F; Dogra\n118A0..118FF; Warang Citi\n119A0..119FF; Nandinagari\n11A00..11A4F; Zanabazar Square\n11A50..11AAF; Soyombo\n11AC0..11AFF; Pau Cin Hau\n11C00..11C6F; Bhaiksuki\n11C70..11CBF; Marchen\n11D00..11D5F; Masaram Gondi\n11D60..11DAF; Gunjala Gondi\n11EE0..11EFF; Makasar\n11FC0..11FFF; Tamil Supplement\n12000..123FF; Cuneiform\n12400..1247F; Cuneiform Numbers and Punctuation\n12480..1254F; Early Dynastic Cuneiform\n13000..1342F; Egyptian Hieroglyphs\n13430..1343F; Egyptian Hieroglyph Format Controls\n14400..1467F; Anatolian Hieroglyphs\n16800..16A3F; Bamum Supplement\n16A40..16A6F; Mro\n16AD0..16AFF; Bassa Vah\n16B00..16B8F; Pahawh Hmong\n16E40..16E9F; Medefaidrin\n16F00..16F9F; Miao\n16FE0..16FFF; Ideographic Symbols and Punctuation\n17000..187FF; Tangut\n18800..18AFF; Tangut Components\n1B000..1B0FF; Kana Supplement\n1B100..1B12F; Kana Extended-A\n1B130..1B16F; Small Kana Extension\n1B170..1B2FF; Nushu\n1BC00..1BC9F; Duployan\n1BCA0..1BCAF; Shorthand Format Controls\n1D000..1D0FF; Byzantine Musical Symbols\n1D100..1D1FF; Musical Symbols\n1D200..1D24F; Ancient Greek Musical Notation\n1D2E0..1D2FF; Mayan Numerals\n1D300..1D35F; Tai Xuan Jing Symbols\n1D360..1D37F; Counting Rod Numerals\n1D400..1D7FF; Mathematical Alphanumeric Symbols\n1D800..1DAAF; Sutton SignWriting\n1E000..1E02F; Glagolitic Supplement\n1E100..1E14F; Nyiakeng Puachue Hmong\n1E2C0..1E2FF; Wancho\n1E800..1E8DF; Mende Kikakui\n1E900..1E95F; Adlam\n1EC70..1ECBF; Indic Siyaq Numbers\n1ED00..1ED4F; Ottoman Siyaq Numbers\n1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols\n1F000..1F02F; Mahjong Tiles\n1F030..1F09F; Domino Tiles\n1F0A0..1F0FF; Playing Cards\n1F100..1F1FF; Enclosed Alphanumeric Supplement\n1F200..1F2FF; Enclosed Ideographic Supplement\n1F300..1F5FF; Miscellaneous Symbols and Pictographs\n1F600..1F64F; Emoticons\n1F650..1F67F; Ornamental Dingbats\n1F680..1F6FF; Transport and Map Symbols\n1F700..1F77F; Alchemical Symbols\n1F780..1F7FF; Geometric Shapes Extended\n1F800..1F8FF; Supplemental Arrows-C\n1F900..1F9FF; Supplemental Symbols and Pictographs\n1FA00..1FA6F; Chess Symbols\n1FA70..1FAFF; Symbols and Pictographs Extended-A\n20000..2A6DF; CJK Unified Ideographs Extension B\n2A700..2B73F; CJK Unified Ideographs Extension C\n2B740..2B81F; CJK Unified Ideographs Extension D\n2B820..2CEAF; CJK Unified Ideographs Extension E\n2CEB0..2EBEF; CJK Unified Ideographs Extension F\n2F800..2FA1F; CJK Compatibility Ideographs Supplement\nE0000..E007F; Tags\nE0100..E01EF; Variation Selectors Supplement\nF0000..FFFFF; Supplementary Private Use Area-A\n100000..10FFFF; Supplementary Private Use Area-B\n\n# EOF\n''')\n</code></pre>\n" }, { "answer_id": 1878387, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>unicodedata.name(chr)</p>\n" }, { "answer_id": 63930824, "author": "Koterpillar", "author_id": 288201, "author_profile": "https://Stackoverflow.com/users/288201", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-sh prettyprint-override\"><code>pip install unicodeblock\n</code></pre>\n<p>A third-party library <a href=\"https://github.com/neuront/pyunicodeblock\" rel=\"nofollow noreferrer\">UnicodeBlock</a> does this. Here is an example from their page:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; import unicodeblock.blocks\n&gt;&gt;&gt; print(unicodeblock.blocks.of('0'))\nDIGIT\n&gt;&gt;&gt; print(unicodeblock.blocks.of('汉'))\nCJK_UNIFIED_IDEOGRAPHS\n&gt;&gt;&gt; print(unicodeblock.blocks.of('あ'))\nHIRAGANA\n</code></pre>\n" }, { "answer_id": 72469378, "author": "Super Mario", "author_id": 7484554, "author_profile": "https://Stackoverflow.com/users/7484554", "pm_score": 0, "selected": false, "text": "<p>I created something based on @zaphod answer:</p>\n<pre><code>import re\n\nclass RangeDict(dict):\n def __getitem__(self, item):\n if not isinstance(item, range): # or xrange in Python 2\n for key in self:\n if item in key:\n return self[key]\n raise KeyError(item)\n else:\n return super().__getitem__(item)\n\nunicode_doc = '''\n# Blocks-14.0.0.txt\n# Date: 2021-01-22, 23:29:00 GMT [KW]\n# © 2021 Unicode®, Inc.\n# For terms of use, see http://www.unicode.org/terms_of_use.html\n#\n# Unicode Character Database\n# For documentation, see http://www.unicode.org/reports/tr44/\n#\n# Format:\n# Start Code..End Code; Block Name\n\n# ================================================\n\n# Note: When comparing block names, casing, whitespace, hyphens,\n# and underbars are ignored.\n# For example, &quot;Latin Extended-A&quot; and &quot;latin extended a&quot; are equivalent.\n# For more information on the comparison of property values,\n# see UAX #44: http://www.unicode.org/reports/tr44/\n#\n# All block ranges start with a value where (cp MOD 16) = 0,\n# and end with a value where (cp MOD 16) = 15. In other words,\n# the last hexadecimal digit of the start of range is ...0\n# and the last hexadecimal digit of the end of range is ...F.\n# This constraint on block ranges guarantees that allocations\n# are done in terms of whole columns, and that code chart display\n# never involves splitting columns in the charts.\n#\n# All code points not explicitly listed for Block\n# have the value No_Block.\n\n# Property: Block\n#\n# @missing: 0000..10FFFF; No_Block\n\n0000..007F; Basic Latin\n0080..00FF; Latin-1 Supplement\n0100..017F; Latin Extended-A\n0180..024F; Latin Extended-B\n0250..02AF; IPA Extensions\n02B0..02FF; Spacing Modifier Letters\n0300..036F; Combining Diacritical Marks\n0370..03FF; Greek and Coptic\n0400..04FF; Cyrillic\n0500..052F; Cyrillic Supplement\n0530..058F; Armenian\n0590..05FF; Hebrew\n0600..06FF; Arabic\n0700..074F; Syriac\n0750..077F; Arabic Supplement\n0780..07BF; Thaana\n07C0..07FF; NKo\n0800..083F; Samaritan\n0840..085F; Mandaic\n0860..086F; Syriac Supplement\n0870..089F; Arabic Extended-B\n08A0..08FF; Arabic Extended-A\n0900..097F; Devanagari\n0980..09FF; Bengali\n0A00..0A7F; Gurmukhi\n0A80..0AFF; Gujarati\n0B00..0B7F; Oriya\n0B80..0BFF; Tamil\n0C00..0C7F; Telugu\n0C80..0CFF; Kannada\n0D00..0D7F; Malayalam\n0D80..0DFF; Sinhala\n0E00..0E7F; Thai\n0E80..0EFF; Lao\n0F00..0FFF; Tibetan\n1000..109F; Myanmar\n10A0..10FF; Georgian\n1100..11FF; Hangul Jamo\n1200..137F; Ethiopic\n1380..139F; Ethiopic Supplement\n13A0..13FF; Cherokee\n1400..167F; Unified Canadian Aboriginal Syllabics\n1680..169F; Ogham\n16A0..16FF; Runic\n1700..171F; Tagalog\n1720..173F; Hanunoo\n1740..175F; Buhid\n1760..177F; Tagbanwa\n1780..17FF; Khmer\n1800..18AF; Mongolian\n18B0..18FF; Unified Canadian Aboriginal Syllabics Extended\n1900..194F; Limbu\n1950..197F; Tai Le\n1980..19DF; New Tai Lue\n19E0..19FF; Khmer Symbols\n1A00..1A1F; Buginese\n1A20..1AAF; Tai Tham\n1AB0..1AFF; Combining Diacritical Marks Extended\n1B00..1B7F; Balinese\n1B80..1BBF; Sundanese\n1BC0..1BFF; Batak\n1C00..1C4F; Lepcha\n1C50..1C7F; Ol Chiki\n1C80..1C8F; Cyrillic Extended-C\n1C90..1CBF; Georgian Extended\n1CC0..1CCF; Sundanese Supplement\n1CD0..1CFF; Vedic Extensions\n1D00..1D7F; Phonetic Extensions\n1D80..1DBF; Phonetic Extensions Supplement\n1DC0..1DFF; Combining Diacritical Marks Supplement\n1E00..1EFF; Latin Extended Additional\n1F00..1FFF; Greek Extended\n2000..206F; General Punctuation\n2070..209F; Superscripts and Subscripts\n20A0..20CF; Currency Symbols\n20D0..20FF; Combining Diacritical Marks for Symbols\n2100..214F; Letterlike Symbols\n2150..218F; Number Forms\n2190..21FF; Arrows\n2200..22FF; Mathematical Operators\n2300..23FF; Miscellaneous Technical\n2400..243F; Control Pictures\n2440..245F; Optical Character Recognition\n2460..24FF; Enclosed Alphanumerics\n2500..257F; Box Drawing\n2580..259F; Block Elements\n25A0..25FF; Geometric Shapes\n2600..26FF; Miscellaneous Symbols\n2700..27BF; Dingbats\n27C0..27EF; Miscellaneous Mathematical Symbols-A\n27F0..27FF; Supplemental Arrows-A\n2800..28FF; Braille Patterns\n2900..297F; Supplemental Arrows-B\n2980..29FF; Miscellaneous Mathematical Symbols-B\n2A00..2AFF; Supplemental Mathematical Operators\n2B00..2BFF; Miscellaneous Symbols and Arrows\n2C00..2C5F; Glagolitic\n2C60..2C7F; Latin Extended-C\n2C80..2CFF; Coptic\n2D00..2D2F; Georgian Supplement\n2D30..2D7F; Tifinagh\n2D80..2DDF; Ethiopic Extended\n2DE0..2DFF; Cyrillic Extended-A\n2E00..2E7F; Supplemental Punctuation\n2E80..2EFF; CJK Radicals Supplement\n2F00..2FDF; Kangxi Radicals\n2FF0..2FFF; Ideographic Description Characters\n3000..303F; CJK Symbols and Punctuation\n3040..309F; Hiragana\n30A0..30FF; Katakana\n3100..312F; Bopomofo\n3130..318F; Hangul Compatibility Jamo\n3190..319F; Kanbun\n31A0..31BF; Bopomofo Extended\n31C0..31EF; CJK Strokes\n31F0..31FF; Katakana Phonetic Extensions\n3200..32FF; Enclosed CJK Letters and Months\n3300..33FF; CJK Compatibility\n3400..4DBF; CJK Unified Ideographs Extension A\n4DC0..4DFF; Yijing Hexagram Symbols\n4E00..9FFF; CJK Unified Ideographs\nA000..A48F; Yi Syllables\nA490..A4CF; Yi Radicals\nA4D0..A4FF; Lisu\nA500..A63F; Vai\nA640..A69F; Cyrillic Extended-B\nA6A0..A6FF; Bamum\nA700..A71F; Modifier Tone Letters\nA720..A7FF; Latin Extended-D\nA800..A82F; Syloti Nagri\nA830..A83F; Common Indic Number Forms\nA840..A87F; Phags-pa\nA880..A8DF; Saurashtra\nA8E0..A8FF; Devanagari Extended\nA900..A92F; Kayah Li\nA930..A95F; Rejang\nA960..A97F; Hangul Jamo Extended-A\nA980..A9DF; Javanese\nA9E0..A9FF; Myanmar Extended-B\nAA00..AA5F; Cham\nAA60..AA7F; Myanmar Extended-A\nAA80..AADF; Tai Viet\nAAE0..AAFF; Meetei Mayek Extensions\nAB00..AB2F; Ethiopic Extended-A\nAB30..AB6F; Latin Extended-E\nAB70..ABBF; Cherokee Supplement\nABC0..ABFF; Meetei Mayek\nAC00..D7AF; Hangul Syllables\nD7B0..D7FF; Hangul Jamo Extended-B\nD800..DB7F; High Surrogates\nDB80..DBFF; High Private Use Surrogates\nDC00..DFFF; Low Surrogates\nE000..F8FF; Private Use Area\nF900..FAFF; CJK Compatibility Ideographs\nFB00..FB4F; Alphabetic Presentation Forms\nFB50..FDFF; Arabic Presentation Forms-A\nFE00..FE0F; Variation Selectors\nFE10..FE1F; Vertical Forms\nFE20..FE2F; Combining Half Marks\nFE30..FE4F; CJK Compatibility Forms\nFE50..FE6F; Small Form Variants\nFE70..FEFF; Arabic Presentation Forms-B\nFF00..FFEF; Halfwidth and Fullwidth Forms\nFFF0..FFFF; Specials\n10000..1007F; Linear B Syllabary\n10080..100FF; Linear B Ideograms\n10100..1013F; Aegean Numbers\n10140..1018F; Ancient Greek Numbers\n10190..101CF; Ancient Symbols\n101D0..101FF; Phaistos Disc\n10280..1029F; Lycian\n102A0..102DF; Carian\n102E0..102FF; Coptic Epact Numbers\n10300..1032F; Old Italic\n10330..1034F; Gothic\n10350..1037F; Old Permic\n10380..1039F; Ugaritic\n103A0..103DF; Old Persian\n10400..1044F; Deseret\n10450..1047F; Shavian\n10480..104AF; Osmanya\n104B0..104FF; Osage\n10500..1052F; Elbasan\n10530..1056F; Caucasian Albanian\n10570..105BF; Vithkuqi\n10600..1077F; Linear A\n10780..107BF; Latin Extended-F\n10800..1083F; Cypriot Syllabary\n10840..1085F; Imperial Aramaic\n10860..1087F; Palmyrene\n10880..108AF; Nabataean\n108E0..108FF; Hatran\n10900..1091F; Phoenician\n10920..1093F; Lydian\n10980..1099F; Meroitic Hieroglyphs\n109A0..109FF; Meroitic Cursive\n10A00..10A5F; Kharoshthi\n10A60..10A7F; Old South Arabian\n10A80..10A9F; Old North Arabian\n10AC0..10AFF; Manichaean\n10B00..10B3F; Avestan\n10B40..10B5F; Inscriptional Parthian\n10B60..10B7F; Inscriptional Pahlavi\n10B80..10BAF; Psalter Pahlavi\n10C00..10C4F; Old Turkic\n10C80..10CFF; Old Hungarian\n10D00..10D3F; Hanifi Rohingya\n10E60..10E7F; Rumi Numeral Symbols\n10E80..10EBF; Yezidi\n10F00..10F2F; Old Sogdian\n10F30..10F6F; Sogdian\n10F70..10FAF; Old Uyghur\n10FB0..10FDF; Chorasmian\n10FE0..10FFF; Elymaic\n11000..1107F; Brahmi\n11080..110CF; Kaithi\n110D0..110FF; Sora Sompeng\n11100..1114F; Chakma\n11150..1117F; Mahajani\n11180..111DF; Sharada\n111E0..111FF; Sinhala Archaic Numbers\n11200..1124F; Khojki\n11280..112AF; Multani\n112B0..112FF; Khudawadi\n11300..1137F; Grantha\n11400..1147F; Newa\n11480..114DF; Tirhuta\n11580..115FF; Siddham\n11600..1165F; Modi\n11660..1167F; Mongolian Supplement\n11680..116CF; Takri\n11700..1174F; Ahom\n11800..1184F; Dogra\n118A0..118FF; Warang Citi\n11900..1195F; Dives Akuru\n119A0..119FF; Nandinagari\n11A00..11A4F; Zanabazar Square\n11A50..11AAF; Soyombo\n11AB0..11ABF; Unified Canadian Aboriginal Syllabics Extended-A\n11AC0..11AFF; Pau Cin Hau\n11C00..11C6F; Bhaiksuki\n11C70..11CBF; Marchen\n11D00..11D5F; Masaram Gondi\n11D60..11DAF; Gunjala Gondi\n11EE0..11EFF; Makasar\n11FB0..11FBF; Lisu Supplement\n11FC0..11FFF; Tamil Supplement\n12000..123FF; Cuneiform\n12400..1247F; Cuneiform Numbers and Punctuation\n12480..1254F; Early Dynastic Cuneiform\n12F90..12FFF; Cypro-Minoan\n13000..1342F; Egyptian Hieroglyphs\n13430..1343F; Egyptian Hieroglyph Format Controls\n14400..1467F; Anatolian Hieroglyphs\n16800..16A3F; Bamum Supplement\n16A40..16A6F; Mro\n16A70..16ACF; Tangsa\n16AD0..16AFF; Bassa Vah\n16B00..16B8F; Pahawh Hmong\n16E40..16E9F; Medefaidrin\n16F00..16F9F; Miao\n16FE0..16FFF; Ideographic Symbols and Punctuation\n17000..187FF; Tangut\n18800..18AFF; Tangut Components\n18B00..18CFF; Khitan Small Script\n18D00..18D7F; Tangut Supplement\n1AFF0..1AFFF; Kana Extended-B\n1B000..1B0FF; Kana Supplement\n1B100..1B12F; Kana Extended-A\n1B130..1B16F; Small Kana Extension\n1B170..1B2FF; Nushu\n1BC00..1BC9F; Duployan\n1BCA0..1BCAF; Shorthand Format Controls\n1CF00..1CFCF; Znamenny Musical Notation\n1D000..1D0FF; Byzantine Musical Symbols\n1D100..1D1FF; Musical Symbols\n1D200..1D24F; Ancient Greek Musical Notation\n1D2E0..1D2FF; Mayan Numerals\n1D300..1D35F; Tai Xuan Jing Symbols\n1D360..1D37F; Counting Rod Numerals\n1D400..1D7FF; Mathematical Alphanumeric Symbols\n1D800..1DAAF; Sutton SignWriting\n1DF00..1DFFF; Latin Extended-G\n1E000..1E02F; Glagolitic Supplement\n1E100..1E14F; Nyiakeng Puachue Hmong\n1E290..1E2BF; Toto\n1E2C0..1E2FF; Wancho\n1E7E0..1E7FF; Ethiopic Extended-B\n1E800..1E8DF; Mende Kikakui\n1E900..1E95F; Adlam\n1EC70..1ECBF; Indic Siyaq Numbers\n1ED00..1ED4F; Ottoman Siyaq Numbers\n1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols\n1F000..1F02F; Mahjong Tiles\n1F030..1F09F; Domino Tiles\n1F0A0..1F0FF; Playing Cards\n1F100..1F1FF; Enclosed Alphanumeric Supplement\n1F200..1F2FF; Enclosed Ideographic Supplement\n1F300..1F5FF; Miscellaneous Symbols and Pictographs\n1F600..1F64F; Emoticons\n1F650..1F67F; Ornamental Dingbats\n1F680..1F6FF; Transport and Map Symbols\n1F700..1F77F; Alchemical Symbols\n1F780..1F7FF; Geometric Shapes Extended\n1F800..1F8FF; Supplemental Arrows-C\n1F900..1F9FF; Supplemental Symbols and Pictographs\n1FA00..1FA6F; Chess Symbols\n1FA70..1FAFF; Symbols and Pictographs Extended-A\n1FB00..1FBFF; Symbols for Legacy Computing\n20000..2A6DF; CJK Unified Ideographs Extension B\n2A700..2B73F; CJK Unified Ideographs Extension C\n2B740..2B81F; CJK Unified Ideographs Extension D\n2B820..2CEAF; CJK Unified Ideographs Extension E\n2CEB0..2EBEF; CJK Unified Ideographs Extension F\n2F800..2FA1F; CJK Compatibility Ideographs Supplement\n30000..3134F; CJK Unified Ideographs Extension G\nE0000..E007F; Tags\nE0100..E01EF; Variation Selectors Supplement\nF0000..FFFFF; Supplementary Private Use Area-A\n100000..10FFFF; Supplementary Private Use Area-B\n\n# EOF\n'''\n\ndef parse_unicode_blocks(txt):\n pattern = re.compile(r'([0-9A-F]+)\\.\\.([0-9A-F]+);\\ (\\S.*\\S)')\n blocks = RangeDict()\n for line in txt.splitlines():\n m = pattern.match(line)\n if m:\n start, end, block_name = m.groups()\n blocks[range(int(start, 16),int(end, 16))] = block_name\n return blocks\n\nblocks = parse_unicode_blocks(unicode_doc)\n\n\ndef block(ch, unicode_blocks=blocks):\n if isinstance(ch, str) and len(ch) == 1:\n cp = ord(ch)\n return blocks[cp]\n else:\n return ''\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
Is there a way to get the Unicode Block of a character in python? The [unicodedata](http://www.python.org/doc/2.5.2/lib/module-unicodedata.html) module doesn't seem to have what I need, and I couldn't find an external library for it. Basically, I need the same functionality as [`Character.UnicodeBlock.of()`](http://java.sun.com/javase/6/docs/api/java/lang/Character.UnicodeBlock.html#of(char)) in java.
I couldn't find one either. Strange! Luckily, the number of Unicode blocks is quite manageably small. This implementation accepts a one-character Unicode string, just like the functions in `unicodedata`. If your inputs are mostly ASCII, this linear search might even be faster than binary search using `bisect` or whatever. If I were submitting this for inclusion in the Python standard library, I'd probably write it as a binary search through an array of statically-initialized `struct`s in C. ``` def block(ch): ''' Return the Unicode block name for ch, or None if ch has no block. >>> block(u'a') 'Basic Latin' >>> block(unichr(0x0b80)) 'Tamil' >>> block(unichr(0xe0080)) ''' assert isinstance(ch, unicode) and len(ch) == 1, repr(ch) cp = ord(ch) for start, end, name in _blocks: if start <= cp <= end: return name def _initBlocks(text): global _blocks _blocks = [] import re pattern = re.compile(r'([0-9A-F]+)\.\.([0-9A-F]+);\ (\S.*\S)') for line in text.splitlines(): m = pattern.match(line) if m: start, end, name = m.groups() _blocks.append((int(start, 16), int(end, 16), name)) # retrieved from http://unicode.org/Public/UNIDATA/Blocks.txt _initBlocks(''' # Blocks-12.0.0.txt # Date: 2018-07-30, 19:40:00 GMT [KW] # © 2018 Unicode®, Inc. # For terms of use, see http://www.unicode.org/terms_of_use.html # # Unicode Character Database # For documentation, see http://www.unicode.org/reports/tr44/ # # Format: # Start Code..End Code; Block Name # ================================================ # Note: When comparing block names, casing, whitespace, hyphens, # and underbars are ignored. # For example, "Latin Extended-A" and "latin extended a" are equivalent. # For more information on the comparison of property values, # see UAX #44: http://www.unicode.org/reports/tr44/ # # All block ranges start with a value where (cp MOD 16) = 0, # and end with a value where (cp MOD 16) = 15. In other words, # the last hexadecimal digit of the start of range is ...0 # and the last hexadecimal digit of the end of range is ...F. # This constraint on block ranges guarantees that allocations # are done in terms of whole columns, and that code chart display # never involves splitting columns in the charts. # # All code points not explicitly listed for Block # have the value No_Block. # Property: Block # # @missing: 0000..10FFFF; No_Block 0000..007F; Basic Latin 0080..00FF; Latin-1 Supplement 0100..017F; Latin Extended-A 0180..024F; Latin Extended-B 0250..02AF; IPA Extensions 02B0..02FF; Spacing Modifier Letters 0300..036F; Combining Diacritical Marks 0370..03FF; Greek and Coptic 0400..04FF; Cyrillic 0500..052F; Cyrillic Supplement 0530..058F; Armenian 0590..05FF; Hebrew 0600..06FF; Arabic 0700..074F; Syriac 0750..077F; Arabic Supplement 0780..07BF; Thaana 07C0..07FF; NKo 0800..083F; Samaritan 0840..085F; Mandaic 0860..086F; Syriac Supplement 08A0..08FF; Arabic Extended-A 0900..097F; Devanagari 0980..09FF; Bengali 0A00..0A7F; Gurmukhi 0A80..0AFF; Gujarati 0B00..0B7F; Oriya 0B80..0BFF; Tamil 0C00..0C7F; Telugu 0C80..0CFF; Kannada 0D00..0D7F; Malayalam 0D80..0DFF; Sinhala 0E00..0E7F; Thai 0E80..0EFF; Lao 0F00..0FFF; Tibetan 1000..109F; Myanmar 10A0..10FF; Georgian 1100..11FF; Hangul Jamo 1200..137F; Ethiopic 1380..139F; Ethiopic Supplement 13A0..13FF; Cherokee 1400..167F; Unified Canadian Aboriginal Syllabics 1680..169F; Ogham 16A0..16FF; Runic 1700..171F; Tagalog 1720..173F; Hanunoo 1740..175F; Buhid 1760..177F; Tagbanwa 1780..17FF; Khmer 1800..18AF; Mongolian 18B0..18FF; Unified Canadian Aboriginal Syllabics Extended 1900..194F; Limbu 1950..197F; Tai Le 1980..19DF; New Tai Lue 19E0..19FF; Khmer Symbols 1A00..1A1F; Buginese 1A20..1AAF; Tai Tham 1AB0..1AFF; Combining Diacritical Marks Extended 1B00..1B7F; Balinese 1B80..1BBF; Sundanese 1BC0..1BFF; Batak 1C00..1C4F; Lepcha 1C50..1C7F; Ol Chiki 1C80..1C8F; Cyrillic Extended-C 1C90..1CBF; Georgian Extended 1CC0..1CCF; Sundanese Supplement 1CD0..1CFF; Vedic Extensions 1D00..1D7F; Phonetic Extensions 1D80..1DBF; Phonetic Extensions Supplement 1DC0..1DFF; Combining Diacritical Marks Supplement 1E00..1EFF; Latin Extended Additional 1F00..1FFF; Greek Extended 2000..206F; General Punctuation 2070..209F; Superscripts and Subscripts 20A0..20CF; Currency Symbols 20D0..20FF; Combining Diacritical Marks for Symbols 2100..214F; Letterlike Symbols 2150..218F; Number Forms 2190..21FF; Arrows 2200..22FF; Mathematical Operators 2300..23FF; Miscellaneous Technical 2400..243F; Control Pictures 2440..245F; Optical Character Recognition 2460..24FF; Enclosed Alphanumerics 2500..257F; Box Drawing 2580..259F; Block Elements 25A0..25FF; Geometric Shapes 2600..26FF; Miscellaneous Symbols 2700..27BF; Dingbats 27C0..27EF; Miscellaneous Mathematical Symbols-A 27F0..27FF; Supplemental Arrows-A 2800..28FF; Braille Patterns 2900..297F; Supplemental Arrows-B 2980..29FF; Miscellaneous Mathematical Symbols-B 2A00..2AFF; Supplemental Mathematical Operators 2B00..2BFF; Miscellaneous Symbols and Arrows 2C00..2C5F; Glagolitic 2C60..2C7F; Latin Extended-C 2C80..2CFF; Coptic 2D00..2D2F; Georgian Supplement 2D30..2D7F; Tifinagh 2D80..2DDF; Ethiopic Extended 2DE0..2DFF; Cyrillic Extended-A 2E00..2E7F; Supplemental Punctuation 2E80..2EFF; CJK Radicals Supplement 2F00..2FDF; Kangxi Radicals 2FF0..2FFF; Ideographic Description Characters 3000..303F; CJK Symbols and Punctuation 3040..309F; Hiragana 30A0..30FF; Katakana 3100..312F; Bopomofo 3130..318F; Hangul Compatibility Jamo 3190..319F; Kanbun 31A0..31BF; Bopomofo Extended 31C0..31EF; CJK Strokes 31F0..31FF; Katakana Phonetic Extensions 3200..32FF; Enclosed CJK Letters and Months 3300..33FF; CJK Compatibility 3400..4DBF; CJK Unified Ideographs Extension A 4DC0..4DFF; Yijing Hexagram Symbols 4E00..9FFF; CJK Unified Ideographs A000..A48F; Yi Syllables A490..A4CF; Yi Radicals A4D0..A4FF; Lisu A500..A63F; Vai A640..A69F; Cyrillic Extended-B A6A0..A6FF; Bamum A700..A71F; Modifier Tone Letters A720..A7FF; Latin Extended-D A800..A82F; Syloti Nagri A830..A83F; Common Indic Number Forms A840..A87F; Phags-pa A880..A8DF; Saurashtra A8E0..A8FF; Devanagari Extended A900..A92F; Kayah Li A930..A95F; Rejang A960..A97F; Hangul Jamo Extended-A A980..A9DF; Javanese A9E0..A9FF; Myanmar Extended-B AA00..AA5F; Cham AA60..AA7F; Myanmar Extended-A AA80..AADF; Tai Viet AAE0..AAFF; Meetei Mayek Extensions AB00..AB2F; Ethiopic Extended-A AB30..AB6F; Latin Extended-E AB70..ABBF; Cherokee Supplement ABC0..ABFF; Meetei Mayek AC00..D7AF; Hangul Syllables D7B0..D7FF; Hangul Jamo Extended-B D800..DB7F; High Surrogates DB80..DBFF; High Private Use Surrogates DC00..DFFF; Low Surrogates E000..F8FF; Private Use Area F900..FAFF; CJK Compatibility Ideographs FB00..FB4F; Alphabetic Presentation Forms FB50..FDFF; Arabic Presentation Forms-A FE00..FE0F; Variation Selectors FE10..FE1F; Vertical Forms FE20..FE2F; Combining Half Marks FE30..FE4F; CJK Compatibility Forms FE50..FE6F; Small Form Variants FE70..FEFF; Arabic Presentation Forms-B FF00..FFEF; Halfwidth and Fullwidth Forms FFF0..FFFF; Specials 10000..1007F; Linear B Syllabary 10080..100FF; Linear B Ideograms 10100..1013F; Aegean Numbers 10140..1018F; Ancient Greek Numbers 10190..101CF; Ancient Symbols 101D0..101FF; Phaistos Disc 10280..1029F; Lycian 102A0..102DF; Carian 102E0..102FF; Coptic Epact Numbers 10300..1032F; Old Italic 10330..1034F; Gothic 10350..1037F; Old Permic 10380..1039F; Ugaritic 103A0..103DF; Old Persian 10400..1044F; Deseret 10450..1047F; Shavian 10480..104AF; Osmanya 104B0..104FF; Osage 10500..1052F; Elbasan 10530..1056F; Caucasian Albanian 10600..1077F; Linear A 10800..1083F; Cypriot Syllabary 10840..1085F; Imperial Aramaic 10860..1087F; Palmyrene 10880..108AF; Nabataean 108E0..108FF; Hatran 10900..1091F; Phoenician 10920..1093F; Lydian 10980..1099F; Meroitic Hieroglyphs 109A0..109FF; Meroitic Cursive 10A00..10A5F; Kharoshthi 10A60..10A7F; Old South Arabian 10A80..10A9F; Old North Arabian 10AC0..10AFF; Manichaean 10B00..10B3F; Avestan 10B40..10B5F; Inscriptional Parthian 10B60..10B7F; Inscriptional Pahlavi 10B80..10BAF; Psalter Pahlavi 10C00..10C4F; Old Turkic 10C80..10CFF; Old Hungarian 10D00..10D3F; Hanifi Rohingya 10E60..10E7F; Rumi Numeral Symbols 10F00..10F2F; Old Sogdian 10F30..10F6F; Sogdian 10FE0..10FFF; Elymaic 11000..1107F; Brahmi 11080..110CF; Kaithi 110D0..110FF; Sora Sompeng 11100..1114F; Chakma 11150..1117F; Mahajani 11180..111DF; Sharada 111E0..111FF; Sinhala Archaic Numbers 11200..1124F; Khojki 11280..112AF; Multani 112B0..112FF; Khudawadi 11300..1137F; Grantha 11400..1147F; Newa 11480..114DF; Tirhuta 11580..115FF; Siddham 11600..1165F; Modi 11660..1167F; Mongolian Supplement 11680..116CF; Takri 11700..1173F; Ahom 11800..1184F; Dogra 118A0..118FF; Warang Citi 119A0..119FF; Nandinagari 11A00..11A4F; Zanabazar Square 11A50..11AAF; Soyombo 11AC0..11AFF; Pau Cin Hau 11C00..11C6F; Bhaiksuki 11C70..11CBF; Marchen 11D00..11D5F; Masaram Gondi 11D60..11DAF; Gunjala Gondi 11EE0..11EFF; Makasar 11FC0..11FFF; Tamil Supplement 12000..123FF; Cuneiform 12400..1247F; Cuneiform Numbers and Punctuation 12480..1254F; Early Dynastic Cuneiform 13000..1342F; Egyptian Hieroglyphs 13430..1343F; Egyptian Hieroglyph Format Controls 14400..1467F; Anatolian Hieroglyphs 16800..16A3F; Bamum Supplement 16A40..16A6F; Mro 16AD0..16AFF; Bassa Vah 16B00..16B8F; Pahawh Hmong 16E40..16E9F; Medefaidrin 16F00..16F9F; Miao 16FE0..16FFF; Ideographic Symbols and Punctuation 17000..187FF; Tangut 18800..18AFF; Tangut Components 1B000..1B0FF; Kana Supplement 1B100..1B12F; Kana Extended-A 1B130..1B16F; Small Kana Extension 1B170..1B2FF; Nushu 1BC00..1BC9F; Duployan 1BCA0..1BCAF; Shorthand Format Controls 1D000..1D0FF; Byzantine Musical Symbols 1D100..1D1FF; Musical Symbols 1D200..1D24F; Ancient Greek Musical Notation 1D2E0..1D2FF; Mayan Numerals 1D300..1D35F; Tai Xuan Jing Symbols 1D360..1D37F; Counting Rod Numerals 1D400..1D7FF; Mathematical Alphanumeric Symbols 1D800..1DAAF; Sutton SignWriting 1E000..1E02F; Glagolitic Supplement 1E100..1E14F; Nyiakeng Puachue Hmong 1E2C0..1E2FF; Wancho 1E800..1E8DF; Mende Kikakui 1E900..1E95F; Adlam 1EC70..1ECBF; Indic Siyaq Numbers 1ED00..1ED4F; Ottoman Siyaq Numbers 1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols 1F000..1F02F; Mahjong Tiles 1F030..1F09F; Domino Tiles 1F0A0..1F0FF; Playing Cards 1F100..1F1FF; Enclosed Alphanumeric Supplement 1F200..1F2FF; Enclosed Ideographic Supplement 1F300..1F5FF; Miscellaneous Symbols and Pictographs 1F600..1F64F; Emoticons 1F650..1F67F; Ornamental Dingbats 1F680..1F6FF; Transport and Map Symbols 1F700..1F77F; Alchemical Symbols 1F780..1F7FF; Geometric Shapes Extended 1F800..1F8FF; Supplemental Arrows-C 1F900..1F9FF; Supplemental Symbols and Pictographs 1FA00..1FA6F; Chess Symbols 1FA70..1FAFF; Symbols and Pictographs Extended-A 20000..2A6DF; CJK Unified Ideographs Extension B 2A700..2B73F; CJK Unified Ideographs Extension C 2B740..2B81F; CJK Unified Ideographs Extension D 2B820..2CEAF; CJK Unified Ideographs Extension E 2CEB0..2EBEF; CJK Unified Ideographs Extension F 2F800..2FA1F; CJK Compatibility Ideographs Supplement E0000..E007F; Tags E0100..E01EF; Variation Selectors Supplement F0000..FFFFF; Supplementary Private Use Area-A 100000..10FFFF; Supplementary Private Use Area-B # EOF ''') ```
243,836
<p>Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?</p> <p>I mean, something like Apache Commons' <code>PropertyUtilsBean.copyProperties()</code></p>
[ { "answer_id": 244116, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": true, "text": "<p>If your class does not modify <code>__getitem__</code> or <code>__setitem__</code> for special attribute access all your attributes are stored in <code>__dict__</code> so you can do:</p>\n\n<pre><code> nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy\n</code></pre>\n\n<p>If you use python properties you should look at <code>inspect.getmembers()</code> and filter out the ones you want to copy.</p>\n" }, { "answer_id": 244654, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 6, "selected": false, "text": "<p>Try <code>destination.__dict__.update(source.__dict__)</code>.</p>\n" }, { "answer_id": 248608, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "<p>At the risk of being modded down, is there <strike>a decent</strike> any use-case for this? </p>\n\n<p>Unless we know exactly what it's for, we can't sensibly call it as \"broken\" as it seems.</p>\n\n<p>Perhaps try this:</p>\n\n<pre><code>firstobject.an_attribute = secondobject.an_attribute\nfirstobject.another_attribute = secondobject.another_attribute\n</code></pre>\n\n<p>That's the sane way of copying things between instances.</p>\n" }, { "answer_id": 252393, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 2, "selected": false, "text": "<p>If you have to do this, I guess the nicest way is to have a class attribute something like :</p>\n\n<pre><code>Class Copyable(object):\n copyable_attributes = ('an_attribute', 'another_attribute')\n</code></pre>\n\n<p>Then iterate them explicitly and use <code>setattr(new, attr, getattr(old, attr))</code>. I still believe it can be solved with a better design though, and don't recommend it.</p>\n" }, { "answer_id": 48970465, "author": "user", "author_id": 4934640, "author_profile": "https://Stackoverflow.com/users/4934640", "pm_score": 1, "selected": false, "text": "<p>Using this you can almost copy everything from one object to another:</p>\n\n<pre><code>import sys\n\n_target_object = sys.stderr\n_target_object_class_type = type( _target_object )\n\nclass TargetCopiedObject(_target_object_class_type):\n \"\"\"\n Which special methods bypasses __getattribute__ in Python?\n https://stackoverflow.com/questions/12872695/which-special-methods-bypasses\n \"\"\"\n\n if hasattr( _target_object, \"__abstractmethods__\" ):\n __abstractmethods__ = _target_object.__abstractmethods__\n\n if hasattr( _target_object, \"__base__\" ):\n __base__ = _target_object.__base__\n\n if hasattr( _target_object, \"__bases__\" ):\n __bases__ = _target_object.__bases__\n\n if hasattr( _target_object, \"__basicsize__\" ):\n __basicsize__ = _target_object.__basicsize__\n\n if hasattr( _target_object, \"__call__\" ):\n __call__ = _target_object.__call__\n\n if hasattr( _target_object, \"__class__\" ):\n __class__ = _target_object.__class__\n\n if hasattr( _target_object, \"__delattr__\" ):\n __delattr__ = _target_object.__delattr__\n\n if hasattr( _target_object, \"__dict__\" ):\n __dict__ = _target_object.__dict__\n\n if hasattr( _target_object, \"__dictoffset__\" ):\n __dictoffset__ = _target_object.__dictoffset__\n\n if hasattr( _target_object, \"__dir__\" ):\n __dir__ = _target_object.__dir__\n\n if hasattr( _target_object, \"__doc__\" ):\n __doc__ = _target_object.__doc__\n\n if hasattr( _target_object, \"__eq__\" ):\n __eq__ = _target_object.__eq__\n\n if hasattr( _target_object, \"__flags__\" ):\n __flags__ = _target_object.__flags__\n\n if hasattr( _target_object, \"__format__\" ):\n __format__ = _target_object.__format__\n\n if hasattr( _target_object, \"__ge__\" ):\n __ge__ = _target_object.__ge__\n\n if hasattr( _target_object, \"__getattribute__\" ):\n __getattribute__ = _target_object.__getattribute__\n\n if hasattr( _target_object, \"__gt__\" ):\n __gt__ = _target_object.__gt__\n\n if hasattr( _target_object, \"__hash__\" ):\n __hash__ = _target_object.__hash__\n\n if hasattr( _target_object, \"__init__\" ):\n __init__ = _target_object.__init__\n\n if hasattr( _target_object, \"__init_subclass__\" ):\n __init_subclass__ = _target_object.__init_subclass__\n\n if hasattr( _target_object, \"__instancecheck__\" ):\n __instancecheck__ = _target_object.__instancecheck__\n\n if hasattr( _target_object, \"__itemsize__\" ):\n __itemsize__ = _target_object.__itemsize__\n\n if hasattr( _target_object, \"__le__\" ):\n __le__ = _target_object.__le__\n\n if hasattr( _target_object, \"__lt__\" ):\n __lt__ = _target_object.__lt__\n\n if hasattr( _target_object, \"__module__\" ):\n __module__ = _target_object.__module__\n\n if hasattr( _target_object, \"__mro__\" ):\n __mro__ = _target_object.__mro__\n\n if hasattr( _target_object, \"__name__\" ):\n __name__ = _target_object.__name__\n\n if hasattr( _target_object, \"__ne__\" ):\n __ne__ = _target_object.__ne__\n\n if hasattr( _target_object, \"__new__\" ):\n __new__ = _target_object.__new__\n\n if hasattr( _target_object, \"__prepare__\" ):\n __prepare__ = _target_object.__prepare__\n\n if hasattr( _target_object, \"__qualname__\" ):\n __qualname__ = _target_object.__qualname__\n\n if hasattr( _target_object, \"__reduce__\" ):\n __reduce__ = _target_object.__reduce__\n\n if hasattr( _target_object, \"__reduce_ex__\" ):\n __reduce_ex__ = _target_object.__reduce_ex__\n\n if hasattr( _target_object, \"__repr__\" ):\n __repr__ = _target_object.__repr__\n\n if hasattr( _target_object, \"__setattr__\" ):\n __setattr__ = _target_object.__setattr__\n\n if hasattr( _target_object, \"__sizeof__\" ):\n __sizeof__ = _target_object.__sizeof__\n\n if hasattr( _target_object, \"__str__\" ):\n __str__ = _target_object.__str__\n\n if hasattr( _target_object, \"__subclasscheck__\" ):\n __subclasscheck__ = _target_object.__subclasscheck__\n\n if hasattr( _target_object, \"__subclasses__\" ):\n __subclasses__ = _target_object.__subclasses__\n\n if hasattr( _target_object, \"__subclasshook__\" ):\n __subclasshook__ = _target_object.__subclasshook__\n\n if hasattr( _target_object, \"__text_signature__\" ):\n __text_signature__ = _target_object.__text_signature__\n\n if hasattr( _target_object, \"__weakrefoffset__\" ):\n __weakrefoffset__ = _target_object.__weakrefoffset__\n\n if hasattr( _target_object, \"mro\" ):\n mro = _target_object.mro\n\n def __init__(self):\n \"\"\"\n Override any super class `type( _target_object )` constructor,\n so we can instantiate any kind of replacement object.\n\n Assures all properties were statically replaced just above. This\n should happen in case some new attribute is added to the python\n language.\n\n This also ignores the only two methods which are not equal,\n `__init__()` and `__getattribute__()`.\n\n How do you programmatically set an attribute?\n https://stackoverflow.com/questions/285061/how-do-you-programmatically\n \"\"\"\n different_methods = set([\"__init__\", \"__getattribute__\"])\n attributes_to_check = set( dir( object ) + dir( type ) )\n attributes_to_copy = dir( _target_object )\n\n # Check for missing magic built-ins methods on the class static initialization\n for attribute in attributes_to_check:\n\n if attribute not in different_methods \\\n and hasattr( _target_object, attribute ):\n\n base_class_attribute = self.__getattribute__( attribute )\n target_class_attribute = _target_object.__getattribute__( attribute )\n\n if base_class_attribute != target_class_attribute:\n sys.stdout.write(\n \" The base class attribute `%s` is different from the \"\n \"target class:\\n%s\\n%s\\n\\n\" % ( attribute,\n base_class_attribute, \n target_class_attribute ) )\n # Finally copy everything it can\n different_methods.update( attributes_to_check )\n\n for attribute in attributes_to_copy:\n\n if attribute not in different_methods:\n print( \"Setting:\", attribute )\n\n try:\n target_class_attribute = _target_object.__getattribute__(attribute)\n setattr( self, attribute, target_class_attribute )\n\n except AttributeError as error:\n print( \"Error coping the attribute `%s`: %s\" % (attribute, error) )\n\n\no = TargetCopiedObject()\nprint( \"TargetCopiedObject:\", o )\n</code></pre>\n\n<p>However, if you run the code above, you will see these errors:</p>\n\n<pre><code>python test.py\nSetting: _CHUNK_SIZE\nSetting: __del__\nSetting: __enter__\nSetting: __exit__\nSetting: __getstate__\nSetting: __iter__\nSetting: __next__\nSetting: _checkClosed\nSetting: _checkReadable\nSetting: _checkSeekable\nSetting: _checkWritable\nSetting: _finalizing\nSetting: buffer\nError coping the attribute `buffer`: readonly attribute\nSetting: close\nSetting: closed\nError coping the attribute `closed`: attribute 'closed' of '_io.TextIOWrapper' objects is not writable\nSetting: detach\nSetting: encoding\nError coping the attribute `encoding`: readonly attribute\nSetting: errors\nError coping the attribute `errors`: attribute 'errors' of '_io.TextIOWrapper' objects is not writable\nSetting: fileno\nSetting: flush\nSetting: isatty\nSetting: line_buffering\nError coping the attribute `line_buffering`: readonly attribute\nSetting: mode\nSetting: name\nError coping the attribute `name`: attribute 'name' of '_io.TextIOWrapper' objects is not writable\nSetting: newlines\nError coping the attribute `newlines`: attribute 'newlines' of '_io.TextIOWrapper' objects is not writable\nSetting: read\nSetting: readable\nSetting: readline\nSetting: readlines\nSetting: seek\nSetting: seekable\nSetting: tell\nSetting: truncate\nSetting: writable\nSetting: write\nSetting: writelines\nTargetCopiedObject: &lt;_io.TextIOWrapper name='&lt;stderr&gt;' mode='w' encoding='utf-8'&gt;\n</code></pre>\n\n<p>You can only copy these read-only properties by doing it on the class static initialization, like the other built-in magic python methods as <code>__str__</code> just above:</p>\n\n<pre><code>import sys\n\n_target_object = sys.stderr\n_target_object_class_type = type( _target_object )\n\nclass TargetCopiedObject(_target_object_class_type):\n \"\"\"\n Which special methods bypasses __getattribute__ in Python?\n https://stackoverflow.com/questions/12872695/which-special-methods-bypasses\n \"\"\"\n\n if hasattr( _target_object, \"__abstractmethods__\" ):\n __abstractmethods__ = _target_object.__abstractmethods__\n\n if hasattr( _target_object, \"__base__\" ):\n __base__ = _target_object.__base__\n\n if hasattr( _target_object, \"__bases__\" ):\n __bases__ = _target_object.__bases__\n\n if hasattr( _target_object, \"__basicsize__\" ):\n __basicsize__ = _target_object.__basicsize__\n\n if hasattr( _target_object, \"__call__\" ):\n __call__ = _target_object.__call__\n\n if hasattr( _target_object, \"__class__\" ):\n __class__ = _target_object.__class__\n\n if hasattr( _target_object, \"__delattr__\" ):\n __delattr__ = _target_object.__delattr__\n\n if hasattr( _target_object, \"__dict__\" ):\n __dict__ = _target_object.__dict__\n\n if hasattr( _target_object, \"__dictoffset__\" ):\n __dictoffset__ = _target_object.__dictoffset__\n\n if hasattr( _target_object, \"__dir__\" ):\n __dir__ = _target_object.__dir__\n\n if hasattr( _target_object, \"__doc__\" ):\n __doc__ = _target_object.__doc__\n\n if hasattr( _target_object, \"__eq__\" ):\n __eq__ = _target_object.__eq__\n\n if hasattr( _target_object, \"__flags__\" ):\n __flags__ = _target_object.__flags__\n\n if hasattr( _target_object, \"__format__\" ):\n __format__ = _target_object.__format__\n\n if hasattr( _target_object, \"__ge__\" ):\n __ge__ = _target_object.__ge__\n\n if hasattr( _target_object, \"__getattribute__\" ):\n __getattribute__ = _target_object.__getattribute__\n\n if hasattr( _target_object, \"__gt__\" ):\n __gt__ = _target_object.__gt__\n\n if hasattr( _target_object, \"__hash__\" ):\n __hash__ = _target_object.__hash__\n\n if hasattr( _target_object, \"__init__\" ):\n __init__ = _target_object.__init__\n\n if hasattr( _target_object, \"__init_subclass__\" ):\n __init_subclass__ = _target_object.__init_subclass__\n\n if hasattr( _target_object, \"__instancecheck__\" ):\n __instancecheck__ = _target_object.__instancecheck__\n\n if hasattr( _target_object, \"__itemsize__\" ):\n __itemsize__ = _target_object.__itemsize__\n\n if hasattr( _target_object, \"__le__\" ):\n __le__ = _target_object.__le__\n\n if hasattr( _target_object, \"__lt__\" ):\n __lt__ = _target_object.__lt__\n\n if hasattr( _target_object, \"__module__\" ):\n __module__ = _target_object.__module__\n\n if hasattr( _target_object, \"__mro__\" ):\n __mro__ = _target_object.__mro__\n\n if hasattr( _target_object, \"__name__\" ):\n __name__ = _target_object.__name__\n\n if hasattr( _target_object, \"__ne__\" ):\n __ne__ = _target_object.__ne__\n\n if hasattr( _target_object, \"__new__\" ):\n __new__ = _target_object.__new__\n\n if hasattr( _target_object, \"__prepare__\" ):\n __prepare__ = _target_object.__prepare__\n\n if hasattr( _target_object, \"__qualname__\" ):\n __qualname__ = _target_object.__qualname__\n\n if hasattr( _target_object, \"__reduce__\" ):\n __reduce__ = _target_object.__reduce__\n\n if hasattr( _target_object, \"__reduce_ex__\" ):\n __reduce_ex__ = _target_object.__reduce_ex__\n\n if hasattr( _target_object, \"__repr__\" ):\n __repr__ = _target_object.__repr__\n\n if hasattr( _target_object, \"__setattr__\" ):\n __setattr__ = _target_object.__setattr__\n\n if hasattr( _target_object, \"__sizeof__\" ):\n __sizeof__ = _target_object.__sizeof__\n\n if hasattr( _target_object, \"__str__\" ):\n __str__ = _target_object.__str__\n\n if hasattr( _target_object, \"__subclasscheck__\" ):\n __subclasscheck__ = _target_object.__subclasscheck__\n\n if hasattr( _target_object, \"__subclasses__\" ):\n __subclasses__ = _target_object.__subclasses__\n\n if hasattr( _target_object, \"__subclasshook__\" ):\n __subclasshook__ = _target_object.__subclasshook__\n\n if hasattr( _target_object, \"__text_signature__\" ):\n __text_signature__ = _target_object.__text_signature__\n\n if hasattr( _target_object, \"__weakrefoffset__\" ):\n __weakrefoffset__ = _target_object.__weakrefoffset__\n\n if hasattr( _target_object, \"mro\" ):\n mro = _target_object.mro\n\n # Copy all the other read only attributes\n if hasattr( _target_object, \"buffer\" ):\n buffer = _target_object.buffer\n\n if hasattr( _target_object, \"closed\" ):\n closed = _target_object.closed\n\n if hasattr( _target_object, \"encoding\" ):\n encoding = _target_object.encoding\n\n if hasattr( _target_object, \"errors\" ):\n errors = _target_object.errors\n\n if hasattr( _target_object, \"line_buffering\" ):\n line_buffering = _target_object.line_buffering\n\n if hasattr( _target_object, \"name\" ):\n name = _target_object.name\n\n if hasattr( _target_object, \"newlines\" ):\n newlines = _target_object.newlines\n\n def __init__(self):\n \"\"\"\n Override any super class `type( _target_object )` constructor,\n so we can instantiate any kind of replacement object.\n\n Assures all properties were statically replaced just above. This\n should happen in case some new attribute is added to the python\n language.\n\n This also ignores the only two methods which are not equal,\n `__init__()` and `__getattribute__()`.\n\n How do you programmatically set an attribute?\n https://stackoverflow.com/questions/285061/how-do-you-programmatically\n \"\"\"\n\n # Add the copied read only atribute to the ignored list, so they\n # do not throw new errors while trying copy they dynamically\n different_methods = set\\\n ([\n \"__init__\",\n \"__getattribute__\",\n \"buffer\",\n \"closed\",\n \"encoding\",\n \"errors\",\n \"line_buffering\",\n \"name\",\n \"newlines\",\n ])\n\n attributes_to_check = set( dir( object ) + dir( type ) )\n attributes_to_copy = dir( _target_object )\n\n # Check for missing magic built-ins methods on the class static initialization\n for attribute in attributes_to_check:\n\n if attribute not in different_methods \\\n and hasattr( _target_object, attribute ):\n\n base_class_attribute = self.__getattribute__( attribute )\n target_class_attribute = _target_object.__getattribute__( attribute )\n\n if base_class_attribute != target_class_attribute:\n sys.stdout.write(\n \" The base class attribute `%s` is different from the \"\n \"target class:\\n%s\\n%s\\n\\n\" % ( attribute,\n base_class_attribute,\n target_class_attribute ) )\n # Finally copy everything it can\n different_methods.update( attributes_to_check )\n\n for attribute in attributes_to_copy:\n\n if attribute not in different_methods:\n print( \"Setting:\", attribute )\n\n try:\n target_class_attribute = _target_object.__getattribute__(attribute)\n setattr( self, attribute, target_class_attribute )\n\n except AttributeError as error:\n print( \"Error coping the attribute `%s`: %s\" % (attribute, error) )\n\n\no = TargetCopiedObject()\nprint( \"TargetCopiedObject:\", o )\n</code></pre>\n\n<p>Now this new version completely works coping everything:</p>\n\n<pre><code>python test.py\nSetting: _CHUNK_SIZE\nSetting: __del__\nSetting: __enter__\nSetting: __exit__\nSetting: __getstate__\nSetting: __iter__\nSetting: __next__\nSetting: _checkClosed\nSetting: _checkReadable\nSetting: _checkSeekable\nSetting: _checkWritable\nSetting: _finalizing\nSetting: close\nSetting: detach\nSetting: fileno\nSetting: flush\nSetting: isatty\nSetting: mode\nSetting: read\nSetting: readable\nSetting: readline\nSetting: readlines\nSetting: seek\nSetting: seekable\nSetting: tell\nSetting: truncate\nSetting: writable\nSetting: write\nSetting: writelines\nTargetCopiedObject: &lt;_io.TextIOWrapper name='&lt;stderr&gt;' mode='w' encoding='utf-8'&gt;\n</code></pre>\n\n<p>The disadvantage of it is that you need to write the Python code manually to overcome the read only attributes. However, you can write python code on the fly with metaprogramming:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/3974554/python-how-to-generate-the-code-on-the-fly\">Python: How to generate the code on the fly?</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Metaprogramming\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Metaprogramming</a></li>\n</ol>\n\n<p>So, if you work over this initial code just above, you can write a script which generates the code it needs to. Hence, you can dynamically and completely copy any Python object.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497/" ]
Is there a library method to copy all the properties between two (already present) instances of the same class, in Python? I mean, something like Apache Commons' `PropertyUtilsBean.copyProperties()`
If your class does not modify `__getitem__` or `__setitem__` for special attribute access all your attributes are stored in `__dict__` so you can do: ``` nobj.__dict__ = oobj.__dict__.copy() # just a shallow copy ``` If you use python properties you should look at `inspect.getmembers()` and filter out the ones you want to copy.
243,851
<p>I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?</p>
[ { "answer_id": 244486, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 1, "selected": false, "text": "<p>Does your code actually need a user logged in via ASP.NET, or does it just need a CurrentPrincipal? I don't think you need to programmatically log in to your site. You can create a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx\" rel=\"nofollow noreferrer\">GenericPrincipal</a>, set the properties you need, and attach it to, for example Thread.CurrentPrincipal or a mocked HttpContext. If your code actually needs RolePrincipal or something then I would change the code to be less coupled to ASP.NET membership.</p>\n" }, { "answer_id": 244587, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "<p>Using your Membership Provider you can validate a user using Membership.ValidateUser. Then you can set the authentication cookie using FormsAuthentication.SetAuthCookie. As long as you have a cookie container this should allow you to log in a user. </p>\n" }, { "answer_id": 250787, "author": "user31934", "author_id": 31934, "author_profile": "https://Stackoverflow.com/users/31934", "pm_score": 2, "selected": false, "text": "<p>I've found it most convenient to create a disposable class that handles setting and resetting Thread.CurrentPrincipal.</p>\n\n<pre><code> public class TemporaryPrincipal : IDisposable {\n private readonly IPrincipal _cache;\n\n public TemporaryPrincipal(IPrincipal tempPrincipal) {\n _cache = Thread.CurrentPrincipal;\n Thread.CurrentPrincipal = tempPrincipal;\n }\n\n public void Dispose() {\n Thread.CurrentPrincipal = _cache;\n }\n }\n</code></pre>\n\n<p>In the test method you just wrap your call with a using statement like this:</p>\n\n<pre><code>using (new TemporaryPrincipal(new AnonymousUserPrincipal())) {\n ClassUnderTest.MethodUnderTest();\n}\n</code></pre>\n" }, { "answer_id": 1111545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>if(Membership.ValidateUser(\"user1\",P@ssw0rd))\n {\n FormsAuthentication.SetAuthCookie(\"user1\",true); \n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16027/" ]
I'm trying to unit test a piece of code that needs a currently logged in user in the test. Using the .Net 2.0 Membership Provider, how can I programmatically log in as a user for this test?
``` if(Membership.ValidateUser("user1",P@ssw0rd)) { FormsAuthentication.SetAuthCookie("user1",true); } ```
243,864
<p>I want to create a list of integers from 1 to <code>n</code>. I can do this in Python using <code>range(1, n+1)</code>, and in Haskell using: <code>take n (iterate (1+) 1)</code>.</p> <p>What is the right OCaml idiom for this?</p>
[ { "answer_id": 244078, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 4, "selected": false, "text": "<p>Here you go:</p>\n<pre><code>let rec range i j = \n if i &gt; j then [] \n else i :: range (i+1) j\n</code></pre>\n<p>Note that this is not tail-recursive. Modern Python versions even have a lazy range.</p>\n" }, { "answer_id": 244104, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 6, "selected": true, "text": "<p>There is no idiom that I know of, but here is a fairly natural definition using an infix operator:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code># let (--) i j = \n let rec aux n acc =\n if n &lt; i then acc else aux (n-1) (n :: acc)\n in aux j [] ;;\nval ( -- ) : int -&gt; int -&gt; int list = &lt;fun&gt;\n# 1--2;;\n- : int list = [1; 2]\n# 1--5;;\n- : int list = [1; 2; 3; 4; 5]\n# 5--10;;\n- : int list = [5; 6; 7; 8; 9; 10]\n</code></pre>\n\n<p>Alternatively, the <a href=\"http://dutherenverseauborddelatable.wordpress.com/downloads/comprehension-for-ocaml/\" rel=\"nofollow noreferrer\">comprehensions syntax extension</a> (which gives the syntax <code>[i .. j]</code> for the above) is likely to be included in a future release of the <a href=\"http://forge.ocamlcore.org/projects/batteries/\" rel=\"nofollow noreferrer\">\"community version\" of OCaml</a>, so that may become idiomatic. I don't recommend you start playing with syntax extensions if you are new to the language, though.</p>\n" }, { "answer_id": 2926149, "author": "Michael Ekstrand", "author_id": 1385039, "author_profile": "https://Stackoverflow.com/users/1385039", "pm_score": 4, "selected": false, "text": "<p>With <a href=\"http://batteries.forge.ocamlcore.org\" rel=\"noreferrer\">Batteries Included</a>, you can write</p>\n\n<pre><code>let nums = List.of_enum (1--10);;\n</code></pre>\n\n<p>The <code>--</code> operator generates an enumeration from the first value to the second. The <code>--^</code> operator is similar, but enumerates a half-open interval (<code>1--^10</code> will enumerate from 1 through 9).</p>\n" }, { "answer_id": 27674212, "author": "user69818", "author_id": 2579955, "author_profile": "https://Stackoverflow.com/users/2579955", "pm_score": 2, "selected": false, "text": "<p>If you use <code>open Batteries</code> (which is a community version of the standard library), you can do <code>range(1,n+1)</code> by <code>List.range 1 `To n</code> (notice the backquote before <code>To</code>).</p>\n\n<p>A more general way (also need batteries) is to use <code>List.init n f</code> which returns a list containing (f 0) (f 1) ... (f (n-1)). </p>\n" }, { "answer_id": 33000776, "author": "Matthias Braun", "author_id": 775954, "author_profile": "https://Stackoverflow.com/users/775954", "pm_score": 2, "selected": false, "text": "<p>OCaml has special syntax for pattern matching on ranges:</p>\n\n<pre><code>let () =\n let my_char = 'a' in\n let is_lower_case = match my_char with\n | 'a'..'z' -&gt; true (* Two dots define a range pattern *)\n | _ -&gt; false\n in\n printf \"result: %b\" is_lower_case\n</code></pre>\n\n<p>To create a range, you can use <a href=\"https://github.com/janestreet/core\" rel=\"nofollow\"><code>Core</code></a>:</p>\n\n<pre><code>List.range 0 1000\n</code></pre>\n" }, { "answer_id": 36098304, "author": "JustGage", "author_id": 1402585, "author_profile": "https://Stackoverflow.com/users/1402585", "pm_score": 2, "selected": false, "text": "<p>A little late to the game here but here's my implementation:</p>\n\n<pre><code>let rec range ?(start=0) len =\n if start &gt;= len\n then []\n else start :: (range len ~start:(start+1))\n</code></pre>\n\n<p>You can then use it very much like the python function:</p>\n\n<pre><code>range 10 \n (* equals: [0; 1; 2; 3; 4; 5; 6; 7; 8; 9] *)\n\nrange ~start:(-3) 3 \n (* equals: [-3; -2; -1; 0; 1; 2] *)\n</code></pre>\n\n<p>naturally I think the best answer is to simply use Core, but this might be better if you only need one function and you're trying to avoid the full framework.</p>\n" }, { "answer_id": 49781512, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": false, "text": "<p>This works in base OCaml: </p>\n\n<p><code>\n# List.init 5 (fun x -&gt; x + 1);;\n- : int list = [1; 2; 3; 4; 5]\n</code></p>\n" }, { "answer_id": 50050695, "author": "rdavison", "author_id": 1631912, "author_profile": "https://Stackoverflow.com/users/1631912", "pm_score": 0, "selected": false, "text": "<p>If you don't need a &quot;step&quot; parameter, one easy way to implement this function would be:</p>\n<pre><code>let range start stop = \n List.init (abs @@ stop - start) (fun i -&gt; i + start)\n</code></pre>\n" }, { "answer_id": 55790735, "author": "Travis S", "author_id": 7644777, "author_profile": "https://Stackoverflow.com/users/7644777", "pm_score": 3, "selected": false, "text": "<p>Following on Alex Coventry from above, but even shorter. </p>\n\n<pre><code>let range n = List.init n succ;; \n&gt; val range : int -&gt; int list = &lt;fun&gt; \nrange 3;; \n&gt; - : int list = [1; 2; 3] \n</code></pre>\n" }, { "answer_id": 56913825, "author": "Nondv", "author_id": 3891844, "author_profile": "https://Stackoverflow.com/users/3891844", "pm_score": 2, "selected": false, "text": "<p>Came up with this:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let range a b =\n List.init (b - a) ((+) a)\n</code></pre>\n" }, { "answer_id": 59956239, "author": "Gark Garcia", "author_id": 9615454, "author_profile": "https://Stackoverflow.com/users/9615454", "pm_score": 3, "selected": false, "text": "<p>If you intend to emulate the lazy behavior of <code>range</code>, I would actually recommend using the <code>Stream</code> module. Something like:</p>\n<pre class=\"lang-ml prettyprint-override\"><code>let range (start: int) (step: int) (stop: int): int stream =\n Stream.from (fun i -&gt; let j = i * step + start in if j &lt; stop then Some j else None)\n</code></pre>\n" }, { "answer_id": 59981035, "author": "Aldrik", "author_id": 8830034, "author_profile": "https://Stackoverflow.com/users/8830034", "pm_score": 0, "selected": false, "text": "<p>Personally I use the range library of OCaml for that.</p>\n<pre><code>(* print sum of all values between 1 and 50, adding 4 to all elements and excluding 53 *)\nRange.(\n from 1 50 \n |&gt; map ((+) 4) \n |&gt; filter ((!=) 53) \n |&gt; fold (+) 0 \n |&gt; print_int\n);;\n</code></pre>\n" }, { "answer_id": 70613105, "author": "Anentropic", "author_id": 202168, "author_profile": "https://Stackoverflow.com/users/202168", "pm_score": 2, "selected": false, "text": "<p>For fun, here's a very Python-like implementation of <code>range</code> using a lazy sequence:</p>\n<pre class=\"lang-ml prettyprint-override\"><code>let range ?(from=0) until ?(step=1) =\n let cmp = match step with\n | i when i &lt; 0 -&gt; (&gt;)\n | i when i &gt; 0 -&gt; (&lt;)\n | _ -&gt; raise (Invalid_argument &quot;step must not be zero&quot;)\n in\n Seq.unfold (function\n i when cmp i until -&gt; Some (i, i + step) | _ -&gt; None\n ) from\n</code></pre>\n<p>So you can get a list of integers from 1 to <code>n</code> by:</p>\n<pre class=\"lang-ml prettyprint-override\"><code># let n = 10;;\nval n : int = 10\n# List.of_seq @@ range ~from:1 (n + 1);;\n- : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]\n</code></pre>\n<p>It also gives other Python-like behaviours, such as concisely counting from 0 by default:</p>\n<pre class=\"lang-ml prettyprint-override\"><code># List.of_seq @@ range 5;;\n- : int list = [0; 1; 2; 3; 4]\n</code></pre>\n<p>...or counting backwards:</p>\n<pre class=\"lang-ml prettyprint-override\"><code># List.of_seq @@ range ~from:20 2 ~step:(-3);;\n- : int list = [20; 17; 14; 11; 8; 5]\n\n(* you have to use a negative step *)\n# List.of_seq @@ range ~from:20 2;;\n- : int list = []\n\n# List.of_seq @@ range 10 ~step:0;;\nException: Invalid_argument &quot;step must not be zero&quot;.\n</code></pre>\n" }, { "answer_id": 72602784, "author": "Mateo", "author_id": 3210331, "author_profile": "https://Stackoverflow.com/users/3210331", "pm_score": 0, "selected": false, "text": "<p>Here is my version using <a href=\"https://ocaml.janestreet.com/ocaml-core/v0.13/doc/base/Base/Sequence/index.html\" rel=\"nofollow noreferrer\">Base.Sequence</a></p>\n<pre><code>open Base\n\nlet pylike_range ?(from=0) ?(step=1) (until: int) : int Sequence.t = \n Sequence.range ~stride:step ~start:`inclusive ~stop:`exclusive from until\n\nlet range_list ?(from=0) ?(step=1) (until: int) : int list = \n pylike_range ~from:from ~step:step until \n |&gt; Sequence.to_list \n</code></pre>\n<p>Example usages:</p>\n<pre><code># range_list 10;;\n- : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]\n\n# range_list 10 ~from:3;;\n- : int list = [3; 4; 5; 6; 7; 8; 9]\n\n# range_list 10 ~from:3 ~step:2;;\n- : int list = [3; 5; 7; 9]\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1386292/" ]
I want to create a list of integers from 1 to `n`. I can do this in Python using `range(1, n+1)`, and in Haskell using: `take n (iterate (1+) 1)`. What is the right OCaml idiom for this?
There is no idiom that I know of, but here is a fairly natural definition using an infix operator: ```ml # let (--) i j = let rec aux n acc = if n < i then acc else aux (n-1) (n :: acc) in aux j [] ;; val ( -- ) : int -> int -> int list = <fun> # 1--2;; - : int list = [1; 2] # 1--5;; - : int list = [1; 2; 3; 4; 5] # 5--10;; - : int list = [5; 6; 7; 8; 9; 10] ``` Alternatively, the [comprehensions syntax extension](http://dutherenverseauborddelatable.wordpress.com/downloads/comprehension-for-ocaml/) (which gives the syntax `[i .. j]` for the above) is likely to be included in a future release of the ["community version" of OCaml](http://forge.ocamlcore.org/projects/batteries/), so that may become idiomatic. I don't recommend you start playing with syntax extensions if you are new to the language, though.
243,865
<p>I have two iterators, a <code>list</code> and an <code>itertools.count</code> object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; c = itertools.count(1) &gt;&gt;&gt; items = ['foo', 'bar'] &gt;&gt;&gt; merged = imerge(items, c) # the mythical "imerge" &gt;&gt;&gt; merged.next() 'foo' &gt;&gt;&gt; merged.next() 1 &gt;&gt;&gt; merged.next() 'bar' &gt;&gt;&gt; merged.next() 2 &gt;&gt;&gt; merged.next() Traceback (most recent call last): ... StopIteration </code></pre> <p>What is the simplest, most concise way to do this?</p>
[ { "answer_id": 243892, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "<p>I'd do something like this. This will be most time and space efficient, since you won't have the overhead of zipping objects together. This will also work if both <code>a</code> and <code>b</code> are infinite.</p>\n\n<pre><code>def imerge(a, b):\n i1 = iter(a)\n i2 = iter(b)\n while True:\n try:\n yield i1.next()\n yield i2.next()\n except StopIteration:\n return\n</code></pre>\n" }, { "answer_id": 243902, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 7, "selected": true, "text": "<p>A generator will solve your problem nicely.</p>\n\n<pre><code>def imerge(a, b):\n for i, j in itertools.izip(a,b):\n yield i\n yield j\n</code></pre>\n" }, { "answer_id": 243909, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "<p>You can use <code>zip</code> as well as <code>itertools.chain</code>. This will <b>only work</b> if the first list is <b>finite</b>:</p>\n\n<pre><code>merge=itertools.chain(*[iter(i) for i in zip(['foo', 'bar'], itertools.count(1))])\n</code></pre>\n" }, { "answer_id": 244049, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 4, "selected": false, "text": "<p>You can do something that is almost exaclty what @Pramod first suggested.</p>\n\n<pre><code>def izipmerge(a, b):\n for i, j in itertools.izip(a,b):\n yield i\n yield j\n</code></pre>\n\n<p>The advantage of this approach is that you won't run out of memory if both a and b are infinite.</p>\n" }, { "answer_id": 244957, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 0, "selected": false, "text": "<p>Why is itertools needed?</p>\n\n<pre><code>def imerge(a,b):\n for i,j in zip(a,b):\n yield i\n yield j\n</code></pre>\n\n<p>In this case at least one of a or b must be of finite length, cause zip will return a list, not an iterator. If you need an iterator as output then you can go for the Claudiu solution.</p>\n" }, { "answer_id": 245042, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what your application is, but you might find the enumerate() function more useful.</p>\n\n<pre><code>&gt;&gt;&gt; items = ['foo', 'bar', 'baz']\n&gt;&gt;&gt; for i, item in enumerate(items):\n... print item\n... print i\n... \nfoo\n0\nbar\n1\nbaz\n2\n</code></pre>\n" }, { "answer_id": 345415, "author": "Tom Swirly", "author_id": 43839, "author_profile": "https://Stackoverflow.com/users/43839", "pm_score": 4, "selected": false, "text": "<p>I also agree that itertools is not needed.</p>\n<p>But why stop at 2?</p>\n<pre><code> def tmerge(*iterators):\n for values in zip(*iterators):\n for value in values:\n yield value\n</code></pre>\n<p>handles any number of iterators from 0 on upwards.</p>\n<p>UPDATE: DOH! A commenter pointed out that this won't work unless all the iterators are the same length.</p>\n<p>The correct code is:</p>\n<pre><code>def tmerge(*iterators):\n empty = {}\n for values in itertools.zip_longest(*iterators, fillvalue=empty):\n for value in values:\n if value is not empty:\n yield value\n</code></pre>\n<p>and yes, I just tried it with lists of unequal length, and a list containing {}.</p>\n" }, { "answer_id": 345433, "author": "user26294", "author_id": 26294, "author_profile": "https://Stackoverflow.com/users/26294", "pm_score": 0, "selected": false, "text": "<p>Using <code>itertools.izip()</code>, instead of <code>zip()</code> as in some of the other answers, will improve performance:</p>\n<p>As &quot;pydoc itertools.izip&quot; shows:</p>\n<blockquote>\n<p>Works like the zip() function but consumes less memory by returning an\niterator instead of a list.</p>\n</blockquote>\n<p>Itertools.izip will also work properly even if one of the iterators is infinite.</p>\n" }, { "answer_id": 345576, "author": "A. Coady", "author_id": 36433, "author_profile": "https://Stackoverflow.com/users/36433", "pm_score": 1, "selected": false, "text": "<p>Use izip and chain together:</p>\n\n<pre><code>&gt;&gt;&gt; list(itertools.chain.from_iterable(itertools.izip(items, c))) # 2.6 only\n['foo', 1, 'bar', 2]\n\n&gt;&gt;&gt; list(itertools.chain(*itertools.izip(items, c)))\n['foo', 1, 'bar', 2]\n</code></pre>\n" }, { "answer_id": 394427, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A concise method is to use a generator expression with itertools.cycle(). It avoids creating a long chain() of tuples.</p>\n\n<pre><code>generator = (it.next() for it in itertools.cycle([i1, i2]))\n</code></pre>\n" }, { "answer_id": 5399982, "author": "vampolo", "author_id": 672268, "author_profile": "https://Stackoverflow.com/users/672268", "pm_score": 3, "selected": false, "text": "<p>I prefer this other way which is much more concise:</p>\n\n<pre><code>iter = reduce(lambda x,y: itertools.chain(x,y), iters)\n</code></pre>\n" }, { "answer_id": 5487453, "author": "Petr Viktorin", "author_id": 99057, "author_profile": "https://Stackoverflow.com/users/99057", "pm_score": 2, "selected": false, "text": "<p>One of the less well known features of Python is that you can have more for clauses in a generator expression. Very useful for flattening nested lists, like those you get from zip()/izip().</p>\n\n<pre><code>def imerge(*iterators):\n return (value for row in itertools.izip(*iterators) for value in row)\n</code></pre>\n" }, { "answer_id": 40498526, "author": "user76284", "author_id": 1667423, "author_profile": "https://Stackoverflow.com/users/1667423", "pm_score": 2, "selected": false, "text": "<p>Here is an elegant solution:</p>\n\n<pre><code>def alternate(*iterators):\n while len(iterators) &gt; 0:\n try:\n yield next(iterators[0])\n # Move this iterator to the back of the queue\n iterators = iterators[1:] + iterators[:1]\n except StopIteration:\n # Remove this iterator from the queue completely\n iterators = iterators[1:]\n</code></pre>\n\n<p>Using an actual queue for better performance (as suggested by David):</p>\n\n<pre><code>from collections import deque\n\ndef alternate(*iterators):\n queue = deque(iterators)\n while len(queue) &gt; 0:\n iterator = queue.popleft()\n try:\n yield next(iterator)\n queue.append(iterator)\n except StopIteration:\n pass\n</code></pre>\n\n<p>It works even when some iterators are finite and others are infinite:</p>\n\n<pre><code>from itertools import count\n\nfor n in alternate(count(), iter(range(3)), count(100)):\n input(n)\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>0\n0\n100\n1\n1\n101\n2\n2\n102\n3\n103\n4\n104\n5\n105\n6\n106\n</code></pre>\n\n<p>It also correctly stops if/when all iterators have been exhausted.</p>\n\n<p>If you want to handle non-iterator iterables, like lists, you can use</p>\n\n<pre><code>def alternate(*iterables):\n queue = deque(map(iter, iterables))\n ...\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18950/" ]
I have two iterators, a `list` and an `itertools.count` object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two: ``` >>> import itertools >>> c = itertools.count(1) >>> items = ['foo', 'bar'] >>> merged = imerge(items, c) # the mythical "imerge" >>> merged.next() 'foo' >>> merged.next() 1 >>> merged.next() 'bar' >>> merged.next() 2 >>> merged.next() Traceback (most recent call last): ... StopIteration ``` What is the simplest, most concise way to do this?
A generator will solve your problem nicely. ``` def imerge(a, b): for i, j in itertools.izip(a,b): yield i yield j ```
243,878
<p><strong>Edit:</strong> This was accidentally posted twice. Original: <a href="https://stackoverflow.com/questions/243900/vb-net-importing-classes">VB.NET Importing Classes</a></p> <p>I've seen some code where a <em>Class</em> is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?</p> <p>TestClass.vb</p> <pre><code>public class TestClass public shared function Somefunc() as Boolean return true end function end class </code></pre> <p>MainClass.vb</p> <pre><code>imports TestClass public class MainClass public sub Main() Somefunc() end sub end class </code></pre> <p>These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere. </p>
[ { "answer_id": 243948, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 4, "selected": true, "text": "<p>Having written the MyBlogLog plugin (the original one, that is) I found that the Wordpress Hooks list (can't remember the link offhand) was incredibly useful, as was the sample code from the Codex and WP Install files. Reading through other developer's plugins is also a good way to learn, as you can see how they implemented things and use those techniques to save yourself some R&amp;D time.</p>\n\n<p>What are you looking to create, anyways?</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I posted a comment with this, but just in case it gets lost...</p>\n\n<p>For your specific needs, you're going to want to store data and be able to manage and retrieve it so creating a custom database table in your plugin is something you will want to do. See this codex link:</p>\n\n<p><a href=\"http://codex.wordpress.org/Creating_Tables_with_Plugins\" rel=\"noreferrer\">http://codex.wordpress.org/Creating_Tables_with_Plugins</a></p>\n\n<p>Then you can just add your management code into the admin screens using the techniques found on this Codex page:</p>\n\n<p><a href=\"http://codex.wordpress.org/Adding_Administration_Menus\" rel=\"noreferrer\">http://codex.wordpress.org/Adding_Administration_Menus</a></p>\n\n<p>If you want to display the items on a page, you can either write yourself a custom PHP WP Page template to query the DB directly:</p>\n\n<p><a href=\"http://codex.wordpress.org/Pages#Page_Templates\" rel=\"noreferrer\">http://codex.wordpress.org/Pages#Page_Templates</a></p>\n\n<p>Or just add a hook filter on your plugin to write the results to the page based on a keyword you specify:</p>\n\n<p><a href=\"http://codex.wordpress.org/Plugin_API#Filters\" rel=\"noreferrer\">http://codex.wordpress.org/Plugin_API#Filters</a></p>\n" }, { "answer_id": 244512, "author": "anonymous coward", "author_id": 26196, "author_profile": "https://Stackoverflow.com/users/26196", "pm_score": 0, "selected": false, "text": "<p>Although technically still information found within the Codex, the Codex contains links to external resources. Apologies for not posting a direct link, but look again, and you should find them.</p>\n" }, { "answer_id": 245777, "author": "rg88", "author_id": 11252, "author_profile": "https://Stackoverflow.com/users/11252", "pm_score": 2, "selected": false, "text": "<p>Here is a <a href=\"http://www.devlounge.net/extras/how-to-write-a-wordpress-plugin\" rel=\"nofollow noreferrer\">useful set of links</a> on how to do Wordpress plugins. Be aware that it is relatively \"advanced\" (in that it introduces a number of object oriented methods to the process). You should really read the Wordpress Codex stuff first.</p>\n" }, { "answer_id": 476852, "author": "Stephen Baugh", "author_id": 55595, "author_profile": "https://Stackoverflow.com/users/55595", "pm_score": 0, "selected": false, "text": "<p>I think one of the most important resources is the code used in other plugins.</p>\n\n<p>Not necessarily doing what yours does, but ones that use have features you want to implement.</p>\n\n<p>For example, if you want to find how to create an options page, you are going to work it out pretty quickly if you see how all the others do it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
**Edit:** This was accidentally posted twice. Original: [VB.NET Importing Classes](https://stackoverflow.com/questions/243900/vb-net-importing-classes) I've seen some code where a *Class* is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well? TestClass.vb ``` public class TestClass public shared function Somefunc() as Boolean return true end function end class ``` MainClass.vb ``` imports TestClass public class MainClass public sub Main() Somefunc() end sub end class ``` These files are in the App\_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere.
Having written the MyBlogLog plugin (the original one, that is) I found that the Wordpress Hooks list (can't remember the link offhand) was incredibly useful, as was the sample code from the Codex and WP Install files. Reading through other developer's plugins is also a good way to learn, as you can see how they implemented things and use those techniques to save yourself some R&D time. What are you looking to create, anyways? **Edit:** I posted a comment with this, but just in case it gets lost... For your specific needs, you're going to want to store data and be able to manage and retrieve it so creating a custom database table in your plugin is something you will want to do. See this codex link: <http://codex.wordpress.org/Creating_Tables_with_Plugins> Then you can just add your management code into the admin screens using the techniques found on this Codex page: <http://codex.wordpress.org/Adding_Administration_Menus> If you want to display the items on a page, you can either write yourself a custom PHP WP Page template to query the DB directly: <http://codex.wordpress.org/Pages#Page_Templates> Or just add a hook filter on your plugin to write the results to the page based on a keyword you specify: <http://codex.wordpress.org/Plugin_API#Filters>
243,894
<p>Does the placement of a function have an effect on the performance of closures within scope? If so, where is the optimal place to put these functions? If not, is the implied association by closure enough reason to place a function in another place logically?</p> <p>For instance, if <strong>foo</strong> does not rely on the value of <strong>localState</strong>, does the fact that <strong>localState</strong> is accessible from <strong>foo</strong> have implications as to <strong>foo</strong>'s execution time, memory use, etc.?</p> <pre><code>(function(){ var localState; function foo(){ // code } function bar(){ // code return localState; } })(); </code></pre> <p>In other words, would this be a better choice, and if so why?</p> <pre><code>(function(){ function foo(){ // code } var localState; function bar(){ // code return localState; } })(); </code></pre> <p><a href="https://stackoverflow.com/users/27024/darius-bacon">Darius Bacon</a> has suggested <a href="https://stackoverflow.com/questions/243894/javascript-closures-and-function-placement#243942">below</a> that the two samples above are identical since <strong>localState</strong> can be accessed anywhere from within the block. However, the example below where <strong>foo</strong> is defined outside the block may be a different case. What do you think?</p> <pre><code>function foo(){ // code } (function(){ var localState; function bar(){ // code foo(); return localState; } })(); </code></pre>
[ { "answer_id": 243942, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 1, "selected": false, "text": "<p>The scope of a var or function declaration is the whole block it appears in, regardless of where in the block the declaration is; so it'd be surprising for it to affect efficiency.</p>\n\n<p>That is, it shouldn't matter whether \"function foo()\" is before or after \"var localState\" within this block. It <em>may</em> matter whether \"function foo()\" is in this block or an enclosing one (if it can be hoisted to a higher scope because it doesn't use <em>any</em> local variables); that depends on details of your Javascript compiler.</p>\n" }, { "answer_id": 243946, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 2, "selected": false, "text": "<p>I don't think there would be any performance overhead, as java script doesn't use the notion of function stack. It supports lexical scoping. The same state is carried forth across closure calls. On a side note, in your example you don't seem to be executing any statements!</p>\n" }, { "answer_id": 243949, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": false, "text": "<p>Both those snippets are equivalent, because they're both defined in the (same) environment of the anonymous function you're creating. I think you'd be able to access <code>localState</code> from <code>foo</code> either way.</p>\n\n<p>That being said... if you have absurd amounts of variables in the environment you're creating, then <code>foo</code>'s execution time might be affected, as variable lookups will likely take longer. If there are tons of variables that you no longer use in the function you define <code>foo</code> in, and <code>foo</code> doesn't need them either, then <code>foo</code> will cause them to not be garbage-collected, so that could also be an issue.</p>\n" }, { "answer_id": 244816, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": false, "text": "<p>Dog, I would hope the order of declarations would be something the JavaScript interpreters would abstract away. In any case, if there is a performance difference, it would be so minimal as to make this a poster child for the evils of premature optimization.</p>\n" }, { "answer_id": 246945, "author": "WPWoodJr", "author_id": 32122, "author_profile": "https://Stackoverflow.com/users/32122", "pm_score": 3, "selected": true, "text": "<p>Every function in Javascript is a closure. The runtime to resolve a variable's value is only incurred if the variable is referenced by the function. For instance, in this example function y captures the value of x even though x is not referenced directly by y:</p>\n\n<pre><code>var x = 3;\nfunction y() eval(\"x\");\ny();\n3\n</code></pre>\n" }, { "answer_id": 1278280, "author": "coderjoe", "author_id": 127792, "author_profile": "https://Stackoverflow.com/users/127792", "pm_score": 0, "selected": false, "text": "<p>In your examples the difference won't really matter. Even if foo is in the global scope you won't have a problem.</p>\n\n<p>However, it's useful to keep in mind that if you use the style of assigning functions to variables to declare your functions the order in which they are declare can become quite a problem.</p>\n\n<p>For a better idea, try the following two examples:</p>\n\n<pre><code>CheckOne();\nfunction CheckOne() {\n alert('check...check one.');\n}\n\nCheckTwo();\nvar CheckTwo = function() {\n alert('check...check two.');\n};\n</code></pre>\n\n<p>The only difference between the second and the first is the style they use to declare their functions. The second one generates a reference error.</p>\n\n<p>Cheers.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
Does the placement of a function have an effect on the performance of closures within scope? If so, where is the optimal place to put these functions? If not, is the implied association by closure enough reason to place a function in another place logically? For instance, if **foo** does not rely on the value of **localState**, does the fact that **localState** is accessible from **foo** have implications as to **foo**'s execution time, memory use, etc.? ``` (function(){ var localState; function foo(){ // code } function bar(){ // code return localState; } })(); ``` In other words, would this be a better choice, and if so why? ``` (function(){ function foo(){ // code } var localState; function bar(){ // code return localState; } })(); ``` [Darius Bacon](https://stackoverflow.com/users/27024/darius-bacon) has suggested [below](https://stackoverflow.com/questions/243894/javascript-closures-and-function-placement#243942) that the two samples above are identical since **localState** can be accessed anywhere from within the block. However, the example below where **foo** is defined outside the block may be a different case. What do you think? ``` function foo(){ // code } (function(){ var localState; function bar(){ // code foo(); return localState; } })(); ```
Every function in Javascript is a closure. The runtime to resolve a variable's value is only incurred if the variable is referenced by the function. For instance, in this example function y captures the value of x even though x is not referenced directly by y: ``` var x = 3; function y() eval("x"); y(); 3 ```
243,897
<p>I have a variable that is built in loop. Something like:</p> <pre><code>$str = ""; for($i = 0; $i &lt; 10; $i++) $str .= "something"; </code></pre> <p>If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one?</p> <p>How do I do this right?</p>
[ { "answer_id": 243913, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 5, "selected": true, "text": "<p>You get the undefined variable because you're concatenating the value of itself with another value.</p>\n\n<p>The equivalent of</p>\n\n<blockquote>\n <p><code>$str = $str . \"something\";</code></p>\n</blockquote>\n\n<p>So, it can't say what's the initial value is. It's the equivalent of this:</p>\n\n<blockquote>\n <p><code>$str = [undefined value] . \"something\";</code></p>\n</blockquote>\n\n<p>What's the result of a concatenation of <code>[undefined value]</code> and <code>\"something\"</code>? The interpreter can't say...</p>\n\n<p>So, you have to put <code>\"\"</code> in the variable first to initiate the variable's value, as you did.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 243920, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>It's safer to not use the auto-declare feature - that's why it issues a notice. A notice is the lowest level of warning, and won't be displayed by default. Most older PHP apps will issue lots of notices if you were to turn them on.</p>\n" }, { "answer_id": 243925, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>If you really need to make it a it cleaner you could do:</p>\n\n<pre><code>for($i = 0, $str = ''; $i &lt; 10; $i++) $str .= \"something\";\n</code></pre>\n\n<p>But what you have is what I normally do. vlceBerg explains it well.</p>\n" }, { "answer_id": 243937, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>PHP variables that are auto-declared are registered as being undefined which is why you're receiving the notice. </p>\n\n<p>It is generally better to declare PHP variables prior to using them though many of the lazy among us, myself included don't always do that.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ]
I have a variable that is built in loop. Something like: ``` $str = ""; for($i = 0; $i < 10; $i++) $str .= "something"; ``` If $str = "" is ommitted, I get undefined variable notice, but I thought php auto-declare a variable the first time it sees undeclared one? How do I do this right?
You get the undefined variable because you're concatenating the value of itself with another value. The equivalent of > > `$str = $str . "something";` > > > So, it can't say what's the initial value is. It's the equivalent of this: > > `$str = [undefined value] . "something";` > > > What's the result of a concatenation of `[undefined value]` and `"something"`? The interpreter can't say... So, you have to put `""` in the variable first to initiate the variable's value, as you did. HTH
243,900
<p>I've seen some code where a <em>Class</em> is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well?</p> <p>TestClass.vb</p> <pre><code>public class TestClass public shared function Somefunc() as Boolean return true end function end class </code></pre> <p>MainClass.vb</p> <pre><code>imports TestClass public class MainClass public sub Main() Somefunc() end sub end class </code></pre> <p>These files are in the App_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere. </p>
[ { "answer_id": 243923, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 1, "selected": false, "text": "<p>Actually, that function is available because it's a <a href=\"http://msdn.microsoft.com/en-us/library/zc2b427x(VS.80).aspx\" rel=\"nofollow noreferrer\">shared</a> function. If you were to remove the shared modifier, you would still have to create an instance of the class to access it.</p>\n\n<p>To achieve access to all variables and all functions within a class by default, you would want to inherit it. </p>\n\n<p>To my knowledge <a href=\"http://visualbasic.about.com/od/usingvbnet/l/bldykImportsa.htm\" rel=\"nofollow noreferrer\">importing</a> a class is basically tying direct reference to it, not creating any sort of instance of it for you to use.</p>\n\n<p>EDIT for clarity: The links are there are VB specific links, thus, explaining the functionality of this pertaining to VB.NET</p>\n" }, { "answer_id": 243999, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>Yes, it's a <a href=\"http://msdn.microsoft.com/en-us/library/7f38zh8x.aspx\" rel=\"nofollow noreferrer\">Visual Basic language feature</a>. While you can create aliases, using <a href=\"http://msdn.microsoft.com/en-us/library/sf0df423.aspx\" rel=\"nofollow noreferrer\">C#'s using statement</a>, it doesn't appear that you can import a shared class into scope. To be honest, I've only ever used it once in a legacy project that had already used it. I see some value, but I'm afraid it may cause more harm than good for future maintainability of your code. </p>\n" }, { "answer_id": 246615, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 3, "selected": true, "text": "<p>One of the reasons this feature is in place is to emulate Visual Basic 6.0's GlobalMultiUse Option for Instancing. Visual Basic 6.0 doesn't have the ability to make modules public across a DLL boundary. Instead you set the instancing property to <code>GlobalMultiUse</code>. It is used mainly for utility classes like a class that export a series of math functions.</p>\n\n<p>Every time you call a subroutine or function on a class with the <code>GlobalMultiUse Instancing</code>, Visual Basic 6.0 instantiates a class behind the scenes before calling the function.</p>\n\n<p>It can be abused to generate global functions/variables with all the advantages and disadvantages.</p>\n" }, { "answer_id": 249391, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 2, "selected": false, "text": "<p>I use it whenever I am using the same library a lot of time. A good example is System.Math.</p>\n\n<p>C# doesn't support this, which I find to be very annoying.</p>\n" }, { "answer_id": 5697882, "author": "gumuruh", "author_id": 687088, "author_profile": "https://Stackoverflow.com/users/687088", "pm_score": -1, "selected": false, "text": "<p>wait, wait, wait.... </p>\n\n<p>I found just this morning that we could derived all the objects (class-s) inside any class\nthat need their references using this method / function;</p>\n\n<pre><code>Protected Overrides Sub Finalize()\n MyBase.Finalize()\nEnd Sub\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
I've seen some code where a *Class* is imported, instead of a namespace, making all the static members/methods of that class available. Is this a feature of VB? Or do other languages do this as well? TestClass.vb ``` public class TestClass public shared function Somefunc() as Boolean return true end function end class ``` MainClass.vb ``` imports TestClass public class MainClass public sub Main() Somefunc() end sub end class ``` These files are in the App\_Code directory. Just curious, because I've never thought of doing this before, nor have I read about it anywhere.
One of the reasons this feature is in place is to emulate Visual Basic 6.0's GlobalMultiUse Option for Instancing. Visual Basic 6.0 doesn't have the ability to make modules public across a DLL boundary. Instead you set the instancing property to `GlobalMultiUse`. It is used mainly for utility classes like a class that export a series of math functions. Every time you call a subroutine or function on a class with the `GlobalMultiUse Instancing`, Visual Basic 6.0 instantiates a class behind the scenes before calling the function. It can be abused to generate global functions/variables with all the advantages and disadvantages.
243,912
<p>I have the following code below in my Servlet, but when IE hits the page, it returns a blank html page. If I use the response.getOutputStream() directly in the StreamResult constructor, the page loads fine. What am I missing?</p> <p><strong>response</strong> is an instance of HttpServletResponse and <strong>xsl</strong> is an instance of Transformer from XSLTC TransformerFactory</p> <pre><code>response.setHeader("Content-Encoding", "gzip"); GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream()); Result outputResult = new StreamResult(gzipOut); xsl.transform(xmlSource, outputResult); </code></pre>
[ { "answer_id": 244269, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 1, "selected": false, "text": "<p>I'm going to guess that you aren't closing the gzipOut stream and therefore it isn't sending the \"footer\" information.</p>\n" }, { "answer_id": 245025, "author": "Adam", "author_id": 30381, "author_profile": "https://Stackoverflow.com/users/30381", "pm_score": -1, "selected": false, "text": "<p>Turns out there is a .finish() on this stream that is required. It is similar to flush, but since it is a different call, the Transformer does not know to use it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30381/" ]
I have the following code below in my Servlet, but when IE hits the page, it returns a blank html page. If I use the response.getOutputStream() directly in the StreamResult constructor, the page loads fine. What am I missing? **response** is an instance of HttpServletResponse and **xsl** is an instance of Transformer from XSLTC TransformerFactory ``` response.setHeader("Content-Encoding", "gzip"); GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream()); Result outputResult = new StreamResult(gzipOut); xsl.transform(xmlSource, outputResult); ```
I'm going to guess that you aren't closing the gzipOut stream and therefore it isn't sending the "footer" information.
243,929
<p>I have several arrays of arrays or arrays of dicts that I would like to store in my iPhone app. This lists are static and won't be modified by the app or users. Occasionally they may be displayed but more likely they'll be iterated over and compared to some input value. Would the best way to store these arrays be a CoreData/SQLite data store, in a header file, or something I'm not thinking of? I could see making a class that only has these arrays stored in them for access, but I'm not sure if that's the best route to take.</p>
[ { "answer_id": 244030, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 3, "selected": false, "text": "<p>Use a property list file. Load it with NSDictionary +dictionaryWithContentsofFile:.</p>\n" }, { "answer_id": 244389, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "<p>Depending on how often you want to modify or localize the items, and your lookup time requirements, a static array may also be the way to go. For constant data, however, SQLite is probably not the route to take, unless you have complex query requirements (as opposed to just by-index).</p>\n" }, { "answer_id": 244978, "author": "Colin Barrett", "author_id": 23106, "author_profile": "https://Stackoverflow.com/users/23106", "pm_score": 3, "selected": true, "text": "<p>I would do the following:</p>\n\n<pre><code>@implementation DataSource\n+ (NSArray *)someData\n{\n static NSArray *data = nil;\n if (!data) {\n data = [[NSArray arrayWithObjects:..., nil] retain];\n }\n return data;\n}\n@end\n</code></pre>\n\n<p>Additional arrays or arrays of dicts would be added as class methods on that class.</p>\n" }, { "answer_id": 254332, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 2, "selected": false, "text": "<p>I would go for the plist approach.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29263/" ]
I have several arrays of arrays or arrays of dicts that I would like to store in my iPhone app. This lists are static and won't be modified by the app or users. Occasionally they may be displayed but more likely they'll be iterated over and compared to some input value. Would the best way to store these arrays be a CoreData/SQLite data store, in a header file, or something I'm not thinking of? I could see making a class that only has these arrays stored in them for access, but I'm not sure if that's the best route to take.
I would do the following: ``` @implementation DataSource + (NSArray *)someData { static NSArray *data = nil; if (!data) { data = [[NSArray arrayWithObjects:..., nil] retain]; } return data; } @end ``` Additional arrays or arrays of dicts would be added as class methods on that class.
243,945
<p>From wikipedia: </p> <blockquote> <p>the cross product is a binary operation on two vectors in a <strong>three-dimensional</strong> Euclidean space that results in another vector which is perpendicular to the plane containing the two input vectors.</p> </blockquote> <p>Given that the definition is only defined in three (<a href="https://en.wikipedia.org/wiki/Seven-dimensional_cross_product#Consequences_of_the_defining_properties" rel="noreferrer">or seven, one and zero</a>) dimensions, how does one calculate the cross product of two 2d vectors?</p> <p>I have seen two implementations. One returns a new vector (but only accepts a single vector), the other returns a scalar (but is a calculation between two vectors).</p> <p>Implementation 1 (returns a scalar):</p> <pre><code>float CrossProduct(const Vector2D &amp; v1, const Vector2D &amp; v2) const { return (v1.X*v2.Y) - (v1.Y*v2.X); } </code></pre> <p>Implementation 2 (returns a vector):</p> <pre><code>Vector2D CrossProduct(const Vector2D &amp; v) const { return Vector2D(v.Y, -v.X); } </code></pre> <p>Why the varying implementations? What would I use the scalar implementation for? What would I use the vector implementation for?</p> <p>The reason I ask is because I'm writing a Vector2D class myself and don't know which method to use.</p>
[ { "answer_id": 243977, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 8, "selected": true, "text": "<p>Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X &amp; Y components (thus the scalar returned is the Z value of the 3D cross product vector).</p>\n\n<p>Note that the magnitude of the vector resulting from 3D cross product is also equal to the <em>area</em> of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.</p>\n\n<p>Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the \"give me a perpendicular vector\" sense.</p>\n\n<p>Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.</p>\n\n<p>Hope this helps...</p>\n" }, { "answer_id": 243984, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 6, "selected": false, "text": "<p><strong>In short:</strong> It's a shorthand notation for a mathematical hack.</p>\n\n<p><strong>Long explanation:</strong></p>\n\n<p>You can't do a cross product with vectors in 2D space. The operation is not defined there.</p>\n\n<p>However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane. </p>\n\n<p>If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.</p>\n\n<p>That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.</p>\n\n<p>From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.</p>\n" }, { "answer_id": 244046, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "<p>Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:</p>\n\n<blockquote>\n <p>| a x b | = |a| . |b| . sine(theta)</p>\n</blockquote>\n\n<p>or</p>\n\n<blockquote>\n <p>sine(theta) = | a x b | / (|a| . |b|)</p>\n</blockquote>\n\n<p>So, in implementation 1 above, if <code>a</code> and <code>b</code> are known in advance to be unit vectors then the result of that function is exactly that sine() value.</p>\n" }, { "answer_id": 527740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I'm using 2d cross product in my calculation to find the new correct rotation for an object that is being acted on by a force vector at an arbitrary point relative to its center of mass. (The scalar Z one.)</p>\n" }, { "answer_id": 29060469, "author": "Bill Burdick", "author_id": 1026782, "author_profile": "https://Stackoverflow.com/users/1026782", "pm_score": 3, "selected": false, "text": "<p>Implementation 1 is the <strong>perp dot product</strong> of the two vectors. The best reference I know of for 2D graphics is the excellent <a href=\"http://www.graphicsgems.org\" rel=\"noreferrer\">Graphics Gems</a> series. If you're doing scratch 2D work, it's <strong>really</strong> important to have these books. Volume IV has an article called \"The Pleasures of Perp Dot Products\" that goes over a lot of uses for it.</p>\n\n<p>One major use of <strong>perp dot product</strong> is to get the scaled <code>sin</code> of the angle between the two vectors, just like the <strong>dot product</strong> returns the scaled <code>cos</code> of the angle. Of course you can use <strong>dot product</strong> and <strong>perp dot product</strong> together to determine the angle between two vectors.</p>\n\n<p><a href=\"http://johnblackburne.blogspot.co.il/2012/02/perp-dot-product.html\" rel=\"noreferrer\">Here</a> is a post on it and <a href=\"http://mathworld.wolfram.com/PerpDotProduct.html\" rel=\"noreferrer\">here</a> is the Wolfram Math World article.</p>\n" }, { "answer_id": 50703927, "author": "Bram", "author_id": 301166, "author_profile": "https://Stackoverflow.com/users/301166", "pm_score": 3, "selected": false, "text": "<p>A useful 2D vector operation is a cross product that returns a scalar. I use it to see if two successive edges in a polygon bend left or right.</p>\n\n<p>From the <a href=\"https://chipmunk-physics.net/\" rel=\"noreferrer\">Chipmunk2D</a> source:</p>\n\n<pre><code>/// 2D vector cross product analog.\n/// The cross product of 2D vectors results in a 3D vector with only a z component.\n/// This function returns the magnitude of the z value.\nstatic inline cpFloat cpvcross(const cpVect v1, const cpVect v2)\n{\n return v1.x*v2.y - v1.y*v2.x;\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
From wikipedia: > > the cross product is a binary operation on two vectors in a **three-dimensional** Euclidean space that results in another vector which is perpendicular to the plane containing the two input vectors. > > > Given that the definition is only defined in three ([or seven, one and zero](https://en.wikipedia.org/wiki/Seven-dimensional_cross_product#Consequences_of_the_defining_properties)) dimensions, how does one calculate the cross product of two 2d vectors? I have seen two implementations. One returns a new vector (but only accepts a single vector), the other returns a scalar (but is a calculation between two vectors). Implementation 1 (returns a scalar): ``` float CrossProduct(const Vector2D & v1, const Vector2D & v2) const { return (v1.X*v2.Y) - (v1.Y*v2.X); } ``` Implementation 2 (returns a vector): ``` Vector2D CrossProduct(const Vector2D & v) const { return Vector2D(v.Y, -v.X); } ``` Why the varying implementations? What would I use the scalar implementation for? What would I use the vector implementation for? The reason I ask is because I'm writing a Vector2D class myself and don't know which method to use.
Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector). Note that the magnitude of the vector resulting from 3D cross product is also equal to the *area* of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors. Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense. Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another. Hope this helps...
243,956
<p>I currently have a silverlight application which rotates through several graphs of live data. Each page has two user controls though: one for an info box at the top and another for the graph to display. I have tried to add a background image to the master page that they are displayed on so that the image is behind everything but as soon as they load, they overwrite the image with their blank canvas.</p> <p>So far attempts to make the background of the user controls transparent have had no effect.</p> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 243975, "author": "MaxM", "author_id": 4226, "author_profile": "https://Stackoverflow.com/users/4226", "pm_score": 0, "selected": false, "text": "<p>There is surely something inside the user controls that has a white background, you could probably find it using Blend, or maybe using <a href=\"http://firstfloorsoftware.com/silverlightspy/\" rel=\"nofollow noreferrer\">Silverlight Spy</a>. Spy is a great app that allows you to see the visual tree of a running app, among other things.</p>\n" }, { "answer_id": 245384, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>You need to set the background to be transparent on the host control itself, not just in the xaml files that get loaded. If you're using the object tag you would do something like:</p>\n\n<pre><code>&lt;object data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"100%\" height=\"100%\"&gt;\n &lt;param name=\"source\" value=\"[your xap file]\"/&gt;\n &lt;param name=\"background\" value=\"transparent\" /&gt;\n ....\n&lt;/object&gt;\n</code></pre>\n\n<p>Because the actual silverlight host control has a background color, if you don't set it to be transparent it will default to white which will overwrite your background regardless of if your canvas is transparent.</p>\n" }, { "answer_id": 246252, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It is now working perfectly. It needed </p>\n\n<pre><code>&lt;param name=\"windowless\" value=\"true\" /&gt; \n</code></pre>\n\n<p>as well as setting the background to transparent.</p>\n\n<p>Thanks for your help, it was much appreciated.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I currently have a silverlight application which rotates through several graphs of live data. Each page has two user controls though: one for an info box at the top and another for the graph to display. I have tried to add a background image to the master page that they are displayed on so that the image is behind everything but as soon as they load, they overwrite the image with their blank canvas. So far attempts to make the background of the user controls transparent have had no effect. Any help would be greatly appreciated.
You need to set the background to be transparent on the host control itself, not just in the xaml files that get loaded. If you're using the object tag you would do something like: ``` <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="[your xap file]"/> <param name="background" value="transparent" /> .... </object> ``` Because the actual silverlight host control has a background color, if you don't set it to be transparent it will default to white which will overwrite your background regardless of if your canvas is transparent.
243,967
<p>Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use <em>exceptions</em> for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations.</p> <p>So I do a trick like this:</p> <pre><code>do { bool isGood = true; .... some code if(!isGood) break; .... some more code if(!isGood) break; .... some more code } while(false); ..... some other code, which has to be executed. </code></pre> <p>I use a "fake" loop which will run once, and I can abort it by <em>break</em> or <em>continue</em>.</p> <p>Some of my colleagues did not like that, and they called it "bad practice". I personally find that approach pretty slick. But what do you think?</p>
[ { "answer_id": 243972, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 0, "selected": false, "text": "<p>I think that there is nothing basically wrong with the technique. I think that I would make sure that the bool is named something more descriptive than isGood. Although, now that I look at it, why would it not work to put all the code that is in the loop into a single if(!isGood) block? The loop only executes once. </p>\n" }, { "answer_id": 243976, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>I have no problem with that as long as the code is readable.</p>\n" }, { "answer_id": 243978, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 5, "selected": false, "text": "<p>You're pretty much just disguising a \"goto\" as a fake loop. Whether you like gotos or not, you'd be just as far ahead using a real undisguised goto.</p>\n\n<p>Personally, I'd just write it as</p>\n\n<pre><code>bool isGood = true;\n\n .... some code\n\n if(isGood)\n {\n .... some more code\n }\n\n if(isGood)\n {\n .... some more code\n }\n</code></pre>\n" }, { "answer_id": 243980, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 4, "selected": false, "text": "<p>You have complicated non-linear control flow inside a difficult to recognize idiom. So, yes, I think this technique is bad. </p>\n\n<p>It might be worthwhile to spend sometime trying to figure out if this can be written a little nicer.</p>\n" }, { "answer_id": 243982, "author": "g .", "author_id": 6944, "author_profile": "https://Stackoverflow.com/users/6944", "pm_score": 5, "selected": false, "text": "<p>Why use a fake loop? You can do the same thing with a method and it probably won't be considered a \"bad practice\" as it is more expected.</p>\n\n<pre><code>someMethod()\n{\n .... some code\n\n if(!isGood)\n return;\n\n .... some more code\n\n if(!isGood)\n return;\n\n .... some more code\n\n }\n</code></pre>\n" }, { "answer_id": 243986, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 1, "selected": false, "text": "<p>It depends on what the alternatives are. <strong>You have to admit that the code you posted is somewhat ugly.</strong> I wouldn't say it's clear. It's a kind of a hack. So if using some other coding solution would be worse, then ok. But if you have better alternative, <strong>don't let the excuse \"it's good enough\" comfort you.</strong></p>\n" }, { "answer_id": 243991, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 3, "selected": false, "text": "<pre><code>public bool Method1(){ ... }\npublic bool Method2(){ ... }\n\npublic void DoStuff(){\n bool everythingWorked = Method1() &amp;&amp; Method2();\n ... stuff you want executed always ...\n}\n</code></pre>\n\n<p>The reason why this works is due to something called short circuit logic. Method2 won't be called if Method1 returns false.</p>\n\n<p>This also has the additional benefit that you can break your method into smaller chunks, which will be easier to unit test.</p>\n" }, { "answer_id": 243996, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": -1, "selected": false, "text": "<p>I think I'd have to agree with your colleagues just because of readability, it's not clear atfirst glance what you are trying to accomplish with this code.</p>\n\n<p>Why not just use </p>\n\n<pre><code>if(isGood)\n{\n...Execute more code\n}\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 244011, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": false, "text": "<p>What you're trying to do is non-local failure recovery. This is what <code>goto</code> is for. Use it. (actually, this is what exception handling is for -- but if you can't use that, 'goto' or 'setjmp/longjmp' are the next best thing).</p>\n\n<p>This pattern, the <code>if(succeeded(..))</code> pattern, and 'goto cleanup', all 3 are semantically and structurally equivalent. Use whichever one is most common in your code project. There's much value in consistency.</p>\n\n<p>I would caution against <code>if(failed(..)) break;</code> on one point in that you're producing a surprising result should you try to nest loops:</p>\n\n<pre><code>do{\n bool isGood = true;\n .... some code\n if(!isGood)\n break;\n .... some more code\n for(....){\n if(!isGood)\n break; // &lt;-- OOPS, this will exit the 'for' loop, which \n // probably isn't what the author intended\n .... some more code\n }\n} while(false);\n..... some other code, which has to be executed.\n</code></pre>\n\n<p>Neither <code>goto cleanup</code> nor <code>if(succeeded(..))</code> have this surprise, so I'd encourage using one of these two instead.</p>\n" }, { "answer_id": 244013, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 1, "selected": false, "text": "<p>Its a very strange idiom. It uses a loop for something its not intended and may cause confusion. I'd imagine this is going to span more than one page, and it would be a surprise to most people that this is never run more than once.</p>\n\n<p>How about using more usual language features like functions?</p>\n\n<pre><code>bool success = someSensibleFunctionName();\n\nif(success)\n{\n ...\n}\n\nsomeCommonCodeInAnotherFunction();\n</code></pre>\n" }, { "answer_id": 244016, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": false, "text": "<p>Basically you just described goto. I use goto in C all the time. I don't consider it bad, unless you use it to emulate a loop (never ever do that!). My typical usage of goto in C is to emulate exceptions (C has no exceptions):</p>\n\n<pre><code>// Code\n\nif (bad_thing_happened) goto catch;\n\n// More code\n\nif (bad_thing_happened) goto catch;\n\n// Even more code\n\nfinally:\n\n// This code is executed in any case\n// whether we have an exception or not,\n// just like finally statement in other\n// languages\n\nreturn whatever;\n\ncatch:\n\n// Code to handle bad error condition\n\n// Make sure code tagged for finally\n// is executed in any case\ngoto finally;\n</code></pre>\n\n<p>Except for the fact that catch and finally have opposite order, I fail to see why this code should be BAD just because it uses goto, if a real try/catch/finally code works <strong>exactly</strong> like this and just doesn't use goto. That makes no sense. And thus I fail to see why your code should be tagged as BAD.</p>\n" }, { "answer_id": 244026, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 1, "selected": false, "text": "<p>I would consider this bad practice. I think it would be more idiomatic, and generally clearer if you made this a function and changed the breaks to returns.</p>\n" }, { "answer_id": 244050, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>If your code is doing something other than the plain meaning of the constructs in place, it's a good sign you've ventured into \"cute\" territory.</p>\n\n<p>In this case you have a \"loop\" that will only run once. Any reader of the code will need to do a double-take to figure out what's going on.</p>\n\n<p>If the case where it isn't \"good\" is truly exceptional, then throwing exceptions would be the better choice.</p>\n" }, { "answer_id": 244052, "author": "Christopher Lightfoot", "author_id": 24525, "author_profile": "https://Stackoverflow.com/users/24525", "pm_score": 1, "selected": false, "text": "<p>Split your code into smaller chunks of functional elements - so you could split the above into a function that returns instead of breaking.</p>\n\n<p>I don't know if the above is bad practice but it's readability is a little off and may be confusing to others who might have to maintain the source.</p>\n" }, { "answer_id": 244068, "author": "Ma99uS", "author_id": 20390, "author_profile": "https://Stackoverflow.com/users/20390", "pm_score": 0, "selected": false, "text": "<p>If splitting code between <strong>if(!isGood) break;</strong> into separate functions, one can end up with dozens of functions containing of just a couple of lines, so that doers not simplify anything. I could not use <strong>return</strong> because I am not ready to leave the function, there is still stuf I want to do there. \nI accept that probably I should just settle for separate <strong>if(isGood) {...}</strong> condition for every code part which I want to execute, but sometimes that would lead to A LOT of curly braces. But I guess I accept that people does not really like that type of construction, so conditions for everything winds!<br> Thanks for your answers. </p>\n" }, { "answer_id": 244069, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>You can use exceptions for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations.</p>\n</blockquote>\n\n<p>Nothing's wrong with using exceptions. Exceptions are part of application logic. The guideline about exceptions is that they should be relatively rare at run time.</p>\n" }, { "answer_id": 244081, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 1, "selected": false, "text": "<p>To me what you are doing is bad in so many ways. The loop can be replaced by putting that code in a method. </p>\n\n<p>I personally believe that if you have to put a ! in front of your conditions then you are looking for the wrong thing. For readability make your boolean match what you are checking for. You are really checking if there is an error or some bad condition, so I would prefer:\n<code><pre>\nIf (isError)\n{\n //Do whatever you need to do for the error and\n return;\n}\n</pre></code>\nover\n<code><pre>\nIf (!isGood)\n{\n //Do something\n}\n</pre></code></p>\n\n<p>So check for what you really want to check for and keep the exception checks to a minimum. Your goal should be readibility over being tricky. Think of the poor soul that is going to have to come along and maintain your code. </p>\n\n<p>One of the first things I worked on 28 years ago was a Fortran program that always needed to check if there was a graphics device available. Someone made the grand decision to call the boolean for this LNOGRAF, so if there was a graphics device available this would be false. I believe it got set this way because of a false efficiency, the check for the device returned zero if there was a graphics device. Throughout the code all the checks were to see if the graphics device was available. It was full of:</p>\n\n<p>If (.NOT. LNOGRAF)</p>\n\n<p>I don't think there was a single:</p>\n\n<p>If (LNOGRAF)</p>\n\n<p>in the program. This was used in mission planning software for B-52's and cruise missiles. It definitely taught me to name my variables for what I'm really checking for.</p>\n" }, { "answer_id": 244121, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 4, "selected": false, "text": "<p>This is convoluted and confusing, I would scrap it immediately.</p>\n\n<p>Consider this alternative:</p>\n\n<pre><code>private void DoSomething()\n{\n // some code\n if (some condition)\n {\n return;\n }\n // some more code\n if (some other condition)\n {\n return;\n }\n // yet more code\n}\n</code></pre>\n\n<p>Also consider breaking up the code above into more than one method.</p>\n" }, { "answer_id": 244127, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 2, "selected": false, "text": "<p>I have used this idiom for years. I find it preferable to the similar nested or serial ifs , the \"goto onError\", or having multiple returns. The above example with the nested loop is something to watch out for. I always add a comment on the \"do\" to make it clear to anyone new to the idiom. </p>\n" }, { "answer_id": 244137, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 1, "selected": false, "text": "<p>What about a functional approach?</p>\n\n<pre><code>\n void method1()\n {\n ... some code\n if( condition )\n method2();\n }\n\n void method2()\n {\n ... some more code\n if( condition )\n method3();\n }\n\n void method3()\n {\n ... yet more code\n if( condition )\n method4();\n }\n</code></pre>\n" }, { "answer_id": 244139, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 7, "selected": true, "text": "<p>Bad practice, it depends.</p>\n<p>What I see in this code is a very creative way to write &quot;goto&quot; with less sulphur-smelling keywords.</p>\n<p>There are multiple alternatives to this code, which can or can not be better, depending on the situation.</p>\n<h2>Your do/while solution</h2>\n<p>Your solution is interesting if you have a lot of code, but will evaluate the &quot;exit&quot; of this processing at some limited points:</p>\n<pre><code>do\n{\n bool isError = false ;\n\n /* some code, perhaps setting isError to true */\n if(isError) break ;\n /* some code, perhaps setting isError to true */\n if(isError) break ;\n /* some code, perhaps setting isError to true */\n}\nwhile(false) ;\n \n// some other code \n</code></pre>\n<p>The problem is that you can't easily use your &quot;if(isError) break ;&quot; is a loop, because it will only exit the inner loop, not your do/while block.</p>\n<p>And of course, if the failure is inside another function, the function must return some kind of error code, and your code must not forget to interpret the error code correctly.</p>\n<p>I won't discuss alternatives using ifs or even nested ifs because, after some thinking, I find them inferior solutions than your own for your problem.</p>\n<h2>Calling a goto a... goto</h2>\n<p>Perhaps you should put clearly on the table the fact you're using a goto, and document the reasons you choose this solution over another.</p>\n<p>At least, it will show something could be wrong with the code, and prompt reviewers to validate or invalidate your solution.</p>\n<p>You must still open a block, and instead of breaking, use a goto.</p>\n<pre><code>{\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n\n while(/* etc.*/)\n {\n // etc.\n for(/* etc.*/)\n {\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n }\n // etc.\n if(/*some failure condition*/) goto MY_EXIT ;\n // etc.\n }\n\n // etc.\n}\n\nMY_EXIT:\n \n// some other code \n</code></pre>\n<p>This way, as you exit the block through the goto, there is no way for you to bypass some object constructor with the goto (which is forbidden by C++).</p>\n<p>This problem solves the process exiting from nested loops problem (and using goto to exit nested loops is an example given by B. Stroustrup as a valid use of goto), but it won't solve the fact some functions calls could fail and be ignored (because someone failed to test correctly their return code, if any).</p>\n<p>Of course, now, you can exit your process from multiple points, from multiple loop nesting depth, so if it is a problem...</p>\n<h2>try/catch</h2>\n<p>If the code is not supposed to fail (so, failure is exceptional), or even if the code structure can fail, but is overly complex to exit, then the following approach could be clearer:</p>\n<pre><code>try\n{\n // All your code\n // You can throw the moment something fails\n // Note that you can call functions, use reccursion,\n // have multiple loops, etc. it won't change\n // anything: If you want to exit the process,\n // then throw a MyExitProcessException exception.\n\n if(/* etc. */)\n {\n // etc.\n while(/* etc.*/)\n {\n // etc.\n for(/* etc.*/)\n {\n // etc.\n if(/*some failure condition*/) throw MyExitProcessException() ;\n // etc.\n }\n // etc.\n\n callSomeFunction() ;\n // the function will throw if the condition is met\n // so no need to test a return code\n\n // etc.\n }\n // etc.\n }\n\n // etc.\n}\ncatch(const MyExitProcessException &amp; e)\n{\n // To avoid catching other exceptions, you should\n // define a &quot;MyExitProcessException&quot; exception\n}\n\n// some other code\n</code></pre>\n<p>If some condition in the code above, or inside some functions called by the code above, is not met, then throw an exception.</p>\n<p>This is somewhat weightier than your do/while solution, but has the same advantages, and can even abort the processing from inside loops or from inside called functions.</p>\n<h2>Discussion</h2>\n<p>Your need seems to come from the fact you can have a complex process to execute (code, functions calls, loops, etc.), but you want to interrupt it over some condition (probably either failure, or because it succeeded sooner than excepted). If you can rewrite it in a different way, you should do it. But perhaps, there is no other way.</p>\n<p>Let's assume that.</p>\n<p><strong>If you can code it with a try/catch, do it</strong>: To interrupt a complex piece of code, throwing an exception is the right solution (the fact you can add failure/success info inside your exception object should not be underestimated). You will have a clearer code after that.</p>\n<p>Now, if you're in a speed bottleneck, resolving your problem with thrown exceptions as an exit is not the fastest way to do it.</p>\n<p>No one can deny your solution is a glorified goto. There won't be a goto-spaghetti code, because the do/while won't let you do that, but it is still a semantic goto. This can be the reasons some could find this code &quot;bad&quot;: They smell the goto without finding its keyword clearly.</p>\n<p>In this case (and in this performance, profiled-verified) case only, your solution seems Ok, and better than the alternative using if), but of lesser quality (IMHO) than the goto solution which at least, doesn't hide itself behind a false loop.</p>\n<h2>Conclusion</h2>\n<p>As far as I am concerned, I find your solution creative, but I would stick to the thrown exception solution.</p>\n<p>So, in order of preference:</p>\n<ol>\n<li>Use try/catch</li>\n<li>Use goto</li>\n<li>Use your do/while loop</li>\n<li>Use ifs/nested ifs</li>\n</ol>\n" }, { "answer_id": 244167, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>For better or worse, I have used the construct in a few places. The start of it is clearly documented, though:</p>\n\n<pre><code> /* This is a one-cycle loop that simplifies error handling */\n do\n {\n ...modestly complex code, including a nested loop...\n } while (0);\n</code></pre>\n\n<p>This is in C, rather than C++ - so exceptions aren't an option. If I were using C++, I would consider seriously using exceptions to handle exceptions. The repeated test idiom suggested by Jeremy is also reasonable; I have used that more frequently. RAII would help me greatly, too; sadly, C does not support that easily. And using more functions would help. Handling breaks from inside the nested loop is done by repeated test.</p>\n\n<p>I would not classify it as a great style; I would not automatically categorize it as \"BAD\".</p>\n" }, { "answer_id": 244170, "author": "user32141", "author_id": 32141, "author_profile": "https://Stackoverflow.com/users/32141", "pm_score": -1, "selected": false, "text": "<p>I think people aren't being honest here.</p>\n\n<p>If I, as your team lead, would see code like this you'd be up for a little one on one, and flagged as a potential problem for the team as that piece of code is particularly horrid.</p>\n\n<p>I say you should listen to your colleagues and rewrite it following any of the suggestions posted here.</p>\n" }, { "answer_id": 244257, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 1, "selected": false, "text": "<p>I would say your solution can be the right solution, but it depends. Paul Tomblin has posted an answer that is better (a series of if tubes) ... if it can be used.</p>\n\n<p>Paul's solution cannot be used when there are expensive object initializations along the way through your loop. If the created objects are used in later steps, the do while (0) solution is better.</p>\n\n<p>That said, variable naming should be improved. Additionally, why reuse the \"escape\" variable so much? Instead trap each individual error condition explicitly and break the loop so that it is obvious what causes the break out at each point.</p>\n\n<p>Someone else suggested using function calls. Again, this may not be an ideal decomposition if it adds unneeded complexity to the function calls due to the number of args that might be passed at any given step.</p>\n\n<p>Others have suggested this is a difficult to understand idiom. Well, first you could put a comment as suggested at the top of the loop. Second, do-while(0) is a normal and common idiom in macros that all C programmers should recognize immediately, so I just don't buy that.</p>\n" }, { "answer_id": 244305, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": -1, "selected": false, "text": "<p>This is what exceptions are for. You can't continue the logic because something went wrong. Even if recovery is trivial, it is still an exception. If you have a really good reason for not using exceptions, such as when you program in a language that does not support them, then use conditional blocks, not loops.</p>\n" }, { "answer_id": 244311, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>A meta comment:\nWhen you're coding, your goal should be clear, maintainable code first. You should not give up legibility on the altar of efficiency unless you profile and prove that it is necessary and that it actually improves things. Jedi mind tricks should be avoided. Always think that the next guy to maintain your code is a big mean psychopath with your home address. Me, for instance.</p>\n" }, { "answer_id": 244523, "author": "Dean Michael", "author_id": 11274, "author_profile": "https://Stackoverflow.com/users/11274", "pm_score": 1, "selected": false, "text": "<p>First, if you just want an answer to whether this code structure or idiom is \"bad\", I would think it is. However, I think this is a symptom of bad decomposition rather than whether the code you have is \"good\" or \"bad\".</p>\n\n<p>I would think much better analysis and refactoring will have to be done to be able to further address the source of the problem, rather than looking just at the code. If you can do something like:</p>\n\n<pre><code>if (condition1(...) &amp;&amp; condition2(...) &amp;&amp; condition3(...) &amp;&amp; ... &amp;&amp; conditionN(...)) {\n // code that ought to run after all conditions\n};\n// code that ought to run whether all conditions are met or not\n</code></pre>\n\n<p>Then I think it would be more \"readable\" and more idiomatic. This way, you can make functions like:</p>\n\n<pre><code>bool conditionN(...) {\n if (!real_condition) return false;\n // code that ought to run\n return true;\n};\n</code></pre>\n\n<p>You get the benefit of better decomposition and help from the compiler to produce the necessary short-circuitry that &amp;&amp;'s will bring. The compiler might even in-line the code in the functions to produce better code than if you would doing the hand-coded loop.</p>\n" }, { "answer_id": 281125, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 2, "selected": false, "text": "<p>Refactor. The clean solution will in most cases be to split this code out into a smaller helper function, from which you can return, rather than breaking out of your not-actually-a-loop.</p>\n\n<p>Then you can substitute your break's for return's, and now people can immediately make sense of your code when reading it, instead of having to stop and wonder why you made this loop which doesn't actually loop. </p>\n\n<p>Yes, I'd say that simply because it doesn't behave as the reader would expect, it's a bad practice. The principle of least surprise, and so on. When I see a loop, I expect it to loop, and if it doesn't, I have to stop and wonder <em>why</em>.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390/" ]
Sometimes you need to skip execution of part of a method under certain non-critical error conditions. You can use *exceptions* for that, but exceptions generally are not recommended in normal application logic, only for abnormal situations. So I do a trick like this: ``` do { bool isGood = true; .... some code if(!isGood) break; .... some more code if(!isGood) break; .... some more code } while(false); ..... some other code, which has to be executed. ``` I use a "fake" loop which will run once, and I can abort it by *break* or *continue*. Some of my colleagues did not like that, and they called it "bad practice". I personally find that approach pretty slick. But what do you think?
Bad practice, it depends. What I see in this code is a very creative way to write "goto" with less sulphur-smelling keywords. There are multiple alternatives to this code, which can or can not be better, depending on the situation. Your do/while solution ---------------------- Your solution is interesting if you have a lot of code, but will evaluate the "exit" of this processing at some limited points: ``` do { bool isError = false ; /* some code, perhaps setting isError to true */ if(isError) break ; /* some code, perhaps setting isError to true */ if(isError) break ; /* some code, perhaps setting isError to true */ } while(false) ; // some other code ``` The problem is that you can't easily use your "if(isError) break ;" is a loop, because it will only exit the inner loop, not your do/while block. And of course, if the failure is inside another function, the function must return some kind of error code, and your code must not forget to interpret the error code correctly. I won't discuss alternatives using ifs or even nested ifs because, after some thinking, I find them inferior solutions than your own for your problem. Calling a goto a... goto ------------------------ Perhaps you should put clearly on the table the fact you're using a goto, and document the reasons you choose this solution over another. At least, it will show something could be wrong with the code, and prompt reviewers to validate or invalidate your solution. You must still open a block, and instead of breaking, use a goto. ``` { // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. while(/* etc.*/) { // etc. for(/* etc.*/) { // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. } // etc. if(/*some failure condition*/) goto MY_EXIT ; // etc. } // etc. } MY_EXIT: // some other code ``` This way, as you exit the block through the goto, there is no way for you to bypass some object constructor with the goto (which is forbidden by C++). This problem solves the process exiting from nested loops problem (and using goto to exit nested loops is an example given by B. Stroustrup as a valid use of goto), but it won't solve the fact some functions calls could fail and be ignored (because someone failed to test correctly their return code, if any). Of course, now, you can exit your process from multiple points, from multiple loop nesting depth, so if it is a problem... try/catch --------- If the code is not supposed to fail (so, failure is exceptional), or even if the code structure can fail, but is overly complex to exit, then the following approach could be clearer: ``` try { // All your code // You can throw the moment something fails // Note that you can call functions, use reccursion, // have multiple loops, etc. it won't change // anything: If you want to exit the process, // then throw a MyExitProcessException exception. if(/* etc. */) { // etc. while(/* etc.*/) { // etc. for(/* etc.*/) { // etc. if(/*some failure condition*/) throw MyExitProcessException() ; // etc. } // etc. callSomeFunction() ; // the function will throw if the condition is met // so no need to test a return code // etc. } // etc. } // etc. } catch(const MyExitProcessException & e) { // To avoid catching other exceptions, you should // define a "MyExitProcessException" exception } // some other code ``` If some condition in the code above, or inside some functions called by the code above, is not met, then throw an exception. This is somewhat weightier than your do/while solution, but has the same advantages, and can even abort the processing from inside loops or from inside called functions. Discussion ---------- Your need seems to come from the fact you can have a complex process to execute (code, functions calls, loops, etc.), but you want to interrupt it over some condition (probably either failure, or because it succeeded sooner than excepted). If you can rewrite it in a different way, you should do it. But perhaps, there is no other way. Let's assume that. **If you can code it with a try/catch, do it**: To interrupt a complex piece of code, throwing an exception is the right solution (the fact you can add failure/success info inside your exception object should not be underestimated). You will have a clearer code after that. Now, if you're in a speed bottleneck, resolving your problem with thrown exceptions as an exit is not the fastest way to do it. No one can deny your solution is a glorified goto. There won't be a goto-spaghetti code, because the do/while won't let you do that, but it is still a semantic goto. This can be the reasons some could find this code "bad": They smell the goto without finding its keyword clearly. In this case (and in this performance, profiled-verified) case only, your solution seems Ok, and better than the alternative using if), but of lesser quality (IMHO) than the goto solution which at least, doesn't hide itself behind a false loop. Conclusion ---------- As far as I am concerned, I find your solution creative, but I would stick to the thrown exception solution. So, in order of preference: 1. Use try/catch 2. Use goto 3. Use your do/while loop 4. Use ifs/nested ifs
243,992
<p>When I create a zip Archive via <code>java.util.zip.*</code>, is there a way to split the resulting archive in multiple volumes? </p> <p>Let's say my overall archive has a <code>filesize</code> of <code>24 MB</code> and I want to split it into 3 files on a limit of 10 MB per file.<br> Is there a zip API which has this feature? Or any other nice ways to achieve this?</p> <p>Thanks Thollsten</p>
[ { "answer_id": 244025, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 4, "selected": true, "text": "<p>Check: <a href=\"http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=38&amp;t=004618\" rel=\"nofollow noreferrer\">http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=38&amp;t=004618</a></p>\n<p><em>I am not aware of any public API that will help you do that.\n(Although if you do not want to do it programatically, there are utilities like WinSplitter that will do it)</em></p>\n<p><em>I have not tried it but, every ZipEntry while using ZippedInput/OutputStream has a compressed size. You may get a rough estimate of the size of the zipped file while creating it. If you need 2MB of zipped files, then you can stop writing to a file after the cumulative size of entries become 1.9MB, taking .1MB for Manifest file and other zip file specific elements.</em>\n<em>So, in a nutshell, you can write a wrapper over the ZippedInputStream as follows:</em></p>\n<pre><code>import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipOutputStream;\n\npublic class ChunkedZippedOutputStream {\n\n private ZipOutputStream zipOutputStream;\n\n private final String path;\n private final String name;\n\n private long currentSize;\n private int currentChunkIndex;\n private final long MAX_FILE_SIZE = 16000000; // Whatever size you want\n private final String PART_POSTFIX = &quot;.part.&quot;;\n private final String FILE_EXTENSION = &quot;.zip&quot;;\n\n public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException {\n this.path = path;\n this.name = name;\n constructNewStream();\n }\n\n public void addEntry(ZipEntry entry) throws IOException {\n long entrySize = entry.getCompressedSize();\n if ((currentSize + entrySize) &gt; MAX_FILE_SIZE) {\n closeStream();\n constructNewStream();\n } else {\n currentSize += entrySize;\n zipOutputStream.putNextEntry(entry);\n }\n }\n\n private void closeStream() throws IOException {\n zipOutputStream.close();\n }\n\n private void constructNewStream() throws FileNotFoundException {\n zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName())));\n currentChunkIndex++;\n currentSize = 0;\n }\n\n private String constructCurrentPartName() {\n // This will give names is the form of &lt;file_name&gt;.part.0.zip, &lt;file_name&gt;.part.1.zip, etc.\n return name + PART_POSTFIX + currentChunkIndex + FILE_EXTENSION;\n }\n}\n</code></pre>\n<p><em>The above program is just a hint of the approach and not a final solution by any means</em>.</p>\n" }, { "answer_id": 245613, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 3, "selected": false, "text": "<p>If the goal is to have the output be compatible with pkzip and winzip, I'm not aware of any open source libraries that do this. We had a similar requirement for one of our apps, and I wound up writing our own implementation (compatible with the zip standard). If I recall, the hardest thing for us was that we had to generate the individual files on the fly (the way that most zip utilities work is they create the big zip file, then go back and split it later - that's a lot easier to implement. Took about a day to write and 2 days to debug.</p>\n\n<p>The zip standard explains what the file format has to look like. If you aren't afraid of rolling up your sleeves a bit, this is definitely doable. You do have to implement a zip file generator yourself, but you can use Java's Deflator class to generate the segment streams for the compressed data. You'll have to generate the file and section headers yourself, but they are just bytes - nothing too hard once you dive in.</p>\n\n<p>Here's the <a href=\"http://www.pkware.com/documents/casestudies/APPNOTE.TXT\" rel=\"noreferrer\">zip specification</a> - section K has the info you are looking for specifically, but you'll need to read A, B, C and F as well. If you are dealing with really big files (We were), you'll have to get into the Zip64 stuff as well - but for 24 MB, you are fine.</p>\n\n<p>If you want to dive in and try it - if you run into questions, post back and I'll see if I can provide some pointers.</p>\n" }, { "answer_id": 51214186, "author": "tpky", "author_id": 4396142, "author_profile": "https://Stackoverflow.com/users/4396142", "pm_score": 0, "selected": false, "text": "<p>Below code is my solution to split zip file in directory structure to chunks based on desired size. I found the previous answers useful so, wanted to contribute with similar but little more neat approach. This code is working for me for my specific needs, and I believe there is room for improvement.</p>\n<pre><code>import java.io.*;\nimport java.util.Enumeration;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipFile;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\n\nclass ChunkedZip {\n private final static long MAX_FILE_SIZE = 1000 * 1000 * 1024; // around 1GB \n private final static String zipCopyDest = &quot;C:\\\\zip2split\\\\copy&quot;;\n\n public static void splitZip(String zipFileName, String zippedPath, String coreId) throws IOException {\n\n System.out.println(&quot;process whole zip file..&quot;);\n FileInputStream fis = new FileInputStream(zippedPath);\n ZipInputStream zipInputStream = new ZipInputStream(fis);\n ZipEntry entry = null;\n int currentChunkIndex = 0;\n //using just to get the uncompressed size of the zipentries\n long entrySize = 0;\n ZipFile zipFile = new ZipFile(zippedPath);\n Enumeration enumeration = zipFile.entries();\n\n String copDest = zipCopyDest + &quot;\\\\&quot; + coreId + &quot;_&quot; + currentChunkIndex + &quot;.zip&quot;;\n\n FileOutputStream fos = new FileOutputStream(new File(copDest));\n BufferedOutputStream bos = new BufferedOutputStream(fos);\n ZipOutputStream zos = new ZipOutputStream(bos);\n long currentSize = 0;\n\n try {\n while ((entry = zipInputStream.getNextEntry()) != null &amp;&amp; enumeration.hasMoreElements()) {\n\n ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();\n System.out.println(zipEntry.getName());\n System.out.println(zipEntry.getSize());\n entrySize = zipEntry.getSize();\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n //long entrySize = entry.getCompressedSize();\n //entrySize = entry.getSize(); //gives -1\n\n if ((currentSize + entrySize) &gt; MAX_FILE_SIZE) {\n zos.close();\n //construct a new stream\n //zos = new ZipOutputStream(new FileOutputStream(new File(zippedPath, constructCurrentPartName(coreId))));\n currentChunkIndex++;\n zos = getOutputStream(currentChunkIndex, coreId);\n currentSize = 0;\n\n } else {\n currentSize += entrySize;\n zos.putNextEntry(new ZipEntry(entry.getName()));\n byte[] buffer = new byte[8192];\n int length = 0;\n while ((length = zipInputStream.read(buffer)) &gt; 0) {\n outputStream.write(buffer, 0, length);\n }\n\n byte[] unzippedFile = outputStream.toByteArray();\n zos.write(unzippedFile);\n unzippedFile = null;\n outputStream.close();\n zos.closeEntry();\n }\n //zos.close();\n }\n } finally {\n zos.close();\n }\n }\n\n public static ZipOutputStream getOutputStream(int i, String coreId) throws IOException {\n System.out.println(&quot;inside of getOutputStream()..&quot;);\n ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipCopyDest + &quot;\\\\&quot; + coreId + &quot;_&quot; + i + &quot;.zip&quot;));\n // out.setLevel(Deflater.DEFAULT_COMPRESSION);\n return out;\n }\n\n public static void main(String args[]) throws IOException {\n String zipFileName = &quot;Large_files_for_testing.zip&quot;;\n String zippedPath = &quot;C:\\\\zip2split\\\\Large_files_for_testing.zip&quot;;\n String coreId = &quot;Large_files_for_testing&quot;;\n splitZip(zipFileName, zippedPath, coreId);\n }\n}\n</code></pre>\n" }, { "answer_id": 55911479, "author": "Drakes", "author_id": 1938889, "author_profile": "https://Stackoverflow.com/users/1938889", "pm_score": 1, "selected": false, "text": "<p>For what it's worth, I like to use <strong>try-with-resources</strong> everywhere. If you are into that design pattern, then you will like this. Also, this solves the problem of empty parts if the entries are larger than the desired part size. You will <em>at least</em> have as many parts as entries in the worst case. </p>\n\n<p>In:</p>\n\n<blockquote>\n <p>my-archive.zip</p>\n</blockquote>\n\n<p>Out:</p>\n\n<blockquote>\n <p>my-archive.part1of3.zip<br>\n my-archive.part2of3.zip<br>\n my-archive.part3of3.zip </p>\n</blockquote>\n\n<p>Note: I'm using logging and Apache Commons FilenameUtils, but feel free to use what you have in your toolkit.</p>\n\n<pre><code>/**\n * Utility class to split a zip archive into parts (not volumes)\n * by attempting to fit as many entries into a single part before\n * creating a new part. If a part would otherwise be empty because\n * the next entry won't fit, it will be added anyway to avoid empty parts.\n *\n * @author Eric Draken, 2019\n */\npublic class Zip\n{\n private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;\n\n private static final String ZIP_PART_FORMAT = \"%s.part%dof%d.zip\";\n\n private static final String EXT = \"zip\";\n\n private static final Logger logger = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );\n\n /**\n * Split a large archive into smaller parts\n *\n * @param zipFile Source zip file to split (must end with .zip)\n * @param outZipFile Destination zip file base path. The \"part\" number will be added automatically\n * @param approxPartSizeBytes Approximate part size\n * @throws IOException Exceptions on file access\n */\n public static void splitZipArchive(\n @NotNull final File zipFile,\n @NotNull final File outZipFile,\n final long approxPartSizeBytes ) throws IOException\n {\n String basename = FilenameUtils.getBaseName( outZipFile.getName() );\n Path basePath = outZipFile.getParentFile() != null ? // Check if this file has a parent folder\n outZipFile.getParentFile().toPath() :\n Paths.get( \"\" );\n String extension = FilenameUtils.getExtension( zipFile.getName() );\n if ( !extension.equals( EXT ) )\n {\n throw new IllegalArgumentException( \"The archive to split must end with .\" + EXT );\n }\n\n // Get a list of entries in the archive\n try ( ZipFile zf = new ZipFile( zipFile ) )\n {\n // Silliness check\n long minRequiredSize = zipFile.length() / 100;\n if ( minRequiredSize &gt; approxPartSizeBytes )\n {\n throw new IllegalArgumentException(\n \"Please select a minimum part size over \" + minRequiredSize + \" bytes, \" +\n \"otherwise there will be over 100 parts.\"\n );\n }\n\n // Loop over all the entries in the large archive\n // to calculate the number of parts required\n Enumeration&lt;? extends ZipEntry&gt; enumeration = zf.entries();\n long partSize = 0;\n long totalParts = 1;\n while ( enumeration.hasMoreElements() )\n {\n long nextSize = enumeration.nextElement().getCompressedSize();\n if ( partSize + nextSize &gt; approxPartSizeBytes )\n {\n partSize = 0;\n totalParts++;\n }\n partSize += nextSize;\n }\n\n // Silliness check: if there are more parts than there\n // are entries, then one entry will occupy one part by contract\n totalParts = Math.min( totalParts, zf.size() );\n\n logger.debug( \"Split requires {} parts\", totalParts );\n if ( totalParts == 1 )\n {\n // No splitting required. Copy file\n Path outFile = basePath.resolve(\n String.format( ZIP_PART_FORMAT, basename, 1, 1 )\n );\n Files.copy( zipFile.toPath(), outFile );\n logger.debug( \"Copied {} to {} (pass-though)\", zipFile.toString(), outFile.toString() );\n return;\n }\n\n // Reset\n enumeration = zf.entries();\n\n // Split into parts\n int currPart = 1;\n ZipEntry overflowZipEntry = null;\n while ( overflowZipEntry != null || enumeration.hasMoreElements() )\n {\n Path outFilePart = basePath.resolve(\n String.format( ZIP_PART_FORMAT, basename, currPart++, totalParts )\n );\n overflowZipEntry = writeEntriesToPart( overflowZipEntry, zf, outFilePart, enumeration, approxPartSizeBytes );\n logger.debug( \"Wrote {}\", outFilePart );\n }\n }\n }\n\n /**\n * Write an entry to the to the outFilePart\n *\n * @param overflowZipEntry ZipEntry that didn't fit in the last part, or null\n * @param inZipFile The large archive to split\n * @param outFilePart The part of the archive currently being worked on\n * @param enumeration Enumeration of ZipEntries\n * @param approxPartSizeBytes Approximate part size\n * @return Overflow ZipEntry, or null\n * @throws IOException File access exceptions\n */\n private static ZipEntry writeEntriesToPart(\n @Nullable ZipEntry overflowZipEntry,\n @NotNull final ZipFile inZipFile,\n @NotNull final Path outFilePart,\n @NotNull final Enumeration&lt;? extends ZipEntry&gt; enumeration,\n final long approxPartSizeBytes\n ) throws IOException\n {\n try (\n ZipOutputStream zos =\n new ZipOutputStream( new FileOutputStream( outFilePart.toFile(), false ) )\n )\n {\n long partSize = 0;\n byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];\n while ( overflowZipEntry != null || enumeration.hasMoreElements() )\n {\n ZipEntry entry = overflowZipEntry != null ? overflowZipEntry : enumeration.nextElement();\n overflowZipEntry = null;\n\n long entrySize = entry.getCompressedSize();\n if ( partSize + entrySize &gt; approxPartSizeBytes )\n {\n if ( partSize != 0 )\n {\n return entry; // Finished this part, but return the dangling ZipEntry\n }\n // Add the entry anyway if the part would otherwise be empty\n }\n partSize += entrySize;\n zos.putNextEntry( entry );\n\n // Get the input stream for this entry and copy the entry\n try ( InputStream is = inZipFile.getInputStream( entry ) )\n {\n int bytesRead;\n while ( (bytesRead = is.read( buffer )) != -1 )\n {\n zos.write( buffer, 0, bytesRead );\n }\n }\n }\n return null; // Finished splitting\n }\n }\n</code></pre>\n" }, { "answer_id": 65830012, "author": "codigoalvo", "author_id": 2547418, "author_profile": "https://Stackoverflow.com/users/2547418", "pm_score": 0, "selected": false, "text": "<p>Here's my solution:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public abstract class ZipHelper {\n\n public static NumberFormat formater = NumberFormat.getNumberInstance(new Locale(&quot;pt&quot;, &quot;BR&quot;));\n\n public static List&lt;Path&gt; zip(Collection&lt;File&gt; inputFiles, long maxSize) throws IOException {\n\n byte[] buffer = new byte[1024];\n int count = 0;\n long currentZipSize = maxSize;\n List&lt;Path&gt; response = new ArrayList&lt;&gt;();\n ZipOutputStream zip = null;\n for (File currentFile : inputFiles) {\n long nextFileSize = currentFile.length();\n long predictedZipSize = currentZipSize + nextFileSize;\n boolean needNewFile = predictedZipSize &gt;= maxSize;\n System.out.println(&quot;[=] ZIP current (&quot; + formater.format(currentZipSize) + &quot;) + next file (&quot; + formater.format(nextFileSize) + &quot;) = predicted (&quot; + formater.format(predictedZipSize) + &quot;) &gt; max (&quot; + formater.format(maxSize) + &quot;) ? &quot; + needNewFile);\n if (needNewFile) {\n safeClose(zip);\n Path tmpFile = Files.createTempFile(&quot;teste-&quot;, (&quot;.part.&quot; + count++ + &quot;.zip&quot;));\n System.out.println(&quot;[#] Starting new file: &quot; + tmpFile);\n zip = new ZipOutputStream(Files.newOutputStream(tmpFile));\n zip.setLevel(Deflater.BEST_COMPRESSION);\n response.add(tmpFile);\n currentZipSize = 0;\n }\n ZipEntry zipEntry = new ZipEntry(currentFile.getName());\n System.out.println(&quot;[&lt;] Adding to ZIP: &quot; + currentFile.getName());\n zip.putNextEntry(zipEntry);\n FileInputStream in = new FileInputStream(currentFile);\n zip.write(in.readAllBytes());\n zip.closeEntry();\n safeClose(in);\n long compressed = zipEntry.getCompressedSize();\n System.out.println(&quot;[=] Compressed current file: &quot; + formater.format(compressed));\n currentZipSize += zipEntry.getCompressedSize();\n }\n safeClose(zip);\n return response;\n }\n\n public static void safeClose(Closeable... closeables) {\n if (closeables != null) {\n for (Closeable closeable : closeables) {\n if (closeable != null) {\n try {\n System.out.println(&quot;[X] Closing: (&quot; + closeable.getClass() + &quot;) - &quot; + closeable);\n closeable.close();\n } catch (Throwable ex) {\n System.err.println(&quot;[!] Error on close: &quot; + closeable);\n ex.printStackTrace();\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>And the console output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[?] Files to process: [\\data\\teste\\TestFile(1).pdf, \\data\\teste\\TestFile(2).pdf, \\data\\teste\\TestFile(3).pdf, \\data\\teste\\TestFile(4).pdf, \\data\\teste\\TestFile(5).pdf, \\data\\teste\\TestFile(6).pdf, \\data\\teste\\TestFile(7).pdf]\n[=] ZIP current (3.145.728) + next file (1.014.332) = predicted (4.160.060) &gt; max (3.145.728) ? true\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-3319961516431535912.part.0.zip\n[&lt;] Adding to ZIP: TestFile(1).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@3d99d22e\n[=] Compressed current file: 940.422\n[=] ZIP current (940.422) + next file (1.511.862) = predicted (2.452.284) &gt; max (3.145.728) ? false\n[&lt;] Adding to ZIP: TestFile(2).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@49fc609f\n[=] Compressed current file: 1.475.178\n[=] ZIP current (2.415.600) + next file (2.439.287) = predicted (4.854.887) &gt; max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@cd2dae5\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-8849887746791381380.part.1.zip\n[&lt;] Adding to ZIP: TestFile(3).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@4973813a\n[=] Compressed current file: 2.374.718\n[=] ZIP current (2.374.718) + next file (2.385.447) = predicted (4.760.165) &gt; max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@6321e813\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-6305809161676875106.part.2.zip\n[&lt;] Adding to ZIP: TestFile(4).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@79be0360\n[=] Compressed current file: 2.202.203\n[=] ZIP current (2.202.203) + next file (292.918) = predicted (2.495.121) &gt; max (3.145.728) ? false\n[&lt;] Adding to ZIP: TestFile(5).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@22a67b4\n[=] Compressed current file: 230.491\n[=] ZIP current (2.432.694) + next file (4.197.512) = predicted (6.630.206) &gt; max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@57855c9a\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-17160527941340008316.part.3.zip\n[&lt;] Adding to ZIP: TestFile(6).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@3b084709\n[=] Compressed current file: 3.020.115\n[=] ZIP current (3.020.115) + next file (1.556.237) = predicted (4.576.352) &gt; max (3.145.728) ? true\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@3224f60b\n[#] Starting new file: C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-14050058835776413808.part.4.zip\n[&lt;] Adding to ZIP: TestFile(7).pdf\n[X] Closing: (class java.io.FileInputStream) - java.io.FileInputStream@63e2203c\n[=] Compressed current file: 1.460.566\n[X] Closing: (class java.util.zip.ZipOutputStream) - java.util.zip.ZipOutputStream@1efed156\n[&gt;] Generated ZIP files(s): [C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-3319961516431535912.part.0.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-8849887746791381380.part.1.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-6305809161676875106.part.2.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-17160527941340008316.part.3.zip, C:\\Users\\Cassio\\AppData\\Local\\Temp\\teste-14050058835776413808.part.4.zip]\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9688/" ]
When I create a zip Archive via `java.util.zip.*`, is there a way to split the resulting archive in multiple volumes? Let's say my overall archive has a `filesize` of `24 MB` and I want to split it into 3 files on a limit of 10 MB per file. Is there a zip API which has this feature? Or any other nice ways to achieve this? Thanks Thollsten
Check: <http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=38&t=004618> *I am not aware of any public API that will help you do that. (Although if you do not want to do it programatically, there are utilities like WinSplitter that will do it)* *I have not tried it but, every ZipEntry while using ZippedInput/OutputStream has a compressed size. You may get a rough estimate of the size of the zipped file while creating it. If you need 2MB of zipped files, then you can stop writing to a file after the cumulative size of entries become 1.9MB, taking .1MB for Manifest file and other zip file specific elements.* *So, in a nutshell, you can write a wrapper over the ZippedInputStream as follows:* ``` import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ChunkedZippedOutputStream { private ZipOutputStream zipOutputStream; private final String path; private final String name; private long currentSize; private int currentChunkIndex; private final long MAX_FILE_SIZE = 16000000; // Whatever size you want private final String PART_POSTFIX = ".part."; private final String FILE_EXTENSION = ".zip"; public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException { this.path = path; this.name = name; constructNewStream(); } public void addEntry(ZipEntry entry) throws IOException { long entrySize = entry.getCompressedSize(); if ((currentSize + entrySize) > MAX_FILE_SIZE) { closeStream(); constructNewStream(); } else { currentSize += entrySize; zipOutputStream.putNextEntry(entry); } } private void closeStream() throws IOException { zipOutputStream.close(); } private void constructNewStream() throws FileNotFoundException { zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName()))); currentChunkIndex++; currentSize = 0; } private String constructCurrentPartName() { // This will give names is the form of <file_name>.part.0.zip, <file_name>.part.1.zip, etc. return name + PART_POSTFIX + currentChunkIndex + FILE_EXTENSION; } } ``` *The above program is just a hint of the approach and not a final solution by any means*.
243,995
<p>I am trying to set the permissions of a folder and all of it's children on a vista computer. The code I have so far is this.</p> <pre><code> public static void SetPermissions(string dir) { DirectoryInfo info = new DirectoryInfo(dir); DirectorySecurity ds = info.GetAccessControl(); ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); info.SetAccessControl(ds); } </code></pre> <p>However it's not working as I would expect it to.<br> Even if I run the code as administrator it will not set the permissions.</p> <p>The folder I am working with is located in C:\ProgramData\&lt;my folder&gt; and I can manually change the rights on it just fine.</p> <p>Any one want to point me in the right direction.</p>
[ { "answer_id": 244036, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 1, "selected": false, "text": "<p>This may be a dumb question, but have you tried performing the same action manually (e.g. using Explorer)? Vista has some directories that not even users in the Administrators group can modify without taking additional steps. I think there are two steps you need to take first.</p>\n\n<p>First, use Explorer to make the same modification you're trying to do in your code. If it fails, troubleshoot that.</p>\n\n<p>Second, test your code on a directory you created under your own user folder. You shouldn't need admin privs to do that; the logged-in account should be able to change ACL on folders under e.g. c:\\Users\\yourname\\documents.</p>\n\n<p>I'd also step through the code in the debugger and look at the \"ds\" object just before your call to SetAccessControl. That might show you something unexpected to set you on the right path.</p>\n" }, { "answer_id": 244798, "author": "Erin", "author_id": 22835, "author_profile": "https://Stackoverflow.com/users/22835", "pm_score": 4, "selected": true, "text": "<p>So the answer is two fold. First off a sub folder was being created before the permissions were set on the folder and I needed to or in one more flag on the permissions to make it so both folders and files inherited the permissions.</p>\n\n<pre><code>public static void SetPermissions(string dir)\n {\n DirectoryInfo info = new DirectoryInfo(dir);\n DirectorySecurity ds = info.GetAccessControl(); \n ds.AddAccessRule(new FileSystemAccessRule(@\"BUILTIN\\Users\", \n FileSystemRights.FullControl,\n InheritanceFlags.ObjectInherit |\n InheritanceFlags.ContainerInherit,\n PropagationFlags.None,\n AccessControlType.Allow));\n info.SetAccessControl(ds); \n }\n</code></pre>\n\n<p>After that every thing appears to be working.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/243995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22835/" ]
I am trying to set the permissions of a folder and all of it's children on a vista computer. The code I have so far is this. ``` public static void SetPermissions(string dir) { DirectoryInfo info = new DirectoryInfo(dir); DirectorySecurity ds = info.GetAccessControl(); ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); info.SetAccessControl(ds); } ``` However it's not working as I would expect it to. Even if I run the code as administrator it will not set the permissions. The folder I am working with is located in C:\ProgramData\<my folder> and I can manually change the rights on it just fine. Any one want to point me in the right direction.
So the answer is two fold. First off a sub folder was being created before the permissions were set on the folder and I needed to or in one more flag on the permissions to make it so both folders and files inherited the permissions. ``` public static void SetPermissions(string dir) { DirectoryInfo info = new DirectoryInfo(dir); DirectorySecurity ds = info.GetAccessControl(); ds.AddAccessRule(new FileSystemAccessRule(@"BUILTIN\Users", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); info.SetAccessControl(ds); } ``` After that every thing appears to be working.
244,001
<p>I know that cursors are frowned upon and I try to avoid their use as much as possible, but there may be some legitimate reasons to use them. I have one and I am trying to use a pair of cursors: one for the primary table and one for the secondary table. The primary table cursor iterates through the primary table in an outer loop. the secondary table cursor iterates through the secondary table in the inner loop. The problem is, that the primary table cursor though apparently proceeding and saving the primary key column value [Fname] into a local variable @Fname, but it does not get the row for the corresponding foreign key column in the secondary table. For the secondary table it always returns the rows whose foreign key column value matches the primary key column value of the <strong>first row</strong> of the primary table. </p> <p>Following is a very simplified example for what I want to do in the real stored procedure. Names is the primary table</p> <pre><code>SET NOCOUNT ON DECLARE @Fname varchar(50) -- to hold the fname column value from outer cursor loop ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop ,@score int ; --prepare primary table to be iterated in the outer loop DECLARE @Names AS Table (Fname varchar(50)) INSERT @Names SELECT 'Jim' UNION SELECT 'Bob' UNION SELECT 'Sam' UNION SELECT 'Jo' --prepare secondary/detail table to be iterated in the inner loop DECLARE @Scores AS Table (Fname varchar(50), Score int) INSERT @Scores SELECT 'Jo',1 UNION SELECT 'Jo',5 UNION SELECT 'Jim',4 UNION SELECT 'Bob',10 UNION SELECT 'Bob',15 --cursor to iterate on the primary table in the outer loop DECLARE curNames CURSOR FOR SELECT Fname FROM @Names OPEN curNames FETCH NEXT FROM curNames INTO @Fname --cursor to iterate on the secondary table in the inner loop DECLARE curScores CURSOR FOR SELECT FName,Score FROM @Scores WHERE Fname = @Fname --*** NOTE: Using the primary table's column value @Fname from the outer loop WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Outer loop @Fname = ' + @Fname OPEN curScores FETCH NEXT FROM curScores INTO @FK_Fname, @Score WHILE @@FETCH_STATUS = 0 BEGIN PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score) FETCH NEXT FROM curScores INTO @FK_Fname, @Score END CLOSE curScores FETCH NEXT FROM curNames INTO @Fname END DEALLOCATE curScores CLOSE curNames DEALLOCATE curNames </code></pre> <p>Here is what I get for the result. Please note that for the outer loop it DOES show the up-to-date Fname, but when that Fname is used as @Fname to fetch the relevant row from the secondary table for the succeeding iterations, it still get the rows that match the first row (Bob) of the primary table.</p> <pre><code>Outer loop @Fname = Bob FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Jim FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Jo FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Sam FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 </code></pre> <p>Please let me know what am I do wrong. Thanks in advance!</p>
[ { "answer_id": 244024, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 0, "selected": false, "text": "<p>I'd try placing the</p>\n\n<pre><code>DECLARE curScores CURSOR\nFOR \n SELECT FName,Score \n FROM @Scores \n WHERE Fname = @Fname \n</code></pre>\n\n<p>inside the first while, beacuse you're declaring the cursor only for the first name value</p>\n" }, { "answer_id": 244040, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 3, "selected": true, "text": "<p>The value of @fName is evaluated at :DECLARE curScores CURSOR and not in the primary loop.\nYou must Declare and then deallocate the secon cursor in the primary loop.</p>\n" }, { "answer_id": 244582, "author": "Aamir", "author_id": 262613, "author_profile": "https://Stackoverflow.com/users/262613", "pm_score": 1, "selected": false, "text": "<p>Thanks to few hints, I was able to find the solution.</p>\n\n<p>I had to DECLARE and DEALLOCATE the secondary cursor within the first loop. I initially hated to do it as I thought alocating and deallocating resources in the loop was not a good idea, but I think there is no other way to avoid this in this particular situation. Noew the working code looks some thing like this:</p>\n\n<pre><code>SET NOCOUNT ON\nDECLARE \n @Fname varchar(50) -- to hold the fname column value from outer cursor loop\n ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop\n ,@score int\n;\n\n--prepare primary table to be iterated in the outer loop\nDECLARE @Names AS Table (Fname varchar(50))\nINSERT @Names\n SELECT 'Jim' UNION\n SELECT 'Bob' UNION\n SELECT 'Sam' UNION\n SELECT 'Jo' \n\n\n--prepare secondary/detail table to be iterated in the inner loop\nDECLARE @Scores AS Table (Fname varchar(50), Score int)\nINSERT @Scores\n SELECT 'Jo',1 UNION\n SELECT 'Jo',5 UNION\n SELECT 'Jim',4 UNION\n SELECT 'Bob',10 UNION\n SELECT 'Bob',15 \n\n--cursor to iterate on the primary table in the outer loop\nDECLARE curNames CURSOR\nFOR SELECT Fname FROM @Names\n\n\nOPEN curNames\nFETCH NEXT FROM curNames INTO @Fname\n\n--cursor to iterate on the secondary table in the inner loop\nDECLARE curScores CURSOR\nFOR \n SELECT FName,Score \n FROM @Scores \n WHERE Fname = @Fname \n --*** NOTE: Using the primary table's column value @Fname from the outer loop\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n PRINT 'Outer loop @Fname = ' + @Fname\n\n OPEN curScores\n FETCH NEXT FROM curScores INTO @FK_Fname, @Score\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score)\n FETCH NEXT FROM curScores INTO @FK_Fname, @Score\n END\n CLOSE curScores\n FETCH NEXT FROM curNames INTO @Fname\nEND\n\nDEALLOCATE curScores\n\nCLOSE curNames\nDEALLOCATE curNames\n</code></pre>\n\n<p>And I am getting the right results:</p>\n\n<pre><code>Outer loop @Fname = Bob\n FK_Fname=Bob. Score= 10\n FK_Fname=Bob. Score= 15\nOuter loop @Fname = Jim\n FK_Fname=Jim. Score= 4\nOuter loop @Fname = Jo\n FK_Fname=Jo. Score= 1\n FK_Fname=Jo. Score= 5\nOuter loop @Fname = Sam\n</code></pre>\n" }, { "answer_id": 244606, "author": "jcollum", "author_id": 30946, "author_profile": "https://Stackoverflow.com/users/30946", "pm_score": 1, "selected": false, "text": "<p>I think you could do this so much easier with temp tables that have row numbers: </p>\n\n<pre><code>create table #temp1\n(\n row int identity(1,1)\n , ... \n)\n</code></pre>\n\n<p>It really looks like you're asking SQL to behave like a language that likes loops. It doesn't. Whenever I find myself writing a loop in SQL I ask myself, does it have to be done this way? 7/10 times the answer is no, I can do it with sets instead.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262613/" ]
I know that cursors are frowned upon and I try to avoid their use as much as possible, but there may be some legitimate reasons to use them. I have one and I am trying to use a pair of cursors: one for the primary table and one for the secondary table. The primary table cursor iterates through the primary table in an outer loop. the secondary table cursor iterates through the secondary table in the inner loop. The problem is, that the primary table cursor though apparently proceeding and saving the primary key column value [Fname] into a local variable @Fname, but it does not get the row for the corresponding foreign key column in the secondary table. For the secondary table it always returns the rows whose foreign key column value matches the primary key column value of the **first row** of the primary table. Following is a very simplified example for what I want to do in the real stored procedure. Names is the primary table ``` SET NOCOUNT ON DECLARE @Fname varchar(50) -- to hold the fname column value from outer cursor loop ,@FK_Fname varchar(50) -- to hold the fname column value from inner cursor loop ,@score int ; --prepare primary table to be iterated in the outer loop DECLARE @Names AS Table (Fname varchar(50)) INSERT @Names SELECT 'Jim' UNION SELECT 'Bob' UNION SELECT 'Sam' UNION SELECT 'Jo' --prepare secondary/detail table to be iterated in the inner loop DECLARE @Scores AS Table (Fname varchar(50), Score int) INSERT @Scores SELECT 'Jo',1 UNION SELECT 'Jo',5 UNION SELECT 'Jim',4 UNION SELECT 'Bob',10 UNION SELECT 'Bob',15 --cursor to iterate on the primary table in the outer loop DECLARE curNames CURSOR FOR SELECT Fname FROM @Names OPEN curNames FETCH NEXT FROM curNames INTO @Fname --cursor to iterate on the secondary table in the inner loop DECLARE curScores CURSOR FOR SELECT FName,Score FROM @Scores WHERE Fname = @Fname --*** NOTE: Using the primary table's column value @Fname from the outer loop WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Outer loop @Fname = ' + @Fname OPEN curScores FETCH NEXT FROM curScores INTO @FK_Fname, @Score WHILE @@FETCH_STATUS = 0 BEGIN PRINT ' FK_Fname=' + @FK_Fname + '. Score=' + STR(@Score) FETCH NEXT FROM curScores INTO @FK_Fname, @Score END CLOSE curScores FETCH NEXT FROM curNames INTO @Fname END DEALLOCATE curScores CLOSE curNames DEALLOCATE curNames ``` Here is what I get for the result. Please note that for the outer loop it DOES show the up-to-date Fname, but when that Fname is used as @Fname to fetch the relevant row from the secondary table for the succeeding iterations, it still get the rows that match the first row (Bob) of the primary table. ``` Outer loop @Fname = Bob FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Jim FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Jo FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 Outer loop @Fname = Sam FK_Fname=Bob. Score=10 FK_Fname=Bob. Score=15 ``` Please let me know what am I do wrong. Thanks in advance!
The value of @fName is evaluated at :DECLARE curScores CURSOR and not in the primary loop. You must Declare and then deallocate the secon cursor in the primary loop.
244,009
<p>In my Rails controller, I'm creating multiple instances of the same model class. I want to add some RSpec expectations so I can test that it is creating the correct number with the correct parameters. So, here's what I have in my spec:</p> <pre> Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => @user.id, :position_id => 1, :is_leader => true) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "2222", :position_id => 2) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "3333", :position_id => 3) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "4444", :position_id => 4) </pre> <p>This is causing problems because it seems that the Bandmate class can only have 1 "should_receive" expectation set on it. So, when I run the example, I get the following error:</p> <pre> Spec::Mocks::MockExpectationError in 'BandsController should create all the bandmates when created' Mock 'Class' expected :create with ({:band_id=>1014, :user_id=>999, :position_id=>1, :is_leader=>true}) but received it with ({:band_id=>1014, :user_id=>"2222", :position_id=>"2"}) </pre> <p>Those are the correct parameters for the second call to create, but RSpec is testing against the wrong parameters.</p> <p>Does anyone know how I can set up my should_receive expectations to allow multiple different calls?</p>
[ { "answer_id": 248742, "author": "James Baker", "author_id": 9365, "author_profile": "https://Stackoverflow.com/users/9365", "pm_score": 6, "selected": true, "text": "<p>Multiple expectations are not a problem at all. What you're running into are ordering problems, given your specific args on unordered expectations. Check <a href=\"http://rspec.info/documentation/3.3/rspec-mocks/#Ordering\" rel=\"noreferrer\">this page</a> for details on ordering expectations.</p>\n\n<p>The short story is that you should add <code>.ordered</code> to the end of each of your expectations.</p>\n" }, { "answer_id": 5178738, "author": "bonyiii", "author_id": 525305, "author_profile": "https://Stackoverflow.com/users/525305", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://rspec.rubyforge.org/rspec/1.1.9/classes/Spec/Mocks.html\" rel=\"nofollow noreferrer\">Mock Receive Counts</a></p>\n\n<p>my_mock.should_receive(:sym).once<br>\n my_mock.should_receive(:sym).twice<br>\n my_mock.should_receive(:sym).exactly(n).times<br>\n my_mock.should_receive(:sym).at_least(:once)<br>\n my_mock.should_receive(:sym).at_least(:twice)<br>\n my_mock.should_receive(:sym).at_least(n).times<br>\n my_mock.should_receive(:sym).at_most(:once)<br>\n my_mock.should_receive(:sym).at_most(:twice)<br>\n my_mock.should_receive(:sym).at_most(n).times<br>\n my_mock.should_receive(:sym).any_number_of_times </p>\n\n<p>Works for rspec 2.5 too.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19964/" ]
In my Rails controller, I'm creating multiple instances of the same model class. I want to add some RSpec expectations so I can test that it is creating the correct number with the correct parameters. So, here's what I have in my spec: ``` Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => @user.id, :position_id => 1, :is_leader => true) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "2222", :position_id => 2) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "3333", :position_id => 3) Bandmate.should_receive(:create).with(:band_id => @band.id, :user_id => "4444", :position_id => 4) ``` This is causing problems because it seems that the Bandmate class can only have 1 "should\_receive" expectation set on it. So, when I run the example, I get the following error: ``` Spec::Mocks::MockExpectationError in 'BandsController should create all the bandmates when created' Mock 'Class' expected :create with ({:band_id=>1014, :user_id=>999, :position_id=>1, :is_leader=>true}) but received it with ({:band_id=>1014, :user_id=>"2222", :position_id=>"2"}) ``` Those are the correct parameters for the second call to create, but RSpec is testing against the wrong parameters. Does anyone know how I can set up my should\_receive expectations to allow multiple different calls?
Multiple expectations are not a problem at all. What you're running into are ordering problems, given your specific args on unordered expectations. Check [this page](http://rspec.info/documentation/3.3/rspec-mocks/#Ordering) for details on ordering expectations. The short story is that you should add `.ordered` to the end of each of your expectations.
244,085
<p>Delphi 2009 complains with an E2283 error: [DCC Error] outputcode.pas(466): E2283 Too many local constants. Use shorter procedures</p> <p>Delphi 2007 compiles just fine. I can't find an abundance of local constants, it's a short (500 line) unit. Do you see any abundance of constants or literals I can address?</p> <pre><code>procedure TOutputCodeForm.FormCreate(Sender: TObject); var poParser : TStringStream; begin if ( IsWindowsVista() ) then begin SetVistaFonts( self ); end; poParser := TStringStream.Create( gstrSQLParser ); SQLParser := TSyntaxMemoParser.Create( self ); SQLParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; SQLParser.UseRegistry := True; SQLParser.CompileFromStream( poParser ); FreeAndNil( poParser ); poParser := TStringStream.Create( gstrCPPParser ); cppParser := TSyntaxMemoParser.Create( self ); cppParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; cppParser.UseRegistry := True; cppParser.CompileFromStream( poParser ); FreeAndNil( poParser ); poParser := TStringStream.Create( gstrPasParser ); pasParser := TSyntaxMemoParser.Create( self ); pasParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; pasParser.Script := ExtractFilePath( Application.ExeName ) + 'pasScript.txt'; pasParser.CompileFromStream( poParser ); {* Free the stream since we are finished with it. *} FreeAndNil( poParser ); poCodeOutput := TSyntaxMemo.Create( self ); poCodeOutput.Parent := Panel1; poCodeOutput.Left := 8; poCodeOutput.Top := 8; poCodeOutput.Width := Panel1.Width - 16; poCodeOutput.Height := Panel1.Height - 16; poCodeOutput.ClipCopyFormats := [smTEXT, smRTF]; poCodeOutput.Font.Charset := ANSI_CHARSET; poCodeOutput.Font.Color := clWindowText; poCodeOutput.Font.Height := -11; poCodeOutput.Font.Name := 'Courier New'; poCodeOutput.Font.Style := []; poCodeOutput.GutterFont.Charset := DEFAULT_CHARSET; poCodeOutput.GutterFont.Color := clWindowText; poCodeOutput.GutterFont.Height := -11; poCodeOutput.GutterFont.Name := 'MS Sans Serif'; poCodeOutput.GutterFont.Style := []; poCodeOutput.HyperCursor := crDefault; poCodeOutput.IndentStep := 1; poCodeOutput.Margin := 2; poCodeOutput.Modified := False; poCodeOutput.MonoPrint := True; poCodeOutput.Options := [smoSyntaxHighlight, smoPrintWrap, smoPrintLineNos, smoPrintFilename, smoPrintDate, smoPrintPageNos, smoAutoIndent, smoTabToColumn, smoWordSelect, smoShowRMargin, smoShowGutter, smoShowWrapColumn, smoTitleAsFilename, smoProcessDroppedFiles, smoBlockOverwriteCursor, smoShowWrapGlyph, smoColumnTrack, smoUseTAB, smoSmartFill, smoOLEDragSource]; poCodeOutput.ReadOnly := False; poCodeOutput.RightMargin := 80; poCodeOutput.SaveFormat := sfTEXT; poCodeOutput.ScrollBars := ssBoth; poCodeOutput.SelLineStyle := lsCRLF; poCodeOutput.SelStart := 3; poCodeOutput.SelLength := 0; poCodeOutput.SelTextColor := clWhite; poCodeOutput.SelTextBack := clBlack; poCodeOutput.TabDefault := 4; poCodeOutput.TabOrder := 0; poCodeOutput.VisiblePropEdPages := [ppOPTIONS, ppHIGHLIGHTING, ppKEYS, ppAUTOCORRECT, ppTEMPLATES]; poCodeOutput.WrapAtColumn := 0; poCodeOutput.OnKeyDown := FormKeyDown; poCodeOutput.ActiveParser := 3; poCodeOutput.Anchors := [akLeft, akTop, akRight, akBottom]; poCodeOutput.Parser1 := pasParser; poCodeOutput.Parser2 := cppParser; poCodeOutput.Parser3 := SQLParser; SQLParser.AttachEditor( poCodeOutput ); cppParser.AttachEditor( poCodeOutput ); pasParser.AttachEditor( poCodeOutput ); poCodeOutput.Lines.AddStrings( poCode ); if ( CodeType = ctCPP ) then poCodeOutput.ActiveParser := 2 else if ( CodeType = ctPascal ) then poCodeOutput.ActiveParser := 1 else poCodeOutput.ActiveParser := 3; MainForm.AdjustFormSize( self, 0.95, 0.75 ); end; </code></pre>
[ { "answer_id": 244108, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "<p>Is Win32 defined, could the constants be from all the included units.</p>\n\n<p>i would do a binary search: keep tearing half the unit out until it compiles, then add stuff back in.</p>\n\n<p>Yes it sucks, but that's one of the features of trying to debug BorlandCodeGaembarcadero's internal compiler errors.</p>\n" }, { "answer_id": 244488, "author": "Jeremy Mullin", "author_id": 7893, "author_profile": "https://Stackoverflow.com/users/7893", "pm_score": 0, "selected": false, "text": "<p>I've found the method (FormCreate) that is the problem and have been refactoring but no matter how small I make the chunks the compiler still has a problem unless I delete some of the code. </p>\n\n<p>François thanks, but I did refactor the code and still get the error. If it built with D2007, and doesn't with D2009, that seems fishy to me.</p>\n\n<pre><code>procedure TOutputCodeForm.FormCreate(Sender: TObject);\nbegin\n\n if ( IsWindowsVista() ) then\n begin\n SetVistaFonts( self );\n end;\n\n SetupParser( SQLParser, gstrSQLParser, '' );\n // unresolved jmu - have to comment this out for now or delphi will complain\n // that there are too many literals in this file. Seems like a delphi bug\n // since this builds in older versions, and I've already refactored it.\n //SetupParser( cppParser, gstrCPPParser, '' );\n SetupParser( pasParser, gstrPasParser, ExtractFilePath( Application.ExeName ) + 'pasScript.txt' );\n SetupCodeOutput( poCodeOutput );\n\n SQLParser.AttachEditor( poCodeOutput );\n cppParser.AttachEditor( poCodeOutput );\n pasParser.AttachEditor( poCodeOutput );\n\n poCodeOutput.Lines.AddStrings( poCode );\n\n if ( CodeType = ctCPP ) then\n poCodeOutput.ActiveParser := 2\n else if ( CodeType = ctPascal ) then\n poCodeOutput.ActiveParser := 1\n else\n poCodeOutput.ActiveParser := 3;\n\n MainForm.AdjustFormSize( self, 0.95, 0.75 );\nend;\n</code></pre>\n" }, { "answer_id": 244698, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 2, "selected": false, "text": "<p>Before claiming it's a compiler bug or asking for help, I would seriously try to organize and clean my code. </p>\n\n<p>I would create dedicated routines to be called for each part in FormCreate instead of this massive bag of yours.\n- SQLParseInit<br>\n- cppParseInit<br>\n- pasParseInit<br>\n- CodeOutPutInit &lt;-+++++ a lot of constants there </p>\n\n<p>And see if 1 in particular is causing problems.</p>\n\n<p>And it would be not bad to build a minimal case, with as few 3rd party dependencies as possible, to allow others to reproduce it, and see if it is indeed a bug or just bad code.<br>\nAnd also remove those $IFDEF... Just provide the actual code that causes this behavior without all the clutter. </p>\n\n<p>Added: As it works in D2007, but not in D2009, I would also double check that all the libraries/3rd party components that you include in your code are correctly migrated to D2009. (drill down that cppParser)</p>\n" }, { "answer_id": 246208, "author": "Jamo", "author_id": 32303, "author_profile": "https://Stackoverflow.com/users/32303", "pm_score": 0, "selected": false, "text": "<p>Given the problem is only happening in one of your Delphi compilers / setups, I find myself wondering if it's related to a component installation problem. Have you tried just creating a basic form that uses static versions of all the components you are creating dynamically? (TSyntaxMemoParser, etc). </p>\n\n<p>(Are you running those Delphi versions on separate machines / VM's btw? Can save a LOT of hassle if you use many third-party components and more than one version of Delphi)</p>\n" }, { "answer_id": 255152, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 0, "selected": false, "text": "<p>From the help:</p>\n\n<blockquote>\n <p>One or more of your procedures contain so many string constant expressions that they exceed the compiler's internal storage limit. This can occur in code that is automatically generated. To fix this, you can shorten your procedures or declare contant identifiers instead of using so many literals in the code.</p>\n</blockquote>\n\n<p>So maybe try putting some of those strings in consts or other variables (non local).</p>\n" }, { "answer_id": 274346, "author": "Darian Miller", "author_id": 35696, "author_profile": "https://Stackoverflow.com/users/35696", "pm_score": 0, "selected": false, "text": "<p>I'd look at the line of \"poCodeOutput.Options := [xx....]\" \nLooks like too many options in the set on one line of code.</p>\n\n<p>Take that one line out and see if you get the error. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7893/" ]
Delphi 2009 complains with an E2283 error: [DCC Error] outputcode.pas(466): E2283 Too many local constants. Use shorter procedures Delphi 2007 compiles just fine. I can't find an abundance of local constants, it's a short (500 line) unit. Do you see any abundance of constants or literals I can address? ``` procedure TOutputCodeForm.FormCreate(Sender: TObject); var poParser : TStringStream; begin if ( IsWindowsVista() ) then begin SetVistaFonts( self ); end; poParser := TStringStream.Create( gstrSQLParser ); SQLParser := TSyntaxMemoParser.Create( self ); SQLParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; SQLParser.UseRegistry := True; SQLParser.CompileFromStream( poParser ); FreeAndNil( poParser ); poParser := TStringStream.Create( gstrCPPParser ); cppParser := TSyntaxMemoParser.Create( self ); cppParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; cppParser.UseRegistry := True; cppParser.CompileFromStream( poParser ); FreeAndNil( poParser ); poParser := TStringStream.Create( gstrPasParser ); pasParser := TSyntaxMemoParser.Create( self ); pasParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo'; pasParser.Script := ExtractFilePath( Application.ExeName ) + 'pasScript.txt'; pasParser.CompileFromStream( poParser ); {* Free the stream since we are finished with it. *} FreeAndNil( poParser ); poCodeOutput := TSyntaxMemo.Create( self ); poCodeOutput.Parent := Panel1; poCodeOutput.Left := 8; poCodeOutput.Top := 8; poCodeOutput.Width := Panel1.Width - 16; poCodeOutput.Height := Panel1.Height - 16; poCodeOutput.ClipCopyFormats := [smTEXT, smRTF]; poCodeOutput.Font.Charset := ANSI_CHARSET; poCodeOutput.Font.Color := clWindowText; poCodeOutput.Font.Height := -11; poCodeOutput.Font.Name := 'Courier New'; poCodeOutput.Font.Style := []; poCodeOutput.GutterFont.Charset := DEFAULT_CHARSET; poCodeOutput.GutterFont.Color := clWindowText; poCodeOutput.GutterFont.Height := -11; poCodeOutput.GutterFont.Name := 'MS Sans Serif'; poCodeOutput.GutterFont.Style := []; poCodeOutput.HyperCursor := crDefault; poCodeOutput.IndentStep := 1; poCodeOutput.Margin := 2; poCodeOutput.Modified := False; poCodeOutput.MonoPrint := True; poCodeOutput.Options := [smoSyntaxHighlight, smoPrintWrap, smoPrintLineNos, smoPrintFilename, smoPrintDate, smoPrintPageNos, smoAutoIndent, smoTabToColumn, smoWordSelect, smoShowRMargin, smoShowGutter, smoShowWrapColumn, smoTitleAsFilename, smoProcessDroppedFiles, smoBlockOverwriteCursor, smoShowWrapGlyph, smoColumnTrack, smoUseTAB, smoSmartFill, smoOLEDragSource]; poCodeOutput.ReadOnly := False; poCodeOutput.RightMargin := 80; poCodeOutput.SaveFormat := sfTEXT; poCodeOutput.ScrollBars := ssBoth; poCodeOutput.SelLineStyle := lsCRLF; poCodeOutput.SelStart := 3; poCodeOutput.SelLength := 0; poCodeOutput.SelTextColor := clWhite; poCodeOutput.SelTextBack := clBlack; poCodeOutput.TabDefault := 4; poCodeOutput.TabOrder := 0; poCodeOutput.VisiblePropEdPages := [ppOPTIONS, ppHIGHLIGHTING, ppKEYS, ppAUTOCORRECT, ppTEMPLATES]; poCodeOutput.WrapAtColumn := 0; poCodeOutput.OnKeyDown := FormKeyDown; poCodeOutput.ActiveParser := 3; poCodeOutput.Anchors := [akLeft, akTop, akRight, akBottom]; poCodeOutput.Parser1 := pasParser; poCodeOutput.Parser2 := cppParser; poCodeOutput.Parser3 := SQLParser; SQLParser.AttachEditor( poCodeOutput ); cppParser.AttachEditor( poCodeOutput ); pasParser.AttachEditor( poCodeOutput ); poCodeOutput.Lines.AddStrings( poCode ); if ( CodeType = ctCPP ) then poCodeOutput.ActiveParser := 2 else if ( CodeType = ctPascal ) then poCodeOutput.ActiveParser := 1 else poCodeOutput.ActiveParser := 3; MainForm.AdjustFormSize( self, 0.95, 0.75 ); end; ```
Is Win32 defined, could the constants be from all the included units. i would do a binary search: keep tearing half the unit out until it compiles, then add stuff back in. Yes it sucks, but that's one of the features of trying to debug BorlandCodeGaembarcadero's internal compiler errors.
244,087
<p>What are some things I can do to improve query performance of an oracle query without creating indexes?</p> <p>Here is the query I'm trying to run faster:</p> <pre><code>SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath FROM items a, itempages b, keygroupdata c WHERE a.ItemType IN (112,115,189,241) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC </code></pre> <p>None of these columns are indexed and each of the tables contains millions of records. Needless to say, it takes over 3 and half minutes for the query to execute. This is a third party database in a production environment and I'm not allowed to create any indexes so any performance improvements would have to be made to the query itself.</p> <p>Thanks!</p>
[ { "answer_id": 244101, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": -1, "selected": false, "text": "<p>Remove the ORDER BY</p>\n\n<p>perform the sort, after you pull the rows back to your application.</p>\n" }, { "answer_id": 244102, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 0, "selected": false, "text": "<p>Without indexing, that query is only going to get worse as the table size increases.\nWith that said, try removing the order by clause and doing that sort on the client side.</p>\n" }, { "answer_id": 244131, "author": "Rob Booth", "author_id": 16445, "author_profile": "https://Stackoverflow.com/users/16445", "pm_score": 4, "selected": true, "text": "<p>First I'd rewrite the query to be ANSI standard:</p>\n\n<pre><code>SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM items a\nINNER JOIN itempages b ON b.ItemNum = a.ItemNum\nINNER JOIN keygroupdata c ON c.ItemNum = b.ItemNum\nWHERE a.ItemType IN (112,115,189,241)\nORDER BY a.DateStored DESC\n</code></pre>\n\n<p>This makes it easier to read and understand what is going on. It also helps you not make mistakes (i.e. Cross Joining)that might cause real big problems. Then I'd get the Explain plan to see what the DBMS is doing with that query. Is it trying to use some indexes? Is it joining the tables correctly?</p>\n\n<p>Then I'd review the tables that I'm working with to see if there are any indexes that already exist that I could be using to make my query faster. Finally as everyone else has suggested I'd remove the Order By clause and just do that in code.</p>\n" }, { "answer_id": 244165, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>Ask the third party to index its join columns, as they should have done in the first place! Without indexes, Oracle has nothing to go on other than brute force.</p>\n" }, { "answer_id": 244204, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 3, "selected": false, "text": "<p>You may want to try creating a materialized view on any of those tables. You can then create an index on the materialized view that will help speed the query (which would then be querying the materialized view instead of the raw table).</p>\n\n<p>Of course, if your underlying table is updated your view and indexes will need to be refreshed.</p>\n" }, { "answer_id": 244241, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>If the query inputs are constant or predictable (the <code>itemType IN (...)</code>), then an alternative would be to run the query once or twice a day and store the results in a local table, with indices where appropriate. </p>\n\n<p>You can then make the costly query 'offline' and have quicker/better results for an interactive query.</p>\n" }, { "answer_id": 244288, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "<p>First, look at the execution plan. Does it accurately reflect the number of rows to be retrieved at each stage of the query execution? How selective is the predicate \"a.ItemType IN (112,115,189,241)\"? Does the execution plan show any use of temporary disk space for joins or sorts?</p>\n\n<p>Actually, maybe you can modify the question to include the execution plan.</p>\n\n<p>Also make sure you do not have hash joins disabled, which is sometimes the case in OLTP-tuned systems, as they are the most efficient way of equijoining bulk data in Oracle. They ought to show up in the execution plan.</p>\n" }, { "answer_id": 244313, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "<p>You can try filtering on item type before you join your tables, as shown here.</p>\n\n<p>If you are running on Oracle prior to 9i, this would sometimes give surprising benefits.</p>\n\n<pre><code>select \n c.claimnumber,\n a.itemdate, \n c.dtn,\n b.filepath\nfrom \n (\n select itemdate\n from items it\n where it.itemtype in(112,115,189,241)\n ) a\n itempages b,\n keygroupdata c\nwhere a.itemnum = b.itemnum\n and b.itemnum = c.itemnum\n</code></pre>\n\n<p>You can also try adding the hints /<em>+RULE</em>/ or /<em>+ORDERED</em>/ to see what happens... again, particularly with older versions, these would sometimes give surprising results.</p>\n\n<pre><code>SELECT /*+RULE*/\n c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM\n items a,\n itempages b,\n keygroupdata c\nWHERE a.ItemType IN (112,115,189,241)\n AND a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\nORDER BY a.DateStored DESC\n</code></pre>\n" }, { "answer_id": 244327, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "<p>Are statistics gathered on these tables? If not, gathering statistics might change the execution plan, although it wouldn't necessarily be for the better.</p>\n\n<p>Aside from that, look at the execution plan. You may see that it is joining the tables in a non-optimal order (e.g. it could be joining b and c before joining with a which has the filter condition).</p>\n\n<p>You could use hints to try to affect the access paths, join order, or join method.</p>\n\n<p><strong>Update</strong>: Responding to the comment led me to <a href=\"http://www.oaktable.net/getFile/117\" rel=\"nofollow noreferrer\">this</a> presentation, which might be helpful or at least interesting.</p>\n" }, { "answer_id": 244388, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 1, "selected": false, "text": "<p>Is this a query that you run often? It seems like it would be in the DB owner's interest to create the indexes that you need to speed this query up. The 3.5 minutes you're spending running the query must have some impact on their production environment!</p>\n\n<p>Also, have they been running update statistics on the tables? That might improve performance, as the join order is computed based on the statistics of the tables.</p>\n\n<p>BTW, what are you allowed to do? Just read? If you can create temporary tables and put indexes on those, I might consider making temporary copies of the table, indexing those, and then do the index-assisted join with the temp copies.</p>\n" }, { "answer_id": 245031, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 0, "selected": false, "text": "<p>Sometimes you can see a benefit by adding extra pathways for the optimizer to choose by adding what seems like redundant elements to the where clause.</p>\n\n<p>For instance, you've got A.ItemNum = B.ItemNum AND B.ItemNum = C.ItemNum. Try adding A.ItemNum = C.ItemNum as well. I'm pretty sure, however, that the optimizer is intelligent enough to figure that out on its own - worth a try though.</p>\n" }, { "answer_id": 246720, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 0, "selected": false, "text": "<p>Depending on the datatype of the ItemType column you may experience faster executing using the following if it's a varchar, Oracle will do implict conversions.</p>\n\n<pre><code>SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM items a,\nitempages b,\nkeygroupdata c\nWHERE ((a.ItemType IN ('112','115','189','241'))\nAND (a.ItemNum = b.ItemNum)\nAND (b.ItemNum = c.ItemNum))\nORDER BY a.DateStored DESC\n</code></pre>\n" }, { "answer_id": 274556, "author": "Mike Meyers", "author_id": 35723, "author_profile": "https://Stackoverflow.com/users/35723", "pm_score": 0, "selected": false, "text": "<p>If you say that there are no indexes, then does this also mean that there are no primary or foreign keys defined? Obviously analysing the tables and gathering statistics are important but if metadata such as defining how the tables are supposed to be joined doesn't exist, then Oracle may well choose a poor execution path. </p>\n\n<p>In that case using a hint such as /*+ ORDERED */ may well be the only option to make the optimizer reliably choose a good execution path. It may also be worth adding foreign keys and primary keys but define them as DISABLE and VALIDATE. </p>\n\n<p>I guess the usefulness of this comment depends on how far the aversion to indexes goes so YMMV.</p>\n" }, { "answer_id": 7751655, "author": "muhammad khalid", "author_id": 993053, "author_profile": "https://Stackoverflow.com/users/993053", "pm_score": 0, "selected": false, "text": "<p>First create a view on this query and then generate a table from this view. Also create an index on date, make a job and schedule it in midnight time when the system is idle.</p>\n" }, { "answer_id": 8071856, "author": "armin walland", "author_id": 1038572, "author_profile": "https://Stackoverflow.com/users/1038572", "pm_score": 1, "selected": false, "text": "<p>I know this thread is very old, but for the search engines I still wanted to offer an alternative solution that will work on oracle and depending on the data might be much faster.</p>\n\n<pre><code>with a as (\n select \n * \n from \n items \n where \n ItemType IN (112,115,189,241)\n)\nSELECT \n c.ClaimNumber\n , a.ItemDate\n , c.DTN, b.FilePath\nFROM \n a,\n itempages b,\n keygroupdata c\nWHERE \n a.ItemNum = b.ItemNum\n AND b.ItemNum = c.ItemNum\nORDER BY \n a.DateStored DESC\n</code></pre>\n\n<p>You can also try the <code>/*+ MATERIALIZE */</code> hint in the <code>WITH</code> clause.</p>\n\n<p>Actually I find oracle's old join syntax much easier to read than ansi sql ^^</p>\n" }, { "answer_id": 47328788, "author": "Max Lambertini", "author_id": 1035663, "author_profile": "https://Stackoverflow.com/users/1035663", "pm_score": 0, "selected": false, "text": "<p>Well, since you can't create indexes, I'd make sure that statistics are all up-to-date then, I'd rewrite the query this way:</p>\n\n<p><code>\nwith a as (select /*+ MATERIALIZE */ ItemType, ItemNum, DateStored, ItemDate from items where ItemType in (112,115,189,241))\nSELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath\nFROM a,\nitempages b,\nkeygroupdata c\nWHERE a.ItemNum = b.ItemNum\nAND b.ItemNum = c.ItemNum\nORDER BY a.DateStored DESC\n</code></p>\n" }, { "answer_id": 71430717, "author": "Scott Dwyer", "author_id": 18433073, "author_profile": "https://Stackoverflow.com/users/18433073", "pm_score": 0, "selected": false, "text": "<p>Heads up, I work at Rockset, but this is a pretty perfect use case, so some info.</p>\n<p>Rockset just announced an early access program for Oracle / MS SQL that provides query performance suitable for real-time data applications without any manual indexing. Using AWS’ DMS, data from Oracle is converted into a stream and sent to Rockset via AWS Kinesis. Rockset tails the Kinesis stream, automatically indexes data and makes it available within a few seconds. Rockset is a fully-managed OLAP database that enables millisecond latency search, aggregations and joins on any data by automatically building a converged index, which combines the power of columnar, row and inverted indexes. It's honestly some cool stuff.</p>\n<p>More info is available here: <a href=\"https://rockset.com/blog/real-time-analytics-on-oracle-and-ms-sql-with-rockset/\" rel=\"nofollow noreferrer\">https://rockset.com/blog/real-time-analytics-on-oracle-and-ms-sql-with-rockset/</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
What are some things I can do to improve query performance of an oracle query without creating indexes? Here is the query I'm trying to run faster: ``` SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath FROM items a, itempages b, keygroupdata c WHERE a.ItemType IN (112,115,189,241) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC ``` None of these columns are indexed and each of the tables contains millions of records. Needless to say, it takes over 3 and half minutes for the query to execute. This is a third party database in a production environment and I'm not allowed to create any indexes so any performance improvements would have to be made to the query itself. Thanks!
First I'd rewrite the query to be ANSI standard: ``` SELECT c.ClaimNumber, a.ItemDate, c.DTN, b.FilePath FROM items a INNER JOIN itempages b ON b.ItemNum = a.ItemNum INNER JOIN keygroupdata c ON c.ItemNum = b.ItemNum WHERE a.ItemType IN (112,115,189,241) ORDER BY a.DateStored DESC ``` This makes it easier to read and understand what is going on. It also helps you not make mistakes (i.e. Cross Joining)that might cause real big problems. Then I'd get the Explain plan to see what the DBMS is doing with that query. Is it trying to use some indexes? Is it joining the tables correctly? Then I'd review the tables that I'm working with to see if there are any indexes that already exist that I could be using to make my query faster. Finally as everyone else has suggested I'd remove the Order By clause and just do that in code.
244,110
<p>Here's the code. Not much to it.</p> <pre><code>&lt;?php include(&quot;Spreadsheet/Excel/Writer.php&quot;); $xls = new Spreadsheet_Excel_Writer(); $sheet = $xls-&gt;addWorksheet('At a Glance'); $colNames = array('Foo', 'Bar'); $sheet-&gt;writeRow(0, 0, $colNames, $colHeadingFormat); for($i=1; $i&lt;=10; $i++) { $row = array( &quot;foo $i&quot;, &quot;bar $i&quot;); $sheet-&gt;writeRow($rowNumber++, 0, $row); } header (&quot;Expires: &quot; . gmdate(&quot;D,d M Y H:i:s&quot;) . &quot; GMT&quot;); header (&quot;Last-Modified: &quot; . gmdate(&quot;D,d M Y H:i:s&quot;) . &quot; GMT&quot;); header (&quot;Cache-Control: no-cache, must-revalidate&quot;); header (&quot;Pragma: no-cache&quot;); $xls-&gt;send(&quot;test.xls&quot;); $xls-&gt;close(); ?&gt; </code></pre> <p>The issue is that I get the following error when I actually open the file with Excel:</p> <pre><code>File error: data may have been lost. </code></pre> <p>Even stranger is the fact that, despite the error, the file seems fine. Any data I happen to be writing is there.</p> <p>Any ideas on how to get rid of this error?</p> <hr /> <h3>Edit</h3> <p>I've modified the code sample to better illustrate the problem. I don't think the first sample was a legit test.</p>
[ { "answer_id": 244161, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<p>Hmm I just installed it to test and didn't get an error - it said Foo like it should.</p>\n\n<p>The file generated was 3,584 bytes; I opened it in Excel 2002</p>\n" }, { "answer_id": 244404, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 4, "selected": true, "text": "<p>The code in the question has a bug which causes the error.</p>\n\n<p>This line writes a bunch of column names to row 0</p>\n\n<pre><code>$sheet-&gt;writeRow(0, 0, $colNames, $colHeadingFormat);\n</code></pre>\n\n<p>Then we have the loop which is supposed to write out the value rows.</p>\n\n<pre><code>for($i=1; $i&lt;=10; $i++)\n{\n $row = array( \"foo $i\", \"bar $i\");\n\n $sheet-&gt;writeRow($rowNumber++, 0, $row);\n}\n</code></pre>\n\n<p>The problem is that <strong>$rowNumber</strong> isn't declared anywhere so it overwrites row 0 on the first pass through the loop.</p>\n\n<p>This overwriting seems to cause an issue with Excel Writer.</p>\n\n<p>The strange thing is that, on the Excel file that gives the error, you still see the row with the column names even though it's technically been overwritten.</p>\n\n<p>I found the solution <a href=\"http://groups.google.com/group/spreadsheet-writeexcel/browse_thread/thread/6656856820b6f799/\" rel=\"noreferrer\">here on Google Groups</a>. Scroll down to the bottom. It's the last post by <strong>Micah</strong> that mentions the issue.</p>\n\n<hr>\n\n<p>And here's the fix</p>\n\n<pre><code>&lt;?php\ninclude(\"Spreadsheet/Excel/Writer.php\");\n\n$xls = new Spreadsheet_Excel_Writer();\n\n$rowNumber = 0;\n$sheet = $xls-&gt;addWorksheet('At a Glance');\n\n$colNames = array('Foo', 'Bar');\n$sheet-&gt;writeRow($rowNumber, 0, $colNames, $colHeadingFormat);\n\nfor($i=1; $i&lt;=10; $i++)\n{\n $rowNumber++;\n $row = array( \"foo $i\", \"bar $i\");\n\n $sheet-&gt;writeRow($rowNumber, 0, $row);\n}\n\nheader (\"Expires: \" . gmdate(\"D,d M Y H:i:s\") . \" GMT\");\nheader (\"Last-Modified: \" . gmdate(\"D,d M Y H:i:s\") . \" GMT\");\nheader (\"Cache-Control: no-cache, must-revalidate\");\nheader (\"Pragma: no-cache\");\n$xls-&gt;send(\"test.xls\");\n$xls-&gt;close();\n?&gt;\n</code></pre>\n" }, { "answer_id": 258324, "author": "jmcnamara", "author_id": 10238, "author_profile": "https://Stackoverflow.com/users/10238", "pm_score": 2, "selected": false, "text": "<p>As Mark Biek points out the main problem is that <code>$rowNumber</code> is uninitialised and as such overwrites row 0.</p>\n\n<p>This means that the generated Excel file will contain 2 data entries for cells A1 and B1, (0, 0 and 0, 1).</p>\n\n<p>This wasn't a problem prior to Office Service Pack 3. However, once SP3 is installed Excel will raise a \"data may have been lost\" warning if it encounters duplicate entries for a cell.</p>\n\n<p>The general solution is to not write more than one data to a cell. :-)</p>\n\n<p>Here is a more <a href=\"http://groups.google.com/group/spreadsheet-writeexcel/browse_thread/thread/3dcea40e6620af3a\" rel=\"nofollow noreferrer\">detailed explanation</a> of the issue. It is in relation to the Perl <a href=\"http://search.cpan.org/~jmcnamara/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm\" rel=\"nofollow noreferrer\">Spreadsheet::WriteExcel</a> module (from which the PHP module is derived) but the thrust is the same.</p>\n" }, { "answer_id": 1660780, "author": "Joernsn", "author_id": 168502, "author_profile": "https://Stackoverflow.com/users/168502", "pm_score": 0, "selected": false, "text": "<p>I got this error when writing to column 0 (A0) with PHPExcel. Excel is 1-indexed (A1), that's why it said \"data may have been lost\".</p>\n\n<pre><code>$this-&gt;m_excel-&gt;getActiveSheet()-&gt;SetCellValue($chr[$col].$row, $data));\n</code></pre>\n\n<p><code>$row</code> was initialized to 0</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
Here's the code. Not much to it. ``` <?php include("Spreadsheet/Excel/Writer.php"); $xls = new Spreadsheet_Excel_Writer(); $sheet = $xls->addWorksheet('At a Glance'); $colNames = array('Foo', 'Bar'); $sheet->writeRow(0, 0, $colNames, $colHeadingFormat); for($i=1; $i<=10; $i++) { $row = array( "foo $i", "bar $i"); $sheet->writeRow($rowNumber++, 0, $row); } header ("Expires: " . gmdate("D,d M Y H:i:s") . " GMT"); header ("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT"); header ("Cache-Control: no-cache, must-revalidate"); header ("Pragma: no-cache"); $xls->send("test.xls"); $xls->close(); ?> ``` The issue is that I get the following error when I actually open the file with Excel: ``` File error: data may have been lost. ``` Even stranger is the fact that, despite the error, the file seems fine. Any data I happen to be writing is there. Any ideas on how to get rid of this error? --- ### Edit I've modified the code sample to better illustrate the problem. I don't think the first sample was a legit test.
The code in the question has a bug which causes the error. This line writes a bunch of column names to row 0 ``` $sheet->writeRow(0, 0, $colNames, $colHeadingFormat); ``` Then we have the loop which is supposed to write out the value rows. ``` for($i=1; $i<=10; $i++) { $row = array( "foo $i", "bar $i"); $sheet->writeRow($rowNumber++, 0, $row); } ``` The problem is that **$rowNumber** isn't declared anywhere so it overwrites row 0 on the first pass through the loop. This overwriting seems to cause an issue with Excel Writer. The strange thing is that, on the Excel file that gives the error, you still see the row with the column names even though it's technically been overwritten. I found the solution [here on Google Groups](http://groups.google.com/group/spreadsheet-writeexcel/browse_thread/thread/6656856820b6f799/). Scroll down to the bottom. It's the last post by **Micah** that mentions the issue. --- And here's the fix ``` <?php include("Spreadsheet/Excel/Writer.php"); $xls = new Spreadsheet_Excel_Writer(); $rowNumber = 0; $sheet = $xls->addWorksheet('At a Glance'); $colNames = array('Foo', 'Bar'); $sheet->writeRow($rowNumber, 0, $colNames, $colHeadingFormat); for($i=1; $i<=10; $i++) { $rowNumber++; $row = array( "foo $i", "bar $i"); $sheet->writeRow($rowNumber, 0, $row); } header ("Expires: " . gmdate("D,d M Y H:i:s") . " GMT"); header ("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT"); header ("Cache-Control: no-cache, must-revalidate"); header ("Pragma: no-cache"); $xls->send("test.xls"); $xls->close(); ?> ```
244,113
<p>I'm working on a stored procedure in SQL Server 2000 with a temp table defined like this:</p> <pre>CREATE TABLE #MapTable (Category varchar(40), Code char(5))</pre> <p>After creating the table I want to insert some standard records (which will then be supplemented dynamically in the procedure). Each category (about 10) will have several codes (typically 3-5), and I'd like to express the insert operation for each category in one statement. </p> <p>Any idea how to do that? </p> <p>The best idea I've had so far is to keep a real table in the db as a template, but I'd really like to avoid that if possible. The database where this will live is a snapshot of a mainframe system, such that the entire database is blown away every night and re-created in a batch process- stored procedures are re-loaded from source control at the end of the process.</p> <p>The issue I'm trying to solve isn't so much keeping it to one statement as it is trying to avoid re-typing the category name over and over.</p>
[ { "answer_id": 244158, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 0, "selected": false, "text": "<p>This might work for you:</p>\n\n<pre><code>CREATE TABLE #MapTable (Category varchar(40), Code char(5))\n\nINSERT INTO #MapTable \nSELECT X.Category, X.Code FROM\n(SELECT 'Foo' as Category, 'AAAAA' as Code\nUNION\nSELECT 'Foo' as Category, 'BBBBB' as Code\nUNION\nSELECT 'Foo' as Category, 'CCCCC' as Code) AS X\n\nSELECT * FROM #MapTable\n</code></pre>\n" }, { "answer_id": 244194, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 3, "selected": false, "text": "<p>DJ's is a fine solution but could be simplified (see below).</p>\n\n<p>Why does it need to be a single statement?</p>\n\n<p>What's wrong with:</p>\n\n<pre><code>insert into #MapTable (category,code) values ('Foo','AAAAA')\ninsert into #MapTable (category,code) values ('Foo','BBBBB')\ninsert into #MapTable (category,code) values ('Foo','CCCCC')\ninsert into #MapTable (category,code) values ('Bar','AAAAA')\n</code></pre>\n\n<p>For me this is much easier to read and maintain.</p>\n\n<hr>\n\n<p>Simplified DJ solution:</p>\n\n<pre><code>CREATE TABLE #MapTable (Category varchar(40), Code char(5))\n\nINSERT INTO #MapTable (Category, Code)\nSELECT 'Foo', 'AAAAA'\nUNION\nSELECT 'Foo', 'BBBBB'\nUNION\nSELECT 'Foo', 'CCCCC' \n\nSELECT * FROM #MapTable\n</code></pre>\n\n<p>There's nothing really wrong with DJ's, it just felt overly complex to me.</p>\n\n<hr>\n\n<p>From the OP:</p>\n\n<blockquote>\n <p>The issue I'm trying to solve isn't so much keeping it to one statement as it\n is trying to avoid re-typing the category name over and over.</p>\n</blockquote>\n\n<p>I feel your pain -- I try to find shortcuts like this too and realize that by the time I solve the problem, I could have typed it long hand.</p>\n\n<p>If I have a lot of repetitive data to input, I'll sometimes use Excel to generate the insert codes for me. Put the Category in one column and the Code in another; use all of the helpful copying techniques to do the hard work</p>\n\n<p>then </p>\n\n<pre><code>=\"insert into #MapTable (category,code) values ('\"&amp;A1&amp;\"','\"&amp;B1&amp;\"')\"\n</code></pre>\n\n<p>in a third row and I've generated my inserts</p>\n\n<p>Of course, all of this is assuming that the Categories and Codes can't be pulled from a system table.</p>\n" }, { "answer_id": 244415, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 2, "selected": true, "text": "<pre>\ninsert into #maptable (category, code)\nselect 'foo1', b.bar\nfrom \n ( select 'bar11' as bar\n union select 'bar12'\n union select 'bar13'\n ) b\nunion\nselect 'foo2', b.bar\nfrom \n ( select 'bar21' as bar\n union select 'bar22'\n union select 'bar23'\n ) b\n</pre>\n" }, { "answer_id": 244638, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Here's the notation I ended up using. It's based on Arvo's answer, but a little shorter and uses cAse to help make things clearer:</p>\n\n<pre><code>SELECT 'foo1', b.code\nFROM ( select 'bar11' as code\n union select 'bar12'\n union select 'bar13' ) b\n\nUNION SELECT 'foo2', b.code\nFROM ( select 'bar21' as code\n union select 'bar22' \n union select 'bar32' ) b\n</code></pre>\n\n<p>This way highlights the category names a little, lines up codes vertically, and uses less vertical space.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I'm working on a stored procedure in SQL Server 2000 with a temp table defined like this: ``` CREATE TABLE #MapTable (Category varchar(40), Code char(5)) ``` After creating the table I want to insert some standard records (which will then be supplemented dynamically in the procedure). Each category (about 10) will have several codes (typically 3-5), and I'd like to express the insert operation for each category in one statement. Any idea how to do that? The best idea I've had so far is to keep a real table in the db as a template, but I'd really like to avoid that if possible. The database where this will live is a snapshot of a mainframe system, such that the entire database is blown away every night and re-created in a batch process- stored procedures are re-loaded from source control at the end of the process. The issue I'm trying to solve isn't so much keeping it to one statement as it is trying to avoid re-typing the category name over and over.
``` insert into #maptable (category, code) select 'foo1', b.bar from ( select 'bar11' as bar union select 'bar12' union select 'bar13' ) b union select 'foo2', b.bar from ( select 'bar21' as bar union select 'bar22' union select 'bar23' ) b ```
244,115
<p>Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going about this?</p>
[ { "answer_id": 244236, "author": "Balint Pato", "author_id": 19621, "author_profile": "https://Stackoverflow.com/users/19621", "pm_score": 2, "selected": false, "text": "<p>If I understand your question well then here are two example methods to tokenize a string. You do not even need the Scanner class, only if you want to pre-cast the tokens, or iterate through them more sofistically than using an array. If an array is enough just use String.split() as given below. </p>\n\n<p>Please give more requirements to enable more precise answers. </p>\n\n<pre><code> import java.util.Scanner;\n\n\n public class Main { \n\n public static void main(String[] args) {\n\n String textToTokenize = \"This is a text that will be tokenized. I will use 1-2 methods.\";\n Scanner scanner = new Scanner(textToTokenize);\n scanner.useDelimiter(\"i.\");\n while (scanner.hasNext()){\n System.out.println(scanner.next());\n }\n\n System.out.println(\" **************** \");\n String[] sSplit = textToTokenize.split(\"i.\");\n\n for (String token: sSplit){\n System.out.println(token);\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 244338, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 2, "selected": false, "text": "<p>If this is for a simple project (for learning how things work), then go with what Balint Pato said.</p>\n\n<p>If this is for a larger project, consider using a scanner generator like <a href=\"http://jflex.de/\" rel=\"nofollow noreferrer\">JFlex</a> instead. Somewhat more complicated, but faster and more powerful.</p>\n" }, { "answer_id": 247495, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 5, "selected": true, "text": "<p>The name \"Scanner\" is a bit misleading, because the word is often used to mean a lexical analyzer, and that's not what Scanner is for. All it is is a substitute for the <code>scanf()</code> function you find in C, Perl, <em>et al</em>. Like StringTokenizer and <code>split()</code>, it's designed to scan ahead until it finds a match for a given pattern, and whatever it skipped over on the way is returned as a token. </p>\n\n<p>A lexical analyzer, on the other hand, has to examine and classify every character, even if it's only to decide whether it can safely ignore them. That means, after each match, it may apply several patterns until it finds one that matches <em>starting at that point</em>. Otherwise, it may find the sequence \"//\" and think it's found the beginning of a comment, when it's really inside a string literal and it just failed to notice the opening quotation mark. </p>\n\n<p>It's actually much more complicated than that, of course, but I'm just illustrating why the built-in tools like StringTokenizer, <code>split()</code> and Scanner aren't suitable for this kind of task. It is, however, possible to use Java's regex classes for a limited form of lexical analysis. In fact, the addition of the Scanner class made it much easier, because of the new Matcher API that was added to support it, i.e., regions and the <code>usePattern()</code> method. Here's an example of a rudimentary scanner built on top of Java's regex classes.</p>\n\n<pre><code>import java.util.*;\nimport java.util.regex.*;\n\npublic class RETokenizer\n{\n static List&lt;Token&gt; tokenize(String source, List&lt;Rule&gt; rules)\n {\n List&lt;Token&gt; tokens = new ArrayList&lt;Token&gt;();\n int pos = 0;\n final int end = source.length();\n Matcher m = Pattern.compile(\"dummy\").matcher(source);\n m.useTransparentBounds(true).useAnchoringBounds(false);\n while (pos &lt; end)\n {\n m.region(pos, end);\n for (Rule r : rules)\n {\n if (m.usePattern(r.pattern).lookingAt())\n {\n tokens.add(new Token(r.name, m.start(), m.end()));\n pos = m.end();\n break;\n }\n }\n pos++; // bump-along, in case no rule matched\n }\n return tokens;\n }\n\n static class Rule\n {\n final String name;\n final Pattern pattern;\n\n Rule(String name, String regex)\n {\n this.name = name;\n pattern = Pattern.compile(regex);\n }\n }\n\n static class Token\n {\n final String name;\n final int startPos;\n final int endPos;\n\n Token(String name, int startPos, int endPos)\n {\n this.name = name;\n this.startPos = startPos;\n this.endPos = endPos;\n }\n\n @Override\n public String toString()\n {\n return String.format(\"Token [%2d, %2d, %s]\", startPos, endPos, name);\n }\n }\n\n public static void main(String[] args) throws Exception\n {\n List&lt;Rule&gt; rules = new ArrayList&lt;Rule&gt;();\n rules.add(new Rule(\"WORD\", \"[A-Za-z]+\"));\n rules.add(new Rule(\"QUOTED\", \"\\\"[^\\\"]*+\\\"\"));\n rules.add(new Rule(\"COMMENT\", \"//.*\"));\n rules.add(new Rule(\"WHITESPACE\", \"\\\\s+\"));\n\n String str = \"foo //in \\\"comment\\\"\\nbar \\\"no //comment\\\" end\";\n List&lt;Token&gt; result = RETokenizer.tokenize(str, rules);\n for (Token t : result)\n {\n System.out.println(t);\n }\n }\n}\n</code></pre>\n\n<p>This, by the way, is the only good use I've ever found for the <code>lookingAt()</code> method. :D</p>\n" }, { "answer_id": 985222, "author": "ra9r", "author_id": 88916, "author_profile": "https://Stackoverflow.com/users/88916", "pm_score": 2, "selected": false, "text": "<p>Most of the answers here are already excellent but I would be remiss if I didn't point out <a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a>. I've created entire compilers around this excellent tool. Version 3 has some amazing features and I'd recommend it for any project that required you to parse input based on a well defined grammar.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370/" ]
Just for my own purposes, I'm trying to build a tokenizer in Java where I can define a regular grammar and have it tokenize input based on that. The StringTokenizer class is deprecated, and I've found a couple functions in Scanner that hint towards what I want to do, but no luck yet. Anyone know a good way of going about this?
The name "Scanner" is a bit misleading, because the word is often used to mean a lexical analyzer, and that's not what Scanner is for. All it is is a substitute for the `scanf()` function you find in C, Perl, *et al*. Like StringTokenizer and `split()`, it's designed to scan ahead until it finds a match for a given pattern, and whatever it skipped over on the way is returned as a token. A lexical analyzer, on the other hand, has to examine and classify every character, even if it's only to decide whether it can safely ignore them. That means, after each match, it may apply several patterns until it finds one that matches *starting at that point*. Otherwise, it may find the sequence "//" and think it's found the beginning of a comment, when it's really inside a string literal and it just failed to notice the opening quotation mark. It's actually much more complicated than that, of course, but I'm just illustrating why the built-in tools like StringTokenizer, `split()` and Scanner aren't suitable for this kind of task. It is, however, possible to use Java's regex classes for a limited form of lexical analysis. In fact, the addition of the Scanner class made it much easier, because of the new Matcher API that was added to support it, i.e., regions and the `usePattern()` method. Here's an example of a rudimentary scanner built on top of Java's regex classes. ``` import java.util.*; import java.util.regex.*; public class RETokenizer { static List<Token> tokenize(String source, List<Rule> rules) { List<Token> tokens = new ArrayList<Token>(); int pos = 0; final int end = source.length(); Matcher m = Pattern.compile("dummy").matcher(source); m.useTransparentBounds(true).useAnchoringBounds(false); while (pos < end) { m.region(pos, end); for (Rule r : rules) { if (m.usePattern(r.pattern).lookingAt()) { tokens.add(new Token(r.name, m.start(), m.end())); pos = m.end(); break; } } pos++; // bump-along, in case no rule matched } return tokens; } static class Rule { final String name; final Pattern pattern; Rule(String name, String regex) { this.name = name; pattern = Pattern.compile(regex); } } static class Token { final String name; final int startPos; final int endPos; Token(String name, int startPos, int endPos) { this.name = name; this.startPos = startPos; this.endPos = endPos; } @Override public String toString() { return String.format("Token [%2d, %2d, %s]", startPos, endPos, name); } } public static void main(String[] args) throws Exception { List<Rule> rules = new ArrayList<Rule>(); rules.add(new Rule("WORD", "[A-Za-z]+")); rules.add(new Rule("QUOTED", "\"[^\"]*+\"")); rules.add(new Rule("COMMENT", "//.*")); rules.add(new Rule("WHITESPACE", "\\s+")); String str = "foo //in \"comment\"\nbar \"no //comment\" end"; List<Token> result = RETokenizer.tokenize(str, rules); for (Token t : result) { System.out.println(t); } } } ``` This, by the way, is the only good use I've ever found for the `lookingAt()` method. :D
244,119
<p>Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ?</p> <p>Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace implementations of some methods.</p>
[ { "answer_id": 244146, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "<p>The <code>java.lang.reflect</code> package classes and methods allow this access, within certain limits.</p>\n\n<p>See <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html\" rel=\"nofollow noreferrer\">java.lang.reflect</a></p>\n" }, { "answer_id": 244156, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 4, "selected": true, "text": "<p>In most of the cases java <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html\" rel=\"nofollow noreferrer\">reflection</a> solves the problem:</p>\n\n<p>Example:</p>\n\n<pre><code>public class Foo {\n\n /**\n * Gets the name Field.\n * \n * @return the name\n */\n public final String getName() {\n return name;\n }\n\n /**\n * Sets the name Field with the name input value.\n * \n * @param name the name to set\n */\n public final void setName(String name) {\n this.name = name;\n }\n\n private String name;\n\n}\n</code></pre>\n\n<p>Now the Reflection Code:</p>\n\n<pre><code>import java.lang.reflect.Field;\n....\n\nFoo foo = new Foo();\nfoo.setName(\"old Name\");\nString fieldName = \"name\";\nClass class1 = Foo.class;\n\ntry {\n\n System.out.println(foo.getName());\n\n Field field = class1.getDeclaredField(fieldName);\n\n field.setAccessible(true);\n\n field.set(foo, \"My New Name\");\n\n System.out.println(foo.getName());\n\n} catch (NoSuchFieldException e) {\n System.out.println(\"FieldNotFound: \" + e);\n} catch (IllegalAccessException e) {\n System.out.println(\"Ilegal Access: \" + e);\n}\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>It's worth mentioning that this approach can be thwarted by a SecurityManager. – Dan Dyer </p>\n" }, { "answer_id": 244174, "author": "Matthew Brubaker", "author_id": 21311, "author_profile": "https://Stackoverflow.com/users/21311", "pm_score": 2, "selected": false, "text": "<p>Without knowing why you want that level of access, I can only wonder what you could need that level of access for. Private members are private for a reason. They are not intended to be accessed from outside the class and could result in undocumented behavior.</p>\n\n<p>That said, you can get access to most things through the java.lang.reflect package.</p>\n\n<p>In my opinion, you should examine why you think you need that level of access and see if you could be doing something differently to not need it. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23691/" ]
Can anoyne recommend a good library that will let me easily read/write private member fields of a class? I was looking through apache commons, but couldnt see it. I must be getting blind ? Edit: Asking questions on the border of legalities always give these questions of "why"? I am writing several javarebel plugins for hotswapping classes. Accessing private variables is only step 1, I might even have to replace implementations of some methods.
In most of the cases java [reflection](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/package-summary.html) solves the problem: Example: ``` public class Foo { /** * Gets the name Field. * * @return the name */ public final String getName() { return name; } /** * Sets the name Field with the name input value. * * @param name the name to set */ public final void setName(String name) { this.name = name; } private String name; } ``` Now the Reflection Code: ``` import java.lang.reflect.Field; .... Foo foo = new Foo(); foo.setName("old Name"); String fieldName = "name"; Class class1 = Foo.class; try { System.out.println(foo.getName()); Field field = class1.getDeclaredField(fieldName); field.setAccessible(true); field.set(foo, "My New Name"); System.out.println(foo.getName()); } catch (NoSuchFieldException e) { System.out.println("FieldNotFound: " + e); } catch (IllegalAccessException e) { System.out.println("Ilegal Access: " + e); } ``` **UPDATE:** It's worth mentioning that this approach can be thwarted by a SecurityManager. – Dan Dyer
244,152
<p>I have a site that requires Windows Authentication the application obtains the credential from the Security.Prinicipal once the user is autenticated the problem is that my credentials on my local environment are different that the ones stored in the DB and the user preferences cannot be obtain. i am doing the following workaround in order to deal with this issue.</p> <pre><code> #if DEBUG var myUser = userBL.GetSingle(@"desiredDomain\otherUserName"); #else var myUser = userBL.GetSingle(HttpApplication.User.Identity.Name); #endif Session.Add("User",myUser); </code></pre> <p>is there any other way rather than impersonating or the above mentioned workaorund to change the the value of HttpApplication.User.Identity.Name this is beacuse I have to change my code everytime I need to commit into repository or deploy the App</p>
[ { "answer_id": 244195, "author": "Brian Lee", "author_id": 4548, "author_profile": "https://Stackoverflow.com/users/4548", "pm_score": 0, "selected": false, "text": "<p>Have you looked into using Impersonation in Web.Config to set the id to your test credentials. I would presume that you have a \"test\" web.config and a \"production\" web.config. This way you won't have to worry about removing it when you go live.</p>\n" }, { "answer_id": 244245, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 0, "selected": false, "text": "<p>I've done this before by wrapping this in a utility method. If HttpContext.Current isn't null, get it from there. Otherwise get it from WindowsIdentity.GetCurrent().</p>\n" }, { "answer_id": 244874, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": true, "text": "<p>While you could alter userBL, why wouldn't you instead alter the database records to reflect that they're in a different domain. I'm assuming you're not hitting the production database, so there should be no issues with a 'sanitizing' step that makes the database useable for dev/test.</p>\n\n<p>e.g.</p>\n\n<pre><code>UPDATE Users \nSET \n UserName = REPLACE(UserName, '\\\\ProductionDomain\\', '\\\\DevDomain\\')\n</code></pre>\n\n<ol>\n<li>using #if DEBUG is bad for this sort of thing. Someone could/should legitimately load a debug version of code on production, and all of a sudden logins are broken. These things are better controlled in a web.config when they are needed.</li>\n<li>Developers should be working against a dev copy of the database. It is very typical to sanitize some aspects of the database when the copy is made. Sometimes this is for privacy regulations (e.g. obscuring users real names and logins) </li>\n</ol>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440/" ]
I have a site that requires Windows Authentication the application obtains the credential from the Security.Prinicipal once the user is autenticated the problem is that my credentials on my local environment are different that the ones stored in the DB and the user preferences cannot be obtain. i am doing the following workaround in order to deal with this issue. ``` #if DEBUG var myUser = userBL.GetSingle(@"desiredDomain\otherUserName"); #else var myUser = userBL.GetSingle(HttpApplication.User.Identity.Name); #endif Session.Add("User",myUser); ``` is there any other way rather than impersonating or the above mentioned workaorund to change the the value of HttpApplication.User.Identity.Name this is beacuse I have to change my code everytime I need to commit into repository or deploy the App
While you could alter userBL, why wouldn't you instead alter the database records to reflect that they're in a different domain. I'm assuming you're not hitting the production database, so there should be no issues with a 'sanitizing' step that makes the database useable for dev/test. e.g. ``` UPDATE Users SET UserName = REPLACE(UserName, '\\ProductionDomain\', '\\DevDomain\') ``` 1. using #if DEBUG is bad for this sort of thing. Someone could/should legitimately load a debug version of code on production, and all of a sudden logins are broken. These things are better controlled in a web.config when they are needed. 2. Developers should be working against a dev copy of the database. It is very typical to sanitize some aspects of the database when the copy is made. Sometimes this is for privacy regulations (e.g. obscuring users real names and logins)
244,157
<p>I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file_get_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way.</p> <p>This is my current code</p> <pre><code> $url = urldecode( $object_list_url ); $xmlstr = file_get_contents ( $url ); $obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA ); </code></pre>
[ { "answer_id": 244163, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>The ini var you're referring to is <code>allow_url_fopen</code>. To check, run this script:</p>\n\n<pre><code>var_dump(ini_get('allow_url_fopen'));\n</code></pre>\n\n<p>Ask your host to turn that ini value on (if it's disabled - it's on by default).</p>\n\n<p>You should not be able to access any remote url without that ini setting on.</p>\n\n<p>Also an idea if they won't could be to try <a href=\"http://docs.php.net/manual/en/function.copy.php\" rel=\"nofollow noreferrer\"><code>copy</code></a>ing the file to your server. I expect all filesystem functions will be covered by that ini setting but it's always worth a try.</p>\n" }, { "answer_id": 244166, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>You could use <a href=\"http://www.php.net/curl\" rel=\"nofollow noreferrer\">cURL</a> (if that's not been disabled).\nSomething like this:</p>\n\n<pre><code>$c = curl_init($url);\ncurl_setopt($c, CURLOPT_RETURNTRANSFER, true);\n$xmlstr = curl_exec($c);\n</code></pre>\n" }, { "answer_id": 244169, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 0, "selected": false, "text": "<p>Can you execute the following script and provide the information as a comment?</p>\n\n<pre><code>&lt;?php\nphpinfo();\n?&gt;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I am trying to read an XML-file from another server. However the the company that's hosting me seems to have turned of the file\_get\_contents function from retrieving files for files from other servers (and their support is not very bright and it takes forever for them to answer). So I need a work around in some way. This is my current code ``` $url = urldecode( $object_list_url ); $xmlstr = file_get_contents ( $url ); $obj = new SimpleXMLElement ( $xmlstr, LIBXML_NOCDATA ); ```
You could use [cURL](http://www.php.net/curl) (if that's not been disabled). Something like this: ``` $c = curl_init($url); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); $xmlstr = curl_exec($c); ```
244,164
<p>I need to resize PNG, JPEG and GIF files. How can I do this using Java?</p>
[ { "answer_id": 244177, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 8, "selected": true, "text": "<p>After loading the image you can try:</p>\n\n<pre><code>BufferedImage createResizedCopy(Image originalImage, \n int scaledWidth, int scaledHeight, \n boolean preserveAlpha)\n {\n System.out.println(\"resizing...\");\n int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;\n BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);\n Graphics2D g = scaledBI.createGraphics();\n if (preserveAlpha) {\n g.setComposite(AlphaComposite.Src);\n }\n g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); \n g.dispose();\n return scaledBI;\n }\n</code></pre>\n" }, { "answer_id": 244306, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.oracle.com/technetwork/java/javase/tech/jai-142803.html\" rel=\"nofollow noreferrer\">Java Advanced Imaging</a> is now open source, and provides the operations you need.</p>\n" }, { "answer_id": 533526, "author": "Joel Carranza", "author_id": 64287, "author_profile": "https://Stackoverflow.com/users/64287", "pm_score": 3, "selected": false, "text": "<p>If you are dealing with large images or want a nice looking result it's not a trivial task in java. Simply doing it via a rescale op via Graphics2D will not create a high quality thumbnail. You can do it using JAI, but it requires more work than you would imagine to get something that looks good and JAI has a nasty habit of blowing our your JVM with OutOfMemory errors. </p>\n\n<p>I suggest using ImageMagick as an external executable if you can get away with it. Its simple to use and it does the job right so that you don't have to. </p>\n" }, { "answer_id": 533596, "author": "David Koelle", "author_id": 2197, "author_profile": "https://Stackoverflow.com/users/2197", "pm_score": 4, "selected": false, "text": "<p>You don't need a library to do this. You can do it with Java itself.</p>\n\n<p>Chris Campbell has an excellent and detailed write-up on scaling images - see <a href=\"https://community.oracle.com/docs/DOC-983611\" rel=\"nofollow noreferrer\">this article</a>.</p>\n\n<p>Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, <a href=\"http://filthyrichclients.org/\" rel=\"nofollow noreferrer\">Filthy Rich Clients</a>. </p>\n" }, { "answer_id": 1202296, "author": "naltatis", "author_id": 24902, "author_profile": "https://Stackoverflow.com/users/24902", "pm_score": 2, "selected": false, "text": "<p>If, having imagemagick installed on your maschine is an option, I recommend <a href=\"http://im4java.sourceforge.net/\" rel=\"nofollow noreferrer\">im4java</a>. It is a very thin abstraction layer upon the command line interface, but does its job very well.</p>\n" }, { "answer_id": 4528136, "author": "Riyad Kalla", "author_id": 553524, "author_profile": "https://Stackoverflow.com/users/553524", "pm_score": 8, "selected": false, "text": "<p>FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called <a href=\"https://github.com/thebuzzmedia/imgscalr\" rel=\"noreferrer\">imgscalr</a> (available on <a href=\"http://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib\" rel=\"noreferrer\">Maven central</a>).</p>\n\n<p>The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).</p>\n\n<p>Usage is dead-simple, just a bunch of static methods. The simplest use-case is:</p>\n\n<pre><code>BufferedImage scaledImage = Scalr.resize(myImage, 200);\n</code></pre>\n\n<p>All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.</p>\n\n<p>I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).</p>\n" }, { "answer_id": 5051429, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://github.com/coobird/thumbnailator\">Thumbnailator</a> is an open-source image resizing library for Java with a fluent interface, distributed under the <a href=\"http://www.opensource.org/licenses/mit-license.php\">MIT license.</a></p>\n\n<p>I wrote this library because making high-quality thumbnails in Java can be surprisingly difficult, and the resulting code could be pretty messy. With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.</p>\n\n<p><strong>A simple example</strong></p>\n\n<p>For a simple example, taking a image and resizing it to 100 x 100 (preserving the aspect ratio of the original image), and saving it to an file can achieved in a single statement:</p>\n\n<pre><code>Thumbnails.of(\"path/to/image\")\n .size(100, 100)\n .toFile(\"path/to/thumbnail\");\n</code></pre>\n\n<p><strong>An advanced example</strong></p>\n\n<p>Performing complex resizing tasks is simplified with Thumbnailator's fluent interface.</p>\n\n<p>Let's suppose we want to do the following:</p>\n\n<ol>\n<li>take the images in a directory and,</li>\n<li>resize them to 100 x 100, with the aspect ratio of the original image,</li>\n<li>save them all to JPEGs with quality settings of <code>0.85</code>,</li>\n<li>where the file names are taken from the original with <code>thumbnail.</code> appended to the beginning</li>\n</ol>\n\n<p>Translated to Thumbnailator, we'd be able to perform the above with the following:</p>\n\n<pre><code>Thumbnails.of(new File(\"path/to/directory\").listFiles())\n .size(100, 100)\n .outputFormat(\"JPEG\")\n .outputQuality(0.85)\n .toFiles(Rename.PREFIX_DOT_THUMBNAIL);\n</code></pre>\n\n<p><strong>A note about image quality and speed</strong></p>\n\n<p>This library also uses the <em>progressive bilinear scaling</em> method highlighted in <a href=\"http://filthyrichclients.org/\">Filthy Rich Clients</a> by Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.</p>\n" }, { "answer_id": 5624935, "author": "kajo", "author_id": 332242, "author_profile": "https://Stackoverflow.com/users/332242", "pm_score": 2, "selected": false, "text": "<p>You could try to use <a href=\"http://www.graphicsmagick.org/\" rel=\"nofollow\">GraphicsMagick Image Processing System</a> with <a href=\"http://im4java.sourceforge.net/\" rel=\"nofollow\">im4java</a> as a comand-line interface for Java.</p>\n\n<p>There are a lot of advantages of GraphicsMagick, but one for all:</p>\n\n<ul>\n<li>GM is used to process billions of\nfiles at the world's largest photo\nsites (e.g. Flickr and Etsy).</li>\n</ul>\n" }, { "answer_id": 7287375, "author": "Jice", "author_id": 925751, "author_profile": "https://Stackoverflow.com/users/925751", "pm_score": 1, "selected": false, "text": "<p>Image Magick has been mentioned. There is a JNI front end project called JMagick. It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility). That said, we've had good experience using JMagick and a compatible version of Image Magick in a production environment to perform scaling at a high throughput, low latency rate. Speed was substantially better then with an all Java graphics library that we previously tried.</p>\n\n<p><a href=\"http://www.jmagick.org/index.html\" rel=\"nofollow\">http://www.jmagick.org/index.html</a></p>\n" }, { "answer_id": 9453681, "author": "Rohit Tiwari", "author_id": 1232688, "author_profile": "https://Stackoverflow.com/users/1232688", "pm_score": 0, "selected": false, "text": "<p>I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.<br>\nYou can download the jgifcode jar and run the GifImageUtil class.\nLink: <a href=\"http://www.jgifcode.com\" rel=\"nofollow\">http://www.jgifcode.com</a></p>\n" }, { "answer_id": 9660714, "author": "Robert", "author_id": 1263113, "author_profile": "https://Stackoverflow.com/users/1263113", "pm_score": 1, "selected": false, "text": "<p>You can use Marvin (pure Java image processing framework) for this kind of operation:\n <a href=\"http://marvinproject.sourceforge.net\" rel=\"nofollow noreferrer\">http://marvinproject.sourceforge.net</a></p>\n\n<p>Scale plug-in:\n<a href=\"http://marvinproject.sourceforge.net/en/plugins/scale.html\" rel=\"nofollow noreferrer\">http://marvinproject.sourceforge.net/en/plugins/scale.html</a></p>\n" }, { "answer_id": 16076530, "author": "Ruju", "author_id": 1425564, "author_profile": "https://Stackoverflow.com/users/1425564", "pm_score": 2, "selected": false, "text": "<p>The Java API does not provide a standard scaling feature for images and downgrading image quality.</p>\n\n<p>Because of this I tried to use cvResize from JavaCV but it seems to cause problems.</p>\n\n<p>I found a good library for image scaling: simply add the dependency for \"java-image-scaling\" in your pom.xml. </p>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;com.mortennobel&lt;/groupId&gt;\n &lt;artifactId&gt;java-image-scaling&lt;/artifactId&gt;\n &lt;version&gt;0.8.6&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n\n<p>In the maven repository you will get the recent version for this.</p>\n\n<p>Ex. In your java program</p>\n\n<pre><code>ResampleOp resamOp = new ResampleOp(50, 40);\nBufferedImage modifiedImage = resamOp.filter(originalBufferedImage, null);\n</code></pre>\n" }, { "answer_id": 27289135, "author": "gstackoverflow", "author_id": 2674303, "author_profile": "https://Stackoverflow.com/users/2674303", "pm_score": 0, "selected": false, "text": "<p>you can use following popular product: <a href=\"https://code.google.com/p/thumbnailator/\" rel=\"nofollow\">thumbnailator</a></p>\n" }, { "answer_id": 37228567, "author": "shareef", "author_id": 944593, "author_profile": "https://Stackoverflow.com/users/944593", "pm_score": 0, "selected": false, "text": "<p>If you dont want to import <a href=\"https://github.com/thebuzzmedia/imgscalr\" rel=\"nofollow noreferrer\">imgScalr</a> like @Riyad Kalla answer above which i tested too works fine, you can do this \ntaken from <a href=\"https://stackoverflow.com/questions/19654017/resizing-bufferedimages-and-storing-them-to-file-results-in-black-background-for\">Peter Walser answer</a> @Peter Walser on another issue though:</p>\n\n<pre><code> /**\n * utility method to get an icon from the resources of this class\n * @param name the name of the icon\n * @return the icon, or null if the icon wasn't found.\n */\n public Icon getIcon(String name) {\n Icon icon = null;\n URL url = null;\n ImageIcon imgicon = null;\n BufferedImage scaledImage = null;\n try {\n url = getClass().getResource(name);\n\n icon = new ImageIcon(url);\n if (icon == null) {\n System.out.println(\"Couldn't find \" + url);\n }\n\n BufferedImage bi = new BufferedImage(\n icon.getIconWidth(),\n icon.getIconHeight(),\n BufferedImage.TYPE_INT_RGB);\n Graphics g = bi.createGraphics();\n // paint the Icon to the BufferedImage.\n icon.paintIcon(null, g, 0,0);\n g.dispose();\n\n bi = resizeImage(bi,30,30);\n scaledImage = bi;// or replace with this line Scalr.resize(bi, 30,30);\n imgicon = new ImageIcon(scaledImage);\n\n } catch (Exception e) {\n System.out.println(\"Couldn't find \" + getClass().getName() + \"/\" + name);\n e.printStackTrace();\n }\n return imgicon;\n }\n\n public static BufferedImage resizeImage (BufferedImage image, int areaWidth, int areaHeight) {\n float scaleX = (float) areaWidth / image.getWidth();\n float scaleY = (float) areaHeight / image.getHeight();\n float scale = Math.min(scaleX, scaleY);\n int w = Math.round(image.getWidth() * scale);\n int h = Math.round(image.getHeight() * scale);\n\n int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;\n\n boolean scaleDown = scale &lt; 1;\n\n if (scaleDown) {\n // multi-pass bilinear div 2\n int currentW = image.getWidth();\n int currentH = image.getHeight();\n BufferedImage resized = image;\n while (currentW &gt; w || currentH &gt; h) {\n currentW = Math.max(w, currentW / 2);\n currentH = Math.max(h, currentH / 2);\n\n BufferedImage temp = new BufferedImage(currentW, currentH, type);\n Graphics2D g2 = temp.createGraphics();\n g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2.drawImage(resized, 0, 0, currentW, currentH, null);\n g2.dispose();\n resized = temp;\n }\n return resized;\n } else {\n Object hint = scale &gt; 2 ? RenderingHints.VALUE_INTERPOLATION_BICUBIC : RenderingHints.VALUE_INTERPOLATION_BILINEAR;\n\n BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = resized.createGraphics();\n g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);\n g2.drawImage(image, 0, 0, w, h, null);\n g2.dispose();\n return resized;\n }\n }\n</code></pre>\n" }, { "answer_id": 38775238, "author": "The One True Colter", "author_id": 6669464, "author_profile": "https://Stackoverflow.com/users/6669464", "pm_score": 1, "selected": false, "text": "<p>Simply use Burkhard's answer but add this line after creating the graphics:</p>\n\n<pre><code> g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n</code></pre>\n\n<p>You could also set the value to BICUBIC, it will produce a better quality image but is a more expensive operation. There are other rendering hints you can set but I have found that interpolation produces the most notable effect.\nKeep in mind if you want to zoom in in a lot, java code most likely will be very slow. I find larger images start to produce lag around 300% zoom even with all rendering hints set to optimize for speed over quality.</p>\n" }, { "answer_id": 48265426, "author": "aanno", "author_id": 1201611, "author_profile": "https://Stackoverflow.com/users/1201611", "pm_score": 1, "selected": false, "text": "<p>It turns out that writing a performant scaler is not trivial. I did it once for an open source project: <a href=\"https://bitbucket.org/nuclos/nuclos/src/4744685e632dfdac79e3fd4a11a077a01654e9db/nuclos-client/src/main/java/org/nuclos/client/image/ImageScaler.java?at=master&amp;fileviewer=file-view-default\" rel=\"nofollow noreferrer\" title=\"ImageScaler\">ImageScaler</a>.</p>\n\n<p>In principle 'java.awt.Image#getScaledInstance(int, int, int)' would do the job as well, but there is a nasty bug with this - refer to my link for details.</p>\n" }, { "answer_id": 59348618, "author": "Fridjato Part Fridjat", "author_id": 12087120, "author_profile": "https://Stackoverflow.com/users/12087120", "pm_score": 0, "selected": false, "text": "<p>Try this folowing method : </p>\n\n<pre><code>ImageIcon icon = new ImageIcon(\"image.png\");\nImage img = icon.getImage();\nImage newImg = img.getScaledInstance(350, 350, java.evt.Image.SCALE_SMOOTH);\nicon = new ImageIcon(img);\nJOptionPane.showMessageDialog(null, \"image on The frame\", \"Display Image\", JOptionPane.INFORMATION_MESSAGE, icon);\n</code></pre>\n" }, { "answer_id": 71508153, "author": "Aqib Butt", "author_id": 2369244, "author_profile": "https://Stackoverflow.com/users/2369244", "pm_score": 0, "selected": false, "text": "<p>you can also use</p>\n<pre><code>Process p = Runtime.getRuntime().exec(&quot;convert &quot; + origPath + &quot; -resize 75% -quality 70 &quot; + largePath + &quot;&quot;);\n p.waitFor();\n</code></pre>\n" }, { "answer_id": 73666348, "author": "Ruwan Pathirana", "author_id": 19273724, "author_profile": "https://Stackoverflow.com/users/19273724", "pm_score": 0, "selected": false, "text": "<p>Design jLabel first:</p>\n<pre><code>JLabel label1 = new JLabel(&quot;&quot;);\nlabel1.setHorizontalAlignment(SwingConstants.CENTER);\nlabel1.setBounds(628, 28, 169, 125);\nframe1.getContentPane().add(label1); //frame1 = &quot;Jframe name&quot;\n</code></pre>\n<p>Then you can code below code(add your own height and width):</p>\n<pre><code>ImageIcon imageIcon1 = new ImageIcon(new ImageIcon(&quot;add location url&quot;).getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); //100, 100 add your own size\nlabel1.setIcon(imageIcon1);\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011/" ]
I need to resize PNG, JPEG and GIF files. How can I do this using Java?
After loading the image you can try: ``` BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) { System.out.println("resizing..."); int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType); Graphics2D g = scaledBI.createGraphics(); if (preserveAlpha) { g.setComposite(AlphaComposite.Src); } g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); g.dispose(); return scaledBI; } ```
244,181
<p>I'm trying to use the VssGet task of the MSBuild Community Tasks, and the error message "File or project not found" is beating me with a stick. I can't figure out what in particular the error message is referring to. Here's the task:</p> <pre><code>&lt;LocalFilePath Include="C:\Documents and Settings\michaelc\My Documents\Visual Studio 2005\Projects\Astronom\Astronom.sln" /&gt; &lt;VssGet DatabasePath="\\ofmapoly003\Individual\michaelc\VSS\Astronom_VSS\srcsafe.ini" Path="$/Astronom_VSS" LocalPath="@(LocalFilePath)" UserName="build" Password="build" Recursive="True" /&gt; </code></pre> <p>If I write a Streamreader to read to either the database path or the local path, it succeeds fine. So the path to everything appears to be accessible. Any ideas?</p>
[ { "answer_id": 244250, "author": "dpurrington", "author_id": 5573, "author_profile": "https://Stackoverflow.com/users/5573", "pm_score": 3, "selected": true, "text": "<p>Two thoughts. One, sometimes a type load exception manifests as a FNF - let's hope that's not it. But if the code is actually being honest, you can track the problem using <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Procmon</a> or <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">Filemon</a>. Start one of those utilities and then run your task again. You should be able to track down a record of a file that couldn't be located.</p>\n" }, { "answer_id": 244906, "author": "Cyberherbalist", "author_id": 16964, "author_profile": "https://Stackoverflow.com/users/16964", "pm_score": 0, "selected": false, "text": "<p>@famoushamsandwich that's a great response -- I had not previously heard of procmon or filemon. Tried procmon on the problem, but even after sifting through the relevant output (my gosh the machine does a lot more stuff behind the screen than I was aware of) I couldn't find where a file I'm referencing wasn't being found. </p>\n" }, { "answer_id": 247324, "author": "Pedro", "author_id": 13188, "author_profile": "https://Stackoverflow.com/users/13188", "pm_score": 0, "selected": false, "text": "<p>Procmon and Filemon are good suggestions - just make sure you filter the results to only show errors. Otherwise the success messages will bury the problem entries. Also, you can filter out processes that are not at fault (either through the filter dialog or by right-clicking the entry and choosing \"Exclude Process\".)</p>\n\n<p>A couple other thoughts:</p>\n\n<ul>\n<li>In the LocalFilePath, you are specifying a single file as opposed to a folder. The task, on the other hand, specifies to get files recursively. Perhaps you need to remove \"\\Astronom.sln\" from the LocalFilePath?</li>\n<li>Is the build task being run under your account or another? It's possible you have a permissions issue</li>\n<li>Do you already have a copy of the code pulled down in the same location? Perhaps there is a failure to overwrite an existing file/folder?</li>\n</ul>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16964/" ]
I'm trying to use the VssGet task of the MSBuild Community Tasks, and the error message "File or project not found" is beating me with a stick. I can't figure out what in particular the error message is referring to. Here's the task: ``` <LocalFilePath Include="C:\Documents and Settings\michaelc\My Documents\Visual Studio 2005\Projects\Astronom\Astronom.sln" /> <VssGet DatabasePath="\\ofmapoly003\Individual\michaelc\VSS\Astronom_VSS\srcsafe.ini" Path="$/Astronom_VSS" LocalPath="@(LocalFilePath)" UserName="build" Password="build" Recursive="True" /> ``` If I write a Streamreader to read to either the database path or the local path, it succeeds fine. So the path to everything appears to be accessible. Any ideas?
Two thoughts. One, sometimes a type load exception manifests as a FNF - let's hope that's not it. But if the code is actually being honest, you can track the problem using [Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) or [Filemon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx). Start one of those utilities and then run your task again. You should be able to track down a record of a file that couldn't be located.
244,183
<p>I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads. </p> <p>I have no idea how to achieve this, but I do have the animated gif I want to use. </p> <p>Any suggestions?</p>
[ { "answer_id": 244190, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 6, "selected": true, "text": "<p>Typically sites that do this by loading content via ajax and listening to the <code>readystatechanged</code> event to update the DOM with a loading GIF or the content.</p>\n\n<p>How are you currently loading your content?</p>\n\n<p>The code would be similar to this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function load(url) {\n // display loading image here...\n document.getElementById('loadingImg').visible = true;\n // request your data...\n var req = new XMLHttpRequest();\n req.open(\"POST\", url, true);\n\n req.onreadystatechange = function () {\n if (req.readyState == 4 &amp;&amp; req.status == 200) {\n // content is loaded...hide the gif and display the content...\n if (req.responseText) {\n document.getElementById('content').innerHTML = req.responseText;\n document.getElementById('loadingImg').visible = false;\n }\n }\n };\n request.send(vars);\n}\n</code></pre>\n\n<p>There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.</p>\n" }, { "answer_id": 4100608, "author": "Mike E.", "author_id": 332044, "author_profile": "https://Stackoverflow.com/users/332044", "pm_score": 4, "selected": false, "text": "<p>You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire <code>&lt;body&gt;</code> to load. It goes something like this:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;style media=\"screen\" type=\"text/css\"&gt;\n .layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }\n .layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }\n &lt;/style&gt;\n &lt;script&gt;\n function downLoad(){\n if (document.all){\n document.all[\"layer1\"].style.visibility=\"hidden\";\n document.all[\"layer2\"].style.visibility=\"visible\";\n } else if (document.getElementById){\n node = document.getElementById(\"layer1\").style.visibility='hidden';\n node = document.getElementById(\"layer2\").style.visibility='visible';\n }\n }\n &lt;/script&gt;\n &lt;/head&gt;\n &lt;body onload=\"downLoad()\"&gt;\n &lt;div id=\"layer1\" class=\"layer1_class\"&gt;\n &lt;table width=\"100%\"&gt;\n &lt;tr&gt;\n &lt;td align=\"center\"&gt;&lt;strong&gt;&lt;em&gt;Please wait while this page is loading...&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;/div&gt;\n &lt;div id=\"layer2\" class=\"layer2_class\"&gt;\n &lt;script type=\"text/javascript\"&gt;\n alert('Just holding things up here. While you are reading this, the body of the page is not loading and the onload event is being delayed');\n &lt;/script&gt;\n Final content. \n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>The onload event won't fire until all of the page has loaded. So the layer2 <code>&lt;DIV&gt;</code> won't be displayed until the page has finished loading, after which onload will fire.</p>\n" }, { "answer_id": 11255697, "author": "Johnz", "author_id": 1490205, "author_profile": "https://Stackoverflow.com/users/1490205", "pm_score": 1, "selected": false, "text": "<p>There's actually a pretty easy way to do this. The code should be something like:</p>\n\n<pre><code>&lt;script type=\"test/javascript\"&gt;\n\n function showcontent(x){\n\n if(window.XMLHttpRequest) {\n xmlhttp = new XMLHttpRequest();\n } else {\n xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');\n }\n\n xmlhttp.onreadystatechange = function() {\n if(xmlhttp.readyState == 1) {\n document.getElementById('content').innerHTML = \"&lt;img src='loading.gif' /&gt;\";\n }\n if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {\n document.getElementById('content').innerHTML = xmlhttp.responseText;\n } \n }\n\n xmlhttp.open('POST', x+'.html', true);\n xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');\n xmlhttp.send(null);\n\n }\n</code></pre>\n\n<p>And in the HTML:</p>\n\n<pre><code>&lt;body onload=\"showcontent(main)\"&gt; &lt;!-- onload optional --&gt;\n&lt;div id=\"content\"&gt;&lt;img src=\"loading.gif\"&gt;&lt;/div&gt; &lt;!-- leave img out if not onload --&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>I did something like that on my page and it works great.</p>\n" }, { "answer_id": 21005907, "author": "Raj Nandan Sharma", "author_id": 3090583, "author_profile": "https://Stackoverflow.com/users/3090583", "pm_score": 0, "selected": false, "text": "<p>You can use <code>&lt;progress&gt;</code> element in HTML5. See this page for source code and live demo. <a href=\"http://purpledesign.in/blog/super-cool-loading-bar-html5/\" rel=\"nofollow\">http://purpledesign.in/blog/super-cool-loading-bar-html5/</a></p>\n\n<p>here is the progress element...</p>\n\n<pre><code>&lt;progress id=\"progressbar\" value=\"20\" max=\"100\"&gt;&lt;/progress&gt;\n</code></pre>\n\n<p>this will have the loading value starting from 20. Of course only the element wont suffice. You need to move it as the script loads. For that we need JQuery. Here is a simple JQuery script that starts the progress from 0 to 100 and does something in defined time slot.</p>\n\n<pre><code>&lt;script&gt;\n $(document).ready(function() {\n if(!Modernizr.meter){\n alert('Sorry your brower does not support HTML5 progress bar');\n } else {\n var progressbar = $('#progressbar'),\n max = progressbar.attr('max'),\n time = (1000/max)*10, \n value = progressbar.val();\n var loading = function() {\n value += 1;\n addValue = progressbar.val(value);\n $('.progress-value').html(value + '%');\n if (value == max) {\n clearInterval(animate);\n //Do Something\n }\nif (value == 16) {\n//Do something \n}\nif (value == 38) {\n//Do something\n}\nif (value == 55) {\n//Do something \n}\nif (value == 72) {\n//Do something \n}\nif (value == 1) {\n//Do something \n}\nif (value == 86) {\n//Do something \n }\n\n};\nvar animate = setInterval(function() {\nloading();\n}, time);\n};\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>Add this to your HTML file.</p>\n\n<pre><code>&lt;div class=\"demo-wrapper html5-progress-bar\"&gt;\n&lt;div class=\"progress-bar-wrapper\"&gt;\n &lt;progress id=\"progressbar\" value=\"0\" max=\"100\"&gt;&lt;/progress&gt;\n &lt;span class=\"progress-value\"&gt;0%&lt;/span&gt;\n&lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Hope this will give you a start.</p>\n" }, { "answer_id": 27340661, "author": "joe_young", "author_id": 4206206, "author_profile": "https://Stackoverflow.com/users/4206206", "pm_score": 3, "selected": false, "text": "<p>How about with jQuery? A simple...</p>\n\n<pre><code>$(window).load(function() { //Do the code in the {}s when the window has loaded \n $(\"#loader\").fadeOut(\"fast\"); //Fade out the #loader div\n});\n</code></pre>\n\n<p><strong>And the HTML...</strong></p>\n\n<pre><code>&lt;div id=\"loader\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p><strong>And CSS...</strong></p>\n\n<pre><code>#loader {\n width: 100%;\n height: 100%;\n background-color: white;\n margin: 0;\n}\n</code></pre>\n\n<p>Then in your loader <code>div</code> you would put the GIF, and any text you wanted, and it will fade out once the page has loaded.</p>\n" }, { "answer_id": 34551921, "author": "Peach", "author_id": 5734986, "author_profile": "https://Stackoverflow.com/users/5734986", "pm_score": 2, "selected": false, "text": "<p>First, set up a loading image in a div. Next, get the div element. Then, set a function that edits the css to make the visibility to \"hidden\". Now, in the <code>&lt;body&gt;</code>, put the onload to the function name.</p>\n" }, { "answer_id": 36768317, "author": "MindCraftMagic", "author_id": 5993161, "author_profile": "https://Stackoverflow.com/users/5993161", "pm_score": 2, "selected": false, "text": "<p><strong>#Pure css method</strong></p>\n\n<blockquote>\n <p>Place this at the top of your code (before header tag)</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>&lt;style&gt; .loader {\r\n position: fixed;\r\n background-color: #FFF;\r\n opacity: 1;\r\n height: 100%;\r\n width: 100%;\r\n top: 0;\r\n left: 0;\r\n z-index: 10;\r\n}\r\n&lt;/style&gt;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"loader\"&gt;\r\n Your Content For Load Screen\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>And This At The Bottom after all other code (except /html tag)</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>&lt;style&gt;\r\n.loader {\r\n -webkit-animation: load-out 1s;\r\n animation: load-out 1s;\r\n -webkit-animation-fill-mode: forwards;\r\n animation-fill-mode: forwards;\r\n}\r\n\r\n@-webkit-keyframes load-out {\r\n from {\r\n top: 0;\r\n opacity: 1;\r\n }\r\n\r\n to {\r\n top: 100%;\r\n opacity: 0;\r\n }\r\n}\r\n\r\n@keyframes load-out {\r\n from {\r\n top: 0;\r\n opacity: 1;\r\n }\r\n\r\n to {\r\n top: 100%;\r\n opacity: 0;\r\n }\r\n}\r\n&lt;/style&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <blockquote>\n <p>This always works for me 100% of the time</p>\n </blockquote>\n</blockquote>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27171/" ]
I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads. I have no idea how to achieve this, but I do have the animated gif I want to use. Any suggestions?
Typically sites that do this by loading content via ajax and listening to the `readystatechanged` event to update the DOM with a loading GIF or the content. How are you currently loading your content? The code would be similar to this: ```js function load(url) { // display loading image here... document.getElementById('loadingImg').visible = true; // request your data... var req = new XMLHttpRequest(); req.open("POST", url, true); req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { // content is loaded...hide the gif and display the content... if (req.responseText) { document.getElementById('content').innerHTML = req.responseText; document.getElementById('loadingImg').visible = false; } } }; request.send(vars); } ``` There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.
244,191
<p>For example:</p> <pre><code>public void doSomething() { final double MIN_INTEREST = 0.0; // ... } </code></pre> <p>Personally, I would rather see these substitution constants declared statically at the class level. I suppose I'm looking for an "industry viewpoint" on the matter.</p>
[ { "answer_id": 244213, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 5, "selected": false, "text": "<p>I would think that you should only put them at the class level if they are used by multiple methods. If it is only used in that method then that looks fine to me.</p>\n" }, { "answer_id": 244215, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": -1, "selected": false, "text": "<p>The reason why you can define a final variable at a class level or method (local) level it's because you can override the global static constant inside the (local) method. </p>\n\n<p>Example: </p>\n\n<pre><code>public class Test {\n\n final double MIN_INTEREST = 0.0;\n\n /**\n * @param args\n */\n public static void main(String[] args) {\n\n\n Test test = new Test();\n\n test.doSomethingLocal();\n test.doSomethingGlobal();\n\n }\n\n public void doSomethingGlobal() {\n\n System.out.println(\"Global-&gt; \" + MIN_INTEREST);\n\n }\n\n public void doSomethingLocal() {\n\n final double MIN_INTEREST = 0.1;\n\n System.out.println(\"Local-&gt; \" + MIN_INTEREST);\n\n }\n}\n</code></pre>\n\n<p>The output will be:</p>\n\n<pre><code>Local-&gt; 0.1\nGlobal-&gt; 0.0\n</code></pre>\n\n<p>So your question doesn't make any sense.</p>\n" }, { "answer_id": 244279, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 3, "selected": false, "text": "<p>I've used this method scoped constants myself but every so often a colleague will down mod it during code reviews. Again, these colleagues are not into reading/writing open source but they are used to enterprise software.</p>\n\n<p>I tell them that it does NOT make sense to use a class level constant if it is used within a single method but I've found more than 1 colleague insisting that it be moved UP.\nI usually comply since I'm not so rigid unless it affects readability and/or performance.</p>\n" }, { "answer_id": 244315, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 5, "selected": true, "text": "<p>My starting position is that every variable or constant should be declared/initialized as close to its first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different.</p>\n<p>For example, a method scoped final won't be visible in the public API. Sometimes this bit of information could be quite useful to the users of your class, and should be moved up.</p>\n<p>In the example you gave in the question, I would say that <code>MIN_INTEREST</code> is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method. (Although, there is no context to the example code, and my assumption could be completely wrong.)</p>\n" }, { "answer_id": 244374, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 2, "selected": false, "text": "<p>Information hiding and modularity are key principles, and narrow scoping is better information hiding. If the constant is only needed by the method, the hiding is good. If and when the constant is useful elsewhere, bring it out to a broader scope, but only as broadly as needed. </p>\n\n<p>You are probably concerned because this is a constant, and therefore, it may seem to belong to some global properties table. Maybe it does. Maybe it doesn't. Your concern is valid, but there is no one best place for all constants. </p>\n" }, { "answer_id": 271033, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Technically, there is no such thing as a \"method scoped constant\" in Java. What you are referring to is simply a final local variable; it is created an destroyed with each method invocation.</p>\n\n<p><a href=\"http://www.java-tips.org/java-se-tips/java.lang/how-do-i-declare-a-constant-in-java.html\" rel=\"noreferrer\">http://www.java-tips.org/java-se-tips/java.lang/how-do-i-declare-a-constant-in-java.html</a></p>\n" }, { "answer_id": 42460729, "author": "Gautam", "author_id": 5971511, "author_profile": "https://Stackoverflow.com/users/5971511", "pm_score": 1, "selected": false, "text": "<p>I have a different take on this: IMHO its better to place them at file/class scope especially if you are working in teams for this reason: say you start with a small piece of code...</p>\n\n<pre><code>public void doSomething() {\n\n final double MIN_INTEREST = 0.0;\n\n // ... \n}\n</code></pre>\n\n<p>and other members of you team expand the class with whole bunch of methods and now the class is a wonderful <code>500 lines</code>/<code>50 methods</code> giant class. Imagine the experience of an engineer who is trying to adding a new method with a constant, they will have to <code>1</code> scan the whole class looking for constants that match their need, <code>2</code> move the constant to class scope hoping that there are no conflicts with existing code and <code>3</code> also add their method.</p>\n\n<p>If you instead add all constants at file/class scope to begin with, engineers have a <code>1</code> single place to look for existing constants and, <code>2</code> derive some constants from others where it makes sense. (for example if you have a constant for <code>pi</code> you may also want to define a new constant with a value of <code>pi/2</code>).</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32142/" ]
For example: ``` public void doSomething() { final double MIN_INTEREST = 0.0; // ... } ``` Personally, I would rather see these substitution constants declared statically at the class level. I suppose I'm looking for an "industry viewpoint" on the matter.
My starting position is that every variable or constant should be declared/initialized as close to its first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different. For example, a method scoped final won't be visible in the public API. Sometimes this bit of information could be quite useful to the users of your class, and should be moved up. In the example you gave in the question, I would say that `MIN_INTEREST` is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method. (Although, there is no context to the example code, and my assumption could be completely wrong.)
244,192
<p>I have a pattern to match with the string: string pattern = @"asc" I am checking the SQL SELECT query for right syntax, semantics, ... I need to say that in the end of the query string I can have "asc" or "desc". How can it be written in C#?</p>
[ { "answer_id": 244201, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>You want the \"alternation\" operator, which is the pipe.</p>\n\n<p>For instance, I believe this would be represented as:</p>\n\n<pre><code>asc|desc\n</code></pre>\n\n<p>If you want to make it a non-capturing group you can do it in the normal way. I'm not a regex expert, but that's the first thing to try.</p>\n\n<p>EDIT: MSDN has a page about <a href=\"http://msdn.microsoft.com/en-us/library/az24scfc.aspx\" rel=\"nofollow noreferrer\">regular expression language elements</a> which may help you.</p>\n" }, { "answer_id": 244203, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 3, "selected": true, "text": "<p>That'd look like </p>\n\n<pre><code>new Regex(\"asc$|desc$\").IsMatch(yourQuery)\n</code></pre>\n\n<p>assuming that you're mandating that asc/desc is the end of the query. You could also do <code>(?:asc|desc)$</code> which is a little cleaner with the single <code>$</code>, but less readable.</p>\n" }, { "answer_id": 244216, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 1, "selected": false, "text": "<p>Just to add to the other answers, you probably wanna apply an ignore case option to the regex as well. </p>\n\n<pre><code>string tempString = \"SELECT * FROM MyTable ORDER BY column DESC\";\n\nRegex r = new Regex(\"asc$|desc$\", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n\nbool answer = r.IsMatch(tempString);\n</code></pre>\n" }, { "answer_id": 244229, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 0, "selected": false, "text": "<p>I reckon something like the following works as a regex in .Net:</p>\n\n<pre><code>asc|desc\\z\n</code></pre>\n\n<p>.. it will match end of line as well as end of string. If you just want end of string try:</p>\n\n<pre><code>asc|desc$\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
I have a pattern to match with the string: string pattern = @"asc" I am checking the SQL SELECT query for right syntax, semantics, ... I need to say that in the end of the query string I can have "asc" or "desc". How can it be written in C#?
That'd look like ``` new Regex("asc$|desc$").IsMatch(yourQuery) ``` assuming that you're mandating that asc/desc is the end of the query. You could also do `(?:asc|desc)$` which is a little cleaner with the single `$`, but less readable.
244,208
<p>I'm using MySQL 5.0.45 on CentOS 5.1.</p> <p><code>SELECT DISTINCT(email) FROM newsletter</code></p> <p>Returns 217259 rows</p> <p><code>SELECT COUNT(DISTINCT(email)) FROM newsletter</code></p> <p>Returns 180698 for the count.</p> <p><code>SELECT COUNT(*) FROM (SELECT DISTINCT(email) FROM newsletter) AS foo</code></p> <p>Returns 180698 for the count.</p> <p>Shouldn't all 3 queries return the same value?</p> <p>Here is the schema of the newsletter table</p> <pre> CREATE TABLE `newsletter` ( `newsID` int(11) NOT NULL auto_increment, `email` varchar(128) NOT NULL default '', `newsletter` varchar(8) NOT NULL default '', PRIMARY KEY (`newsID`) ) ENGINE=MyISAM; </pre> <p><strong>Update:</strong> I've found that if I add a <codE>WHERE</code> clause to the first query then I get the correct results. The <codE>WHERE</code> clause is such that it will not effect the results.</p> <p><code>SELECT DISTINCT(email) FROM newsletter WHERE newsID > 0</code></p>
[ { "answer_id": 244225, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "<p>could you possibly intersect the differing results to see what the extra rows are?</p>\n" }, { "answer_id": 244262, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>In the first case, what happens if you change it to \"<code>select distinct(email) from newsletter order by email;</code>\" I don't think it should make a difference, but it might.</p>\n" }, { "answer_id": 244435, "author": "Maglob", "author_id": 27520, "author_profile": "https://Stackoverflow.com/users/27520", "pm_score": 2, "selected": false, "text": "<p>My guess is that there are some null values in email column. Try</p>\n\n<pre><code>select count(*) from newsletter where email is null;\n</code></pre>\n" }, { "answer_id": 244454, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 0, "selected": false, "text": "<p>Yes, as Maglob <a href=\"https://stackoverflow.com/questions/244208/mysql-countdistinct-unexpected-results#244435\">said</a> you may be getting some NULLs in your email column. Try with something like:</p>\n\n<pre><code>SELECT COUNT(COALESCE(email, 0)) FROM newsletter\n</code></pre>\n\n<p>That would give you the results you expect. Oh, wait. The definition says that email does not accept NULL values. If that is truly the case, then it is odd.</p>\n" }, { "answer_id": 244472, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "<p>One possible explanation is that rows were deleted from the table between your two queries. But I assume you've run these multiple times in various orders so I doubt that's it.</p>\n\n<p>What rowcount do you get from this query:</p>\n\n<pre><code>SELECT email FROM newsletter GROUP BY email;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
I'm using MySQL 5.0.45 on CentOS 5.1. `SELECT DISTINCT(email) FROM newsletter` Returns 217259 rows `SELECT COUNT(DISTINCT(email)) FROM newsletter` Returns 180698 for the count. `SELECT COUNT(*) FROM (SELECT DISTINCT(email) FROM newsletter) AS foo` Returns 180698 for the count. Shouldn't all 3 queries return the same value? Here is the schema of the newsletter table ``` CREATE TABLE `newsletter` ( `newsID` int(11) NOT NULL auto_increment, `email` varchar(128) NOT NULL default '', `newsletter` varchar(8) NOT NULL default '', PRIMARY KEY (`newsID`) ) ENGINE=MyISAM; ``` **Update:** I've found that if I add a `WHERE` clause to the first query then I get the correct results. The `WHERE` clause is such that it will not effect the results. `SELECT DISTINCT(email) FROM newsletter WHERE newsID > 0`
could you possibly intersect the differing results to see what the extra rows are?
244,219
<p>In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing, </p> <pre><code>docs.Sort((x, y) =&gt; x.StoredDate.CompareTo(y.StoredDate)); docs.Reverse(); </code></pre> <p>but is there a lambda expression to do it one step?</p> <p>In the above example, StoredDate is a property typed as a DateTime.</p>
[ { "answer_id": 244221, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 4, "selected": false, "text": "<pre><code>docs.Sort((x, y) =&gt; y.StoredDate.CompareTo(x.StoredDate));\n</code></pre>\n\n<p>Should do what you're looking for.</p>\n" }, { "answer_id": 244227, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": false, "text": "<pre><code>docs.Sort((x, y) =&gt; -x.StoredDate.CompareTo(y.StoredDate));\n</code></pre>\n\n<p>Note the minus sign.</p>\n" }, { "answer_id": 244228, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 7, "selected": true, "text": "<p>Though it's untested...</p>\n\n<pre><code>docs.Sort((x, y) =&gt; y.StoredDate.CompareTo(x.StoredDate));\n</code></pre>\n\n<p>should be the opposite of what you originally had.</p>\n" }, { "answer_id": 8002567, "author": "Scott Baker", "author_id": 127888, "author_profile": "https://Stackoverflow.com/users/127888", "pm_score": 6, "selected": false, "text": "<p>What's wrong with: </p>\n\n<pre><code>docs.OrderByDescending(d =&gt; d.StoredDate);\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing, ``` docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate)); docs.Reverse(); ``` but is there a lambda expression to do it one step? In the above example, StoredDate is a property typed as a DateTime.
Though it's untested... ``` docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate)); ``` should be the opposite of what you originally had.
244,222
<p>I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX. I have a web service that provides data to the client. When the web service is called directly, it is properly compressed. However, when it is called via ASP.NET AJAX, the JSON response is not compressed.</p> <p>How can I get ASP.NET AJAX to send its JSON response with GZip compression?</p>
[ { "answer_id": 248963, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>What browser are you using? There's a bug in IE 6 that causes errors in compression. So ASP.NET AJAX turns off compression to IE 6 browsers:</p>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2005/06/28/416185.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2005/06/28/416185.aspx</a></p>\n\n<p>Also, did you enable compression for ASMX files?</p>\n" }, { "answer_id": 264331, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 0, "selected": false, "text": "<p>Last I checked, the gzipping was something that IIS does (when setup correctly) - and of course when the browser sends the required headers</p>\n" }, { "answer_id": 266753, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 3, "selected": false, "text": "<p>IIS7 uses the content-encoding to decide whether to compress the response (assuming of course that the browser can accept gzip). They're set in applicationHost.config, and by default the list is</p>\n\n<pre><code>&lt;dynamicTypes&gt;\n &lt;add mimeType=\"text/*\" enabled=\"true\" /&gt;\n &lt;add mimeType=\"message/*\" enabled=\"true\" /&gt;\n &lt;add mimeType=\"application/x-javascript\" enabled=\"true\" /&gt;\n &lt;add mimeType=\"*/*\" enabled=\"false\" /&gt;\n&lt;/dynamicTypes&gt;\n</code></pre>\n\n<p>If you call the web service directly, the XML response has a content-type of <code>text/xml</code>, which gets compressed. When called by AJAX, the JSON response has a content type of <code>application/json</code>, so it isn't compressed. Adding the following to applicationHost.config should fix that...</p>\n\n<pre><code> &lt;add mimeType=\"application/json\" enabled=\"true\" /&gt;\n</code></pre>\n" }, { "answer_id": 304680, "author": "Thomas Hansen", "author_id": 29746, "author_profile": "https://Stackoverflow.com/users/29746", "pm_score": 0, "selected": false, "text": "<p>In general you don't want to do this unless you wouldn't mind throwing orders of magnitudes the amount of server power into your apps...</p>\n\n<p>Also not only server-CPU but also client-CPU becomes a problem when you do this....</p>\n\n<p>This concludes with that your app becomes WAY slower if you GZip all your Ajax Responses...!</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX. I have a web service that provides data to the client. When the web service is called directly, it is properly compressed. However, when it is called via ASP.NET AJAX, the JSON response is not compressed. How can I get ASP.NET AJAX to send its JSON response with GZip compression?
IIS7 uses the content-encoding to decide whether to compress the response (assuming of course that the browser can accept gzip). They're set in applicationHost.config, and by default the list is ``` <dynamicTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/x-javascript" enabled="true" /> <add mimeType="*/*" enabled="false" /> </dynamicTypes> ``` If you call the web service directly, the XML response has a content-type of `text/xml`, which gets compressed. When called by AJAX, the JSON response has a content type of `application/json`, so it isn't compressed. Adding the following to applicationHost.config should fix that... ``` <add mimeType="application/json" enabled="true" /> ```
244,243
<p>I ran into the problem that my primary key sequence is not in sync with my table rows. </p> <p>That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.</p> <p>It seems to be caused by import/restores not maintaining the sequence properly.</p>
[ { "answer_id": 244251, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>Try <a href=\"http://www.postgresql.org/docs/7.3/static/sql-reindex.html\" rel=\"nofollow noreferrer\">reindex</a>.</p>\n\n<p>UPDATE: As pointed out in the comments, this was in reply to the original question.</p>\n" }, { "answer_id": 244265, "author": "meleyal", "author_id": 4196, "author_profile": "https://Stackoverflow.com/users/4196", "pm_score": 11, "selected": true, "text": "<pre><code>-- Login to psql and run the following\n\n-- What is the result?\nSELECT MAX(id) FROM your_table;\n\n-- Then run...\n-- This should be higher than the last result.\nSELECT nextval('your_table_id_seq');\n\n-- If it's not higher... run this set the sequence last to your highest id. \n-- (wise to run a quick pg_dump first...)\n\nBEGIN;\n-- protect against concurrent inserts while you update the counter\nLOCK TABLE your_table IN EXCLUSIVE MODE;\n-- Update the sequence\nSELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);\nCOMMIT;\n</code></pre>\n\n<p><a href=\"http://www.ruby-forum.com/topic/64428#72333\" rel=\"noreferrer\">Source - Ruby Forum</a></p>\n" }, { "answer_id": 355416, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p><strike>ALTER SEQUENCE sequence_name RESTART WITH (SELECT max(id) FROM table_name);</strike>\nDoesn't work.</p>\n\n<p>Copied from @tardate answer:</p>\n\n<pre><code>SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;\n</code></pre>\n" }, { "answer_id": 3698777, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 8, "selected": false, "text": "<p><a href=\"http://www.postgresql.org/docs/9.4/static/functions-info.html\" rel=\"noreferrer\"><code>pg_get_serial_sequence</code></a> can be used to avoid any incorrect assumptions about the sequence name. This resets the sequence in one shot:</p>\n\n<pre><code>SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);\n</code></pre>\n\n<p>Or more concisely:</p>\n\n<pre><code>SELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;\n</code></pre>\n\n<p>However this form can't handle empty tables correctly, since max(id) is null, and neither can you setval 0 because it would be out of range of the sequence. One workaround for this is to resort to the <code>ALTER SEQUENCE</code> syntax i.e.</p>\n\n<pre><code>ALTER SEQUENCE table_name_id_seq RESTART WITH 1;\nALTER SEQUENCE table_name_id_seq RESTART; -- 8.4 or higher\n</code></pre>\n\n<p>But <code>ALTER SEQUENCE</code> is of limited use because the sequence name and restart value cannot be expressions.</p>\n\n<p>It seems the best all-purpose solution is to call <code>setval</code> with false as the 3rd parameter, allowing us to specify the \"next value to use\":</p>\n\n<pre><code>SELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n</code></pre>\n\n<p>This ticks all my boxes:</p>\n\n<ol>\n<li>avoids hard-coding the actual sequence name </li>\n<li>handles empty tables correctly </li>\n<li>handles tables with existing data, and does not leave a\nhole in the sequence</li>\n</ol>\n\n<p>Finally, note that <code>pg_get_serial_sequence</code> only works if the sequence is owned by the column. This will be the case if the incrementing column was defined as a <code>serial</code> type, however if the sequence was added manually it is necessary to ensure <code>ALTER SEQUENCE .. OWNED BY</code> is also performed. </p>\n\n<p>i.e. if <code>serial</code> type was used for table creation, this should all work:</p>\n\n<pre><code>CREATE TABLE t1 (\n id serial,\n name varchar(20)\n);\n\nSELECT pg_get_serial_sequence('t1', 'id'); -- returns 't1_id_seq'\n\n-- reset the sequence, regardless whether table has rows or not:\nSELECT setval(pg_get_serial_sequence('t1', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n</code></pre>\n\n<p>But if sequences were added manually:</p>\n\n<pre><code>CREATE TABLE t2 (\n id integer NOT NULL,\n name varchar(20)\n);\n\nCREATE SEQUENCE t2_custom_id_seq\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\nALTER TABLE t2 ALTER COLUMN id SET DEFAULT nextval('t2_custom_id_seq'::regclass);\n\nALTER SEQUENCE t2_custom_id_seq OWNED BY t2.id; -- required for pg_get_serial_sequence\n\nSELECT pg_get_serial_sequence('t2', 'id'); -- returns 't2_custom_id_seq'\n\n-- reset the sequence, regardless whether table has rows or not:\nSELECT setval(pg_get_serial_sequence('t2', 'id'), coalesce(max(id),0) + 1, false) FROM t1;\n</code></pre>\n" }, { "answer_id": 3786682, "author": "user457226", "author_id": 457226, "author_profile": "https://Stackoverflow.com/users/457226", "pm_score": 3, "selected": false, "text": "<p>Reset all sequence from public</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text) RETURNS \"pg_catalog\".\"void\" AS \n$body$ \n DECLARE \n BEGIN \n EXECUTE 'SELECT setval( ''' \n || tablename \n || '_id_seq'', ' \n || '(SELECT id + 1 FROM \"' \n || tablename \n || '\" ORDER BY id DESC LIMIT 1), false)'; \n END; \n$body$ LANGUAGE 'plpgsql';\n\nselect sequence_name, reset_sequence(split_part(sequence_name, '_id_seq',1)) from information_schema.sequences\n where sequence_schema='public';\n</code></pre>\n" }, { "answer_id": 4101362, "author": "David Snowsill", "author_id": 6218, "author_profile": "https://Stackoverflow.com/users/6218", "pm_score": 6, "selected": false, "text": "<p>This will reset all sequences from public making no assumptions about table or column names. Tested on version 8.4</p>\n<pre><code>CREATE OR REPLACE FUNCTION &quot;reset_sequence&quot; (tablename text, columnname text, sequence_name text) \n RETURNS &quot;pg_catalog&quot;.&quot;void&quot; AS \n \n $body$ \n DECLARE \n BEGIN \n \n EXECUTE 'SELECT setval( ''' || sequence_name || ''', ' || '(SELECT MAX(' || columnname || \n ') FROM ' || tablename || ')' || '+1)';\n \n END; \n \n $body$ LANGUAGE 'plpgsql';\n \n \nSELECT table_name || '_' || column_name || '_seq', \n reset_sequence(table_name, column_name, table_name || '_' || column_name || '_seq') \nFROM information_schema.columns where column_default like 'nextval%';\n</code></pre>\n" }, { "answer_id": 5252155, "author": "mauro", "author_id": 652407, "author_profile": "https://Stackoverflow.com/users/652407", "pm_score": 2, "selected": false, "text": "<p>The Klaus answer is the most useful, execpt for a little miss : you\nhave to add DISTINCT in select statement.</p>\n\n<p>However, if you are sure that no table+column names can be equivalent\nfor two different tables, you can also use :</p>\n\n<pre><code>select sequence_name, --PG_CLASS.relname, PG_ATTRIBUTE.attname\n reset_sequence(split_part(sequence_name, '_id_seq',1))\nfrom PG_CLASS\njoin PG_ATTRIBUTE on PG_ATTRIBUTE.attrelid = PG_CLASS.oid\njoin information_schema.sequences\n on information_schema.sequences.sequence_name = PG_CLASS.relname || '_' || PG_ATTRIBUTE.attname\nwhere sequence_schema='public';\n</code></pre>\n\n<p>which is an extension of user457226 solution for the case when\nsome interested column name is not 'ID'.</p>\n" }, { "answer_id": 5252617, "author": "mauro", "author_id": 652407, "author_profile": "https://Stackoverflow.com/users/652407", "pm_score": 2, "selected": false, "text": "<p>before I had not tried yet the code : in the following I post\nthe version for the sql-code for both Klaus and user457226 solutions\nwhich worked on my pc [Postgres 8.3], with just some little adjustements\nfor the Klaus one and of my version for the user457226 one.</p>\n\n<p>Klaus solution :</p>\n\n<pre><code>drop function IF EXISTS rebuilt_sequences() RESTRICT;\nCREATE OR REPLACE FUNCTION rebuilt_sequences() RETURNS integer as\n$body$\n DECLARE sequencedefs RECORD; c integer ;\n BEGIN\n FOR sequencedefs IN Select\n constraint_column_usage.table_name as tablename,\n constraint_column_usage.table_name as tablename, \n constraint_column_usage.column_name as columnname,\n replace(replace(columns.column_default,'''::regclass)',''),'nextval(''','') as sequencename\n from information_schema.constraint_column_usage, information_schema.columns\n where constraint_column_usage.table_schema ='public' AND \n columns.table_schema = 'public' AND columns.table_name=constraint_column_usage.table_name\n AND constraint_column_usage.column_name = columns.column_name\n AND columns.column_default is not null\n LOOP \n EXECUTE 'select max('||sequencedefs.columnname||') from ' || sequencedefs.tablename INTO c;\n IF c is null THEN c = 0; END IF;\n IF c is not null THEN c = c+ 1; END IF;\n EXECUTE 'alter sequence ' || sequencedefs.sequencename ||' restart with ' || c;\n END LOOP;\n\n RETURN 1; END;\n$body$ LANGUAGE plpgsql;\n\nselect rebuilt_sequences();\n</code></pre>\n\n<p>user457226 solution :</p>\n\n<pre><code>--drop function IF EXISTS reset_sequence (text,text) RESTRICT;\nCREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text,columnname text) RETURNS bigint --\"pg_catalog\".\"void\"\nAS\n$body$\n DECLARE seqname character varying;\n c integer;\n BEGIN\n select tablename || '_' || columnname || '_seq' into seqname;\n EXECUTE 'SELECT max(\"' || columnname || '\") FROM \"' || tablename || '\"' into c;\n if c is null then c = 0; end if;\n c = c+1; --because of substitution of setval with \"alter sequence\"\n --EXECUTE 'SELECT setval( \"' || seqname || '\", ' || cast(c as character varying) || ', false)'; DOES NOT WORK!!!\n EXECUTE 'alter sequence ' || seqname ||' restart with ' || cast(c as character varying);\n RETURN nextval(seqname)-1;\n END;\n$body$ LANGUAGE 'plpgsql';\n\nselect sequence_name, PG_CLASS.relname, PG_ATTRIBUTE.attname,\n reset_sequence(PG_CLASS.relname,PG_ATTRIBUTE.attname)\nfrom PG_CLASS\njoin PG_ATTRIBUTE on PG_ATTRIBUTE.attrelid = PG_CLASS.oid\njoin information_schema.sequences\n on information_schema.sequences.sequence_name = PG_CLASS.relname || '_' || PG_ATTRIBUTE.attname || '_seq'\nwhere sequence_schema='public';\n</code></pre>\n" }, { "answer_id": 5943183, "author": "alvherre", "author_id": 242383, "author_profile": "https://Stackoverflow.com/users/242383", "pm_score": 4, "selected": false, "text": "<p>These functions are fraught with perils when sequence names, column names, table names or schema names have funny characters such as spaces, punctuation marks, and the like. I have written this:</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION sequence_max_value(oid) RETURNS bigint\nVOLATILE STRICT LANGUAGE plpgsql AS $$\nDECLARE\n tabrelid oid;\n colname name;\n r record;\n newmax bigint;\nBEGIN\n FOR tabrelid, colname IN SELECT attrelid, attname\n FROM pg_attribute\n WHERE (attrelid, attnum) IN (\n SELECT adrelid::regclass,adnum\n FROM pg_attrdef\n WHERE oid IN (SELECT objid\n FROM pg_depend\n WHERE refobjid = $1\n AND classid = 'pg_attrdef'::regclass\n )\n ) LOOP\n FOR r IN EXECUTE 'SELECT max(' || quote_ident(colname) || ') FROM ' || tabrelid::regclass LOOP\n IF newmax IS NULL OR r.max &gt; newmax THEN\n newmax := r.max;\n END IF;\n END LOOP;\n END LOOP;\n RETURN newmax;\nEND; $$ ;\n</code></pre>\n\n<p>You can call it for a single sequence by passing it the OID and it will return the highest number used by any table that has the sequence as default; or you can run it with a query like this, to reset all the sequences in your database:</p>\n\n<pre><code> select relname, setval(oid, sequence_max_value(oid))\n from pg_class\n where relkind = 'S';\n</code></pre>\n\n<p>Using a different qual you can reset only the sequence in a certain schema, and so on. For example, if you want to adjust sequences in the \"public\" schema:</p>\n\n<pre><code>select relname, setval(pg_class.oid, sequence_max_value(pg_class.oid))\n from pg_class, pg_namespace\n where pg_class.relnamespace = pg_namespace.oid and\n nspname = 'public' and\n relkind = 'S';\n</code></pre>\n\n<p>Note that due to how setval() works, you don't need to add 1 to the result.</p>\n\n<p>As a closing note, I have to warn that some databases seem to have defaults linking to sequences in ways that do not let the system catalogs have full information of them. This happens when you see things like this in psql's \\d:</p>\n\n<pre><code>alvherre=# \\d baz\n Tabla «public.baz»\n Columna | Tipo | Modificadores \n---------+---------+------------------------------------------------\n a | integer | default nextval(('foo_a_seq'::text)::regclass)\n</code></pre>\n\n<p>Note that the nextval() call in that default clause has a ::text cast in addition to the ::regclass cast. I <em>think</em> this is due to databases being pg_dump'ed from old PostgreSQL versions. What will happen is that the function sequence_max_value() above will ignore such a table. To fix the problem, you can redefine the DEFAULT clause to refer to the sequence directly without the cast:</p>\n\n<pre><code>alvherre=# alter table baz alter a set default nextval('foo_a_seq');\nALTER TABLE\n</code></pre>\n\n<p>Then psql displays it properly:</p>\n\n<pre><code>alvherre=# \\d baz\n Tabla «public.baz»\n Columna | Tipo | Modificadores \n---------+---------+----------------------------------------\n a | integer | default nextval('foo_a_seq'::regclass)\n</code></pre>\n\n<p>As soon as you've fixed that, the function works correctly for this table as well as all others that might use the same sequence.</p>\n" }, { "answer_id": 7406591, "author": "Daniel Cristian Cruz", "author_id": 943169, "author_profile": "https://Stackoverflow.com/users/943169", "pm_score": 3, "selected": false, "text": "<p>My version use the first one, with some error checking...</p>\n\n<pre><code>BEGIN;\nCREATE OR REPLACE FUNCTION reset_sequence(_table_schema text, _tablename text, _columnname text, _sequence_name text)\nRETURNS pg_catalog.void AS\n$BODY$\nDECLARE\nBEGIN\n PERFORM 1\n FROM information_schema.sequences\n WHERE\n sequence_schema = _table_schema AND\n sequence_name = _sequence_name;\n IF FOUND THEN\n EXECUTE 'SELECT setval( ''' || _table_schema || '.' || _sequence_name || ''', ' || '(SELECT MAX(' || _columnname || ') FROM ' || _table_schema || '.' || _tablename || ')' || '+1)';\n ELSE\n RAISE WARNING 'SEQUENCE NOT UPDATED ON %.%', _tablename, _columnname;\n END IF;\nEND; \n$BODY$\n LANGUAGE 'plpgsql';\n\nSELECT reset_sequence(table_schema, table_name, column_name, table_name || '_' || column_name || '_seq')\nFROM information_schema.columns\nWHERE column_default LIKE 'nextval%';\n\nDROP FUNCTION reset_sequence(_table_schema text, _tablename text, _columnname text, _sequence_name text) ;\nCOMMIT;\n</code></pre>\n" }, { "answer_id": 13308052, "author": "Antony Hatchkins", "author_id": 237105, "author_profile": "https://Stackoverflow.com/users/237105", "pm_score": 3, "selected": false, "text": "<p>Putting it all together</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text) \nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\n EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''id''),\n (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';\nEND;\n$body$ LANGUAGE 'plpgsql';\n</code></pre>\n\n<p>will fix '<code>id'</code> sequence of the given table (as usually necessary with django for instance).</p>\n" }, { "answer_id": 14633145, "author": "EB.", "author_id": 84041, "author_profile": "https://Stackoverflow.com/users/84041", "pm_score": 4, "selected": false, "text": "<p>Reset all sequences, no assumptions about names except that the primary key of each table is \"id\":</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text, columnname text)\nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\n EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''' || columnname || '''),\n (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';\nEND;\n$body$ LANGUAGE 'plpgsql';\n\nselect table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name) from information_schema.columns where column_default like 'nextval%';\n</code></pre>\n" }, { "answer_id": 16781395, "author": "Wolph", "author_id": 54017, "author_profile": "https://Stackoverflow.com/users/54017", "pm_score": 1, "selected": false, "text": "<p>Ugly hack to fix it using some shell magic, not a great solution but might inspire others with similar problems :)</p>\n\n<pre><code>pg_dump -s &lt;DATABASE&gt; | grep 'CREATE TABLE' | awk '{print \"SELECT setval(#\" $3 \"_id_seq#, (SELECT MAX(id) FROM \" $3 \"));\"}' | sed \"s/#/'/g\" | psql &lt;DATABASE&gt; -f -\n</code></pre>\n" }, { "answer_id": 23390399, "author": "Erwin Brandstetter", "author_id": 939860, "author_profile": "https://Stackoverflow.com/users/939860", "pm_score": 8, "selected": false, "text": "<h3>The shortest and fastest way</h3>\n<pre><code>SELECT setval('tbl_tbl_id_seq', max(tbl_id)) FROM tbl;\n</code></pre>\n<p><code>tbl_id</code> being the <code>serial</code> or <code>IDENTITY</code> column of table <code>tbl</code>, drawing from the sequence <code>tbl_tbl_id_seq</code> (resulting default name). See:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/9875223/auto-increment-table-column/9875517#9875517\">Auto increment table column</a></li>\n</ul>\n<p><strong>If</strong> you don't know the name of the attached sequence (which doesn't have to be in default form), use <a href=\"https://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE\" rel=\"noreferrer\"><strong><code>pg_get_serial_sequence()</code></strong></a> (works for <code>IDENTITY</code>, too):</p>\n<pre><code>SELECT setval(pg_get_serial_sequence('tbl', 'tbl_id'), max(tbl_id)) FROM tbl;\n</code></pre>\n<p>There is no off-by-one error here. <a href=\"https://www.postgresql.org/docs/current/functions-sequence.html\" rel=\"noreferrer\">The manual:</a></p>\n<blockquote>\n<p>The two-parameter form sets the sequence's <code>last_value</code> field to the\nspecified value and sets its <code>is_called</code> field to true, meaning that the\n<strong>next <code>nextval</code> will advance the sequence</strong> before returning a value.</p>\n</blockquote>\n<p>Bold emphasis mine.</p>\n<p><strong>If</strong> the table can be empty, and to actually start from 1 in this case:</p>\n<pre><code>SELECT setval(pg_get_serial_sequence('tbl', 'tbl_id')\n , COALESCE(max(tbl_id) + 1, 1)\n , false)\nFROM tbl;\n</code></pre>\n<p>We can't just use the 2-parameter form and start with <code>0</code> because the lower bound of sequences is <em><strong>1</strong></em> by default (unless customized).</p>\n<h3>Safe under concurrent write load</h3>\n<p>To also defend against concurrent sequence activity or writes, <em><strong>lock the table</strong></em> in <code>SHARE</code> mode. It keeps concurrent transactions from writing a higher number (or anything at all).</p>\n<p>To also take clients into account that may have fetched sequence numbers in advance without any locks on the main table, yet (can happen in certain setups), only <em>increase</em> the current value of the sequence, never decrease it. That may seem paranoid, but that's in accord with the nature of sequences and defending against concurrency issues.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>BEGIN;\n\nLOCK TABLE tbl IN SHARE MODE;\n\nSELECT setval('tbl_tbl_id_seq', max(tbl_id))\nFROM tbl\nHAVING max(tbl_id) &gt; (SELECT last_value FROM tbl_tbl_id_seq); -- prevent lower number\n\nCOMMIT;\n</code></pre>\n<p><code>SHARE</code> mode is strong enough for the purpose. <a href=\"https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-TABLES\" rel=\"noreferrer\">The manual:</a></p>\n<blockquote>\n<p>This mode protects a table against concurrent data changes.</p>\n</blockquote>\n<p>It conflicts with <code>ROW EXCLUSIVE</code> mode.</p>\n<blockquote>\n<p>The commands <code>UPDATE</code>, <code>DELETE</code>, and <code>INSERT</code> acquire this lock mode on the target table.</p>\n</blockquote>\n" }, { "answer_id": 23831064, "author": "user", "author_id": 781695, "author_profile": "https://Stackoverflow.com/users/781695", "pm_score": 2, "selected": false, "text": "<p>If you see this error when you are loading custom SQL data for initialization, another way to avoid this is:</p>\n\n<p>Instead of writing:</p>\n\n<pre><code>INSERT INTO book (id, name, price) VALUES (1 , 'Alchemist' , 10),\n</code></pre>\n\n<p>Remove the <code>id</code> (primary key) from initial data</p>\n\n<pre><code>INSERT INTO book (name, price) VALUES ('Alchemist' , 10),\n</code></pre>\n\n<p>This keeps the Postgres sequence in sync !</p>\n" }, { "answer_id": 25603776, "author": "Haider Ali Wajihi", "author_id": 870561, "author_profile": "https://Stackoverflow.com/users/870561", "pm_score": 5, "selected": false, "text": "<p>This command for only change auto generated key sequence value in postgresql </p>\n\n<pre><code>ALTER SEQUENCE \"your_sequence_name\" RESTART WITH 0;\n</code></pre>\n\n<p>In place of zero you can put any number from which you want to restart sequence.</p>\n\n<p>default sequence name will <code>\"TableName_FieldName_seq\"</code>. For example, if your table name is <code>\"MyTable\"</code> and your field name is <code>\"MyID\"</code>, then your sequence name will be <strong><code>\"MyTable_MyID_seq\"</code></strong>.</p>\n\n<p>This is answer is same as @murugesanponappan's answer, but there is a syntax error in his solution. you can not use sub query <code>(select max()...)</code> in <code>alter</code> command. So that either you have to use fixed numeric value or you need to use a variable in place of sub query.</p>\n" }, { "answer_id": 26801367, "author": "Ian Bytchek", "author_id": 458356, "author_profile": "https://Stackoverflow.com/users/458356", "pm_score": 3, "selected": false, "text": "<p>Some really hardcore answers here, I'm assuming it used to be really bad at around the time when this has been asked, since a lot of answers from here don't works for version 9.3. The <a href=\"http://www.postgresql.org/docs/8.0/static/sql-createsequence.html\" rel=\"noreferrer\">documentation</a> since version 8.0 provides an answer to this very question:</p>\n\n<pre><code>SELECT setval('serial', max(id)) FROM distributors;\n</code></pre>\n\n<p>Also, if you need to take care of case-sensitive sequence names, that's how you do it:</p>\n\n<pre><code>SELECT setval('\"Serial\"', max(id)) FROM distributors;\n</code></pre>\n" }, { "answer_id": 30380044, "author": "mcandre", "author_id": 350106, "author_profile": "https://Stackoverflow.com/users/350106", "pm_score": -1, "selected": false, "text": "<p><code>SELECT setval...</code> makes JDBC bork, so here's a Java-compatible way of doing this:</p>\n\n<pre><code>-- work around JDBC 'A result was returned when none was expected.'\n-- fix broken nextval due to poorly written 20140320100000_CreateAdminUserRoleTables.sql\nDO 'BEGIN PERFORM setval(pg_get_serial_sequence(''admin_user_role_groups'', ''id''), 1 + COALESCE(MAX(id), 0), FALSE) FROM admin_user_role_groups; END;';\n</code></pre>\n" }, { "answer_id": 30593263, "author": "anydasa", "author_id": 2987511, "author_profile": "https://Stackoverflow.com/users/2987511", "pm_score": 3, "selected": false, "text": "<p>Recheck all sequence in public schema function</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION public.recheck_sequence (\n)\nRETURNS void AS\n$body$\nDECLARE\n _table_name VARCHAR;\n _column_name VARCHAR; \n _sequence_name VARCHAR;\nBEGIN\n FOR _table_name IN SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = 'public' LOOP\n FOR _column_name IN SELECT column_name FROM information_schema.columns WHERE table_name = _table_name LOOP\n SELECT pg_get_serial_sequence(_table_name, _column_name) INTO _sequence_name;\n IF _sequence_name IS NOT NULL THEN \n EXECUTE 'SELECT setval('''||_sequence_name||''', COALESCE((SELECT MAX('||quote_ident(_column_name)||')+1 FROM '||quote_ident(_table_name)||'), 1), FALSE);';\n END IF;\n END LOOP; \n END LOOP;\nEND;\n$body$\nLANGUAGE 'plpgsql'\nVOLATILE\nCALLED ON NULL INPUT\nSECURITY INVOKER\nCOST 100;\n</code></pre>\n" }, { "answer_id": 37867461, "author": "Baldiry", "author_id": 2797271, "author_profile": "https://Stackoverflow.com/users/2797271", "pm_score": 2, "selected": false, "text": "<p>This answer is a copy from mauro.</p>\n\n<pre><code>drop function IF EXISTS rebuilt_sequences() RESTRICT;\nCREATE OR REPLACE FUNCTION rebuilt_sequences() RETURNS integer as\n$body$\n DECLARE sequencedefs RECORD; c integer ;\n BEGIN\n FOR sequencedefs IN Select\n DISTINCT(constraint_column_usage.table_name) as tablename,\n constraint_column_usage.column_name as columnname,\n replace(replace(columns.column_default,'''::regclass)',''),'nextval(''','') as sequencename\n from information_schema.constraint_column_usage, information_schema.columns\n where constraint_column_usage.table_schema ='public' AND \n columns.table_schema = 'public' AND columns.table_name=constraint_column_usage.table_name\n AND constraint_column_usage.column_name = columns.column_name\n AND columns.column_default is not null \n ORDER BY sequencename\n LOOP \n EXECUTE 'select max('||sequencedefs.columnname||') from ' || sequencedefs.tablename INTO c;\n IF c is null THEN c = 0; END IF;\n IF c is not null THEN c = c+ 1; END IF;\n EXECUTE 'alter sequence ' || sequencedefs.sequencename ||' minvalue '||c ||' start ' || c ||' restart with ' || c;\n END LOOP;\n\n RETURN 1; END;\n$body$ LANGUAGE plpgsql;\n\nselect rebuilt_sequences();\n</code></pre>\n" }, { "answer_id": 38575949, "author": "Pietro", "author_id": 488413, "author_profile": "https://Stackoverflow.com/users/488413", "pm_score": 4, "selected": false, "text": "<p>I suggest this solution found on postgres wiki. It updates all sequences of your tables.</p>\n\n<pre><code>SELECT 'SELECT SETVAL(' ||\n quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||\n ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||\n quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'\nFROM pg_class AS S,\n pg_depend AS D,\n pg_class AS T,\n pg_attribute AS C,\n pg_tables AS PGT\nWHERE S.relkind = 'S'\n AND S.oid = D.objid\n AND D.refobjid = T.oid\n AND D.refobjid = C.attrelid\n AND D.refobjsubid = C.attnum\n AND T.relname = PGT.tablename\nORDER BY S.relname;\n</code></pre>\n\n<p>How to use(from postgres wiki):</p>\n\n<ul>\n<li>Save this to a file, say 'reset.sql'</li>\n<li>Run the file and save its output in a way that doesn't include the usual headers, then run that output. Example:</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>psql -Atq -f reset.sql -o temp\npsql -f temp\nrm temp\n</code></pre>\n\n<p>Original article(also with fix for sequence ownership) <a href=\"https://wiki.postgresql.org/wiki/Fixing_Sequences\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 39274810, "author": "Stanislav Yanev", "author_id": 6783854, "author_profile": "https://Stackoverflow.com/users/6783854", "pm_score": 2, "selected": false, "text": "<p>To restart all sequence to 1 use:</p>\n\n<pre><code>-- Create Function\nCREATE OR REPLACE FUNCTION \"sy_restart_seq_to_1\" (\n relname TEXT\n)\nRETURNS \"pg_catalog\".\"void\" AS\n$BODY$\n\nDECLARE\n\nBEGIN\n EXECUTE 'ALTER SEQUENCE '||relname||' RESTART WITH 1;';\nEND;\n$BODY$\n\nLANGUAGE 'plpgsql';\n\n-- Use Function\nSELECT \n relname\n ,sy_restart_seq_to_1(relname)\nFROM pg_class\nWHERE relkind = 'S';\n</code></pre>\n" }, { "answer_id": 43519125, "author": "Vao Tsun", "author_id": 5315974, "author_profile": "https://Stackoverflow.com/users/5315974", "pm_score": 3, "selected": false, "text": "<p>Yet another plpgsql - resets only if <code>max(att) &gt; then lastval</code></p>\n\n<pre><code>do --check seq not in sync\n$$\ndeclare\n _r record;\n _i bigint;\n _m bigint;\nbegin\n for _r in (\n SELECT relname,nspname,d.refobjid::regclass, a.attname, refobjid\n FROM pg_depend d\n JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid\n JOIN pg_class r on r.oid = objid\n JOIN pg_namespace n on n.oid = relnamespace\n WHERE d.refobjsubid &gt; 0 and relkind = 'S'\n ) loop\n execute format('select last_value from %I.%I',_r.nspname,_r.relname) into _i;\n execute format('select max(%I) from %s',_r.attname,_r.refobjid) into _m;\n if coalesce(_m,0) &gt; _i then\n raise info '%',concat('changed: ',_r.nspname,'.',_r.relname,' from:',_i,' to:',_m);\n execute format('alter sequence %I.%I restart with %s',_r.nspname,_r.relname,_m+1);\n end if;\n end loop;\n\nend;\n$$\n;\n</code></pre>\n\n<p>also commenting the line <code>--execute format('alter sequence</code> will give the list, not actually resetting the value</p>\n" }, { "answer_id": 44932074, "author": "Nintynuts", "author_id": 6220064, "author_profile": "https://Stackoverflow.com/users/6220064", "pm_score": 2, "selected": false, "text": "<p>I spent an hour trying to get djsnowsill's answer to work with a database using Mixed Case tables and columns, then finally stumbled upon the solution thanks to a comment from Manuel Darveau, but I thought I could make it a bit clearer for everyone:</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION \"reset_sequence\" (tablename text, columnname text)\nRETURNS \"pg_catalog\".\"void\" AS\n$body$\nDECLARE\nBEGIN\nEXECUTE format('SELECT setval(pg_get_serial_sequence(''%1$I'', %2$L),\n (SELECT COALESCE(MAX(%2$I)+1,1) FROM %1$I), false)',tablename,columnname);\nEND;\n$body$ LANGUAGE 'plpgsql';\n\nSELECT format('%s_%s_seq',table_name,column_name), reset_sequence(table_name,column_name) \nFROM information_schema.columns WHERE column_default like 'nextval%';\n</code></pre>\n\n<p>This has the benefit of:</p>\n\n<ul>\n<li>not assuming ID column is spelled a particular way.</li>\n<li>not assuming all tables have a sequence.</li>\n<li>working for Mixed Case table/column names. </li>\n<li>using format to be more concise.</li>\n</ul>\n\n<p>To explain, the problem was that <code>pg_get_serial_sequence</code> takes strings to work out what you're referring to, so if you do:</p>\n\n<pre><code>\"TableName\" --it thinks it's a table or column\n'TableName' --it thinks it's a string, but makes it lower case\n'\"TableName\"' --it works!\n</code></pre>\n\n<p>This is achieved using <code>''%1$I''</code> in the format string, <code>''</code> makes an apostrophe <code>1$</code> means first arg, and <code>I</code> means in quotes</p>\n" }, { "answer_id": 49719450, "author": "Yehia Amer", "author_id": 1835701, "author_profile": "https://Stackoverflow.com/users/1835701", "pm_score": 3, "selected": false, "text": "<p>This issue happens with me when using entity framework to create the database and then seed the database with initial data, this makes the sequence mismatch.</p>\n\n<p>I Solved it by Creating a script to run after seeding the database:</p>\n\n<pre><code>DO\n$do$\nDECLARE tablename text;\nBEGIN\n -- change the where statments to include or exclude whatever tables you need\n FOR tablename IN SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' AND table_name != '__EFMigrationsHistory'\n LOOP\n EXECUTE format('SELECT setval(pg_get_serial_sequence(''\"%s\"'', ''Id''), (SELECT MAX(\"Id\") + 1 from \"%s\"))', tablename, tablename);\n END LOOP;\nEND\n$do$\n</code></pre>\n" }, { "answer_id": 55090083, "author": "Михаил Шатилов", "author_id": 7856242, "author_profile": "https://Stackoverflow.com/users/7856242", "pm_score": 2, "selected": false, "text": "<pre><code>select 'SELECT SETVAL(' || seq [ 1] || ', COALESCE(MAX('||column_name||')+1, 1) ) FROM '||table_name||';'\nfrom (\n SELECT table_name, column_name, column_default, regexp_match(column_default, '''.*''') as seq\n from information_schema.columns\n where column_default ilike 'nextval%'\n ) as sequense_query\n</code></pre>\n" }, { "answer_id": 56155955, "author": "Nick Van Berckelaer", "author_id": 5795188, "author_profile": "https://Stackoverflow.com/users/5795188", "pm_score": 1, "selected": false, "text": "<p>A method to update all sequences in your schema that are used as an ID:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DO $$ DECLARE\n r RECORD;\nBEGIN\nFOR r IN (SELECT tablename, pg_get_serial_sequence(tablename, 'id') as sequencename\n FROM pg_catalog.pg_tables\n WHERE schemaname='YOUR_SCHEMA'\n AND tablename IN (SELECT table_name \n FROM information_schema.columns \n WHERE table_name=tablename and column_name='id')\n order by tablename)\nLOOP\nEXECUTE\n 'SELECT setval(''' || r.sequencename || ''', COALESCE(MAX(id), 1), MAX(id) IS NOT null)\n FROM ' || r.tablename || ';';\nEND LOOP;\nEND $$;\n</code></pre>\n" }, { "answer_id": 58185391, "author": "Asad Rao", "author_id": 852406, "author_profile": "https://Stackoverflow.com/users/852406", "pm_score": 2, "selected": false, "text": "<p>Just run below command:</p>\n\n<pre><code>SELECT setval('my_table_seq', (SELECT max(id) FROM my_table));\n</code></pre>\n" }, { "answer_id": 61831530, "author": "brianwaganer", "author_id": 10298071, "author_profile": "https://Stackoverflow.com/users/10298071", "pm_score": 0, "selected": false, "text": "<p>There are a lot of good answers here. I had the same need after reloading my Django database.</p>\n\n<p>But I needed:</p>\n\n<ul>\n<li>All in one Function</li>\n<li>Could fix one or more schemas at a time</li>\n<li>Could fix all or just one table at a time</li>\n<li>Also wanted a nice way to see exactly what had changed, or not changed</li>\n</ul>\n\n<p>This seems very similar need to what the original ask was for.<br>\nThanks to Baldiry and Mauro got me on the right track.</p>\n\n<pre><code>drop function IF EXISTS reset_sequences(text[], text) RESTRICT;\nCREATE OR REPLACE FUNCTION reset_sequences(\n in_schema_name_list text[] = '{\"django\", \"dbaas\", \"metrics\", \"monitor\", \"runner\", \"db_counts\"}',\n in_table_name text = '%') RETURNS text[] as\n$body$\n DECLARE changed_seqs text[];\n DECLARE sequence_defs RECORD; c integer ;\n BEGIN\n FOR sequence_defs IN\n select\n DISTINCT(ccu.table_name) as table_name,\n ccu.column_name as column_name,\n replace(replace(c.column_default,'''::regclass)',''),'nextval(''','') as sequence_name\n from information_schema.constraint_column_usage ccu,\n information_schema.columns c\n where ccu.table_schema = ANY(in_schema_name_list)\n and ccu.table_schema = c.table_schema\n AND c.table_name = ccu.table_name\n and c.table_name like in_table_name\n AND ccu.column_name = c.column_name\n AND c.column_default is not null\n ORDER BY sequence_name\n LOOP\n EXECUTE 'select max(' || sequence_defs.column_name || ') from ' || sequence_defs.table_name INTO c;\n IF c is null THEN c = 1; else c = c + 1; END IF;\n EXECUTE 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c;\n changed_seqs = array_append(changed_seqs, 'alter sequence ' || sequence_defs.sequence_name || ' restart with ' || c);\n END LOOP;\n changed_seqs = array_append(changed_seqs, 'Done');\n\n RETURN changed_seqs;\nEND\n$body$ LANGUAGE plpgsql;\n</code></pre>\n\n<p>Then to Execute and See the changes run:</p>\n\n<pre><code>select *\nfrom unnest(reset_sequences('{\"django\", \"dbaas\", \"metrics\", \"monitor\", \"runner\", \"db_counts\"}'));\n</code></pre>\n\n<p>Returns</p>\n\n<pre><code>activity_id_seq restart at 22\napi_connection_info_id_seq restart at 4\napi_user_id_seq restart at 1\napplication_contact_id_seq restart at 20\n</code></pre>\n" }, { "answer_id": 64250938, "author": "Alexi Theodore", "author_id": 9819342, "author_profile": "https://Stackoverflow.com/users/9819342", "pm_score": 1, "selected": false, "text": "<p>So I can tell there aren't enough opinions or reinvented wheels in this thread, so I decided to spice things up.</p>\n<p>Below is a procedure that:</p>\n<ul>\n<li>is focused (only affects) on sequences that are associated with tables</li>\n<li>works for both SERIAL and GENERATED AS IDENTITY columns</li>\n<li>works for good_column_names and &quot;BAD_column_123&quot; names</li>\n<li>automatically assigns the respective sequences' defined start value if the table is empty</li>\n<li>allows for a specific sequences to be affected only (in schema.table.column notation)</li>\n<li>has a preview mode</li>\n</ul>\n<pre><code>CREATE OR REPLACE PROCEDURE pg_reset_all_table_sequences(\n IN commit_mode BOOLEAN DEFAULT FALSE\n, IN mask_in TEXT DEFAULT NULL\n) AS\n$$\nDECLARE\n sql_reset TEXT;\n each_sec RECORD;\n new_val TEXT;\nBEGIN\n\nsql_reset :=\n$sql$\nSELECT setval(pg_get_serial_sequence('%1$s.%2$s', '%3$s'), coalesce(max(&quot;%3$s&quot;), %4$s), false) FROM %1$s.%2$s;\n$sql$\n;\n\nFOR each_sec IN (\n\n SELECT\n quote_ident(table_schema) as table_schema\n , quote_ident(table_name) as table_name\n , column_name\n , coalesce(identity_start::INT, seqstart) as min_val\n FROM information_schema.columns\n JOIN pg_sequence ON seqrelid = pg_get_serial_sequence(quote_ident(table_schema)||'.'||quote_ident(table_name) , column_name)::regclass\n WHERE\n (is_identity::boolean OR column_default LIKE 'nextval%') -- catches both SERIAL and IDENTITY sequences\n\n -- mask on column address (schema.table.column) if supplied\n AND coalesce( table_schema||'.'||table_name||'.'||column_name = mask_in, TRUE )\n)\nLOOP\n\nIF commit_mode THEN\n EXECUTE format(sql_reset, each_sec.table_schema, each_sec.table_name, each_sec.column_name, each_sec.min_val) INTO new_val;\n RAISE INFO 'Resetting sequence for: %.% (%) to %'\n , each_sec.table_schema\n , each_sec.table_name\n , each_sec.column_name\n , new_val\n ;\nELSE\n RAISE INFO 'Sequence found for resetting: %.% (%)'\n , each_sec.table_schema\n , each_sec.table_name\n , each_sec.column_name\n ;\nEND IF\n;\n\nEND LOOP;\n\nEND\n$$\nLANGUAGE plpgsql\n;\n</code></pre>\n<p>to preview:</p>\n<p><code>call pg_reset_all_table_sequences();</code></p>\n<p>to commit:</p>\n<p><code>call pg_reset_all_table_sequences(true);</code></p>\n<p>to specify only your target table:</p>\n<p><code>call pg_reset_all_table_sequences('schema.table.column');</code></p>\n" }, { "answer_id": 66982974, "author": "DevonDahon", "author_id": 931247, "author_profile": "https://Stackoverflow.com/users/931247", "pm_score": 5, "selected": false, "text": "<p>In the example below, the <strong>table</strong> name is <code>users</code> and the <strong>schema</strong> name is <code>public</code> (default schema), replace it according to your needs.</p>\n<h3>1. Check the <code>max id</code>:</h3>\n<pre><code>SELECT MAX(id) FROM public.users;\n</code></pre>\n<h3>2. Check the <code>next value</code>:</h3>\n<pre><code>SELECT nextval('public.&quot;users_id_seq&quot;');\n</code></pre>\n<h3>3. If the <code>next value</code> is lower than the <code>max id</code>, reset it:</h3>\n<pre><code>SELECT setval('public.&quot;users_id_seq&quot;',\n (SELECT MAX(id) FROM public.users)\n);\n</code></pre>\n<h3>Note:</h3>\n<p><code>nextval()</code> will increment the sequence before returning the current value while <code>currval()</code> would just return the current value, as documented <a href=\"https://www.postgresql.org/docs/current/functions-sequence.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 70908122, "author": "NemyaNation", "author_id": 3396971, "author_profile": "https://Stackoverflow.com/users/3396971", "pm_score": 0, "selected": false, "text": "<p>I couldn't find an answer explicitly for Rails.</p>\n<p>From the <code>rails console</code></p>\n<pre><code>ActiveRecord::Base.connection.execute(&quot;SELECT setval(pg_get_serial_sequence('table_name', 'id'), MAX(id)) FROM table_name;&quot;)\n</code></pre>\n<p>Replacing <code>table_name</code> with <code>users</code> for example.</p>\n" }, { "answer_id": 74640952, "author": "Fenerbahce", "author_id": 15512188, "author_profile": "https://Stackoverflow.com/users/15512188", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT setval('sequencename', COALESCE((SELECT MAX(id)+1 FROM tablename), 1), false);\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
I ran into the problem that my primary key sequence is not in sync with my table rows. That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists. It seems to be caused by import/restores not maintaining the sequence properly.
``` -- Login to psql and run the following -- What is the result? SELECT MAX(id) FROM your_table; -- Then run... -- This should be higher than the last result. SELECT nextval('your_table_id_seq'); -- If it's not higher... run this set the sequence last to your highest id. -- (wise to run a quick pg_dump first...) BEGIN; -- protect against concurrent inserts while you update the counter LOCK TABLE your_table IN EXCLUSIVE MODE; -- Update the sequence SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false); COMMIT; ``` [Source - Ruby Forum](http://www.ruby-forum.com/topic/64428#72333)
244,246
<p>I want to create an alias for a class name. The following syntax would be perfect:</p> <pre><code>public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName { ... } public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName; </code></pre> <p>but it won't compile.</p> <hr /> <h2>Example</h2> <p><strong>Note</strong> This example is provided for convenience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question.</p> <p>Some existing code depends on the presence of a static class:</p> <pre><code>public static class ColorScheme { ... } </code></pre> <p>This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme:</p> <pre><code>public static class Outlook2003ColorScheme { ... } public static class Outlook2007ColorScheme { ... } </code></pre> <p>But i'm still faced with the fact that the code depends on the presence of a static class called <code>ColorScheme</code>. My first thought was to create a <code>ColorScheme</code> class that I will inherit from either <code>Outlook2003</code> or <code>Outlook2007</code>:</p> <pre><code>public static class ColorScheme : Outlook2007ColorScheme { } </code></pre> <p>but you cannot inherit from a static class.</p> <p>My next thought was to create the static <code>ColorScheme</code> class, but make <code>Outlook2003ColorScheme</code> and <code>Outlook2007ColorScheme</code> classes non-static. Then a static variable in the static <code>ColorScheme</code> class can point to either &quot;true&quot; color scheme:</p> <pre><code>public static class ColorScheme { private static CustomColorScheme = new Outlook2007ColorScheme(); ... } private class CustomColorScheme { ... } private class Outlook2008ColorScheme : CustomColorScheme { ... } private class Outlook2003ColorScheme : CustomColorScheme { ... } </code></pre> <p>but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my <code>ColorScheme</code> class would need to have the 30 different property getters thunk down into the contained object.</p> <p>That's just too much typing.</p> <p>So my next thought was to alias the class:</p> <pre><code>public static ColorScheme = Outlook2007ColorScheme; </code></pre> <p>But that doesn't compile.</p> <p>How can I alias a static class into another name?</p> <hr /> <p><strong>Update:</strong> Can someone please add the answer <em>&quot;You cannot do this in C#&quot;</em>, so I can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful.</p> <p>I just want to close this question out.</p>
[ { "answer_id": 244255, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "<p><strong>You can’t</strong>. The next best thing you <em>can</em> do is have <code>using</code> declarations in the files that use the class.</p>\n<p>For example, you could rewrite the dependent code using an import alias (as a quasi-<code>typedef</code> substitute):</p>\n<pre><code>using ColorScheme = The.Fully.Qualified.Namespace.Outlook2007ColorScheme;\n</code></pre>\n<p>Unfortunately this needs to go into every scope/file that uses the name.</p>\n<p>I therefore don't know if this is practical in your case.</p>\n" }, { "answer_id": 244259, "author": "dpurrington", "author_id": 5573, "author_profile": "https://Stackoverflow.com/users/5573", "pm_score": 4, "selected": false, "text": "<p>try this: </p>\n\n<pre><code>using ColorScheme=[fully qualified].Outlook2007ColorScheme\n</code></pre>\n" }, { "answer_id": 244270, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "<p>You want a (<a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"noreferrer\">Factory</a>|<a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"noreferrer\">Singleton</a>), depending on your requirements. The premise is to make it so that the client code doesn't have to know which color scheme it is getting. If the color scheme should be application wide, a singleton should be fine. If you may use a different scheme in different circumstances, a Factory pattern is probably the way to go. Either way, when the color scheme needs to change, the code only has to be changed in one place.</p>\n\n<pre><code>public interface ColorScheme {\n Color TitleBar { get; }\n Color Background{ get; }\n ...\n}\n\npublic static class ColorSchemeFactory {\n\n private static ColorScheme scheme = new Outlook2007ColorScheme();\n\n public static ColorScheme GetColorScheme() { //Add applicable arguments\n return scheme;\n }\n}\n\npublic class Outlook2003ColorScheme: ColorScheme {\n public Color TitleBar {\n get { return Color.LightBlue; }\n }\n\n public Color Background {\n get { return Color.Gray; }\n }\n}\n\npublic class Outlook2007ColorScheme: ColorScheme {\n public Color TitleBar {\n get { return Color.Blue; }\n }\n\n public Color Background {\n get { return Color.White; }\n }\n}\n</code></pre>\n" }, { "answer_id": 244284, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 2, "selected": false, "text": "<p>Is it possible to change to using an interface?</p>\n\n<p>Perhaps you could create an <code>IColorScheme</code> interface that all of the classes implement?</p>\n\n<p>This would work well with the factory pattern as shown by Chris Marasti-Georg</p>\n" }, { "answer_id": 244289, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 5, "selected": false, "text": "<p>You can make an alias for your class by adding this line of code:</p>\n\n<pre><code>using Outlook2007ColorScheme = YourNameSpace.ColorScheme;\n</code></pre>\n" }, { "answer_id": 436588, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": true, "text": "<p>You cannot alias a class name in C#.</p>\n<p>There are things you can do that are not aliasing a class name in C#.</p>\n<p>But to answer the original question: you cannot alias a class name in C#.</p>\n<hr />\n<p><strong>Update:</strong> People are confused why <code>using</code> doesn't work. Example:</p>\n<p><strong>Form1.cs</strong></p>\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);\n}\n</code></pre>\n<p><strong>ColorScheme.cs</strong></p>\n<pre><code>class ColorScheme\n{\n public static Color ApplyColorScheme(Color c) { ... }\n}\n</code></pre>\n<p>And everything works. Now i want to create a <em>new</em> class, and <em>alias</em> <code>ColorScheme</code> to it (so that <strong>no code needs to be modified</strong>):</p>\n<p><strong>ColorScheme.cs</strong></p>\n<pre><code>using ColorScheme = Outlook2007ColorScheme;\n\nclass Outlook2007ColorScheme\n{\n public static Color ApplyColorScheme(Color c) { ... }\n}\n</code></pre>\n<p>Ohh, i'm sorry. This code doesn't compile:</p>\n<p><img src=\"https://i.stack.imgur.com/GybrT.png\" alt=\"enter image description here\" /></p>\n<p>My question was how to <em>alias</em> a class in C#. It cannot be done. There are things i can do that are <em>not</em> aliasing a class name in C#:</p>\n<ul>\n<li>change everyone who depends on <code>ColorScheme</code> to <code>using</code> <code>ColorScheme</code> instead (code change workaround because i cannot alias)</li>\n<li>change everyone who depends on <code>ColorScheme</code> to use a factory pattern them a polymorphic class or interface (code change workaround because i cannot alias)</li>\n</ul>\n<p>But these workarounds involve breaking existing code: not an option.</p>\n<p>If people depend on the presence of a <code>ColorScheme</code> class, i have to actually copy/paste a <code>ColorScheme</code> class.</p>\n<p>In other words: i cannot alias a class name in C#.</p>\n<p>This contrasts with other object oriented languages, where i could define the alias:</p>\n<pre><code>ColorScheme = Outlook2007ColorScheme\n</code></pre>\n<p>and i'd be done.</p>\n" }, { "answer_id": 28787521, "author": "Timothy", "author_id": 2946652, "author_profile": "https://Stackoverflow.com/users/2946652", "pm_score": 2, "selected": false, "text": "<p>Aliasing the way that you would like to do it will not work in C#. This is because aliasing is done through the <code>using</code> directive, which is limited to the file/namespace in question. If you have 50 files that use the old class name, that will mean 50 places to update.</p>\n\n<p>That said, I think there is an easy solution to make your code change as minimal as possible. Make the <code>ColorScheme</code> class a facade for your calls to the actual classes with the implementation, and use the <code>using</code> in that file to determine which <code>ColorScheme</code> you use.</p>\n\n<p>In other words, do this:</p>\n\n<pre><code>using CurrentColorScheme = Outlook2007ColorScheme;\npublic static class ColorScheme\n{\n public static Color ApplyColorScheme(Color c)\n {\n return CurrentColorScheme.ApplyColorScheme(c);\n }\n public static Something DoSomethingElse(Param a, Param b)\n {\n return CurrentColorScheme.DoSomethingElse(a, b);\n }\n}\n</code></pre>\n\n<p>Then in your code behind, change nothing:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor);\n}\n</code></pre>\n\n<p>You can then update the values of <code>ColorScheme</code> by updating one line of code (<code>using CurrentColorScheme = Outlook2008ColorScheme;</code>).</p>\n\n<p>A couple concerns here:</p>\n\n<ul>\n<li>Every new method or property definition will then need to be added in two places, to the <code>ColorScheme</code> class and to the <code>Outlook2007ColorScheme</code> class. This is extra work, but if this is true legacy code, it shouldn't be a frequent occurence. As a bonus, the code in <code>ColorScheme</code> is so simple that any possible bug is very obvious.</li>\n<li>This use of static classes doesn't seem natural to me; I probably would try to refactor the legacy code to do this differently, but I understand too that your situation may not allow that.</li>\n<li>If you already have a <code>ColorScheme</code> class that you're replacing, this approach and any other could be a problem. I would advise that you rename that class to something like <code>ColorSchemeOld</code>, and then access it through <code>using CurrentColorScheme = ColorSchemeOld;</code>.</li>\n</ul>\n" }, { "answer_id": 31062732, "author": "percebus", "author_id": 1361858, "author_profile": "https://Stackoverflow.com/users/1361858", "pm_score": 2, "selected": false, "text": "<p>I suppose you can always inherit from the base class with nothing added</p>\n\n<pre><code>public class Child : MyReallyReallyLongNamedClass {}\n</code></pre>\n\n<p><em>UPDATE</em></p>\n\n<p>But if you have the capability of refactoring the <code>class</code> itself: A class name is usually unnecessarily long due to lack of <code>namespace</code>s.</p>\n\n<p>If you see cases as <code>ApiLoginUser</code>, <code>DataBaseUser</code>, <code>WebPortalLoginUser</code>, is usually indication of lack of <code>namespace</code> due the fear that the name <code>User</code> might conflict.</p>\n\n<p>In this case however, you can use <code>namespace</code> alias <strong>,as it has been pointed out in above posts</strong></p>\n\n<pre><code>using LoginApi = MyCompany.Api.Login;\nusing AuthDB = MyCompany.DataBase.Auth;\nusing ViewModels = MyCompany.BananasPortal.Models;\n\n// ...\nAuthDB.User dbUser;\nusing ( var ctxt = new AuthDB.AuthContext() )\n{\n dbUser = ctxt.Users.Find(userId);\n}\n\nvar apiUser = new LoginApi.Models.User {\n Username = dbUser.EmailAddess,\n Password = \"*****\"\n };\n\nLoginApi.UserSession apiUserSession = await LoginApi.Login(apiUser);\nvar vm = new ViewModels.User(apiUserSession.User.Details);\nreturn View(vm);\n</code></pre>\n\n<p>Note how the <code>class</code> names are all <code>User</code>, but in different <code>namespace</code>s. Quoting <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">PEP-20: Zen of Python</a>:</p>\n\n<blockquote>\n <p>Namespaces are one honking great idea -- let's do more of those!</p>\n</blockquote>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 32315230, "author": "Mark Farmiloe", "author_id": 2179404, "author_profile": "https://Stackoverflow.com/users/2179404", "pm_score": 0, "selected": false, "text": "<p>It's a very late partial answer - but if you define the same class 'ColorScheme', in the same namespace 'Outlook', but in separate assemblies, one called Outlook2003 and the other Outlook2007, then all you need to do is reference the appropriate assembly.</p>\n" }, { "answer_id": 47420103, "author": "J-Americano", "author_id": 3317003, "author_profile": "https://Stackoverflow.com/users/3317003", "pm_score": 3, "selected": false, "text": "<p>I'm adding this comment for users finding this long after OP accepted their \"answer\".\nAliasing in C# works by specifying the class name using it's fully qualified namespace. One defined, the alias name can be used within it's scope. \nExample.</p>\n\n<pre><code>using aliasClass = Fully.Qualified.Namespace.Example;\n//Example being the class in the Fully.Qualified.Namespace\n\npublic class Test{\n\n public void Test_Function(){\n\n aliasClass.DoStuff();\n //aliasClass here representing the Example class thus aliasing\n //aliasClass will be in scope for all code in my Test.cs file\n }\n\n}\n</code></pre>\n\n<p>Apologies for the quickly typed code but hopefully it explains how this should be implemented so that users aren't mislead into believing it cannot be done in C#.</p>\n" }, { "answer_id": 67751762, "author": "JeanLColombo", "author_id": 8834550, "author_profile": "https://Stackoverflow.com/users/8834550", "pm_score": 0, "selected": false, "text": "<p>The best way I've found to simulate alias in C# is inheritance.</p>\n<p>Create a new class that inherits from the original class:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName\n{\n ...\n}\n\npublic class MyName \n : LongClassNameOrOneThatContainsVersionOrDomainSpecificName\n{\n\n}\n</code></pre>\n<p>The only thing that you would need to be careful is the constructor. You need to provide a a constructor for <code>MyName</code> class.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class MyName \n : LongClassNameOrOneThatContainsVersionOrDomainSpecificName\n{\n public MyName(T1 param1, T2 param2) : base(param1, param2) {} \n}\n</code></pre>\n<p>In this example I'm using <code>T1</code> and <code>T2</code> as generic types, since I don't know the constructor for your <code>LongClassNameOrOneThatContainsVersionOrDomainSpecificName</code> class.</p>\n<p><strong>Beware, though, that this is not alias</strong>. Doing this to you application might run into some issues or problems. You might need to create some extra code to check for types, or even overload some operators.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
I want to create an alias for a class name. The following syntax would be perfect: ``` public class LongClassNameOrOneThatContainsVersionsOrDomainSpecificName { ... } public class MyName = LongClassNameOrOneThatContainsVersionOrDomainSpecificName; ``` but it won't compile. --- Example ------- **Note** This example is provided for convenience only. Don't try to solve this particular problem by suggesting changing the design of the entire system. The presence, or lack, of this example doesn't change the original question. Some existing code depends on the presence of a static class: ``` public static class ColorScheme { ... } ``` This color scheme is the Outlook 2003 color scheme. i want to introduce an Outlook 2007 color scheme, while retaining the Outlook 2003 color scheme: ``` public static class Outlook2003ColorScheme { ... } public static class Outlook2007ColorScheme { ... } ``` But i'm still faced with the fact that the code depends on the presence of a static class called `ColorScheme`. My first thought was to create a `ColorScheme` class that I will inherit from either `Outlook2003` or `Outlook2007`: ``` public static class ColorScheme : Outlook2007ColorScheme { } ``` but you cannot inherit from a static class. My next thought was to create the static `ColorScheme` class, but make `Outlook2003ColorScheme` and `Outlook2007ColorScheme` classes non-static. Then a static variable in the static `ColorScheme` class can point to either "true" color scheme: ``` public static class ColorScheme { private static CustomColorScheme = new Outlook2007ColorScheme(); ... } private class CustomColorScheme { ... } private class Outlook2008ColorScheme : CustomColorScheme { ... } private class Outlook2003ColorScheme : CustomColorScheme { ... } ``` but that would require me to convert a class composed entirly of readonly static Colors into overridable properties, and then my `ColorScheme` class would need to have the 30 different property getters thunk down into the contained object. That's just too much typing. So my next thought was to alias the class: ``` public static ColorScheme = Outlook2007ColorScheme; ``` But that doesn't compile. How can I alias a static class into another name? --- **Update:** Can someone please add the answer *"You cannot do this in C#"*, so I can mark that as the accepted answer. Anyone else wanting the answer to the same question will find this question, the accepted answer, and a number of workarounds that might, or might not, be useful. I just want to close this question out.
You cannot alias a class name in C#. There are things you can do that are not aliasing a class name in C#. But to answer the original question: you cannot alias a class name in C#. --- **Update:** People are confused why `using` doesn't work. Example: **Form1.cs** ``` private void button1_Click(object sender, EventArgs e) { this.BackColor = ColorScheme.ApplyColorScheme(this.BackColor); } ``` **ColorScheme.cs** ``` class ColorScheme { public static Color ApplyColorScheme(Color c) { ... } } ``` And everything works. Now i want to create a *new* class, and *alias* `ColorScheme` to it (so that **no code needs to be modified**): **ColorScheme.cs** ``` using ColorScheme = Outlook2007ColorScheme; class Outlook2007ColorScheme { public static Color ApplyColorScheme(Color c) { ... } } ``` Ohh, i'm sorry. This code doesn't compile: ![enter image description here](https://i.stack.imgur.com/GybrT.png) My question was how to *alias* a class in C#. It cannot be done. There are things i can do that are *not* aliasing a class name in C#: * change everyone who depends on `ColorScheme` to `using` `ColorScheme` instead (code change workaround because i cannot alias) * change everyone who depends on `ColorScheme` to use a factory pattern them a polymorphic class or interface (code change workaround because i cannot alias) But these workarounds involve breaking existing code: not an option. If people depend on the presence of a `ColorScheme` class, i have to actually copy/paste a `ColorScheme` class. In other words: i cannot alias a class name in C#. This contrasts with other object oriented languages, where i could define the alias: ``` ColorScheme = Outlook2007ColorScheme ``` and i'd be done.
244,252
<p>I've been looking (without great luck) for the perfect reference card with all the basic sorting algos in C (or maybe in pseudo code). Wikipedia is a terrific source of info but this time I'm looking for something definitely more portable (pocket size if possible) and of course printable. Any suggestion would be much appreciated!</p>
[ { "answer_id": 244258, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 3, "selected": false, "text": "<p>What you need is a book called Algorithms in C by Robert Sedgewick.</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0768682339\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Algorithms-C-paperback-Robert-Sedgewick/dp/0768682339/</a></p>\n\n<p>I would probably look for a used one. New ones are somewhat expensive (but, still totally worth it.)</p>\n" }, { "answer_id": 244260, "author": "Tim", "author_id": 10755, "author_profile": "https://Stackoverflow.com/users/10755", "pm_score": 0, "selected": false, "text": "<p>Try the Bible:</p>\n\n<p><a href=\"http://dannyreviews.com/h/Art_Programming.html\" rel=\"nofollow noreferrer\">http://dannyreviews.com/h/Art_Programming.html</a></p>\n" }, { "answer_id": 244292, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 4, "selected": false, "text": "<p>You should definitely check out the <a href=\"http://www.sorting-algorithms.com/\" rel=\"noreferrer\">Animated Sorting Algorithms</a> page. It is an amazing resource for sorting algorithms.</p>\n\n<p><strong>EDIT</strong> Thanks to Peterino for the new link!</p>\n" }, { "answer_id": 244294, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>Generally speaking, people do not worry too much about the different algorithms, and many people use the standard library <code>qsort()</code> function (which might or might not actually use a Quicksort) to do their sorting. When they don't use it, they usually have more complex requirements. This might be because they need to external sorting (spilling data to disk), or for reasons related to performance. Occasionally, the perceived overhead of the function-call-per-comparison associated with using <code>qsort()</code> (or, indeed, <code>bsearch()</code>) is too great. Sometimes, people don't want to risk the potential O(N^2) worst-case behaviour of Quicksort, but most production <code>qsort()</code> algorithms will avoid that for you.</p>\n\n<p>Quite apart from the various books on algorithms - Sedgewick is one such, but there are many others - you could also take a look at Jon Bentley's \"Programming Pearls\" or \"More Programming Pearls\" books. This would be good, anyway - they are excellent - but \"More Programming Pearls\" also includes a library of simple algorithms written in awk, including insertion sort, heap sort and quick sort. It misses out Bubble Sort, Shell Sort, and BogoSort. It also does not include Radix Sort.</p>\n" }, { "answer_id": 244632, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": true, "text": "<p>I made this for a friend of mine studying C, maybe you will find it helpful:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic void swap(int *a, int *b) {\n if (a != b) {\n int c = *a;\n *a = *b;\n *b = c;\n }\n}\n\nvoid bubblesort(int *a, int l) {\n int i, j;\n\n for (i = l - 2; i &gt;= 0; i--)\n for (j = i; j &lt; l - 1 &amp;&amp; a[j] &gt; a[j + 1]; j++)\n swap(a + j, a + j + 1);\n}\n\nvoid selectionsort(int *a, int l) {\n int i, j, k;\n for (i = 0; i &lt; l; i++) {\n for (j = (k = i) + 1; j &lt; l; j++)\n if (a[j] &lt; a[k])\n k = j;\n swap(a + i, a + k);\n }\n}\n\nstatic void hsort_helper(int *a, int i, int l) {\n int j;\n\n for (j = 2 * i + 1; j &lt; l; i = j, j = 2 * j + 1)\n if (a[i] &lt; a[j])\n if (j + 1 &lt; l &amp;&amp; a[j] &lt; a[j + 1])\n swap(a + i, a + ++j);\n else\n swap(a + i, a + j);\n else if (j + 1 &lt; l &amp;&amp; a[i] &lt; a[j + 1])\n swap(a + i, a + ++j);\n else\n break;\n}\n\nvoid heapsort(int *a, int l) {\n int i;\n\n for (i = (l - 2) / 2; i &gt;= 0; i--)\n hsort_helper(a, i, l);\n\n while (l-- &gt; 0) {\n swap(a, a + l);\n hsort_helper(a, 0, l);\n }\n}\n\nstatic void msort_helper(int *a, int *b, int l) {\n int i, j, k, m;\n\n switch (l) {\n case 1:\n a[0] = b[0];\n case 0:\n return;\n }\n\n m = l / 2;\n msort_helper(b, a, m);\n msort_helper(b + m, a + m, l - m);\n for (i = 0, j = 0, k = m; i &lt; l; i++)\n a[i] = b[j &lt; m &amp;&amp; !(k &lt; l &amp;&amp; b[j] &gt; b[k]) ? j++ : k++];\n}\n\nvoid mergesort(int *a, int l) {\n int *b;\n\n if (l &lt; 0)\n return;\n\n b = malloc(l * sizeof(int));\n memcpy(b, a, l * sizeof(int));\n msort_helper(a, b, l);\n free(b);\n}\n\nstatic int pivot(int *a, int l) {\n int i, j;\n\n for (i = j = 1; i &lt; l; i++)\n if (a[i] &lt;= a[0])\n swap(a + i, a + j++);\n\n swap(a, a + j - 1);\n\n return j;\n}\n\nvoid quicksort(int *a, int l) {\n int m;\n\n if (l &lt;= 1)\n return;\n\n m = pivot(a, l);\n quicksort(a, m - 1);\n quicksort(a + m, l - m);\n}\n\nstruct node {\n int value;\n struct node *left, *right;\n};\n\nvoid btreesort(int *a, int l) {\n int i;\n struct node *root = NULL, **ptr;\n\n for (i = 0; i &lt; l; i++) {\n for (ptr = &amp;root; *ptr;)\n ptr = a[i] &lt; (*ptr)-&gt;value ? &amp;(*ptr)-&gt;left : &amp;(*ptr)-&gt;right;\n *ptr = malloc(sizeof(struct node));\n **ptr = (struct node){.value = a[i]};\n }\n\n for (i = 0; i &lt; l; i++) {\n struct node *node;\n for (ptr = &amp;root; (*ptr)-&gt;left; ptr = &amp;(*ptr)-&gt;left);\n a[i] = (*ptr)-&gt;value;\n node = (*ptr)-&gt;right;\n free(*ptr);\n (*ptr) = node;\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
I've been looking (without great luck) for the perfect reference card with all the basic sorting algos in C (or maybe in pseudo code). Wikipedia is a terrific source of info but this time I'm looking for something definitely more portable (pocket size if possible) and of course printable. Any suggestion would be much appreciated!
I made this for a friend of mine studying C, maybe you will find it helpful: ``` #include <stdlib.h> #include <string.h> static void swap(int *a, int *b) { if (a != b) { int c = *a; *a = *b; *b = c; } } void bubblesort(int *a, int l) { int i, j; for (i = l - 2; i >= 0; i--) for (j = i; j < l - 1 && a[j] > a[j + 1]; j++) swap(a + j, a + j + 1); } void selectionsort(int *a, int l) { int i, j, k; for (i = 0; i < l; i++) { for (j = (k = i) + 1; j < l; j++) if (a[j] < a[k]) k = j; swap(a + i, a + k); } } static void hsort_helper(int *a, int i, int l) { int j; for (j = 2 * i + 1; j < l; i = j, j = 2 * j + 1) if (a[i] < a[j]) if (j + 1 < l && a[j] < a[j + 1]) swap(a + i, a + ++j); else swap(a + i, a + j); else if (j + 1 < l && a[i] < a[j + 1]) swap(a + i, a + ++j); else break; } void heapsort(int *a, int l) { int i; for (i = (l - 2) / 2; i >= 0; i--) hsort_helper(a, i, l); while (l-- > 0) { swap(a, a + l); hsort_helper(a, 0, l); } } static void msort_helper(int *a, int *b, int l) { int i, j, k, m; switch (l) { case 1: a[0] = b[0]; case 0: return; } m = l / 2; msort_helper(b, a, m); msort_helper(b + m, a + m, l - m); for (i = 0, j = 0, k = m; i < l; i++) a[i] = b[j < m && !(k < l && b[j] > b[k]) ? j++ : k++]; } void mergesort(int *a, int l) { int *b; if (l < 0) return; b = malloc(l * sizeof(int)); memcpy(b, a, l * sizeof(int)); msort_helper(a, b, l); free(b); } static int pivot(int *a, int l) { int i, j; for (i = j = 1; i < l; i++) if (a[i] <= a[0]) swap(a + i, a + j++); swap(a, a + j - 1); return j; } void quicksort(int *a, int l) { int m; if (l <= 1) return; m = pivot(a, l); quicksort(a, m - 1); quicksort(a + m, l - m); } struct node { int value; struct node *left, *right; }; void btreesort(int *a, int l) { int i; struct node *root = NULL, **ptr; for (i = 0; i < l; i++) { for (ptr = &root; *ptr;) ptr = a[i] < (*ptr)->value ? &(*ptr)->left : &(*ptr)->right; *ptr = malloc(sizeof(struct node)); **ptr = (struct node){.value = a[i]}; } for (i = 0; i < l; i++) { struct node *node; for (ptr = &root; (*ptr)->left; ptr = &(*ptr)->left); a[i] = (*ptr)->value; node = (*ptr)->right; free(*ptr); (*ptr) = node; } } ```
244,261
<p>I have a somewhat complicated branching structure at work (at least for me). It is something like this:</p> <pre> Main | 1 | 2 | \ 3 \ Ver2 | 1 | \ 2 \ | ProjectA 3 | 1 </pre> <p>There are 2 branches off of main. "Ver2" which has everyone's changes for the next version, and "ProjectA" which is my work.</p> <p>My question is: Is there a way to create a config spec that knows what has been merged so I get:</p> <ol> <li>Anything from ProjectA that has not been merged</li> <li>If the LATEST from ProjectA has been merged to Ver2, then get the LATEST from Ver2 branch</li> <li>If there is not a ProjectA branch, get from Ver2</li> <li>If there is no Ver2, get from MAIN</li> </ol> <p>For example, in the above case, if I merged version 1 from ProjectA to version 2 in Ver2 branch, then I would want to see version 3 on Ver2. However, if I have not yet merged those files, I would want version 1 from ProjectA in my view.</p>
[ { "answer_id": 244274, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Hmm … your request is a bit unspecific. While there are many recent developments in this general area, they're all quite specialized (naturally, since the field has matured). The original parsing approaches haven't really changed, though. You might want to read up on changes in parser creation tools (<a href=\"http://www.antlr.org/\" rel=\"nofollow noreferrer\">Antlr</a>, <a href=\"http://www.devincook.com/goldparser/\" rel=\"nofollow noreferrer\">Gold Parser</a>, to name but a few).</p>\n" }, { "answer_id": 244287, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 4, "selected": true, "text": "<p>Mentioning the dragon book and antlr means you've answered your own question.</p>\n\n<p>If you're looking for other parser generators you could also check out boost::spirit (<a href=\"http://spirit.sourceforge.net/\" rel=\"noreferrer\">http://spirit.sourceforge.net/</a>).</p>\n\n<p>Depending on what you're trying to achieve you might also want to consider a DSL, which you can either parse yourself or write in a scripting language like boo, ruby, python etc...</p>\n" }, { "answer_id": 244362, "author": "skinp", "author_id": 2907, "author_profile": "https://Stackoverflow.com/users/2907", "pm_score": 0, "selected": false, "text": "<p>You might also want to take a look at <a href=\"http://sablecc.org\" rel=\"nofollow noreferrer\">SableCC</a>, another parser generator \"which generates fully featured object-oriented frameworks for building compilers\". </p>\n\n<p>Their is some documentation about basic uses <a href=\"http://www.brainycreatures.org/compiler/sablecc.asp\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://sablecc.org/wiki/DocumentationPage\" rel=\"nofollow noreferrer\">here</a>. Since you asked about research papers, <a href=\"http://sablecc.sourceforge.net/documentation.html\" rel=\"nofollow noreferrer\">SableCC's main developper's master thesis</a> (1998) is available and explains a little more about SableCC advantages. </p>\n\n<p>Although the current stable version is 3.2, the development branch v4 is a complete rewrite and should implement features new to parser generators.</p>\n" }, { "answer_id": 1005799, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 0, "selected": false, "text": "<p>If you want to build custom analyzers for complex languages,\nconsider our DMS Software Reengineering Toolkit.\nSee <a href=\"http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html\" rel=\"nofollow noreferrer\">http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html</a></p>\n\n<p>This provides very strong parsing technology, making it \"easy\" to define your language\n(especially in comparison with most parser generators). </p>\n\n<p>Conventional parser generators may help\nwith parsing, but they provide zero help in the hard part of the\nprocess, which happens after you can parse the code.\nDMS provides a vast amount of machinery to support analyzing and transforming\nthe code once your have parsed it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20605/" ]
I have a somewhat complicated branching structure at work (at least for me). It is something like this: ``` Main | 1 | 2 | \ 3 \ Ver2 | 1 | \ 2 \ | ProjectA 3 | 1 ``` There are 2 branches off of main. "Ver2" which has everyone's changes for the next version, and "ProjectA" which is my work. My question is: Is there a way to create a config spec that knows what has been merged so I get: 1. Anything from ProjectA that has not been merged 2. If the LATEST from ProjectA has been merged to Ver2, then get the LATEST from Ver2 branch 3. If there is not a ProjectA branch, get from Ver2 4. If there is no Ver2, get from MAIN For example, in the above case, if I merged version 1 from ProjectA to version 2 in Ver2 branch, then I would want to see version 3 on Ver2. However, if I have not yet merged those files, I would want version 1 from ProjectA in my view.
Mentioning the dragon book and antlr means you've answered your own question. If you're looking for other parser generators you could also check out boost::spirit (<http://spirit.sourceforge.net/>). Depending on what you're trying to achieve you might also want to consider a DSL, which you can either parse yourself or write in a scripting language like boo, ruby, python etc...
244,276
<p>A website I'm working on (using AS2 because it's oldschool) has a larger index .swf file that loads sub-swfs using <code>loadMovie("foo1.swf", placeToShowSwf)</code>. There's <code>foo1.swf</code> through 4, which is silly because the only thing that's different between them is a single number in the address of an xml file that tells it what content to load. So I want to reduce this to one file, with a simple function that the index file calls to load the xml file, as seen here.</p> <pre><code>function setFooNum(i:Number) { fooNum = i; //my_xml = new XML(); edit: this line has since been removed and is kept for historical purposes my_xml.load("foo"+fooNum+".xml"); }; </code></pre> <p>However, for some reason, the xml file won't load. It loads properly outside the function, but that doesn't do me much good. It changes fooNum properly, but that doesn't do me any good if the wrong xml file is already loading. As far as I can tell, the code behaves as though the <code>my_xml.load("foo"+fooNum+".xml")</code> isn't there at all.</p> <p>Is this some sort of security measure I don't know about, and is there any way around it?</p> <p><strong><em>EDIT</em></strong> As several people pointed out, the <code>my_xml = new XML()</code> line was the culprit. Unfortunately, I'm now getting a new and exciting error. When <code>setFooNum(i)</code> is called immediately after the <code>loadMove()</code> in the index file, a <code>trace(fooNum)</code> inside the <code>setFooNum()</code> function prints that fooNum is set correctly, but a <code>trace(fooNum)</code> inside the <code>onLoad()</code> (which returns a success despite loading apparently nothing, btw) shows that fooNum is undefined! Also, I made a button in the index swf that calls <code>setFooNum(3)</code> (for debugging purposes), which for some reason makes it work fine. So waiting a few seconds for the file to load seems to solve the problem, but that's an incredibly ugly solution. </p> <p>So how do I wait until everything is completely loaded before calling <code>setFooNum()</code>? </p>
[ { "answer_id": 244308, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>Your function is creating a new XML instance each time, and as a result you will need to define the onLoad function each time as well, if you reuse the same XML instance then you won't need to re-define the function, e.g.</p>\n\n<pre>\nvar iFooNum:Number;\nvar oXML:XML = new XML();\n\noXML.onLoad = function (success:Boolean) {\n if(success) {\n //Do Something with XML.\n }\n}\n\nloadFooNum = function(i:Number) {\n iFooNum = i;\n oXML.load(\"foo\" + i + \".xml\");\n}\n\n</pre>\n\n<p>If your loading the XML file from a different domain you will need a crossdomain.xml file on the other domain to allow flash to load the XML file.</p>\n" }, { "answer_id": 244414, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 0, "selected": false, "text": "<p>Assuming you defined the onLoad event hanlder for your XMLinstance outside the function, you can remove the declaration of the instance from within the function body:</p>\n\n<pre><code>function setFooNum(i:Number) {\n fooNum = i;\n my_xml.load(\"foo\"+fooNum+\".xml\");\n};\n</code></pre>\n" }, { "answer_id": 1451112, "author": "Ryuken", "author_id": 176208, "author_profile": "https://Stackoverflow.com/users/176208", "pm_score": 0, "selected": false, "text": "<p>This tutorial on kirupa website could help you. </p>\n\n<p><a href=\"http://www.kirupa.com/web/xml/index.htm\" rel=\"nofollow noreferrer\">http://www.kirupa.com/web/xml/index.htm</a></p>\n\n<p>It explains how to work with AS and XML. Hope this helps you get the answer. </p>\n" }, { "answer_id": 1785414, "author": "mattbasta", "author_id": 205229, "author_profile": "https://Stackoverflow.com/users/205229", "pm_score": 2, "selected": true, "text": "<p>Perhaps you should double-check that you have proper authorization in <code>crossdomain.xml</code>. If your crossdomain file is jacked, none of your requests will go through.</p>\n\n<p><a href=\"http://crossdomainxml.org/\" rel=\"nofollow noreferrer\">http://crossdomainxml.org/</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32139/" ]
A website I'm working on (using AS2 because it's oldschool) has a larger index .swf file that loads sub-swfs using `loadMovie("foo1.swf", placeToShowSwf)`. There's `foo1.swf` through 4, which is silly because the only thing that's different between them is a single number in the address of an xml file that tells it what content to load. So I want to reduce this to one file, with a simple function that the index file calls to load the xml file, as seen here. ``` function setFooNum(i:Number) { fooNum = i; //my_xml = new XML(); edit: this line has since been removed and is kept for historical purposes my_xml.load("foo"+fooNum+".xml"); }; ``` However, for some reason, the xml file won't load. It loads properly outside the function, but that doesn't do me much good. It changes fooNum properly, but that doesn't do me any good if the wrong xml file is already loading. As far as I can tell, the code behaves as though the `my_xml.load("foo"+fooNum+".xml")` isn't there at all. Is this some sort of security measure I don't know about, and is there any way around it? ***EDIT*** As several people pointed out, the `my_xml = new XML()` line was the culprit. Unfortunately, I'm now getting a new and exciting error. When `setFooNum(i)` is called immediately after the `loadMove()` in the index file, a `trace(fooNum)` inside the `setFooNum()` function prints that fooNum is set correctly, but a `trace(fooNum)` inside the `onLoad()` (which returns a success despite loading apparently nothing, btw) shows that fooNum is undefined! Also, I made a button in the index swf that calls `setFooNum(3)` (for debugging purposes), which for some reason makes it work fine. So waiting a few seconds for the file to load seems to solve the problem, but that's an incredibly ugly solution. So how do I wait until everything is completely loaded before calling `setFooNum()`?
Perhaps you should double-check that you have proper authorization in `crossdomain.xml`. If your crossdomain file is jacked, none of your requests will go through. <http://crossdomainxml.org/>
244,280
<p>I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as...</p> <pre><code>System.Web.Caching.Cache cache = new System.Web.Caching.Cache(); cache.Add(...); </code></pre> <p>...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test.</p> <p>How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?</p>
[ { "answer_id": 244293, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 2, "selected": false, "text": "<p>I think your best bet would be to use a mock object (look into Rhino Mocks).</p>\n" }, { "answer_id": 244331, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it.</p>\n\n<p>Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes.</p>\n\n<pre><code>public interface ICacheWrapper\n{\n ...methods to support\n}\n\npublic class CacheWrapper : ICacheWrapper\n{\n private System.Web.Caching.Cache cache;\n public CacheWrapper( System.Web.Caching.Cache cache )\n {\n this.cache = cache;\n }\n\n ... implement methods using cache ...\n}\n\npublic class MockCacheWrapper : ICacheWrapper\n{\n private MockCache cache;\n public MockCacheWrapper( MockCache cache )\n {\n this.cache = cache;\n }\n\n ... implement methods using mock cache...\n}\n\npublic class MockCache\n{\n ... implement ways to set mock values and retrieve them...\n}\n\n[Test]\npublic void CachingTest()\n{\n ... set up omitted...\n\n ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() );\n\n CacheManager manager = new CacheManager( wrapper );\n\n manager.Insert(item,value);\n\n Assert.AreEqual( value, manager[item] );\n}\n</code></pre>\n\n<p>Real code</p>\n\n<pre><code>...\n\nCacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache ));\n\nmanager.Add(item,value);\n\n...\n</code></pre>\n" }, { "answer_id": 244890, "author": "Jacob Proffitt", "author_id": 1336, "author_profile": "https://Stackoverflow.com/users/1336", "pm_score": 1, "selected": false, "text": "<p>A very useful tool for unit testing legacy code is <a href=\"http://typemock.com/\" rel=\"nofollow noreferrer\">TypeMock Isolator</a>. It'll allow you to bypass the cache object entirely by telling it to mock that class and any method calls you find problematic. Unlike other mock frameworks, TypeMock uses reflection to intercept those method calls you tell it to mock for you so you don't have to deal with cumbersome wrappers.</p>\n\n<p>TypeMock <strong>is</strong> a commercial product, but it has free versions for open-source projects. They <strong>used</strong> to have a \"community\" edition that was a single-user license but I don't know if that's still offered.</p>\n" }, { "answer_id": 18019833, "author": "DarkoM", "author_id": 2102684, "author_profile": "https://Stackoverflow.com/users/2102684", "pm_score": 0, "selected": false, "text": "<pre><code>var httpResponse = MockRepository.GenerateMock&lt;HttpResponseBase&gt;();\nvar cache = MockRepository.GenerateMock&lt;HttpCachePolicyBase&gt;();\n cache.Stub(x =&gt; x.SetOmitVaryStar(true));\n httpResponse.Stub(x =&gt; x.Cache).Return(cache);\n httpContext.Stub(x =&gt; x.Response).Return(httpResponse);\n httpContext.Response.Stub(x =&gt; x.Cache).Return(cache);\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm trying to implement a unit test for a function in a project that doesn't have unit tests and this function requires a System.Web.Caching.Cache object as a parameter. I've been trying to create this object by using code such as... ``` System.Web.Caching.Cache cache = new System.Web.Caching.Cache(); cache.Add(...); ``` ...and then passing the 'cache' in as a parameter but the Add() function is causing a NullReferenceException. My best guess so far is that I can't create this cache object in a unit test and need to retrieve it from the HttpContext.Current.Cache which I obviously don't have access to in a unit test. How do you unit test a function that requires a System.Web.Caching.Cache object as a parameter?
When I've been faced with this sort of problem (where the class in question doesn't implement an interface), I often end up writing a wrapper with associated interface around the class in question. Then I use my wrapper in my code. For unit tests, I hand mock the wrapper and insert my own mock object into it. Of course, if a mocking framework works, then use it instead. My experience is that all mocking frameworks have some issues with various .NET classes. ``` public interface ICacheWrapper { ...methods to support } public class CacheWrapper : ICacheWrapper { private System.Web.Caching.Cache cache; public CacheWrapper( System.Web.Caching.Cache cache ) { this.cache = cache; } ... implement methods using cache ... } public class MockCacheWrapper : ICacheWrapper { private MockCache cache; public MockCacheWrapper( MockCache cache ) { this.cache = cache; } ... implement methods using mock cache... } public class MockCache { ... implement ways to set mock values and retrieve them... } [Test] public void CachingTest() { ... set up omitted... ICacheWrapper wrapper = new MockCacheWrapper( new MockCache() ); CacheManager manager = new CacheManager( wrapper ); manager.Insert(item,value); Assert.AreEqual( value, manager[item] ); } ``` Real code ``` ... CacheManager manager = new CacheManager( new CacheWrapper( HttpContext.Current.Cache )); manager.Add(item,value); ... ```
244,285
<p>I've got to get a quick and dirty configuration editor up and running. The flow goes something like this:</p> <p>configuration (POCOs on server) are serialized to XML.<br> The XML is well formed at this point. The configuration is sent to the web server in XElements.<br> On the web server, the XML (Yes, ALL OF IT) is dumped into a textarea for editing.<br> The user edits the XML directly in the webpage and clicks Submit.<br> In the response, I retrieve the altered text of the XML configuration. At this point, ALL escapes have been reverted by the process of displaying them in a webpage.<br> I attempt to load the string into an XML object (XmlElement, XElement, whatever). KABOOM.</p> <p>The problem is that serialization escapes attribute strings, but this is lost in translation along the way. </p> <p>For example, let's say I have an object that has a regex. Here's the configuration as it comes to the web server:</p> <pre><code>&lt;Configuration&gt; &lt;Validator Expression="[^&amp;lt;]" /&gt; &lt;/Configuration&gt; </code></pre> <p>So, I put this into a textarea, where it looks like this to the user:</p> <pre><code>&lt;Configuration&gt; &lt;Validator Expression="[^&lt;]" /&gt; &lt;/Configuration&gt; </code></pre> <p>So the user makes a slight modification and submits the changes back. On the web server, the response string looks like:</p> <pre><code>&lt;Configuration&gt; &lt;Validator Expression="[^&lt;]" /&gt; &lt;Validator Expression="[^&amp;]" /&gt; &lt;/Configuration&gt; </code></pre> <p>So, the user added another validator thingie, and now BOTH have attributes with illegal characters. If I try to load this into any XML object, it throws an exception because &lt; and &amp; are not valid within a text string. I CANNOT CANNOT CANNOT CANNOT use any kind of encoding function, as it encodes the entire bloody thing:</p> <p>var result = Server.HttpEncode(editedConfig);</p> <p>results in </p> <pre><code>&amp;lt;Configuration&amp;gt; &amp;lt;Validator Expression="[^&amp;lt;]" /&amp;gt; &amp;lt;Validator Expression="[^&amp;amp;]" /&amp;gt; &amp;lt;/Configuration&amp;gt; </code></pre> <p>This is NOT valid XML. If I try to load this into an XML element of any kind I will be hit by a falling anvil. I don't like falling anvils. </p> <p>SO, the question remains... Is the ONLY way I can get this string XML ready for parsing into an XML object is by using regex replaces? Is there any way to "turn off constraints" when I load? How do you get around this???</p> <hr> <p>One last response and then wiki-izing this, as I don't think there is a valid answer.</p> <p>The XML I place in the textarea IS valid, escaped XML. The process of 1) putting it in the text area 2) sending it to the client 3) displaying it to the client 4) submitting the form it's in 5) sending it back to the server and 6) retrieving the value from the form REMOVES ANY AND ALL ESCAPES. </p> <p>Let me say this again: I'M not un-escaping ANYTHING. Just displaying it in the browser does this!</p> <p>Things to mull over: Is there a way to prevent this un-escaping from happening in the first place? Is there a way to take almost-valid XML and "clean" it in a safe manner?</p> <hr> <p>This question now has a bounty on it. To collect the bounty, you demonstrate how to edit VALID XML in a browser window WITHOUT a 3rd party/open source tool that doesn't require me to use regex to escape attribute values manually, that doesn't require users to escape their attributes, and that doesn't fail when roundtripping (&amp;amp;amp;amp;amp;etc;)</p>
[ { "answer_id": 244299, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>Erm … <em>How</em> do you serialize? Usually, the XML serializer should never produce invalid XML.</p>\n\n<p>/EDIT in response to your update: Do <strong>not</strong> display invalid XML to your user to edit! Instead, display the properly escaped XML in the TextBox. Repairing broken XML isn't fun and I actually see no reason not to display/edit the XML in a valid, escaped form.</p>\n\n<p>Again I could ask: <em>how</em> do you display the XML in the TextBox? You seem to intentionally unescape the XML at some point.</p>\n\n<p>/EDIT in response to your latest comment: Well yes, obviously, since the it can contain HTML. You need to escape your XML properly before writing it out into an HTML page. With that, I mean the <em>whole</em> XML. So this:</p>\n\n<pre><code>&lt;foo mean-attribute=\"&amp;lt;\"&gt;\n</code></pre>\n\n<p>becomes this:</p>\n\n<pre><code>&amp;lt;foo mean-attribute=\"&amp;amp;&amp;lt;\"&amp;gt;\n</code></pre>\n" }, { "answer_id": 244330, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "<p>This special character - \"&lt;\" - should have replaced with other characters so that your XML will be valid. Check this link for XML special characters:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references</a></p>\n\n<p>Try also to encode your TextBlock content before sending it to the deserializer:</p>\n\n<pre><code>HttpServerUtility utility = new HttpServerUtility();\nstring encodedText = utility.HtmlEncode(text);\n</code></pre>\n" }, { "answer_id": 244358, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>As you say, the normal serializer should escape everything for you. </p>\n\n<p>The problem, then, is the text block: you need to handle anything passed through the textblock yourself. </p>\n\n<p>You might try HttpUtility.HtmlEncode(), but I think the simplest method is to just encase anything you pass through the text block in a CDATA section.</p>\n\n<p>Normally of course I would want everything properly escaped rather than relying on the CDATA \"crutch\", but I would also want to use the built-in tools to do the escaping. For something that is edited in it's \"hibernated\" state by a user, I think CDATA might be the way to go.</p>\n\n<p>Also see this earlier question:<br>\n<a href=\"https://stackoverflow.com/questions/157646/best-way-to-encode-text-data-for-xml\">Best way to encode text data for XML</a></p>\n\n<hr>\n\n<p><strong>Update</strong><br>\nBased on a comment to another response, I've realized you're showing the users the markup, not just the contents. Xml parsers are, well, picky. I think the best thing you could do in this case is to check for well-formedness <em>before</em> accepting the edited xml. </p>\n\n<p>Perhaps try to automatically correct certain kinds of errors (like bad ampersands from my linked question), but then get the line number and column number of the first validation error from the .Net xml parser and use that to show users where their mistake is until they give you something acceptable. Bonus points if you also validate against a schema.</p>\n" }, { "answer_id": 244571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Is this really my only option? Isn't this a common enough problem that it has a solution somewhere in the framework?</p>\n\n<pre><code>private string EscapeAttributes(string configuration)\n{\n var lt = @\"(?&lt;=\\w+\\s*=\\s*\"\"[^\"\"]*)&lt;(?=[^\"\"]*\"\")\";\n configuration = Regex.Replace(configuration, lt, \"&amp;lt;\");\n\n return configuration;\n}\n</code></pre>\n\n<p>(edit: deleted ampersand replacement as it causes problems roundtripping)</p>\n" }, { "answer_id": 246652, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "<p>Of course when you put entity references inside a textarea they come out unescaped. Textareas aren't magic, you have to &escape; everything you put in them just like every other element. Browsers might <em>display</em> a raw '&lt;' in a textarea, but only because they're trying to clean up your mistakes.</p>\n\n<p>So if you're putting editable XML in a textarea, you need to escape the attribute value once to make it valid XML, and then you have to escape the whole XML again to make it valid HTML. The final source you want to appear in the page would be:</p>\n\n<pre><code>&lt;textarea name=\"somexml\"&gt;\n &amp;lt;Configuration&amp;gt;\n &amp;lt;Validator Expression=\"[^&amp;amp;lt;]\" /&amp;gt;\n &amp;lt;Validator Expression=\"[^&amp;amp;amp;]\" /&amp;gt;\n &amp;lt;/Configuration&amp;gt;\n&lt;/textarea&gt;\n</code></pre>\n\n<p>Question is based on a misunderstanding of the content model of the textarea element - a validator would have picked up the problem right away.</p>\n\n<p>ETA re comment: Well, what problem remains? That's the issue on the serialisation side. All that remains is parsing it back in, and for that you have to assume the user can create well-formed XML.</p>\n\n<p>Trying to parse non-well-formed XML, in order to allow errors like having '&lt;' or '&amp;' unescaped in an attribute value is a loss, totally against how XML is supposed to work. If you can't trust your users to write well-formed XML, give them an easier non-XML interface, such as a simple newline-separated list of regexp strings.</p>\n" }, { "answer_id": 486327, "author": "Dan McClain", "author_id": 53587, "author_profile": "https://Stackoverflow.com/users/53587", "pm_score": 1, "selected": false, "text": "<p>You could take a look at something like <a href=\"http://tinymce.moxiecode.com/\" rel=\"nofollow noreferrer\">TinyMCE</a>, which allows you to edit html in a rich text box. If you can't configure it to do exactly what you want, you could use it as inspiration.</p>\n" }, { "answer_id": 492890, "author": "13ren", "author_id": 50979, "author_profile": "https://Stackoverflow.com/users/50979", "pm_score": 1, "selected": false, "text": "<p>Note: firefox (in my test) does not unescape in text areas as you describe. Specifically, this code:</p>\n\n<pre><code>&lt;textarea cols=\"80\" rows=\"10\" id=\"1\"&gt;&lt;/textarea&gt;\n\n&lt;script&gt;\nelem = document.getElementById(\"1\");\n\nelem.value = '\\\n&lt;Configuration&gt;\\n\\\n &lt;Validator Expression=\"[^&amp;lt;]\" /&gt;\\n\\\n&lt;/Configuration&gt;\\\n'\nalert(elem.value);\n&lt;/script&gt;\n</code></pre>\n\n<p>Is alerted and displayed to the user <em>unchanged</em>, as:</p>\n\n<pre><code>&lt;Configuration&gt;\n &lt;Validator Expression=\"[^&amp;lt;]\" /&gt;\n&lt;/Configuration&gt;\n</code></pre>\n\n<p>So maybe one (un-viable?) solution is for your users to use firefox.</p>\n\n<hr>\n\n<p>It seems two parts to your question have been revealed:</p>\n\n<p>1 <strong>XML that you display is getting unescaped.</strong></p>\n\n<p>For example, \"<code>&amp;lt;</code>\" is unescaped as \"&lt;\". But since \"&lt;\" is also unescaped as \"&lt;\", information is lost and you can't get it back.</p>\n\n<p>One solution is for you to escape all the \"<code>&amp;</code>\" characters, so that \"<code>&amp;lt;</code>\" becomes \"<code>&amp;amp;lt;</code>\". This will then be unescaped by the textarea as \"<code>&amp;lt;</code>\". When you read it back, it will be as it was in the first place. (I'm assuming that the textarea actually changes the string, but firefox isn't behaving as you report, so I can't check this)</p>\n\n<p>Another solution (mentioned already I think) is to build/buy/borrow a custom text area (not bad if simple, but there's all the editing keys, ctrl-C, ctrl-shift-left and so on).</p>\n\n<p>2 <strong>You would like users to not have to bother escaping.</strong></p>\n\n<p>You're in escape-hell:</p>\n\n<p>A regex replace will mostly work... but how can you reliably detect the end quote (\"), when the user might (legitimately, within the terms you've given) enter :</p>\n\n<pre><code>&lt;Configuration&gt;\n &lt;Validator Expression=\"[^\"&lt;]\" /&gt;\n&lt;/Configuration&gt;\n</code></pre>\n\n<p>Looking at it from the point of view of the regex syntax, it also can't tell whether the final \" is part of the regex, or the end of it. Regex syntax usually solves this problem with an explicit terminator eg:</p>\n\n<pre><code>/[^\"&lt;]/\n</code></pre>\n\n<p>If users used this syntax (with the terminator), and you wrote a parser for it, then you could determine when the regex has ended, and therefore that the next \" character is not part of the regex, but part of the XML, and therefore which parts need to be escaped. I'm not saying you should this! I'm saying it's theoretically possible. It's pretty far from quick and dirty.</p>\n\n<p>BTW: The same problem arises for text within an element. The following is legitimate, within the terms you've given, but has the same parsing problems:</p>\n\n<pre><code>&lt;Configuration&gt;\n &lt;Expression&gt;&lt;/Expression&gt;&lt;/Expression&gt;\n&lt;/Configuration&gt;\n</code></pre>\n\n<p>The basic rule in a syntax that allows \"any text\" is that the delimiter <em>must</em> be escaped, (e.g. \" or &lt;), so that the end can be recognized. Most syntax also escapes a bunch of other stuff, for convenience/inconvenience. (<em>EDIT</em> it will need to have an escape for the escape character itself: for XML, it is \"<code>&amp;</code>\", which when literal is escaped as \"<code>&amp;amp;</code>\" For regex, it is the C/unix-style \"<code>\\</code>\", which when literal is escaped as \"<code>\\\\</code>\").</p>\n\n<p>Nest syntaxes, and you're in escape-hell.</p>\n\n<p>One simple solution for you is to tell your users: this is a <strong>quick</strong> and <strong>dirty</strong> configuration editor, so you're not getting any fancy \"no need to escape\" mamby-pamby:</p>\n\n<ul>\n<li>List the characters and escapes next\nto the text area, eg: \"&lt;\" as\n\"<code>&amp;lt</code>\".</li>\n<li>For XML that won't\nvalidate, show them the list again.</li>\n</ul>\n\n<hr>\n\n<p>Looking back, I see <a href=\"https://stackoverflow.com/questions/244285/how-the-heck-can-you-edit-valid-xml-in-a-webpage/246652#246652\">bobince</a> gave the same basic answer before me.</p>\n" }, { "answer_id": 522986, "author": "13ren", "author_id": 50979, "author_profile": "https://Stackoverflow.com/users/50979", "pm_score": 1, "selected": false, "text": "<p>Inserting CDATA around all text would give you another escape mechanism that would (1) save users from manually escaping, and (2) enable the text that was automatically unescaped by the textarea to be read back correctly.</p>\n\n<pre><code> &lt;Configuration&gt;\n &lt;Validator Expression=\"&lt;![CDATA[ [^&lt;] ]]&gt;\" /&gt;\n &lt;/Configuration&gt;\n</code></pre>\n\n<p>:-)</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got to get a quick and dirty configuration editor up and running. The flow goes something like this: configuration (POCOs on server) are serialized to XML. The XML is well formed at this point. The configuration is sent to the web server in XElements. On the web server, the XML (Yes, ALL OF IT) is dumped into a textarea for editing. The user edits the XML directly in the webpage and clicks Submit. In the response, I retrieve the altered text of the XML configuration. At this point, ALL escapes have been reverted by the process of displaying them in a webpage. I attempt to load the string into an XML object (XmlElement, XElement, whatever). KABOOM. The problem is that serialization escapes attribute strings, but this is lost in translation along the way. For example, let's say I have an object that has a regex. Here's the configuration as it comes to the web server: ``` <Configuration> <Validator Expression="[^&lt;]" /> </Configuration> ``` So, I put this into a textarea, where it looks like this to the user: ``` <Configuration> <Validator Expression="[^<]" /> </Configuration> ``` So the user makes a slight modification and submits the changes back. On the web server, the response string looks like: ``` <Configuration> <Validator Expression="[^<]" /> <Validator Expression="[^&]" /> </Configuration> ``` So, the user added another validator thingie, and now BOTH have attributes with illegal characters. If I try to load this into any XML object, it throws an exception because < and & are not valid within a text string. I CANNOT CANNOT CANNOT CANNOT use any kind of encoding function, as it encodes the entire bloody thing: var result = Server.HttpEncode(editedConfig); results in ``` &lt;Configuration&gt; &lt;Validator Expression="[^&lt;]" /&gt; &lt;Validator Expression="[^&amp;]" /&gt; &lt;/Configuration&gt; ``` This is NOT valid XML. If I try to load this into an XML element of any kind I will be hit by a falling anvil. I don't like falling anvils. SO, the question remains... Is the ONLY way I can get this string XML ready for parsing into an XML object is by using regex replaces? Is there any way to "turn off constraints" when I load? How do you get around this??? --- One last response and then wiki-izing this, as I don't think there is a valid answer. The XML I place in the textarea IS valid, escaped XML. The process of 1) putting it in the text area 2) sending it to the client 3) displaying it to the client 4) submitting the form it's in 5) sending it back to the server and 6) retrieving the value from the form REMOVES ANY AND ALL ESCAPES. Let me say this again: I'M not un-escaping ANYTHING. Just displaying it in the browser does this! Things to mull over: Is there a way to prevent this un-escaping from happening in the first place? Is there a way to take almost-valid XML and "clean" it in a safe manner? --- This question now has a bounty on it. To collect the bounty, you demonstrate how to edit VALID XML in a browser window WITHOUT a 3rd party/open source tool that doesn't require me to use regex to escape attribute values manually, that doesn't require users to escape their attributes, and that doesn't fail when roundtripping (&amp;amp;amp;amp;etc;)
Erm … *How* do you serialize? Usually, the XML serializer should never produce invalid XML. /EDIT in response to your update: Do **not** display invalid XML to your user to edit! Instead, display the properly escaped XML in the TextBox. Repairing broken XML isn't fun and I actually see no reason not to display/edit the XML in a valid, escaped form. Again I could ask: *how* do you display the XML in the TextBox? You seem to intentionally unescape the XML at some point. /EDIT in response to your latest comment: Well yes, obviously, since the it can contain HTML. You need to escape your XML properly before writing it out into an HTML page. With that, I mean the *whole* XML. So this: ``` <foo mean-attribute="&lt;"> ``` becomes this: ``` &lt;foo mean-attribute="&amp;&lt;"&gt; ```
244,326
<p>I was wondering if it is possible to do something like this:</p> <pre><code> &lt;uc1:TestControl ID="TestControl1" runat="server"&gt; &lt;div&gt;More random HTML, etc...&lt;/div&gt; &lt;/uc1:TestControl&gt; </code></pre> <p>I got an error of "Type 'System.Web.UI.UserControl' does not have a public property named 'div'.". Doing a little research, I found I could add the following property to the server control:</p> <pre><code>[ParseChildren(false)] public partial class TestControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } </code></pre> <p>Is it possible to read the content from an ASP.NET control?</p> <p>Edit: Changed wording to reflect that I am curious if you can do this with either a server or user control</p>
[ { "answer_id": 244353, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": true, "text": "<p>In a server control, you would create <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.aspx\" rel=\"nofollow noreferrer\">a property that implements ITemplate</a> to contain that content. I'm not positive whether that is possible in a user control, but it may be.</p>\n" }, { "answer_id": 741881, "author": "DevMania", "author_id": 70909, "author_profile": "https://Stackoverflow.com/users/70909", "pm_score": 0, "selected": false, "text": "<p>yeah it is possible</p>\n\n<p>check this MSDN Article about creating templated user controls, plus you can add [ParseChildren(false)] to the user control class so you can see them from the page holding them.\n<a href=\"http://msdn.microsoft.com/en-us/library/36574bf6.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/36574bf6.aspx</a></p>\n\n<p>hope this helps.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
I was wondering if it is possible to do something like this: ``` <uc1:TestControl ID="TestControl1" runat="server"> <div>More random HTML, etc...</div> </uc1:TestControl> ``` I got an error of "Type 'System.Web.UI.UserControl' does not have a public property named 'div'.". Doing a little research, I found I could add the following property to the server control: ``` [ParseChildren(false)] public partial class TestControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } } ``` Is it possible to read the content from an ASP.NET control? Edit: Changed wording to reflect that I am curious if you can do this with either a server or user control
In a server control, you would create [a property that implements ITemplate](http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.aspx) to contain that content. I'm not positive whether that is possible in a user control, but it may be.
244,329
<p>Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause &amp; I was hoping you all could help.</p> <p>We have a system that looks up latitude &amp; longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat &amp; long of a zip code tend to change less often than we release.</p> <p>Anyway, the hash is surrounded by a class that has a "get" and "add" method that are both synchronized. We access this class as a singleton.</p> <p>I'm not claiming this is the best setup, but it's where we're at. (I plan to change to wrap the Map in a Collections.synchronizedMap() call ASAP.)</p> <p>We use this cache in a multi-threaded environment, where we thread 2 calls for 2 zips (so we can calculate the distance between the two). These sometimes happen at very nearly the same time, so its very possible that both calls access the map at the same time.</p> <p>Just recently we had an incident where two different zip codes returned the same value. Assuming that the initial values were actually different, is there any way that writing the values into the Map would cause the same value to be written for two different keys? Or, is there any way that 2 "gets" could cross wires and accidentally return the same value?</p> <p>The only other explanation I have is that the initial data was corrupt (wrong values), but it seems very unlikely.</p> <p>Any ideas would be appreciated. Thanks, Peter</p> <p>(PS: Let me know if you need more info, code, etc.)</p> <pre><code>public class InMemoryGeocodingCache implements GeocodingCache { private Map cache = new HashMap(); private static GeocodingCache instance = new InMemoryGeocodingCache(); public static GeocodingCache getInstance() { return instance; } public synchronized LatLongPair get(String zip) { return (LatLongPair) cache.get(zip); } public synchronized boolean has(String zip) { return cache.containsKey(zip); } public synchronized void add(String zip, double lat, double lon) { cache.put(zip, new LatLongPair(lat, lon)); } } public class LatLongPair { double lat; double lon; LatLongPair(double lat, double lon) { this.lat = lat; this.lon = lon; } public double getLatitude() { return this.lat; } public double getLongitude() { return this.lon; } } </code></pre>
[ { "answer_id": 244352, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 3, "selected": false, "text": "<p>Why it's happening is hard to tell. More code could help.</p>\n\n<p>You should probably just be using a ConcurrentHashMap anyway. This will be more efficient, in general, than a synchronized Map. You don't synchronize access to it, it handles it internally (more efficiently than you could).</p>\n" }, { "answer_id": 244379, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>One thing to look out for is if the key or the value might be changing, for instance if instead of making a new object for each insertion, you're just changing the values of an existing object and re-inserting it.</p>\n\n<p>You also want to make sure that the key object defines both hashCode and equals in such a way that you don't violate the HashMap contract (ie if equals returns true, the hashCodes need to be the same, but not necessarily vice versa).</p>\n" }, { "answer_id": 244667, "author": "james", "author_id": 32155, "author_profile": "https://Stackoverflow.com/users/32155", "pm_score": 2, "selected": false, "text": "<p>is it possible the LatLonPair is being modified? I'd suggest making the lat and lon fields final so that they are not accidentally being modified elsewhere in the code.</p>\n\n<p>note, you should also make your singleton \"instance\" and the map reference \"cache\" final.</p>\n" }, { "answer_id": 244819, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 3, "selected": false, "text": "<p>The code looks correct. </p>\n\n<p>The only concern is that lat and lon are package visible, so the following is possible for the same package code:</p>\n\n<pre><code>LatLongPair llp = InMemoryGeocodingCache.getInstance().get(ZIP1);\nllp.lat = x;\nllp.lon = y;\n</code></pre>\n\n<p>which will obviously modify the in-cache object.</p>\n\n<p>So make lat and lon final too.</p>\n\n<p>P.S. Since your key (zip-code) is unique and small, there is no need to compute hash on every operation. It's easier to use TreeMap (wrapped into Collections.synchronizedMap()).</p>\n\n<p>P.P.S. Practical approach: write a test for two threads doing put/get operations in never-ending loop, validating the result on every get. You would need a multi-CPU machine for that though.</p>\n" }, { "answer_id": 244832, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 2, "selected": false, "text": "<p>James is correct. Since you are handing back an Object its internals could be modified and anything holding a reference to that Object (Map) will reflect that change. Final is a good answer.</p>\n" }, { "answer_id": 245599, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 0, "selected": false, "text": "<p>I don't really see anything wrong with the code you posted that would cause the problem you described. My guess would be that it's a problem with the client of your geo-code cache that has problems.</p>\n\n<p>Other things to consider (some of these are pretty obvious, but I figured I'd point them out anyway):</p>\n\n<ol>\n<li>Which two zip codes were you having problems with? Are you sure they don't have identical geocodes in the source system?</li>\n<li>Are you sure you aren't accidentally comparing two identical zip codes?</li>\n</ol>\n" }, { "answer_id": 268376, "author": "Michael Rutherfurd", "author_id": 33889, "author_profile": "https://Stackoverflow.com/users/33889", "pm_score": 0, "selected": false, "text": "<p>The presence of the <strong>has(String ZIP)</strong> method implies that you have something like the following in your code:</p>\n\n<pre><code>GeocodingCache cache = InMemoryGeocodingCache.getInstance();\n\nif (!cache.has(ZIP)) {\n cache.add(ZIP, x, y);\n}\n</code></pre>\n\n<p>Unfortunately this opens you up to sync problems between the has() returning false and the add() adding which <em>could</em> result in the issue you described.</p>\n\n<p>A better solution would be to move the check inside the add method so the check and update are covered by the same lock like: </p>\n\n<pre><code>public synchronized void add(String zip, double lat, double lon) {\n if (cache.containsKey(zip)) return;\n cache.put(zip, new LatLongPair(lat, lon));\n}\n</code></pre>\n\n<p>The other thing I should mention is that if you are using <strong>getInstance()</strong> as a singleton you should have a private constructor to stop the possibility of additional caches being created using <strong>new InMemoryGeocodingCache()</strong>.</p>\n" }, { "answer_id": 19983126, "author": "stones333", "author_id": 989857, "author_profile": "https://Stackoverflow.com/users/989857", "pm_score": 0, "selected": false, "text": "<p>Here is the java doc on HashMap:</p>\n\n<p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html\" rel=\"nofollow\">http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html</a></p>\n\n<p>Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be \"wrapped\" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:</p>\n\n<p>Map m = Collections.synchronizedMap(new HashMap(...));</p>\n\n<p><strong>Or better, use java.util.concurrent.ConcurrentHashMap</strong></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7773/" ]
Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help. We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release. Anyway, the hash is surrounded by a class that has a "get" and "add" method that are both synchronized. We access this class as a singleton. I'm not claiming this is the best setup, but it's where we're at. (I plan to change to wrap the Map in a Collections.synchronizedMap() call ASAP.) We use this cache in a multi-threaded environment, where we thread 2 calls for 2 zips (so we can calculate the distance between the two). These sometimes happen at very nearly the same time, so its very possible that both calls access the map at the same time. Just recently we had an incident where two different zip codes returned the same value. Assuming that the initial values were actually different, is there any way that writing the values into the Map would cause the same value to be written for two different keys? Or, is there any way that 2 "gets" could cross wires and accidentally return the same value? The only other explanation I have is that the initial data was corrupt (wrong values), but it seems very unlikely. Any ideas would be appreciated. Thanks, Peter (PS: Let me know if you need more info, code, etc.) ``` public class InMemoryGeocodingCache implements GeocodingCache { private Map cache = new HashMap(); private static GeocodingCache instance = new InMemoryGeocodingCache(); public static GeocodingCache getInstance() { return instance; } public synchronized LatLongPair get(String zip) { return (LatLongPair) cache.get(zip); } public synchronized boolean has(String zip) { return cache.containsKey(zip); } public synchronized void add(String zip, double lat, double lon) { cache.put(zip, new LatLongPair(lat, lon)); } } public class LatLongPair { double lat; double lon; LatLongPair(double lat, double lon) { this.lat = lat; this.lon = lon; } public double getLatitude() { return this.lat; } public double getLongitude() { return this.lon; } } ```
Why it's happening is hard to tell. More code could help. You should probably just be using a ConcurrentHashMap anyway. This will be more efficient, in general, than a synchronized Map. You don't synchronize access to it, it handles it internally (more efficiently than you could).
244,340
<p>I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?</p>
[ { "answer_id": 253897, "author": "flxkid", "author_id": 13036, "author_profile": "https://Stackoverflow.com/users/13036", "pm_score": 0, "selected": false, "text": "<p>From what I can tell, DCs in python are abstracted due to platform variation. So a device context in python doesn't directly map to a device context in Windows even though many of the methods are direct Windows method calls. To make this happen it appears you would need to make your own DelegateDC class or something similar that is intended just for Windows so that you could set the DC handle directly.</p>\n\n<p>There might also be some way to attach a wxWindow to the window handle after which you could get a wxWindowDC from the wxWindow...can't figure this out though.</p>\n" }, { "answer_id": 1821168, "author": "FogleBird", "author_id": 90308, "author_profile": "https://Stackoverflow.com/users/90308", "pm_score": 2, "selected": true, "text": "<p>I downloaded the wxWidgets source and dug around, and I think this will work.</p>\n\n<p>You need the handle (HWND) for the external window, not the DC.</p>\n\n<pre><code>window = wx.Frame(None, -1, '')\nwindow.AssociateHandle(hwnd)\ndc = wx.WindowDC(window)\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13036/" ]
I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long. I need to blit this DC into a memory DC in python. The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns. None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell. This of course keeps me from doing my blit. Is there any way to do this?
I downloaded the wxWidgets source and dug around, and I think this will work. You need the handle (HWND) for the external window, not the DC. ``` window = wx.Frame(None, -1, '') window.AssociateHandle(hwnd) dc = wx.WindowDC(window) ```
244,345
<p>I was watching Rob Connerys webcasts on the MVCStoreFront App, and I noticed he was unit testing even the most mundane things, things like:</p> <pre><code>public Decimal DiscountPrice { get { return this.Price - this.Discount; } } </code></pre> <p>Would have a test like:</p> <pre><code>[TestMethod] public void Test_DiscountPrice { Product p = new Product(); p.Price = 100; p.Discount = 20; Assert.IsEqual(p.DiscountPrice,80); } </code></pre> <p>While, I am all for unit testing, I sometimes wonder if this form of test first development is really beneficial, for example, in a real process, you have 3-4 layers above your code (Business Request, Requirements Document, Architecture Document), where the actual defined business rule (Discount Price is Price - Discount) could be misdefined.</p> <p>If that's the situation, your unit test means nothing to you.</p> <p>Additionally, your unit test is another point of failure:</p> <pre><code>[TestMethod] public void Test_DiscountPrice { Product p = new Product(); p.Price = 100; p.Discount = 20; Assert.IsEqual(p.DiscountPrice,90); } </code></pre> <p>Now the test is flawed. Obviously in a simple test, it's no big deal, but say we were testing a complicated business rule. What do we gain here?</p> <p>Fast forward two years into the application's life, when maintenance developers are maintaining it. Now the business changes its rule, and the test breaks again, some rookie developer then fixes the test incorrectly...we now have another point of failure.</p> <p>All I see is more possible points of failure, with no real beneficial return, if the discount price is wrong, the test team will still find the issue, how did unit testing save any work?</p> <p>What am I missing here? Please teach me to love TDD, as I'm having a hard time accepting it as useful so far. I want too, because I want to stay progressive, but it just doesn't make sense to me.</p> <p>EDIT: A couple people keep mentioned that testing helps enforce the spec. It has been my experience that the spec has been wrong as well, more often than not, but maybe I'm doomed to work in an organization where the specs are written by people who shouldn't be writing specs.</p>
[ { "answer_id": 244349, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": true, "text": "<p>First, testing is like security -- you can never be 100% sure you've got it, but each layer adds more confidence and a framework for more easily fixing the problems that remain.</p>\n\n<p>Second, you can break tests into subroutines which themselves can then be tested. When you have 20 similar tests, making a (tested) subroutine means your main test is 20 simple invocations of the subroutine which is much more likely to be correct.</p>\n\n<p>Third, some would argue that <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\" rel=\"noreferrer\">TDD</a> addresses this concern. That is, if you just write 20 tests and they pass, you're not completely confident that they are actually testing anything. But if each test you wrote initially <em>failed</em>, and then you fixed it, then you're much more confident that it's really testing your code. IMHO this back-and-forth takes more time than it's worth, but it is a process that tries to address your concern.</p>\n" }, { "answer_id": 244363, "author": "Jim C", "author_id": 21706, "author_profile": "https://Stackoverflow.com/users/21706", "pm_score": 2, "selected": false, "text": "<p>Test everything you can. Even trivial mistakes, like forgetting to convert meters to feet can have very expensive side effects. Write a test, write the code for it to check, get it to pass, move on. Who knows at some point in the future, someone may change the discount code. A test can detect the problem. </p>\n" }, { "answer_id": 244377, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "<p>Most unit tests, test assumptions. In this case, the discount price should be the price minus the discount. If your assumptions are wrong I bet your code is also wrong. And if you make a silly mistake, the test will fail and you will correct it.</p>\n\n<p>If the rules change, the test will fail and that is a good thing. So you have to change the test too in this case.</p>\n\n<p>As a general rule, if a test fails right away (and you don't use test first design), either the test or the code is wrong (or both if you are having a bad day). You use common sense (and possilby the specs) to correct the offending code and rerun the test.</p>\n\n<p>Like Jason said, testing is security. And yes, sometimes they introduce extra work because of faulty tests. But most of the time they are huge time savers. (And you have the perfect opportunity to punish the guy who breaks the test (we are talking rubber chicken)).</p>\n" }, { "answer_id": 244386, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<p>Unit tests are there so that your units (methods) do what you expect. Writing the test first forces you to think about what you expect <strong>before</strong> you write the code. Thinking before doing is always a good idea.</p>\n\n<p>Unit tests should reflect the business rules. Granted, there can be errors in the code, but writing the test first allows you to write it from the perspective of the business rule before any code has been written. Writing the test afterwards, I think, is more likely to lead to the error you describe because you <strong>know</strong> how the code implements it and are tempted just to make sure that the implementation is correct -- not that the intent is correct.</p>\n\n<p>Also, unit tests are only one form -- and the lowest, at that -- of tests that you should be writing. Integration tests and acceptance tests should also be written, the latter by the customer, if possible, to make sure that the system operates the way it is expected. If you find errors during this testing, go back and write unit tests (that fail) to test the change in functionality to make it work correctly, then change your code to make the test pass. Now you have regression tests that capture your bug fixes.</p>\n\n<p>[EDIT]</p>\n\n<p>Another thing that I have found with doing TDD. It almost forces good design by default. This is because highly coupled designs are nearly impossible to unit test in isolation. It doesn't take very long using TDD to figure out that using interfaces, inversion of control, and dependency injection -- all patterns that will improve your design and reduce coupling -- are really important for testable code.</p>\n" }, { "answer_id": 244409, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": false, "text": "<p>A test being wrong is unlikely to break your production code. At least, not any worse than having no test at all. So it's not a \"point of failure\": the tests don't have to be correct in order for the product to actually work. They might have to be correct before it's signed off as working, but the process of fixing any broken tests does not endanger your implementation code.</p>\n\n<p>You can think of tests, even trivial tests like these, as being a second opinion what the code is supposed to do. One opinion is the test, the other is the implementation. If they don't agree, then you know you have a problem and you look closer.</p>\n\n<p>It's also useful if someone in future wants to implement the same interface from scratch. They shouldn't have to read the first implementation in order to know what Discount means, and the tests act as an unambiguous back-up to any written description of the interface you may have.</p>\n\n<p>That said, you're trading off time. If there are other tests you could be writing using the time you save skipping these trivial tests, maybe they would be more valuable. It depends on your test setup and the nature of the application, really. If the Discount is important to the app, then you're going to catch any bugs in this method in functional testing anyway. All unit testing does is let you catch them at the point you're testing this unit, when the location of the error will be immediately obvious, instead of waiting until the app is integrated together and the location of the error <em>might</em> be less obvious.</p>\n\n<p>By the way, personally I wouldn't use 100 as the price in the test case (or rather, if I did then I'd add another test with another price). The reason is that someone in future might think that Discount is supposed to be a percentage. One purpose of trivial tests like this is to ensure that mistakes in reading the specification are corrected.</p>\n\n<p>[Concerning the edit: I think it's inevitable that an incorrect specification is a point of failure. If you don't know what the app is supposed to do, then chances are it won't do it. But writing tests to reflect the spec doesn't magnify this problem, it merely fails to solve it. So you aren't adding new points of failure, you're just representing the existing faults in code instead of <s>waffle</s> documentation.]</p>\n" }, { "answer_id": 244502, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 2, "selected": false, "text": "<p>Remember that the cost of fixing defects increases (exponentially) as the defects live through the development cycle. Yes, the testing team might catch the defect, but it will (usually) take more work to isolate and fix the defect from that point than if a unit test had failed, and it will be easier to introduce other defects while fixing it if you don't have unit tests to run. </p>\n\n<p>That's usually easier to see with something more than a trivial example ... and with trivial examples, well, if you somehow mess up the unit test, the person reviewing it will catch the error in the test or the error in the code, or both. (They are being reviewed, right?) As <a href=\"https://stackoverflow.com/questions/244345/how-do-you-unit-test-a-unit-test#244386\">tvanfosson points out</a>, unit testing is just one part of an SQA plan. </p>\n\n<p>In a sense, unit tests are insurance. They're no guarantee that you'll catch every defect, and it may seem at times like you're spending a lot of resources on them, but when they do catch defects that you can fix, you'll be spending a lot less than if you'd had no tests at all and had to fix all defects downstream.</p>\n" }, { "answer_id": 245142, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>All I see is more possible points of failure, with no real beneficial return, if the discount price is wrong, the test team will still find the issue, how did unit testing save any work?</p>\n </blockquote>\n</blockquote>\n\n<p>Unit testing isn't really supposed to save work, it's supposed to help you find and prevent bugs. It's <em>more</em> work, but it's the right kind of work. It's thinking about your code at the lowest levels of granularity and writing test cases that prove that it works under <em>expected</em> conditions, for a given set of inputs. It's isolating variables so you can save <em>time</em> by looking in the right place when a bug does present itself. It's <em>saving</em> that suite of tests so that you can use them again and again when you have to make a change down the road.</p>\n\n<p>I personally think that most methodologies are not many steps removed from <a href=\"http://en.wikipedia.org/wiki/Cargo_cult_programming#Cargo_cult_software_engineering\" rel=\"nofollow noreferrer\">cargo cult software engineering</a>, TDD included, but you don't have to adhere to strict TDD to reap the benefits of unit testing. Keep the good parts and throw out the parts that yield little benefit.</p>\n\n<p>Finally, the answer to your titular question \"<strong>How do you unit test a unit test?</strong>\" is that you shouldn't have to. Each unit test should be brain-dead simple. Call a method with a specific input and compare it to its expected output. If the specification for a method changes then you can expect that some of the unit tests for that method will need to change as well. That's one of the reasons that you do unit testing at such a low level of granularity, so only <em>some</em> of the unit tests have to change. If you find that tests for many different methods are changing for one change in a requirement, then you may not be testing at a fine enough level of granularity.</p>\n" }, { "answer_id": 249579, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 3, "selected": false, "text": "<p>When applying Test-Driven Development (TDD), one begins with a <strong>failing</strong> test. This step, that might seem unecessary, actually is here to verify the unit test is testing something. Indeed, if the test never fails, it brings no value and worse, leads to wrong confidence as you'll rely on a positive result that is not proving anything. </p>\n\n<p>When following this process strictly, all ''units'' are protected by the safety net the unit tests are making, even the most mundane. </p>\n\n<pre><code>Assert.IsEqual(p.DiscountPrice,90);\n</code></pre>\n\n<p>There is no reason the test evolves in that direction - or I'm missing something in your reasoning. When the price is 100 and the discount 20, the discount price is 80. This is like an invariant. </p>\n\n<p>Now imagine your software needs to support another kind of discount based on percentage, perhaps depending on the volume bought, your Product::DiscountPrice() method may become more complicated. And it is possible that introducing those changes breaks the simple discount rule we had initially. Then you'll see the value of this test which will detect the regression immediately.</p>\n\n<hr>\n\n<p>Red - Green - Refactor - this is to remember the essence of the TDD process.</p>\n\n<p><strong>Red</strong> refers to JUnit red bar when a tests fails.</p>\n\n<p><strong>Green</strong> is the color of JUnit progress bar when all tests pass.</p>\n\n<p><strong>Refactor</strong> under green condition: remove any dupliation, improve readability.</p>\n\n<hr>\n\n<p>Now to address your point about the \"3-4 layers above the code\", this is true in a traditional (waterfall-like) process, not when the development process is agile. And agile is the world where TDD is coming from ; TDD is the cornerstone of <a href=\"http://www.extremeprogramming.org/rules/testfirst.html\" rel=\"nofollow noreferrer\">eXtreme Programming</a>. </p>\n\n<p>Agile is about direct communication rather than thrown-over-the-wall requirement documents.</p>\n" }, { "answer_id": 255221, "author": "Ilja Preuß", "author_id": 11765, "author_profile": "https://Stackoverflow.com/users/11765", "pm_score": 3, "selected": false, "text": "<p>Unit testing works very similar to double entry book keeping. You state the same thing (business rule) in two quite different ways (as programmed rules in your production code, and as simple, representative examples in your tests). It's very unlikely that you make <em>the same</em> mistake in both, so if they both agree with each other, it's rather unlikely that you got it wrong.</p>\n\n<p>How is testing going to be worth the effort? In my experience in at least four ways, at least when doing test driven development:</p>\n\n<ul>\n<li>it helps you come up with a well decoupled design. You can only unit test code that is well decoupled;</li>\n<li>it helps you determine when you are done. Having to specify the needed behavior in tests helps to not build functionality that you don't actually need, and determine when the functionality is complete;</li>\n<li>it gives you a safety net for refactorings, which makes the code much more amenable to changes; and</li>\n<li>it saves you a lot of debugging time, which is horribly costly (I've heard estimates that traditionally, developers spend up to 80% of their time debugging).</li>\n</ul>\n" }, { "answer_id": 424623, "author": "Andrzej Doyle", "author_id": 45664, "author_profile": "https://Stackoverflow.com/users/45664", "pm_score": 3, "selected": false, "text": "<p>How does one <a href=\"http://www.ibm.com/developerworks/java/library/j-jester/\" rel=\"noreferrer\">test a test</a>? <a href=\"http://en.wikipedia.org/wiki/Mutation_testing\" rel=\"noreferrer\">Mutation testing</a> is a valuable technique that I have personally used to surprisingly good effect. Read the linked article for more details, and links to even more academic references, but in general it \"tests your tests\" by modifying your source code (changing \"x += 1\" to \"x -= 1\" for example) and then rerunning your tests, ensuring that at least one test fails. Any mutations that don't cause test failures are flagged for later investigation.</p>\n\n<p>You'd be surprised at how you can have 100% line and branch coverage with a set of tests that look comprehensive, and yet you can fundamentally change or even comment out a line in your source without any of the tests complaining. Often this comes down to not testing with the right inputs to cover all boundary cases, sometimes it's more subtle, but in all cases I was impressed with how much came out of it.</p>\n" }, { "answer_id": 649601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Even more automation can help here !\nYes, writing unit tests can be a lot of work, so use some tools to help you out.\nHave a look at something like Pex, from Microsoft, if you're using .Net\nIt will automatically create suites of unit tests for you by examining your code. It will come up with tests which give good coverage, trying to cover all paths through your code.</p>\n\n<p>Of course, just by looking at your code it can't know what you were actually trying to do, so it doesn't know if it's correct or not. But, it will generate interesting tests cases for you, and you can then examine them and see if it is behaving as you expect.</p>\n\n<p>If you then go further and write parameterized unit tests (you can think of these as contracts, really) it will generate specific tests cases from these, and this time it can know if something's wrong, because your assertions in your tests will fail.</p>\n" }, { "answer_id": 943161, "author": "cwash", "author_id": 59561, "author_profile": "https://Stackoverflow.com/users/59561", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>While, I am all for unit testing, I\n sometimes wonder if this form of test\n first development is really beneficial...</p>\n</blockquote>\n\n<p>Small, trivial tests like this can be the \"canary in the coalmine\" for your codebase, alerting of danger before it's too late. The trivial tests are useful to keep around because they help you get the interactions right. </p>\n\n<p>For example, think about a trivial test put in place to probe how to use an API you're unfamiliar with. If that test has any relevance to what you're doing in the code that uses the API \"for real\" it's useful to keep that test around. When the API releases a new version and you need to upgrade. You now have your assumptions about how you expect the API to behave recorded in an executable format that you can use to catch regressions.</p>\n\n<blockquote>\n <p>...[I]n a real process, you have 3-4\n layers above your code (Business\n Request, Requirements Document,\n Architecture Document), where the\n actual defined business rule (Discount\n Price is Price - Discount) could be\n misdefined. If that's the situation,\n your unit test means nothing to you.</p>\n</blockquote>\n\n<p>If you've been coding for years without writing tests it may not be immediately obvious to you that there is any value. But if you are of the mindset that the best way to work is \"release early, release often\" or \"agile\" in that you want the ability to deploy rapidly/continuously, then your test definitely means something. The only way to do this is by legitimizing every change you make to the code with a test. No matter how small the test, once you have a green test suite you're theoretically OK to deploy. See also \"continuous production\" and \"perpetual beta.\" </p>\n\n<p>You don't have to be \"test first\" to be of this mindset, either, but that generally is the most efficient way to get there. When you do TDD, you lock yourself into small two to three minute Red Green Refactor cycle. At no point are you not able to stop and leave and have a complete mess on your hands that will take an hour to debug and put back together.</p>\n\n<blockquote>\n <p>Additionally, your unit test is another\n point of failure... </p>\n</blockquote>\n\n<p>A successful test is one that demonstrates a failure in the system. A failing test will alert you to an error in the logic of the test or in the logic of your system. The goal of your tests is to break your code or prove one scenario works.</p>\n\n<p>If you're writing tests <em>after</em> the code, you run the risk of writing a test that is \"bad\" because in order to see that your test truly works, you need to see it both broken and working. When you're writing tests after the code, this means you have to \"spring the trap\" and introduce a bug into the code to see the test fail. Most developers are not only uneasy about this, but would argue it is a waste of time.</p>\n\n<blockquote>\n <p>What do we gain here?</p>\n</blockquote>\n\n<p>There is definitely a benefit to doing things this way. Michael Feathers defines \"legacy code\" as \"untested code.\" When you take this approach, you legitimize every change you make to your codebase. It's more rigorous than not using tests, but when it comes to maintaining a large codebase, it pays for itself.</p>\n\n<p>Speaking of Feathers, there are two great resources you should check out in regard to this:</p>\n\n<ul>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0131177052\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Working Effectively with Legacy Code</a></li>\n<li><a href=\"http://www.manning.com/baley/\" rel=\"noreferrer\">Brownfield Application Development in .NET</a></li>\n</ul>\n\n<p>Both of these explain how to work these types of practices and disciplines into projects that aren't \"Greenfield.\" They provide techniques for writing tests around tightly coupled components, hard wired dependencies, and things that you don't necessarily have control over. It's all about finding \"seams\" and testing around those.</p>\n\n<blockquote>\n <p>[I]f the discount price is wrong, the\n test team will still find the issue,\n how did unit testing save any work?</p>\n</blockquote>\n\n<p>Habits like these are like an investment. Returns aren't immediate; they build up over time. The alternative to not testing is essentially taking on debt of not being able to catch regressions, introduce code without fear of integration errors, or drive design decisions. The beauty is you legitimize every change introduced into your codebase.</p>\n\n<blockquote>\n <p>What am I missing here? Please teach\n me to love TDD, as I'm having a hard\n time accepting it as useful so far. I\n want too, because I want to stay\n progressive, but it just doesn't make\n sense to me.</p>\n</blockquote>\n\n<p>I look at it as a professional responsibility. It's an ideal to strive toward. But it is very hard to follow and tedious. If you care about it, and feel you shouldn't produce code that is not tested, you'll be able to find the will power to learn good testing habits. One thing that I do a lot now (as do others) is timebox myself an hour to write code without any tests at all, then have the discipline to throw it away. This may seem wasteful, but it's not really. It's not like that exercise cost a company physical materials. It helped me to understand the problem and how to write code in such a way that it is both of higher quality and testable.</p>\n\n<p>My advice would ultimately be that if you really don't have a desire to be good at it, then don't do it at all. Poor tests that aren't maintained, don't perform well, etc. can be worse than not having any tests. It's hard to learn on your own, and you probably won't love it, but it is going to be next to impossible to learn if you don't have a desire to do it, or can't see enough value in it to warrant the time investment.</p>\n\n<blockquote>\n <p>A couple people keep mentioned that\n testing helps enforce the spec. It has\n been my experience that the spec has\n been wrong as well, more often than\n not...</p>\n</blockquote>\n\n<p>A developer's keyboard is where the rubber meets the road. If the spec is wrong and you don't raise the flag on it, then it's highly probable you'll get blamed for it. Or at least your code will. The discipline and rigor involved in testing is difficult to adhere to. It's not at all easy. It takes practice, a lot of learning and a lot of mistakes. But eventually it does pay off. On a fast-paced, quickly changing project, it's the only way you can sleep at night, no matter if it slows you down.</p>\n\n<p>Another thing to think about here is that techniques that are fundamentally the same as testing have been proven to work in the past: \"clean room\" and \"design by contract\" both tend to produce the same types of \"meta\"-code constructs that tests do, and enforce those at different points. None of these techniques are silver bullets, and rigor is going to cost you ultimately in the scope of features you can deliver in terms of time to market. But that's not what it's about. It's about being able to maintain what you do deliver. And that's very important for most projects.</p>\n" }, { "answer_id": 1076159, "author": "cwash", "author_id": 59561, "author_profile": "https://Stackoverflow.com/users/59561", "pm_score": 1, "selected": false, "text": "<p>I've thought a bit about a good way to respond to this question, and would like to draw a parallel to the scientific method. IMO, you could rephrase this question, \"How do you experiment an experiment?\"</p>\n\n<p>Experiments verify empirical assumptions (hypotheses) about the physical universe. Unit tests will test assumptions about the state or behavior of the code they call. We can talk about the validity of an experiment, but that's because we know, through numerous other experiments, that something doesn't fit. It doesn't have both <em>convergent validity</em> and <em>empirical evidence</em>. We don't design a new experiment to test or verify the validity of <em>an experiment</em>, but we may design a <em>completely new experiment</em>.</p>\n\n<p>So <strong>like experiments</strong>, we don't describe the validity of a unit test based on whether or not it passes a unit test itself. Along with other unit tests, it describes the assumptions we make about the system it is testing. Also, like experiments, we try to remove as much complexity as we can from what we are testing. <em>\"As simple as possible, but no simpler.\"</em></p>\n\n<p><strong>Unlike experiments</strong>, we have a trick up our sleeve to verify our tests are valid other than just convergent validity. We can cleverly introduce a bug we know should be caught by the test, and see if the test does indeed fail. (If only we could do that in the real world, we'd depend much less on this convergent validity thing!) A more efficient way to do this is watch your test fail before implementing it (the red step in <em>Red, Green, Refactor</em>).</p>\n" }, { "answer_id": 1076882, "author": "Ray", "author_id": 117730, "author_profile": "https://Stackoverflow.com/users/117730", "pm_score": 2, "selected": false, "text": "<p>I see your point, but it's clearly overstated.</p>\n\n<p>Your argument is basically: Tests introduce failure. Therefore tests are bad/waste of time.</p>\n\n<p>While that may be true in some cases, it's hardly the majority.</p>\n\n<p>TDD assumes: More Tests = Less Failure.</p>\n\n<p>Tests are <strong>more likely</strong> to catch points of failure than introduce them.</p>\n" }, { "answer_id": 1225972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Even if you do not test your code, it will surely be tested in production by your users. Users are very creative in trying to crash your soft and finding even non-critical errors.</p>\n\n<p>Fixing bugs in production is much more costly than resolving issues in development phase.\nAs a side-effect, you will lose income because of an exodus of customers. You can count on 11 lost or not gained customers for 1 angry customer.</p>\n" }, { "answer_id": 2848474, "author": "Jonathan", "author_id": 208565, "author_profile": "https://Stackoverflow.com/users/208565", "pm_score": 1, "selected": false, "text": "<p>You need to use the correct paradigm when writing tests. </p>\n\n<ol>\n<li>Start by first writing your tests. </li>\n<li>Make sure they fail to start off with.</li>\n<li>Get them to pass.</li>\n<li>Code review before you checkin your code (make sure the tests are reviewed.)</li>\n</ol>\n\n<p>You cant always be sure but they improve overall tests.</p>\n" }, { "answer_id": 2848521, "author": "johnsyweb", "author_id": 78845, "author_profile": "https://Stackoverflow.com/users/78845", "pm_score": 2, "selected": false, "text": "<p>I see unit tests and production code as having a symbiotic relationship. Simply put: one tests the other. And both test the developer.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I was watching Rob Connerys webcasts on the MVCStoreFront App, and I noticed he was unit testing even the most mundane things, things like: ``` public Decimal DiscountPrice { get { return this.Price - this.Discount; } } ``` Would have a test like: ``` [TestMethod] public void Test_DiscountPrice { Product p = new Product(); p.Price = 100; p.Discount = 20; Assert.IsEqual(p.DiscountPrice,80); } ``` While, I am all for unit testing, I sometimes wonder if this form of test first development is really beneficial, for example, in a real process, you have 3-4 layers above your code (Business Request, Requirements Document, Architecture Document), where the actual defined business rule (Discount Price is Price - Discount) could be misdefined. If that's the situation, your unit test means nothing to you. Additionally, your unit test is another point of failure: ``` [TestMethod] public void Test_DiscountPrice { Product p = new Product(); p.Price = 100; p.Discount = 20; Assert.IsEqual(p.DiscountPrice,90); } ``` Now the test is flawed. Obviously in a simple test, it's no big deal, but say we were testing a complicated business rule. What do we gain here? Fast forward two years into the application's life, when maintenance developers are maintaining it. Now the business changes its rule, and the test breaks again, some rookie developer then fixes the test incorrectly...we now have another point of failure. All I see is more possible points of failure, with no real beneficial return, if the discount price is wrong, the test team will still find the issue, how did unit testing save any work? What am I missing here? Please teach me to love TDD, as I'm having a hard time accepting it as useful so far. I want too, because I want to stay progressive, but it just doesn't make sense to me. EDIT: A couple people keep mentioned that testing helps enforce the spec. It has been my experience that the spec has been wrong as well, more often than not, but maybe I'm doomed to work in an organization where the specs are written by people who shouldn't be writing specs.
First, testing is like security -- you can never be 100% sure you've got it, but each layer adds more confidence and a framework for more easily fixing the problems that remain. Second, you can break tests into subroutines which themselves can then be tested. When you have 20 similar tests, making a (tested) subroutine means your main test is 20 simple invocations of the subroutine which is much more likely to be correct. Third, some would argue that [TDD](http://en.wikipedia.org/wiki/Test-driven_development) addresses this concern. That is, if you just write 20 tests and they pass, you're not completely confident that they are actually testing anything. But if each test you wrote initially *failed*, and then you fixed it, then you're much more confident that it's really testing your code. IMHO this back-and-forth takes more time than it's worth, but it is a process that tries to address your concern.
244,367
<p>What is the correct way to setup a named pipe in C# across a network?</p> <p>Currently I have two machines, 'client' and 'server'.</p> <p>Server sets up its pipe in the following manner:</p> <pre><code>NamedPipeServerStream pipeServer = new NamedPipeServerStream( "pipe", PipeDirection.InOut, 10, PipeTransmissionMode.Byte, PipeOptions.None) pipeServer.WaitForConnection(); //... Read some data from the pipe </code></pre> <p>The client sets up its connection in the following manner:</p> <pre><code>NamedPipeClientStream pipeClient = new NamedPipeClientStream( "server", "pipe", PipeDirection.InOut); pipeClient.Connect(); //This line throws an exception //... Write some data to the pipe </code></pre> <p>The 'server' machine can be accessed on the network by going to "\\server".</p> <p>Whenever I run the program, I get a System.UnauthorizedAccessException that says "Access to the path is denied." The code works fine when I run the server and client on my local machine and attempt to connect to "." with the client.</p>
[ { "answer_id": 244391, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Look in the System.Runtime.Remoting namespace. IIRC, named pipes are one option for the protocol used by remoting channels.</p>\n" }, { "answer_id": 246399, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 2, "selected": false, "text": "<p>You need to set permissions on the NamedPipeServerStream so that the client will have permissions to access the pipe. </p>\n\n<p>I would look at the SetAccessControl method of your NamedPipeServerStream.</p>\n" }, { "answer_id": 1025806, "author": "Shiraz Bhaiji", "author_id": 86611, "author_profile": "https://Stackoverflow.com/users/86611", "pm_score": -1, "selected": true, "text": "<p>It is not possible to used named pipes between machines.</p>\n\n<p>\"The WCF-NetNamedPipe adapter provides cross-process communication on the <strong>same computer</strong>\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb226493.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb226493.aspx</a></p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341413/" ]
What is the correct way to setup a named pipe in C# across a network? Currently I have two machines, 'client' and 'server'. Server sets up its pipe in the following manner: ``` NamedPipeServerStream pipeServer = new NamedPipeServerStream( "pipe", PipeDirection.InOut, 10, PipeTransmissionMode.Byte, PipeOptions.None) pipeServer.WaitForConnection(); //... Read some data from the pipe ``` The client sets up its connection in the following manner: ``` NamedPipeClientStream pipeClient = new NamedPipeClientStream( "server", "pipe", PipeDirection.InOut); pipeClient.Connect(); //This line throws an exception //... Write some data to the pipe ``` The 'server' machine can be accessed on the network by going to "\\server". Whenever I run the program, I get a System.UnauthorizedAccessException that says "Access to the path is denied." The code works fine when I run the server and client on my local machine and attempt to connect to "." with the client.
It is not possible to used named pipes between machines. "The WCF-NetNamedPipe adapter provides cross-process communication on the **same computer**" <http://msdn.microsoft.com/en-us/library/bb226493.aspx>
244,381
<p>We are using Hibernate Spring MVC with OpenSessionInView filter. Here is a problem we are running into (pseudo code)</p> <pre><code>transaction 1 load object foo transaction 1 end update foo's properties (not calling session.save or session.update but only foo's setters) validate foo (using hibernate validator) if validation fails ? go back to edit screen transaction 2 (read only) load form backing objects from db transaction 2 end go to view else transaction 3 session.update(foo) transaction 3 end </code></pre> <p>the problem we have is if the validation fails foo is marked "dirty" in the hibernate session (since we use OpenSessionInView we only have one session throughout the http request), when we load the form backing objects (like a list of some entities using an HQL query), hibernate before performing the query checks if there are dirty objects in the session, it sees that foo is and flushes it, when transaction 2 is committed the updates are written to the database. The problem is that even though it is a read only transaction and even though foo wasn't updated in transaction 2 hibernate doesn't have knowledge of which object was updated in which transaction and doesn't flush only objects from that transaction. Any suggestions? did somebody ran into similar problem before</p> <p>Update: this post sheds some more light on the problem: <a href="http://brian.pontarelli.com/2007/04/03/hibernate-pitfalls-part-2/" rel="nofollow noreferrer">http://brian.pontarelli.com/2007/04/03/hibernate-pitfalls-part-2/</a></p>
[ { "answer_id": 244703, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 1, "selected": false, "text": "<p>You can run a get on foo to put it into the hibernate session, and then replace it with the object you created elsewhere. But for this to work, you have to know all the ids for your objects so that the ids will look correct to Hibernate.</p>\n" }, { "answer_id": 254342, "author": "Gareth Davis", "author_id": 31480, "author_profile": "https://Stackoverflow.com/users/31480", "pm_score": 1, "selected": false, "text": "<p>There are a couple of options here. First is that you don't actually need transaction 2 since the session is open you could just load the backing objects from the db, thus avoiding the dirty check on the session. The other option is to evict foo from the session after it is retrieved and later use session.merge() to reattach it when you what your changes to be stored.</p>\n\n<p>With hibernate it is important to understand what exactly is going on under the covers. At every commit boundary it will attempt to flush all changes to objects in the current session regardless of whether or not the changes where made in the current transaction or any transaction at all for that matter. This is way you don't actually need to call session.update() for any object that is already in the session.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 293111, "author": "Maxim", "author_id": 11587, "author_profile": "https://Stackoverflow.com/users/11587", "pm_score": 0, "selected": false, "text": "<p>What about using Session.clear() and/or Session.evict()?</p>\n" }, { "answer_id": 327319, "author": "cliff.meyers", "author_id": 41754, "author_profile": "https://Stackoverflow.com/users/41754", "pm_score": 0, "selected": false, "text": "<p>What about setting singleSession=false on the filter? That might put your operations into separate sessions so you don't have to deal with the 1st level cache issues. Otherwise you will probably want to detach/attach your objects manually as the user above suggests. You could also change the FlushMode on your Session if you don't want things being flushed automatically (FlushMode.MANUAL).</p>\n" }, { "answer_id": 1129151, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>There is a design issue here. Do you think an ORM is a transparent abstraction of your datastore, or do you think it's a set of data manipulation libraries? I would say that Hibernate is the former. Its whole reason for existing is to remove the distinction between your in-memory object state and your database state. It does provide low-level mechanisms to allow you to pry the two apart and deal with them separately, but by doing so you're removing a lot of Hibernate's value.</p>\n\n<p>So very simply - Hibernate = your database. If you don't want something persisted, don't change your persistent objects. </p>\n\n<p>Validate your data before you update your domain objects. By all means validate domain objects as well, but that's a last line of defense. If you do get a validation error on a persistent object, don't swallow the exception. Unless you prevent it, Hibernate will do the right thing, which is to close the session there and then.</p>\n" }, { "answer_id": 1792168, "author": "zmf", "author_id": 13285, "author_profile": "https://Stackoverflow.com/users/13285", "pm_score": 0, "selected": false, "text": "<p>Implement a service layer, take a look at spring's @Transactional annotation, and mark your methods as @Transactional(readOnly=true) where applicable. </p>\n\n<p>Your flush mode is probably set to auto, which means you don't really have control of when a DB commit happens.</p>\n\n<p>You could also set your flush mode to manual, and your services/repos will only try to synchronize the db with your app when you tell them to.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332/" ]
We are using Hibernate Spring MVC with OpenSessionInView filter. Here is a problem we are running into (pseudo code) ``` transaction 1 load object foo transaction 1 end update foo's properties (not calling session.save or session.update but only foo's setters) validate foo (using hibernate validator) if validation fails ? go back to edit screen transaction 2 (read only) load form backing objects from db transaction 2 end go to view else transaction 3 session.update(foo) transaction 3 end ``` the problem we have is if the validation fails foo is marked "dirty" in the hibernate session (since we use OpenSessionInView we only have one session throughout the http request), when we load the form backing objects (like a list of some entities using an HQL query), hibernate before performing the query checks if there are dirty objects in the session, it sees that foo is and flushes it, when transaction 2 is committed the updates are written to the database. The problem is that even though it is a read only transaction and even though foo wasn't updated in transaction 2 hibernate doesn't have knowledge of which object was updated in which transaction and doesn't flush only objects from that transaction. Any suggestions? did somebody ran into similar problem before Update: this post sheds some more light on the problem: <http://brian.pontarelli.com/2007/04/03/hibernate-pitfalls-part-2/>
You can run a get on foo to put it into the hibernate session, and then replace it with the object you created elsewhere. But for this to work, you have to know all the ids for your objects so that the ids will look correct to Hibernate.
244,390
<p>Right now, I have </p> <pre><code>SELECT gp_id FROM gp.keywords WHERE keyword_id = 15 AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id) </code></pre> <p>This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.</p> <p>What I'm trying to do is get the gp_id from gp.keywords where the the keywords table keyword_id column is a specific value and the practice_link is the practices table corresponds to the gp_id that I have, which is stored in the id column of that table.</p>
[ { "answer_id": 244405, "author": "SquareCog", "author_id": 15962, "author_profile": "https://Stackoverflow.com/users/15962", "pm_score": 1, "selected": false, "text": "<p><pre><code>\nselect k.gp_id \nfrom gp.keywords as k,\n gp.practices as p\nwhere\nkeyword_id=15\nand practice_link is not null\nand p.id=k.gp_id\n</pre></code></p>\n" }, { "answer_id": 244406, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT k.gp_id\nFROM gp.keywords k, gp.practices p\nWHERE \n p.id = k.gp_id.AND\n k.keyword_id = 15 AND\n p.practice_link is not null\n</code></pre>\n" }, { "answer_id": 244407, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT g.gp_id, p.practice_link FROM gp.keywords g, gp.practices p \nWHERE\ng.keyword_id = 15 AND p.practice_link IS NOT NULL AND p.id = g.gp_id\n</code></pre>\n" }, { "answer_id": 244411, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p>I'm not even sure that is valid SQL, so I'm surprised it is working at all:</p>\n\n<pre><code>SELECT gp_id\nFROM gp.keywords\nWHERE keyword_id = 15\n AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id)\n</code></pre>\n\n<p>How about this instead:</p>\n\n<pre><code>SELECT kw.gp_id, p.practice_link\nFROM gp.keywords AS kw\nINNER JOIN gp.practices AS p\n ON p.id = kw.gp_id\nWHERE kw.keyword_id = 15\n</code></pre>\n\n<p>I would steer clear of implicit joins as in the other examples. It only leads to tears later.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
Right now, I have ``` SELECT gp_id FROM gp.keywords WHERE keyword_id = 15 AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id) ``` This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows. What I'm trying to do is get the gp\_id from gp.keywords where the the keywords table keyword\_id column is a specific value and the practice\_link is the practices table corresponds to the gp\_id that I have, which is stored in the id column of that table.
I'm not even sure that is valid SQL, so I'm surprised it is working at all: ``` SELECT gp_id FROM gp.keywords WHERE keyword_id = 15 AND (SELECT practice_link FROM gp.practices WHERE practice_link IS NOT NULL AND id = gp_id) ``` How about this instead: ``` SELECT kw.gp_id, p.practice_link FROM gp.keywords AS kw INNER JOIN gp.practices AS p ON p.id = kw.gp_id WHERE kw.keyword_id = 15 ``` I would steer clear of implicit joins as in the other examples. It only leads to tears later.
244,392
<p>Here's the quick and skinny of my issue:</p> <pre>$("a").toggle(function() { /*function A*/ }, function() { /*function B*/ });</pre> <p>Inside <code>function A</code> a form is displayed. If the user successfully completes the form, the form is hidden again (returning to it's original state).</p> <p>Inside <code>function B</code> the same form is hidden.</p> <p>The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding. </p> <p>Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link <strong><em>twice</em></strong> before returning to the toggle state that displays the form.</p> <p>Is there anyway to programmatically reset the toggle switch to its initial state?</p>
[ { "answer_id": 244468, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 5, "selected": true, "text": "<p>jQuery has two <code>.toggle()</code> methods:</p>\n\n<p><a href=\"http://api.jquery.com/toggle/\" rel=\"nofollow noreferrer\"><code>.toggle()</code></a></p>\n\n<blockquote>\n <p>Toggles each of the set of matched\n elements. If they are shown, toggle\n makes them hidden. If they are hidden,\n toggle makes them shown.</p>\n</blockquote>\n\n<p><a href=\"https://api.jquery.com/toggle-event/\" rel=\"nofollow noreferrer\"><code>.toggle(even, odd)</code></a></p>\n\n<blockquote>\n <p>Toggle between two function calls every other click.</p>\n</blockquote>\n\n<p>In this case you want the first one. Something like this should do the trick:</p>\n\n<pre><code>$(\"a\").click(function() {\n $(\"#theForm\").toggle();\n});\n</code></pre>\n" }, { "answer_id": 244599, "author": "neezer", "author_id": 32154, "author_profile": "https://Stackoverflow.com/users/32154", "pm_score": 2, "selected": false, "text": "<p>Ahh, it's the simple things in life...</p>\n\n<p>I was using the latter definition of <code>toggle(even,odd);</code>, but I had forgot to include in my original description of the problem that my second toggle function was not only hiding the form, but destroying it as well.</p>\n\n<p><code>function A</code>: Ajax load the form into an appended div. Hide and destroy the div on a successful form post.</p>\n\n<p><code>function B</code>: Destroy the div.</p>\n\n<p>You both reminded me that <code>toggle();</code> only deals with the CSS property, and as such it is not well-suited to this task. But then I realized that I was unnecessarily re-loading the form on each \"odd\" state by destroying it when I was done, so I eventually came back to this:</p>\n\n<pre>$(\"link\").click(function() {\n if ($(this).siblings(\".form-div\").length == 0) {\n // form is not loaded; load and show the form; hide when done\n }\n else {\n $(this).siblings(\".form-div\").toggle();\n }\n});</pre>\n\n<p>...which does what I want it to do. Thanks for setting me straight about <code>toggle();</code>!</p>\n" }, { "answer_id": 1750472, "author": "Michal Zuber", "author_id": 213102, "author_profile": "https://Stackoverflow.com/users/213102", "pm_score": 3, "selected": false, "text": "<p>Here's what I used:</p>\n\n<pre><code>$(document).ready(function() {\n $('#listing_position').click(function() {\n\n var div_form = $('#listing_position_input');\n if (div_form.hasClass('hide')) {\n div_form.removeClass('hide');\n } else {\n div_form.addClass('hide');\n }\n }); \n});\n</code></pre>\n" }, { "answer_id": 4918065, "author": "xiatica", "author_id": 564811, "author_profile": "https://Stackoverflow.com/users/564811", "pm_score": 2, "selected": false, "text": "<p>Went with this one to avoid the additional hide/show class.\nI think this is more flexible than foxy's solution as you can add more functions within but don't quote me on that i'm a noob</p>\n\n<pre><code>$(\"#clickie\").click(function(){\n if ( $(\"#mydiv\").css(\"display\") == \"none\" ){\n $(\"#mydiv\").show();\n } else {\n $(\"#mydiv\").hide();\n}\n</code></pre>\n" }, { "answer_id": 8540165, "author": "Nicky Vandevoorde", "author_id": 698371, "author_profile": "https://Stackoverflow.com/users/698371", "pm_score": 5, "selected": false, "text": "<p>You can check the state of the toggle in jQuery by using <code>.is(\":hidden\")</code>. So in basic code what I used:</p>\n\n<pre><code>$(\"#div_clicked\").click(function() {\n if ($(\"#toggle_div\").is(\":hidden\")) {\n // do this\n } else {\n // do that\n}\n}); # add missing closing\n</code></pre>\n" }, { "answer_id": 27014328, "author": "Vishal Patel", "author_id": 2578899, "author_profile": "https://Stackoverflow.com/users/2578899", "pm_score": -1, "selected": false, "text": "<pre><code>$(\"#div_clicked\").click(function() {\n if ($(\"#toggle_div\").is(\":visible\")) {\n // do this\n } else {\n // do that\n}\n</code></pre>\n\n<p>Replace hidden with visible</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
Here's the quick and skinny of my issue: ``` $("a").toggle(function() { /*function A*/ }, function() { /*function B*/ }); ``` Inside `function A` a form is displayed. If the user successfully completes the form, the form is hidden again (returning to it's original state). Inside `function B` the same form is hidden. The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding. Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link ***twice*** before returning to the toggle state that displays the form. Is there anyway to programmatically reset the toggle switch to its initial state?
jQuery has two `.toggle()` methods: [`.toggle()`](http://api.jquery.com/toggle/) > > Toggles each of the set of matched > elements. If they are shown, toggle > makes them hidden. If they are hidden, > toggle makes them shown. > > > [`.toggle(even, odd)`](https://api.jquery.com/toggle-event/) > > Toggle between two function calls every other click. > > > In this case you want the first one. Something like this should do the trick: ``` $("a").click(function() { $("#theForm").toggle(); }); ```
244,408
<p>I've got two collections (generic Lists), let's call them ListA and ListB.</p> <p>In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in ListA. What's the best way of doing this? Is Linq to objects a nice fit? What algorithm would you use?</p> <p>Example</p> <p>ListA: ItemWithID1, ItemWithID2¨</p> <p>ListB: ItemWithID1, ItemWithID2, ItemWithID3, ItemWithID4</p> <p>EDIT: I forgot to mention in my original question that ListA and ListB doesn't contain the same types. So the only way to compare them is through the .Id property. Which invalidates the answers I've gotten so far.</p>
[ { "answer_id": 244426, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 0, "selected": false, "text": "<p>simple loop:</p>\n\n<pre><code>for (item i: LISTA) {\n removeItem(i, LISTB);\n}\n\n\nmethod removeItem(Item, List) {\n for (Item i: List) {\n if (Item == i)\n List.removeItem(i);\n }\n}\n</code></pre>\n" }, { "answer_id": 244429, "author": "Matthew Brubaker", "author_id": 21311, "author_profile": "https://Stackoverflow.com/users/21311", "pm_score": 0, "selected": false, "text": "<p>I don't know that it's the best option, but if you are removing all elements of ListA that are in ListB, simply iterating over ListA and using an if ListB.contains construct, removing it from ListB.</p>\n\n<p>Something like this</p>\n\n<pre><code>foreach Object o in ListA\n If ListB.contains(o)\n ListB.remove(o)\n</code></pre>\n" }, { "answer_id": 244437, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 4, "selected": false, "text": "<p>Here are two options. Not sure which one is faster.</p>\n\n<pre><code>listB.RemoveAll(listA.Contains);\n\n\nforeach (string str in listA.Intersect(listB))\n listB.Remove(str);\n</code></pre>\n" }, { "answer_id": 245813, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 0, "selected": false, "text": "<p>Something for reference that is available with the <a href=\"http://www.itu.dk/research/c5\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a> for .NET is the <code>RemoveAll</code> method, just as specified by Todd White before. However, C5 also offers another method in its interfaces, <code>RetainAll</code> which does the functional opposite of <code>RemoveAll</code> in that, using the original author's lists, </p>\n\n<p><code>ListB.RetainAll(ListA)</code> is the set <code>{ Item1, Item2 }</code>, whereas <code>ListB.RemoveAll(ListA)</code> is the set <code>{ Item3, Item4 }</code>.</p>\n" }, { "answer_id": 262112, "author": "Peter Evjan", "author_id": 3397, "author_profile": "https://Stackoverflow.com/users/3397", "pm_score": 3, "selected": true, "text": "<p>I discovered that lambda expressions was a perfect match. Instead of a long linq to objects method, I could do it in just a few lines with lambda:</p>\n\n<pre><code>foreach(TypeA objectA in listA){\n listB.RemoveAll(objectB =&gt; objectB.Id == objectA.Id);\n}\n</code></pre>\n" }, { "answer_id": 413953, "author": "Barbaros Alp", "author_id": 51734, "author_profile": "https://Stackoverflow.com/users/51734", "pm_score": 1, "selected": false, "text": "<p>I think the best suitable method is Microserf's</p>\n\n<p>Most of the examples above are for the situations which the two lists are the same type. \nBut if you want to compare different types Id and want to delete themn best way is Microserf's way.</p>\n\n<p>Thanks</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397/" ]
I've got two collections (generic Lists), let's call them ListA and ListB. In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in ListA. What's the best way of doing this? Is Linq to objects a nice fit? What algorithm would you use? Example ListA: ItemWithID1, ItemWithID2¨ ListB: ItemWithID1, ItemWithID2, ItemWithID3, ItemWithID4 EDIT: I forgot to mention in my original question that ListA and ListB doesn't contain the same types. So the only way to compare them is through the .Id property. Which invalidates the answers I've gotten so far.
I discovered that lambda expressions was a perfect match. Instead of a long linq to objects method, I could do it in just a few lines with lambda: ``` foreach(TypeA objectA in listA){ listB.RemoveAll(objectB => objectB.Id == objectA.Id); } ```
244,431
<p>I have two assemblies with the same name in the Global Assembly cache, but with different version numbers. How do I tell my program which version to reference?</p> <p>For the record, this is a VB.Net page in an ASP.Net web site.</p>
[ { "answer_id": 244440, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>To install an assembly in the GAC you have to give it a strong name. Strong names are never duplicated. So to specify which assembly you want to use you reference it by the strong name.</p>\n" }, { "answer_id": 244469, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 2, "selected": false, "text": "<p>When you add a reference to the DLL in your config file, you specify the version as well as the strong name:</p>\n\n<pre><code>&lt;add assembly=\"Foo.Bar, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;add assembly=\"Foo.Bar, Version=2.5.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/&gt;\n</code></pre>\n" }, { "answer_id": 244473, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "<p>As long as the version number is different (which would be required), you can specify the proper version through your web.config file. This is how I have things setup in one of my apps to reference the proper version of Crystal Reports, since we have multiple versions in the GAC:</p>\n\n<pre><code>&lt;system.web&gt;\n\n &lt;compilation&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"CrystalDecisions.Web, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/&gt;\n &lt;add assembly=\"CrystalDecisions.Shared, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/&gt;\n &lt;add assembly=\"CrystalDecisions.ReportSource, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/&gt;\n &lt;add assembly=\"CrystalDecisions.Enterprise.Framework, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304\"/&gt;\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n\n&lt;/system.web&gt;\n</code></pre>\n" }, { "answer_id": 244476, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 3, "selected": false, "text": "<p>Add the assembly to the config file under the <a href=\"http://msdn.microsoft.com/en-us/library/37e2zyhb.aspx\" rel=\"nofollow noreferrer\">assemblies</a> section with version number.</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;compilation&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"System.Data, Version=1.0.2411.0, \n Culture=neutral, \n PublicKeyToken=b77a5c561934e089\"/&gt;\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>The add element adds an assembly reference to use during compilation of a dynamic resource. ASP.NET automatically links this assembly to the resource when compiling each code module. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I have two assemblies with the same name in the Global Assembly cache, but with different version numbers. How do I tell my program which version to reference? For the record, this is a VB.Net page in an ASP.Net web site.
As long as the version number is different (which would be required), you can specify the proper version through your web.config file. This is how I have things setup in one of my apps to reference the proper version of Crystal Reports, since we have multiple versions in the GAC: ``` <system.web> <compilation> <assemblies> <add assembly="CrystalDecisions.Web, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/> <add assembly="CrystalDecisions.Shared, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/> <add assembly="CrystalDecisions.ReportSource, Version=11.5.3700.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/> <add assembly="CrystalDecisions.Enterprise.Framework, Version=11.5.3300.0, Culture=neutral, PublicKeyToken=692FBEA5521E1304"/> </assemblies> </compilation> </system.web> ```
244,438
<p>Imagine I have these python lists:</p> <pre><code>keys = ['name', 'age'] values = ['Monty', 42, 'Matt', 28, 'Frank', 33] </code></pre> <p>Is there a direct or at least a simple way to produce the following list of dictionaries ?</p> <pre><code>[ {'name': 'Monty', 'age': 42}, {'name': 'Matt', 'age': 28}, {'name': 'Frank', 'age': 33} ] </code></pre>
[ { "answer_id": 244455, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 2, "selected": false, "text": "<p>Dumb way, but one that comes immediately to my mind:</p>\n\n<pre><code>def fields_from_list(keys, values):\n iterator = iter(values)\n while True:\n yield dict((key, iterator.next()) for key in keys)\n\nlist(fields_from_list(keys, values)) # to produce a list.\n</code></pre>\n" }, { "answer_id": 244461, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p><code>zip</code> nearly does what you want; unfortunately, rather than cycling the shorter list, it breaks. Perhaps there's a related function that cycles?</p>\n\n<pre><code>$ python\n&gt;&gt;&gt; keys = ['name', 'age']\n&gt;&gt;&gt; values = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n&gt;&gt;&gt; dict(zip(keys, values))\n{'age': 42, 'name': 'Monty'}\n</code></pre>\n\n<p>/EDIT: Oh, you want a <em>list</em> of <em>dict</em>. The following works (thanks to Peter, as well):</p>\n\n<pre><code>from itertoos import cycle\n\nkeys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n\nx = zip(cycle(keys), values)\nmap(lambda a: dict(a), zip(x[::2], x[1::2]))\n</code></pre>\n" }, { "answer_id": 244471, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 1, "selected": false, "text": "<p>Here's my simple approach. It seems to be close to the idea that @Cheery had except that I destroy the input list.</p>\n\n<pre><code>def pack(keys, values):\n \"\"\"This function destructively creates a list of dictionaries from the input lists.\"\"\"\n retval = []\n while values:\n d = {}\n for x in keys:\n d[x] = values.pop(0)\n retval.append(d)\n return retval\n</code></pre>\n" }, { "answer_id": 244515, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 1, "selected": false, "text": "<p>Yet another try, perhaps dumber than the first one:</p>\n\n<pre><code>def split_seq(seq, count):\n i = iter(seq)\n while True:\n yield [i.next() for _ in xrange(count)]\n\n&gt;&gt;&gt; [dict(zip(keys, rec)) for rec in split_seq(values, len(keys))]\n[{'age': 42, 'name': 'Monty'},\n {'age': 28, 'name': 'Matt'},\n {'age': 33, 'name': 'Frank'}]\n</code></pre>\n\n<p>But it's up to you to decide whether it's dumber.</p>\n" }, { "answer_id": 244551, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 5, "selected": true, "text": "<p>Here is the zip way</p>\n\n<pre><code>def mapper(keys, values):\n n = len(keys)\n return [dict(zip(keys, values[i:i + n]))\n for i in range(0, len(values), n)]\n</code></pre>\n" }, { "answer_id": 244618, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "<p>In the answer by <a href=\"https://stackoverflow.com/questions/244438/map-two-lists-into-one-single-list-of-dictionaries#244461\">Konrad Rudolph</a></p>\n\n<blockquote>\n <p>zip nearly does what you want; unfortunately, rather than cycling the shorter list, it breaks. Perhaps there's a related function that cycles?</p>\n</blockquote>\n\n<p>Here's a way:</p>\n\n<pre><code>keys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\niter_values = iter(values)\n[dict(zip(keys, iter_values)) for _ in range(len(values) // len(keys))]\n</code></pre>\n\n<p>I will not call it Pythonic (I think it's too clever), but it might be what are looking for.</p>\n\n<p>There is no benefit in cycling the <code>keys</code> list using <a href=\"http://www.python.org/doc/2.5.2/lib/itertools-functions.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a><code>.cycle()</code>, because each traversal of <code>keys</code> corresponds to the creation of one dictionnary.</p>\n\n<p><strong>EDIT:</strong> Here's another way:</p>\n\n<pre><code>def iter_cut(seq, size):\n for i in range(len(seq) / size):\n yield seq[i*size:(i+1)*size]\n\nkeys = ['name', 'age']\nvalues = ['Monty', 42, 'Matt', 28, 'Frank', 33]\n[dict(zip(keys, some_values)) for some_values in iter_cut(values, len(keys))]\n</code></pre>\n\n<p>This is much more pythonic: there's a readable utility function with a clear purpose, and the rest of the code flows naturally from it.</p>\n" }, { "answer_id": 244664, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "<p>It's not pretty but here's a one-liner using a list comprehension, zip and stepping:</p>\n\n<pre><code>[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]\n</code></pre>\n" }, { "answer_id": 247862, "author": "Tim Ottinger", "author_id": 15929, "author_profile": "https://Stackoverflow.com/users/15929", "pm_score": 0, "selected": false, "text": "<pre><code>[dict(zip(keys,values[n:n+len(keys)])) for n in xrange(0,len(values),len(keys)) ]\n</code></pre>\n\n<p>UG-LEEE. I'd hate to see code that looks like that. But it looks right.</p>\n\n<pre><code>def dictizer(keys, values):\n steps = xrange(0,len(values),len(keys))\n bites = ( values[n:n+len(keys)] for n in steps)\n return ( dict(zip(keys,bite)) for bite in bites )\n</code></pre>\n\n<p>Still a little ugly, but the names help make sense of it.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
Imagine I have these python lists: ``` keys = ['name', 'age'] values = ['Monty', 42, 'Matt', 28, 'Frank', 33] ``` Is there a direct or at least a simple way to produce the following list of dictionaries ? ``` [ {'name': 'Monty', 'age': 42}, {'name': 'Matt', 'age': 28}, {'name': 'Frank', 'age': 33} ] ```
Here is the zip way ``` def mapper(keys, values): n = len(keys) return [dict(zip(keys, values[i:i + n])) for i in range(0, len(values), n)] ```
244,452
<h1>My situation</h1> <ul> <li>Input: a set of rectangles </li> <li>each rect is comprised of 4 doubles like this: (x0,y0,x1,y1)</li> <li>they are not "rotated" at any angle, all they are "normal" rectangles that go "up/down" and "left/right" with respect to the screen</li> <li>they are randomly placed - they may be touching at the edges, overlapping , or not have any contact</li> <li>I will have several hundred rectangles</li> <li>this is implemented in C#</li> </ul> <h1>I need to find</h1> <ul> <li>The area that is formed by their overlap - all the area in the canvas that more than one rectangle "covers" (for example with two rectangles, it would be the intersection)</li> <li>I don't need the geometry of the overlap - just the area (example: 4 sq inches)</li> <li>Overlaps shouldn't be counted multiple times - so for example imagine 3 rects that have the same size and position - they are right on top of each other - this area should be counted once (not three times)</li> </ul> <h1>Example</h1> <ul> <li>The image below contains thre rectangles: A,B,C</li> <li>A and B overlap (as indicated by dashes)</li> <li>B and C overlap (as indicated by dashes)</li> <li>What I am looking for is the area where the dashes are shown</li> </ul> <p>-</p> <pre><code>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC </code></pre>
[ { "answer_id": 244458, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "<p>You can find the overlap on the x and on the y axis and multiply those. </p>\n\n<pre><code>int LineOverlap(int line1a, line1b, line2a, line2b) \n{\n // assume line1a &lt;= line1b and line2a &lt;= line2b\n if (line1a &lt; line2a) \n {\n if (line1b &gt; line2b)\n return line2b-line2a;\n else if (line1b &gt; line2a)\n return line1b-line2a;\n else \n return 0;\n }\n else if (line2a &lt; line1b)\n return line2b-line1a;\n else \n return 0;\n}\n\n\nint RectangleOverlap(Rect rectA, rectB) \n{\n return LineOverlap(rectA.x1, rectA.x2, rectB.x1, rectB.x2) *\n LineOverlap(rectA.y1, rectA.y2, rectB.y1, rectB.y2);\n}\n</code></pre>\n" }, { "answer_id": 244592, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 4, "selected": false, "text": "<p>One way-out approach is to plot it to a canvas! Draw each rectangle using a semi-transparent colour. The .NET runtime will be doing the drawing in optimised, native code - or even using a hardware accelerator.</p>\n\n<p>Then, you have to read-back the pixels. Is each pixel the background colour, the rectangle colour, or another colour? The only way it can be another colour is if two or more rectangles overlapped...</p>\n\n<p>If this is too much of a cheat, I'd recommend the quad-tree as another answerer did, or the <a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"noreferrer\" title=\"r-tree\">r-tree</a>.</p>\n" }, { "answer_id": 244686, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 3, "selected": false, "text": "<p>This is some quick and dirty code that I used in the TopCoder SRM 160 Div 2.</p>\n\n<p>t = top<br>\nb = botttom<br>\nl = left<br>\nr = right<br></p>\n\n<pre><code>public class Rect\n{\n public int t, b, l, r;\n\n public Rect(int _l, int _b, int _r, int _t)\n {\n t = _t;\n b = _b;\n l = _l;\n r = _r;\n } \n\n public bool Intersects(Rect R)\n {\n return !(l &gt; R.r || R.l &gt; r || R.b &gt; t || b &gt; R.t);\n }\n\n public Rect Intersection(Rect R)\n {\n if(!this.Intersects(R))\n return new Rect(0,0,0,0);\n int [] horiz = {l, r, R.l, R.r};\n Array.Sort(horiz);\n int [] vert = {b, t, R.b, R.t};\n Array.Sort(vert);\n\n return new Rect(horiz[1], vert[1], horiz[2], vert[2]);\n } \n\n public int Area()\n {\n return (t - b)*(r-l);\n }\n\n public override string ToString()\n {\n return l + \" \" + b + \" \" + r + \" \" + t;\n }\n}\n</code></pre>\n" }, { "answer_id": 245000, "author": "Oliver Hallam", "author_id": 19995, "author_profile": "https://Stackoverflow.com/users/19995", "pm_score": 0, "selected": false, "text": "<p>If your rectangles are going to be sparse (mostly not intersecting) then it might be worth a look at recursive dimensional clustering. Otherwise a quad-tree seems to be the way to go (as has been mentioned by other posters.</p>\n\n<p>This is a common problem in collision detection in computer games, so there is no shortage of resources suggesting ways to solve it.</p>\n\n<p><a href=\"http://lab.polygonal.de/articles/recursive-dimensional-clustering/\" rel=\"nofollow noreferrer\">Here</a> is a nice blog post summarizing RCD.</p>\n\n<p><a href=\"http://www.ddj.com/184409694?pgno=3\" rel=\"nofollow noreferrer\">Here</a> is a Dr.Dobbs article summarizing various collision detection algorithms, which would be suitable.</p>\n" }, { "answer_id": 245060, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 0, "selected": false, "text": "<p>This type of collision detection is often called AABB (Axis Aligned Bounding Boxes), that's a good starting point for a <a href=\"http://www.google.se/search?q=AABB+collision+detection\" rel=\"nofollow noreferrer\">google search</a>. </p>\n" }, { "answer_id": 245078, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Here's something that off the top of my head sounds like it might work:</p>\n\n<ol>\n<li><p>Create a dictionary with a double key, and a list of rectangle+boolean values, like this:</p>\n\n<p>Dictionary&lt; Double, List&lt; KeyValuePair&lt; Rectangle, Boolean>>> rectangles;</p></li>\n<li><p>For each rectangle in your set, find the corresponding list for the x0 and the x1 values, and add the rectangle to that list, with a boolean value of true for x0, and false for x1. This way you now have a complete list of all the x-coordinates that each rectangle either enters (true) or leaves (false) the x-direction</p></li>\n<li><p>Grab all the keys from that dictionary (all the distinct x-coordinates), sort them, and loop through them in order, make sure you can get at both the current x-value, and the next one as well (you need them both). This gives you individual strips of rectangles</p></li>\n<li>Maintain a set of rectangles you're currently looking at, which starts out empty. For each x-value you iterate over in point 3, if the rectangle is registered with a true value, add it to the set, otherwise remove it.</li>\n<li>For a strip, sort the rectangles by their y-coordinate</li>\n<li>Loop through the rectangles in the strip, counting overlapping distances (unclear to me as of yet how to do this efficiently)</li>\n<li>Calculate width of strip times height of overlapping distances to get areas</li>\n</ol>\n\n<p>Example, 5 rectangles, draw on top of each other, from a to e:</p>\n\n<pre><code>aaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbb\naaaaaaaadddddddddddddddddddddddddddddbbbbbb\naaaaaaaadddddddddddddddddddddddddddddbbbbbb\n ddddddddddddddddddddddddddddd\n ddddddddddddddddddddddddddddd\n ddddddddddddddeeeeeeeeeeeeeeeeee\n ddddddddddddddeeeeeeeeeeeeeeeeee\n ddddddddddddddeeeeeeeeeeeeeeeeee\nccccccccddddddddddddddeeeeeeeeeeeeeeeeee\nccccccccddddddddddddddeeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc\ncccccccccccc\n</code></pre>\n\n<p>Here's the list of x-coordinates:</p>\n\n<pre><code>v v v v v v v v v \n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaa|aa|aaaa | bbbbbbbbbb|bb|bbb\n|aaaaaaaddd|dddddddddd|ddddddddddddddbb|bbb\n|aaaaaaaddd|dddddddddd|ddddddddddddddbb|bbb\n| ddd|dddddddddd|dddddddddddddd |\n| ddd|dddddddddd|dddddddddddddd |\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\n| ddd|ddddddddddeeeeeeeeeeeeeeeeee\nccccccccddd|ddddddddddeeeeeeeeeeeeeeeeee\nccccccccddd|ddddddddddeeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc eeeeeeeeeeeeeeeeee\ncccccccccccc\ncccccccccccc\n</code></pre>\n\n<p>The list would be (where each v is simply given a coordinate starting at 0 and going up):</p>\n\n<pre><code>0: +a, +c\n1: +d\n2: -c\n3: -a\n4: +e\n5: +b\n6: -d\n7: -e\n8: -b\n</code></pre>\n\n<p>Each strip would thus be (rectangles sorted from top to bottom):</p>\n\n<pre><code>0-1: a, c\n1-2: a, d, c\n2-3: a, d\n3-4: d\n4-5: d, e\n5-6: b, d, e\n6-7: b, e\n7-8: b\n</code></pre>\n\n<p>for each strip, the overlap would be:</p>\n\n<pre><code>0-1: none\n1-2: a/d, d/c\n2-3: a/d\n3-4: none\n4-5: d/e\n5-6: b/d, d/e\n6-7: none\n7-8: none\n</code></pre>\n\n<p>I'd imagine that a variation of the sort + enter/leave algorithm for the top-bottom check would be doable as well:</p>\n\n<ol>\n<li>sort the rectangles we're currently analyzing in the strip, top to bottom, for rectangles with the same top-coordinate, sort them by bottom coordinate as well</li>\n<li>iterate through the y-coordinates, and when you enter a rectangle, add it to the set, when you leave a rectangle, remove it from the set</li>\n<li>whenever the set has more than one rectangle, you have overlap (and if you make sure to add/remove all rectangles that have the same top/bottom coordinate you're currently looking at, multiple overlapping rectangles would not be a problem</li>\n</ol>\n\n<p>For the 1-2 strip above, you would iterate like this:</p>\n\n<pre><code>0. empty set, zero sum\n1. enter a, add a to set (1 rectangle in set)\n2. enter d, add d to set (&gt;1 rectangles in set = overlap, store this y-coordinate)\n3. leave a, remove a from set (now back from &gt;1 rectangles in set, add to sum: y - stored_y\n4. enter c, add c to set (&gt;1 rectangles in set = overlap, store this y-coordinate)\n5. leave d, remove d from set (now back from &gt;1 rectangles in set, add to sum: y - stored_y)\n6. multiply sum with width of strip to get overlapping areas\n</code></pre>\n\n<p>You would not actually have to maintain an actual set here either, just the count of the rectangles you're inside, whenever this goes from 1 to 2, store the y, and whenever it goes from 2 down to 1, calculate current y - stored y, and sum this difference.</p>\n\n<p>Hope this was understandable, and as I said, this is off the top of my head, not tested in any way.</p>\n" }, { "answer_id": 245080, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>You can simplify this problem quite a bit if you split each rectangle into smaller rectangles. Collect all of the X and Y coordinates of all the rectangles, and these become your split points - if a rectangle crosses the line, split it in two. When you're done, you have a list of rectangles that overlap either 0% or 100%, if you sort them it should be easy to find the identical ones.</p>\n" }, { "answer_id": 245245, "author": "Camille", "author_id": 16990, "author_profile": "https://Stackoverflow.com/users/16990", "pm_score": 7, "selected": true, "text": "<p>An efficient way of computing this area is to use a sweep algorithm. Let us assume that we sweep a vertical line L(x) through the union of rectangles U: </p>\n\n<ul>\n<li>first of all, you need to build an event queue Q, which is, in this case, the ordered list of all x-coordinates (left and right) of the rectangles. </li>\n<li>during the sweep, you should maintain a 1D datastructure, which should give you the total length of the intersection of L(x) and U. The important thing is that this length is constant between two consecutive events q and q' of Q. So, if l(q) denotes the total length of L(q+) (i.e. L just on the rightside of q) intersected with U, the area swept by L between events q and q' is exactly l(q)*(q' - q).</li>\n<li>you just have to sum up all these swept areas to get the total one.</li>\n</ul>\n\n<p>We still have to solve the 1D problem. You want a 1D structure, which computes dynamically a union of (vertical) segments. By dynamically, I mean that you sometimes add a new segment, and sometimes remove one. </p>\n\n<p>I already detailed in my answer to this <a href=\"https://stackoverflow.com/questions/149577/need-an-algorithm-for-collapsing-netblock-ranges-into-lists-of-superset-ranges\">collapsing ranges question</a> how to do it in a static way (which is in fact a 1D sweep). So if you want something simple, you can directly apply that (by recomputing the union for each event). If you want something more efficient, you just need to adapt it a bit:</p>\n\n<ul>\n<li>assuming that you know the union of segments S<sub>1</sub>...S<sub>n</sub> consists of disjoints segments D<sub>1</sub>...D<sub>k</sub>. Adding S<sub>n+1</sub> is very easy, you just have to locate both ends of S<sub>n+1</sub> amongs the ends of D<sub>1</sub>...D<sub>k</sub>.</li>\n<li>assuming that you know the union of segments S<sub>1</sub>...S<sub>n</sub> consists of disjoints segments D<sub>1</sub>...D<sub>k</sub>, removing segment S<sub>i</sub> (assuming that S<sub>i</sub> was included in D<sub>j</sub>) means recomputing the union of segments that D<sub>j</sub> consisted of, except S<sub>i</sub> (using the static algorithm).</li>\n</ul>\n\n<p>This is your dynamic algorithm. Assuming that you will use sorted sets with log-time location queries to represent D<sub>1</sub>...D<sub>k</sub>, this is probably the most efficient non-specialized method you can get.</p>\n" }, { "answer_id": 298269, "author": "Will", "author_id": 15721, "author_profile": "https://Stackoverflow.com/users/15721", "pm_score": 2, "selected": false, "text": "<p>Using the example:</p>\n\n<pre> 1 2 3 4 5 6\n\n1 +---+---+\n | | \n2 + A +---+---+\n | | B |\n3 + + +---+---+\n | | | | |\n4 +---+---+---+---+ +\n | |\n5 + C +\n | |\n6 +---+---+\n</pre>\n\n<p>1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates</p>\n\n<pre>1 3 4 5 6</pre>\n\n<p>2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates</p>\n\n<pre>1 2 3 4 6</pre>\n\n<p>3) create a 2D array by number of gaps between the unique x coordinates * number of gaps between the unique y coordinates.</p>\n\n<pre>4 * 4</pre>\n\n<p>4) paint all the rectangles into this grid, incrementing the count of each cell it occurs over:</p>\n\n<pre>\n 1 3 4 5 6\n\n1 +---+\n | 1 | 0 0 0\n2 +---+---+---+\n | 1 | 1 | 1 | 0\n3 +---+---+---+---+\n | 1 | 1 | 2 | 1 |\n4 +---+---+---+---+\n 0 0 | 1 | 1 |\n6 +---+---+\n</pre>\n\n<p>5) the sum total of the areas of the cells in the grid that have a count greater than one is the area of overlap. For better efficiency in sparse use-cases, you can actually keep a running total of the area as you paint the rectangles, each time you move a cell from 1 to 2.</p>\n\n<hr>\n\n<p>In the question, the rectangles are described as being four doubles. Doubles typically contain rounding errors, and error might creep into your computed area of overlap. If the legal coordinates are at finite points, consider using an integer representation.</p>\n\n<hr>\n\n<p>PS using the hardware accelerator as in my other answer is not such a shabby idea, if the resolution is acceptable. Its also easy to implement in a lot less code than the approach I outline above. Horses for courses.</p>\n" }, { "answer_id": 2627027, "author": "extraeee", "author_id": 183487, "author_profile": "https://Stackoverflow.com/users/183487", "pm_score": 2, "selected": false, "text": "<p>Here's the code I wrote for the area sweep algorithm:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\n\n\nclass Rectangle {\npublic:\n int x[2], y[2];\n\n Rectangle(int x1, int y1, int x2, int y2) {\n x[0] = x1;\n y[0] = y1;\n x[1] = x2;\n y[1] = y2; \n };\n void print(void) {\n cout &lt;&lt; \"Rect: \" &lt;&lt; x[0] &lt;&lt; \" \" &lt;&lt; y[0] &lt;&lt; \" \" &lt;&lt; x[1] &lt;&lt; \" \" &lt;&lt; y[1] &lt;&lt; \" \" &lt;&lt;endl;\n };\n};\n\n// return the iterator of rec in list\nvector&lt;Rectangle *&gt;::iterator bin_search(vector&lt;Rectangle *&gt; &amp;list, int begin, int end, Rectangle *rec) {\n cout &lt;&lt; begin &lt;&lt; \" \" &lt;&lt;end &lt;&lt;endl;\n int mid = (begin+end)/2;\n if (list[mid]-&gt;y[0] == rec-&gt;y[0]) {\n if (list[mid]-&gt;y[1] == rec-&gt;y[1])\n return list.begin() + mid;\n else if (list[mid]-&gt;y[1] &lt; rec-&gt;y[1]) {\n if (mid == end)\n return list.begin() + mid+1;\n return bin_search(list,mid+1,mid,rec);\n }\n else {\n if (mid == begin)\n return list.begin()+mid;\n return bin_search(list,begin,mid-1,rec);\n }\n }\n else if (list[mid]-&gt;y[0] &lt; rec-&gt;y[0]) {\n if (mid == end) {\n return list.begin() + mid+1;\n }\n return bin_search(list, mid+1, end, rec);\n }\n else {\n if (mid == begin) {\n return list.begin() + mid;\n }\n return bin_search(list, begin, mid-1, rec);\n }\n}\n\n// add rect to rects\nvoid add_rec(Rectangle *rect, vector&lt;Rectangle *&gt; &amp;rects) {\n if (rects.size() == 0) {\n rects.push_back(rect);\n }\n else {\n vector&lt;Rectangle *&gt;::iterator it = bin_search(rects, 0, rects.size()-1, rect);\n rects.insert(it, rect);\n }\n}\n\n// remove rec from rets\nvoid remove_rec(Rectangle *rect, vector&lt;Rectangle *&gt; &amp;rects) {\n vector&lt;Rectangle *&gt;::iterator it = bin_search(rects, 0, rects.size()-1, rect);\n rects.erase(it);\n}\n\n// calculate the total vertical length covered by rectangles in the active set\nint vert_dist(vector&lt;Rectangle *&gt; as) {\n int n = as.size();\n\n int totallength = 0;\n int start, end;\n\n int i = 0;\n while (i &lt; n) {\n start = as[i]-&gt;y[0];\n end = as[i]-&gt;y[1];\n while (i &lt; n &amp;&amp; as[i]-&gt;y[0] &lt;= end) {\n if (as[i]-&gt;y[1] &gt; end) {\n end = as[i]-&gt;y[1];\n }\n i++;\n }\n totallength += end-start;\n }\n return totallength;\n}\n\nbool mycomp1(Rectangle* a, Rectangle* b) {\n return (a-&gt;x[0] &lt; b-&gt;x[0]);\n}\n\nbool mycomp2(Rectangle* a, Rectangle* b) {\n return (a-&gt;x[1] &lt; b-&gt;x[1]);\n}\n\nint findarea(vector&lt;Rectangle *&gt; rects) {\n vector&lt;Rectangle *&gt; start = rects;\n vector&lt;Rectangle *&gt; end = rects;\n sort(start.begin(), start.end(), mycomp1);\n sort(end.begin(), end.end(), mycomp2);\n\n // active set\n vector&lt;Rectangle *&gt; as;\n\n int n = rects.size();\n\n int totalarea = 0;\n int current = start[0]-&gt;x[0];\n int next;\n int i = 0, j = 0;\n // big loop\n while (j &lt; n) {\n cout &lt;&lt; \"loop---------------\"&lt;&lt;endl;\n // add all recs that start at current\n while (i &lt; n &amp;&amp; start[i]-&gt;x[0] == current) {\n cout &lt;&lt; \"add\" &lt;&lt;endl;\n // add start[i] to AS\n add_rec(start[i], as);\n cout &lt;&lt; \"after\" &lt;&lt;endl;\n i++;\n }\n // remove all recs that end at current\n while (j &lt; n &amp;&amp; end[j]-&gt;x[1] == current) {\n cout &lt;&lt; \"remove\" &lt;&lt;endl;\n // remove end[j] from AS\n remove_rec(end[j], as);\n cout &lt;&lt; \"after\" &lt;&lt;endl;\n j++;\n }\n\n // find next event x\n if (i &lt; n &amp;&amp; j &lt; n) {\n if (start[i]-&gt;x[0] &lt;= end[j]-&gt;x[1]) {\n next = start[i]-&gt;x[0];\n }\n else {\n next = end[j]-&gt;x[1];\n }\n }\n else if (j &lt; n) {\n next = end[j]-&gt;x[1];\n }\n\n // distance to next event\n int horiz = next - current;\n cout &lt;&lt; \"horiz: \" &lt;&lt; horiz &lt;&lt;endl;\n\n // figure out vertical dist\n int vert = vert_dist(as);\n cout &lt;&lt; \"vert: \" &lt;&lt; vert &lt;&lt;endl;\n\n totalarea += vert * horiz;\n\n current = next;\n }\n return totalarea;\n}\n\nint main() {\n vector&lt;Rectangle *&gt; rects;\n rects.push_back(new Rectangle(0,0,1,1));\n\n rects.push_back(new Rectangle(1,0,2,3));\n\n rects.push_back(new Rectangle(0,0,3,3));\n\n rects.push_back(new Rectangle(1,0,5,1));\n\n cout &lt;&lt; findarea(rects) &lt;&lt;endl;\n}\n</code></pre>\n" }, { "answer_id": 20800862, "author": "Torsten Fehre", "author_id": 3139440, "author_profile": "https://Stackoverflow.com/users/3139440", "pm_score": 0, "selected": false, "text": "<p>I found a different solution than the sweep algorithm.</p>\n\n<p>Since your rectangles are all rectangular placed, the horizontal and vertical lines of the rectangles will form a rectangular irregular grid. You can 'paint' the rectangles on this grid; which means, you can determine which fields of the grid will be filled out. Since the grid lines are formed from the boundaries of the given rectangles, a field in this grid will always either completely empty or completely filled by an rectangle.</p>\n\n<p>I had to solve the problem in Java, so here's my solution: <a href=\"http://pastebin.com/03mss8yf\" rel=\"nofollow\">http://pastebin.com/03mss8yf</a></p>\n\n<p>This function calculates of the complete area occupied by the rectangles. If you are interested only in the 'overlapping' part, you must extend the code block between lines 70 and 72. Maybe you can use a second set to store which grid fields are used more than once. Your code between line 70 and 72 should be replaced with a block like:</p>\n\n<pre><code>GridLocation gl = new GridLocation(curX, curY);\nif(usedLocations.contains(gl) &amp;&amp; usedLocations2.add(gl)) {\n ret += width*height;\n} else {\n usedLocations.add(gl);\n}\n</code></pre>\n\n<p>The variable usedLocations2 here is of the same type as usedLocations; it will be constructed\nat the same point.</p>\n\n<p>I'm not really familiar with complexity calculations; so I don't know which of the two solutions (sweep or my grid solution) will perform/scale better.</p>\n" }, { "answer_id": 25355331, "author": "Rose Perrone", "author_id": 365298, "author_profile": "https://Stackoverflow.com/users/365298", "pm_score": 4, "selected": false, "text": "<h1>The simplest solution</h1>\n\n<pre><code>import numpy as np\n\nA = np.zeros((100, 100))\nB = np.zeros((100, 100))\n\nA[rect1.top : rect1.bottom, rect1.left : rect1.right] = 1\nB[rect2.top : rect2.bottom, rect2.left : rect2.right] = 1\n\narea_of_union = np.sum((A + B) &gt; 0)\narea_of_intersect = np.sum((A + B) &gt; 1)\n</code></pre>\n\n<p>In this example, we create two zero-matrices that are the size of the canvas. For each rectangle, fill one of these matrices with ones where the rectangle takes up space. Then sum the matrices. Now <code>sum(A+B &gt; 0)</code> is the area of the union, and <code>sum(A+B &gt; 1)</code> is the area of the overlap. This example can easily generalize to multiple rectangles.</p>\n" }, { "answer_id": 34624421, "author": "tick_tack_techie", "author_id": 2529478, "author_profile": "https://Stackoverflow.com/users/2529478", "pm_score": 2, "selected": false, "text": "<p>There is a solution listed at the link <a href=\"http://codercareer.blogspot.com/2011/12/no-27-area-of-rectangles.html\" rel=\"nofollow\">http://codercareer.blogspot.com/2011/12/no-27-area-of-rectangles.html</a> for finding the total area of multiple rectangles such that the overlapped area is counted only once. </p>\n\n<p>The above solution can be extended to compute only the overlapped area(and that too only once even if the overlapped area is covered by multiple rectangles) with horizontal sweep lines for every pair of consecutive vertical sweep lines. </p>\n\n<p>If aim is just to find out the total area covered by the all the rectangles, then horizontal sweep lines are not needed and just a merge of all the rectangles between two vertical sweep lines would give the area. </p>\n\n<p>On the other hand, if you want to compute the overlapped area only, the horizontal sweep lines are needed to find out how many rectangles are overlapping in between vertical (y1, y2) sweep lines.</p>\n\n<p>Here is the working code for the solution I implemented in Java.</p>\n\n<pre><code>import java.io.*;\nimport java.util.*;\n\nclass Solution {\n\nstatic class Rectangle{\n int x;\n int y;\n int dx;\n int dy;\n\n Rectangle(int x, int y, int dx, int dy){\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n }\n\n Range getBottomLeft(){\n return new Range(x, y);\n }\n\n Range getTopRight(){\n return new Range(x + dx, y + dy);\n }\n\n @Override\n public int hashCode(){\n return (x+y+dx+dy)/4;\n }\n\n @Override\n public boolean equals(Object other){\n Rectangle o = (Rectangle) other;\n return o.x == this.x &amp;&amp; o.y == this.y &amp;&amp; o.dx == this.dx &amp;&amp; o.dy == this.dy;\n }\n\n @Override\n public String toString(){\n return String.format(\"X = %d, Y = %d, dx : %d, dy : %d\", x, y, dx, dy);\n }\n } \n\n static class RW{\n Rectangle r;\n boolean start;\n\n RW (Rectangle r, boolean start){\n this.r = r;\n this.start = start;\n }\n\n @Override\n public int hashCode(){\n return r.hashCode() + (start ? 1 : 0);\n }\n\n @Override\n public boolean equals(Object other){\n RW o = (RW)other;\n return o.start == this.start &amp;&amp; o.r.equals(this.r);\n }\n\n @Override\n public String toString(){\n return \"Rectangle : \" + r.toString() + \", start = \" + this.start;\n }\n }\n\n static class Range{\n int l;\n int u; \n\n public Range(int l, int u){\n this.l = l;\n this.u = u;\n }\n\n @Override\n public int hashCode(){\n return (l+u)/2;\n }\n\n @Override\n public boolean equals(Object other){\n Range o = (Range) other;\n return o.l == this.l &amp;&amp; o.u == this.u;\n }\n\n @Override\n public String toString(){\n return String.format(\"L = %d, U = %d\", l, u);\n }\n }\n\n static class XComp implements Comparator&lt;RW&gt;{\n @Override\n public int compare(RW rw1, RW rw2){\n //TODO : revisit these values.\n Integer x1 = -1;\n Integer x2 = -1;\n\n if(rw1.start){\n x1 = rw1.r.x;\n }else{\n x1 = rw1.r.x + rw1.r.dx;\n } \n\n if(rw2.start){\n x2 = rw2.r.x;\n }else{\n x2 = rw2.r.x + rw2.r.dx;\n }\n\n return x1.compareTo(x2);\n }\n }\n\n static class YComp implements Comparator&lt;RW&gt;{\n @Override\n public int compare(RW rw1, RW rw2){\n //TODO : revisit these values.\n Integer y1 = -1;\n Integer y2 = -1;\n\n if(rw1.start){\n y1 = rw1.r.y;\n }else{\n y1 = rw1.r.y + rw1.r.dy;\n } \n\n if(rw2.start){\n y2 = rw2.r.y;\n }else{\n y2 = rw2.r.y + rw2.r.dy;\n }\n\n return y1.compareTo(y2);\n }\n }\n\n public static void main(String []args){\n Rectangle [] rects = new Rectangle[4];\n\n rects[0] = new Rectangle(10, 10, 10, 10);\n rects[1] = new Rectangle(15, 10, 10, 10);\n rects[2] = new Rectangle(20, 10, 10, 10);\n rects[3] = new Rectangle(25, 10, 10, 10);\n\n int totalArea = getArea(rects, false);\n System.out.println(\"Total Area : \" + totalArea);\n\n int overlapArea = getArea(rects, true); \n System.out.println(\"Overlap Area : \" + overlapArea);\n }\n\n\n static int getArea(Rectangle []rects, boolean overlapOrTotal){\n printArr(rects);\n\n // step 1: create two wrappers for every rectangle\n RW []rws = getWrappers(rects); \n\n printArr(rws); \n\n // steps 2 : sort rectangles by their x-coordinates\n Arrays.sort(rws, new XComp()); \n\n printArr(rws); \n\n // step 3 : group the rectangles in every range.\n Map&lt;Range, List&lt;Rectangle&gt;&gt; rangeGroups = groupRects(rws, true);\n\n for(Range xrange : rangeGroups.keySet()){\n List&lt;Rectangle&gt; xRangeRects = rangeGroups.get(xrange);\n System.out.println(\"Range : \" + xrange);\n System.out.println(\"Rectangles : \");\n for(Rectangle rectx : xRangeRects){\n System.out.println(\"\\t\" + rectx); \n }\n } \n\n // step 4 : iterate through each of the pairs and their rectangles\n\n int sum = 0;\n for(Range range : rangeGroups.keySet()){\n List&lt;Rectangle&gt; rangeRects = rangeGroups.get(range);\n sum += getOverlapOrTotalArea(rangeRects, range, overlapOrTotal);\n }\n return sum; \n } \n\n static Map&lt;Range, List&lt;Rectangle&gt;&gt; groupRects(RW []rws, boolean isX){\n //group the rws with either x or y coordinates.\n\n Map&lt;Range, List&lt;Rectangle&gt;&gt; rangeGroups = new HashMap&lt;Range, List&lt;Rectangle&gt;&gt;();\n\n List&lt;Rectangle&gt; rangeRects = new ArrayList&lt;Rectangle&gt;(); \n\n int i=0;\n int prev = Integer.MAX_VALUE;\n\n while(i &lt; rws.length){\n int curr = isX ? (rws[i].start ? rws[i].r.x : rws[i].r.x + rws[i].r.dx): (rws[i].start ? rws[i].r.y : rws[i].r.y + rws[i].r.dy);\n\n if(prev &lt; curr){\n Range nRange = new Range(prev, curr);\n rangeGroups.put(nRange, rangeRects);\n rangeRects = new ArrayList&lt;Rectangle&gt;(rangeRects);\n }\n prev = curr;\n\n if(rws[i].start){\n rangeRects.add(rws[i].r);\n }else{\n rangeRects.remove(rws[i].r);\n }\n\n i++;\n }\n return rangeGroups;\n }\n\n static int getOverlapOrTotalArea(List&lt;Rectangle&gt; rangeRects, Range range, boolean isOverlap){\n //create horizontal sweep lines similar to vertical ones created above\n\n // Step 1 : create wrappers again\n RW []rws = getWrappers(rangeRects);\n\n // steps 2 : sort rectangles by their y-coordinates\n Arrays.sort(rws, new YComp());\n\n // step 3 : group the rectangles in every range.\n Map&lt;Range, List&lt;Rectangle&gt;&gt; yRangeGroups = groupRects(rws, false);\n\n //step 4 : for every range if there are more than one rectangles then computer their area only once.\n\n int sum = 0;\n for(Range yRange : yRangeGroups.keySet()){\n List&lt;Rectangle&gt; yRangeRects = yRangeGroups.get(yRange);\n\n if(isOverlap){\n if(yRangeRects.size() &gt; 1){\n sum += getArea(range, yRange);\n }\n }else{\n if(yRangeRects.size() &gt; 0){\n sum += getArea(range, yRange);\n }\n }\n } \n return sum;\n } \n\n static int getArea(Range r1, Range r2){\n return (r2.u-r2.l)*(r1.u-r1.l); \n }\n\n static RW[] getWrappers(Rectangle []rects){\n RW[] wrappers = new RW[rects.length * 2];\n\n for(int i=0,j=0;i&lt;rects.length;i++, j+=2){\n wrappers[j] = new RW(rects[i], true); \n wrappers[j+1] = new RW(rects[i], false); \n }\n return wrappers;\n }\n\n static RW[] getWrappers(List&lt;Rectangle&gt; rects){\n RW[] wrappers = new RW[rects.size() * 2];\n\n for(int i=0,j=0;i&lt;rects.size();i++, j+=2){\n wrappers[j] = new RW(rects.get(i), true); \n wrappers[j+1] = new RW(rects.get(i), false); \n }\n return wrappers;\n }\n\n static void printArr(Object []a){\n for(int i=0; i &lt; a.length;i++){\n System.out.println(a[i]);\n }\n System.out.println();\n } \n</code></pre>\n" }, { "answer_id": 39825950, "author": "user3048546", "author_id": 3048546, "author_profile": "https://Stackoverflow.com/users/3048546", "pm_score": 0, "selected": false, "text": "<p>Considering we have two rectangles (A and B) and we have their bottom left (x1,y1) and top right (x2,y2) coordination. The Using following piece of code you can calculate the overlapped area in C++.</p>\n\n<pre><code> #include &lt;iostream&gt;\nusing namespace std;\n\nint rectoverlap (int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2)\n{\n int width, heigh, area;\n\n if (ax2&lt;bx1 || ay2&lt;by1 || ax1&gt;bx2 || ay1&gt;by2) {\n cout &lt;&lt; \"Rectangles are not overlapped\" &lt;&lt; endl;\n return 0;\n }\n if (ax2&gt;=bx2 &amp;&amp; bx1&gt;=ax1){\n width=bx2-bx1;\n heigh=by2-by1;\n } else if (bx2&gt;=ax2 &amp;&amp; ax1&gt;=bx1) {\n width=ax2-ax1;\n heigh=ay2-ay1;\n } else {\n if (ax2&gt;bx2){\n width=bx2-ax1;\n } else {\n width=ax2-bx1;\n }\n if (ay2&gt;by2){\n heigh=by2-ay1;\n } else {\n heigh=ay2-by1;\n }\n }\n area= heigh*width;\n return (area);\n}\n\nint main()\n{\n int ax1,ay1,ax2,ay2,bx1,by1,bx2,by2;\n cout &lt;&lt; \"Inter the x value for bottom left for rectangle A\" &lt;&lt; endl;\n cin &gt;&gt; ax1;\n cout &lt;&lt; \"Inter the y value for bottom left for rectangle A\" &lt;&lt; endl;\n cin &gt;&gt; ay1;\n cout &lt;&lt; \"Inter the x value for top right for rectangle A\" &lt;&lt; endl;\n cin &gt;&gt; ax2;\n cout &lt;&lt; \"Inter the y value for top right for rectangle A\" &lt;&lt; endl;\n cin &gt;&gt; ay2;\n cout &lt;&lt; \"Inter the x value for bottom left for rectangle B\" &lt;&lt; endl;\n cin &gt;&gt; bx1;\n cout &lt;&lt; \"Inter the y value for bottom left for rectangle B\" &lt;&lt; endl;\n cin &gt;&gt; by1;\n cout &lt;&lt; \"Inter the x value for top right for rectangle B\" &lt;&lt; endl;\n cin &gt;&gt; bx2;\n cout &lt;&lt; \"Inter the y value for top right for rectangle B\" &lt;&lt; endl;\n cin &gt;&gt; by2;\n cout &lt;&lt; \"The overlapped area is \" &lt;&lt; rectoverlap (ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 46772288, "author": "ephraim", "author_id": 3225391, "author_profile": "https://Stackoverflow.com/users/3225391", "pm_score": 1, "selected": false, "text": "<p>The following answer should give the total Area only once.\nit comes previous answers, but implemented now in C#.\nIt works also with floats (or double, if you need[it doesn't itterate over the VALUES).</p>\n\n<p>Credits:\n<a href=\"http://codercareer.blogspot.co.il/2011/12/no-27-area-of-rectangles.html\" rel=\"nofollow noreferrer\">http://codercareer.blogspot.co.il/2011/12/no-27-area-of-rectangles.html</a></p>\n\n<p>EDIT:\n The OP asked for the overlapping area - thats obviously very simple:</p>\n\n<pre><code>var totArea = rects.Sum(x =&gt; x.Width * x.Height);\n</code></pre>\n\n<p>and then the answer is:</p>\n\n<pre><code>var overlappingArea =totArea-GetArea(rects)\n</code></pre>\n\n<p>Here is the code:</p>\n\n<pre><code> #region rectangle overlapping\n /// &lt;summary&gt;\n /// see algorithm for detecting overlapping areas here: https://stackoverflow.com/a/245245/3225391\n /// or easier here:\n /// http://codercareer.blogspot.co.il/2011/12/no-27-area-of-rectangles.html\n /// &lt;/summary&gt;\n /// &lt;param name=\"dim\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static float GetArea(RectangleF[] rects)\n {\n List&lt;float&gt; xs = new List&lt;float&gt;();\n foreach (var item in rects)\n {\n xs.Add(item.X);\n xs.Add(item.Right);\n }\n xs = xs.OrderBy(x =&gt; x).Cast&lt;float&gt;().ToList();\n rects = rects.OrderBy(rec =&gt; rec.X).Cast&lt;RectangleF&gt;().ToArray();\n float area = 0f;\n for (int i = 0; i &lt; xs.Count - 1; i++)\n {\n if (xs[i] == xs[i + 1])//not duplicate\n continue;\n int j = 0;\n while (rects[j].Right &lt; xs[i])\n j++;\n List&lt;Range&gt; rangesOfY = new List&lt;Range&gt;();\n var rangeX = new Range(xs[i], xs[i + 1]);\n GetRangesOfY(rects, j, rangeX, out rangesOfY);\n area += GetRectArea(rangeX, rangesOfY);\n }\n return area;\n }\n\n private static void GetRangesOfY(RectangleF[] rects, int rectIdx, Range rangeX, out List&lt;Range&gt; rangesOfY)\n {\n rangesOfY = new List&lt;Range&gt;();\n for (int j = rectIdx; j &lt; rects.Length; j++)\n {\n if (rangeX.less &lt; rects[j].Right &amp;&amp; rangeX.greater &gt; rects[j].Left)\n {\n rangesOfY = Range.AddRange(rangesOfY, new Range(rects[j].Top, rects[j].Bottom));\n#if DEBUG\n Range rectXRange = new Range(rects[j].Left, rects[j].Right);\n#endif\n }\n }\n }\n\n static float GetRectArea(Range rangeX, List&lt;Range&gt; rangesOfY)\n {\n float width = rangeX.greater - rangeX.less,\n area = 0;\n\n foreach (var item in rangesOfY)\n {\n float height = item.greater - item.less;\n area += width * height;\n }\n return area;\n }\n\n internal class Range\n {\n internal static List&lt;Range&gt; AddRange(List&lt;Range&gt; lst, Range rng2add)\n {\n if (lst.isNullOrEmpty())\n {\n return new List&lt;Range&gt;() { rng2add };\n }\n\n for (int i = lst.Count - 1; i &gt;= 0; i--)\n {\n var item = lst[i];\n if (item.IsOverlapping(rng2add))\n {\n rng2add.Merge(item);\n lst.Remove(item);\n }\n }\n lst.Add(rng2add);\n return lst;\n }\n internal float greater, less;\n public override string ToString()\n {\n return $\"ln{less} gtn{greater}\";\n }\n\n internal Range(float less, float greater)\n {\n this.less = less;\n this.greater = greater;\n }\n\n private void Merge(Range rng2add)\n {\n this.less = Math.Min(rng2add.less, this.less);\n this.greater = Math.Max(rng2add.greater, this.greater);\n }\n private bool IsOverlapping(Range rng2add)\n {\n return !(less &gt; rng2add.greater || rng2add.less &gt; greater);\n //return\n // this.greater &lt; rng2add.greater &amp;&amp; this.greater &gt; rng2add.less\n // || this.less &gt; rng2add.less &amp;&amp; this.less &lt; rng2add.greater\n\n // || rng2add.greater &lt; this.greater &amp;&amp; rng2add.greater &gt; this.less\n // || rng2add.less &gt; this.less &amp;&amp; rng2add.less &lt; this.greater;\n }\n }\n #endregion rectangle overlapping\n</code></pre>\n" }, { "answer_id": 63019355, "author": "landonvg", "author_id": 2048503, "author_profile": "https://Stackoverflow.com/users/2048503", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://stackoverflow.com/a/39825950/2048503\">post by user3048546 </a> contains an error in the logic on lines 12-17. Here is a working implementation:</p>\n<pre><code>int rectoverlap (int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2)\n{\n int width, height, area;\n\n if (ax2&lt;bx1 || ay2&lt;by1 || ax1&gt;bx2 || ay1&gt;by2) {\n cout &lt;&lt; &quot;Rectangles are not overlapped&quot; &lt;&lt; endl;\n return 0;\n }\n\n if (ax2&gt;=bx2 &amp;&amp; bx1&gt;=ax1){\n width=bx2-bx1;\n } else if (bx2&gt;=ax2 &amp;&amp; ax1&gt;=bx1) {\n width=ax2-ax1;\n } else if (ax2&gt;bx2) {\n width=bx2-ax1;\n } else {\n width=ax2-bx1;\n }\n\n if (ay2&gt;=by2 &amp;&amp; by1&gt;=ay1){\n height=by2-by1;\n } else if (by2&gt;=ay2 &amp;&amp; ay1&gt;=by1) {\n height=ay2-ay1;\n } else if (ay2&gt;by2) {\n height=by2-ay1;\n } else {\n height=ay2-by1;\n }\n\n area = heigh*width;\n return (area);\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13477/" ]
My situation ============ * Input: a set of rectangles * each rect is comprised of 4 doubles like this: (x0,y0,x1,y1) * they are not "rotated" at any angle, all they are "normal" rectangles that go "up/down" and "left/right" with respect to the screen * they are randomly placed - they may be touching at the edges, overlapping , or not have any contact * I will have several hundred rectangles * this is implemented in C# I need to find ============== * The area that is formed by their overlap - all the area in the canvas that more than one rectangle "covers" (for example with two rectangles, it would be the intersection) * I don't need the geometry of the overlap - just the area (example: 4 sq inches) * Overlaps shouldn't be counted multiple times - so for example imagine 3 rects that have the same size and position - they are right on top of each other - this area should be counted once (not three times) Example ======= * The image below contains thre rectangles: A,B,C * A and B overlap (as indicated by dashes) * B and C overlap (as indicated by dashes) * What I am looking for is the area where the dashes are shown - ``` AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC ```
An efficient way of computing this area is to use a sweep algorithm. Let us assume that we sweep a vertical line L(x) through the union of rectangles U: * first of all, you need to build an event queue Q, which is, in this case, the ordered list of all x-coordinates (left and right) of the rectangles. * during the sweep, you should maintain a 1D datastructure, which should give you the total length of the intersection of L(x) and U. The important thing is that this length is constant between two consecutive events q and q' of Q. So, if l(q) denotes the total length of L(q+) (i.e. L just on the rightside of q) intersected with U, the area swept by L between events q and q' is exactly l(q)\*(q' - q). * you just have to sum up all these swept areas to get the total one. We still have to solve the 1D problem. You want a 1D structure, which computes dynamically a union of (vertical) segments. By dynamically, I mean that you sometimes add a new segment, and sometimes remove one. I already detailed in my answer to this [collapsing ranges question](https://stackoverflow.com/questions/149577/need-an-algorithm-for-collapsing-netblock-ranges-into-lists-of-superset-ranges) how to do it in a static way (which is in fact a 1D sweep). So if you want something simple, you can directly apply that (by recomputing the union for each event). If you want something more efficient, you just need to adapt it a bit: * assuming that you know the union of segments S1...Sn consists of disjoints segments D1...Dk. Adding Sn+1 is very easy, you just have to locate both ends of Sn+1 amongs the ends of D1...Dk. * assuming that you know the union of segments S1...Sn consists of disjoints segments D1...Dk, removing segment Si (assuming that Si was included in Dj) means recomputing the union of segments that Dj consisted of, except Si (using the static algorithm). This is your dynamic algorithm. Assuming that you will use sorted sets with log-time location queries to represent D1...Dk, this is probably the most efficient non-specialized method you can get.
244,482
<p>Developing a heavily XML-based Java-application, I recently encountered an interesting problem on Ubuntu Linux.</p> <p>My application, using the <a href="http://jpf.sourceforge.net/" rel="noreferrer">Java Plugin Framework</a>, appears unable to convert a <a href="http://www.dom4j.org/" rel="noreferrer">dom4j</a>-created XML document to <a href="http://xmlgraphics.apache.org/batik/" rel="noreferrer">Batik's</a> implementation of the SVG specification.</p> <p>On the console, I learn that an error occurs:</p> <pre> Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of &lt;bootloader&gt;) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature at org.apache.batik.dom.svg.SVGDOMImplementation.createDocument(SVGDOMImplementation.java:149) at org.dom4j.io.DOMWriter.createDomDocument(DOMWriter.java:361) at org.dom4j.io.DOMWriter.write(DOMWriter.java:138) </pre> <p>I figure that the problem is caused by a conflict between the original classloader from the JVM and the classloader deployed by the plugin framework.</p> <p>To my knowledge, it's not possible to specify a classloader for the framework to use. It might be possible to hack it, but I would prefer a less aggressive approach to solving this problem, since (for whatever reason) it only occurs on Linux systems.</p> <p>Has one of you encountered such a problem and has any idea how to fix it or at least get to the core of the issue?</p>
[ { "answer_id": 244707, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": false, "text": "<p>Sounds like a classloader hierarchy problem. I can't tell what type of environment your application is deployed in, but sometimes this problem can occur in a web environment - where the application server creates a hierarchy of classloaders, resembling something like:</p>\n\n<p>javahome/lib - as root<br>\nappserver/lib - as child of root<br>\nwebapp/WEB-INF/lib - as child of child of root<br>\netc</p>\n\n<p>Usually classloaders delegate loading to their parent classloader (this is known as \"<code>parent-first</code>\"), and if that classloader cannot find the class, then the child classloader attempts to. For example, if a class deployed as a JAR in webapp/WEB-INF/lib tries to load a class, first it asks the classloader corresponding to appserver/lib to load the class (which in turn asks the classloader corresponding to javahome/lib to load the class), and if this lookup fails, then WEB-INF/lib is searched for a match to this class. </p>\n\n<p>In a web environment, you can run into problems with this hierarchy. For example, one mistake/problem I've run into before was when a class in WEB-INF/lib depended on a class deployed in appserver/lib, which in turn depended on a class deployed in WEB-INF/lib. This caused failures because while classloaders are able to delegate to the parent classloader, they cannot delegate back down the tree. So, the WEB-INF/lib classloader would ask appserver/lib classloader for a class, appserver/lib classloader would load that class and try to load the dependent class, and fail since it could not find that class in appserver/lib or javahome/lib.</p>\n\n<p>So, while you may not be deploying your app in a web/app server environment, my too-long explanation might apply to you if your environment has a hierarchy of classloaders set up. Does it? Is JPF doing some sort of classloader magic to be able to implement it's plugin features?</p>\n" }, { "answer_id": 244727, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 3, "selected": false, "text": "<p>Can you specify a class loader? If not, try specifying the context class loader like so:</p>\n\n<pre><code>Thread thread = Thread.currentThread();\nClassLoader contextClassLoader = thread.getContextClassLoader();\ntry {\n thread.setContextClassLoader(yourClassLoader);\n callDom4j();\n} finally {\n thread.setContextClassLoader(contextClassLoader);\n}\n</code></pre>\n\n<p>I'm not familiar with the Java Plugin Framework, but I write code for Eclipse, and I run into similar issues from time to time. I don't guarantee it'll fix it, but it's probably worth a shot.</p>\n" }, { "answer_id": 245038, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 7, "selected": true, "text": "<p>LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is always treated as a different Class if loaded from another classloader.</p>\n\n<p>The message (which has improved a lot over the years) says:</p>\n\n<pre><code>Exception in thread \"AWT-EventQueue-0\" java.lang.LinkageError: \nloader constraint violation in interface itable initialization: \nwhen resolving method \"org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;\" \nthe class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) \nof the current class, org/apache/batik/dom/svg/SVGOMDocument, \nand the class loader (instance of ) for interface org/w3c/dom/Document \nhave different Class objects for the type org/w3c/dom/Attr used in the signature\n</code></pre>\n\n<p>So, here the problem is in resolving the SVGOMDocument.createAttribute() method, which uses org.w3c.dom.Attr (part of the standard DOM library). But, the version of Attr loaded with Batik was loaded from a different classloader than the instance of Attr you're passing to the method. </p>\n\n<p>You'll see that Batik's version seems to be loaded from the Java plugin. And yours is being loaded from \" \", which is most likely one of the built-in JVM loaders (boot classpath, ESOM, or classpath). </p>\n\n<p>The three prominent classloader models are:</p>\n\n<ul>\n<li>delegation (the default in the JDK - ask parent, then me)</li>\n<li>post-delegation (common in plugins, servlets, and places where you want isolation - ask me, then parent)</li>\n<li>sibling (common in dependency models like OSGi, Eclipse, etc)</li>\n</ul>\n\n<p>I don't know what delegation strategy the JPF classloader uses, but the key is that you want one version of the dom library to be loaded and everyone to source that class from the same location. That may mean removing it from the classpath and loading as a plugin, or preventing Batik from loading it, or something else.</p>\n" }, { "answer_id": 1784480, "author": "Anselm Schuster", "author_id": 217167, "author_profile": "https://Stackoverflow.com/users/217167", "pm_score": 2, "selected": false, "text": "<p>The answers from Alex and Matt are very helpful. I could benefit from their analysis too. </p>\n\n<p>I had the same problem when using the Batik library in a Netbeans RCP framework, the Batik library being included as a \"Library Wrapper Module\". If some other module makes use of XML apis, and no dependency on Batik is needed and established for that module, the class loader constraint violation problem arises with similar error messages.</p>\n\n<p>In Netbeans, individual modules use dedicated class loaders, and the dependence relationship between modules implies suitable class loader delegation routing.</p>\n\n<p>I could resolve the problem by simply omitting the xml-apis jar file from the Batik library bundle.</p>\n" }, { "answer_id": 24395292, "author": "vineetv2821993", "author_id": 2523281, "author_profile": "https://Stackoverflow.com/users/2523281", "pm_score": 3, "selected": false, "text": "<p>May be this will help someone because it works out pretty good for me. The issue can be solve by integrating your own dependencies. Follow this simple steps</p>\n\n<h2> First check the error which should be like this :</h2>\n\n<ul>\n<li>Method execution failed: </li>\n<li>java.lang.LinkageError: loader constraint violation:</li>\n<li>when resolving method \"org.slf4j.impl.<strong>StaticLoggerBinder</strong>.getLoggerFactory()Lorg/slf4j/ILoggerFactory;\" </li>\n<li>the class loader (instance of org/openmrs/module/ModuleClassLoader) of the current class, org/slf4j/<strong>LoggerFactory</strong>, </li>\n<li>and the class loader (instance of org/apache/catalina/loader/WebappClassLoader) for resolved class, org/slf4j/impl/<strong>StaticLoggerBinder</strong>, </li>\n<li>have different Class objects for the type taticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory; used in the signature</li>\n</ul>\n\n<hr>\n\n<ol start=\"2\">\n<li><p>See the two highlighted class. Google search for them like \"StaticLoggerBinder.class jar download\" &amp; \"LoggeraFactory.class jar download\". This will show you first or in some case second link (Site is <a href=\"http://www.java2s.com\" rel=\"nofollow noreferrer\">http://www.java2s.com</a> ) which is one of the jar version you have included in your project. You can smartly identify it yourself, but we are addicted of google ;)</p></li>\n<li><p>After that you will know the jar file name, in my case it is like slf4j-log4j12-1.5.6.jar &amp; slf4j-api-1.5.8</p></li>\n<li>Now the latest version of this file is available here <a href=\"http://mvnrepository.com/\" rel=\"nofollow noreferrer\">http://mvnrepository.com/</a> (actually all version till date, this is the site from where maven get your dependencies).</li>\n<li>Now add both file as a dependencies with the latest version (or keep both file version same, either chosen version is old). Following is the dependency you have to include in pom.xml</li>\n</ol>\n\n<hr>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;org.slf4j&lt;/groupId&gt;\n &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;\n &lt;version&gt;1.7.7&lt;/version&gt;\n&lt;/dependency&gt;\n&lt;dependency&gt;\n &lt;groupId&gt;org.slf4j&lt;/groupId&gt;\n &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;\n &lt;version&gt;1.7.7&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n\n<hr>\n\n<p><img src=\"https://i.stack.imgur.com/Rb1Iv.png\" alt=\"How to get dependecy definition from Maven Site\"></p>\n" }, { "answer_id": 54743902, "author": "Per Lundberg", "author_id": 227779, "author_profile": "https://Stackoverflow.com/users/227779", "pm_score": 1, "selected": false, "text": "<p>As specified in <a href=\"https://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm\">this question</a>, enabling the <code>-verbose:class</code> will make the JVM log information about all classes being loaded, which can be incredibly helpful to understand where the classes are coming from in more complex scenarios &amp; applications.</p>\n\n<p>The output you get looks roughly like this (copied from that question):</p>\n\n<pre><code>[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]\n[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n</code></pre>\n" }, { "answer_id": 58607052, "author": "zero zero", "author_id": 12284576, "author_profile": "https://Stackoverflow.com/users/12284576", "pm_score": 1, "selected": false, "text": "<p>I find this class be loaded twice. Find the reason is that parallelWebappClassLoader load class by itself first rather than use it's parent classLoader.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25141/" ]
Developing a heavily XML-based Java-application, I recently encountered an interesting problem on Ubuntu Linux. My application, using the [Java Plugin Framework](http://jpf.sourceforge.net/), appears unable to convert a [dom4j](http://www.dom4j.org/)-created XML document to [Batik's](http://xmlgraphics.apache.org/batik/) implementation of the SVG specification. On the console, I learn that an error occurs: ``` Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of <bootloader>) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature at org.apache.batik.dom.svg.SVGDOMImplementation.createDocument(SVGDOMImplementation.java:149) at org.dom4j.io.DOMWriter.createDomDocument(DOMWriter.java:361) at org.dom4j.io.DOMWriter.write(DOMWriter.java:138) ``` I figure that the problem is caused by a conflict between the original classloader from the JVM and the classloader deployed by the plugin framework. To my knowledge, it's not possible to specify a classloader for the framework to use. It might be possible to hack it, but I would prefer a less aggressive approach to solving this problem, since (for whatever reason) it only occurs on Linux systems. Has one of you encountered such a problem and has any idea how to fix it or at least get to the core of the issue?
LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is always treated as a different Class if loaded from another classloader. The message (which has improved a lot over the years) says: ``` Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of ) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature ``` So, here the problem is in resolving the SVGOMDocument.createAttribute() method, which uses org.w3c.dom.Attr (part of the standard DOM library). But, the version of Attr loaded with Batik was loaded from a different classloader than the instance of Attr you're passing to the method. You'll see that Batik's version seems to be loaded from the Java plugin. And yours is being loaded from " ", which is most likely one of the built-in JVM loaders (boot classpath, ESOM, or classpath). The three prominent classloader models are: * delegation (the default in the JDK - ask parent, then me) * post-delegation (common in plugins, servlets, and places where you want isolation - ask me, then parent) * sibling (common in dependency models like OSGi, Eclipse, etc) I don't know what delegation strategy the JPF classloader uses, but the key is that you want one version of the dom library to be loaded and everyone to source that class from the same location. That may mean removing it from the classpath and loading as a plugin, or preventing Batik from loading it, or something else.
244,489
<p>I have a managed dll that calls into a native library. This native library generally returns IntPtrs. These can be passed in to other methods in the native library to do things, or to tell the library to free the instance associated with the IntPtr. But only some of the instances need to freed in this way, others are managed by the library. The problem is that the documentation is not always clear about which instances must be freed and which must not.</p> <p>What I want to know is if there is a way that I can tell if my code has kept references to any of the pointers which must be freed, and so is causing memory to leak?</p>
[ { "answer_id": 244707, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": false, "text": "<p>Sounds like a classloader hierarchy problem. I can't tell what type of environment your application is deployed in, but sometimes this problem can occur in a web environment - where the application server creates a hierarchy of classloaders, resembling something like:</p>\n\n<p>javahome/lib - as root<br>\nappserver/lib - as child of root<br>\nwebapp/WEB-INF/lib - as child of child of root<br>\netc</p>\n\n<p>Usually classloaders delegate loading to their parent classloader (this is known as \"<code>parent-first</code>\"), and if that classloader cannot find the class, then the child classloader attempts to. For example, if a class deployed as a JAR in webapp/WEB-INF/lib tries to load a class, first it asks the classloader corresponding to appserver/lib to load the class (which in turn asks the classloader corresponding to javahome/lib to load the class), and if this lookup fails, then WEB-INF/lib is searched for a match to this class. </p>\n\n<p>In a web environment, you can run into problems with this hierarchy. For example, one mistake/problem I've run into before was when a class in WEB-INF/lib depended on a class deployed in appserver/lib, which in turn depended on a class deployed in WEB-INF/lib. This caused failures because while classloaders are able to delegate to the parent classloader, they cannot delegate back down the tree. So, the WEB-INF/lib classloader would ask appserver/lib classloader for a class, appserver/lib classloader would load that class and try to load the dependent class, and fail since it could not find that class in appserver/lib or javahome/lib.</p>\n\n<p>So, while you may not be deploying your app in a web/app server environment, my too-long explanation might apply to you if your environment has a hierarchy of classloaders set up. Does it? Is JPF doing some sort of classloader magic to be able to implement it's plugin features?</p>\n" }, { "answer_id": 244727, "author": "Adam Crume", "author_id": 25498, "author_profile": "https://Stackoverflow.com/users/25498", "pm_score": 3, "selected": false, "text": "<p>Can you specify a class loader? If not, try specifying the context class loader like so:</p>\n\n<pre><code>Thread thread = Thread.currentThread();\nClassLoader contextClassLoader = thread.getContextClassLoader();\ntry {\n thread.setContextClassLoader(yourClassLoader);\n callDom4j();\n} finally {\n thread.setContextClassLoader(contextClassLoader);\n}\n</code></pre>\n\n<p>I'm not familiar with the Java Plugin Framework, but I write code for Eclipse, and I run into similar issues from time to time. I don't guarantee it'll fix it, but it's probably worth a shot.</p>\n" }, { "answer_id": 245038, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 7, "selected": true, "text": "<p>LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is always treated as a different Class if loaded from another classloader.</p>\n\n<p>The message (which has improved a lot over the years) says:</p>\n\n<pre><code>Exception in thread \"AWT-EventQueue-0\" java.lang.LinkageError: \nloader constraint violation in interface itable initialization: \nwhen resolving method \"org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;\" \nthe class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) \nof the current class, org/apache/batik/dom/svg/SVGOMDocument, \nand the class loader (instance of ) for interface org/w3c/dom/Document \nhave different Class objects for the type org/w3c/dom/Attr used in the signature\n</code></pre>\n\n<p>So, here the problem is in resolving the SVGOMDocument.createAttribute() method, which uses org.w3c.dom.Attr (part of the standard DOM library). But, the version of Attr loaded with Batik was loaded from a different classloader than the instance of Attr you're passing to the method. </p>\n\n<p>You'll see that Batik's version seems to be loaded from the Java plugin. And yours is being loaded from \" \", which is most likely one of the built-in JVM loaders (boot classpath, ESOM, or classpath). </p>\n\n<p>The three prominent classloader models are:</p>\n\n<ul>\n<li>delegation (the default in the JDK - ask parent, then me)</li>\n<li>post-delegation (common in plugins, servlets, and places where you want isolation - ask me, then parent)</li>\n<li>sibling (common in dependency models like OSGi, Eclipse, etc)</li>\n</ul>\n\n<p>I don't know what delegation strategy the JPF classloader uses, but the key is that you want one version of the dom library to be loaded and everyone to source that class from the same location. That may mean removing it from the classpath and loading as a plugin, or preventing Batik from loading it, or something else.</p>\n" }, { "answer_id": 1784480, "author": "Anselm Schuster", "author_id": 217167, "author_profile": "https://Stackoverflow.com/users/217167", "pm_score": 2, "selected": false, "text": "<p>The answers from Alex and Matt are very helpful. I could benefit from their analysis too. </p>\n\n<p>I had the same problem when using the Batik library in a Netbeans RCP framework, the Batik library being included as a \"Library Wrapper Module\". If some other module makes use of XML apis, and no dependency on Batik is needed and established for that module, the class loader constraint violation problem arises with similar error messages.</p>\n\n<p>In Netbeans, individual modules use dedicated class loaders, and the dependence relationship between modules implies suitable class loader delegation routing.</p>\n\n<p>I could resolve the problem by simply omitting the xml-apis jar file from the Batik library bundle.</p>\n" }, { "answer_id": 24395292, "author": "vineetv2821993", "author_id": 2523281, "author_profile": "https://Stackoverflow.com/users/2523281", "pm_score": 3, "selected": false, "text": "<p>May be this will help someone because it works out pretty good for me. The issue can be solve by integrating your own dependencies. Follow this simple steps</p>\n\n<h2> First check the error which should be like this :</h2>\n\n<ul>\n<li>Method execution failed: </li>\n<li>java.lang.LinkageError: loader constraint violation:</li>\n<li>when resolving method \"org.slf4j.impl.<strong>StaticLoggerBinder</strong>.getLoggerFactory()Lorg/slf4j/ILoggerFactory;\" </li>\n<li>the class loader (instance of org/openmrs/module/ModuleClassLoader) of the current class, org/slf4j/<strong>LoggerFactory</strong>, </li>\n<li>and the class loader (instance of org/apache/catalina/loader/WebappClassLoader) for resolved class, org/slf4j/impl/<strong>StaticLoggerBinder</strong>, </li>\n<li>have different Class objects for the type taticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory; used in the signature</li>\n</ul>\n\n<hr>\n\n<ol start=\"2\">\n<li><p>See the two highlighted class. Google search for them like \"StaticLoggerBinder.class jar download\" &amp; \"LoggeraFactory.class jar download\". This will show you first or in some case second link (Site is <a href=\"http://www.java2s.com\" rel=\"nofollow noreferrer\">http://www.java2s.com</a> ) which is one of the jar version you have included in your project. You can smartly identify it yourself, but we are addicted of google ;)</p></li>\n<li><p>After that you will know the jar file name, in my case it is like slf4j-log4j12-1.5.6.jar &amp; slf4j-api-1.5.8</p></li>\n<li>Now the latest version of this file is available here <a href=\"http://mvnrepository.com/\" rel=\"nofollow noreferrer\">http://mvnrepository.com/</a> (actually all version till date, this is the site from where maven get your dependencies).</li>\n<li>Now add both file as a dependencies with the latest version (or keep both file version same, either chosen version is old). Following is the dependency you have to include in pom.xml</li>\n</ol>\n\n<hr>\n\n<pre><code>&lt;dependency&gt;\n &lt;groupId&gt;org.slf4j&lt;/groupId&gt;\n &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;\n &lt;version&gt;1.7.7&lt;/version&gt;\n&lt;/dependency&gt;\n&lt;dependency&gt;\n &lt;groupId&gt;org.slf4j&lt;/groupId&gt;\n &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;\n &lt;version&gt;1.7.7&lt;/version&gt;\n&lt;/dependency&gt;\n</code></pre>\n\n<hr>\n\n<p><img src=\"https://i.stack.imgur.com/Rb1Iv.png\" alt=\"How to get dependecy definition from Maven Site\"></p>\n" }, { "answer_id": 54743902, "author": "Per Lundberg", "author_id": 227779, "author_profile": "https://Stackoverflow.com/users/227779", "pm_score": 1, "selected": false, "text": "<p>As specified in <a href=\"https://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm\">this question</a>, enabling the <code>-verbose:class</code> will make the JVM log information about all classes being loaded, which can be incredibly helpful to understand where the classes are coming from in more complex scenarios &amp; applications.</p>\n\n<p>The output you get looks roughly like this (copied from that question):</p>\n\n<pre><code>[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]\n[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]\n[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]\n</code></pre>\n" }, { "answer_id": 58607052, "author": "zero zero", "author_id": 12284576, "author_profile": "https://Stackoverflow.com/users/12284576", "pm_score": 1, "selected": false, "text": "<p>I find this class be loaded twice. Find the reason is that parallelWebappClassLoader load class by itself first rather than use it's parent classLoader.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a managed dll that calls into a native library. This native library generally returns IntPtrs. These can be passed in to other methods in the native library to do things, or to tell the library to free the instance associated with the IntPtr. But only some of the instances need to freed in this way, others are managed by the library. The problem is that the documentation is not always clear about which instances must be freed and which must not. What I want to know is if there is a way that I can tell if my code has kept references to any of the pointers which must be freed, and so is causing memory to leak?
LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is always treated as a different Class if loaded from another classloader. The message (which has improved a lot over the years) says: ``` Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of ) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature ``` So, here the problem is in resolving the SVGOMDocument.createAttribute() method, which uses org.w3c.dom.Attr (part of the standard DOM library). But, the version of Attr loaded with Batik was loaded from a different classloader than the instance of Attr you're passing to the method. You'll see that Batik's version seems to be loaded from the Java plugin. And yours is being loaded from " ", which is most likely one of the built-in JVM loaders (boot classpath, ESOM, or classpath). The three prominent classloader models are: * delegation (the default in the JDK - ask parent, then me) * post-delegation (common in plugins, servlets, and places where you want isolation - ask me, then parent) * sibling (common in dependency models like OSGi, Eclipse, etc) I don't know what delegation strategy the JPF classloader uses, but the key is that you want one version of the dom library to be loaded and everyone to source that class from the same location. That may mean removing it from the classpath and loading as a plugin, or preventing Batik from loading it, or something else.
244,506
<p>Given a list of urls, I would like to check that each url:</p> <ul> <li>Returns a 200 OK status code</li> <li>Returns a response within X amount of time</li> </ul> <p>The end goal is a system that is capable of flagging urls as potentially broken so that an administrator can review them.</p> <p>The script will be written in PHP and will most likely run on a daily basis via cron.</p> <p>The script will be processing approximately 1000 urls at a go.</p> <p>Question has two parts:</p> <ul> <li>Are there any bigtime gotchas with an operation like this, what issues have you run into?</li> <li>What is the best method for checking the status of a url in PHP considering both accuracy and performance?</li> </ul>
[ { "answer_id": 244513, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 2, "selected": false, "text": "<ol>\n<li>fopen() supports http URI.</li>\n<li>If you need more flexibility (such as timeout), look into the cURL extension.</li>\n</ol>\n" }, { "answer_id": 244518, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 3, "selected": false, "text": "<p>Look into cURL. There's a library for PHP.</p>\n\n<p>There's also an executable version of cURL so you could even write the script in bash.</p>\n" }, { "answer_id": 244529, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 0, "selected": false, "text": "<p>One potential problem you will undoubtably run into is when the box this script is running on looses access to the Internet... you'll get 1000 false positives.</p>\n\n<p>It would probably be better for your script to keep some type of history and only report a failure after 5 days of failure.</p>\n\n<p>Also, the script should be self-checking in some way (like checking a known good web site [google?]) before continuing with the standard checks.</p>\n" }, { "answer_id": 244538, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>I actually wrote something in PHP that does this over a database of 5k+ URLs. I used the PEAR class <a href=\"http://pear.php.net/package/HTTP_Request/docs/1.4.3/li_HTTP_Request.html\" rel=\"nofollow noreferrer\">HTTP_Request</a>, which has a method called <a href=\"http://pear.php.net/package/HTTP_Request/docs/1.4.3/HTTP_Request/HTTP_Request.html#methodgetResponseCode\" rel=\"nofollow noreferrer\">getResponseCode</a>(). I just iterate over the URLs, passing them to getResponseCode and evaluate the response.</p>\n\n<p>However, it doesn't work for FTP addresses, URLs that don't begin with http or https (unconfirmed, but I believe it's the case), and sites with invalid security certificates (a 0 is not found). Also, a 0 is returned for server-not-found (there's no status code for that).</p>\n\n<p>And it's probably easier than cURL as you include a few files and use a single function to get an integer code back.</p>\n" }, { "answer_id": 244542, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 1, "selected": false, "text": "<p>Seems like it might be a job for <a href=\"http://us.php.net/curl\" rel=\"nofollow noreferrer\">curl</a>.</p>\n\n<p>If you're not stuck on PHP Perl's LWP might be an answer too.</p>\n" }, { "answer_id": 244655, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 1, "selected": false, "text": "<p>You should also be aware of URLs returning 301 or 302 HTTP responses which redirect to another page. Generally this doesn't mean the link is invalid. For example, <a href=\"http://amazon.com\" rel=\"nofollow noreferrer\">http://amazon.com</a> returns 301 and redirects to <a href=\"http://www.amazon.com/\" rel=\"nofollow noreferrer\">http://www.amazon.com/</a>.</p>\n" }, { "answer_id": 244669, "author": "Henning", "author_id": 29549, "author_profile": "https://Stackoverflow.com/users/29549", "pm_score": 5, "selected": true, "text": "<p>Use the PHP cURL extension. Unlike fopen() it can also make HTTP HEAD requests which are sufficient to check the availability of a URL and save you a ton of bandwith as you don't have to download the entire body of the page to check.</p>\n\n<p>As a starting point you could use some function like this:</p>\n\n<pre><code>function is_available($url, $timeout = 30) {\n $ch = curl_init(); // get cURL handle\n\n // set cURL options\n $opts = array(CURLOPT_RETURNTRANSFER =&gt; true, // do not output to browser\n CURLOPT_URL =&gt; $url, // set URL\n CURLOPT_NOBODY =&gt; true, // do a HEAD request only\n CURLOPT_TIMEOUT =&gt; $timeout); // set timeout\n curl_setopt_array($ch, $opts); \n\n curl_exec($ch); // do it!\n\n $retval = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; // check if HTTP OK\n\n curl_close($ch); // close handle\n\n return $retval;\n}\n</code></pre>\n\n<p>However, there's a ton of possible optimizations: You might want to re-use the cURL instance and, if checking more than one URL per host, even re-use the connection.</p>\n\n<p>Oh, and this code does check strictly for HTTP response code 200. It does not follow redirects (302) -- but there also is a cURL-option for that.</p>\n" }, { "answer_id": 244717, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 1, "selected": false, "text": "<p>Just returning a 200 response is not enough; many valid links will continue to return \"200\" after they change into porn / gambling portals when the former owner fails to renew.</p>\n\n<p>Domain squatters typically ensure that every URL in their domains returns 200.</p>\n" }, { "answer_id": 11370884, "author": "hammady", "author_id": 441849, "author_profile": "https://Stackoverflow.com/users/441849", "pm_score": 0, "selected": false, "text": "<p>You only need a bash script to do this. Please check my answer on a similar post <a href=\"https://stackoverflow.com/a/11370861/441849\">here</a>. It is a one-liner that reuses HTTP connections to dramatically improve speed, retries n times for temporary errors and follows redirects.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3238/" ]
Given a list of urls, I would like to check that each url: * Returns a 200 OK status code * Returns a response within X amount of time The end goal is a system that is capable of flagging urls as potentially broken so that an administrator can review them. The script will be written in PHP and will most likely run on a daily basis via cron. The script will be processing approximately 1000 urls at a go. Question has two parts: * Are there any bigtime gotchas with an operation like this, what issues have you run into? * What is the best method for checking the status of a url in PHP considering both accuracy and performance?
Use the PHP cURL extension. Unlike fopen() it can also make HTTP HEAD requests which are sufficient to check the availability of a URL and save you a ton of bandwith as you don't have to download the entire body of the page to check. As a starting point you could use some function like this: ``` function is_available($url, $timeout = 30) { $ch = curl_init(); // get cURL handle // set cURL options $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser CURLOPT_URL => $url, // set URL CURLOPT_NOBODY => true, // do a HEAD request only CURLOPT_TIMEOUT => $timeout); // set timeout curl_setopt_array($ch, $opts); curl_exec($ch); // do it! $retval = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200; // check if HTTP OK curl_close($ch); // close handle return $retval; } ``` However, there's a ton of possible optimizations: You might want to re-use the cURL instance and, if checking more than one URL per host, even re-use the connection. Oh, and this code does check strictly for HTTP response code 200. It does not follow redirects (302) -- but there also is a cURL-option for that.
244,509
<p>I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused.</p> <p>A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.</p>
[ { "answer_id": 244514, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 2, "selected": false, "text": "<p>AUTOINCREMENT is what you want. As long as you don't change the table's settings, AUTOINCREMENT will continue to grow.</p>\n" }, { "answer_id": 244516, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": true, "text": "<p>In MySQL that's the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html\" rel=\"nofollow noreferrer\">standard solution.</a></p>\n\n<pre><code>CREATE TABLE animals (\n id MEDIUMINT NOT NULL AUTO_INCREMENT,\n name CHAR(30) NOT NULL,\n PRIMARY KEY (id)\n );\n</code></pre>\n" }, { "answer_id": 244521, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>AUTOINCREMENT is the standard way to automatically create a unique key. It will start at 1 (or 0, I can't remember and it doesn't matter) then increment with each new record added to the table. If a record is deleted, its key will <em>not</em> be reused.</p>\n" }, { "answer_id": 244525, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 1, "selected": false, "text": "<p>Auto increment primary keys are relatively standard depending on which DBA you're talking to which week.</p>\n\n<p>I believe the basic identity integer will hit about 2 billion rows(is this right for mySQL?) before running out of room so you don't have to worry about hitting the cap.</p>\n" }, { "answer_id": 244527, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 1, "selected": false, "text": "<p>AUTO_INCREMENT is the common choice, it sets a number starting from 1 to every new row you insert. All the work of figuring out which number to use is done by the db, you just ask it back after inserting if you need to ( in php you get it by callin mysql_last_insertid I think )</p>\n" }, { "answer_id": 244530, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": "<p>Unless you have an overriding reason to generate your own PK then using the autoincrement would be good enough. That way the database manages the keys. When you are inserting a row you have to leave out the primary key column.</p>\n\n<p>Say you have a table table = (a, b, c) where a is the primary key then the insert statement would be </p>\n\n<p>insert into table (b, c) values ('bbb', 'ccc')</p>\n\n<p>and the primary key will be auto inserted by the databse.</p>\n" }, { "answer_id": 245064, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For something simple auto increment is best. For something more complicated that will ultimately have a lot of entries I generate a GUID and insert that as the key. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete a row, that row's key won't ever be reused. A preliminary search has turned up the AUTOINCREMENT keyword in mySQL. However, I'd still like to know if that will work for what I want and what the common solution to this issue is.
In MySQL that's the [standard solution.](http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html) ``` CREATE TABLE animals ( id MEDIUMINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (id) ); ```
244,517
<p>Where is a reliable registry key to find install location of Excel 2007?</p>
[ { "answer_id": 244578, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 0, "selected": false, "text": "<p>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\</p>\n" }, { "answer_id": 244580, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\X.0\\Common\\InstallRoot]\n</code></pre>\n\n<blockquote>\n <p>which contains a key named 'Path' with\n the installation directory of that\n version of Office. This is consistent\n for Excel 8.0 through 12.0. If you\n want to look for a specific product,\n use Excel, Word, Access, etc., in\n place of Common.</p>\n \n <ul>\n <li>Jon\n ------- Jon Peltier, Microsoft Excel MVP</li>\n </ul>\n</blockquote>\n\n<p>From: <a href=\"http://www.developersdex.com/vb/message.asp?p=2677&amp;r=6199020\" rel=\"noreferrer\">http://www.developersdex.com/vb/message.asp?p=2677&amp;r=6199020</a></p>\n" }, { "answer_id": 244589, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 1, "selected": false, "text": "<p>Here is another direction you can go. I have not tested this.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/240794\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/240794</a></p>\n" }, { "answer_id": 244734, "author": "Jason", "author_id": 16794, "author_profile": "https://Stackoverflow.com/users/16794", "pm_score": 0, "selected": false, "text": "<p>I have found this key to be consistent across all my Office 2007 installations. </p>\n\n<pre><code>[HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Components\\9B905EB838DBFEE4991CF8E66F518BBF]\n</code></pre>\n\n<p>If you are reading this, and you have Excel 2007, can you Vote this up (or leave a comment) if it is reliable for you too? (Vote it down, or post a comment if it is wrong?)</p>\n\n<p><strong>NOTE:</strong>\nThis is not consistent across my machines.</p>\n\n<pre><code>[HKLM\\SOFTWARE\\Microsoft\\Office\\X.0\\Common\\InstallRoot]\n</code></pre>\n" }, { "answer_id": 289009, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 3, "selected": false, "text": "<p>I'm using the following key:</p>\n\n<pre><code>[HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\excel.exe]\n</code></pre>\n\n<p>If the folder name contains Office12, you've got 2007. I'm using this method to decide during installation to install Office 2000-2003 addins or Office 2007 addins, as well as the folder to install them to.</p>\n\n<p>This is extremely reliable, and also works well with localized versions of Windows. So far we've tested on French, German, Spanish and Italian with much better success than the other methods we were previously using. XLSTART should be the same in all languages, but be wary when developing word addins as \"STARTUP\" is localized in some cases.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
Where is a reliable registry key to find install location of Excel 2007?
How about: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\X.0\Common\InstallRoot] ``` > > which contains a key named 'Path' with > the installation directory of that > version of Office. This is consistent > for Excel 8.0 through 12.0. If you > want to look for a specific product, > use Excel, Word, Access, etc., in > place of Common. > > > * Jon > ------- Jon Peltier, Microsoft Excel MVP > > > From: <http://www.developersdex.com/vb/message.asp?p=2677&r=6199020>
244,522
<p>I am writing a web application that will run in kiosk mode on a touch screen. I am currently only targeting it for running on Firefox 3. A few of the use cases I have need to visit external sites. I wish to do so with an embedded browser, which I'm tackling with the help of an <code>&lt;iframe&gt;</code>. I need back/forward buttons for the embedded home page. </p> <p>I've managed to access the history object of the iframe with</p> <pre><code>var w = document.getElementById('embeddedBrowser').contentWindow; w.history.back(); </code></pre> <p>The <code>history</code> of the embedded window is the same as that of the parent window. Therefore for a newly loaded <code>&lt;iframe&gt;</code>, this call will go back to the previous page of the system.</p> <p>Is there any way to avoid this or a more correct way of solving this?</p>
[ { "answer_id": 244742, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 1, "selected": false, "text": "<p>You might want to take a look at <a href=\"http://www.adobe.com/products/air/develop/ajax/\" rel=\"nofollow noreferrer\">Adobe AIR</a>. It lets you write your application using all the same tools / languages (ajax, html, etc etc), but since it runs as a desktop app and not in a web browser, you have more control over things, such as embedding browser frames and knowing exactly what they are doing, what URL it's going to, controlling it's history, etc. <a href=\"https://stackoverflow.com/questions/149338/adobe-air-book-from-htmljavascript-perspective#149432\">Look here</a> for a few pointers on getting started.</p>\n" }, { "answer_id": 245084, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 3, "selected": true, "text": "<p>Because there is only one history object shared within each tab this seems impossible. The proper way around it would be to test <code>window.history.current</code> or <code>window.history.previous</code> before calling back. Unfortunately, <code>window.history.current</code> is privileged and so not available to unsigned pages.</p>\n\n<p>Here's a rough sketch of a messy workaround:</p>\n\n<pre><code>&lt;iframe src=\"somepage.html\" name=\"myframe\"&gt;&lt;/iframe&gt;\n&lt;p&gt;&lt;a href=\"#\" id=\"backBtn\"&gt;Back&lt;/a&gt;&lt;/p&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n\n document.getElementById('backBtn').onclick = function () {\n if (window.frames['myframe'].location.hash !== '#stopper') {\n window.history.back();\n }\n // ... else hide the button?\n return false; // pop event bubble\n };\n window.frames['myframe'].onload = function () {\n this.location.hash = 'stopper';\n };\n\n&lt;/script&gt;\n</code></pre>\n\n<p>Of course, this is assuming that no (#hash) browsing ever goes on in parent window, and so on, but it seems to work for the problem of limiting back movement.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27349/" ]
I am writing a web application that will run in kiosk mode on a touch screen. I am currently only targeting it for running on Firefox 3. A few of the use cases I have need to visit external sites. I wish to do so with an embedded browser, which I'm tackling with the help of an `<iframe>`. I need back/forward buttons for the embedded home page. I've managed to access the history object of the iframe with ``` var w = document.getElementById('embeddedBrowser').contentWindow; w.history.back(); ``` The `history` of the embedded window is the same as that of the parent window. Therefore for a newly loaded `<iframe>`, this call will go back to the previous page of the system. Is there any way to avoid this or a more correct way of solving this?
Because there is only one history object shared within each tab this seems impossible. The proper way around it would be to test `window.history.current` or `window.history.previous` before calling back. Unfortunately, `window.history.current` is privileged and so not available to unsigned pages. Here's a rough sketch of a messy workaround: ``` <iframe src="somepage.html" name="myframe"></iframe> <p><a href="#" id="backBtn">Back</a></p> <script type="text/javascript"> document.getElementById('backBtn').onclick = function () { if (window.frames['myframe'].location.hash !== '#stopper') { window.history.back(); } // ... else hide the button? return false; // pop event bubble }; window.frames['myframe'].onload = function () { this.location.hash = 'stopper'; }; </script> ``` Of course, this is assuming that no (#hash) browsing ever goes on in parent window, and so on, but it seems to work for the problem of limiting back movement.
244,531
<p>I need to search a string and replace all occurrences of <code>%FirstName%</code> and <code>%PolicyAmount%</code> with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the <code>String.Replace()</code> method. I've seen web pages on the subject that suggest</p> <pre><code>Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase); </code></pre> <p>However for some reason when I try and replace <code>%PolicyAmount%</code> with <code>$0</code>, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex. </p> <p>Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?</p>
[ { "answer_id": 244539, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<pre><code>Regex.Replace(strInput, strToken.Replace(\"$\", \"[$]\"), strReplaceWith, RegexOptions.IgnoreCase);\n</code></pre>\n" }, { "answer_id": 244559, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<p>The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.</p>\n\n<p>Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.</p>\n" }, { "answer_id": 244585, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx\" rel=\"noreferrer\">From MSDN</a><br />\n$0 - \"Substitutes the last substring matched by group number number (decimal).\"</p>\n\n<p>In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to</p>\n\n<pre><code>string value = Regex.Replace(\"%PolicyAmount%\", \"%PolicyAmount%\", @\"$$0\", RegexOptions.IgnoreCase);\n</code></pre>\n" }, { "answer_id": 244933, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 8, "selected": false, "text": "<p>Seems like <code>string.Replace</code> <em>should</em> have an overload that takes a <code>StringComparison</code> argument. Since it doesn't, you could try something like this:</p>\n\n<pre><code>public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)\n{\n StringBuilder sb = new StringBuilder();\n\n int previousIndex = 0;\n int index = str.IndexOf(oldValue, comparison);\n while (index != -1)\n {\n sb.Append(str.Substring(previousIndex, index - previousIndex));\n sb.Append(newValue);\n index += oldValue.Length;\n\n previousIndex = index;\n index = str.IndexOf(oldValue, index, comparison);\n }\n sb.Append(str.Substring(previousIndex));\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 3551121, "author": "CleverPatrick", "author_id": 22399, "author_profile": "https://Stackoverflow.com/users/22399", "pm_score": 5, "selected": false, "text": "<p>Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:</p>\n\n<pre><code>string res = Microsoft.VisualBasic.Strings.Replace(res, \n \"%PolicyAmount%\", \n \"$0\", \n Compare: Microsoft.VisualBasic.CompareMethod.Text);\n</code></pre>\n\n<p>In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.</p>\n" }, { "answer_id": 4627100, "author": "Allanrbo", "author_id": 40645, "author_profile": "https://Stackoverflow.com/users/40645", "pm_score": 2, "selected": false, "text": "<p>a version similar to C. Dragon's, but for if you only need a single replacement:</p>\n\n<pre><code>int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);\nif (n &gt;= 0)\n{\n myText = myText.Substring(0, n)\n + newValue\n + myText.Substring(n + oldValue.Length);\n}\n</code></pre>\n" }, { "answer_id": 6755752, "author": "rboarman", "author_id": 131818, "author_profile": "https://Stackoverflow.com/users/131818", "pm_score": 5, "selected": false, "text": "<p>Here's an extension method. Not sure where I found it.</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)\n {\n int startIndex = 0;\n while (true)\n {\n startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);\n if (startIndex == -1)\n break;\n\n originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);\n\n startIndex += newValue.Length;\n }\n\n return originalString;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 12051066, "author": "Karl Glennon", "author_id": 23393, "author_profile": "https://Stackoverflow.com/users/23393", "pm_score": 4, "selected": false, "text": "<pre><code> /// &lt;summary&gt;\n /// A case insenstive replace function.\n /// &lt;/summary&gt;\n /// &lt;param name=\"originalString\"&gt;The string to examine.(HayStack)&lt;/param&gt;\n /// &lt;param name=\"oldValue\"&gt;The value to replace.(Needle)&lt;/param&gt;\n /// &lt;param name=\"newValue\"&gt;The new value to be inserted&lt;/param&gt;\n /// &lt;returns&gt;A string&lt;/returns&gt;\n public static string CaseInsenstiveReplace(string originalString, string oldValue, string newValue)\n {\n Regex regEx = new Regex(oldValue,\n RegexOptions.IgnoreCase | RegexOptions.Multiline);\n return regEx.Replace(originalString, newValue);\n }\n</code></pre>\n" }, { "answer_id": 24580455, "author": "ruffin", "author_id": 1028230, "author_profile": "https://Stackoverflow.com/users/1028230", "pm_score": 6, "selected": false, "text": "<p>Kind of a confusing group of answers, in part because the title of the question is actually <em>much</em> larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.</p>\n\n<p>Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.</p>\n\n<pre><code>public static string ReplaceCaseInsensitiveFind(this string str, string findMe,\n string newValue)\n{\n return Regex.Replace(str,\n Regex.Escape(findMe),\n Regex.Replace(newValue, \"\\\\$[0-9]+\", @\"$$$0\"),\n RegexOptions.IgnoreCase);\n}\n</code></pre>\n\n<p>So...</p>\n\n<ul>\n<li>This is <a href=\"https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive#comment5549925_244933\">an extension method</a> @MarkRobinson </li>\n<li>This <a href=\"https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive#comment5771414_244933\">doesn't try to skip Regex</a> @Helge (you really have to do byte-by-byte if you want to string sniff like this outside of Regex)</li>\n<li>Passes @MichaelLiu 's <a href=\"https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive#comment31063745_244933\">excellent test case</a>, <code>\"œ\".ReplaceCaseInsensitiveFind(\"oe\", \"\")</code>, though he may have had a slightly different behavior in mind.</li>\n</ul>\n\n<p>Unfortunately, <a href=\"https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive/244933#comment19010354_244585\">@HA 's comment that you have to <code>Escape</code> all three isn't correct</a>. The initial value and <code>newValue</code> doesn't need to be.</p>\n\n<p><strong>Note:</strong> You do, however, have to escape <code>$</code>s in the new value that you're inserting <strong>if they're part of what would appear to be a \"captured value\" marker</strong>. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...</p>\n\n<p><code>\"This is HIS fork, hIs spoon, hissssssss knife.\".ReplaceCaseInsensitiveFind(\"his\", @\"he$0r\")</code></p>\n\n<p>Here's the error:</p>\n\n<pre><code>An unhandled exception of type 'System.ArgumentException' occurred in System.dll\n\nAdditional information: parsing \"The\\hisr\\ is\\ he\\HISr\\ fork,\\ he\\hIsr\\ spoon,\\ he\\hisrsssssss\\ knife\\.\" - Unrecognized escape sequence \\h.\n</code></pre>\n\n<p>Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read <a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"noreferrer\">Spolsky on encodings</a>) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on \"<a href=\"http://www.htmlgoodies.com/html5/javascript/jslint-errors-and-options-described.html#fbid=49_PApIFUSX\" rel=\"noreferrer\">insecure regular expressions</a>\" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is <code>$10</code> really a valid \"capture value\" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.</p>\n\n<p>That weird <code>$</code> escaping (and that <code>Regex.Escape</code> didn't escape captured value patterns like <code>$0</code> as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842</p>\n" }, { "answer_id": 25318933, "author": "Brandon", "author_id": 738665, "author_profile": "https://Stackoverflow.com/users/738665", "pm_score": 1, "selected": false, "text": "<p>Here is another option for executing Regex replacements, since not many people seem to notice the matches contain the location within the string:</p>\n\n<pre><code> public static string ReplaceCaseInsensative( this string s, string oldValue, string newValue ) {\n var sb = new StringBuilder(s);\n int offset = oldValue.Length - newValue.Length;\n int matchNo = 0;\n foreach (Match match in Regex.Matches(s, Regex.Escape(oldValue), RegexOptions.IgnoreCase))\n {\n sb.Remove(match.Index - (offset * matchNo), match.Length).Insert(match.Index - (offset * matchNo), newValue);\n matchNo++;\n }\n return sb.ToString();\n }\n</code></pre>\n" }, { "answer_id": 25426773, "author": "JeroenV", "author_id": 3964020, "author_profile": "https://Stackoverflow.com/users/3964020", "pm_score": 3, "selected": false, "text": "<p>Inspired by cfeduke's answer, I made this function which uses IndexOf to find the old value in the string and then replaces it with the new value. I used this in an SSIS script processing millions of rows, and the regex-method was way slower than this.</p>\n\n<pre><code>public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)\n{\n int prevPos = 0;\n string retval = str;\n // find the first occurence of oldValue\n int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);\n\n while (pos &gt; -1)\n {\n // remove oldValue from the string\n retval = retval.Remove(pos, oldValue.Length);\n\n // insert newValue in it's place\n retval = retval.Insert(pos, newValue);\n\n // check if oldValue is found further down\n prevPos = pos + newValue.Length;\n pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);\n }\n\n return retval;\n}\n</code></pre>\n" }, { "answer_id": 39696868, "author": "Mark Cranness", "author_id": 365611, "author_profile": "https://Stackoverflow.com/users/365611", "pm_score": 2, "selected": false, "text": "<p>Based on Jeff Reddy's answer, with some optimisations and validations:</p>\n\n<pre><code>public static string Replace(string str, string oldValue, string newValue, StringComparison comparison)\n{\n if (oldValue == null)\n throw new ArgumentNullException(\"oldValue\");\n if (oldValue.Length == 0)\n throw new ArgumentException(\"String cannot be of zero length.\", \"oldValue\");\n\n StringBuilder sb = null;\n\n int startIndex = 0;\n int foundIndex = str.IndexOf(oldValue, comparison);\n while (foundIndex != -1)\n {\n if (sb == null)\n sb = new StringBuilder(str.Length + (newValue != null ? Math.Max(0, 5 * (newValue.Length - oldValue.Length)) : 0));\n sb.Append(str, startIndex, foundIndex - startIndex);\n sb.Append(newValue);\n\n startIndex = foundIndex + oldValue.Length;\n foundIndex = str.IndexOf(oldValue, startIndex, comparison);\n }\n\n if (startIndex == 0)\n return str;\n sb.Append(str, startIndex, str.Length - startIndex);\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 39792637, "author": "Chad Kuehn", "author_id": 1069995, "author_profile": "https://Stackoverflow.com/users/1069995", "pm_score": 3, "selected": false, "text": "<p>Expanding on <a href=\"https://stackoverflow.com/questions/244531/is-there-an-alternative-to-string-replace-that-is-case-insensitive#answer-244933\">C. Dragon 76</a>'s popular answer by making his code into an extension that overloads the default <code>Replace</code> method.</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)\n {\n StringBuilder sb = new StringBuilder();\n\n int previousIndex = 0;\n int index = str.IndexOf(oldValue, comparison);\n while (index != -1)\n {\n sb.Append(str.Substring(previousIndex, index - previousIndex));\n sb.Append(newValue);\n index += oldValue.Length;\n\n previousIndex = index;\n index = str.IndexOf(oldValue, index, comparison);\n }\n sb.Append(str.Substring(previousIndex));\n return sb.ToString();\n }\n}\n</code></pre>\n" }, { "answer_id": 48337741, "author": "Fredrik Johansson", "author_id": 325874, "author_profile": "https://Stackoverflow.com/users/325874", "pm_score": 0, "selected": false, "text": "<p>(Since everyone is taking a shot at this). Here's my version (with null checks, and correct input and replacement escaping) ** Inspired from around the internet and other versions:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\npublic static class MyExtensions {\n public static string ReplaceIgnoreCase(this string search, string find, string replace) {\n return Regex.Replace(search ?? \"\", Regex.Escape(find ?? \"\"), (replace ?? \"\").Replace(\"$\", \"$$\"), RegexOptions.IgnoreCase); \n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var result = \"This is a test\".ReplaceIgnoreCase(\"IS\", \"was\");\n</code></pre>\n" }, { "answer_id": 51447661, "author": "Simon Hewitt", "author_id": 616187, "author_profile": "https://Stackoverflow.com/users/616187", "pm_score": 0, "selected": false, "text": "<p>Let me make my case and then you can tear me to shreds if you like.</p>\n\n<p>Regex is not the answer for this problem - too slow and memory hungry, relatively speaking.</p>\n\n<p>StringBuilder is much better than string mangling.</p>\n\n<p>Since this will be an extension method to supplement <code>string.Replace</code>, I believe it important to match how that works - therefore throwing exceptions for the same argument issues is important as is returning the original string if a replacement was not made.</p>\n\n<p>I believe that having a StringComparison parameter is not a good idea.\nI did try it but the test case originally mentioned by michael-liu showed a problem:-</p>\n\n<pre><code>[TestCase(\"œ\", \"oe\", \"\", StringComparison.InvariantCultureIgnoreCase, Result = \"\")]\n</code></pre>\n\n<p>Whilst IndexOf will match, there is a mismatch between the length of the match in the source string (1) and oldValue.Length (2). This manifested itself by causing IndexOutOfRange in some other solutions when oldValue.Length was added to the current match position and I could not find a way around this.\nRegex fails to match the case anyway, so I took the pragmatic solution of only using <code>StringComparison.OrdinalIgnoreCase</code> for my solution.</p>\n\n<p>My code is similar to other answers but my twist is that I look for a match before going to the trouble of creating a <code>StringBuilder</code>. If none is found then a potentially large allocation is avoided. The code then becomes a <code>do{...}while</code> rather than a <code>while{...}</code></p>\n\n<p>I have done some extensive testing against other Answers and this came out fractionally faster and used slightly less memory.</p>\n\n<pre><code> public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)\n {\n if (str == null) throw new ArgumentNullException(nameof(str));\n if (oldValue == null) throw new ArgumentNullException(nameof(oldValue));\n if (oldValue.Length == 0) throw new ArgumentException(\"String cannot be of zero length.\", nameof(oldValue));\n\n var position = str.IndexOf(oldValue, 0, StringComparison.OrdinalIgnoreCase);\n if (position == -1) return str;\n\n var sb = new StringBuilder(str.Length);\n\n var lastPosition = 0;\n\n do\n {\n sb.Append(str, lastPosition, position - lastPosition);\n\n sb.Append(newValue);\n\n } while ((position = str.IndexOf(oldValue, lastPosition = position + oldValue.Length, StringComparison.OrdinalIgnoreCase)) != -1);\n\n sb.Append(str, lastPosition, str.Length - lastPosition);\n\n return sb.ToString();\n }\n</code></pre>\n" }, { "answer_id": 63315139, "author": "Markus Hartmair", "author_id": 1220972, "author_profile": "https://Stackoverflow.com/users/1220972", "pm_score": 2, "selected": false, "text": "<p>Since .NET Core 2.0 or .NET Standard 2.1 respectively, this is baked into the .NET runtime [1]:</p>\n<pre><code>&quot;hello world&quot;.Replace(&quot;World&quot;, &quot;csharp&quot;, StringComparison.CurrentCultureIgnoreCase); // &quot;hello csharp&quot;\n</code></pre>\n<p>[1] <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.string.replace#System_String_Replace_System_String_System_String_System_StringComparison\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.string.replace#System_String_Replace_System_String_System_String_System_StringComparison</a>_</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21155/" ]
I need to search a string and replace all occurrences of `%FirstName%` and `%PolicyAmount%` with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the `String.Replace()` method. I've seen web pages on the subject that suggest ``` Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase); ``` However for some reason when I try and replace `%PolicyAmount%` with `$0`, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex. Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?
[From MSDN](http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx) $0 - "Substitutes the last substring matched by group number number (decimal)." In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to ``` string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase); ```
244,588
<p>I was kind of scratching my head at this a week ago, and now with a little bit more Cocoa experience under my belt I feel like I have an inkling as to what might be going on. </p> <p>I'm making an application that is driven by a UINavigationController. In the AppDelegate, I create an instance of this class, using "page 1" as the Root View Controller.</p> <pre><code>UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:page1ViewController]; </code></pre> <p>Now here's where I'm having the problem. From "page 1" I'd like to use a modal view controller that slides over the interface and then disappears once the user has made an edit. I do that using code like this, inside of Page1ViewController:</p> <pre><code>[self presentModalViewController:myModalViewController animated:YES]; </code></pre> <p>When the Modal View Controller is gone, I want a value on "Page 1" to change based on what the user entered in the Modal View Controller. So, I wrote some code like this, which resides in the Modal View Controller: </p> <pre><code>[self.parentViewController dismissModalViewControllerAnimated:YES]; [self.parentViewController doSomethingPleaseWithSomeData:someData]; </code></pre> <p>The update to page 1 wasn't happening, and it took me a long time to realize that the "doSomethingPleaseWithSomeData" message was not being sent to Page1ViewController, but the Navigation Controller. </p> <p>Is this always to be expected when using Navigation Controllers? Did I perhaps configure something improperly? Is there an easy way to get at the View Controller that I want (in this case, Page1ViewController).</p>
[ { "answer_id": 244661, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "<p>There are a couple of ways you can handle this. The simplest is probably just to add a UIViewController property into myModalViewController and set it to page1Controller before you present it:</p>\n\n<pre><code>myModalViewController.logicalParent = self; //page1Controller\n[self presentModalViewController:myModalViewController animated:YES];\n</code></pre>\n\n<p>Just make sure you add the appropriate instance variable @property, and @synthesize for logicalParent to myModalViewController, then you will have a way to communicate data back to the ViewController that triggered the modal dialog. This is also for passing data back and forth between different levels of navigation before you push and pop them on the stack.</p>\n\n<p>The one important thing to worry about when doing this is that it is easy to get retain loops if you are not careful. Depending on exactly how you structure this you might need to use assign properties.</p>\n" }, { "answer_id": 281270, "author": "Alex", "author_id": 35999, "author_profile": "https://Stackoverflow.com/users/35999", "pm_score": 5, "selected": true, "text": "<p>I would recommend using the delegation pattern to solve your problem. Create a property</p>\n\n<pre><code>@property (nonatomic, assign) id &lt;MyModalViewDelegate&gt; delegate;\n</code></pre>\n\n<p>And a corresponding protocol</p>\n\n<pre><code>@protocol MyModalViewDelegate\n@optional\n - (void)myModalViewControllerDidFinish:(MyModalViewController *)aModalViewController;\n@end\n</code></pre>\n\n<p>When the user finishes with your view (e.g. taps the save button), send this message:</p>\n\n<pre><code>if ([self.delegate respondsToSelector:@selector(myModalViewControllerDidFinish:)])\n [self.delegate myModalViewControllerDidFinish:self];\n</code></pre>\n\n<p>Now, set the delegate to the view controller that should manage the whole thing, and it will be notified when the view controller is finished. Note that you'll need your view controller to dismiss the modal view controller. But, logically, that makes sense, since it was the object that presented the modal view controller in the first place.</p>\n\n<p>This is how Apple solves this problem in, for example, the UIImagePickerController and UIPersonPickerController.</p>\n" }, { "answer_id": 3788669, "author": "Michael", "author_id": 457474, "author_profile": "https://Stackoverflow.com/users/457474", "pm_score": 1, "selected": false, "text": "<p>I just ran into this same problem. It definitely seems that if you put a UIViewController embedded in a NavigationController, then when, from that UIViewController you present another UIViewController modally, the presentee thinks that the presenter is the NavigationController. In other words, parentViewController is incorrect.</p>\n\n<p>I bet this is a bug: either that, or the documentation seems incomplete. I will inquire.</p>\n" }, { "answer_id": 4478207, "author": "zgobolos", "author_id": 546998, "author_profile": "https://Stackoverflow.com/users/546998", "pm_score": 1, "selected": false, "text": "<p>Just ran into the same problem. I believe this is a bug. My scenario is the following:\nA navigation hierarchy with A, B and C view controllers in this order. On C there's a button that would open a modal view controller called D. Once D is presented the navigation controller drops C from its hierarchy which is a terrible behavior. Once D gets dismissed, the navigation controller <em>instantiates</em> a new C type view controller and pushes it into its hierarchy to recover the original one. Terrible. My solution is hacking the navigation hierarchy this way (a very bad solution but works well. with a 2 dimension array you could implement stacking modals):</p>\n\n<pre><code>- (void)presentModalViewController:(UIViewController *)c {\n [self.navigationHierarchy removeAllObjects];\n [self.navigationHierarchy addObjectsFromArray:[navigation viewControllers]];\n [navigation setViewControllers:[NSArray array] animated:YES];\n [navigation presentModalViewController:c animated:YES];\n}\n\n- (void)dismissModalViewController {\n [navigation dismissModalViewControllerAnimated:YES];\n [navigation setViewControllers:[NSArray arrayWithArray:self.navigationHierarchy] animated:YES];\n}\n</code></pre>\n\n<p>These two methods are defined where I maintain the main navigation hiererchy: the app delegate. navigation and navigationhierarchy are defined this way:</p>\n\n<pre><code>NSMutableArray *navigationHierarchy;\nUINavigationController *navigation;\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
I was kind of scratching my head at this a week ago, and now with a little bit more Cocoa experience under my belt I feel like I have an inkling as to what might be going on. I'm making an application that is driven by a UINavigationController. In the AppDelegate, I create an instance of this class, using "page 1" as the Root View Controller. ``` UINavigationController *aNavigationController = [[UINavigationController alloc] initWithRootViewController:page1ViewController]; ``` Now here's where I'm having the problem. From "page 1" I'd like to use a modal view controller that slides over the interface and then disappears once the user has made an edit. I do that using code like this, inside of Page1ViewController: ``` [self presentModalViewController:myModalViewController animated:YES]; ``` When the Modal View Controller is gone, I want a value on "Page 1" to change based on what the user entered in the Modal View Controller. So, I wrote some code like this, which resides in the Modal View Controller: ``` [self.parentViewController dismissModalViewControllerAnimated:YES]; [self.parentViewController doSomethingPleaseWithSomeData:someData]; ``` The update to page 1 wasn't happening, and it took me a long time to realize that the "doSomethingPleaseWithSomeData" message was not being sent to Page1ViewController, but the Navigation Controller. Is this always to be expected when using Navigation Controllers? Did I perhaps configure something improperly? Is there an easy way to get at the View Controller that I want (in this case, Page1ViewController).
I would recommend using the delegation pattern to solve your problem. Create a property ``` @property (nonatomic, assign) id <MyModalViewDelegate> delegate; ``` And a corresponding protocol ``` @protocol MyModalViewDelegate @optional - (void)myModalViewControllerDidFinish:(MyModalViewController *)aModalViewController; @end ``` When the user finishes with your view (e.g. taps the save button), send this message: ``` if ([self.delegate respondsToSelector:@selector(myModalViewControllerDidFinish:)]) [self.delegate myModalViewControllerDidFinish:self]; ``` Now, set the delegate to the view controller that should manage the whole thing, and it will be notified when the view controller is finished. Note that you'll need your view controller to dismiss the modal view controller. But, logically, that makes sense, since it was the object that presented the modal view controller in the first place. This is how Apple solves this problem in, for example, the UIImagePickerController and UIPersonPickerController.
244,591
<p>This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;</code></pre> I get the error. However, here is the part I don't get. If I comment out that line, the very next line<pre><code>foreach (string dir in lbFolders.SelectedItems)</code></pre> executes just fine.</p> <p>Edit: As usual, my communication skills are lacking. Let me clarify.</p> <p>I know that accessing GUI items from threads other than the ones they were created on causes problems. I know the right way to access them is via delegate.</p> <p>My question was mainly this: Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.</p>
[ { "answer_id": 244604, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 4, "selected": true, "text": "<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;\n</code></pre>\n\n<p>On that line you perform an assignment (<strong>set/add</strong>), which by default is not thread-safe.</p>\n\n<p>On the second line it's just a <strong>get</strong> operation, where thread-safety merely doesn't matter.</p>\n\n<p>EDIT: I don't mean access to the prgAll element.</p>\n\n<p>Accessing the Count property <strong>changes the internal state</strong> of the ListBox inner collection, that is why it throws the exception.</p>\n" }, { "answer_id": 244607, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "<p>The Count property of SelectedItems is not thread-safe, so you can't use it cross-thread. </p>\n" }, { "answer_id": 244612, "author": "Matt Warren", "author_id": 4500, "author_profile": "https://Stackoverflow.com/users/4500", "pm_score": 1, "selected": false, "text": "<p>You can't touch a GUI object from a thread that isn't the main GUI thread. See <a href=\"https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the\">here</a> for more details and the solution.</p>\n" }, { "answer_id": 244613, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "<p>You're trying to write to a control from a thread other than the main thread. Use Invoke or BeginInvoke.</p>\n\n<pre><code>void SetMax()\n{\n if (prgAll.InvokeRequired)\n {\n prgAll.BeginInvoke(new MethodInvoker(SetMax));\n return;\n }\n\n prgAll.Maximum = lbFolders.SelectedItems.Count;\n}\n</code></pre>\n" }, { "answer_id": 244614, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 4, "selected": false, "text": "<p>You can't access GUI elements from a separate thread. Use a delegate to make the change. </p>\n\n<p>eg.</p>\n\n<pre><code>lblStatus.Invoke((Action)(() =&gt; lblStatus.Text = counter.ToString()));\n</code></pre>\n\n<p>or older skool:</p>\n\n<pre><code>lblTest.Invoke((MethodInvoker)(delegate() \n{ \n lblTest.Text = i.ToString(); \n}));\n</code></pre>\n\n<p>I've got a blog post on how to do this in all the .Net releases <a href=\"http://rumandcode.wordpress.com/2008/07/17/doing-invokes-on-winform-controls-examples-from-delegates-to-lambdas/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 244657, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 1, "selected": false, "text": "<p>Because you created a control in a thread and you're trying to reach it from another one. Call the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx\" rel=\"nofollow noreferrer\">InvokeRequired</a> property as shown here:</p>\n\n<pre><code>private void RunMe()\n{\n if (!InvokeRequired)\n {\n myLabel.Text = \"You pushed the button!\";\n }\n else\n {\n Invoke(new ThreadStart(RunMe));\n }\n}\n</code></pre>\n" }, { "answer_id": 27435728, "author": "Gatherer", "author_id": 4041523, "author_profile": "https://Stackoverflow.com/users/4041523", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>private delegate void xThreadCallBack();\nprivate void ThreadCallBack()\n{\n if (this.InvokeRequired)\n {\n this.BeginInvoke(new xThreadCallBack(ThreadCallBack));\n }\n else\n {\n //do what you want\n }\n}\n</code></pre>\n\n<p>Though, the answer with the lambda expression would suffice.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this ``` prgAll.Maximum = lbFolders.SelectedItems.Count; ``` I get the error. However, here is the part I don't get. If I comment out that line, the very next line ``` foreach (string dir in lbFolders.SelectedItems) ``` executes just fine. Edit: As usual, my communication skills are lacking. Let me clarify. I know that accessing GUI items from threads other than the ones they were created on causes problems. I know the right way to access them is via delegate. My question was mainly this: Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.
``` prgAll.Maximum = lbFolders.SelectedItems.Count; ``` On that line you perform an assignment (**set/add**), which by default is not thread-safe. On the second line it's just a **get** operation, where thread-safety merely doesn't matter. EDIT: I don't mean access to the prgAll element. Accessing the Count property **changes the internal state** of the ListBox inner collection, that is why it throws the exception.
244,601
<p>I have YAML data that looks sort of like this, but ~150k of it:</p> <pre><code>--- all: foo: 1025 bar: baz: 37628 quux: a: 179 b: 7 </code></pre> <p>...or the same thing in JSON:</p> <pre><code>{"all":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"}} </code></pre> <p>I want to present this content in an expandable JavaScripty HTML tree view (examples: <a href="http://developer.yahoo.com/yui/examples/treeview/default_tree.html" rel="noreferrer">1</a>, <a href="http://www.mattkruse.com/javascript/mktree/" rel="noreferrer">2</a>) to make it easier to explore. How do I do this?</p> <p>I guess what I really want to figure out is how to take this YAML/JSON data, and automatically display it as a tree (with hash keys sorted alphabetically). So far, I've been tussling with <a href="http://developer.yahoo.com/yui/treeview/" rel="noreferrer">YUI's tree view</a>, but it doesn't accept straight JSON, and my feeble attempts to massage the data into something useful don't seem to be working.</p> <p>Thanks for any help.</p>
[ { "answer_id": 245117, "author": "user32225", "author_id": 32225, "author_profile": "https://Stackoverflow.com/users/32225", "pm_score": 1, "selected": false, "text": "<p>Version 2.6 of YUI's TreeView now does take a JavaScript object but not in this format and won't sort it automatically. You would have to use YUI's JSON utility to convert it to an actual JavaScript which you will have to traverse. Your sample will have to be converted to something like this:</p>\n\n<pre><code>{label:\"all\", children[\n {label:\"bar\", children:[\n {label:\"baz: 37628\"},\n {label:\"quux\", children[\n {label:\"a: 179\"},\n {label:\"b: 7\"}\n ]},\n {label:\"foo: 1025\"}\n ]}\n]}\n</code></pre>\n\n<p>I've probably missing some comma or something. Your incoming data might not be sorted so you will have to sort each array. Then, you just need to pass this object as the second argument to the TreeView constructor and the tree should appear.</p>\n" }, { "answer_id": 247415, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": false, "text": "<p>You can convert your JSON data to nicely nested DIVs with this. I haven't tested it with a wide number of datasets, but it seems to work.</p>\n\n<pre><code>function renderJSON(obj) {\n 'use strict';\n var keys = [],\n retValue = \"\";\n for (var key in obj) {\n if (typeof obj[key] === 'object') {\n retValue += \"&lt;div class='tree'&gt;\" + key;\n retValue += renderJSON(obj[key]);\n retValue += \"&lt;/div&gt;\";\n } else {\n retValue += \"&lt;div class='tree'&gt;\" + key + \" = \" + obj[key] + \"&lt;/div&gt;\";\n }\n\n keys.push(key);\n }\n return retValue;\n}\n</code></pre>\n" }, { "answer_id": 247531, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 4, "selected": true, "text": "<p>I finally came up with a super-elegant way to do this in about 5 lines of code, based on the fact that the simple <a href=\"http://en.wikipedia.org/wiki/YAML\" rel=\"nofollow noreferrer\">YAML</a> looks a lot like <a href=\"http://en.wikipedia.org/wiki/Markdown\" rel=\"nofollow noreferrer\">Markdown</a>.</p>\n\n<p>We're starting off with this:</p>\n\n<pre><code>---\nall:\n foo: 1025\n bar:\n baz: 37628\n quux:\n a: 179\n b: 7\n</code></pre>\n\n<p>Use regexps (in this case, in Perl) to remove the starting <code>---</code>, and put hyphens before the key on each line:</p>\n\n<pre><code>$data =~ s/^---\\n//s;\n$data =~ s/^(\\s*)(\\S.*)$/$1- $2/gm;\n</code></pre>\n\n<p>Voila, Markdown:</p>\n\n<pre><code>- all:\n - foo: 1025\n - bar:\n - baz: 37628\n - quux:\n - a: 179\n - b: 7\n</code></pre>\n\n<p>Now, just run it through a Markdown processor:</p>\n\n<pre><code>use Text::Markdown qw( markdown );\nprint markdown($data);\n</code></pre>\n\n<p>And you get an HTML list -- clean, semantic, backwards-compatible:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;all:\n &lt;ul&gt;\n &lt;li&gt;foo: 1025&lt;/li&gt;\n &lt;li&gt;bar:&lt;/li&gt;\n &lt;li&gt;baz: 37628&lt;/li&gt;\n &lt;li&gt;quux:\n &lt;ul&gt;\n &lt;li&gt;a: 179&lt;/li&gt;\n &lt;li&gt;b: 7&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><a href=\"http://developer.yahoo.com/yui/treeview/\" rel=\"nofollow noreferrer\">YUI Treeview</a> can enhance existing lists, so we wrap it all up:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;!-- CSS + JS served via YUI hosting: developer.yahoo.com/yui/articles/hosting/ --&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/combo?2.6.0/build/treeview/assets/skins/sam/treeview.css\"&gt;\n &lt;script type=\"text/javascript\" src=\"http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js&amp;2.6.0/build/treeview/treeview-min.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"markup\" class=\"yui-skin-sam\"&gt;\n &lt;!-- start Markdown-generated list --&gt;\n &lt;ul&gt;\n &lt;li&gt;all:\n &lt;ul&gt;\n &lt;li&gt;foo: 1025&lt;/li&gt;\n &lt;li&gt;bar:&lt;/li&gt;\n &lt;li&gt;baz: 37628&lt;/li&gt;\n &lt;li&gt;quux:\n &lt;ul&gt;\n &lt;li&gt;a: 179&lt;/li&gt;\n &lt;li&gt;b: 7&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;!-- end Markdown-generated list --&gt;\n &lt;/div&gt;\n &lt;script type=\"text/javascript\"&gt;\n var treeInit = function() {\n var tree = new YAHOO.widget.TreeView(\"markup\");\n tree.render();\n };\n YAHOO.util.Event.onDOMReady(treeInit);\n &lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>So this all works out to about 5 lines of code (turn YAML into Markdown, turn Markdown into an HTML list, and place that HTML list inside a template HTML file. The generated HTML's progressively-enhanced / degradable, since it's fully viewable on non-JavaScript browsers as a plain old list.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31100/" ]
I have YAML data that looks sort of like this, but ~150k of it: ``` --- all: foo: 1025 bar: baz: 37628 quux: a: 179 b: 7 ``` ...or the same thing in JSON: ``` {"all":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"}} ``` I want to present this content in an expandable JavaScripty HTML tree view (examples: [1](http://developer.yahoo.com/yui/examples/treeview/default_tree.html), [2](http://www.mattkruse.com/javascript/mktree/)) to make it easier to explore. How do I do this? I guess what I really want to figure out is how to take this YAML/JSON data, and automatically display it as a tree (with hash keys sorted alphabetically). So far, I've been tussling with [YUI's tree view](http://developer.yahoo.com/yui/treeview/), but it doesn't accept straight JSON, and my feeble attempts to massage the data into something useful don't seem to be working. Thanks for any help.
I finally came up with a super-elegant way to do this in about 5 lines of code, based on the fact that the simple [YAML](http://en.wikipedia.org/wiki/YAML) looks a lot like [Markdown](http://en.wikipedia.org/wiki/Markdown). We're starting off with this: ``` --- all: foo: 1025 bar: baz: 37628 quux: a: 179 b: 7 ``` Use regexps (in this case, in Perl) to remove the starting `---`, and put hyphens before the key on each line: ``` $data =~ s/^---\n//s; $data =~ s/^(\s*)(\S.*)$/$1- $2/gm; ``` Voila, Markdown: ``` - all: - foo: 1025 - bar: - baz: 37628 - quux: - a: 179 - b: 7 ``` Now, just run it through a Markdown processor: ``` use Text::Markdown qw( markdown ); print markdown($data); ``` And you get an HTML list -- clean, semantic, backwards-compatible: ``` <ul> <li>all: <ul> <li>foo: 1025</li> <li>bar:</li> <li>baz: 37628</li> <li>quux: <ul> <li>a: 179</li> <li>b: 7</li> </ul> </li> </ul> </li> </ul> ``` [YUI Treeview](http://developer.yahoo.com/yui/treeview/) can enhance existing lists, so we wrap it all up: ``` <html> <head> <!-- CSS + JS served via YUI hosting: developer.yahoo.com/yui/articles/hosting/ --> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.6.0/build/treeview/assets/skins/sam/treeview.css"> <script type="text/javascript" src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js&2.6.0/build/treeview/treeview-min.js"></script> </head> <body> <div id="markup" class="yui-skin-sam"> <!-- start Markdown-generated list --> <ul> <li>all: <ul> <li>foo: 1025</li> <li>bar:</li> <li>baz: 37628</li> <li>quux: <ul> <li>a: 179</li> <li>b: 7</li> </ul> </li> </ul> </li> </ul> <!-- end Markdown-generated list --> </div> <script type="text/javascript"> var treeInit = function() { var tree = new YAHOO.widget.TreeView("markup"); tree.render(); }; YAHOO.util.Event.onDOMReady(treeInit); </script> </body> </html> ``` So this all works out to about 5 lines of code (turn YAML into Markdown, turn Markdown into an HTML list, and place that HTML list inside a template HTML file. The generated HTML's progressively-enhanced / degradable, since it's fully viewable on non-JavaScript browsers as a plain old list.
244,639
<p>I have a medium size Java file. Everytime I make a change to one of my files, BuildTable.java, Git reports it as a massive change, even if is only a line or two. BuildTable.java is about 200 lines and the change in this commit only changed a single line.</p> <p>git-diff ouputs this:</p> <pre><code>--- a/src/BuildTable.java +++ b/src/BuildTable.java @@ -1 +1 @@ -import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file +import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file </code></pre> <p>After doing a git-commit -a</p> <pre><code>Created commit fe43985: better error notifications 3 files changed, 54 insertions(+), 50 deletions(-) rewrite src/BuildTable.java (78%) </code></pre> <p>Is Git seeing this file as binary or something? Is this a problem? If it is, how do I fix this?</p>
[ { "answer_id": 244713, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 5, "selected": false, "text": "<p>Clearly, git does not like your mac-style line endings (CR only). Its diff algorithm uses LF as the line separator.</p>\n\n<p>Fix your files to have windows-style (CR LF) or unix (LF only) line endings.</p>\n" }, { "answer_id": 244782, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>Set <code>core.autocrlf</code> and <code>core.safecrlf</code> with <a href=\"http://git-scm.com/docs/git-config\" rel=\"nofollow noreferrer\"><code>git-config</code></a>. This will cause git to automatically convert line endings when transferring from/to the object store. You might need to make a commit to store the \"new\" endings.</p>\n\n<p>Judging from your pasted example, you might be also suffering from \"old-style Mac line endings\" (thanks to <a href=\"https://stackoverflow.com/users/11549/ddaa\">ddaa</a> and <a href=\"https://stackoverflow.com/users/19563/charles-bailey\">Charles Bailey</a> for the hint), which are only bare <code>CR</code>s without any <code>LF</code>, a case not handled by git. If this is true (check with a hex editor), use a tool like <a href=\"http://linux.die.net/man/1/recode\" rel=\"nofollow noreferrer\"><code>recode</code></a> to translate this garbage into some 21st century format, like proper <code>LF</code>-only Unix line endings.</p>\n" }, { "answer_id": 251383, "author": "Paul Wicks", "author_id": 85, "author_profile": "https://Stackoverflow.com/users/85", "pm_score": 5, "selected": true, "text": "<p>To fix this, I didn't need to change any of the core git settings, as the default line endings being generated were fine, it was just that this particular file was mangled. To fix it I opened vim and executed the following command</p>\n\n<pre><code>:%s/^M/\\r/g\n</code></pre>\n\n<p>Note that to type the \"^M\" you have to type ctrl-V and then ctrl-M.</p>\n" }, { "answer_id": 1814909, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 0, "selected": false, "text": "<pre><code>git diff -b\n</code></pre>\n\n<p>Ignores end of line changes when showing you the differences.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I have a medium size Java file. Everytime I make a change to one of my files, BuildTable.java, Git reports it as a massive change, even if is only a line or two. BuildTable.java is about 200 lines and the change in this commit only changed a single line. git-diff ouputs this: ``` --- a/src/BuildTable.java +++ b/src/BuildTable.java @@ -1 +1 @@ -import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file +import java.io.FileNotFoundException;^Mimport java.io.FileReader;^Mimport java.io.InputStreamReader;^Mimport java.io.PushbackReader;^Mimport java.util.ArrayList;^Mimport \ No newline at end of file ``` After doing a git-commit -a ``` Created commit fe43985: better error notifications 3 files changed, 54 insertions(+), 50 deletions(-) rewrite src/BuildTable.java (78%) ``` Is Git seeing this file as binary or something? Is this a problem? If it is, how do I fix this?
To fix this, I didn't need to change any of the core git settings, as the default line endings being generated were fine, it was just that this particular file was mangled. To fix it I opened vim and executed the following command ``` :%s/^M/\r/g ``` Note that to type the "^M" you have to type ctrl-V and then ctrl-M.
244,640
<p>I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually “we” since it is a team effort) are developing that will interact with WCF services running on a remote server. (This is our first attempt at this, so we are in a learning mode). One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named “Contract”, “Loan” and “Terms”. Each table contains just one row. When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class;</p> <pre><code>private System.Data.DataSet _ds = null; public void BindData(System.Data.DataSet ds) { string sErr = ""; try { _ds = ds; // save to private member variable // more code goes down here } } </code></pre> <p>We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE.</p> <pre><code>private System.Windows.Forms.BindingSource bindsrcContract; private System.Windows.Forms.BindingSource bindsrcLoan; private System.Windows.Forms.BindingSource bindsrcTerms; </code></pre> <p>We are binding the values like this</p> <pre><code>if (bindsrcContract.DataSource == null) { bindsrcContract.DataSource = _ds; bindsrcContract.DataMember = “contract”; txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true)); txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true)); txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true)); txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true)); } if (bindsrcLoan.DataSource == null) { bindsrcLoan.DataSource = _ds; bindsrcLoan.DataMember = “loan”; mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true)); cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true)); } </code></pre> <p>This works when we do the first read from the service and get a dataset back. The information is displayed on the form's controls, we can update it using the form, and then “save” it by passing the changed values back to the WCF service.</p> <p>Here is our problem. If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information. Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service. On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet.</p> <p>We have tried everything we can think of, but clearly we are missing something. This is our first attempt at using the BindingSource control. We have tried</p> <pre><code>bindsrcContract.ResetBindings(false); </code></pre> <p>and </p> <pre><code>bindsrcContract.ResetBindings(true); </code></pre> <p>and </p> <pre><code>bindsrcContract.RaiseListChangedEvents = true; </code></pre> <p>and </p> <pre><code>for (int i = 0; i &lt; bindsrcContract.Count; i++) { bindsrcContract.ResetItem(i); } </code></pre> <p>As well as resetting the DataMember property again.</p> <pre><code>bindsrcContract.DataMember = ”Contract”; </code></pre> <p>We’ve looked at a lot of examples. Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but we’re not using one here. Can anyone please point out where we are going wrong, or point us to resources that will provide some more information?</p> <p>We’re using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server.</p> <p>Thanks in advance</p> <p>wes</p>
[ { "answer_id": 244983, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "<p>Failing all else, you can reassign the DataSource every time you receive a new dataset, doing something like this:</p>\n\n<pre><code>bindsrcContract.DataSource = typeof(System.Data.DataSet);\nbindsrcContract.DataSource = _ds;\n</code></pre>\n\n<p>(Also, initializing DataMember first and then DataSource will give you better performance.)</p>\n" }, { "answer_id": 248300, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 0, "selected": false, "text": "<p>Wes, I'm very glad I could help. I still remember an issue very similar to yours taking me weeks to figure out in the wild...</p>\n\n<p>Regarding your questions, here's all I know:</p>\n\n<ol>\n<li><p>If you set the DataSource first, then the DataMember, your data source will be scanned twice, since setting the DataMember subsequently changes the existing (valid) binding. If you do it the other way around, setting DataMember first (with DataSource being null or better, typeof(YourData)), binding only takes place once when you set the DataSource.</p></li>\n<li><p>I think you can apply the same solution here. Instead of just</p>\n\n<pre><code>bindsrcContract.DataSource = _ds;\n</code></pre>\n\n<p>in your last line, you should write</p>\n\n<pre><code>bindsrcContract.DataSource = typeof(System.Data.DataSet);\nbindsrcContract.DataSource = _ds;\n</code></pre></li>\n<li><p>Sorry to disappoint, but I learned all I know about data binding from MSDN as well as trial-and-error. It was quite painful. Hopefully someone else can chime in with a useful link or two.</p></li>\n</ol>\n" }, { "answer_id": 265471, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 1, "selected": false, "text": "<p>The underlying problem in both your questions is that the Binding-Manager keeps the links to the original objects.</p>\n<p>When you assign _ds as the DataSource, the Binding-Manager analyzes the DataSet and acts accordingly. If you assign some other DataSet to _ds, the Binding-Manager has no way of knowing this. It still has the reference on the original DataSet-object. So this explains why you have to reset the DataSource-property to the new DataSet.</p>\n<p>It also explains why the removing and adding of the table doesn't lead to your expected result. Again, the Binding-Manager holds the reference to the old table (or the first row in that table). The new table is never bound. Also in this case the reassigning of _ds does not help, because _ds points to the same DataSet-object as before. The Binding-Manager is smart enough to notice that it's the same object and does no rebinding action.</p>\n<p>You either have to modify the contents of your bound objects (which fires a PropertyChanged-Event to which the Binding-Manager subscribes) or you have to trigger a complete rebind by assigning a different object to the DataSource-property.</p>\n<p>This is a simplified description of what actually happens, but I hope it's enough to explain and solve your problem. Unfortunately I have yet to find a comprehensive explanation of WinForms databinding on the web (or elsewhere).</p>\n" }, { "answer_id": 4740912, "author": "Jimmy V", "author_id": 582131, "author_profile": "https://Stackoverflow.com/users/582131", "pm_score": 2, "selected": false, "text": "<p>I was having a similar issue today and found this works.</p>\n\n<pre><code>private void btnCancel_Click(object sender, EventArgs e)\n{\n this.MyTable.RejectChanges();\n this.txtMyBoundTextBox.DataBindings[0].ReadValue();\n this.EditState = EditStates.NotEditting;\n}\n</code></pre>\n" }, { "answer_id": 16346912, "author": "zeljko", "author_id": 2344678, "author_profile": "https://Stackoverflow.com/users/2344678", "pm_score": 0, "selected": false, "text": "<p>try combination :</p>\n\n<pre><code>bindingsource.EndEdit() // writting data to underlying source \nbindingSource.ResetBindings(false) // force controls to reread data from bindingSource\n</code></pre>\n\n<p>use this whenever you write something to controls.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually “we” since it is a team effort) are developing that will interact with WCF services running on a remote server. (This is our first attempt at this, so we are in a learning mode). One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named “Contract”, “Loan” and “Terms”. Each table contains just one row. When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class; ``` private System.Data.DataSet _ds = null; public void BindData(System.Data.DataSet ds) { string sErr = ""; try { _ds = ds; // save to private member variable // more code goes down here } } ``` We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE. ``` private System.Windows.Forms.BindingSource bindsrcContract; private System.Windows.Forms.BindingSource bindsrcLoan; private System.Windows.Forms.BindingSource bindsrcTerms; ``` We are binding the values like this ``` if (bindsrcContract.DataSource == null) { bindsrcContract.DataSource = _ds; bindsrcContract.DataMember = “contract”; txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true)); txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true)); txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true)); txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true)); } if (bindsrcLoan.DataSource == null) { bindsrcLoan.DataSource = _ds; bindsrcLoan.DataMember = “loan”; mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true)); cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true)); } ``` This works when we do the first read from the service and get a dataset back. The information is displayed on the form's controls, we can update it using the form, and then “save” it by passing the changed values back to the WCF service. Here is our problem. If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information. Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service. On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet. We have tried everything we can think of, but clearly we are missing something. This is our first attempt at using the BindingSource control. We have tried ``` bindsrcContract.ResetBindings(false); ``` and ``` bindsrcContract.ResetBindings(true); ``` and ``` bindsrcContract.RaiseListChangedEvents = true; ``` and ``` for (int i = 0; i < bindsrcContract.Count; i++) { bindsrcContract.ResetItem(i); } ``` As well as resetting the DataMember property again. ``` bindsrcContract.DataMember = ”Contract”; ``` We’ve looked at a lot of examples. Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but we’re not using one here. Can anyone please point out where we are going wrong, or point us to resources that will provide some more information? We’re using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server. Thanks in advance wes
I was having a similar issue today and found this works. ``` private void btnCancel_Click(object sender, EventArgs e) { this.MyTable.RejectChanges(); this.txtMyBoundTextBox.DataBindings[0].ReadValue(); this.EditState = EditStates.NotEditting; } ```
244,646
<p>I'm looking for the equivalent in Qt to <code>GetTickCount()</code></p> <p>Something that will allow me to measure the time it takes for a segment of code to run as in:</p> <pre><code>uint start = GetTickCount(); // do something.. uint timeItTook = GetTickCount() - start; </code></pre> <p>any suggestions?</p>
[ { "answer_id": 244676, "author": "Dusty Campbell", "author_id": 2174, "author_profile": "https://Stackoverflow.com/users/2174", "pm_score": 8, "selected": true, "text": "<p>How about <a href=\"http://doc.qt.io/qt-5/qtime.html\" rel=\"noreferrer\"><code>QTime</code></a>? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this:</p>\n\n<pre><code>QTime myTimer;\nmyTimer.start();\n// do something..\nint nMilliseconds = myTimer.elapsed();\n</code></pre>\n" }, { "answer_id": 4381741, "author": "sivabudh", "author_id": 65313, "author_profile": "https://Stackoverflow.com/users/65313", "pm_score": 7, "selected": false, "text": "<p>I think it's probably better to use <a href=\"http://doc.qt.io/qt-5/qelapsedtimer.html\" rel=\"noreferrer\"><code>QElapsedTimer</code></a> since that is why the class exists in the first place. It was introduced with Qt 4.7. Note that it is also immuned to system's clock time change.</p>\n\n<p>Example usage:</p>\n\n<pre><code>#include &lt;QDebug&gt;\n#include &lt;QElapsedTimer&gt;\n...\n...\nQElapsedTimer timer;\ntimer.start();\nslowOperation(); // we want to measure the time of this slowOperation()\nqDebug() &lt;&lt; timer.elapsed();\n</code></pre>\n" }, { "answer_id": 13003265, "author": "Lilian A. Moraru", "author_id": 1020714, "author_profile": "https://Stackoverflow.com/users/1020714", "pm_score": 5, "selected": false, "text": "<p>Even if the first answer was accepted, the rest of the people who read the answers should consider <code>sivabudh</code>'s suggestion. <br/>\n<a href=\"http://doc.qt.io/qt-5/qelapsedtimer.html\" rel=\"noreferrer\"><code>QElapsedTimer</code></a> can also be used to calculate the time in nanoseconds. <br/>\nCode example:</p>\n\n<pre><code>QElapsedTimer timer;\nqint64 nanoSec;\ntimer.start();\n//something happens here\nnanoSec = timer.nsecsElapsed();\n//printing the result(nanoSec)\n//something else happening here\ntimer.restart();\n//some other operation\nnanoSec = timer.nsecsElapsed();\n</code></pre>\n" }, { "answer_id": 22772205, "author": "Oliver Hoffmann", "author_id": 1633383, "author_profile": "https://Stackoverflow.com/users/1633383", "pm_score": 2, "selected": false, "text": "<p>If you want to use <a href=\"http://doc.qt.io/qt-5/qelapsedtimer.html\" rel=\"nofollow\"><code>QElapsedTimer</code></a>, you should consider the overhead of this class.</p>\n\n<p>For example, the following code run on my machine:</p>\n\n<pre><code>static qint64 time = 0;\nstatic int count = 0;\nQElapsedTimer et;\net.start();\ntime += et.nsecsElapsed();\nif (++count % 10000 == 0)\n qDebug() &lt;&lt; \"timing:\" &lt;&lt; (time / count) &lt;&lt; \"ns/call\";\n</code></pre>\n\n<p>gives me this output:</p>\n\n<pre><code>timing: 90 ns/call \ntiming: 89 ns/call \n...\n</code></pre>\n\n<p>You should measure this for yourself and respect the overhead for your timing.</p>\n" }, { "answer_id": 38651310, "author": "Damien", "author_id": 919155, "author_profile": "https://Stackoverflow.com/users/919155", "pm_score": 2, "selected": false, "text": "<p>Expending the previous answers, here is a macro that does everything for you.</p>\n\n<pre><code>#include &lt;QDebug&gt;\n#include &lt;QElapsedTimer&gt;\n#define CONCAT_(x,y) x##y\n#define CONCAT(x,y) CONCAT_(x,y)\n\n#define CHECKTIME(x) \\\n QElapsedTimer CONCAT(sb_, __LINE__); \\\n CONCAT(sb_, __LINE__).start(); \\\n x \\\n qDebug() &lt;&lt; __FUNCTION__ &lt;&lt; \":\" &lt;&lt; __LINE__ &lt;&lt; \" Elapsed time: \" &lt;&lt; CONCAT(sb_, __LINE__).elapsed() &lt;&lt; \" ms.\";\n</code></pre>\n\n<p>And then you can simple use as:</p>\n\n<pre><code>CHECKTIME(\n // any code\n for (int i=0; i&lt;1000; i++)\n {\n timeConsumingFunc();\n }\n)\n</code></pre>\n\n<p>output:</p>\n\n<blockquote>\n <p>onSpeedChanged : 102 Elapsed time: 2 ms.</p>\n</blockquote>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
I'm looking for the equivalent in Qt to `GetTickCount()` Something that will allow me to measure the time it takes for a segment of code to run as in: ``` uint start = GetTickCount(); // do something.. uint timeItTook = GetTickCount() - start; ``` any suggestions?
How about [`QTime`](http://doc.qt.io/qt-5/qtime.html)? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this: ``` QTime myTimer; myTimer.start(); // do something.. int nMilliseconds = myTimer.elapsed(); ```
244,665
<p>This is the css for setting the color for h1 text that is linked:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-left h1 a, a:visited { color: #055830; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="nav-left"&gt; &lt;h1&gt;&lt;a href="/index.php/housing/"&gt;Housing&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>It does not look like it is working appropriately, any help is appreciated.</p>
[ { "answer_id": 244670, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 4, "selected": true, "text": "<p>What about:</p>\n\n<pre><code>.nav-left h1 a:visited{\n color:#055830;\n}\n</code></pre>\n" }, { "answer_id": 244681, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>.nav-left h1 a {\n color: #055830;\n}\n</code></pre>\n\n<p>You don't need to add a:visited if it is the same color.</p>\n" }, { "answer_id": 244688, "author": "Traingamer", "author_id": 27609, "author_profile": "https://Stackoverflow.com/users/27609", "pm_score": 2, "selected": false, "text": "<p>If you want them the same, you must be specific:</p>\n\n<p>.nav-left h1 a, a:visited</p>\n\n<p>is not the same as:</p>\n\n<p>.nav-left h1 a, <strong>.nav-left h1 a</strong>:visited</p>\n" }, { "answer_id": 244937, "author": "closetgeekshow", "author_id": 8691, "author_profile": "https://Stackoverflow.com/users/8691", "pm_score": 3, "selected": false, "text": "<p>if you want the colour to be the same for unvisited links you'll need to add a specific selector for that as well</p>\n\n<pre><code>.nav-left h1 a:link, .nav-left h1 a:visited {\n color:#055830;\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
This is the css for setting the color for h1 text that is linked: ```css .nav-left h1 a, a:visited { color: #055830; } ``` ```html <div class="nav-left"> <h1><a href="/index.php/housing/">Housing</a></h1> </div> ``` It does not look like it is working appropriately, any help is appreciated.
What about: ``` .nav-left h1 a:visited{ color:#055830; } ```
244,671
<p>I'm looking for an UPDATE statement where it will update a single duplicate row only and remain the rest (duplicate rows) intact as is, using ROWID or something else or other elements to utilize in Oracle SQL or PL/SQL?</p> <p>Here is an example duptest table to work with:</p> <pre><code>CREATE TABLE duptest (ID VARCHAR2(5), NONID VARCHAR2(5)); </code></pre> <ul> <li><p>run one <code>INSERT INTO duptest VALUES('1','a');</code> </p></li> <li><p>run four (4) times <code>INSERT INTO duptest VALUES('2','b');</code> </p></li> </ul> <p>Also, the first duplicate row has to be updated (not deleted), always, whereas the other three (3) have to be remained as is!</p> <p>Thanks a lot, Val.</p>
[ { "answer_id": 244757, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": false, "text": "<p>Will this work for you:</p>\n\n<pre><code>update duptest \nset nonid = 'c'\nWHERE ROWID IN (SELECT MIN (ROWID)\n FROM duptest \n GROUP BY id, nonid)\n</code></pre>\n" }, { "answer_id": 244809, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "<p>This worked for me, even for repeated runs.</p>\n\n<pre><code>--third, update the one row\nUPDATE DUPTEST DT\nSET DT.NONID = 'c'\nWHERE (DT.ID,DT.ROWID) IN(\n --second, find the row id of the first dup\n SELECT \n DT.ID\n ,MIN(DT.ROWID) AS FIRST_ROW_ID\n FROM DUPTEST DT\n WHERE ID IN(\n --first, find the dups\n SELECT ID\n FROM DUPTEST\n GROUP BY ID\n HAVING COUNT(*) &gt; 1\n )\n GROUP BY\n DT.ID\n )\n</code></pre>\n" }, { "answer_id": 244857, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 1, "selected": false, "text": "<p>I think this should work.</p>\n\n<pre><code>UPDATE DUPTEST SET NONID = 'C'\nWHERE ROWID in (\n Select ROWID from (\n SELECT ROWID, Row_Number() over (Partition By ID, NONID order by ID) rn\n ) WHERE rn = 1\n)\n</code></pre>\n" }, { "answer_id": 245969, "author": "Thorsten", "author_id": 25320, "author_profile": "https://Stackoverflow.com/users/25320", "pm_score": 0, "selected": false, "text": "<p>I know that this does not answer your initial question, but there is no key on your table and the problem you have adressing a specific row results from that.</p>\n\n<p>So my suggestion - if the specific application allows for it - would be to add a key column to your table (e.g. REAL_ID as INTEGER).</p>\n\n<p>Then you could find out the lowest id for the duplicates</p>\n\n<pre><code>select min (real_id) \nfrom duptest\ngroup by (id, nonid)\n</code></pre>\n\n<p>and update just these rows:</p>\n\n<pre><code>update duptest\nset nonid = 'C'\nwhere real_id in (&lt;select from above&gt;)\n</code></pre>\n\n<p>I'm sure the update statement can be tuned somewhat, but I hope it illustrates the idea.</p>\n\n<p>The advantage is a \"cleaner\" design (your id column is not really an id), and a more portable solution than relying on the DB-specific versions of rowid.</p>\n" }, { "answer_id": 277041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>UPDATE duptest \nSET nonid = 'c' \nWHERE nonid = 'b' \n AND rowid = (SELECT min(rowid) \n FROM duptest \n WHERE nonid = 'b');\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for an UPDATE statement where it will update a single duplicate row only and remain the rest (duplicate rows) intact as is, using ROWID or something else or other elements to utilize in Oracle SQL or PL/SQL? Here is an example duptest table to work with: ``` CREATE TABLE duptest (ID VARCHAR2(5), NONID VARCHAR2(5)); ``` * run one `INSERT INTO duptest VALUES('1','a');` * run four (4) times `INSERT INTO duptest VALUES('2','b');` Also, the first duplicate row has to be updated (not deleted), always, whereas the other three (3) have to be remained as is! Thanks a lot, Val.
Will this work for you: ``` update duptest set nonid = 'c' WHERE ROWID IN (SELECT MIN (ROWID) FROM duptest GROUP BY id, nonid) ```
244,677
<p>Can it be known in general whether or not placing a case within a for loop will result in bad assembly. I'm interested mainly in Delphi, but this is an interesting programming question, both in terms of style and performance. </p> <p>Here are my codez!</p> <pre> case ResultList.CompareType of TextCompareType: begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; end; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; </pre> <p>alternatively I could write </p> <pre> begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin case ResultList.CompareType of TextCompareType: begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; end; end; end; </pre> <p>I don't like the second way because I'm asking a question I know the answer to in a for loop and I don't like the first way because I'm repeating the code I use to figure out which of my objects contain valid information. </p> <p>Perhaps there is a design pattern someone could suggest that would circumvent this all together.</p>
[ { "answer_id": 244687, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": true, "text": "<p>Why not using subclasses? </p>\n\n<p>This saves the use of the case statement.</p>\n\n<pre><code>TComparer = class \nprotected\n function Compare(const AItem1, AItem2: TItem): Boolean; virtual; abstract;\npublic\n procedure DoCompare(ResultList: ...);\nend;\n\nTTextComparer = class (TComparer)\nprotected\n function Compare(const AItem1, AItem2: TItem): Boolean; override;\nend;\n\nprocedure TComparer.DoCompare(ResultList: ...);\nvar\n LastGoodIndex, I : Integer;\nbegin \n LastGoodIndex := -1;\n for I := 1 to ResultList.Count -1 do\n if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then\n LastGoodIndex := I\n else if not ResultList[I].Indeterminate then begin\n if Compare(ResultList[LastGoodIndex], ResultList[I]) then\n Result := TrueEval\n else \n Result := FalseEval;\n end;\nend;\n\nfunction TTextComparer.Compare(const AItem1, AItem2: TItem): Boolean; \nbegin\n Result := StrComp(ResultList[LastGoodIndex].ResultAsText,\n ResultList[I].ResultAsText) &gt; 0) \nend;\n</code></pre>\n" }, { "answer_id": 244747, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 1, "selected": false, "text": "<p>I suspect that it's more efficient to use a lambda or closure or even just a function reference. My Pascal's rusted right out, so my example is perl:</p>\n\n<pre><code>my %type = (\n TextCompareType =&gt; sub { $_[0] lt $_[1] },\n NumericCompareType =&gt; sub { $_[0] &lt; $_[1] },\n DateCompareType =&gt; sub { ... },\n BooleanCompareType =&gt; sub { ... },\n );\n\nfor (my $i = 1; $i &lt;= $#list; ++$i)\n{\n if ( $type{$ResultList{CompareType}}-&gt;($list[$i-1], $list[$i]) )\n {\n $result = 1; # ?\n }\n}\n</code></pre>\n\n<p>I'm not really following most of your code, but I think I've captured the essence of the question without fully capturing the code.</p>\n\n<p>Another solution is to create comparator objects as subclasses off a base comparator class, and then call the object's compare function, but you do mention trying to stay structured instead of OO.</p>\n" }, { "answer_id": 244761, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 2, "selected": false, "text": "<p>In general, there is no way to know what assembly-language output will be generated for particular programming-language constructs. Every compiler is different. Even for a particular compiler, every application will be different, and the compiler will have different optimization strategies available to it.</p>\n\n<p>If you are really worried about it, the easiest thing to do is compile the program and see what it generates. Play around with code and optimization settings until it looks how you want it to. (Or write assembly by hand.)</p>\n\n<p>The common advice is to just write the clearest code you can, and don't worry about tweaking performance unless you really need to.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
Can it be known in general whether or not placing a case within a for loop will result in bad assembly. I'm interested mainly in Delphi, but this is an interesting programming question, both in terms of style and performance. Here are my codez! ``` case ResultList.CompareType of TextCompareType: begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; end; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; ``` alternatively I could write ``` begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin case ResultList.CompareType of TextCompareType: begin if (StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) and (Result FalseEval) then Result := TrueEval else Result := FalseEval; LastGoodIndex := I; end; NumericCompareType: begin //Same as above with a numeric comparison end; DateCompareType: begin //Same as above with a date comparison end; BooleanCompareType: begin //Same as above with a boolean comparison end; end; end; end; ``` I don't like the second way because I'm asking a question I know the answer to in a for loop and I don't like the first way because I'm repeating the code I use to figure out which of my objects contain valid information. Perhaps there is a design pattern someone could suggest that would circumvent this all together.
Why not using subclasses? This saves the use of the case statement. ``` TComparer = class protected function Compare(const AItem1, AItem2: TItem): Boolean; virtual; abstract; public procedure DoCompare(ResultList: ...); end; TTextComparer = class (TComparer) protected function Compare(const AItem1, AItem2: TItem): Boolean; override; end; procedure TComparer.DoCompare(ResultList: ...); var LastGoodIndex, I : Integer; begin LastGoodIndex := -1; for I := 1 to ResultList.Count -1 do if (LastGoodIndex = -1) and (not ResultList[I].Indeterminate) then LastGoodIndex := I else if not ResultList[I].Indeterminate then begin if Compare(ResultList[LastGoodIndex], ResultList[I]) then Result := TrueEval else Result := FalseEval; end; end; function TTextComparer.Compare(const AItem1, AItem2: TItem): Boolean; begin Result := StrComp(ResultList[LastGoodIndex].ResultAsText, ResultList[I].ResultAsText) > 0) end; ```
244,680
<p>Can someone explain what this means?</p> <pre><code>int (*data[2])[2]; </code></pre>
[ { "answer_id": 244692, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p><strong>What are the parentheses for?</strong></p>\n\n<p>In C brackets [] have a higher precedence than the asterisk *</p>\n\n<p><strong>Good explanation from Wikipedia:</strong></p>\n\n<blockquote>\n <p>To declare a variable as being a\n pointer to an array, we must make use\n of parentheses. This is because in C\n brackets ([]) have higher precedence\n than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this:</p>\n</blockquote>\n\n<pre><code>double (*elephant)[20];\n</code></pre>\n\n<blockquote>\n <p>This declares that elephant is a\n pointer, and the type it points at is\n an array of 20 double values.</p>\n \n <p>To declare a pointer to an array of\n pointers, simply combine the\n notations.</p>\n</blockquote>\n\n<pre><code>int *(*crocodile)[15];\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/C_variable_types_and_declarations\" rel=\"noreferrer\">Source</a>.</p>\n\n<p><strong>And your actual case:</strong></p>\n\n<pre><code>int (*data[2])[5];\n</code></pre>\n\n<p>data is an array of 2 elements. Each element contains a pointer to an array of 5 ints.</p>\n\n<p>So you you could have in code using your 'data' type:</p>\n\n<pre><code>int (*data[2])[5];\nint x1[5];\ndata[0] = &amp;x1;\ndata[1] = &amp;x1;\n\ndata[2] = &amp;x1;//&lt;--- out of bounds, crash data has no 3rd element\nint y1[10];\ndata[0] = &amp;y1;//&lt;--- compiling error, each element of data must point to an int[5] not an int[10]\n</code></pre>\n" }, { "answer_id": 244705, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": false, "text": "<p>There is a very cool program called \"cdecl\" that you can download for Linux/Unix and probably for Windows as well. You paste in a C (or C++ if you use c++decl) variable declaration and it spells it out in simple words.</p>\n" }, { "answer_id": 244942, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": -1, "selected": false, "text": "<p>data[2] - an array of two integers</p>\n\n<p>*data[2] - a pointer to an array of two integers</p>\n\n<p>(*data[2]) - \"</p>\n\n<p>(*data[2])[2] - an array of 2 pointers to arrays of two integers.</p>\n" }, { "answer_id": 245688, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": false, "text": "<p>If you know how to read <em>expressions</em> in C, then you're one step away from reading complicated declarations.</p>\n\n<p>What does</p>\n\n<pre><code>char *p;\n</code></pre>\n\n<p>really mean? It means that <code>*p</code> is a char. What does</p>\n\n<pre><code>int (*data[2])[5];\n</code></pre>\n\n<p>mean? It means that <code>(*data[x])[y]</code> is an int (provided 0 &lt;= x &lt; 2 and 0 &lt;= y &lt; 5). Now, just think about what the implications of that are. <code>data</code> has to be... an array of 2... pointers... to arrays of 5... integers.</p>\n\n<p>Don't you think that's quite elegant? All you're doing is stating the type of an expression. Once you grasp that, declarations will never intimidate you again!</p>\n\n<p>The \"quick rule\" is to start with the variable name, scan to the right until you hit a ), go back to the variable name and scan to the left until you hit a (. Then \"step out\" of the pair of parentheses, and repeat the process.</p>\n\n<p>Let's apply it to something ridiculous:</p>\n\n<pre><code>void **(*(*weird)[6])(char, int);\n</code></pre>\n\n<p><code>weird</code> is a pointer to an array of 6 pointers to functions each accepting a char and an int as argument, and each returning a pointer to a pointer to void.</p>\n\n<p>Now that you know what it is and how it's done... <em>don't</em> do it. Use typedefs to break your declarations into more manageable chunks. E.g.</p>\n\n<pre><code>typedef void **(*sillyFunction)(char, int);\n\nsillyFunction (*weird)[6];\n</code></pre>\n" }, { "answer_id": 22361953, "author": "AbstractDonut", "author_id": 3408627, "author_profile": "https://Stackoverflow.com/users/3408627", "pm_score": -1, "selected": false, "text": "<p>If you have an array:</p>\n\n<pre><code>int myArray[5];\nint * myArrayPtr = myArray;\n</code></pre>\n\n<p>Would be perfectly reasonable. <code>myArray</code> without the brackets is a pointer to an <code>int</code>. When you add the brackets its like you deference the pointer <code>myArray</code>. You could write...</p>\n\n<pre><code>myArrayPtr[1] = 3;\n</code></pre>\n\n<p>Which is perfectly reasonable. Using parenthesis just makes things harder to read and understand IMO. And they show that people don't understand pointers, arrays, and pointer arithmetic, which is how the compiler or linker goes from one to the other. It seems with parenthesis you do get bounds checking though.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32185/" ]
Can someone explain what this means? ``` int (*data[2])[2]; ```
**What are the parentheses for?** In C brackets [] have a higher precedence than the asterisk \* **Good explanation from Wikipedia:** > > To declare a variable as being a > pointer to an array, we must make use > of parentheses. This is because in C > brackets ([]) have higher precedence > than the asterisk (\*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this: > > > ``` double (*elephant)[20]; ``` > > This declares that elephant is a > pointer, and the type it points at is > an array of 20 double values. > > > To declare a pointer to an array of > pointers, simply combine the > notations. > > > ``` int *(*crocodile)[15]; ``` [Source](http://en.wikipedia.org/wiki/C_variable_types_and_declarations). **And your actual case:** ``` int (*data[2])[5]; ``` data is an array of 2 elements. Each element contains a pointer to an array of 5 ints. So you you could have in code using your 'data' type: ``` int (*data[2])[5]; int x1[5]; data[0] = &x1; data[1] = &x1; data[2] = &x1;//<--- out of bounds, crash data has no 3rd element int y1[10]; data[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10] ```
244,695
<p>The structures of my Git repositories look like this:</p> <pre><code>A-B-C-D-E-F # master branch in separate repo1 A-B-C-D-E-G-H # master branch in separate repo2 </code></pre> <p>A-H are simple commits. As you can see the repositories are related (repo2 is a fork of repo1). I'm trying to combine these two repositories in one.</p> <p>Afterwards the single repository should have the following structure:</p> <pre><code>A-B-C-D-E-F # master branch of previous repo1 \ \ G-H # master branch of previous repo2 </code></pre> <p>I've already spent a lot of time reading the Git User's Guide and so on. However, this (special) case of use doesn't seem to be documented anywhere.</p>
[ { "answer_id": 244710, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 3, "selected": false, "text": "<p>Your picture suggests that you don't really want to \"combine the two repositories\" so much as merge commits G and H in to repo1. You should be able to do something as simple as add repo2 as a remote to repo1 and fetch/pull the changes in.</p>\n" }, { "answer_id": 244759, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "<p>I think Jim is right. Also bear in mind that if two commits do exactly the same patch/diff against the code, they will have exactly the same SHA1 hash. So A through E should have the same SHA1 in both repos, so it shouldn't be a problem to merge from one to the other, and keep the merged repo as the sole repo to move forward with.</p>\n\n<p>You can setup on repo1 a tracking branch for repo2, and then keep them distinct that way, and delay the merge to whenever you want.</p>\n" }, { "answer_id": 245240, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 7, "selected": true, "text": "<p>You can treat another git repository on the same filesystem as a remote repo.</p>\n\n<p>In the first, do the following:</p>\n\n<pre><code>git remote add &lt;name&gt; /path/to/other/repo/.git\ngit fetch &lt;name&gt;\ngit branch &lt;name&gt; &lt;name&gt;/master #optional\n</code></pre>\n\n<p>Now they're both branches in a single repository. You can switch between them with git checkout, merge with git merge, etc.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
The structures of my Git repositories look like this: ``` A-B-C-D-E-F # master branch in separate repo1 A-B-C-D-E-G-H # master branch in separate repo2 ``` A-H are simple commits. As you can see the repositories are related (repo2 is a fork of repo1). I'm trying to combine these two repositories in one. Afterwards the single repository should have the following structure: ``` A-B-C-D-E-F # master branch of previous repo1 \ \ G-H # master branch of previous repo2 ``` I've already spent a lot of time reading the Git User's Guide and so on. However, this (special) case of use doesn't seem to be documented anywhere.
You can treat another git repository on the same filesystem as a remote repo. In the first, do the following: ``` git remote add <name> /path/to/other/repo/.git git fetch <name> git branch <name> <name>/master #optional ``` Now they're both branches in a single repository. You can switch between them with git checkout, merge with git merge, etc.
244,715
<p>I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take.</p> <p>Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low level as disabling certain context menu items). Of course, I still need to enforce the permissions server side. </p> <p>So, I was wondering if anyone has any suggestions for the best way to</p> <ol> <li>maintain the permissions and use them in server code</li> <li>have easy access to the permissions in javascript</li> <li>not have to make a round-trip request to the server for each individual permission</li> </ol> <p>Thoughts?</p>
[ { "answer_id": 244814, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<p>Encode them as <a href=\"http://json.org\" rel=\"nofollow noreferrer\">JSON</a>.</p>\n" }, { "answer_id": 244855, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 2, "selected": false, "text": "<p>If you transmit the permission structure to the client as a JSON object (or XML, if you prefer), you can manipulate that object with the client-side code, and send it back to the server, which can do whatever it needs to validate the data and persist it.</p>\n" }, { "answer_id": 244865, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 1, "selected": false, "text": "<p>I don't necessarily see it as the most \"correct\" solution, but would it be possible to keep all the permission stuff on the server side, and just serve the updated UI rather than some kind of JSON permissions system?</p>\n\n<p>You'd have to make the decision based on how busy and intensive your app expects to be, but definitely a decision worth making either way</p>\n" }, { "answer_id": 244948, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 3, "selected": true, "text": "<p>If you have a clear set of permissions, like a \"user level\" or \"user type\", you could just pass the value down in a hidden field and access the value through the DOM. You could still do this if your permissions were more granular, but you would either have a lot of hidden fields or you would have to encode the information into XML or JSON or some other format. </p>\n\n<p>You might set them as bit flags so that you could OR a single numeric value with a mask to see if the user had the permission for a specific activity. That would be very flexible and as long as you don't have more than 32 or so specific \"rights\", that would allow for any permutation of those rights in a very small package (basically an unsigned int).</p>\n\n<p>For example:</p>\n\n<pre><code>0x00000001 //edit permission\n0x00000002 //create new thing permission\n0x00000004 //delete things permission\n0x00000008 //view hidden things permission\n .\n .\n .\n0x80000000 //total control of the server and everyone logged in\n</code></pre>\n\n<p>Then a user with a permission of <code>0x000007</code> could edit, create, and delete, but nothing else.</p>\n\n<p>In either case, I think you're on the right track - make the request once per page invocation, store the permissions in a global JavaScript data structure, and go from there. AJAX is nice, but you don't want to query the server for every specific permission all over your page. You would do it once on the page load, set up the presentation of your page and save the value in a global variable, then reference the permission(s) locally for event functions. </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25330/" ]
I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take. Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low level as disabling certain context menu items). Of course, I still need to enforce the permissions server side. So, I was wondering if anyone has any suggestions for the best way to 1. maintain the permissions and use them in server code 2. have easy access to the permissions in javascript 3. not have to make a round-trip request to the server for each individual permission Thoughts?
If you have a clear set of permissions, like a "user level" or "user type", you could just pass the value down in a hidden field and access the value through the DOM. You could still do this if your permissions were more granular, but you would either have a lot of hidden fields or you would have to encode the information into XML or JSON or some other format. You might set them as bit flags so that you could OR a single numeric value with a mask to see if the user had the permission for a specific activity. That would be very flexible and as long as you don't have more than 32 or so specific "rights", that would allow for any permutation of those rights in a very small package (basically an unsigned int). For example: ``` 0x00000001 //edit permission 0x00000002 //create new thing permission 0x00000004 //delete things permission 0x00000008 //view hidden things permission . . . 0x80000000 //total control of the server and everyone logged in ``` Then a user with a permission of `0x000007` could edit, create, and delete, but nothing else. In either case, I think you're on the right track - make the request once per page invocation, store the permissions in a global JavaScript data structure, and go from there. AJAX is nice, but you don't want to query the server for every specific permission all over your page. You would do it once on the page load, set up the presentation of your page and save the value in a global variable, then reference the permission(s) locally for event functions.
244,719
<p>I'm trying to get a bare-bones example of logging going in my ASP.NET application. I would like to use the My.Log functionality to write out error log messages to a text log file. I have tried several things via Google but none of them seem to work. In general, when I use any of the properties of My.Log.DefaultFileWriter in the code it says "Object reference not set".</p> <p>My basic question is: What do I need in my web.config file (and/or anywhere else, if necessary) so that I can write messages with</p> <pre><code>My.Log.WriteEntry("blahblahblah") </code></pre> <p>in my code, to a text file, D:\log.txt?</p> <p>Thanks.</p> <hr> <p>Edit: specific code used:</p> <pre><code> &lt;system.diagnostics&gt; &lt;sources &gt; &lt;source name="DefaultSource" switchName="DefaultSwitch"&gt; &lt;listeners&gt; &lt;add name="FileLog"/&gt; &lt;/listeners&gt; &lt;/source&gt; &lt;/sources&gt; &lt;sharedListeners&gt; &lt;add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" initializeData="FileLogWriter" /&gt; &lt;/sharedListeners&gt; &lt;switches&gt; &lt;add name="DefaultSwitch" value="Verbose"/&gt; &lt;/switches&gt; &lt;trace autoflush="true"&gt;&lt;/trace&gt; &lt;/system.diagnostics&gt; </code></pre> <p>Then in the code:</p> <pre><code>My.Log.DefaultFileLogWriter.CustomLocation = "D:\" My.Log.DefaultFileLogWriter.BaseFileName = "log" My.Log.WriteEntry("blahblahblah") </code></pre> <p>(this would write to D:\log.log).</p>
[ { "answer_id": 244740, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/log-info/walkthrough-changing-where-my-application-log-writes-information\" rel=\"nofollow noreferrer\">Walkthrough: Changing Where My.Application.Log Writes Information </a></p>\n" }, { "answer_id": 244841, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>I know it's not a hello world example, but I suggest also checking out log4net (<a href=\"http://logging.apache.org/log4net/index.html\" rel=\"nofollow noreferrer\">http://logging.apache.org/log4net/index.html</a>). It's pretty awesome.</p>\n" }, { "answer_id": 434682, "author": "renegadeMind", "author_id": 53270, "author_profile": "https://Stackoverflow.com/users/53270", "pm_score": 0, "selected": false, "text": "<p>log4net is the bst option for logging in asp.net</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1607294/" ]
I'm trying to get a bare-bones example of logging going in my ASP.NET application. I would like to use the My.Log functionality to write out error log messages to a text log file. I have tried several things via Google but none of them seem to work. In general, when I use any of the properties of My.Log.DefaultFileWriter in the code it says "Object reference not set". My basic question is: What do I need in my web.config file (and/or anywhere else, if necessary) so that I can write messages with ``` My.Log.WriteEntry("blahblahblah") ``` in my code, to a text file, D:\log.txt? Thanks. --- Edit: specific code used: ``` <system.diagnostics> <sources > <source name="DefaultSource" switchName="DefaultSwitch"> <listeners> <add name="FileLog"/> </listeners> </source> </sources> <sharedListeners> <add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" initializeData="FileLogWriter" /> </sharedListeners> <switches> <add name="DefaultSwitch" value="Verbose"/> </switches> <trace autoflush="true"></trace> </system.diagnostics> ``` Then in the code: ``` My.Log.DefaultFileLogWriter.CustomLocation = "D:\" My.Log.DefaultFileLogWriter.BaseFileName = "log" My.Log.WriteEntry("blahblahblah") ``` (this would write to D:\log.log).
[Walkthrough: Changing Where My.Application.Log Writes Information](https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/log-info/walkthrough-changing-where-my-application-log-writes-information)
244,720
<p>Because I need to display a <a href="http://codeflow.org/ubuntu.png" rel="nofollow noreferrer">huge number of labels</a> that <a href="http://www.youtube.com/watch?v=A_ah-SE-cNY" rel="nofollow noreferrer">move independently</a>, I need to render a label in <a href="http://pyglet.org" rel="nofollow noreferrer">pyglet</a> to a texture (otherwise updating the vertex list for each glyph is too slow).</p> <p>I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below:</p> <pre><code>from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() </code></pre> <p>Any idea how I could color this?</p>
[ { "answer_id": 246962, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "<p>Isn't that when you use decaling, through <code><a href=\"http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texenv.html\" rel=\"nofollow noreferrer\">glTexEnv()</a></code>?</p>\n" }, { "answer_id": 405855, "author": "Joseph Garvin", "author_id": 50385, "author_profile": "https://Stackoverflow.com/users/50385", "pm_score": 2, "selected": false, "text": "<p>You want to set <code>glEnable(GL_COLOR_MATERIAL)</code>. This makes the texture color mix with the current OpenGL color. You can also use the <code>glColorMaterial</code> function to specify whether the front/back/both of each polygon should be affected. Docs <a href=\"http://www.glprogramming.com/blue/ch05.html#id37922\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ]
Because I need to display a [huge number of labels](http://codeflow.org/ubuntu.png) that [move independently](http://www.youtube.com/watch?v=A_ah-SE-cNY), I need to render a label in [pyglet](http://pyglet.org) to a texture (otherwise updating the vertex list for each glyph is too slow). I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See the example below: ``` from pyglet.gl import * def label2texture(label): vertex_list = label._vertex_lists[0].vertices[:] xpos = map(int, vertex_list[::8]) ypos = map(int, vertex_list[1::8]) glyphs = label._get_glyphs() xstart = xpos[0] xend = xpos[-1] + glyphs[-1].width width = xend - xstart ystart = min(ypos) yend = max(ystart+glyph.height for glyph in glyphs) height = yend - ystart texture = pyglet.image.Texture.create(width, height, pyglet.gl.GL_RGBA) for glyph, x, y in zip(glyphs, xpos, ypos): data = glyph.get_image_data() x = x - xstart y = height - glyph.height - y + ystart texture.blit_into(data, x, y, 0) return texture.get_transform(flip_y=True) window = pyglet.window.Window() label = pyglet.text.Label('Hello World!', font_size = 36) texture = label2texture(label) @window.event def on_draw(): hoff = (window.width / 2) - (texture.width / 2) voff = (window.height / 2) - (texture.height / 2) glClear(GL_COLOR_BUFFER_BIT) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0.0, 1.0, 0.0, 1.0) window.clear() glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture.id) glColor4f(1.0, 0.0, 0.0, 1.0) #I'd like the font to be red glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex2d(hoff,voff); glTexCoord2d(1.0,1.0); glVertex2d(hoff+texture.width,voff); glTexCoord2d(1.0,0.0); glVertex2d(hoff+texture.width,voff+texture.height); glTexCoord2d(0.0,0.0); glVertex2d(hoff, voff+texture.height); glEnd(); pyglet.app.run() ``` Any idea how I could color this?
You want to set `glEnable(GL_COLOR_MATERIAL)`. This makes the texture color mix with the current OpenGL color. You can also use the `glColorMaterial` function to specify whether the front/back/both of each polygon should be affected. Docs [here](http://www.glprogramming.com/blue/ch05.html#id37922).
244,758
<p>So this might be really simple, but I haven't been able to find any examples to learn off of yet, so please bear with me. ;) </p> <p>Here's basically what I want to do:</p> <pre><code>&lt;div&gt;Lots of content! Lots of content! Lots of content! ...&lt;/div&gt; .... $("div").html("Itsy-bitsy bit of content!"); </code></pre> <p>I want to smoothly animate between the dimensions of the div with lots of content to the dimensions of the div with very little when the new content is injected.</p> <p>Thoughts?</p>
[ { "answer_id": 244847, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 3, "selected": false, "text": "<p>maybe something like this?</p>\n\n<pre><code>$(\".testLink\").click(function(event) {\n event.preventDefault();\n $(\".testDiv\").hide(400,function(event) {\n $(this).html(\"Itsy-bitsy bit of content!\").show(400);\n });\n});\n</code></pre>\n\n<p>Close to what I think you wanted, also try slideIn/slideOut or look at the UI/Effects plugin.</p>\n" }, { "answer_id": 245011, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 5, "selected": false, "text": "<p>You can use the <a href=\"http://docs.jquery.com/Effects/animate#paramsoptions\" rel=\"noreferrer\">animate method</a>.</p>\n\n<pre><code>$(\"div\").animate({width:\"200px\"},400);\n</code></pre>\n" }, { "answer_id": 245054, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 0, "selected": false, "text": "<p>Hello meyahoocoma4c5ki0pprxr19sxhajsogo6jgks5dt.</p>\n\n<p>You could wrap the 'content div' with an 'outer div' which is set to an absolute width value. Inject the new content with a \"hide()\" or \"animate({width})\" method, shown in the other answers. This way, the page doesn't reflow in between because the wrapper div holds a steady width.</p>\n" }, { "answer_id": 245316, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": true, "text": "<p>Try this jQuery plugin:</p>\n\n<pre><code>// Animates the dimensional changes resulting from altering element contents\n// Usage examples: \n// $(\"#myElement\").showHtml(\"new HTML contents\");\n// $(\"div\").showHtml(\"new HTML contents\", 400);\n// $(\".className\").showHtml(\"new HTML contents\", 400, \n// function() {/* on completion */});\n(function($)\n{\n $.fn.showHtml = function(html, speed, callback)\n {\n return this.each(function()\n {\n // The element to be modified\n var el = $(this);\n\n // Preserve the original values of width and height - they'll need \n // to be modified during the animation, but can be restored once\n // the animation has completed.\n var finish = {width: this.style.width, height: this.style.height};\n\n // The original width and height represented as pixel values.\n // These will only be the same as `finish` if this element had its\n // dimensions specified explicitly and in pixels. Of course, if that \n // was done then this entire routine is pointless, as the dimensions \n // won't change when the content is changed.\n var cur = {width: el.width()+'px', height: el.height()+'px'};\n\n // Modify the element's contents. Element will resize.\n el.html(html);\n\n // Capture the final dimensions of the element \n // (with initial style settings still in effect)\n var next = {width: el.width()+'px', height: el.height()+'px'};\n\n el .css(cur) // restore initial dimensions\n .animate(next, speed, function() // animate to final dimensions\n {\n el.css(finish); // restore initial style settings\n if ( $.isFunction(callback) ) callback();\n });\n });\n };\n\n\n})(jQuery);\n</code></pre>\n\n<p>Commenter RonLugge points out that this can cause problems if you call it twice on the same element(s), where the first animation hasn't finished before the second begins. This is because the second animation will take the current (mid-animation) sizes as the desired \"ending\" values, and proceed to fix them as the final values (effectively stopping the animation in its tracks rather than animating toward the \"natural\" size)...</p>\n\n<p>The easiest way to resolve this is to call <a href=\"http://api.jquery.com/stop/\" rel=\"noreferrer\"><code>stop()</code></a> before calling <code>showHtml()</code>, and passing <code>true</code> for the second (<em>jumpToEnd</em>) parameter:</p>\n\n<pre><code>$(selector).showHtml(\"new HTML contents\")\n .stop(true, true)\n .showHtml(\"even newer contents\");\n</code></pre>\n\n<p>This will cause the first animation to complete immediately (if it is still running), before beginning a new one.</p>\n" }, { "answer_id": 475889, "author": "Daan", "author_id": 58565, "author_profile": "https://Stackoverflow.com/users/58565", "pm_score": 3, "selected": false, "text": "<p>Here is how I fixed this, I hope this will be usefull !\nThe animation is 100% smooth :)</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"div-1\"&gt;&lt;div id=\"div-2\"&gt;Some content here&lt;/div&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>// cache selectors for better performance\nvar container = $('#div-1'),\n wrapper = $('#div-2');\n\n// temporarily fix the outer div's width\ncontainer.css({width: wrapper.width()});\n// fade opacity of inner div - use opacity because we cannot get the width or height of an element with display set to none\nwrapper.fadeTo('slow', 0, function(){\n // change the div content\n container.html(\"&lt;div id=\\\"2\\\" style=\\\"display: none;\\\"&gt;new content (with a new width)&lt;/div&gt;\");\n // give the outer div the same width as the inner div with a smooth animation\n container.animate({width: wrapper.width()}, function(){\n // show the inner div\n wrapper.fadeTo('slow', 1);\n });\n});\n</code></pre>\n\n<p>There might be a shorter version of my code, but I just kept it like this.</p>\n" }, { "answer_id": 5972286, "author": "A-P", "author_id": 749720, "author_profile": "https://Stackoverflow.com/users/749720", "pm_score": 1, "selected": false, "text": "<p>This does the job for me. You can also add a width to the temp div.</p>\n\n<pre><code>$('div#to-transition').wrap( '&lt;div id=\"tmp\"&gt;&lt;/div&gt;' );\n$('div#tmp').css( { height: $('div#to-transition').outerHeight() + 'px' } );\n$('div#to-transition').fadeOut('fast', function() {\n $(this).html(new_html);\n $('div#tmp').animate( { height: $(this).outerHeight() + 'px' }, 'fast' );\n $(this).fadeIn('fast', function() {\n $(this).unwrap();\n });\n});\n</code></pre>\n" }, { "answer_id": 27139850, "author": "davidcondrey", "author_id": 1922144, "author_profile": "https://Stackoverflow.com/users/1922144", "pm_score": 0, "selected": false, "text": "<p>You can smooth out the jQuery animation using <code>dequeue</code>. Test for presence of class (set upon hover and removed on mouseOut animate callback) before staring new animation. When new animation does start, dequeue.</p>\n\n<p><a href=\"http://codepen.io/dcdev/pen/XJbRwo\" rel=\"nofollow noreferrer\">Here's a quick demo.</a></p>\n\n<pre><code>var space = ($(window).width() - 100);\n$('.column').width(space/4);\n\n$(\".column\").click(function(){\n if (!$(this).hasClass('animated')) {\n $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {});\n }\n\n $(this).addClass('animated');\n $('.column').not($(this).parent()).dequeue().stop().animate({width: 'toggle', opacity: '0.75'}, 1750,'linear', function () {\n $(this).removeClass('animated').dequeue();\n\n });\n $(this).dequeue().stop().animate({\n width:(space/4)\n }, 1400,'linear',function(){\n $(this).html('AGAIN');\n });\n});\n</code></pre>\n\n<p>The demo is setup as 5 full-height columns, clicking any of the columns 2 thru 5 will animate toggle width of the other 3 and move the clicked element to the far left.</p>\n\n<p><img src=\"https://i.stack.imgur.com/bfuXW.jpg\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/C7YV8.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 27534587, "author": "snotbubblelou", "author_id": 1123521, "author_profile": "https://Stackoverflow.com/users/1123521", "pm_score": 0, "selected": false, "text": "<p>To piggy-back on the jquery plugin solution (too low of reputation to add this as a comment) jQuery.html() will remove any event handlers on the appended html. Changing:</p>\n\n<pre><code>// Modify the element's contents. Element will resize.\nel.html(html);\n</code></pre>\n\n<p>to </p>\n\n<pre><code>// Modify the element's contents. Element will resize.\nel.append(html);\n</code></pre>\n\n<p>will retain the event handlers of the \"html\" elements</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
So this might be really simple, but I haven't been able to find any examples to learn off of yet, so please bear with me. ;) Here's basically what I want to do: ``` <div>Lots of content! Lots of content! Lots of content! ...</div> .... $("div").html("Itsy-bitsy bit of content!"); ``` I want to smoothly animate between the dimensions of the div with lots of content to the dimensions of the div with very little when the new content is injected. Thoughts?
Try this jQuery plugin: ``` // Animates the dimensional changes resulting from altering element contents // Usage examples: // $("#myElement").showHtml("new HTML contents"); // $("div").showHtml("new HTML contents", 400); // $(".className").showHtml("new HTML contents", 400, // function() {/* on completion */}); (function($) { $.fn.showHtml = function(html, speed, callback) { return this.each(function() { // The element to be modified var el = $(this); // Preserve the original values of width and height - they'll need // to be modified during the animation, but can be restored once // the animation has completed. var finish = {width: this.style.width, height: this.style.height}; // The original width and height represented as pixel values. // These will only be the same as `finish` if this element had its // dimensions specified explicitly and in pixels. Of course, if that // was done then this entire routine is pointless, as the dimensions // won't change when the content is changed. var cur = {width: el.width()+'px', height: el.height()+'px'}; // Modify the element's contents. Element will resize. el.html(html); // Capture the final dimensions of the element // (with initial style settings still in effect) var next = {width: el.width()+'px', height: el.height()+'px'}; el .css(cur) // restore initial dimensions .animate(next, speed, function() // animate to final dimensions { el.css(finish); // restore initial style settings if ( $.isFunction(callback) ) callback(); }); }); }; })(jQuery); ``` Commenter RonLugge points out that this can cause problems if you call it twice on the same element(s), where the first animation hasn't finished before the second begins. This is because the second animation will take the current (mid-animation) sizes as the desired "ending" values, and proceed to fix them as the final values (effectively stopping the animation in its tracks rather than animating toward the "natural" size)... The easiest way to resolve this is to call [`stop()`](http://api.jquery.com/stop/) before calling `showHtml()`, and passing `true` for the second (*jumpToEnd*) parameter: ``` $(selector).showHtml("new HTML contents") .stop(true, true) .showHtml("even newer contents"); ``` This will cause the first animation to complete immediately (if it is still running), before beginning a new one.
244,772
<p>I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a <code>Schedule</code>) with some values determined by invoking the appropriate <code>WithXXX</code> and chaining them together.</p> <p>I've encountered some commonality amongst my builders and I want to abstract that away into a base class to increase code reuse. Unfortunately what I end up with looks like:</p> <pre><code>public abstract class BaseBuilder&lt;T,BLDR&gt; where BLDR : BaseBuilder&lt;T,BLDR&gt; where T : new() { public abstract T Build(); protected int Id { get; private set; } protected abstract BLDR This { get; } public BLDR WithId(int id) { Id = id; return This; } } </code></pre> <p>Take special note of the <code>protected abstract BLDR This { get; }</code>.</p> <p>A sample implementation of a domain class builder is:</p> <pre><code>public class ScheduleIntervalBuilder : BaseBuilder&lt;ScheduleInterval,ScheduleIntervalBuilder&gt; { private int _scheduleId; // ... // UG! here's the problem: protected override ScheduleIntervalBuilder This { get { return this; } } public override ScheduleInterval Build() { return new ScheduleInterval { Id = base.Id, ScheduleId = _scheduleId // ... }; } public ScheduleIntervalBuilder WithScheduleId(int scheduleId) { _scheduleId = scheduleId; return this; } // ... } </code></pre> <p>Because BLDR is not of type BaseBuilder I cannot use <code>return this</code> in the <code>WithId(int)</code> method of <code>BaseBuilder</code>.</p> <p>Is exposing the child type with the property <code>abstract BLDR This { get; }</code> my only option here, or am I missing some syntax trick?</p> <p>Update (since I can show why I'm doing this a bit more clearly):</p> <p>The end result is to have builders that build profiled domain classes that one would expect to retrieve from the database in a [programmer] readable format. There's nothing wrong with...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new Schedule { ScheduleId = 1 // ... } ); </code></pre> <p>as that's pretty readable already. The alternative builder syntax is:</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .WithId(1) // ... .Build() ); </code></pre> <p>the advantage I'm looking for out of using builders (and implementing all these <code>WithXXX</code> methods) is to abstract away complex property creation (automatically expand our database lookup values with the correct <code>Lookup.KnownValues</code> without hitting the database obviously) and having the builder provide commonly reusable test profiles for domain classes...</p> <pre><code>mock.Expect(m =&gt; m.Select(It.IsAny&lt;int&gt;())).Returns( new ScheduleBuilder() .AsOneDay() .Build() ); </code></pre>
[ { "answer_id": 244805, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>All I can say is that if there <em>is</em> a way of doing it, I want to know about it too - I use <em>exactly</em> this pattern in my <a href=\"http://github.com/jskeet/dotnet-protobufs/tree/master\" rel=\"noreferrer\">Protocol Buffers port</a>. In fact, I'm glad to see that someone else has resorted to it - it means we're at least somewhat likely to be right!</p>\n" }, { "answer_id": 245702, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<p>This is a good implementation strategy for C#.</p>\n\n<p>Some other languages (can't think of name of research language I've seen this in) have type systems that either support a covariant \"self\"/\"this\" directly, or have other clever ways to express this pattern, but with C#'s type system, this is a good (only?) solution.</p>\n" }, { "answer_id": 9244978, "author": "dvdvorle", "author_id": 481635, "author_profile": "https://Stackoverflow.com/users/481635", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question, but I think you can use a simple cast to avoid the <code>abstract BLDR This { get; }</code></p>\n\n<p>The resulting code would then be:</p>\n\n<pre><code>public abstract class BaseBuilder&lt;T, BLDR&gt; where BLDR : BaseBuilder&lt;T, BLDR&gt;\n where T : new()\n{\n public abstract T Build();\n\n protected int Id { get; private set; }\n\n public BLDR WithId(int id)\n {\n _id = id;\n return (BLDR)this;\n }\n}\n\npublic class ScheduleIntervalBuilder :\n BaseBuilder&lt;ScheduleInterval,ScheduleIntervalBuilder&gt;\n{\n private int _scheduleId;\n // ...\n\n public override ScheduleInterval Build()\n {\n return new ScheduleInterval\n {\n Id = base.Id,\n ScheduleId = _scheduleId\n // ...\n };\n }\n\n public ScheduleIntervalBuilder WithScheduleId(int scheduleId)\n {\n _scheduleId = scheduleId;\n return this;\n }\n\n // ...\n}\n</code></pre>\n\n<p>Of course you could encapsulate the builder with</p>\n\n<pre><code>protected BLDR This\n{\n get\n {\n return (BLDR)this;\n }\n}\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645/" ]
I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a `Schedule`) with some values determined by invoking the appropriate `WithXXX` and chaining them together. I've encountered some commonality amongst my builders and I want to abstract that away into a base class to increase code reuse. Unfortunately what I end up with looks like: ``` public abstract class BaseBuilder<T,BLDR> where BLDR : BaseBuilder<T,BLDR> where T : new() { public abstract T Build(); protected int Id { get; private set; } protected abstract BLDR This { get; } public BLDR WithId(int id) { Id = id; return This; } } ``` Take special note of the `protected abstract BLDR This { get; }`. A sample implementation of a domain class builder is: ``` public class ScheduleIntervalBuilder : BaseBuilder<ScheduleInterval,ScheduleIntervalBuilder> { private int _scheduleId; // ... // UG! here's the problem: protected override ScheduleIntervalBuilder This { get { return this; } } public override ScheduleInterval Build() { return new ScheduleInterval { Id = base.Id, ScheduleId = _scheduleId // ... }; } public ScheduleIntervalBuilder WithScheduleId(int scheduleId) { _scheduleId = scheduleId; return this; } // ... } ``` Because BLDR is not of type BaseBuilder I cannot use `return this` in the `WithId(int)` method of `BaseBuilder`. Is exposing the child type with the property `abstract BLDR This { get; }` my only option here, or am I missing some syntax trick? Update (since I can show why I'm doing this a bit more clearly): The end result is to have builders that build profiled domain classes that one would expect to retrieve from the database in a [programmer] readable format. There's nothing wrong with... ``` mock.Expect(m => m.Select(It.IsAny<int>())).Returns( new Schedule { ScheduleId = 1 // ... } ); ``` as that's pretty readable already. The alternative builder syntax is: ``` mock.Expect(m => m.Select(It.IsAny<int>())).Returns( new ScheduleBuilder() .WithId(1) // ... .Build() ); ``` the advantage I'm looking for out of using builders (and implementing all these `WithXXX` methods) is to abstract away complex property creation (automatically expand our database lookup values with the correct `Lookup.KnownValues` without hitting the database obviously) and having the builder provide commonly reusable test profiles for domain classes... ``` mock.Expect(m => m.Select(It.IsAny<int>())).Returns( new ScheduleBuilder() .AsOneDay() .Build() ); ```
All I can say is that if there *is* a way of doing it, I want to know about it too - I use *exactly* this pattern in my [Protocol Buffers port](http://github.com/jskeet/dotnet-protobufs/tree/master). In fact, I'm glad to see that someone else has resorted to it - it means we're at least somewhat likely to be right!
244,777
<p>Can I use comments inside a <a href="https://en.wikipedia.org/wiki/JSON" rel="noreferrer">JSON</a> file? If so, how?</p>
[ { "answer_id": 244795, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 7, "selected": false, "text": "<p>You can't. At least that's my experience from a quick glance at <a href=\"http://json.org\" rel=\"noreferrer\">json.org</a>.</p>\n\n<p>JSON has its syntax visualized on that page. There isn't any note about comments.</p>\n" }, { "answer_id": 244858, "author": "Eli", "author_id": 27580, "author_profile": "https://Stackoverflow.com/users/27580", "pm_score": 14, "selected": true, "text": "<p>No.</p>\n<p>JSON is data-only. If you include a comment, then it must be data too.</p>\n<p>You could have a designated data element called <code>&quot;_comment&quot;</code> (or something) that should be ignored by apps that use the JSON data.</p>\n<p>You would probably be better having the comment in the processes that generates/receives the JSON, as they are supposed to know what the JSON data will be in advance, or at least the structure of it.</p>\n<p>But if you decided to:</p>\n<pre><code>{\n &quot;_comment&quot;: &quot;comment text goes here...&quot;,\n &quot;glossary&quot;: {\n &quot;title&quot;: &quot;example glossary&quot;,\n &quot;GlossDiv&quot;: {\n &quot;title&quot;: &quot;S&quot;,\n &quot;GlossList&quot;: {\n &quot;GlossEntry&quot;: {\n &quot;ID&quot;: &quot;SGML&quot;,\n &quot;SortAs&quot;: &quot;SGML&quot;,\n &quot;GlossTerm&quot;: &quot;Standard Generalized Markup Language&quot;,\n &quot;Acronym&quot;: &quot;SGML&quot;,\n &quot;Abbrev&quot;: &quot;ISO 8879:1986&quot;,\n &quot;GlossDef&quot;: {\n &quot;para&quot;: &quot;A meta-markup language, used to create markup languages such as DocBook.&quot;,\n &quot;GlossSeeAlso&quot;: [&quot;GML&quot;, &quot;XML&quot;]\n },\n &quot;GlossSee&quot;: &quot;markup&quot;\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 245213, "author": "Neil Albrock", "author_id": 32124, "author_profile": "https://Stackoverflow.com/users/32124", "pm_score": 5, "selected": false, "text": "<p>The idea behind JSON is to provide simple data exchange between applications. These are typically web based and the language is JavaScript.</p>\n\n<p>It doesn't really allow for comments as such, however, passing a comment as one of the name/value pairs in the data would certainly work, although that data would obviously need to be ignored or handled specifically by the parsing code.</p>\n\n<p>All that said, it's not the intention that the JSON file should contain comments in the traditional sense. It should just be the data.</p>\n\n<p>Have a look at the <a href=\"http://www.json.org/\" rel=\"noreferrer\">JSON website</a> for more detail.</p>\n" }, { "answer_id": 2611372, "author": "John T. Vonachen", "author_id": 313226, "author_profile": "https://Stackoverflow.com/users/313226", "pm_score": 6, "selected": false, "text": "<p>If your text file, which is a JSON string, is going to be read by some program, how difficult would it be to strip out either C or C++ style comments before using it?</p>\n\n<p><strong>Answer:</strong> It would be a one liner. If you do that then JSON files could be used as configuration files.</p>\n" }, { "answer_id": 3104376, "author": "Kyle Simpson", "author_id": 228852, "author_profile": "https://Stackoverflow.com/users/228852", "pm_score": 10, "selected": false, "text": "<p><strong>Include comments if you choose; strip them out with a minifier before parsing or transmitting.</strong></p>\n<p>I just released <strong><a href=\"http://github.com/getify/JSON.minify\" rel=\"noreferrer\">JSON.minify()</a></strong> which strips out comments and whitespace from a block of JSON and makes it valid JSON that can be parsed. So, you might use it like:</p>\n<pre><code>JSON.parse(JSON.minify(my_str));\n</code></pre>\n<p>When I released it, I got a huge backlash of people disagreeing with even the idea of it, so I decided that I'd write a comprehensive blog post on why <a href=\"http://web.archive.org/web/20100629021329/http://blog.getify.com/2010/06/json-comments/\" rel=\"noreferrer\">comments make sense in JSON</a>. It includes this notable comment from the creator of JSON:</p>\n<blockquote>\n<p>Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. - <a href=\"https://web.archive.org/web/20190112173904/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"noreferrer\">Douglas Crockford, 2012</a></p>\n</blockquote>\n<p>Hopefully that's helpful to those who disagree with why <strong>JSON.minify()</strong> could be useful.</p>\n" }, { "answer_id": 3356227, "author": "raffel", "author_id": 404282, "author_profile": "https://Stackoverflow.com/users/404282", "pm_score": 6, "selected": false, "text": "<p>You should write a <a href=\"http://json-schema.org/\" rel=\"nofollow noreferrer\">JSON schema</a> instead. JSON schema is currently a proposed Internet draft specification. Besides documentation, the schema can also be used for validating your JSON data.</p>\n<p>Example:</p>\n<pre><code>{\n &quot;description&quot;: &quot;A person&quot;,\n &quot;type&quot;: &quot;object&quot;,\n &quot;properties&quot;: {\n &quot;name&quot;: {\n &quot;type&quot;: &quot;string&quot;\n },\n &quot;age&quot;: {\n &quot;type&quot;: &quot;integer&quot;,\n &quot;maximum&quot;: 125\n }\n }\n}\n</code></pre>\n<p>You can provide documentation by using the <strong>description</strong> schema attribute.</p>\n" }, { "answer_id": 4183018, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 11, "selected": false, "text": "<p><strong>No</strong>, comments of the form <code>//…</code> or <code>/*…*/</code> are not allowed in JSON. This answer is based on:</p>\n<ul>\n<li><a href=\"https://www.json.org\" rel=\"noreferrer\">https://www.json.org</a></li>\n<li><a href=\"http://www.ietf.org/rfc/rfc4627.txt\" rel=\"noreferrer\">RFC 4627</a>:\nThe <code>application/json</code> Media Type for JavaScript Object Notation (JSON)</li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc8259\" rel=\"noreferrer\">RFC 8259</a> The JavaScript Object Notation (JSON) Data Interchange Format (supercedes RFCs 4627, 7158, 7159)</li>\n</ul>\n" }, { "answer_id": 4729509, "author": "David", "author_id": 83852, "author_profile": "https://Stackoverflow.com/users/83852", "pm_score": 5, "selected": false, "text": "<p>The Dojo Toolkit JavaScript toolkit (at least as of version 1.4), allows you to include comments in your JSON. The comments can be of <code>/* */</code> format. Dojo Toolkit consumes the JSON via the <code>dojo.xhrGet()</code> call.</p>\n\n<p>Other JavaScript toolkits may work similarly.</p>\n\n<p>This can be helpful when experimenting with alternate data structures (or even data lists) before choosing a final option.</p>\n" }, { "answer_id": 6440396, "author": "peterk", "author_id": 576448, "author_profile": "https://Stackoverflow.com/users/576448", "pm_score": 5, "selected": false, "text": "<p>I just encountering this for configuration files. I don't want to use <strong>XML</strong> (verbose, graphically, ugly, hard to read), or \"ini\" format (no hierarchy, no real standard, etc.) or Java \"Properties\" format (like .ini).</p>\n\n<p>JSON can do all they can do, but it is way less verbose and more human readable - and parsers are easy and ubiquitous in many languages. It's just a tree of data. But out-of-band comments are a necessity often to document \"default\" configurations and the like. Configurations are never to be \"full documents\", but trees of saved data that can be human readable when needed.</p>\n\n<p>I guess one could use <code>\"#\": \"comment\"</code>, for \"valid\" JSON.</p>\n" }, { "answer_id": 7251912, "author": "Marnen Laibow-Koser", "author_id": 109011, "author_profile": "https://Stackoverflow.com/users/109011", "pm_score": 8, "selected": false, "text": "<p>Consider using <a href=\"https://yaml.org/\" rel=\"noreferrer\">YAML</a>. It's nearly a superset of JSON (virtually all valid JSON is valid YAML) and it allows comments.</p>\n" }, { "answer_id": 7901053, "author": "schoetbi", "author_id": 108238, "author_profile": "https://Stackoverflow.com/users/108238", "pm_score": 7, "selected": false, "text": "<p>Comments are not an official standard, although some parsers support C++-style comments. One that I use is <a href=\"https://github.com/open-source-parsers/jsoncpp\" rel=\"noreferrer\">JsonCpp</a>. In the examples there is this one:</p>\n<pre><code>// Configuration options\n{\n // Default encoding for text\n &quot;encoding&quot; : &quot;UTF-8&quot;,\n\n // Plug-ins loaded at start-up\n &quot;plug-ins&quot; : [\n &quot;python&quot;,\n &quot;c++&quot;,\n &quot;ruby&quot;\n ],\n\n // Tab indent size\n &quot;indent&quot; : { &quot;length&quot; : 3, &quot;use_space&quot;: true }\n}\n</code></pre>\n<p><a href=\"http://www.jsonlint.com\" rel=\"noreferrer\">jsonlint</a> does not validate this. So comments are a parser specific extension and not standard.</p>\n<p>Another parser is <a href=\"https://json5.org/\" rel=\"noreferrer\">JSON5</a>.</p>\n<p>An alternative to JSON <a href=\"https://github.com/toml-lang/toml\" rel=\"noreferrer\">TOML</a>.</p>\n<p>A further alternative is <a href=\"https://www.npmjs.com/package/jsonc\" rel=\"noreferrer\">jsonc</a>.</p>\n<p>The latest version of <a href=\"https://github.com/nlohmann/json#comments-in-json\" rel=\"noreferrer\">nlohmann/json</a> has optional support for ignoring comments on parsing.</p>\n" }, { "answer_id": 10976934, "author": "Artur Czajka", "author_id": 572370, "author_profile": "https://Stackoverflow.com/users/572370", "pm_score": 9, "selected": false, "text": "<p>Comments were removed from JSON by design.</p>\n<blockquote>\n<p>I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.</p>\n<p>Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.</p>\n</blockquote>\n<p>Source: <a href=\"https://web.archive.org/web/20120507093915/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"noreferrer\">Public statement by Douglas Crockford on G+</a></p>\n" }, { "answer_id": 11805048, "author": "AZ.", "author_id": 166286, "author_profile": "https://Stackoverflow.com/users/166286", "pm_score": 5, "selected": false, "text": "<p>It depends on your JSON library. <a href=\"https://github.com/JamesNK/Newtonsoft.Json\" rel=\"noreferrer\">Json.NET</a> supports JavaScript-style comments, <code>/* commment */</code>.</p>\n\n<p>See <a href=\"https://stackoverflow.com/a/10325432/166286\">another Stack&nbsp;Overflow question</a>.</p>\n" }, { "answer_id": 13812297, "author": "Basel Shishani", "author_id": 804138, "author_profile": "https://Stackoverflow.com/users/804138", "pm_score": 5, "selected": false, "text": "<p>JSON makes a lot of sense for config files and other local usage because it's ubiquitous and because it's much simpler than XML.</p>\n<p>If people have strong reasons against having comments in JSON when communicating data (whether valid or not), then possibly JSON could be split into two:</p>\n<ul>\n<li>JSON-COM: JSON on the wire, or rules that apply when communicating JSON data.</li>\n<li>JSON-DOC: JSON document, or JSON in files or locally. Rules that define a valid JSON document.</li>\n</ul>\n<p>JSON-DOC will allow comments, and other minor differences might exist such as handling whitespace. Parsers can easily convert from one spec to the other.</p>\n<p>With regards to the <a href=\"https://web.archive.org/web/20190112173904/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"nofollow noreferrer\">remark</a> made by Douglas Crockford on this issues (referenced by @Artur Czajka)</p>\n<blockquote>\n<p>Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser.</p>\n</blockquote>\n<p>We're talking about a generic config file issue (cross language/platform), and he's answering with a JS specific utility!</p>\n<p>Sure a JSON specific minify can be implemented in any language,\nbut standardize this so it becomes ubiquitous across parsers in all languages and platforms so people stop wasting their time lacking the feature because they have good use-cases for it, looking the issue up in online forums, and getting people telling them it's a bad idea or suggesting it's easy to implement stripping comments out of text files.</p>\n<p>The other issue is interoperability. Suppose you have a library or API or any kind of subsystem which has some config or data files associated with it. And this subsystem is\nto be accessed from different languages. Then do you go about telling people: by the way\ndon't forget to strip out the comments from the JSON files before passing them to the parser!</p>\n" }, { "answer_id": 17300561, "author": "gaborous", "author_id": 1121352, "author_profile": "https://Stackoverflow.com/users/1121352", "pm_score": 5, "selected": false, "text": "<p>JSON does not support comments natively, but you can make your own decoder or at least preprocessor to strip out comments, that's perfectly fine (as long as you just ignore comments and don't use them to guide how your application should process the JSON data).</p>\n<blockquote>\n<p>JSON does not have comments. A JSON encoder MUST NOT output comments.\nA JSON decoder MAY accept and ignore comments.</p>\n</blockquote>\n<blockquote>\n<p>Comments should never be used to transmit anything meaningful. That is\nwhat JSON is for.</p>\n</blockquote>\n<p>Cf: <a href=\"https://web.archive.org/web/20130101004216/http://tech.groups.yahoo.com/group/json/message/152\" rel=\"nofollow noreferrer\">Douglas Crockford, author of JSON spec</a>.</p>\n" }, { "answer_id": 18018493, "author": "p3drosola", "author_id": 249161, "author_profile": "https://Stackoverflow.com/users/249161", "pm_score": 8, "selected": false, "text": "<p>DISCLAIMER: YOUR WARRANTY IS VOID</p>\n\n<p>As has been pointed out, this hack takes advantage of the implementation of the spec. Not all JSON parsers will understand this sort of JSON. Streaming parsers in particular will choke.</p>\n\n<p>It's an interesting curiosity, but you <strong>should really not be using it for anything at all</strong>. Below is the original answer.</p>\n\n<hr>\n\n<p>I've found a little hack that allows you to place comments in a JSON file that will not affect the parsing, or alter the data being represented in any way.</p>\n\n<p>It appears that when declaring an object literal you can specify two values with the same key, and the last one takes precedence. Believe it or not, it turns out that JSON parsers work the same way. So we can use this to create comments in the source JSON that will not be present in a parsed object representation. </p>\n\n<pre><code>({a: 1, a: 2});\n// =&gt; Object {a: 2}\nObject.keys(JSON.parse('{\"a\": 1, \"a\": 2}')).length; \n// =&gt; 1\n</code></pre>\n\n<p>If we apply this technique, your commented JSON file might look like this:</p>\n\n<pre><code>{\n \"api_host\" : \"The hostname of your API server. You may also specify the port.\",\n \"api_host\" : \"hodorhodor.com\",\n\n \"retry_interval\" : \"The interval in seconds between retrying failed API calls\",\n \"retry_interval\" : 10,\n\n \"auth_token\" : \"The authentication token. It is available in your developer dashboard under 'Settings'\",\n \"auth_token\" : \"5ad0eb93697215bc0d48a7b69aa6fb8b\",\n\n \"favorite_numbers\": \"An array containing my all-time favorite numbers\",\n \"favorite_numbers\": [19, 13, 53]\n}\n</code></pre>\n\n<p>The above code is <a href=\"http://jsonlint.com/\" rel=\"noreferrer\">valid JSON</a>. If you parse it, you'll get an object like this:</p>\n\n<pre><code>{\n \"api_host\": \"hodorhodor.com\",\n \"retry_interval\": 10,\n \"auth_token\": \"5ad0eb93697215bc0d48a7b69aa6fb8b\",\n \"favorite_numbers\": [19,13,53]\n}\n</code></pre>\n\n<p>Which means there is no trace of the comments, and they won't have weird side-effects.</p>\n\n<p>Happy hacking!</p>\n" }, { "answer_id": 19234265, "author": "Sergey Orshanskiy", "author_id": 1243926, "author_profile": "https://Stackoverflow.com/users/1243926", "pm_score": 5, "selected": false, "text": "<p>You <em>can</em> have comments in <a href=\"https://en.wikipedia.org/wiki/JSONP\" rel=\"nofollow noreferrer\">JSONP</a>, but not in pure JSON. I've just spent an hour trying to make my program work with <a href=\"https://web.archive.org/web/20200131214417/http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&amp;callback=?\" rel=\"nofollow noreferrer\">this example from Highcharts</a>.</p>\n<p>If you follow the link, you will see</p>\n<pre><code>?(/* AAPL historical OHLC data from the Google Finance API */\n[\n/* May 2006 */\n[1147651200000,67.79],\n[1147737600000,64.98],\n...\n[1368057600000,456.77],\n[1368144000000,452.97]\n]);\n</code></pre>\n<p>Since I had a similar file in my local folder, there were no issues with the <a href=\"https://en.wikipedia.org/wiki/Same-origin_policy\" rel=\"nofollow noreferrer\">Same-origin policy</a>, so I decided to use pure JSON… and, of course, <code>$.getJSON</code> was failing silently because of the comments.</p>\n<p>Eventually I just sent a manual HTTP request to the address above and realized that the content-type was <code>text/javascript</code> since, well, JSONP returns pure JavaScript. In this case comments <em>are allowed</em>. But my application returned content-type <code>application/json</code>, so I had to remove the comments.</p>\n" }, { "answer_id": 19655633, "author": "Chris", "author_id": 959219, "author_profile": "https://Stackoverflow.com/users/959219", "pm_score": 4, "selected": false, "text": "<p>To cut a JSON item into parts I add \"dummy comment\" lines:</p>\n\n<pre><code>{\n\n\"#############################\" : \"Part1\",\n\n\"data1\" : \"value1\",\n\"data2\" : \"value2\",\n\n\"#############################\" : \"Part2\",\n\n\"data4\" : \"value3\",\n\"data3\" : \"value4\"\n\n}\n</code></pre>\n" }, { "answer_id": 20267852, "author": "Steve Thomas", "author_id": 1869759, "author_profile": "https://Stackoverflow.com/users/1869759", "pm_score": 3, "selected": false, "text": "<p>Sigh. Why not just add fields, e.g.</p>\n\n<pre><code>{\n \"note1\" : \"This demonstrates the provision of annotations within a JSON file\",\n \"field1\" : 12,\n \"field2\" : \"some text\",\n\n \"note2\" : \"Add more annotations as necessary\"\n}\n</code></pre>\n\n<p>Just make sure your \"notex\" names don't conflict with any real fields.</p>\n" }, { "answer_id": 20434146, "author": "Joshua Richardson", "author_id": 973402, "author_profile": "https://Stackoverflow.com/users/973402", "pm_score": 4, "selected": false, "text": "<p>The author of JSON wants us to include comments in the JSON, but strip them out before parsing them (see <a href=\"https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"noreferrer\">link</a> provided by Michael Burr). If JSON should have comments, why not standardize them, and let the JSON parser do the job? I don't agree with the logic there, but, alas, that's the standard. Using a YAML solution as suggested by others is good, but it requires a library dependency.</p>\n\n<p>If you want to strip out comments, but don't want to have a library dependency, here is a two-line solution, which works for C++-style comments, but can be adapted to others:</p>\n\n<pre><code>var comments = new RegExp(\"//.*\", 'mg');\ndata = JSON.parse(fs.readFileSync(sample_file, 'utf8').replace(comments, ''));\n</code></pre>\n\n<p>Note that this solution can only be used in cases where you can be sure that the JSON data does not contain the comment initiator, e.g. ('//').</p>\n\n<p>Another way to achieve JSON parsing, stripping of comments, and no extra library, is to evaluate the JSON in a JavaScript interpreter. The caveat with that approach, of course, is that you would only want to evaluate untainted data (no untrusted user-input). Here is an example of this approach in Node.js -- another caveat, the following example will only read the data once and then it will be cached:</p>\n\n<pre><code>data = require(fs.realpathSync(doctree_fp));\n</code></pre>\n" }, { "answer_id": 21409180, "author": "Aurimas", "author_id": 757328, "author_profile": "https://Stackoverflow.com/users/757328", "pm_score": 3, "selected": false, "text": "<p>There is a good solution (hack), which is valid JSON, <strong>but it will not work in all cases</strong> (see comments below).\nJust make the same key twice (or more). For example:</p>\n<pre><code>{\n &quot;param&quot; : &quot;This is the comment place&quot;,\n &quot;param&quot; : &quot;This is value place&quot;,\n}\n</code></pre>\n<p>So JSON will understand this as:</p>\n<pre><code>{\n &quot;param&quot; : &quot;This is value place&quot;,\n}\n</code></pre>\n" }, { "answer_id": 21613658, "author": "Andrejs", "author_id": 1180621, "author_profile": "https://Stackoverflow.com/users/1180621", "pm_score": 6, "selected": false, "text": "<p>If you are using <a href=\"https://github.com/FasterXML/jackson\" rel=\"noreferrer\">Jackson</a> as your JSON parser then this is how you enable it to allow comments:</p>\n\n<pre><code>ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_COMMENTS, true);\n</code></pre>\n\n<p>Then you can have comments like this:</p>\n\n<pre><code>{\n key: \"value\" // Comment\n}\n</code></pre>\n\n<p>And you can also have comments starting with <code>#</code> by setting:</p>\n\n<pre><code>mapper.configure(Feature.ALLOW_YAML_COMMENTS, true);\n</code></pre>\n\n<p>But in general (as answered before) the specification does not allow comments.</p>\n" }, { "answer_id": 22537629, "author": "laktak", "author_id": 52817, "author_profile": "https://Stackoverflow.com/users/52817", "pm_score": 8, "selected": false, "text": "<p>JSON does not support comments. It was also never intended to be used for configuration files where comments would be needed.</p>\n<p>Hjson is a configuration file format for humans. Relaxed syntax, fewer mistakes, more comments.</p>\n<p><a href=\"https://i.stack.imgur.com/u2E8q.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u2E8q.gif\" alt=\"Hjson intro\" /></a></p>\n<p>See <a href=\"https://hjson.github.io/\" rel=\"noreferrer\">hjson.github.io</a> for JavaScript, Java, Python, PHP, Rust, Go, Ruby, C++ and C# libraries.</p>\n" }, { "answer_id": 23275699, "author": "William Entriken", "author_id": 300224, "author_profile": "https://Stackoverflow.com/users/300224", "pm_score": 5, "selected": false, "text": "<p>This is a <strong>&quot;can you&quot;</strong> question. And here is a <strong>&quot;yes&quot;</strong> answer.</p>\n<p>No, you shouldn't use duplicative object members to stuff side channel data into a JSON encoding. (See &quot;The names within an object SHOULD be unique&quot; <a href=\"https://www.rfc-editor.org/rfc/rfc8259\" rel=\"nofollow noreferrer\">in the RFC</a>).</p>\n<p>And yes, you could <a href=\"https://web.archive.org/web/20190112173904/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"nofollow noreferrer\">insert comments <em>around</em> the JSON</a>, which you could parse out.</p>\n<p>But if you want a way of inserting and extracting arbitrary side-channel data to a valid JSON, here is an answer. We take advantage of the non-unique representation of data in a JSON encoding. This is allowed<sup>*</sup> in section two of the RFC under &quot;whitespace is allowed before or after any of the six structural characters&quot;.</p>\n<p><i><sup>*</sup>The RFC only states &quot;whitespace is allowed before or after any of the six structural characters&quot;, not explicitly mentioning strings, numbers, &quot;false&quot;, &quot;true&quot;, and &quot;null&quot;. This omission is ignored in ALL implementations.</i></p>\n<hr />\n<p>First, canonicalize your JSON by minifying it:</p>\n<pre><code>$jsonMin = json_encode(json_decode($json));\n</code></pre>\n<p>Then encode your comment in binary:</p>\n<pre><code>$hex = unpack('H*', $comment);\n$commentBinary = base_convert($hex[1], 16, 2);\n</code></pre>\n<p>Then steg your binary:</p>\n<pre><code>$steg = str_replace('0', ' ', $commentBinary);\n$steg = str_replace('1', &quot;\\t&quot;, $steg);\n</code></pre>\n<p>Here is your output:</p>\n<pre><code>$jsonWithComment = $steg . $jsonMin;\n</code></pre>\n" }, { "answer_id": 24545329, "author": "Даниил Пронин", "author_id": 766307, "author_profile": "https://Stackoverflow.com/users/766307", "pm_score": 3, "selected": false, "text": "<p>I just found \"<a href=\"https://www.npmjs.org/package/grunt-strip-json-comments\" rel=\"noreferrer\">grunt-strip-json-comments</a>\".</p>\n\n<blockquote>\n <p>“Strip comments from JSON. It lets you use comments in your JSON files!”</p>\n</blockquote>\n\n<pre><code>{\n // Rainbows\n \"unicorn\": /* ❤ */ \"cake\"\n}\n</code></pre>\n" }, { "answer_id": 24618928, "author": "Maurício Giordano", "author_id": 1822704, "author_profile": "https://Stackoverflow.com/users/1822704", "pm_score": -1, "selected": false, "text": "<p>Yes, you can, but your parse will probably fail (there is no standard).</p>\n\n<p>To parse it you should remove those comments, or by hand, or using a regular expression:</p>\n\n<p>It replaces any comments, like:</p>\n\n<pre><code>/****\n * Hey\n */\n\n/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/\n</code></pre>\n\n<p>It replaces any comments, like:</p>\n\n<pre><code>// Hey\n\n/\\/\\/.*/\n</code></pre>\n\n<p>In JavaScript, you could do something like this:</p>\n\n<pre><code>jsonString = jsonString.replace(/\\/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*\\/+/, \"\").replace(/\\/\\/.*/,\"\")\nvar object = JSON.parse(jsonString);\n</code></pre>\n" }, { "answer_id": 24839354, "author": "Nick", "author_id": 956278, "author_profile": "https://Stackoverflow.com/users/956278", "pm_score": 3, "selected": false, "text": "<p>If your context is Node.js configuration, you might consider JavaScript via <code>module.exports</code> as an alternative to JSON:</p>\n\n<pre><code>module.exports = {\n \"key\": \"value\",\n\n // And with comments!\n \"key2\": \"value2\"\n};\n</code></pre>\n\n<p>The <code>require</code> syntax will still be the same. Being JavaScript, the file extension should be <code>.js</code>.</p>\n" }, { "answer_id": 24957191, "author": "dvdmn", "author_id": 770446, "author_profile": "https://Stackoverflow.com/users/770446", "pm_score": 6, "selected": false, "text": "<p>If you are using the Newtonsoft.Json library with ASP.NET to read/deserialize you can use comments in the JSON content:</p>\n<blockquote>\n<p>//&quot;name&quot;: &quot;string&quot;</p>\n<p>//&quot;id&quot;: int</p>\n</blockquote>\n<p>or</p>\n<blockquote>\n<p>/* This is a</p>\n<p>comment example */</p>\n</blockquote>\n<p><strong>PS:</strong> Single-line comments are only supported with 6+ versions of Newtonsoft Json.</p>\n<p><strong>Additional note for people who can't think out of the box:</strong> I use the JSON format for basic settings in an ASP.NET web application I made. I read the file, convert it into the settings object with the Newtonsoft library and use it when necessary.</p>\n<p>I prefer writing comments about each individual setting in the JSON file itself, and I really don't care about the integrity of the JSON format as long as the library I use is OK with it.</p>\n<p>I think this is an 'easier to use/understand' way than creating a separate 'settings.README' file and explaining the settings in it.</p>\n<p>If you have a problem with this kind of usage; sorry, the genie is out of the lamp. People would find other usages for JSON format, and there is nothing you can do about it.</p>\n" }, { "answer_id": 27169861, "author": "Joy", "author_id": 978320, "author_profile": "https://Stackoverflow.com/users/978320", "pm_score": 4, "selected": false, "text": "<p>We are using <a href=\"https://github.com/sindresorhus/strip-json-comments\"><code>strip-json-comments</code></a> for our project. It supports something like:</p>\n\n<pre><code>/*\n * Description \n*/\n{\n // rainbows\n \"unicorn\": /* ❤ */ \"cake\"\n}\n</code></pre>\n\n<p>Simply <code>npm install --save strip-json-comments</code> to install and use it like:</p>\n\n<pre><code>var strip_json_comments = require('strip-json-comments')\nvar json = '{/*rainbows*/\"unicorn\":\"cake\"}';\nJSON.parse(strip_json_comments(json));\n//=&gt; {unicorn: 'cake'}\n</code></pre>\n" }, { "answer_id": 31193416, "author": "spuder", "author_id": 1626687, "author_profile": "https://Stackoverflow.com/users/1626687", "pm_score": 1, "selected": false, "text": "<p>There are other libraries that are JSON compatible, which support comments.</p>\n\n<p>One notable example is the <a href=\"https://github.com/hashicorp/hcl\" rel=\"nofollow noreferrer\">\"Hashcorp Language\" (HCL)\"</a>. It is written by the same people who made Vagrant, packer, consul, and vault.</p>\n" }, { "answer_id": 31512948, "author": "Manish Shrivastava", "author_id": 1133932, "author_profile": "https://Stackoverflow.com/users/1133932", "pm_score": 5, "selected": false, "text": "<p><strong>JSON is not a framed protocol</strong>. It is a <em>language free format</em>. So a comment's format is not defined for JSON.</p>\n\n<p>As many people have suggested, there are some tricks, for example, duplicate keys or a specific key <code>_comment</code> that you can use. It's up to you.</p>\n" }, { "answer_id": 33583560, "author": "Mark", "author_id": 723090, "author_profile": "https://Stackoverflow.com/users/723090", "pm_score": 3, "selected": false, "text": "<p>As many answers have already pointed out, JSON does not natively have comments. Of course sometimes you want them anyway. For <strong>Python</strong>, two ways to do that are with <a href=\"https://github.com/vaidik/commentjson\" rel=\"noreferrer\"><code>commentjson</code></a> (<code>#</code> and <code>//</code> for Python&nbsp;2 only) or <a href=\"https://github.com/mverleg/pyjson_tricks\" rel=\"noreferrer\"><code>json_tricks</code></a> (<code>#</code> or <code>//</code> for Python&nbsp;2 and Python&nbsp;3), which has several other features. Disclaimer: I made <code>json_tricks</code>.</p>\n" }, { "answer_id": 33885543, "author": "Smit Johnth", "author_id": 2112218, "author_profile": "https://Stackoverflow.com/users/2112218", "pm_score": 5, "selected": false, "text": "<p>If you use <a href=\"http://json5.org/\" rel=\"noreferrer\">JSON5</a> you can include comments.</p>\n\n<hr>\n\n<p><strong>JSON5 is a proposed extension to JSON</strong> that aims to make it easier for humans to write and maintain by hand. It does this by adding some minimal syntax features directly from ECMAScript&nbsp;5.</p>\n" }, { "answer_id": 33963845, "author": "Dominic Cerisano", "author_id": 1048170, "author_profile": "https://Stackoverflow.com/users/1048170", "pm_score": 6, "selected": false, "text": "<p><strong>NO</strong>. JSON used to support comments but they were abused and removed from the standard.</p>\n<p>From the creator of JSON:</p>\n<blockquote>\n<p>I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't. - <a href=\"https://web.archive.org/web/20120506232618/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"noreferrer\">Douglas Crockford, 2012</a></p>\n</blockquote>\n<p>The official JSON site is at <a href=\"http://json.org\" rel=\"noreferrer\">JSON.org</a>. JSON is defined as a <a href=\"http://ecma-international.org/publications/standards/Ecma-404.htm\" rel=\"noreferrer\">standard</a> by ECMA International. There is always a petition process to have standards revised. It is unlikely that annotations will be added to the JSON standard for several reasons.</p>\n<p>JSON by design is an easily reverse-engineered (human parsed) alternative to XML. It is simplified even to the point that annotations are unnecessary. It is not even a markup language. The goal is stability and interoperablilty.</p>\n<p>Anyone who understands the &quot;has-a&quot; relationship of object orientation can understand any JSON structure - that is the whole point. It is just a directed acyclic graph (DAG) with node tags (key/value pairs), which is a near universal data structure.</p>\n<p>This only annotation required might be &quot;//These are DAG tags&quot;. The key names can be as informative as required, allowing arbitrary semantic arity.</p>\n<p>Any platform can parse JSON with just a few lines of code. XML requires complex OO libraries that are not viable on many platforms.</p>\n<p>Annotations would just make JSON less interoperable. There is simply nothing else to add unless what you really need is a markup language (XML), and don't care if your persisted data is easily parsed.</p>\n<p><strong>BUT</strong> as the creator of JSON also observed, there has always been JS pipeline support for comments:</p>\n<blockquote>\n<p>Go ahead and insert all the comments you like.\nThen pipe it through JSMin before handing it to your JSON parser. - <a href=\"https://web.archive.org/web/20120506232618/https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr\" rel=\"noreferrer\">Douglas Crockford, 2012</a></p>\n</blockquote>\n" }, { "answer_id": 34504798, "author": "vitaly-t", "author_id": 1102051, "author_profile": "https://Stackoverflow.com/users/1102051", "pm_score": 4, "selected": false, "text": "<p>You can use JSON with comments in it, if you load it as a text file, and then remove comments.</p>\n\n<p>For example, you can use <a href=\"https://www.npmjs.com/package/decomment\" rel=\"nofollow noreferrer\">decomment</a> library for that. Below is a complete example.</p>\n\n<p><strong>Input JSON (file input.js):</strong></p>\n\n<pre><code>/*\n* multi-line comments\n**/\n{\n \"value\": 123 // one-line comment\n}\n</code></pre>\n\n<p><strong>Test Application:</strong></p>\n\n<pre><code>var decomment = require('decomment');\nvar fs = require('fs');\n\nfs.readFile('input.js', 'utf8', function (err, data) {\n if (err) {\n console.log(err);\n } else {\n var text = decomment(data); // removing comments\n var json = JSON.parse(text); // parsing JSON\n console.log(json);\n }\n});\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>{ value: 123 }\n</code></pre>\n\n<p>See also: <a href=\"https://github.com/vitaly-t/gulp-decomment\" rel=\"nofollow noreferrer\">gulp-decomment</a>, <a href=\"https://github.com/vitaly-t/grunt-decomment\" rel=\"nofollow noreferrer\">grunt-decomment</a></p>\n" }, { "answer_id": 35347457, "author": "MovGP0", "author_id": 601990, "author_profile": "https://Stackoverflow.com/users/601990", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"https://www.w3.org/TR/json-ld/\" rel=\"nofollow\">JSON-LD</a> and the <a href=\"https://schema.org/comment\" rel=\"nofollow\">schema.org comment</a> type to properly write comments: </p>\n\n<pre><code>{\n \"https://schema.org/comment\": \"this is a comment\"\n}\n</code></pre>\n" }, { "answer_id": 36213249, "author": "Meru-kun", "author_id": 5146783, "author_profile": "https://Stackoverflow.com/users/5146783", "pm_score": 2, "selected": false, "text": "<p>If you are using PHP, you can use this function to search for and remove // /* type comments from the JSON string before parsing it into an object/array:</p>\n\n<pre><code>function json_clean_decode($json, $assoc = true, $depth = 512, $options = 0) {\n // search and remove comments like /* */ and //\n $json = preg_replace(\"#(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|([\\s\\t]//.*)|(^//.*)#\", '', $json);\n\n if(version_compare(phpversion(), '5.4.0', '&gt;=')) {\n $json = json_decode($json, $assoc, $depth, $options);\n }\n elseif(version_compare(phpversion(), '5.3.0', '&gt;=')) {\n $json = json_decode($json, $assoc, $depth);\n }\n else {\n $json = json_decode($json, $assoc);\n }\n\n return $json;\n }\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 39171793, "author": "WilliamK", "author_id": 3123980, "author_profile": "https://Stackoverflow.com/users/3123980", "pm_score": 5, "selected": false, "text": "<p>In my case, I need to use comments for debug purposes just before the output of the JSON. So I put the debug information in the <strong>HTTP header</strong>, to avoid breaking the client:</p>\n<pre><code>header(&quot;My-Json-Comment: Yes, I know it's a workaround ;-) &quot;);\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/yMh3J.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yMh3J.png\" alt=\"Enter image description here\" /></a></p>\n" }, { "answer_id": 41038255, "author": "xdeepakv", "author_id": 1594359, "author_profile": "https://Stackoverflow.com/users/1594359", "pm_score": 2, "selected": false, "text": "<p>Yes, you can have comments. But I will not recommend whatever reason mentioned above.</p>\n\n<p>I did some investigation, and I found all JSON require methods use the <code>JSON.parse</code> method. So I came to a solution: We can override or do monkey patching around JSON.parse.</p>\n\n<blockquote>\n <p>Note: tested on Node.js only ;-)</p>\n</blockquote>\n\n<pre><code>var oldParse = JSON.parse;\nJSON.parse = parse;\nfunction parse(json){\n json = json.replace(/\\/\\*.+\\*\\//, function(comment){\n console.log(\"comment:\", comment);\n return \"\";\n });\n return oldParse(json)\n}\n</code></pre>\n\n<p>JSON file:</p>\n\n<pre><code>{\n \"test\": 1\n /* Hello, babe */\n}\n</code></pre>\n" }, { "answer_id": 43440043, "author": "Alexander Shostak", "author_id": 7875310, "author_profile": "https://Stackoverflow.com/users/7875310", "pm_score": 3, "selected": false, "text": "<p>You can use simple preprocessing via regular expressions. For instance, the following function will decode commented JSON in PHP:</p>\n\n<pre><code>function json_decode_commented ($data, $objectsAsArrays = false, $maxDepth = 512, $opts = 0) {\n $data = preg_replace('~\n (\" (?:[^\"\\\\\\\\] | \\\\\\\\\\\\\\\\ | \\\\\\\\\")*+ \") | \\# [^\\v]*+ | // [^\\v]*+ | /\\* .*? \\*/\n ~xs', '$1', $data);\n\n return json_decode($data, $objectsAsArrays, $maxDepth, $opts);\n}\n</code></pre>\n\n<p>It supports all PHP-style comments: /*, #, //. String literals are preserved as is.</p>\n" }, { "answer_id": 44700108, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 7, "selected": false, "text": "<p>Here is what I found in the <a href=\"https://web.archive.org/web/20170517210432/https://firebase.google.com/docs/cloud-messaging/js/client#configure_the_browser_to_receive_messages\" rel=\"noreferrer\">Google Firebase documentation</a> that allows you to put comments in JSON:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n &quot;//&quot;: &quot;Some browsers will use this to enable push notifications.&quot;,\n &quot;//&quot;: &quot;It is the same for all projects, this is not your project's sender ID&quot;,\n &quot;gcm_sender_id&quot;: &quot;1234567890&quot;\n}\n</code></pre>\n" }, { "answer_id": 50930429, "author": "fyngyrz", "author_id": 599484, "author_profile": "https://Stackoverflow.com/users/599484", "pm_score": 5, "selected": false, "text": "<p>JSON doesn't allow comments, per se. The reasoning is utterly foolish, because you can use JSON <em>itself</em> to create comments, which obviates the reasoning entirely, <em>and</em> loads the parser data space for no good reason at all for <em>exactly</em> the same result and potential issues, such as they are: a JSON file with comments.</p>\n<blockquote>\n<p><strong>If you try to put comments in (using <code>//</code> or <code>/* */</code> or <code>#</code> for instance), then some parsers will fail because this is strictly not\nwithin the JSON specification. So you should <em>never</em> do that.</strong></p>\n</blockquote>\n<p>Here, for instance, where my <a href=\"https://fyngyrz.com/?page_id=3622\" rel=\"nofollow noreferrer\">image manipulation system</a> has saved image notations and some basic formatted (comment) information relating to them (at the bottom):</p>\n<pre><code>{\n &quot;Notations&quot;: [\n {\n &quot;anchorX&quot;: 333,\n &quot;anchorY&quot;: 265,\n &quot;areaMode&quot;: &quot;Ellipse&quot;,\n &quot;extentX&quot;: 356,\n &quot;extentY&quot;: 294,\n &quot;opacity&quot;: 0.5,\n &quot;text&quot;: &quot;Elliptical area on top&quot;,\n &quot;textX&quot;: 333,\n &quot;textY&quot;: 265,\n &quot;title&quot;: &quot;Notation 1&quot;\n },\n {\n &quot;anchorX&quot;: 87,\n &quot;anchorY&quot;: 385,\n &quot;areaMode&quot;: &quot;Rectangle&quot;,\n &quot;extentX&quot;: 109,\n &quot;extentY&quot;: 412,\n &quot;opacity&quot;: 0.5,\n &quot;text&quot;: &quot;Rect area\\non bottom&quot;,\n &quot;textX&quot;: 98,\n &quot;textY&quot;: 385,\n &quot;title&quot;: &quot;Notation 2&quot;\n },\n {\n &quot;anchorX&quot;: 69,\n &quot;anchorY&quot;: 104,\n &quot;areaMode&quot;: &quot;Polygon&quot;,\n &quot;extentX&quot;: 102,\n &quot;extentY&quot;: 136,\n &quot;opacity&quot;: 0.5,\n &quot;pointList&quot;: [\n {\n &quot;i&quot;: 0,\n &quot;x&quot;: 83,\n &quot;y&quot;: 104\n },\n {\n &quot;i&quot;: 1,\n &quot;x&quot;: 69,\n &quot;y&quot;: 136\n },\n {\n &quot;i&quot;: 2,\n &quot;x&quot;: 102,\n &quot;y&quot;: 132\n },\n {\n &quot;i&quot;: 3,\n &quot;x&quot;: 83,\n &quot;y&quot;: 104\n }\n ],\n &quot;text&quot;: &quot;Simple polygon&quot;,\n &quot;textX&quot;: 85,\n &quot;textY&quot;: 104,\n &quot;title&quot;: &quot;Notation 3&quot;\n }\n ],\n &quot;imageXW&quot;: 512,\n &quot;imageYW&quot;: 512,\n &quot;imageName&quot;: &quot;lena_std.ato&quot;,\n &quot;tinyDocs&quot;: {\n &quot;c01&quot;: &quot;JSON image notation data:&quot;,\n &quot;c02&quot;: &quot;-------------------------&quot;,\n &quot;c03&quot;: &quot;&quot;,\n &quot;c04&quot;: &quot;This data contains image notations and related area&quot;,\n &quot;c05&quot;: &quot;selection information that provides a means for an&quot;,\n &quot;c06&quot;: &quot;image gallery to display notations with elliptical,&quot;,\n &quot;c07&quot;: &quot;rectangular, polygonal or freehand area indications&quot;,\n &quot;c08&quot;: &quot;over an image displayed to a gallery visitor.&quot;,\n &quot;c09&quot;: &quot;&quot;,\n &quot;c10&quot;: &quot;X and Y positions are all in image space. The image&quot;,\n &quot;c11&quot;: &quot;resolution is given as imageXW and imageYW, which&quot;,\n &quot;c12&quot;: &quot;you use to scale the notation areas to their proper&quot;,\n &quot;c13&quot;: &quot;locations and sizes for your display of the image,&quot;,\n &quot;c14&quot;: &quot;regardless of scale.&quot;,\n &quot;c15&quot;: &quot;&quot;,\n &quot;c16&quot;: &quot;For Ellipses, anchor is the center of the ellipse,&quot;,\n &quot;c17&quot;: &quot;and the extents are the X and Y radii respectively.&quot;,\n &quot;c18&quot;: &quot;&quot;,\n &quot;c19&quot;: &quot;For Rectangles, the anchor is the top left and the&quot;,\n &quot;c20&quot;: &quot;extents are the bottom right.&quot;,\n &quot;c21&quot;: &quot;&quot;,\n &quot;c22&quot;: &quot;For Freehand and Polygon area modes, the pointList&quot;,\n &quot;c23&quot;: &quot;contains a series of numbered XY points. If the area&quot;,\n &quot;c24&quot;: &quot;is closed, the last point will be the same as the&quot;,\n &quot;c25&quot;: &quot;first, so all you have to be concerned with is drawing&quot;,\n &quot;c26&quot;: &quot;lines between the points in the list. Anchor and extent&quot;,\n &quot;c27&quot;: &quot;are set to the top left and bottom right of the indicated&quot;,\n &quot;c28&quot;: &quot;region, and can be used as a simplistic rectangular&quot;,\n &quot;c29&quot;: &quot;detect for the mouse hover position over these types&quot;,\n &quot;c30&quot;: &quot;of areas.&quot;,\n &quot;c31&quot;: &quot;&quot;,\n &quot;c32&quot;: &quot;The textx and texty positions provide basic positioning&quot;,\n &quot;c33&quot;: &quot;information to help you locate the text information&quot;,\n &quot;c34&quot;: &quot;in a reasonable location associated with the area&quot;,\n &quot;c35&quot;: &quot;indication.&quot;,\n &quot;c36&quot;: &quot;&quot;,\n &quot;c37&quot;: &quot;Opacity is a value between 0 and 1, where .5 represents&quot;,\n &quot;c38&quot;: &quot;a 50% opaque backdrop and 1.0 represents a fully opaque&quot;,\n &quot;c39&quot;: &quot;backdrop. Recommendation is that regions be drawn&quot;,\n &quot;c40&quot;: &quot;only if the user hovers the pointer over the image,&quot;,\n &quot;c41&quot;: &quot;and that the text associated with the regions be drawn&quot;,\n &quot;c42&quot;: &quot;only if the user hovers the pointer over the indicated&quot;,\n &quot;c43&quot;: &quot;region.&quot;\n }\n}\n</code></pre>\n" }, { "answer_id": 51232322, "author": "bortunac", "author_id": 544803, "author_profile": "https://Stackoverflow.com/users/544803", "pm_score": 2, "selected": false, "text": "<p>*.json files are generally used as configuration files or static data, thus the need of comments → some editors like NetBeans accept comments in *.json.</p>\n<p>The problem is parsing content to an object. The solution is to always apply a cleaning function (server or client).</p>\n<p>###PHP</p>\n<pre><code> $rgx_arr = [&quot;/\\/\\/[^\\n]*/sim&quot;, &quot;/\\/\\*.*?\\*\\//sim&quot;, &quot;/[\\n\\r\\t]/sim&quot;];\n $valid_json_str = \\preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));\n</code></pre>\n<p>###JavaScript</p>\n<pre><code>valid_json_str = json_str.replace(/\\/\\/[^\\n]*/gim,'').replace(/\\/\\*.*?\\*\\//gim,'')\n</code></pre>\n" }, { "answer_id": 54329228, "author": "Tom", "author_id": 150016, "author_profile": "https://Stackoverflow.com/users/150016", "pm_score": 3, "selected": false, "text": "<p>The practical answer for <a href=\"https://en.wikipedia.org/wiki/Visual_Studio_Code\" rel=\"nofollow noreferrer\">Visual Studio Code</a> users in 2019 is to use the 'jsonc' extension.</p>\n<p>It is practical, because that is the extension recognized by Visual Studio Code to indicate &quot;JSON with comments&quot;. Please let me know about other editors/IDEs in the comments below.</p>\n<p>It would be nice if Visual Studio Code and other editors would add native support for JSON5 as well, but for now Visual Studio Code only includes support for 'jsonc'.</p>\n<p>(I searched through all the answers before posting this and none mention 'jsonc'.)</p>\n" }, { "answer_id": 55238032, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 2, "selected": false, "text": "<p>Sure you can comment JSON. To read a commented JSON file from JavaScript you can strip comments before parsing it (see the code below). I'm sure this code can be improved, but it is easy to understand for those who use regular expressions.</p>\n<p>I use commented JSON files to specify neuron shapes for my synthetic reflex systems. I also use commented JSON to store intermediate states for a running neuron system. It is very convenient to have comments. Don't listen to didacts who tell you they are a bad idea.</p>\n<pre><code>fetch(filename).then(function(response) {\n return response.text();\n}).then(function(commented) {\n return commented.\n replace(/\\/\\*[\\s\\S]*?\\*\\/|([^\\\\:]|^)\\/\\/.*$/gm, '$1').\n replace(/\\r/,&quot;\\n&quot;).\n replace(/\\n[\\n]+/,&quot;\\n&quot;);\n}).then(function(clean) {\n return JSON.parse(clean);\n}).then(function(json) {\n // Do what you want with the JSON object.\n});\n</code></pre>\n" }, { "answer_id": 55547317, "author": "Malekai", "author_id": 10415695, "author_profile": "https://Stackoverflow.com/users/10415695", "pm_score": 1, "selected": false, "text": "<p>I came across this problem in my current project as I have quite a bit of JSON that requires some commenting to keep things easy to remember.</p>\n<p>I've used this simple Python function to replace comments &amp; use <code>json.loads</code> to convert it into a <code>dict</code>:</p>\n<pre><code>import json, re\n\ndef parse_json(data_string):\n result = []\n for line in data_string.split(&quot;\\n&quot;):\n line = line.strip()\n if len(line) &lt; 1 or line[0:2] == &quot;//&quot;:\n continue\n if line[-1] not in &quot;\\,\\&quot;\\'&quot;:\n line = re.sub(&quot;\\/\\/.*?$&quot;, &quot;&quot;, line)\n result.append(line)\n return json.loads(&quot;\\n&quot;.join(result))\n\nprint(parse_json(&quot;&quot;&quot;\n{\n // This is a comment\n &quot;name&quot;: &quot;value&quot; // so is this\n // &quot;name&quot;: &quot;value&quot;\n // the above line gets removed\n}\n&quot;&quot;&quot;))\n</code></pre>\n" }, { "answer_id": 56626450, "author": "Roy Prins", "author_id": 470917, "author_profile": "https://Stackoverflow.com/users/470917", "pm_score": 5, "selected": false, "text": "<p><em><strong>Disclaimer: This is silly</strong></em></p>\n<p>There is actually a way to add comments, and stay within the specification (no additional parser needed). It will not result into human-readable comments without any sort of parsing though.</p>\n<p>You could abuse the following:</p>\n<blockquote>\n<p>Insignificant whitespace is allowed before or after any token.\nWhitespace is any sequence of one or more of the following code\npoints: character tabulation (U+0009), line feed (U+000A), carriage\nreturn (U+000D), and space (U+0020).</p>\n</blockquote>\n<p>In a hacky way, you can abuse this to add a comment. For instance: start and end your comment with a tab. Encode the comment in base3 and use the other whitespace characters to represent them. For instance.</p>\n<pre><code>010212 010202 011000 011000 011010 001012 010122 010121 011021 010202 001012 011022 010212 011020 010202 010202\n</code></pre>\n<p>(<code>hello base three</code> in ASCII) But instead of 0 use space, for 1 use line feed and for 2 use carriage return.</p>\n<p>This will just leave you with a lot of unreadable whitespace (unless you make an IDE plugin to encode/decode it on the fly).</p>\n<p>I never even tried this, for obvious reasons and neither should you.</p>\n" }, { "answer_id": 58731581, "author": "ifelse.codes", "author_id": 2950614, "author_profile": "https://Stackoverflow.com/users/2950614", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://www.json.org/\" rel=\"noreferrer\">JSON specification</a> does not support comments, <code>// or /* */</code> style.</p>\n<p>But some JSON parsing libraries and IDEs support them.</p>\n<p>Like:</p>\n<ol>\n<li><a href=\"https://json5.org/\" rel=\"noreferrer\">JSON5</a></li>\n<li><a href=\"https://code.visualstudio.com/docs/languages/json#_json-with-comments\" rel=\"noreferrer\">Visual Studio Code</a></li>\n<li><a href=\"https://github.com/vaidik/commentjson\" rel=\"noreferrer\">Commentjson</a></li>\n</ol>\n" }, { "answer_id": 62338887, "author": "nevelis", "author_id": 333988, "author_profile": "https://Stackoverflow.com/users/333988", "pm_score": 1, "selected": false, "text": "<p>Yes. You can put comments in a JSON file.</p>\n\n<pre><code>{\n \"\": \"Location to post to\",\n \"postUrl\": \"https://example.com/upload/\",\n\n \"\": \"Username for basic auth\",\n \"username\": \"joebloggs\",\n\n \"\": \"Password for basic auth (note this is in clear, be sure to use HTTPS!\",\n \"password\": \"bloejoggs\"\n}\n</code></pre>\n\n<p>A comment is simply a piece of text describing the purpose of a block of code or configuration. And because you can specify keys multiple times in JSON, you can do it like this. It's syntactically correct and the only tradeoff is you'll have an empty key with some garbage value in your dictionary (which you could trim...)</p>\n\n<p>I saw this question years and years ago but I only just saw this done like this in a project I'm working on and I thought this was a really clean way to do it. Enjoy!</p>\n" }, { "answer_id": 64202860, "author": "khashashin", "author_id": 7986808, "author_profile": "https://Stackoverflow.com/users/7986808", "pm_score": 0, "selected": false, "text": "<p>I really like @eli 's approach, there are over 30 answers but no one has mentioned lists (array). So using @eli 's approach we could do something like:</p>\n<pre><code>&quot;part_of_speech&quot;: {\n &quot;__comment&quot;: [\n &quot;@param {String} type - the following types can be used: &quot;,\n &quot;NOUN, VERB, ADVERB, ADJECTIVE, PRONOUN, PREPOSITION&quot;,\n &quot;CONJUNCTION, INTERJECTION, NUMERAL, PARTICLE, PHRASE&quot;,\n &quot;@param {String} type_free_form - is optional, can be empty string&quot;,\n &quot;@param {String} description - is optional, can be empty string&quot;,\n &quot;@param {String} source - is optional, can be empty string&quot;\n ],\n &quot;type&quot;: &quot;NOUN&quot;,\n &quot;type_free_form&quot;: &quot;noun&quot;,\n &quot;description&quot;: &quot;&quot;,\n &quot;source&quot;: &quot;https://google.com&quot;,\n &quot;noun_class&quot;: {\n &quot;__comment&quot;: [\n &quot;@param {String} noun_class - the following types can be used: &quot;,\n &quot;1_class, 2_class, 3_class, 4_class, 5_class, 6_class&quot;\n ],\n &quot;noun_class&quot;: &quot;4_class&quot;\n }\n}\n</code></pre>\n" }, { "answer_id": 64907232, "author": "Audrius Meškauskas", "author_id": 1439305, "author_profile": "https://Stackoverflow.com/users/1439305", "pm_score": 5, "selected": false, "text": "<p><strong>Yes</strong>, the new standard, <a href=\"https://spec.json5.org/#comments\" rel=\"noreferrer\">JSON5</a> allows the C++ style comments, among many <a href=\"https://spec.json5.org/#introduction\" rel=\"noreferrer\">other extensions</a>:</p>\n<pre><code>// A single line comment.\n\n/* A multi-\n line comment. */\n</code></pre>\n<p>The JSON5 Data Interchange Format (JSON5) is a superset of JSON that aims to alleviate some of the limitations of JSON. It is fully backwards compatible, and using it is probably better than writing the custom non standard parser, turning non standard features on for the existing one or using various hacks like string fields for commenting. Or, if the parser in use supports, simply agree <em>we are using JSON 5 subset that is JSON and C++ style comments</em>. It is much better than <em>we tweak JSON standard the way we see fit</em>.</p>\n<p>There is already <a href=\"https://www.npmjs.com/package/json5\" rel=\"noreferrer\">npm package</a>, <a href=\"https://pypi.org/project/json5/\" rel=\"noreferrer\">Python package</a>, <a href=\"https://github.com/falkreon/Jankson\" rel=\"noreferrer\">Java package</a> and <a href=\"https://gist.github.com/inlife/b54a0d9228e428284e1d8eccbed97e35\" rel=\"noreferrer\">C library</a> available. It is backwards compatible. I see no reason to stay with the &quot;official&quot; JSON restrictions.</p>\n<p>I think that removing comments from JSON has been driven by the same reasons as removing the operator overloading in Java: can be used the wrong way yet some clearly legitimate use cases were overlooked. For operator overloading, it is matrix algebra and complex numbers. For JSON comments, its is configuration files and other documents that may be written, edited or read by humans and not just by parser.</p>\n" }, { "answer_id": 66570490, "author": "Boppity Bop", "author_id": 347484, "author_profile": "https://Stackoverflow.com/users/347484", "pm_score": -1, "selected": false, "text": "<p>Comments are needed in JSON and <strong>comments ARE available in at least .NET Core</strong> JSON and Newtonsoft Json. Works perfectly.</p>\n<pre><code>{\n // this is a comment for those who is ok with being different\n &quot;regular-json&quot;: &quot;stuff&quot;...\n}\n</code></pre>\n" }, { "answer_id": 68124843, "author": "peak", "author_id": 997358, "author_profile": "https://Stackoverflow.com/users/997358", "pm_score": 3, "selected": false, "text": "<p>As <a href=\"https://web.archive.org/web/20130101004216/http://tech.groups.yahoo.com:80/group/json/message/152\" rel=\"noreferrer\">the inventor of JSON said</a>:</p>\n<blockquote>\n<p>JSON does not have comments. A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments.</p>\n</blockquote>\n<p>The utility <a href=\"/questions/tagged/jq\" class=\"post-tag\" title=\"show questions tagged &#39;jq&#39;\" rel=\"tag\">jq</a> includes a decoder that does allow &quot;#&quot;-style comments and so jq is one of several tools that can be used in conjunction with JSON-with-comments files, so long as such files are treated as &quot;jq programs&quot;, rather than as JSON files. For example:</p>\n<pre><code>$ jq -ncf &lt;(echo $'[1, # one\\n2 ] # two') \n[1,2]\n</code></pre>\n<p>More importantly, jq can handle very large JSON-with-comments files as programs; this can be illustrated using a well-known JSON file:</p>\n<pre><code>$ ls -l JEOPARDY_QUESTIONS1.json\n-rw-r--r-- 2 xyzzy staff 55554625 May 12 2016 JEOPARDY_QUESTIONS1.json\n\n$ jq -nf JEOPARDY_QUESTIONS1.json | jq length\n216930\n</code></pre>\n" }, { "answer_id": 68782282, "author": "dilshan", "author_id": 13237885, "author_profile": "https://Stackoverflow.com/users/13237885", "pm_score": 3, "selected": false, "text": "<p>The Pure answer is <strong>No</strong>.</p>\n<p>But some editors and platforms use workarounds to add comments to JSON.</p>\n<p><strong>1</strong>. Today most editors have built-in options and extensions to add comments to JSON documents. (eg:- VS Code also has a JSON with Comments <code>(jsonc) mode</code> / VS Code also has nice extensions for that)</p>\n<p><a href=\"https://code.visualstudio.com/docs/languages/json#_json-with-comments\" rel=\"noreferrer\">Link to activate jsonc mode in VsCode </a></p>\n<p><strong>2</strong>. Some platforms provide built-in ways to add comments (impure json).\n(eg:- In firebase, I can comment <code>firebase.json</code>s for a while without issue.</p>\n<pre><code> {\n &quot;hosting&quot;: {\n &quot;headers&quot;: [\n /*{\n &quot;source&quot;: &quot;*.html&quot;,\n &quot;headers&quot;: [\n {\n &quot;key&quot;: &quot;Content-Security-Policy&quot;,\n &quot;value&quot;: &quot;default-src 'self' ...&quot;\n }\n ]\n },*/\n ]\n }\n }\n</code></pre>\n<p><strong>3</strong>. In your own JSON parsing method, you can set a predefined key name as a comment.</p>\n<p>eg:-</p>\n<pre><code> {\n &quot;comment&quot; : &quot;This is a comment&quot;,\n &quot;//&quot; : &quot;This also comment&quot;,\n &quot;name&quot; : &quot;This is a real value&quot;\n }\n</code></pre>\n" }, { "answer_id": 70139980, "author": "Deleted", "author_id": 585968, "author_profile": "https://Stackoverflow.com/users/585968", "pm_score": 2, "selected": false, "text": "<p>Well at the time of writing, <strong>appsettings.json</strong> supports comments.</p>\n<p>e.g. (<a href=\"https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#configure-logging\" rel=\"nofollow noreferrer\">sample</a> courtesy of Microsoft)</p>\n<pre><code>{\n &quot;Logging&quot;: {\n &quot;LogLevel&quot;: { // All providers, LogLevel applies to all the enabled providers.\n &quot;Default&quot;: &quot;Error&quot;, // Default logging, Error and higher.\n &quot;Microsoft&quot;: &quot;Warning&quot; // All Microsoft* categories, Warning and higher.\n },\n &quot;Debug&quot;: { // Debug provider.\n &quot;LogLevel&quot;: {\n &quot;Default&quot;: &quot;Information&quot;, // Overrides preceding LogLevel:Default setting.\n &quot;Microsoft.Hosting&quot;: &quot;Trace&quot; // Debug:Microsoft.Hosting category.\n }\n },\n &quot;EventSource&quot;: { // EventSource provider\n &quot;LogLevel&quot;: {\n &quot;Default&quot;: &quot;Warning&quot; // All categories of EventSource provider.\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 70373317, "author": "Heewoon", "author_id": 17341715, "author_profile": "https://Stackoverflow.com/users/17341715", "pm_score": 3, "selected": false, "text": "<p>Although JSON does not support comments, <strong>JSONC</strong> does.</p>\n<p>Name your file with '.jsonc' extension and use a <strong>jsonc</strong> parser.<br />\nSorry if this answer was too late.</p>\n<pre><code>jsonWithComments.jsonc\n</code></pre>\n<p>Example:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n // This is a comment!\n &quot;something&quot;: &quot;idk&quot;\n\n}\n</code></pre>\n<p>If this is unclear, I think the bot is weird.\nPlease try before voting this question as unhelpful.</p>\n" }, { "answer_id": 71157617, "author": "EKanadily", "author_id": 365867, "author_profile": "https://Stackoverflow.com/users/365867", "pm_score": 3, "selected": false, "text": "<p>json specs doesn't support comments BUT you can work around the problem by writing your comment as keys, like this</p>\n<pre><code>{\n &quot;// my own comment goes here&quot;:&quot;&quot;,\n &quot;key1&quot;:&quot;value 1&quot;,\n\n &quot;// another comment goes here&quot;:&quot;&quot;,\n &quot;key 2&quot;: &quot;value 2 here&quot;\n}\n</code></pre>\n<p>this way we are using the comment texts as keys ensuring (almost) that they are unique and they will not break any parsers. if some of your comments are not unique just add random numbers at the end.</p>\n<p>if you need to parse comments to do any processing like stripping them you can fill the comment values with text indicating that it is a comment , like so:</p>\n<pre><code> {\n &quot;// my own comment goes here&quot; : &quot;_comment&quot;,\n &quot;key1&quot;:&quot;value 1&quot;,\n\n &quot;// another comment goes here&quot; : &quot;_comment&quot;,\n &quot;key 2&quot;: &quot;value 2 here&quot;\n} \n \n</code></pre>\n<p>this way a parser can find all comments and process them.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4105/" ]
Can I use comments inside a [JSON](https://en.wikipedia.org/wiki/JSON) file? If so, how?
No. JSON is data-only. If you include a comment, then it must be data too. You could have a designated data element called `"_comment"` (or something) that should be ignored by apps that use the JSON data. You would probably be better having the comment in the processes that generates/receives the JSON, as they are supposed to know what the JSON data will be in advance, or at least the structure of it. But if you decided to: ``` { "_comment": "comment text goes here...", "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } } ```
244,779
<p>I have the following <code>before_filter</code>:</p> <pre><code> def find_current_membership respond_to do |wants| wants.html { @current_membership = @group.memberships.for(@current_user) } wants.rss {} wants.js { @current_membership = @group.memberships.for(@current_user) } end end </code></pre> <p>I would like to share the code for the HTML and JS blocks. Is there a better way than just throwing the code into a method? I was hoping this would work:</p> <pre><code> def find_current_membership respond_to do |wants| wants.rss {} wants.all { @current_membership = @group.memberships.for(@current_user) } end end </code></pre> <p>But alas, it did not.</p>
[ { "answer_id": 244831, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": false, "text": "<p>In this case you could probably do something like:</p>\n\n<pre><code>before_filter :only =&gt; :find_current_membership do |c|\n load_current_membership if not request.format.rss?\nend\n</code></pre>\n\n<p>Alternatively you could use the request.format.rss? in your controller method to conditionally load the memberships.</p>\n\n<p>Either way your first step should be to refactor that into a method.</p>\n" }, { "answer_id": 244893, "author": "Cameron Booth", "author_id": 14873, "author_profile": "https://Stackoverflow.com/users/14873", "pm_score": 3, "selected": true, "text": "<p>If I'm reading this right, it looks like <code>find_current_membership</code> is your <code>before_filter</code> method, is that right? eg:</p>\n\n<pre><code>class SomeController &lt; ApplicationController\n before_filter :find_current_membership\n ...\n</code></pre>\n\n<p>I think it's a bit non-standard to use <code>respond_to</code> inside a <code>before_filter</code>, they are meant to just do something and render on failure. It seems to me like you want something more like this</p>\n\n<pre><code> class SomeController &lt; ApplicationController\n before_filter :find_current_membership\n\n def some_action\n # stuff, or maybe nothing\n end\n\n private\n def find_current_membership\n @current_membership = @group.memberships.for(@current_user) unless request.format.rss?\n end\n end\n</code></pre>\n" }, { "answer_id": 246551, "author": "allesklar", "author_id": 19893, "author_profile": "https://Stackoverflow.com/users/19893", "pm_score": 1, "selected": false, "text": "<p>How about this simple solution!?</p>\n\n<pre><code>def find_current_membership\n @current_membership = @group.memberships.for(@current_user)\n respond_to do |wants|\n wants.html\n wants.rss {}\n wants.js\n end\nend\n</code></pre>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14895/" ]
I have the following `before_filter`: ``` def find_current_membership respond_to do |wants| wants.html { @current_membership = @group.memberships.for(@current_user) } wants.rss {} wants.js { @current_membership = @group.memberships.for(@current_user) } end end ``` I would like to share the code for the HTML and JS blocks. Is there a better way than just throwing the code into a method? I was hoping this would work: ``` def find_current_membership respond_to do |wants| wants.rss {} wants.all { @current_membership = @group.memberships.for(@current_user) } end end ``` But alas, it did not.
If I'm reading this right, it looks like `find_current_membership` is your `before_filter` method, is that right? eg: ``` class SomeController < ApplicationController before_filter :find_current_membership ... ``` I think it's a bit non-standard to use `respond_to` inside a `before_filter`, they are meant to just do something and render on failure. It seems to me like you want something more like this ``` class SomeController < ApplicationController before_filter :find_current_membership def some_action # stuff, or maybe nothing end private def find_current_membership @current_membership = @group.memberships.for(@current_user) unless request.format.rss? end end ```
244,807
<p>I have a c# site which makes use of a lot of images with embedded english text. </p> <p>How can I use a standard resource file to swap out images depending on the language?</p> <p>I have a resx file in my App_GlobalResources directory, but I can't seem to get it plugged into an asp:image control for the imageurl correctly.</p> <p>Ideas?</p> <p><strong>UPDATE:</strong> </p> <p>For some further information, here is the image tag code:</p> <pre><code>&lt;asp:image runat="server" ID="img2" ImageUrl="&lt;%$Resources: Resource, cs_logo %&gt;" /&gt; </code></pre> <p>The result on the client side is:</p> <pre><code>&lt;img id="img2" src="System.Drawing.Bitmap" style="border-width:0px;" /&gt; </code></pre> <p>Note that the source is obviously not what I expected...</p>
[ { "answer_id": 244830, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 4, "selected": true, "text": "<p>you can store the url of the image in your resource file and use the following inline code in the control </p>\n\n<pre><code>&lt;asp:Image ImageUrl=\"&lt;%$resources:Image1 %&gt;\" /&gt;\n</code></pre>\n\n<h3>Update</h3>\n\n<p>this <a href=\"http://aspalliance.com/726\" rel=\"noreferrer\">link</a> could be helpful on what you are trying to accomplish</p>\n\n<p>or </p>\n\n<p>you can also try to stored the resource as string and set the value to the url location instead of storing the image in the resouce file.</p>\n" }, { "answer_id": 245141, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>One thing you might try to do is to create a simple \"image service\" that can serve up the image in the proper format from the embedded resources.</p>\n\n<p>You don't have to create web service itself, you simply create an aspx page and in the code behind you change the the Response.ContentType to be \"image/png\" or whatever format you prefer. This also requires a get parameter in the URL to the page itself, but that can be easily filtered. So the Page_Load method of your image service might look something like this:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\n Dim FinalBitmap As Bitmap\n Dim strRenderSource As String\n Dim msStream As New MemoryStream()\n\n strRenderSource = Request.Params(\"ImageName\").ToString()\n\n ' Write your code here that gets the image from the app resources.\n FinalBitmap = New Bitmap(Me.Resources(strRenderSource))\n FinalBitmap.Save(msStream, ImageFormat.Png)\n\n Response.Clear()\n Response.ContentType = \"image/png\"\n\n msStream.WriteTo(Response.OutputStream)\n\n If Not IsNothing(FinalBitmap) Then FinalBitmap.Dispose()\n\nEnd Sub\n</code></pre>\n\n<p>Then back on your ASPX page you have...</p>\n\n<pre><code>&lt;asp:Image ImageUrl=\"http://localhost/GetImage.aspx?ImageName=Image1\" /&gt;\n</code></pre>\n\n<p>Oh, and don't forget to import System.Drawing and System.Drawing.Imaging in the page.</p>\n" }, { "answer_id": 1847349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>if you are using global resources file you need to add it like this </p>\n\n<pre><code>&lt;img id=\"WelocmeICon\" runat=\"server\" alt=\"welcome icon\" \n src=\"&lt;%$resources:NmcResource,WelcomeIcon %&gt;\" /&gt;\n</code></pre>\n\n<p>and because i use img control i added runatserver and id for it </p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
I have a c# site which makes use of a lot of images with embedded english text. How can I use a standard resource file to swap out images depending on the language? I have a resx file in my App\_GlobalResources directory, but I can't seem to get it plugged into an asp:image control for the imageurl correctly. Ideas? **UPDATE:** For some further information, here is the image tag code: ``` <asp:image runat="server" ID="img2" ImageUrl="<%$Resources: Resource, cs_logo %>" /> ``` The result on the client side is: ``` <img id="img2" src="System.Drawing.Bitmap" style="border-width:0px;" /> ``` Note that the source is obviously not what I expected...
you can store the url of the image in your resource file and use the following inline code in the control ``` <asp:Image ImageUrl="<%$resources:Image1 %>" /> ``` ### Update this [link](http://aspalliance.com/726) could be helpful on what you are trying to accomplish or you can also try to stored the resource as string and set the value to the url location instead of storing the image in the resouce file.
244,812
<p>I have an existing database with the table Transactions in it. I have added a new table called TransactionSequence where each transaction will ultimately have only one record. We are using the sequence table to count transactions for a given account. I have mapped this as a one-to-one mapping where TransactionSequence has a primary key of TransactionId. </p> <p>The constraint is that there is an instead of trigger on the transaction table does not allow updates of cancelled or posted transactions. </p> <p>So, when the sequence is calculated and the transaction is saved, NHibernate tries to send an update on the transaction like 'UPDATE Transaction SET TransactionId = ? WHERE TransactionId = ?'. But this fails because of the trigger. How can I configure my mapping so that NHibernate will not try to update the Transaction table when a new TransactionSequence table is inserted?</p> <p>Transaction mapping:</p> <pre><code>&lt;class name="Transaction" table="Transaction" dynamic-update="true" select-before-update="true"&gt; &lt;id name="Id" column="ID"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;property name="TransactionTypeId" access="field.camelcase-underscore" /&gt; &lt;property name="TransactionStatusId" column="DebitDebitStatus" access="field.camelcase-underscore" /&gt; &lt;one-to-one name="Sequence" class="TransactionSequence" fetch="join" lazy="false" constrained="false"&gt; &lt;/one-to-one&gt; &lt;/class&gt; </code></pre> <p>And the sequence mapping:</p> <pre><code>&lt;class name="TransactionSequence" table="TransactionSequence" dynamic-update="true"&gt; &lt;id name="TransactionId" column="TransactionID" type="Int32"&gt; &lt;generator class="foreign"&gt; &lt;param name="property"&gt;Transaction&lt;/param&gt; &lt;/generator&gt; &lt;/id&gt; &lt;version name="Version" column="Version" unsaved-value="-1" access="field.camelcase-underscore" /&gt; &lt;property name="SequenceNumber" not-null="true" /&gt; &lt;one-to-one name="Transaction" class="Transaction" constrained="true" foreign-key="fk_Transaction_Sequence" /&gt; &lt;/class&gt; </code></pre> <p>Any help would be greatly appreciated...</p>
[ { "answer_id": 244871, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 5, "selected": true, "text": "<p>One to one mapping in nhibernate doesn't work the way you think it does. It's designed so that you have two classes, which when persisted to their corresponding tables have the same primary keys.</p>\n\n<p>However you can make it work, but it's not pretty. I'll show you how then offer up some alternatives:</p>\n\n<p>In your Transaction hbml:</p>\n\n<pre><code>&lt;one-to-one name=\"Sequence\" class=\"TransactionSequence\" property-ref=\"Transaction\"/&gt;\n</code></pre>\n\n<p>In your Sequence html:</p>\n\n<pre><code>&lt;many-to-one name=\"Transaction\" class=\"Transaction\" column=\"fk_Transaction_Sequence\" /&gt;\n</code></pre>\n\n<p>This <em>should</em> do what you want it to do. Note the property-ref.</p>\n\n<p>The next question you're going to post on is going to ask how you get lazy loading on one-to-one associations. The answer is, you can't... well you can, but it probably won't work. The problem is that you have your foreign key on the sequence table, which means that nhibernate has to hit the database to see if the target exists. Then you can try playing around with constrained=\"true/false\" to see if you can persuade it to lazily load the one-to-one association.</p>\n\n<p>All in all, it's going to result in a total waste of your time.</p>\n\n<p>I suggest either:</p>\n\n<ol>\n<li>Have two many-to-one associations.</li>\n<li>Have a many-to-one association with a collection on the other end.</li>\n</ol>\n\n<p>This will save you a lot of headaches in the long run.</p>\n" }, { "answer_id": 246688, "author": "SteveBering", "author_id": 32196, "author_profile": "https://Stackoverflow.com/users/32196", "pm_score": 2, "selected": false, "text": "<p>Turns out that for my situation a <code>&lt;join table&gt;</code> mapping worked best. I just had to make sure that I made the properties that came from the second table were nullable types, or it would do an insert on save even if nothing had changed. Since I did not need lazy loading for the second table, this works great. I am sure that I could have gotten paired many-to-one mappings to work, but it was not intuitive and seems more complicated than the join table option, however <code>&lt;join table&gt;</code> is only available in NHibernate 2.0 and up.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32196/" ]
I have an existing database with the table Transactions in it. I have added a new table called TransactionSequence where each transaction will ultimately have only one record. We are using the sequence table to count transactions for a given account. I have mapped this as a one-to-one mapping where TransactionSequence has a primary key of TransactionId. The constraint is that there is an instead of trigger on the transaction table does not allow updates of cancelled or posted transactions. So, when the sequence is calculated and the transaction is saved, NHibernate tries to send an update on the transaction like 'UPDATE Transaction SET TransactionId = ? WHERE TransactionId = ?'. But this fails because of the trigger. How can I configure my mapping so that NHibernate will not try to update the Transaction table when a new TransactionSequence table is inserted? Transaction mapping: ``` <class name="Transaction" table="Transaction" dynamic-update="true" select-before-update="true"> <id name="Id" column="ID"> <generator class="native" /> </id> <property name="TransactionTypeId" access="field.camelcase-underscore" /> <property name="TransactionStatusId" column="DebitDebitStatus" access="field.camelcase-underscore" /> <one-to-one name="Sequence" class="TransactionSequence" fetch="join" lazy="false" constrained="false"> </one-to-one> </class> ``` And the sequence mapping: ``` <class name="TransactionSequence" table="TransactionSequence" dynamic-update="true"> <id name="TransactionId" column="TransactionID" type="Int32"> <generator class="foreign"> <param name="property">Transaction</param> </generator> </id> <version name="Version" column="Version" unsaved-value="-1" access="field.camelcase-underscore" /> <property name="SequenceNumber" not-null="true" /> <one-to-one name="Transaction" class="Transaction" constrained="true" foreign-key="fk_Transaction_Sequence" /> </class> ``` Any help would be greatly appreciated...
One to one mapping in nhibernate doesn't work the way you think it does. It's designed so that you have two classes, which when persisted to their corresponding tables have the same primary keys. However you can make it work, but it's not pretty. I'll show you how then offer up some alternatives: In your Transaction hbml: ``` <one-to-one name="Sequence" class="TransactionSequence" property-ref="Transaction"/> ``` In your Sequence html: ``` <many-to-one name="Transaction" class="Transaction" column="fk_Transaction_Sequence" /> ``` This *should* do what you want it to do. Note the property-ref. The next question you're going to post on is going to ask how you get lazy loading on one-to-one associations. The answer is, you can't... well you can, but it probably won't work. The problem is that you have your foreign key on the sequence table, which means that nhibernate has to hit the database to see if the target exists. Then you can try playing around with constrained="true/false" to see if you can persuade it to lazily load the one-to-one association. All in all, it's going to result in a total waste of your time. I suggest either: 1. Have two many-to-one associations. 2. Have a many-to-one association with a collection on the other end. This will save you a lot of headaches in the long run.
244,826
<p>I'm stuck with .Net 1.1 application (i.e. I can not use the generics goodies from 2.0 for now), and I was trying to optimize some parts of the code. As it deals a lot with runtime callable wrappers, which need to be released, I ended up to create a utility method which loops until all references are released. The signature of the method is:</p> <pre><code>void ReleaseObject(object comObject) </code></pre> <p>After releasing all comObjects, I call GC.Collect and GC.WaitForPendingFinalizers (don't ask - anybody dealing with Office interop knows).</p> <p>And ... as usual, I hit a corner case - if I do not assign the corresponding managed reference to null before the GC.Collect call, it does not cleanup properly.</p> <p>So, my code looks like:</p> <pre><code>ReleaseObject(myComObject); myComObject = null; GC.Collect() ... </code></pre> <p>As, there are a bunch of xxx=null, I decided to put this in the util method, but as there is a difference between passing by reference, and passing a reference parameter, obviously I had to change the method to:</p> <pre><code>void ReleaseObject(out object comObject) { //do release comObject = null; } </code></pre> <p>and edit the caller to:</p> <pre><code>MyComClass myComObject = xxxx; ReleaseObject(out myComObject); </code></pre> <p>This fails with a message: "Cannot convert from 'out MyComClass' to 'out object'"</p> <p>While I can think of why it can be a problem (i.e. the reverse cast from object to MyComClass is not implicit, and there is no guarantee what the method will do), I was wondering if there is a workaround, or I need to stay with my hundreds assignments of nulls.</p> <p>Note: I have a bunch of different COM objects types, thats why I need a "object" parameter, and not a type safe one.</p>
[ { "answer_id": 244838, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Why is it better to call a method than to just set the variable to null? They're both single line calls, and the latter is a lot simpler.</p>\n\n<p>It does sound very odd that you need to set them to null in the first place though. Are these static variables, or instance variables whose values need to be released earlier than their containing object? If the variable is just a local variable which will go out of scope anyway, setting it to null shouldn't make any difference (in release).</p>\n\n<p>Do the RCWs not implement IDisposable? If so, calling Dispose (preferably via a using statement) would be the best bet.</p>\n\n<p>(After discussions in comments.)</p>\n\n<p>These are local variables, which aren't referenced later in the method. That means the garbage collector will realise that they don't need to be treated as \"root\" references - so setting them to null shouldn't make any difference.</p>\n\n<p>To answer the original question directly, however: no, you can't pass a variable by reference unless the method parameter is of exactly the same type, so you're out of luck here. (With generics it would be possible, but you've said you're limited to .NET 1.1.)</p>\n" }, { "answer_id": 244880, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>You should be calling <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx\" rel=\"nofollow noreferrer\"><code>Marshal.ReleaseComObject</code></a>, which AFAIK was available in 1.1.</p>\n\n<p>You probably mean \"ref\":</p>\n\n<pre><code>static void ReleaseObject(ref object comObject)\n{\n if(comObject != null)\n {\n //do release\n comObject = null;\n }\n}\n</code></pre>\n\n<p>[edit re comments] however, this will only work for untyped objects, so not much use without generics! Oh for C# 2.0...</p>\n\n<p>Re the \"ref\"; if the variables are truly variables (meaning: method variables), then they will go out of scope shortly and get collected. The \"ref\" would only be useful to release fields. But to be honest, it would be simpler just to set them to null...</p>\n\n<p>A typical COM pattern is:</p>\n\n<pre><code>SomeType obj = new SomeType();\ntry {\n obj.SomeMethod(); // etc\n} finally {\n Marshal.ReleaseComObject(obj);\n}\n</code></pre>\n" }, { "answer_id": 244887, "author": "Leopold Cimrman", "author_id": 32008, "author_profile": "https://Stackoverflow.com/users/32008", "pm_score": 0, "selected": false, "text": "<p>In my opinion you won't be able to set those objects to null in another method (BTW you would need to use <strong>ref</strong> parameter instead of <strong>out</strong> to make it working, anyway you would hit the same problem with \"Cannot convert...\" error.)\nI'd recommend to create and array of objects and than iterate through that array, calling the ReleaseObject method and setting those objects to null. Something like:</p>\n\n<pre><code>List garbagedObjects = new List();\ngarbagedObjects.Add(myComObject1);\ngarbagedObjects.Add(myComObject2);\n...\nforeach(object garbagedObject in garbagedObjects)\n{\n ReleaseObject(garbagedObject);\n garbagedObject = null;\n}\ngarbagedObjects = null;\nGC.Collect();\n...\n</code></pre>\n" }, { "answer_id": 245357, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>Sunny, ref and out are a marshalling hints + contract to the compiler. Ref and out are a carryover to COM days - the marshalling hints for objects when sent over the wire / between processes.</p>\n\n<p>The <code>out</code> contract</p>\n\n<pre><code>void foo( out MyClass x)\n</code></pre>\n\n<ol>\n<li>foo() will set <code>x</code> to something before it returns.</li>\n<li><code>x</code> has no value when foo() is entered, and you get a compiler error if you attempt to use <code>x</code> before setting it. (use of unassigned out parameter x)</li>\n</ol>\n\n<p>The <code>ref</code> contract </p>\n\n<pre><code>void foo( ref MyClass x)\n</code></pre>\n\n<ol>\n<li>ref allows changing the callers reference.</li>\n<li>x has to be assignable \n\n<ul>\n<li>you cannot cast something to an intermediate variable foo( ref (object) something)</li>\n<li>x can not be a property</li>\n</ul></li>\n</ol>\n\n<p>The reality of the last two points are likely to stop you doing what you're trying to do, because in effect they make no sense when you understand what references really are. If you want to know that, ask Jon Skeet (he wrote a book).</p>\n\n<p>When marshalling ref, it says that in addition to the return value, bring back ref values as well.\nWhen marshalling out, it says don't bother sending the out value when the method is called, but remember to bring back the out value in addition to the return value.</p>\n\n<hr>\n\n<p>DISCLAIMER DISCLAIMER DISCLAIMER</p>\n\n<p>As others point out, something fishy is going on. It appears the brute-force code you are maintaining has some subtle bugs and suffers from coding by coincidence. The best solution is probably to add another layer of indirection. i.e. A wrapper to the wrapper class that ensures deterministic cleanup where you can write the messy code once and only once instead of peppering it throughout your codebase.</p>\n\n<hr>\n\n<p>That said .. </p>\n\n<p>Alternative 1</p>\n\n<p>Ref won't do the trick unless you provide overloads for every type of (com) object you will call it with.</p>\n\n<pre><code>// need a remove method for each type. \nvoid Remove( ref Com1 x ) { ...; x = null; }\nvoid Remove( ref Con2 x ) { ...; x = null; }\nvoid Remove( ref Com3 x ) { ...; x = null; }\n\n// a generics version using ref.\nvoid RemoveComRef&lt;ComT&gt;(ref ComT t) where ComT : class\n{\n System.Runtime.InteropServices.Marshal.ReleaseComObject(t);\n t = null; \n}\n\nCom1 c1 = new Com1();\nCom2 c2 = new Com2();\nRemove( ref c1 );\nRemoveComRef(ref c2); // the generics version again.\n</code></pre>\n\n<p>Alternative 2</p>\n\n<p>If you don't want to do that, return null from the Remove() method and cast back to the type of object. </p>\n\n<pre><code>class Remover\n{\n // .net 1.1 must cast if assigning\n public static object Remove(object x)\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(x);\n return null;\n }\n\n // uses generics.\n public static ComT RemoveCom&lt;ComT&gt;(ComT t) where ComT : class\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(t);\n return null;\n } \n}\n\nCom1 c1 = new Com1();\nCom2 c2 = new Com2();\nc1 = (Com1)Remover.Remove(c1); // no reliance on generics\nc2 = Remover.RemoveCom(c2); // relies on generics\n</code></pre>\n\n<p>* I added generic versions for comparison.</p>\n\n<p>The above code has the effect that when looking at code you become suspicious when you see a call to Remove(x) without the assignment (making wrong code look wrong). You could even Grep through the codebase looking for calls to Remove where assignment doesn't take place. </p>\n\n<hr>\n\n<p>DISCLAIMER - all the above is predicated on your needing to set the reference to null manually, which (normally) isn't necessary.</p>\n" } ]
2008/10/28
[ "https://Stackoverflow.com/questions/244826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220/" ]
I'm stuck with .Net 1.1 application (i.e. I can not use the generics goodies from 2.0 for now), and I was trying to optimize some parts of the code. As it deals a lot with runtime callable wrappers, which need to be released, I ended up to create a utility method which loops until all references are released. The signature of the method is: ``` void ReleaseObject(object comObject) ``` After releasing all comObjects, I call GC.Collect and GC.WaitForPendingFinalizers (don't ask - anybody dealing with Office interop knows). And ... as usual, I hit a corner case - if I do not assign the corresponding managed reference to null before the GC.Collect call, it does not cleanup properly. So, my code looks like: ``` ReleaseObject(myComObject); myComObject = null; GC.Collect() ... ``` As, there are a bunch of xxx=null, I decided to put this in the util method, but as there is a difference between passing by reference, and passing a reference parameter, obviously I had to change the method to: ``` void ReleaseObject(out object comObject) { //do release comObject = null; } ``` and edit the caller to: ``` MyComClass myComObject = xxxx; ReleaseObject(out myComObject); ``` This fails with a message: "Cannot convert from 'out MyComClass' to 'out object'" While I can think of why it can be a problem (i.e. the reverse cast from object to MyComClass is not implicit, and there is no guarantee what the method will do), I was wondering if there is a workaround, or I need to stay with my hundreds assignments of nulls. Note: I have a bunch of different COM objects types, thats why I need a "object" parameter, and not a type safe one.
Why is it better to call a method than to just set the variable to null? They're both single line calls, and the latter is a lot simpler. It does sound very odd that you need to set them to null in the first place though. Are these static variables, or instance variables whose values need to be released earlier than their containing object? If the variable is just a local variable which will go out of scope anyway, setting it to null shouldn't make any difference (in release). Do the RCWs not implement IDisposable? If so, calling Dispose (preferably via a using statement) would be the best bet. (After discussions in comments.) These are local variables, which aren't referenced later in the method. That means the garbage collector will realise that they don't need to be treated as "root" references - so setting them to null shouldn't make any difference. To answer the original question directly, however: no, you can't pass a variable by reference unless the method parameter is of exactly the same type, so you're out of luck here. (With generics it would be possible, but you've said you're limited to .NET 1.1.)