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
|
---|---|---|---|---|---|---|
63,632 | <p>I'm trying to import an XML file via a web page in a Ruby on Rails application, the code ruby view code is as follows (I've removed HTML layout tags to make reading the code easier)</p>
<pre><code><% form_for( :fmfile, :url => '/fmfiles', :html => { :method => :post, :name => 'Form_Import_DDR', :enctype => 'multipart/form-data' } ) do |f| %>
<%= f.file_field :document, :accept => 'text/xml', :name => 'fmfile_document' %>
<%= submit_tag 'Import DDR' %>
<% end %>
</code></pre>
<p>Results in the following HTML form</p>
<pre><code><form action="/fmfiles" enctype="multipart/form-data" method="post" name="Form_Import_DDR"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="3da97372885564a4587774e7e31aaf77119aec62" />
<input accept="text/xml" id="fmfile_document" name="fmfile_document" size="30" type="file" />
<input name="commit" type="submit" value="Import DDR" />
</form>
</code></pre>
<p>The Form_Import_DDR method in the 'fmfiles_controller' is the code that does the hard work of reading the XML document in using REXML. The code is as follows</p>
<pre><code>@fmfile = Fmfile.new
@fmfile.user_id = current_user.id
@fmfile.file_group_id = 1
@fmfile.name = params[:fmfile_document].original_filename
respond_to do |format|
if @fmfile.save
require 'rexml/document'
doc = REXML::Document.new(params[:fmfile_document].read)
doc.root.elements['File'].elements['BaseTableCatalog'].each_element('BaseTable') do |n|
@base_table = BaseTable.new
@base_table.base_table_create(@fmfile.user_id, @fmfile.id, n)
end
</code></pre>
<p>And it carries on reading all the different XML elements in.</p>
<p>I'm using Rails 2.1.0 and Mongrel 1.1.5 in Development environment on Mac OS X 10.5.4, site DB and browser on same machine.</p>
<p>My question is this. This whole process works fine when reading an XML document with character encoding UTF-8 but fails when the XML file is UTF-16, does anyone know why this is happening and how it can be stopped?</p>
<p>I have included the error output from the debugger console below, it takes about 5 minutes to get this output and the browser times out before the following output with the 'Failed to open page'</p>
<pre><code>Processing FmfilesController#create (for 127.0.0.1 at 2008-09-15 16:50:56) [POST]
Session ID: BAh7CDoMdXNlcl9pZGkGOgxjc3JmX2lkIiVmM2I3YWU2YWI4ODU2NjI0NDM2
NTFmMDE1OGY1OWQxNSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxh
c2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--dd9f588a68ed628ab398dd1a967eedcd09e505e0
Parameters: {"commit"=>"Import DDR", "authenticity_token"=>"3da97372885564a4587774e7e31aaf77119aec62", "action"=>"create", "fmfile_document"=>#<File:/var/folders/LU/LU50A0vNHA07S4rxDAOk4E+++TI/-Tmp-/CGI.3001.1>, "controller"=>"fmfiles"}
[4;36;1mUser Load (0.000350)[0m [0;1mSELECT * FROM "users" WHERE (id = 1) LIMIT 1[0m
[4;35;1mFmfile Create (0.000483)[0m [0mINSERT INTO "fmfiles" ("name", "file_group_id", "updated_at", "report_created_at", "report_link", "report_version", "option_on_open_account_name", "user_id", "option_default_custom_menu_set", "option_on_close_script", "path", "report_type", "option_on_open_layout", "option_on_open_script", "created_at") VALUES('TheTest_fp7 2.xml', 1, '2008-09-15 15:50:56', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, '2008-09-15 15:50:56')[0m
REXML::ParseException (#<Iconv::InvalidCharacter: "਼䙍偒数 (followed by a few thousand similar looking chinese characters)
䙍偒数潲琾", ["\n"]>
/Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `conv'
/Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `decode'
/Library/Ruby/Site/1.8/rexml/source.rb:50:in `encoding='
/Library/Ruby/Site/1.8/rexml/parsers/baseparser.rb:210:in `pull'
/Library/Ruby/Site/1.8/rexml/parsers/treeparser.rb:21:in `parse'
/Library/Ruby/Site/1.8/rexml/document.rb:190:in `build'
/Library/Ruby/Site/1.8/rexml/document.rb:45:in `initialize'
</code></pre>
| [
{
"answer_id": 64068,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than a rails/mongrel problem, it sounds more likely that there's an issue either with your XML file or with the way REXML handles it. You can check this by writing a short script to read your XML file directly (rather than within a request) and seeing if it still fails.</p>\n\n<p>Assuming it does, there are a couple of things I'd look at. First, I'd check you are running the latest version of REXML. A couple of years ago there was a bug (<a href=\"http://www.germane-software.com/projects/rexml/ticket/63\" rel=\"nofollow noreferrer\">http://www.germane-software.com/projects/rexml/ticket/63</a>) in its UTF-16 handling. </p>\n\n<p>The second thing I'd check is if you're issue is similar to this: <a href=\"http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/ba7b0585c7a6330d\" rel=\"nofollow noreferrer\">http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/ba7b0585c7a6330d</a>. If so you can try the workaround in that thread.</p>\n\n<p>If none of the above helps, then please reply with more information, such as the exception you are getting when you try and read the file.</p>\n"
},
{
"answer_id": 65207,
"author": "Matt Haughton",
"author_id": 6106,
"author_profile": "https://Stackoverflow.com/users/6106",
"pm_score": 0,
"selected": false,
"text": "<p>Since getting this to work requires me to only change the encoding attribute of the first XML element to have the value UTF-8 instead of UTF-16, the XML file is actually UTF-8 and labelled wrongly by the application that generates it.</p>\n\n<p>The XML file is a FileMaker DDR export produced by FileMaker Pro Advanced 8.5 on OS X 10.5.4</p>\n"
},
{
"answer_id": 262462,
"author": "Dema",
"author_id": 407003,
"author_profile": "https://Stackoverflow.com/users/407003",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried doing this using JRuby? I've heard Unicode strings are better supported in JRuby.</p>\n\n<p>One other thing you can try is to use another XML parsing library, such as libxml ou Hpricot. </p>\n\n<p>REXML is one of the slowest Ruby XML libraries you can use and might not scale.</p>\n"
},
{
"answer_id": 291489,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I think your problem may be related to the problem I just detailed in <a href=\"https://stackoverflow.com/questions/291455/xml-data-at-root-level-is-invalid\">this post</a>. If I were you, I'd open it up in TextPad in Binary mode and see if there are any Byte Order Marks before your XML starts.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6106/"
]
| I'm trying to import an XML file via a web page in a Ruby on Rails application, the code ruby view code is as follows (I've removed HTML layout tags to make reading the code easier)
```
<% form_for( :fmfile, :url => '/fmfiles', :html => { :method => :post, :name => 'Form_Import_DDR', :enctype => 'multipart/form-data' } ) do |f| %>
<%= f.file_field :document, :accept => 'text/xml', :name => 'fmfile_document' %>
<%= submit_tag 'Import DDR' %>
<% end %>
```
Results in the following HTML form
```
<form action="/fmfiles" enctype="multipart/form-data" method="post" name="Form_Import_DDR"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="3da97372885564a4587774e7e31aaf77119aec62" />
<input accept="text/xml" id="fmfile_document" name="fmfile_document" size="30" type="file" />
<input name="commit" type="submit" value="Import DDR" />
</form>
```
The Form\_Import\_DDR method in the 'fmfiles\_controller' is the code that does the hard work of reading the XML document in using REXML. The code is as follows
```
@fmfile = Fmfile.new
@fmfile.user_id = current_user.id
@fmfile.file_group_id = 1
@fmfile.name = params[:fmfile_document].original_filename
respond_to do |format|
if @fmfile.save
require 'rexml/document'
doc = REXML::Document.new(params[:fmfile_document].read)
doc.root.elements['File'].elements['BaseTableCatalog'].each_element('BaseTable') do |n|
@base_table = BaseTable.new
@base_table.base_table_create(@fmfile.user_id, @fmfile.id, n)
end
```
And it carries on reading all the different XML elements in.
I'm using Rails 2.1.0 and Mongrel 1.1.5 in Development environment on Mac OS X 10.5.4, site DB and browser on same machine.
My question is this. This whole process works fine when reading an XML document with character encoding UTF-8 but fails when the XML file is UTF-16, does anyone know why this is happening and how it can be stopped?
I have included the error output from the debugger console below, it takes about 5 minutes to get this output and the browser times out before the following output with the 'Failed to open page'
```
Processing FmfilesController#create (for 127.0.0.1 at 2008-09-15 16:50:56) [POST]
Session ID: BAh7CDoMdXNlcl9pZGkGOgxjc3JmX2lkIiVmM2I3YWU2YWI4ODU2NjI0NDM2
NTFmMDE1OGY1OWQxNSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxh
c2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--dd9f588a68ed628ab398dd1a967eedcd09e505e0
Parameters: {"commit"=>"Import DDR", "authenticity_token"=>"3da97372885564a4587774e7e31aaf77119aec62", "action"=>"create", "fmfile_document"=>#<File:/var/folders/LU/LU50A0vNHA07S4rxDAOk4E+++TI/-Tmp-/CGI.3001.1>, "controller"=>"fmfiles"}
[4;36;1mUser Load (0.000350)[0m [0;1mSELECT * FROM "users" WHERE (id = 1) LIMIT 1[0m
[4;35;1mFmfile Create (0.000483)[0m [0mINSERT INTO "fmfiles" ("name", "file_group_id", "updated_at", "report_created_at", "report_link", "report_version", "option_on_open_account_name", "user_id", "option_default_custom_menu_set", "option_on_close_script", "path", "report_type", "option_on_open_layout", "option_on_open_script", "created_at") VALUES('TheTest_fp7 2.xml', 1, '2008-09-15 15:50:56', NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, '2008-09-15 15:50:56')[0m
REXML::ParseException (#<Iconv::InvalidCharacter: "਼䙍偒数 (followed by a few thousand similar looking chinese characters)
䙍偒数潲琾", ["\n"]>
/Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `conv'
/Library/Ruby/Site/1.8/rexml/encodings/ICONV.rb:7:in `decode'
/Library/Ruby/Site/1.8/rexml/source.rb:50:in `encoding='
/Library/Ruby/Site/1.8/rexml/parsers/baseparser.rb:210:in `pull'
/Library/Ruby/Site/1.8/rexml/parsers/treeparser.rb:21:in `parse'
/Library/Ruby/Site/1.8/rexml/document.rb:190:in `build'
/Library/Ruby/Site/1.8/rexml/document.rb:45:in `initialize'
``` | Rather than a rails/mongrel problem, it sounds more likely that there's an issue either with your XML file or with the way REXML handles it. You can check this by writing a short script to read your XML file directly (rather than within a request) and seeing if it still fails.
Assuming it does, there are a couple of things I'd look at. First, I'd check you are running the latest version of REXML. A couple of years ago there was a bug (<http://www.germane-software.com/projects/rexml/ticket/63>) in its UTF-16 handling.
The second thing I'd check is if you're issue is similar to this: <http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/ba7b0585c7a6330d>. If so you can try the workaround in that thread.
If none of the above helps, then please reply with more information, such as the exception you are getting when you try and read the file. |
63,671 | <p>I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it. Is it bad? Are there unintended consequences of doing so?</p>
<pre><code>public interface Foo { Bar GetBar(); }
public struct Fubar : Foo { public Bar GetBar() { return new Bar(); } }
</code></pre>
| [
{
"answer_id": 63709,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": -1,
"selected": false,
"text": "<p>Structs are just like classes that live in the stack. I see no reason why they should be \"unsafe\".</p>\n"
},
{
"answer_id": 63711,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>There are no consequences to a struct implementing an interface. For example the built-in system structs implement interfaces like <code>IComparable</code> and <code>IFormattable</code>.</p>\n"
},
{
"answer_id": 63712,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>There is very little reason for a value type to implement an interface. Since you cannot subclass a value type, you can always refer to it as its concrete type.</p>\n\n<p>Unless of course, you have multiple structs all implementing the same interface, it might be marginally useful then, but at that point I'd recommend using a class and doing it right.</p>\n\n<p>Of course, by implementing an interface, you are boxing the struct, so it now sits on the heap, and you won't be able to pass it by value anymore...This really reinforces my opinion that you should just use a class in this situation.</p>\n"
},
{
"answer_id": 63716,
"author": "Simon Keep",
"author_id": 1127460,
"author_profile": "https://Stackoverflow.com/users/1127460",
"pm_score": 1,
"selected": false,
"text": "<p>I think the problem is that it causes boxing because structs are value types so there is a slight performance penalty.</p>\n\n<p>This link suggests there might be other issues with it...</p>\n\n<p><a href=\"http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/abhinaba/archive/2005/10/05/477238.aspx</a></p>\n"
},
{
"answer_id": 63732,
"author": "dotnetengineer",
"author_id": 8033,
"author_profile": "https://Stackoverflow.com/users/8033",
"pm_score": 2,
"selected": false,
"text": "<p>Structs are implemented as value types and classes are reference types. If you have a variable of type Foo, and you store an instance of Fubar in it, it will \"Box it\" up into a reference type, thus defeating the advantage of using a struct in the first place.</p>\n\n<p>The only reason I see to use a struct instead of a class is because it will be a value type and not a reference type, but the struct can't inherit from a class. If you have the struct inherit an interface, and you pass around interfaces, you lose that value type nature of the struct. Might as well just make it a class if you need interfaces.</p>\n"
},
{
"answer_id": 63757,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 7,
"selected": true,
"text": "<p>There are several things going on in this question...</p>\n\n<p>It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: <a href=\"https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface</a></p>\n\n<p>In general, structs should be used for objects that have value-type semantics. By implementing an interface on a struct you can run into boxing concerns as the struct is cast back and forth between the struct and the interface. As a result of the boxing, operations that change the internal state of the struct may not behave properly.</p>\n"
},
{
"answer_id": 63817,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>(Well got nothing major to add but don't have editing prowess yet so here goes..)<br>\n<strong>Perfectly Safe. Nothing illegal with implementing interfaces on structs. However you should question why you'd want to do it.</strong> </p>\n\n<p>However <strong>obtaining an interface reference to a struct will BOX</strong> it. So performance penalty and so on. </p>\n\n<p>The only valid scenario which I can think of right now is <a href=\"https://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs#51585\">illustrated in my post here</a>. When you want to modify a struct's state stored in a collection, you'd have to do it via an additional interface exposed on the struct.</p>\n"
},
{
"answer_id": 1289537,
"author": "ShuggyCoUk",
"author_id": 12748,
"author_profile": "https://Stackoverflow.com/users/12748",
"pm_score": 8,
"selected": false,
"text": "<p>Since no one else explicitly provided this answer I will add the following:</p>\n\n<p><strong>Implementing</strong> an interface on a struct has no negative consequences whatsoever.</p>\n\n<p>Any <em>variable</em> of the interface type used to hold a struct will result in a boxed value of that struct being used. If the struct is immutable (a good thing) then this is at worst a performance issue unless you are:</p>\n\n<ul>\n<li>using the resulting object for locking purposes (an immensely bad idea any way)</li>\n<li>using reference equality semantics and expecting it to work for two boxed values from the same struct.</li>\n</ul>\n\n<p>Both of these would be unlikely, instead you are likely to be doing one of the following:</p>\n\n<h3>Generics</h3>\n\n<p>Perhaps many reasonable reasons for structs implementing interfaces is so that they can be used within a <strong>generic</strong> context with <em><a href=\"http://msdn.microsoft.com/en-us/library/d5x73970.aspx\" rel=\"noreferrer\">constraints</a></em>. When used in this fashion the variable like so:</p>\n\n<pre><code>class Foo<T> : IEquatable<Foo<T>> where T : IEquatable<T>\n{\n private readonly T a;\n\n public bool Equals(Foo<T> other)\n {\n return this.a.Equals(other.a);\n }\n}\n</code></pre>\n\n<ol>\n<li>Enable the use of the struct as a type parameter \n\n<ul>\n<li>so long as no other constraint like <code>new()</code> or <code>class</code> is used.</li>\n</ul></li>\n<li>Allow the avoidance of boxing on structs used in this way.</li>\n</ol>\n\n<p>Then this.a is NOT an interface reference thus it does not cause a box of whatever is placed into it. Further when the c# compiler compiles the generic classes and needs to insert invocations of the instance methods defined on instances of the Type parameter T it can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.constrained.aspx\" rel=\"noreferrer\">constrained</a> opcode:</p>\n\n<blockquote>\n <p>If thisType is a value type and thisType implements method then ptr is passed unmodified as the 'this' pointer to a call method instruction, for the implementation of method by thisType.</p>\n</blockquote>\n\n<p>This avoids the boxing and since the value type is implementing the interface is <em>must</em> implement the method, thus no boxing will occur. In the above example the <code>Equals()</code> invocation is done with no box on this.a<sup>1</sup>.</p>\n\n<h3>Low friction APIs</h3>\n\n<p>Most structs should have primitive-like semantics where bitwise identical values are considered equal<sup>2</sup>. The runtime will supply such behaviour in the implicit <code>Equals()</code> but this can be slow. Also this implicit equality is <em>not</em> exposed as an implementation of <code>IEquatable<T></code> and thus prevents structs being used easily as keys for Dictionaries unless they explicitly implement it themselves. It is therefore common for many public struct types to declare that they implement <code>IEquatable<T></code> (where <code>T</code> is them self) to make this easier and better performing as well as consistent with the behaviour of many existing value types within the CLR BCL.</p>\n\n<p>All the primitives in the BCL implement at a minimum: </p>\n\n<ul>\n<li><code>IComparable</code></li>\n<li><code>IConvertible</code></li>\n<li><code>IComparable<T></code></li>\n<li><code>IEquatable<T></code> (And thus <code>IEquatable</code>)</li>\n</ul>\n\n<p>Many also implement <code>IFormattable</code>, further many of the System defined value types like DateTime, TimeSpan and Guid implement many or all of these as well. If you are implementing a similarly 'widely useful' type like a complex number struct or some fixed width textual values then implementing many of these common interfaces (correctly) will make your struct more useful and usable.</p>\n\n<h2>Exclusions</h2>\n\n<p>Obviously if the interface strongly implies <em>mutability</em> (such as <code>ICollection</code>) then implementing it is a bad idea as it would mean tat you either made the struct mutable (leading to the sorts of errors described already where the modifications occur on the boxed value rather than the original) or you confuse users by ignoring the implications of the methods like <code>Add()</code> or throwing exceptions.</p>\n\n<p>Many interfaces do NOT imply mutability (such as <code>IFormattable</code>) and serve as the idiomatic way to expose certain functionality in a consistent fashion. Often the user of the struct will not care about any boxing overhead for such behaviour.</p>\n\n<h2>Summary</h2>\n\n<p>When done sensibly, on immutable value types, implementation of useful interfaces is a good idea</p>\n\n<hr>\n\n<h3>Notes:</h3>\n\n<p>1: Note that the compiler may use this when invoking virtual methods on variables which are <em>known</em> to be of a specific struct type but in which it is required to invoke a virtual method. For example:</p>\n\n<pre><code>List<int> l = new List<int>();\nforeach(var x in l)\n ;//no-op\n</code></pre>\n\n<p>The enumerator returned by the List is a struct, an optimization to avoid an allocation when enumerating the list (With some interesting <a href=\"http://www.eggheadcafe.com/software/aspnet/31702392/c-compiler-challenge--s.aspx\" rel=\"noreferrer\">consequences</a>). However the semantics of foreach specify that if the enumerator implements <code>IDisposable</code> then <code>Dispose()</code> will be called once the iteration is completed. Obviously having this occur through a boxed call would eliminate any benefit of the enumerator being a struct (in fact it would be worse). Worse, if dispose call modifies the state of the enumerator in some way then this would happen on the boxed instance and many subtle bugs might be introduced in complex cases. Therefore the IL emitted in this sort of situation is:</p>\n\n<pre>\nIL_0001: newobj System.Collections.Generic.List..ctor\nIL_0006: stloc.0 \nIL_0007: nop \nIL_0008: ldloc.0 \nIL_0009: callvirt System.Collections.Generic.List.GetEnumerator\nIL_000E: stloc.2 \nIL_000F: br.s IL_0019\nIL_0011: ldloca.s 02 \nIL_0013: call System.Collections.Generic.List.get_Current\nIL_0018: stloc.1 \nIL_0019: ldloca.s 02 \nIL_001B: call System.Collections.Generic.List.MoveNext\nIL_0020: stloc.3 \nIL_0021: ldloc.3 \nIL_0022: brtrue.s IL_0011\nIL_0024: leave.s IL_0035\nIL_0026: ldloca.s 02 \nIL_0028: constrained. System.Collections.Generic.List.Enumerator\nIL_002E: callvirt System.IDisposable.Dispose\nIL_0033: nop \nIL_0034: endfinally \n</pre>\n\n<p>Thus the implementation of IDisposable does not cause any performance issues and the (regrettable) mutable aspect of the enumerator is preserved should the Dispose method actually do anything! </p>\n\n<p>2: double and float are exceptions to this rule where NaN values are not considered equal.</p>\n"
},
{
"answer_id": 14322574,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "<p>In some cases it may be good for a struct to implement an interface (if it was never useful, it's doubtful the creators of .net would have provided for it). If a struct implements a read-only interface like <code>IEquatable<T></code>, storing the struct in a storage location (variable, parameter, array element, etc.) of type <code>IEquatable<T></code> will require that it be boxed (each struct type actually defines two kinds of things: a storage location type which behaves as a value type and a heap-object type which behaves as a class type; the first is implicitly convertible to the second--\"boxing\"--and the second may be converted to the first via explicit cast--\"unboxing\"). It is possible to exploit a structure's implementation of an interface without boxing, however, using what are called constrained generics.</p>\n\n<p>For example, if one had a method <code>CompareTwoThings<T>(T thing1, T thing2) where T:IComparable<T></code>, such a method could call <code>thing1.Compare(thing2)</code> without having to box <code>thing1</code> or <code>thing2</code>. If <code>thing1</code> happens to be, e.g., an <code>Int32</code>, the run-time will know that when it generates the code for <code>CompareTwoThings<Int32>(Int32 thing1, Int32 thing2)</code>. Since it will know the exact type of both the thing hosting the method and the thing that's being passed as a parameter, it won't have to box either of them.</p>\n\n<p>The biggest problem with structs that implement interfaces is that a struct which gets stored in a location of interface type, <code>Object</code>, or <code>ValueType</code> (as opposed to a location of its own type) will behave as a class object. For read-only interfaces this is not generally a problem, but for a mutating interface like <code>IEnumerator<T></code> it can yield some strange semantics.</p>\n\n<p>Consider, for example, the following code:</p>\n\n<pre><code>List<String> myList = [list containing a bunch of strings]\nvar enumerator1 = myList.GetEnumerator(); // Struct of type List<String>.IEnumerator\nenumerator1.MoveNext(); // 1\nvar enumerator2 = enumerator1;\nenumerator2.MoveNext(); // 2\nIEnumerator<string> enumerator3 = enumerator2;\nenumerator3.MoveNext(); // 3\nIEnumerator<string> enumerator4 = enumerator3;\nenumerator4.MoveNext(); // 4\n</code></pre>\n\n<p>Marked statement #1 will prime <code>enumerator1</code> to read the first element. The state of that enumerator will be copied to <code>enumerator2</code>. Marked statement #2 will advance that copy to read the second element, but will not affect <code>enumerator1</code>. The state of that second enumerator will then be copied to <code>enumerator3</code>, which will be advanced by marked statement #3. Then, because <code>enumerator3</code> and <code>enumerator4</code> are both reference types, a <em>REFERENCE</em> to <code>enumerator3</code> will then be copied to <code>enumerator4</code>, so marked statement will effectively advance <em>both</em> <code>enumerator3</code> and <code>enumerator4</code>.</p>\n\n<p>Some people try to pretend that value types and reference types are both kinds of <code>Object</code>, but that's not really true. Real value types are convertible to <code>Object</code>, but are not instances of it. An instance of <code>List<String>.Enumerator</code> which is stored in a location of that type is a value-type and behaves as a value type; copying it to a location of type <code>IEnumerator<String></code> will convert it to a reference type, and <em>it will behave as a reference type</em>. The latter is a kind of <code>Object</code>, but the former is not.</p>\n\n<p>BTW, a couple more notes: (1) In general, mutable class types should have their <code>Equals</code> methods test reference equality, but there is no decent way for a boxed struct to do so; (2) despite its name, <code>ValueType</code> is a class type, not a value type; all types derived from <code>System.Enum</code> are value types, as are all types which derive from <code>ValueType</code> with the exception of <code>System.Enum</code>, but both <code>ValueType</code> and <code>System.Enum</code> are class types.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it. Is it bad? Are there unintended consequences of doing so?
```
public interface Foo { Bar GetBar(); }
public struct Fubar : Foo { public Bar GetBar() { return new Bar(); } }
``` | There are several things going on in this question...
It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: <https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface>
In general, structs should be used for objects that have value-type semantics. By implementing an interface on a struct you can run into boxing concerns as the struct is cast back and forth between the struct and the interface. As a result of the boxing, operations that change the internal state of the struct may not behave properly. |
63,687 | <p>I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?</p>
<p>I am using Java 1.5.</p>
| [
{
"answer_id": 63701,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 6,
"selected": true,
"text": "<p>You can add a shutdown hook to your application by doing the following:</p>\n\n<pre><code>Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {\n public void run() {\n // what you want to do\n }\n}));\n</code></pre>\n\n<p>This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.</p>\n\n<p>Please note the <a href=\"https://stackoverflow.com/questions/63687/calling-function-when-program-exits-in-java#63886\">caveats</a> though!</p>\n"
},
{
"answer_id": 63886,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 4,
"selected": false,
"text": "<p>Adding a shutdown hook <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)\" rel=\"noreferrer\">addShutdownHook(java.lang.Thread)</a> is probably what you look for. There are problems with that approach, though:</p>\n\n<ul>\n<li>you will lose the changes if the program aborts in an uncontrolled way (i.e. if it is killed)</li>\n<li>you will lose the changes if there are errors (permission denied, disk full, network errors)</li>\n</ul>\n\n<p>So it might be better to save settings immediately (possibly in an extra thread, to avoid waiting times).</p>\n"
},
{
"answer_id": 64773,
"author": "Avrom",
"author_id": 8840,
"author_profile": "https://Stackoverflow.com/users/8840",
"pm_score": 0,
"selected": false,
"text": "<p>Are you creating a stand alone GUI app (i.e. Swing)?</p>\n\n<p>If so, you should consider how you are providing options to your users how to exit the application.\nNamely, if there is going to be a File menu, I would expect that there will be an \"Exit\" menu item.\nAlso, if the user closes the last window in the app, I would also expect it to exit the application.\nIn both cases, it should call code that handles saving the user's preferences.</p>\n"
},
{
"answer_id": 69288,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 0,
"selected": false,
"text": "<p>Using Runtime.getRuntime().addShutdownHook() is certainly a way to do this - but if you are writing Swing applications, I strongly recommend that you take a look at JSR 296 (Swing Application Framework)</p>\n\n<p>Here's a good article on the basics: <a href=\"http://java.sun.com/developer/technicalArticles/javase/swingappfr/\" rel=\"nofollow noreferrer\">http://java.sun.com/developer/technicalArticles/javase/swingappfr/</a>.</p>\n\n<p>The JSR reference implementation provides the kind of features that you are looking for at a higher level of abstraction than adding shutdown hooks.</p>\n\n<p>Here is the reference implementation: <a href=\"https://appframework.dev.java.net/\" rel=\"nofollow noreferrer\">https://appframework.dev.java.net/</a></p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?
I am using Java 1.5. | You can add a shutdown hook to your application by doing the following:
```
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// what you want to do
}
}));
```
This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.
Please note the [caveats](https://stackoverflow.com/questions/63687/calling-function-when-program-exits-in-java#63886) though! |
63,694 | <p>Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?</p>
<p>In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write <code>Fraction<int> frac = new Fraction<int>(1,2)</code> and/or <code>Fraction<double> frac = new Fraction<double>(0.1, 1.0)</code>.</p>
<p>Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?</p>
| [
{
"answer_id": 63858,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>First, your class should limit the generic parameter to primitives ( public class Fraction where T : struct, new() ).</p>\n\n<p>Second, you'll probably need to create <a href=\"http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx\" rel=\"nofollow noreferrer\">implicit cast overloads</a> so you can handle casting from one type to another without the compiler crying. </p>\n\n<p>Third, you can overload the four basic operators as well to make the interface more flexible when combining fractions of different types.</p>\n\n<p>Lastly, you have to consider how you are handling arithmetic over and underflows. A good library is going to be extremely explicit in how it handles overflows; otherwise you cannot trust the outcome of operations of different fraction types.</p>\n"
},
{
"answer_id": 63889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I believe this answers your question:</p>\n<p><a href=\"http://www.codeproject.com/KB/cs/genericnumerics.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/genericnumerics.aspx</a></p>\n"
},
{
"answer_id": 64142,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 6,
"selected": true,
"text": "<p>Here is a way to abstract out the operators that is relatively painless.</p>\n\n<pre><code> abstract class MathProvider<T>\n {\n public abstract T Divide(T a, T b);\n public abstract T Multiply(T a, T b);\n public abstract T Add(T a, T b);\n public abstract T Negate(T a);\n public virtual T Subtract(T a, T b)\n {\n return Add(a, Negate(b));\n }\n }\n\n class DoubleMathProvider : MathProvider<double>\n {\n public override double Divide(double a, double b)\n {\n return a / b;\n }\n\n public override double Multiply(double a, double b)\n {\n return a * b;\n }\n\n public override double Add(double a, double b)\n {\n return a + b;\n }\n\n public override double Negate(double a)\n {\n return -a;\n }\n }\n\n class IntMathProvider : MathProvider<int>\n {\n public override int Divide(int a, int b)\n {\n return a / b;\n }\n\n public override int Multiply(int a, int b)\n {\n return a * b;\n }\n\n public override int Add(int a, int b)\n {\n return a + b;\n }\n\n public override int Negate(int a)\n {\n return -a;\n }\n }\n\n class Fraction<T>\n {\n static MathProvider<T> _math;\n // Notice this is a type constructor. It gets run the first time a\n // variable of a specific type is declared for use.\n // Having _math static reduces overhead.\n static Fraction()\n {\n // This part of the code might be cleaner by once\n // using reflection and finding all the implementors of\n // MathProvider and assigning the instance by the one that\n // matches T.\n if (typeof(T) == typeof(double))\n _math = new DoubleMathProvider() as MathProvider<T>;\n else if (typeof(T) == typeof(int))\n _math = new IntMathProvider() as MathProvider<T>;\n // ... assign other options here.\n\n if (_math == null)\n throw new InvalidOperationException(\n \"Type \" + typeof(T).ToString() + \" is not supported by Fraction.\");\n }\n\n // Immutable impementations are better.\n public T Numerator { get; private set; }\n public T Denominator { get; private set; }\n\n public Fraction(T numerator, T denominator)\n {\n // We would want this to be reduced to simpilest terms.\n // For that we would need GCD, abs, and remainder operations\n // defined for each math provider.\n Numerator = numerator;\n Denominator = denominator;\n }\n\n public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b)\n {\n return new Fraction<T>(\n _math.Add(\n _math.Multiply(a.Numerator, b.Denominator),\n _math.Multiply(b.Numerator, a.Denominator)),\n _math.Multiply(a.Denominator, b.Denominator));\n }\n\n public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b)\n {\n return new Fraction<T>(\n _math.Subtract(\n _math.Multiply(a.Numerator, b.Denominator),\n _math.Multiply(b.Numerator, a.Denominator)),\n _math.Multiply(a.Denominator, b.Denominator));\n }\n\n public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b)\n {\n return new Fraction<T>(\n _math.Multiply(a.Numerator, b.Denominator),\n _math.Multiply(a.Denominator, b.Numerator));\n }\n\n // ... other operators would follow.\n }\n</code></pre>\n\n<p>If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the <code>MathProvider<T></code> implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.</p>\n\n<p><strong>Edit:</strong> Fixed definitions of add and subtract for <code>Fraction<T></code>.\nAnother interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: <a href=\"http://conal.net/papers/beautiful-differentiation/\" rel=\"noreferrer\">http://conal.net/papers/beautiful-differentiation/</a></p>\n"
},
{
"answer_id": 4399400,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a subtle problem that comes with generic types. Suppose an algorithm involves division, say Gaussian elimination to solve a system of equations. If you pass in integers, you'll get a wrong answer because you'll carry out <em>integer</em> division. But if you pass in double arguments that happen have integer values, you'll get the right answer. </p>\n\n<p>The same thing happens with square roots, as in Cholesky factorization. Factoring an integer matrix will go wrong, whereas factoring a matrix of doubles that happen to have integer values will be fine.</p>\n"
},
{
"answer_id": 65107700,
"author": "Mike Marynowski",
"author_id": 612510,
"author_profile": "https://Stackoverflow.com/users/612510",
"pm_score": 1,
"selected": false,
"text": "<p>The other approaches here will work, but they have a high performance impact over raw operators. I figured I would post this here for someone who needs the fastest, not the prettiest approach.</p>\n<p>If you want to do generic math without paying a performance penalty, then this is, unfortunately, the way to do it:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[MethodImpl(MethodImplOptions.AggressiveInlining)]\npublic static T IncrementToMax(T value)\n{\n if (typeof(T) == typeof(char))\n return (char)(object)value! < char.MaxValue ? (T)(object)(char)((char)(object)value + 1) : value;\n \n if (typeof(T) == typeof(byte))\n return (byte)(object)value! < byte.MaxValue ? (T)(object)(byte)((byte)(object)value + 1) : value;\n\n // ...rest of the types\n}\n</code></pre>\n<p>It looks horrific, I know, but using this method will produce code that runs as fast as possible. The JIT will optimize out all the casts and conditional branches.</p>\n<p>You can read the explanation and some additional important details here: <a href=\"http://www.singulink.com/codeindex/post/generic-math-at-raw-operator-speed\" rel=\"nofollow noreferrer\">http://www.singulink.com/codeindex/post/generic-math-at-raw-operator-speed</a></p>\n"
},
{
"answer_id": 74468046,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 0,
"selected": false,
"text": "<p>.NET 7 introduces a new feature - generic math (read more <a href=\"https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11#generic-math-support\" rel=\"nofollow noreferrer\">here</a>) which is based on addition of <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members#static-abstract-interface-methods\" rel=\"nofollow noreferrer\"><code>static abstract</code> interface methods</a>. This feature introduces a lot of interfaces which allow to generically abstract over number types and/or math operations:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Fraction<T> :\n IAdditionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,\n ISubtractionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,\n IDivisionOperators<Fraction<T>, Fraction<T>, Fraction<T>>\n where T : INumber<T>\n{\n public T Numerator { get; }\n public T Denominator { get; }\n\n public Fraction(T numerator, T denominator)\n {\n Numerator = numerator;\n Denominator = denominator;\n }\n\n public static Fraction<T> operator +(Fraction<T> left, Fraction<T> right) =>\n new(left.Numerator * right.Denominator + right.Numerator * left.Denominator,\n left.Denominator * right.Denominator);\n\n public static Fraction<T> operator -(Fraction<T> left, Fraction<T> right) =>\n new(left.Numerator * right.Denominator - right.Numerator * left.Denominator,\n left.Denominator * right.Denominator);\n\n public static Fraction<T> operator /(Fraction<T> left, Fraction<T> right) =>\n new(left.Numerator * right.Denominator, left.Denominator * right.Numerator);\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
| Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?
In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write `Fraction<int> frac = new Fraction<int>(1,2)` and/or `Fraction<double> frac = new Fraction<double>(0.1, 1.0)`.
Unfortunately there is no interface representing the four basic operations (+,-,\*,/). Has anybody found a workable, feasible way of implementing this? | Here is a way to abstract out the operators that is relatively painless.
```
abstract class MathProvider<T>
{
public abstract T Divide(T a, T b);
public abstract T Multiply(T a, T b);
public abstract T Add(T a, T b);
public abstract T Negate(T a);
public virtual T Subtract(T a, T b)
{
return Add(a, Negate(b));
}
}
class DoubleMathProvider : MathProvider<double>
{
public override double Divide(double a, double b)
{
return a / b;
}
public override double Multiply(double a, double b)
{
return a * b;
}
public override double Add(double a, double b)
{
return a + b;
}
public override double Negate(double a)
{
return -a;
}
}
class IntMathProvider : MathProvider<int>
{
public override int Divide(int a, int b)
{
return a / b;
}
public override int Multiply(int a, int b)
{
return a * b;
}
public override int Add(int a, int b)
{
return a + b;
}
public override int Negate(int a)
{
return -a;
}
}
class Fraction<T>
{
static MathProvider<T> _math;
// Notice this is a type constructor. It gets run the first time a
// variable of a specific type is declared for use.
// Having _math static reduces overhead.
static Fraction()
{
// This part of the code might be cleaner by once
// using reflection and finding all the implementors of
// MathProvider and assigning the instance by the one that
// matches T.
if (typeof(T) == typeof(double))
_math = new DoubleMathProvider() as MathProvider<T>;
else if (typeof(T) == typeof(int))
_math = new IntMathProvider() as MathProvider<T>;
// ... assign other options here.
if (_math == null)
throw new InvalidOperationException(
"Type " + typeof(T).ToString() + " is not supported by Fraction.");
}
// Immutable impementations are better.
public T Numerator { get; private set; }
public T Denominator { get; private set; }
public Fraction(T numerator, T denominator)
{
// We would want this to be reduced to simpilest terms.
// For that we would need GCD, abs, and remainder operations
// defined for each math provider.
Numerator = numerator;
Denominator = denominator;
}
public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Add(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Subtract(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(a.Denominator, b.Numerator));
}
// ... other operators would follow.
}
```
If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the `MathProvider<T>` implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.
**Edit:** Fixed definitions of add and subtract for `Fraction<T>`.
Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: <http://conal.net/papers/beautiful-differentiation/> |
63,741 | <p>Why does the default IntelliJ default class javadoc comment use non-standard syntax? Instead of creating a line with "User: jstauffer" it could create a line with "@author jstauffer". The other lines that it creates (Date and Time) probably don't have javadoc syntax to use but why not use the javadoc syntax when available?</p>
<p>For reference here is an example:</p>
<pre>/**
* Created by IntelliJ IDEA.
* User: jstauffer
* Date: Nov 13, 2007
* Time: 11:15:10 AM
* To change this template use File | Settings | File Templates.
*/</pre>
| [
{
"answer_id": 63922,
"author": "Rob Dickerson",
"author_id": 7530,
"author_profile": "https://Stackoverflow.com/users/7530",
"pm_score": 6,
"selected": false,
"text": "<p>I'm not sure why Idea doesn't use the <code>@author</code> tag by default. </p>\n\n<p>But you can change this behavior by going to <code>File -> Settings -> File Templates</code> and editing the <code>File Header</code> entry in the <code>Includes</code> tab.</p>\n\n<p>As of IDEA 14 it's: <code>File -> Settings -> Editor -> File and Code Templates -> Includes -> File Header</code></p>\n"
},
{
"answer_id": 165283,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 2,
"selected": false,
"text": "<p>The default is readable, usable, but does not adhere to or suggest any coding standard.</p>\n\n<p>I think the reason IntelliJ doesn't use the Javadoc tags in the default, is so that it avoids possible interference with any coding/javadoc standards that might exist in development shops. It should be obvious to the user if the default needs to be modified to something more appropriate.</p>\n\n<p>Where I am working, the use of author tags is discouraged, for various reasons.</p>\n"
},
{
"answer_id": 879295,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 1,
"selected": false,
"text": "<p>It is likely that the header snippet you show is older than javadoc and was just borrowed from some coding standard document, probably written for C++.</p>\n"
},
{
"answer_id": 879421,
"author": "Trampas Kirk",
"author_id": 72053,
"author_profile": "https://Stackoverflow.com/users/72053",
"pm_score": 2,
"selected": false,
"text": "<p>Because it's a default file template that you're supposed to change to your organization's standard, or your tastes.</p>\n\n<p>My best guess.</p>\n"
},
{
"answer_id": 27890765,
"author": "user1154390",
"author_id": 1154390,
"author_profile": "https://Stackoverflow.com/users/1154390",
"pm_score": 3,
"selected": false,
"text": "<p>In AndroidStuido 1.0.2 on Mac</p>\n\n<p>Go in <strong>Preferences</strong>\nthen on left span <strong>File and Code Templates</strong>\nAfter selecting file and code templates on right hand side select <strong>includes</strong> tab select\n<strong>file Header</strong> and change your file header.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| Why does the default IntelliJ default class javadoc comment use non-standard syntax? Instead of creating a line with "User: jstauffer" it could create a line with "@author jstauffer". The other lines that it creates (Date and Time) probably don't have javadoc syntax to use but why not use the javadoc syntax when available?
For reference here is an example:
```
/**
* Created by IntelliJ IDEA.
* User: jstauffer
* Date: Nov 13, 2007
* Time: 11:15:10 AM
* To change this template use File | Settings | File Templates.
*/
``` | I'm not sure why Idea doesn't use the `@author` tag by default.
But you can change this behavior by going to `File -> Settings -> File Templates` and editing the `File Header` entry in the `Includes` tab.
As of IDEA 14 it's: `File -> Settings -> Editor -> File and Code Templates -> Includes -> File Header` |
63,743 | <p>I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like</p>
<pre><code>container.innerHTML = content;
</code></pre>
<p>Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content occupied more vertical space then a new one would occupy AND a user scrolled the page down -- scrolled more than new content would allow, provided its height.</p>
<p>In this case the page redraws incorrectly -- some artifacts of the old content remain. It works fine, and it is even possible to get rid of artifacts, by minimizing and restoring the browser (or force the window to be redrawn in an other way), however this does not seem very convenient.</p>
<p>I am testing this only under Safari (this is a iPhone-optimized website).</p>
<p>Does anybody have the idea how to deal with this?</p>
| [
{
"answer_id": 63811,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you are having a problem with the browser itself. Does this problem only occur in one browser?</p>\n\n<p>One thing you might try is using a lightweight library like <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. It handles browser differences fairly nicely. To set the inner HTML for a div with the ID of <strong>container</strong> you would simply write this:</p>\n\n<pre><code>$('#container').html( content );\n</code></pre>\n\n<p>That will work in most browsers. I do not know if it will fix your problem specifically or not but it may be worth a try.</p>\n"
},
{
"answer_id": 64219,
"author": "Twan",
"author_id": 6702,
"author_profile": "https://Stackoverflow.com/users/6702",
"pm_score": 0,
"selected": false,
"text": "<p>Would it work to set the scroll position back to the top (element.scrollTop = 0; element.scrollLeft = 0; by heart) before replacing the content?</p>\n"
},
{
"answer_id": 64596,
"author": "jpbarto",
"author_id": 8511,
"author_profile": "https://Stackoverflow.com/users/8511",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like the webkit rendering engine of Safari is not at first recognizing the content change, at least not fully enough to remove the previous html content. Minimizing and then restoring the windows initiates a redraw event in the browser's rendering engine. </p>\n\n<p>I think I would explore 2 avenues: first could I use an iframe instead of the current 'content' node? Browsers expect IFrames to change, however as you're seeing they're not always so good at changing content of DIV or other elements.</p>\n\n<p>Secondly, perhaps by modifying the scroll position as suggested earlier. You could simply move the scroll back to 0 as suggested or if that is to obtrusive you could try to restore the scroll after the content change. Subtract the height of the old content node from the current scroll position (reseting the browser's scroll to the content node's 0), change the node content, then add the new node's height to the scroll position.</p>\n\n<p>Palehorse is right though (I can't vote his answer up at the moment - no points) an abstraction library like jQuery, Dojo, or even Prototype can often help with these matters. Especially if you see your page / site moving beyond simple DOM manipulation you'll find the tools and enhancements provided by libraries to be a huge help.</p>\n"
},
{
"answer_id": 64736,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "<p>Set the element's CSS height to 'auto' every time you update innerHTML.</p>\n"
},
{
"answer_id": 64740,
"author": "Vitaly Sharovatov",
"author_id": 6647,
"author_profile": "https://Stackoverflow.com/users/6647",
"pm_score": 0,
"selected": false,
"text": "<p>I would try doing container.innerHTML = ''; container.innerHTML = content; </p>\n"
},
{
"answer_id": 65912,
"author": "Scott Swezey",
"author_id": 9439,
"author_profile": "https://Stackoverflow.com/users/9439",
"pm_score": 3,
"selected": true,
"text": "<p>The easiest solution that I have found would be to place an anchor tag <code><a></code> at the top of the <code>div</code> you are editing:</p>\n\n<pre><code><a name=\"ajax-div\"></a>\n</code></pre>\n\n<p>Then when you change the content of the <code>div</code>, you can do this to have the browser jump to your anchor tag:</p>\n\n<pre><code>location.hash = 'ajax-div';\n</code></pre>\n\n<p>Use this to make sure the user isn't scrolled down too far when you update the content and you shouldn't get the issue in the first place.</p>\n\n<p>(tested in the latest FF beta and latest safari)</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
]
| I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like
```
container.innerHTML = content;
```
Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content occupied more vertical space then a new one would occupy AND a user scrolled the page down -- scrolled more than new content would allow, provided its height.
In this case the page redraws incorrectly -- some artifacts of the old content remain. It works fine, and it is even possible to get rid of artifacts, by minimizing and restoring the browser (or force the window to be redrawn in an other way), however this does not seem very convenient.
I am testing this only under Safari (this is a iPhone-optimized website).
Does anybody have the idea how to deal with this? | The easiest solution that I have found would be to place an anchor tag `<a>` at the top of the `div` you are editing:
```
<a name="ajax-div"></a>
```
Then when you change the content of the `div`, you can do this to have the browser jump to your anchor tag:
```
location.hash = 'ajax-div';
```
Use this to make sure the user isn't scrolled down too far when you update the content and you shouldn't get the issue in the first place.
(tested in the latest FF beta and latest safari) |
63,748 | <p>I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this:
</p>
<pre><code>Graph g = new Graph();
Node n1 = new Node("#1");
Node n2 = new Node("#2");
Edge e1 = new Edge("e#1", "#1", "#2");
// Each node is added like a reference
g.addNode(n1);
g.addNode(n2);
g.addEdge(e1);
// This will break the internal integrity of the graph
n1.setName("#3");
g.getNode("#2").setName("#4");
</code></pre>
<p></p>
<p>I believe I should clone the nodes and the edges when adding them to the graph and return a NodeEnvelope class that will maintain the graph structural integrity. Is this the right way of doing this or the design is broken from the beginning ?</p>
| [
{
"answer_id": 63795,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion you should never clone the element unless you explicitly state that your data structure does that.</p>\n\n<p>The desired functionality of most things needs the actual object to be passed into the data structure by-reference.</p>\n\n<p>If you want to make the <code>Node</code> class safer, make it an inner class of the graph.</p>\n"
},
{
"answer_id": 63846,
"author": "Jim Kiley",
"author_id": 7178,
"author_profile": "https://Stackoverflow.com/users/7178",
"pm_score": 2,
"selected": false,
"text": "<p>It isn't clear to me why you are adding the additional indirection of the String names for the nodes. Wouldn't it make more sense for your Edge constructor's signature to be something like <code>public Edge(String, Node, Node)</code> instead of <code>public Edge (String, String, String)</code>?</p>\n\n<p>I don't know where clone would help you here.</p>\n\n<p>ETA: If the danger comes from having the node name changed after the node is created, throw an <code>IllegalOperationException</code> if the client tries to call setName() on a node with an existing name.</p>\n"
},
{
"answer_id": 64598,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the comments by @jhkiley.blogspot.com, you can create a factory for Edges and Nodes that refuses to create objects with a name that was already used.</p>\n"
},
{
"answer_id": 64847,
"author": "Rob Dickerson",
"author_id": 7530,
"author_profile": "https://Stackoverflow.com/users/7530",
"pm_score": 3,
"selected": true,
"text": "<p>I work with graph structures in Java a lot, and my advice would be to make any data member of the Node and Edge class that the Graph depends on for maintaining its structure final, with no setters. In fact, if you can, I would make Node and Edge completely immutable, which has <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=29\" rel=\"nofollow noreferrer\">many benefits</a>.</p>\n\n<p>So, for example:</p>\n\n<pre><code>public final class Node {\n\n private final String name;\n\n public Node(String name) {\n this.name = name;\n }\n\n public String getName() { return name; }\n // note: no setter for name\n}\n</code></pre>\n\n<p>You would then do your uniqueness check in the Graph object:</p>\n\n<pre><code>public class Graph {\n Set<Node> nodes = new HashSet<Node>();\n public void addNode(Node n) {\n // note: this assumes you've properly overridden \n // equals and hashCode in Node to make Nodes with the \n // same name .equal() and hash to the same value.\n if(nodes.contains(n)) {\n throw new IllegalArgumentException(\"Already in graph: \" + node);\n }\n nodes.add(n);\n }\n}\n</code></pre>\n\n<p>If you need to modify a name of a node, remove the old node and add a new one. This might sound like extra work, but it saves a lot of effort keeping everything straight.</p>\n\n<p>Really, though, creating your own Graph structure from the ground up is probably unnecessary -- this issue is only the first of many you are likely to run into if you build your own.</p>\n\n<p>I would recommend finding a good open source Java graph library, and using that instead. Depending on what you are doing, there are a few options out there. I have used <a href=\"http://jung.sourceforge.net/\" rel=\"nofollow noreferrer\">JUNG</a> in the past, and would recommend it as a good starting point.</p>\n"
},
{
"answer_id": 65104,
"author": "chrisk",
"author_id": 8814,
"author_profile": "https://Stackoverflow.com/users/8814",
"pm_score": 1,
"selected": false,
"text": "<p>Using NodeEnvelopes or edge/node Factories sounds like overdesign to me.</p>\n\n<p>Do you really want to expose a setName() method on Node at all? There's nothing in your example to suggest that you need that. If you make both your Node and Edge classes immutable, most of the integrity-violation scenarios you're envisioning become impossible. (If you need them to be mutable but only until they're added to a Graph, you could enforce this by having an isInGraph flag on your Node/Edge classes that is set to true by Graph.Add{Node, Edge}, and have your mutators throw an exception if called after this flag is set.)</p>\n\n<p>I agree with jhkiley that passing Node objects to the Edge constructor (instead of Strings) sounds like a good idea.</p>\n\n<p>If you want a more intrusive approach, you could have a pointer from the Node class back to the Graph it resides in, and update the Graph if any critical properties (e.g., the name) of the Node ever change. But I wouldn't do that unless you're sure you need to be able to change the names of existing Nodes while preserving Edge relationships, which seems unlikely.</p>\n"
},
{
"answer_id": 354535,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 1,
"selected": false,
"text": "<p>Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from \"<a href=\"http://java.sun.com/docs/books/effective/\" rel=\"nofollow noreferrer\">Effective Java</a>\" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3885/"
]
| I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this:
```
Graph g = new Graph();
Node n1 = new Node("#1");
Node n2 = new Node("#2");
Edge e1 = new Edge("e#1", "#1", "#2");
// Each node is added like a reference
g.addNode(n1);
g.addNode(n2);
g.addEdge(e1);
// This will break the internal integrity of the graph
n1.setName("#3");
g.getNode("#2").setName("#4");
```
I believe I should clone the nodes and the edges when adding them to the graph and return a NodeEnvelope class that will maintain the graph structural integrity. Is this the right way of doing this or the design is broken from the beginning ? | I work with graph structures in Java a lot, and my advice would be to make any data member of the Node and Edge class that the Graph depends on for maintaining its structure final, with no setters. In fact, if you can, I would make Node and Edge completely immutable, which has [many benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29).
So, for example:
```
public final class Node {
private final String name;
public Node(String name) {
this.name = name;
}
public String getName() { return name; }
// note: no setter for name
}
```
You would then do your uniqueness check in the Graph object:
```
public class Graph {
Set<Node> nodes = new HashSet<Node>();
public void addNode(Node n) {
// note: this assumes you've properly overridden
// equals and hashCode in Node to make Nodes with the
// same name .equal() and hash to the same value.
if(nodes.contains(n)) {
throw new IllegalArgumentException("Already in graph: " + node);
}
nodes.add(n);
}
}
```
If you need to modify a name of a node, remove the old node and add a new one. This might sound like extra work, but it saves a lot of effort keeping everything straight.
Really, though, creating your own Graph structure from the ground up is probably unnecessary -- this issue is only the first of many you are likely to run into if you build your own.
I would recommend finding a good open source Java graph library, and using that instead. Depending on what you are doing, there are a few options out there. I have used [JUNG](http://jung.sourceforge.net/) in the past, and would recommend it as a good starting point. |
63,764 | <p>How can I find what databases I have a minimum of read access to in either basic SQL, MySQL specific or in PHP?</p>
| [
{
"answer_id": 63869,
"author": "Jay Shepherd",
"author_id": 7511,
"author_profile": "https://Stackoverflow.com/users/7511",
"pm_score": 1,
"selected": false,
"text": "<p>In MySQL, you can execute </p>\n\n<p><code>SHOW DATABASES;</code></p>\n\n<p><strong>Description</strong></p>\n\n<p><code>SHOW DATABASES;</code>to see what you have at least minimal access to. Are you looking for something more programmatic?</p>\n"
},
{
"answer_id": 157565,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 4,
"selected": true,
"text": "<p>There is a command in MySQL which can show you all of the permissions you have. The command is:</p>\n\n<pre>\nSHOW GRANTS;\n</pre>\n\n<p>It will give you output similar to:</p>\n\n<pre>\nroot@(none)~> show grants;\n+---------------------------------------------------------------------+\n| Grants for root@localhost |\n+---------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | \n+---------------------------------------------------------------------+\n1 row in set (0.00 sec)\n</pre>\n\n<p>This is documented at in the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-grants.html\" rel=\"noreferrer\">manual here</a>.</p>\n"
},
{
"answer_id": 628669,
"author": "SeanJA",
"author_id": 75924,
"author_profile": "https://Stackoverflow.com/users/75924",
"pm_score": 1,
"selected": false,
"text": "<p>You could also try connecting to the database with phps mysql_connect(...) will tell you quickly whether or not you have access.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
| How can I find what databases I have a minimum of read access to in either basic SQL, MySQL specific or in PHP? | There is a command in MySQL which can show you all of the permissions you have. The command is:
```
SHOW GRANTS;
```
It will give you output similar to:
```
root@(none)~> show grants;
+---------------------------------------------------------------------+
| Grants for root@localhost |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
```
This is documented at in the [manual here](http://dev.mysql.com/doc/refman/5.0/en/show-grants.html). |
63,771 | <p>As I build *nix piped commands I find that I want to see the output of one stage to verify correctness before building the next stage but I don't want to re-run each stage. Does anyone know of a program that will help with that? It would keep the output of the last stage automatically to use for any new stages. I usually do this by sending the result of each command to a temporary file (i.e. tee or run each command one at a time) but it would be nice for a program to handle this.</p>
<p>I envision something like a tabbed interface where each tab is labeled with each pipe command and selecting a tab shows the output (at least a hundred lines) of applying that command to to the previous result.</p>
| [
{
"answer_id": 63783,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 3,
"selected": false,
"text": "<p>Use 'tee' to copy the intermediate results out to some file as well as pass them on to the next stage of the pipe, like so:</p>\n\n<pre><code>cat /var/log/syslog | tee /tmp/syslog.out | grep something | tee /tmp/grep.out | sed 's/foo/bar/g' | tee /tmp/sed.out | cat >>/var/log/syslog.cleaned\n</code></pre>\n"
},
{
"answer_id": 63803,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><code>tee</code>(1) is your friend. It sends its input to both the specified file and stdout. </p>\n\n<p>Stick it between your pipes. For example:</p>\n\n<pre><code>ls | tee /tmp/out1 | sort | tee /tmp/out2 | sed 's/foo/bar/g'\n</code></pre>\n"
},
{
"answer_id": 63838,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use pipes if you need bidirectional communication (i.e. with netcat): </p>\n\n<pre><code>mknod backpipe p\nnc -l -p 80 0<backpipe | tee -a inflow | nc localhost 81 | tee -a outflow 1>backpipe\n</code></pre>\n\n<p>(<a href=\"http://clug.net.nz/index.php/netcat\" rel=\"nofollow noreferrer\" title=\"via\">via</a>)</p>\n"
},
{
"answer_id": 63877,
"author": "GodEater",
"author_id": 6756,
"author_profile": "https://Stackoverflow.com/users/6756",
"pm_score": 1,
"selected": false,
"text": "<p>There's also the \"pv\" command - available in debian / ubuntu repostitories which shows you the throughput of your pipes.</p>\n\n<p>An example from the man page :\nTransferring a file from another process and passing the expected size to pv:</p>\n\n<pre><code> cat file | pv -s 12345 | nc -w 1 somewhere.com 3000\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
]
| As I build \*nix piped commands I find that I want to see the output of one stage to verify correctness before building the next stage but I don't want to re-run each stage. Does anyone know of a program that will help with that? It would keep the output of the last stage automatically to use for any new stages. I usually do this by sending the result of each command to a temporary file (i.e. tee or run each command one at a time) but it would be nice for a program to handle this.
I envision something like a tabbed interface where each tab is labeled with each pipe command and selecting a tab shows the output (at least a hundred lines) of applying that command to to the previous result. | Use 'tee' to copy the intermediate results out to some file as well as pass them on to the next stage of the pipe, like so:
```
cat /var/log/syslog | tee /tmp/syslog.out | grep something | tee /tmp/grep.out | sed 's/foo/bar/g' | tee /tmp/sed.out | cat >>/var/log/syslog.cleaned
``` |
63,776 | <p>Given an integer typedef:</p>
<pre><code>typedef unsigned int TYPE;
</code></pre>
<p>or</p>
<pre><code>typedef unsigned long TYPE;
</code></pre>
<p>I have the following code to reverse the bits of an integer:</p>
<pre><code>TYPE max_bit= (TYPE)-1;
void reverse_int_setup()
{
TYPE bits= (TYPE)max_bit;
while (bits <<= 1)
max_bit= bits;
}
TYPE reverse_int(TYPE arg)
{
TYPE bit_setter= 1, bit_tester= max_bit, result= 0;
for (result= 0; bit_tester; bit_tester>>= 1, bit_setter<<= 1)
if (arg & bit_tester)
result|= bit_setter;
return result;
}
</code></pre>
<p>One just needs first to run reverse_int_setup(), which stores an integer with the highest bit turned on, then any call to reverse_int(<em>arg</em>) returns <em>arg</em> with its bits reversed (to be used as a key to a binary tree, taken from an increasing counter, but that's more or less irrelevant).</p>
<p>Is there a platform-agnostic way to have in compile-time the correct value for max_int after the call to reverse_int_setup(); Otherwise, is there an algorithm you consider <em>better/leaner</em> than the one I have for reverse_int()?</p>
<p>Thanks.</p>
| [
{
"answer_id": 63854,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>long temp = 0;\nint counter = 0;\nint number_of_bits = sizeof(value) * 8; // get the number of bits that represent value (assuming that it is aligned to a byte boundary)\n\nwhile(value > 0) // loop until value is empty\n{\n temp <<= 1; // shift whatever was in temp left to create room for the next bit\n temp |= (value & 0x01); // get the lsb from value and set as lsb in temp\n value >>= 1; // shift value right by one to look at next lsb\n\n counter++;\n}\n\nvalue = temp;\n\nif (counter < number_of_bits)\n{\n value <<= counter-number_of_bits;\n}\n</code></pre>\n\n<p>(I'm assuming that you know how many bits value holds and it is stored in number_of_bits)</p>\n\n<p>Obviously temp needs to be the longest imaginable data type and when you copy temp back into value, all the extraneous bits in temp should magically vanish (I think!). </p>\n\n<p>Or, the 'c' way would be to say :</p>\n\n<pre><code>while(value)\n</code></pre>\n\n<p>your choice</p>\n"
},
{
"answer_id": 64023,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>We can store the results of reversing all possible 1 byte sequences in an array (256 distinct entries), then use a combination of lookups into this table and some oring logic to get the reverse of integer.</p>\n"
},
{
"answer_id": 64626,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "<p>The following program serves to demonstrate a leaner algorithm for reversing bits, which can be easily extended to handle 64bit numbers.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\nint main(int argc, char**argv)\n{\n int32_t x;\n if ( argc != 2 ) \n {\n printf(\"Usage: %s hexadecimal\\n\", argv[0]);\n return 1;\n }\n\n sscanf(argv[1],\"%x\", &x);\n /* swap every neigbouring bit */\n x = (x&0xAAAAAAAA)>>1 | (x&0x55555555)<<1;\n /* swap every 2 neighbouring bits */\n x = (x&0xCCCCCCCC)>>2 | (x&0x33333333)<<2;\n /* swap every 4 neighbouring bits */\n x = (x&0xF0F0F0F0)>>4 | (x&0x0F0F0F0F)<<4;\n /* swap every 8 neighbouring bits */\n x = (x&0xFF00FF00)>>8 | (x&0x00FF00FF)<<8;\n /* and so forth, for say, 32 bit int */\n x = (x&0xFFFF0000)>>16 | (x&0x0000FFFF)<<16;\n printf(\"0x%x\\n\",x);\n return 0;\n}\n</code></pre>\n\n<p>This code should not contain errors, and was tested using 0x12345678 to produce 0x1e6a2c48 which is the correct answer.</p>\n"
},
{
"answer_id": 64949,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 2,
"selected": false,
"text": "<pre><code>typedef unsigned long TYPE;\n\nTYPE reverser(TYPE n)\n{\n TYPE k = 1, nrev = 0, i, nrevbit1, nrevbit2;\n int count;\n\n for(i = 0; !i || (1 << i && (1 << i) != 1); i+=2)\n {\n /*In each iteration, we swap one bit \n on the 'right half' of the number with another \n on the left half*/\n\n k = 1<<i; /*this is used to find how many positions \n to the left (or right, for the other bit) \n we gotta move the bits in this iteration*/\n\n count = 0;\n\n while(k << 1 && k << 1 != 1)\n {\n k <<= 1;\n count++;\n }\n\n nrevbit1 = n & (1<<(i/2));\n nrevbit1 <<= count;\n\n nrevbit2 = n & 1<<((i/2) + count);\n nrevbit2 >>= count;\n\n nrev |= nrevbit1;\n nrev |= nrevbit2;\n }\n return nrev;\n}\n</code></pre>\n\n<p>This works fine in gcc under Windows, but I'm not sure if it's completely platform independent. A few places of concern are:</p>\n\n<ul>\n<li><p>the condition in the for loop - it assumes that when you left shift 1 beyond the leftmost bit, you get either a 0 with the 1 'falling out' (what I'd expect and what good old Turbo C gives iirc), or the 1 circles around and you get a 1 (what seems to be gcc's behaviour).</p></li>\n<li><p>the condition in the inner while loop: see above. But there's a strange thing happening here: in this case, gcc seems to let the 1 fall out and not circle around!</p></li>\n</ul>\n\n<p>The code might prove cryptic: if you're interested and need an explanation please don't hesitate to ask - I'll put it up someplace.</p>\n"
},
{
"answer_id": 70906,
"author": "Sundar R",
"author_id": 8127,
"author_profile": "https://Stackoverflow.com/users/8127",
"pm_score": 4,
"selected": true,
"text": "<pre><code>#include<stdio.h>\n#include<limits.h>\n\n#define TYPE_BITS sizeof(TYPE)*CHAR_BIT\n\ntypedef unsigned long TYPE;\n\nTYPE reverser(TYPE n)\n{\n TYPE nrev = 0, i, bit1, bit2;\n int count;\n\n for(i = 0; i < TYPE_BITS; i += 2)\n {\n /*In each iteration, we swap one bit on the 'right half' \n of the number with another on the left half*/\n\n count = TYPE_BITS - i - 1; /*this is used to find how many positions \n to the left (and right) we gotta move \n the bits in this iteration*/\n\n bit1 = n & (1<<(i/2)); /*Extract 'right half' bit*/\n bit1 <<= count; /*Shift it to where it belongs*/\n\n bit2 = n & 1<<((i/2) + count); /*Find the 'left half' bit*/\n bit2 >>= count; /*Place that bit in bit1's original position*/\n\n nrev |= bit1; /*Now add the bits to the reversal result*/\n nrev |= bit2;\n }\n return nrev;\n}\n\nint main()\n{\n TYPE n = 6;\n\n printf(\"%lu\", reverser(n));\n return 0;\n}\n</code></pre>\n\n<p>This time I've used the 'number of bits' idea from TK, but made it somewhat more portable by not assuming a byte contains 8 bits and instead using the CHAR_BIT macro. The code is more efficient now (with the inner for loop removed). I hope the code is also slightly less cryptic this time. :)</p>\n\n<p>The need for using count is that the number of positions by which we have to shift a bit varies in each iteration - we have to move the rightmost bit by 31 positions (assuming 32 bit number), the second rightmost bit by 29 positions and so on. Hence count must decrease with each iteration as i increases. </p>\n\n<p>Hope that bit of info proves helpful in understanding the code... </p>\n"
},
{
"answer_id": 73999,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a variation and correction to TK's solution which might be clearer than the solutions by sundar. It takes single bits from t and pushes them into return_val:</p>\n\n<pre><code>typedef unsigned long TYPE;\n#define TYPE_BITS sizeof(TYPE)*8\n\nTYPE reverser(TYPE t)\n{\n unsigned int i;\n TYPE return_val = 0\n for(i = 0; i < TYPE_BITS; i++)\n {/*foreach bit in TYPE*/\n /* shift the value of return_val to the left and add the rightmost bit from t */\n return_val = (return_val << 1) + (t & 1);\n /* shift off the rightmost bit of t */\n t = t >> 1;\n }\n return(return_val);\n}\n</code></pre>\n"
},
{
"answer_id": 74332,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>@ΤΖΩΤΖΙΟΥ</p>\n\n<p>In reply to ΤΖΩΤΖΙΟΥ 's comments, I present modified version of above which depends on a upper limit for bit width.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\ntypedef int32_t TYPE;\nTYPE reverse(TYPE x, int bits)\n{\n TYPE m=~0;\n switch(bits)\n {\n case 64:\n x = (x&0xFFFFFFFF00000000&m)>>16 | (x&0x00000000FFFFFFFF&m)<<16;\n case 32:\n x = (x&0xFFFF0000FFFF0000&m)>>16 | (x&0x0000FFFF0000FFFF&m)<<16;\n case 16:\n x = (x&0xFF00FF00FF00FF00&m)>>8 | (x&0x00FF00FF00FF00FF&m)<<8;\n case 8:\n x = (x&0xF0F0F0F0F0F0F0F0&m)>>4 | (x&0x0F0F0F0F0F0F0F0F&m)<<4;\n x = (x&0xCCCCCCCCCCCCCCCC&m)>>2 | (x&0x3333333333333333&m)<<2;\n x = (x&0xAAAAAAAAAAAAAAAA&m)>>1 | (x&0x5555555555555555&m)<<1;\n }\n return x;\n}\n\nint main(int argc, char**argv)\n{\n TYPE x;\n TYPE b = (TYPE)-1;\n int bits;\n if ( argc != 2 ) \n {\n printf(\"Usage: %s hexadecimal\\n\", argv[0]);\n return 1;\n }\n for(bits=1;b;b<<=1,bits++);\n --bits;\n printf(\"TYPE has %d bits\\n\", bits);\n sscanf(argv[1],\"%x\", &x);\n\n printf(\"0x%x\\n\",reverse(x, bits));\n return 0;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n <li>gcc will warn on the 64bit constants</li>\n <li>the printfs will generate warnings too</li>\n <li>If you need more than 64bit, the code should be simple enough to extend</li>\n</ul>\n\n<p>I apologise in advance for the coding crimes I committed above - mercy good sir!</p>\n"
},
{
"answer_id": 79181,
"author": "mxg",
"author_id": 11157,
"author_profile": "https://Stackoverflow.com/users/11157",
"pm_score": 1,
"selected": false,
"text": "<p>There's a nice collection of \"Bit Twiddling Hacks\", including a variety of simple and not-so simple bit reversing algorithms coded in C at <a href=\"http://graphics.stanford.edu/~seander/bithacks.html\" rel=\"nofollow noreferrer\">http://graphics.stanford.edu/~seander/bithacks.html</a>.</p>\n\n<p>I personally like the \"Obvious\" algorigthm (<a href=\"http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious\" rel=\"nofollow noreferrer\">http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious</a>) because, well, it's obvious. Some of the others may require less instructions to execute. If I really need to optimize the heck out of something I may choose the not-so-obvious but faster versions. Otherwise, for readability, maintainability, and portability I would choose the Obvious one.</p>\n"
},
{
"answer_id": 1845062,
"author": "The Neocompressionist",
"author_id": 224525,
"author_profile": "https://Stackoverflow.com/users/224525",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a more generally useful variation. Its advantage is its ability to work in situations where the bit length of the value to be reversed -- the codeword -- is unknown but is guaranteed not to exceed a value we'll call maxLength. A good example of this case is Huffman code decompression. </p>\n\n<p>The code below works on codewords from 1 to 24 bits in length. It has been optimized for fast execution on a Pentium D. Note that it accesses the lookup table as many as 3 times per use. I experimented with many variations that reduced that number to 2 at the expense of a larger table (4096 and 65,536 entries). This version, with the 256-byte table, was the clear winner, partly because it is so advantageous for table data to be in the caches, and perhaps also because the processor has an 8-bit table lookup/translation instruction.</p>\n\n<pre><code>const unsigned char table[] = { \n0x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0, \n0x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8, \n0x04,0x84,0x44,0xC4,0x24,0xA4,0x64,0xE4,0x14,0x94,0x54,0xD4,0x34,0xB4,0x74,0xF4, \n0x0C,0x8C,0x4C,0xCC,0x2C,0xAC,0x6C,0xEC,0x1C,0x9C,0x5C,0xDC,0x3C,0xBC,0x7C,0xFC, \n0x02,0x82,0x42,0xC2,0x22,0xA2,0x62,0xE2,0x12,0x92,0x52,0xD2,0x32,0xB2,0x72,0xF2, \n0x0A,0x8A,0x4A,0xCA,0x2A,0xAA,0x6A,0xEA,0x1A,0x9A,0x5A,0xDA,0x3A,0xBA,0x7A,0xFA, \n0x06,0x86,0x46,0xC6,0x26,0xA6,0x66,0xE6,0x16,0x96,0x56,0xD6,0x36,0xB6,0x76,0xF6, \n0x0E,0x8E,0x4E,0xCE,0x2E,0xAE,0x6E,0xEE,0x1E,0x9E,0x5E,0xDE,0x3E,0xBE,0x7E,0xFE, \n0x01,0x81,0x41,0xC1,0x21,0xA1,0x61,0xE1,0x11,0x91,0x51,0xD1,0x31,0xB1,0x71,0xF1, \n0x09,0x89,0x49,0xC9,0x29,0xA9,0x69,0xE9,0x19,0x99,0x59,0xD9,0x39,0xB9,0x79,0xF9, \n0x05,0x85,0x45,0xC5,0x25,0xA5,0x65,0xE5,0x15,0x95,0x55,0xD5,0x35,0xB5,0x75,0xF5, \n0x0D,0x8D,0x4D,0xCD,0x2D,0xAD,0x6D,0xED,0x1D,0x9D,0x5D,0xDD,0x3D,0xBD,0x7D,0xFD, \n0x03,0x83,0x43,0xC3,0x23,0xA3,0x63,0xE3,0x13,0x93,0x53,0xD3,0x33,0xB3,0x73,0xF3, \n0x0B,0x8B,0x4B,0xCB,0x2B,0xAB,0x6B,0xEB,0x1B,0x9B,0x5B,0xDB,0x3B,0xBB,0x7B,0xFB, \n0x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7, \n0x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF}; \n\n\nconst unsigned short masks[17] = \n{0,0,0,0,0,0,0,0,0,0X0100,0X0300,0X0700,0X0F00,0X1F00,0X3F00,0X7F00,0XFF00}; \n\n\nunsigned long codeword; // value to be reversed, occupying the low 1-24 bits \nunsigned char maxLength; // bit length of longest possible codeword (<= 24) \nunsigned char sc; // shift count in bits and index into masks array \n\n\nif (maxLength <= 8) \n{ \n codeword = table[codeword << (8 - maxLength)]; \n} \nelse \n{ \n sc = maxLength - 8; \n\n if (maxLength <= 16) \n {\n codeword = (table[codeword & 0X00FF] << sc) \n | table[codeword >> sc]; \n } \n else if (maxLength & 1) // if maxLength is 17, 19, 21, or 23 \n { \n codeword = (table[codeword & 0X00FF] << sc) \n | table[codeword >> sc] | \n (table[(codeword & masks[sc]) >> (sc - 8)] << 8); \n } \n else // if maxlength is 18, 20, 22, or 24 \n { \n codeword = (table[codeword & 0X00FF] << sc) \n | table[codeword >> sc] \n | (table[(codeword & masks[sc]) >> (sc >> 1)] << (sc >> 1)); \n } \n} \n</code></pre>\n"
},
{
"answer_id": 1845084,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 0,
"selected": false,
"text": "<p>The generic approach hat would work for objects of any type of any size would be to reverse the of bytes of the object, and the reverse the order of bits in each byte. In this case the bit-level algorithm is tied to a concrete number of bits (a byte), while the \"variable\" logic (with regard to size) is lifted to the level of whole bytes.</p>\n"
},
{
"answer_id": 2489633,
"author": "ivan",
"author_id": 298718,
"author_profile": "https://Stackoverflow.com/users/298718",
"pm_score": 0,
"selected": false,
"text": "<p>In case bit-reversal is time critical, and mainly in conjunction with FFT, the best is to store the whole bit reversed array. In any case, this array will be smaller in size than the roots of unity that have to be precomputed in FFT Cooley-Tukey algorithm. An easy way to compute the array is:</p>\n\n<pre><code>int BitReverse[Size]; // Size is power of 2\nvoid Init()\n{\n BitReverse[0] = 0;\n for(int i = 0; i < Size/2; i++)\n {\n BitReverse[2*i] = BitReverse[i]/2;\n BitReverse[2*i+1] = (BitReverse[i] + Size)/2;\n }\n} // end it's all\n</code></pre>\n"
},
{
"answer_id": 5036813,
"author": "Bernd Jendrissek",
"author_id": 117911,
"author_profile": "https://Stackoverflow.com/users/117911",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my generalization of freespace's solution (in case we one day get 128-bit machines). It results in jump-free code when compiled with gcc -O3, and is obviously insensitive to the definition of foo_t on sane machines. Unfortunately it does depend on shift being a power of 2!</p>\n\n<pre><code>#include <limits.h>\n#include <stdio.h>\n\ntypedef unsigned long foo_t;\n\nfoo_t reverse(foo_t x)\n{\n int shift = sizeof (x) * CHAR_BIT / 2;\n foo_t mask = (1 << shift) - 1;\n int i;\n\n for (i = 0; shift; i++) {\n x = ((x & mask) << shift) | ((x & ~mask) >> shift);\n shift >>= 1;\n mask ^= (mask << shift);\n }\n\n return x;\n} \n\nint main() {\n printf(\"reverse = 0x%08lx\\n\", reverse(0x12345678L));\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899/"
]
| Given an integer typedef:
```
typedef unsigned int TYPE;
```
or
```
typedef unsigned long TYPE;
```
I have the following code to reverse the bits of an integer:
```
TYPE max_bit= (TYPE)-1;
void reverse_int_setup()
{
TYPE bits= (TYPE)max_bit;
while (bits <<= 1)
max_bit= bits;
}
TYPE reverse_int(TYPE arg)
{
TYPE bit_setter= 1, bit_tester= max_bit, result= 0;
for (result= 0; bit_tester; bit_tester>>= 1, bit_setter<<= 1)
if (arg & bit_tester)
result|= bit_setter;
return result;
}
```
One just needs first to run reverse\_int\_setup(), which stores an integer with the highest bit turned on, then any call to reverse\_int(*arg*) returns *arg* with its bits reversed (to be used as a key to a binary tree, taken from an increasing counter, but that's more or less irrelevant).
Is there a platform-agnostic way to have in compile-time the correct value for max\_int after the call to reverse\_int\_setup(); Otherwise, is there an algorithm you consider *better/leaner* than the one I have for reverse\_int()?
Thanks. | ```
#include<stdio.h>
#include<limits.h>
#define TYPE_BITS sizeof(TYPE)*CHAR_BIT
typedef unsigned long TYPE;
TYPE reverser(TYPE n)
{
TYPE nrev = 0, i, bit1, bit2;
int count;
for(i = 0; i < TYPE_BITS; i += 2)
{
/*In each iteration, we swap one bit on the 'right half'
of the number with another on the left half*/
count = TYPE_BITS - i - 1; /*this is used to find how many positions
to the left (and right) we gotta move
the bits in this iteration*/
bit1 = n & (1<<(i/2)); /*Extract 'right half' bit*/
bit1 <<= count; /*Shift it to where it belongs*/
bit2 = n & 1<<((i/2) + count); /*Find the 'left half' bit*/
bit2 >>= count; /*Place that bit in bit1's original position*/
nrev |= bit1; /*Now add the bits to the reversal result*/
nrev |= bit2;
}
return nrev;
}
int main()
{
TYPE n = 6;
printf("%lu", reverser(n));
return 0;
}
```
This time I've used the 'number of bits' idea from TK, but made it somewhat more portable by not assuming a byte contains 8 bits and instead using the CHAR\_BIT macro. The code is more efficient now (with the inner for loop removed). I hope the code is also slightly less cryptic this time. :)
The need for using count is that the number of positions by which we have to shift a bit varies in each iteration - we have to move the rightmost bit by 31 positions (assuming 32 bit number), the second rightmost bit by 29 positions and so on. Hence count must decrease with each iteration as i increases.
Hope that bit of info proves helpful in understanding the code... |
63,800 | <p>Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include</p>
<pre><code>\ / < > ? * :
</code></pre>
<p>I know HOW to validate names (a regular expression).</p>
<p>I need to validate filenames entered by users. </p>
<p>My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!</p>
| [
{
"answer_id": 63861,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 2,
"selected": false,
"text": "<p>No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.</p>\n\n<p>Also, if trying to port an Windows app to Mac or Unix it is best to use:</p>\n\n<pre><code>File.separator\n</code></pre>\n\n<p>To determine the correct file separator to use on each platform.</p>\n"
},
{
"answer_id": 63963,
"author": "Andrew",
"author_id": 7613,
"author_profile": "https://Stackoverflow.com/users/7613",
"pm_score": 0,
"selected": false,
"text": "<p>When you create a <code>new File</code> the inputted arguments will be normalized by a platform specific implementation of the <code>java.io.FileSystem</code> class. There are no Java specific restrictions that I know of.</p>\n\n<p>and yes, always use <code>File.separator</code>.</p>\n"
},
{
"answer_id": 63993,
"author": "Bill Michell",
"author_id": 7938,
"author_profile": "https://Stackoverflow.com/users/7938",
"pm_score": 0,
"selected": false,
"text": "<p>Java supports any <code>String</code> that can be expressed in Unicode (subject to some ridiculously long maximum length, <code>Integer.MAX_VALUE</code>), and file names are just another kind of <code>String</code>.</p>\n\n<p>Of course, this means that you can try and refer to a file using a name that isn't supported by the underlying Operating System. If you do this, you'll get some kind of <code>IOException</code> when you try and use the File reference...</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8118/"
]
| Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include
```
\ / < > ? * :
```
I know HOW to validate names (a regular expression).
I need to validate filenames entered by users.
My application does not need to run on any other platform, though, of course, I would prefer to be platform independent! | No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.
Also, if trying to port an Windows app to Mac or Unix it is best to use:
```
File.separator
```
To determine the correct file separator to use on each platform. |
63,805 | <p>How do I ask PowerShell where something is? </p>
<p>For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.</p>
| [
{
"answer_id": 63831,
"author": "Nicholas",
"author_id": 8054,
"author_profile": "https://Stackoverflow.com/users/8054",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to do what you want (I found it on <a href=\"http://huddledmasses.org/powershell-find-path/\" rel=\"nofollow noreferrer\">http://huddledmasses.org/powershell-find-path/</a>):</p>\n\n<pre><code>Function Find-Path($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = \"Any\")\n## You could comment out the function stuff and use it as a script instead, with this line:\n#param($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = \"Any\")\n if($(Test-Path $Path -Type $type)) {\n return $path\n } else {\n [string[]]$paths = @($pwd);\n $paths += \"$pwd;$env:path\".split(\";\")\n\n $paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }\n if($paths.Length -gt 0) {\n if($All) {\n return $paths;\n } else {\n return $paths[0]\n }\n }\n }\n throw \"Couldn't find a matching path of type $type\"\n}\nSet-Alias find Find-Path\n</code></pre>\n"
},
{
"answer_id": 63835,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>Check this <a href=\"http://blog.stangroome.com/2007/09/06/my-manwich-powershell-which\" rel=\"nofollow noreferrer\">PowerShell Which</a>.</p>\n\n<p>The code provided there suggests this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>($Env:Path).Split(\";\") | Get-ChildItem -filter notepad.exe\n</code></pre>\n"
},
{
"answer_id": 63891,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 7,
"selected": false,
"text": "<p>I usually just type:</p>\n\n<pre><code>gcm notepad\n</code></pre>\n\n<p>or</p>\n\n<pre><code>gcm note*\n</code></pre>\n\n<p>gcm is the default alias for Get-Command.</p>\n\n<p>On my system, gcm note* outputs:</p>\n\n<pre><code>[27] » gcm note*\n\nCommandType Name Definition\n----------- ---- ----------\nApplication notepad.exe C:\\WINDOWS\\notepad.exe\nApplication notepad.exe C:\\WINDOWS\\system32\\notepad.exe\nApplication Notepad2.exe C:\\Utils\\Notepad2.exe\nApplication Notepad2.ini C:\\Utils\\Notepad2.ini\n</code></pre>\n\n<p>You get the directory and the command that matches what you're looking for.</p>\n"
},
{
"answer_id": 65148,
"author": "halr9000",
"author_id": 6637,
"author_profile": "https://Stackoverflow.com/users/6637",
"pm_score": 10,
"selected": true,
"text": "<p>The very first alias I made once I started customizing my profile in PowerShell was 'which'.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>New-Alias which get-command\n</code></pre>\n\n<p>To add this to your profile, type this:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>\"`nNew-Alias which get-command\" | add-content $profile\n</code></pre>\n\n<p>The `n at the start of the last line is to ensure it will start as a new line.</p>\n"
},
{
"answer_id": 8484635,
"author": "Anonymous",
"author_id": 1095069,
"author_profile": "https://Stackoverflow.com/users/1095069",
"pm_score": 2,
"selected": false,
"text": "<p>Try the <a href=\"http://ss64.com/nt/where.html\" rel=\"nofollow noreferrer\"><code>where</code></a> command on Windows 2003 or later (or Windows 2000/XP if you've installed a Resource Kit). </p>\n\n<p>BTW, this received more answers in other questions:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/304319/is-there-an-equivalent-of-which-on-windows\">Is there an equivalent of 'which' on Windows?</a></p>\n\n<p><a href=\"https://superuser.com/questions/34492/powershell-equivalent-to-unix-which-command\">PowerShell equivalent to Unix <code>which</code> command?</a></p>\n"
},
{
"answer_id": 16949127,
"author": "petrsnd",
"author_id": 246826,
"author_profile": "https://Stackoverflow.com/users/246826",
"pm_score": 8,
"selected": false,
"text": "<p>Here is an actual *nix equivalent, i.e. it gives *nix-style output.</p>\n\n<pre><code>Get-Command <your command> | Select-Object -ExpandProperty Definition\n</code></pre>\n\n<p>Just replace with whatever you're looking for.</p>\n\n<pre><code>PS C:\\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition\nC:\\Windows\\system32\\notepad.exe\n</code></pre>\n\n<p>When you add it to your profile, you will want to use a function rather than an alias because you can't use aliases with pipes:</p>\n\n<pre><code>function which($name)\n{\n Get-Command $name | Select-Object -ExpandProperty Definition\n}\n</code></pre>\n\n<p>Now, when you reload your profile you can do this:</p>\n\n<pre><code>PS C:\\> which notepad\nC:\\Windows\\system32\\notepad.exe\n</code></pre>\n"
},
{
"answer_id": 20728713,
"author": "Jerome",
"author_id": 1503073,
"author_profile": "https://Stackoverflow.com/users/1503073",
"pm_score": 0,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>function Which([string] $cmd) {\n $path = (($Env:Path).Split(\";\") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName\n if ($path) { $path.ToString() }\n}\n\n# Check if Chocolatey is installed\nif (Which('cinst.bat')) {\n Write-Host \"yes\"\n} else {\n Write-Host \"no\"\n}\n</code></pre>\n\n<p>Or this version, calling the original where command.</p>\n\n<p>This version also works better, because it is not limited to bat files:</p>\n\n<pre><code>function which([string] $cmd) {\n $where = iex $(Join-Path $env:SystemRoot \"System32\\where.exe $cmd 2>&1\")\n $first = $($where -split '[\\r\\n]')\n if ($first.getType().BaseType.Name -eq 'Array') {\n $first = $first[0]\n }\n if (Test-Path $first) {\n $first\n }\n}\n\n# Check if Curl is installed\nif (which('curl')) {\n echo 'yes'\n} else {\n echo 'no'\n}\n</code></pre>\n"
},
{
"answer_id": 22776692,
"author": "thesqldev",
"author_id": 3483572,
"author_profile": "https://Stackoverflow.com/users/3483572",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Try this example:</strong></p>\n\n<pre><code>(Get-Command notepad.exe).Path\n</code></pre>\n"
},
{
"answer_id": 33754315,
"author": "VortiFred",
"author_id": 5571459,
"author_profile": "https://Stackoverflow.com/users/5571459",
"pm_score": 4,
"selected": false,
"text": "<p>My proposition for the Which function:</p>\n\n<pre><code>function which($cmd) { get-command $cmd | % { $_.Path } }\n\nPS C:\\> which devcon\n\nC:\\local\\code\\bin\\devcon.exe\n</code></pre>\n"
},
{
"answer_id": 43299243,
"author": "Chris F Carroll",
"author_id": 550314,
"author_profile": "https://Stackoverflow.com/users/550314",
"pm_score": 3,
"selected": false,
"text": "<p>A quick-and-dirty match to Unix <code>which</code> is</p>\n\n<pre><code>New-Alias which where.exe\n</code></pre>\n\n<p>But it returns multiple lines if they exist so then it becomes</p>\n\n<pre><code>function which {where.exe command | select -first 1}\n</code></pre>\n"
},
{
"answer_id": 43354653,
"author": "js2010",
"author_id": 6654942,
"author_profile": "https://Stackoverflow.com/users/6654942",
"pm_score": 3,
"selected": false,
"text": "<p>I like <code>Get-Command | Format-List</code>, or shorter, using aliases for the two and only for <code>powershell.exe</code>:</p>\n<pre><code>gcm powershell | fl\n</code></pre>\n<p>You can find aliases like this:</p>\n<pre><code>alias -definition Format-List\n</code></pre>\n<p>Tab completion works with <code>gcm</code>.</p>\n<p>To have tab list all options at once:</p>\n<pre><code>set-psreadlineoption -editmode emacs\n</code></pre>\n"
},
{
"answer_id": 49116772,
"author": "Jeff Zeitlin",
"author_id": 6083222,
"author_profile": "https://Stackoverflow.com/users/6083222",
"pm_score": 1,
"selected": false,
"text": "<p>I have this <code>which</code> advanced function in my PowerShell profile:</p>\n<pre><code> function which {\n <#\n .SYNOPSIS\n Identifies the source of a PowerShell command.\n .DESCRIPTION\n Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable\n (which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in\n provided; aliases are expanded and the source of the alias definition is returned.\n .INPUTS\n No inputs; you cannot pipe data to this function.\n .OUTPUTS\n .PARAMETER Name\n The name of the command to be identified.\n .EXAMPLE\n PS C:\\Users\\Smith\\Documents> which Get-Command\n \n Get-Command: Cmdlet in module Microsoft.PowerShell.Core\n \n (Identifies type and source of command)\n .EXAMPLE\n PS C:\\Users\\Smith\\Documents> which notepad\n \n C:\\WINDOWS\\SYSTEM32\\notepad.exe\n \n (Indicates the full path of the executable)\n #>\n param(\n [String]$name\n )\n \n $cmd = Get-Command $name\n $redirect = $null\n switch ($cmd.CommandType) {\n "Alias" { "{0}: Alias for ({1})" -f $cmd.Name, (. { which $cmd.Definition } ) }\n "Application" { $cmd.Source }\n "Cmdlet" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }\n "Function" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }\n "Workflow" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }\n "ExternalScript" { $cmd.Source }\n default { $cmd }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 62127237,
"author": "Amin",
"author_id": 7910299,
"author_profile": "https://Stackoverflow.com/users/7910299",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>function which($name) {\n if ($name) { $input = $name }\n Get-Command $input | Select-Object -ExpandProperty Path\n}\n</code></pre>\n\n<p>copy-paste the command to your profile (<code>notepad $profile</code>).</p>\n\n<p>Examples:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>❯ echo clang.exe | which\nC:\\Program Files\\LLVM\\bin\\clang.exe\n\n❯ which clang.exe\nC:\\Program Files\\LLVM\\bin\\clang.exe\n</code></pre>\n"
},
{
"answer_id": 62995766,
"author": "George Ogden",
"author_id": 12103577,
"author_profile": "https://Stackoverflow.com/users/12103577",
"pm_score": 0,
"selected": false,
"text": "<p>You can install the <code>which</code> command from <a href=\"https://goprogram.co.uk/software/commands\" rel=\"nofollow noreferrer\">https://goprogram.co.uk/software/commands</a>, along with all of the other UNIX commands.</p>\n"
},
{
"answer_id": 69868490,
"author": "blenderfreaky",
"author_id": 7869744,
"author_profile": "https://Stackoverflow.com/users/7869744",
"pm_score": 0,
"selected": false,
"text": "<p>If you have <a href=\"https://github.com/ScoopInstaller/Scoop\" rel=\"nofollow noreferrer\">scoop</a> you can install a direct clone of which:</p>\n<pre><code>scoop install which\nwhich notepad\n</code></pre>\n"
},
{
"answer_id": 71627654,
"author": "rayiik",
"author_id": 14073060,
"author_profile": "https://Stackoverflow.com/users/14073060",
"pm_score": 0,
"selected": false,
"text": "<p>There also always the option of using which. there are actually three ways to access which from Windows powershell, the first (not necessarily the best) wsl -e which command (this requires installation of windows subsystem for Linux and a running distro). B. <a href=\"http://gnuwin32.sourceforge.net/packages.html\" rel=\"nofollow noreferrer\">gnuwin32</a> which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers option three, install <a href=\"https://www.msys2.org/\" rel=\"nofollow noreferrer\">msys2</a> (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.</p>\n"
},
{
"answer_id": 71627691,
"author": "rayiik",
"author_id": 14073060,
"author_profile": "https://Stackoverflow.com/users/14073060",
"pm_score": -1,
"selected": false,
"text": "<p>There also always the option of using which. there are actually three ways to access which from Windows powershell</p>\n<ul>\n<li>The first, (though not the best) is wsl(windows subsystem for linux)</li>\n</ul>\n<pre class=\"lang-sh prettyprint-override\"><code>wsl -e which command \n</code></pre>\n<p>This requires installation of windows subsystem for Linux and a running distro.</p>\n<ul>\n<li><p>Next is <a href=\"http://gnuwin32.sourceforge.net/packages.html\" rel=\"nofollow noreferrer\">gnuwin32</a> which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers</p>\n</li>\n<li><p>Third, install <a href=\"https://www.msys2.org/\" rel=\"nofollow noreferrer\">msys2</a> (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.</p>\n</li>\n</ul>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
]
| How do I ask PowerShell where something is?
For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths. | The very first alias I made once I started customizing my profile in PowerShell was 'which'.
```sh
New-Alias which get-command
```
To add this to your profile, type this:
```sh
"`nNew-Alias which get-command" | add-content $profile
```
The `n at the start of the last line is to ensure it will start as a new line. |
63,870 | <p>I have a rather large file (150 million lines of 10 chars). I need to split it in 150 files of 2 million lines, with each output line being alternatively the first 5 characters or the last 5 characters of the source line.
I could do this in Perl rather quickly, but I was wondering if there was an easy solution using bash.
Any ideas?</p>
| [
{
"answer_id": 63941,
"author": "HD.",
"author_id": 6525,
"author_profile": "https://Stackoverflow.com/users/6525",
"pm_score": 3,
"selected": true,
"text": "<p>Homework? :-)</p>\n\n<p>I would think that a simple pipe with sed (to split each line into two) and split (to split things up into multiple files) would be enough.</p>\n\n<p>The man command is your friend.</p>\n\n<hr>\n\n<p>Added after confirmation that it is not homework:</p>\n\n<p>How about</p>\n\n<pre><code>sed 's/\\(.....\\)\\(.....\\)/\\1\\n\\2/' input_file | split -l 2000000 - out-prefix-\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 63973,
"author": "che",
"author_id": 7806,
"author_profile": "https://Stackoverflow.com/users/7806",
"pm_score": 0,
"selected": false,
"text": "<p>I think that something like this could work:</p>\n\n<pre><code>out_file=1\nout_pairs=0\ncat $in_file | while read line; do\n if [ $out_pairs -gt 1000000 ]; then\n out_file=$(($out_file + 1))\n out_pairs=0\n fi\n echo \"${line%?????}\" >> out${out_file}\n echo \"${line#?????}\" >> out${out_file}\n out_pairs=$(($out_pairs + 1))\ndone\n</code></pre>\n\n<p>Not sure if it's simpler or more efficient than using Perl, though.</p>\n"
},
{
"answer_id": 64008,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 0,
"selected": false,
"text": "<p>First five chars of each line variant, assuming that the large file called x.txt, and assuming it's OK to create files in the current directory with names x.txt.* :</p>\n\n<p>split -l 2000000 x.txt x.txt.out && (for splitfile in x.txt.out*; do outfile=\"${splitfile}.firstfive\"; echo \"$splitfile -> $outfile\"; cut -c 1-5 \"$splitfile\" > \"$outfile\"; done)</p>\n"
},
{
"answer_id": 72982898,
"author": "lacostenycoder",
"author_id": 3625433,
"author_profile": "https://Stackoverflow.com/users/3625433",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just use native linux <code>split</code> function?</p>\n<pre><code>split -d -l 999999 input_filename\n</code></pre>\n<p>this will output new split files with file names like <code>x00 x01 x02...</code></p>\n<p>for more info see the manual</p>\n<pre><code>man split\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7028/"
]
| I have a rather large file (150 million lines of 10 chars). I need to split it in 150 files of 2 million lines, with each output line being alternatively the first 5 characters or the last 5 characters of the source line.
I could do this in Perl rather quickly, but I was wondering if there was an easy solution using bash.
Any ideas? | Homework? :-)
I would think that a simple pipe with sed (to split each line into two) and split (to split things up into multiple files) would be enough.
The man command is your friend.
---
Added after confirmation that it is not homework:
How about
```
sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix-
```
? |
63,881 | <p>I have a strange problem with my cake (cake_1.2.0.7296-rc2).
My start()-action runs twice, under certain circumstances, even though only one request is made.</p>
<p>The triggers seem to be :
- loading an object like: <code>$this->Questionnaire->read(null, $questionnaire_id);</code>
- accessing $this-data </p>
<p>If I disable the call to <code>loadAvertisement()</code> from the <code>start()</code>-action, this does not happen.
If I disable the two calls inside <code>loadAdvertisement():</code></p>
<pre><code>$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
$question = $this->Questionnaire->Question->read(null, $question_id);
</code></pre>
<p>... then it doesn't happen either.</p>
<p>Why?</p>
<p>See my code below, the Controller is "questionnaires_controller".</p>
<pre><code>function checkValidQuestionnaire($id)
{
$this->layout = 'questionnaire_frontend_layout';
if (!$id)
{
$id = $this->Session->read('Questionnaire.id');
}
if ($id)
{
$this->data = $this->Questionnaire->read(null, $id);
//echo "from ".$questionnaire['Questionnaire']['validFrom']." ".date("y.m.d");
//echo " - to ".$questionnaire['Questionnaire']['validTo']." ".date("y.m.d");
if ($this->data['Questionnaire']['isPublished'] != 1
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
)
{
$id = 0;
$this->flash(__('Ungültiges Quiz. Weiter zum Archiv...', true), array('action'=>'archive'));
}
}
else
{
$this->flash(__('Invalid Questionnaire', true), array('action'=>'intro'));
}
return $id;
}
function start($id = null) {
$this->log("start");
$id = $this->checkValidQuestionnaire($id);
//$questionnaire = $this->Questionnaire->read(null, $id);
$this->set('questionnaire', $this->data);
// reset flow-controlling session vars
$this->Session->write('Questionnaire',array('id' => $id));
$this->Session->write('Questionnaire'.$id.'currQuestion', null);
$this->Session->write('Questionnaire'.$id.'lastAnsweredQuestion', null);
$this->Session->write('Questionnaire'.$id.'correctAnswersNum', null);
$this->loadAdvertisement($id, 0);
$this->Session->write('Questionnaire'.$id.'previewMode', $this->params['named']['preview_mode']);
if (!$this->Session->read('Questionnaire'.$id.'previewMode'))
{
$questionnaire['Questionnaire']['participiantStartCount']++;
$this->Questionnaire->save($questionnaire);
}
}
function loadAdvertisement($questionnaire_id, $question_id)
{
//$questionnaire = array();
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
//$question = array();
$question = $this->Questionnaire->Question->read(null, $question_id);
if (isset($question['Question']['advertisement_id']) && $question['Question']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $question['Question']['advertisement_id']));
}
else if (isset($questionnaire['Questionnaire']['advertisement_id']) && $questionnaire['Questionnaire']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $questionnaire['Questionnaire']['advertisement_id']));
}
}
</code></pre>
<p>I really don't understand this... it don't think it's meant to be this way.
Any help would be greatly appreciated! :)</p>
<p>Regards,
Stu</p>
| [
{
"answer_id": 64176,
"author": "eelco",
"author_id": 8293,
"author_profile": "https://Stackoverflow.com/users/8293",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to try and find out where it comes from using the debug_print_backtrace() function. (<a href=\"http://nl.php.net/manual/en/function.debug-print-backtrace.php\" rel=\"nofollow noreferrer\">http://nl.php.net/manual/en/function.debug-print-backtrace.php</a></p>\n"
},
{
"answer_id": 353493,
"author": "Martz",
"author_id": 44576,
"author_profile": "https://Stackoverflow.com/users/44576",
"pm_score": 4,
"selected": false,
"text": "<p>Check your layout for non-existent links, for example a misconfigured link to favicon.ico will cause the controller action to be triggered for a second time. Make sure favicon.ico points towards the webroot rather than the local directory, or else requests will be generated for /controller/action/favicon.ico rather than /favicon.ico - and thus trigger your action.</p>\n\n<p>This can also happen with images, stylesheets and javascript includes.</p>\n\n<p>To counter check the $id is an int, then check to ensure $id exists as a primary key in the database before progressing on to any functionality.</p>\n"
},
{
"answer_id": 943508,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Had the same problem, with a certain action randomly running 2-3 times. I tracked down two causes:</p>\n\n<ul>\n<li><p>Firefox add-on Yslow was set to load automatically from it's Preferences, causing pages to reload when using F5 (not when loading the page from the browser's address bar and pressing Enter).</p></li>\n<li><p>I had a faulty css style declaration within the options of a $html->link(); in some cases it would end up as background-image: url('');, which caused a rerun also. Setting the style for the link to background-image: none; when no image was available fixed things for me.</p></li>\n</ul>\n\n<p>Hope this helps. I know this is quite an old post, but as it comes up pretty high in Google when searching for this problem, I thought it might help others by still posting.</p>\n\n<p>Good luck</p>\n\n<p>Jeroen den Haan</p>\n"
},
{
"answer_id": 944647,
"author": "unicorn_crack",
"author_id": 100765,
"author_profile": "https://Stackoverflow.com/users/100765",
"pm_score": 1,
"selected": false,
"text": "<p>I had a problem like this last week.</p>\n\n<p>Two possible reasons</p>\n\n<ul>\n<li>Faulty routes (DO check your routes configuration)</li>\n<li>Faulty AppController. I add loads of stuff into AppController, especially to beforeFilter() and beforeRender() so you might want to check those out also.</li>\n</ul>\n\n<p>One more thing, are where are you setting the Questioneer.id in your Session? Perhaps that's the problem?</p>\n"
},
{
"answer_id": 1564586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For me it was a JS issue.</p>\n\n<p>Take care of wrap function with jQuery that re-execute JS in wrapped content! </p>\n"
},
{
"answer_id": 12165162,
"author": "Aloe",
"author_id": 1631160,
"author_profile": "https://Stackoverflow.com/users/1631160",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it occurs when there is a broken link in the web page. Each browser deals with it variously (Firefox calls it 2x). I tested it, there is no difference in CakePHP v1.3 and v2.2.1. To find out who the culprit is, add this line to the code, and then open the second generated file in you <code>www</code> folder:</p>\n\n<pre><code>file_put_contents(\"log-\" . date(\"Hms\") . \".txt\", $this->params['pass'] ); // CakePHP v1.3 \nfile_put_contents(\"log-\" . date(\"Hms\") . \".txt\", $this->request['pass'] ); //CakePHP v2.2.1\n</code></pre>\n\n<p>PS: First I blame jQuery for it. But in the end it was forgotten image for AJAX loading in 3rd part script. </p>\n"
},
{
"answer_id": 17543801,
"author": "Vijay Kumbhar",
"author_id": 447509,
"author_profile": "https://Stackoverflow.com/users/447509",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem in chrome, I disabled my 'HTML Validator' add on. Which was loading the page twice</p>\n"
},
{
"answer_id": 28416302,
"author": "jtrumbull",
"author_id": 3112730,
"author_profile": "https://Stackoverflow.com/users/3112730",
"pm_score": 0,
"selected": false,
"text": "<p>I was having a similar issue, the problem seemed to be isolated to case-insensitivity on the endpoint.\n <br/><br/> ie: <br/>\n<a href=\"http://server/Questionnaires/loadAvertisement\" rel=\"nofollow\">http://server/Questionnaires/loadAvertisement</a> -vs- <br/>\n<a href=\"http://server/questionnaires/loadavertisement\" rel=\"nofollow\">http://server/questionnaires/loadavertisement</a></p>\n\n<p>When calling the proper-cased endpoint, the method ran once -whereas the lower-cased ran twice. The problem was occurring sporadically -happening on one controller, but not on another (essentially the same logic, no additional components etc.). I couldn't confirm, but believe the fault to be of the browser -not the CakePHP itself.</p>\n\n<p>My workaround was assuring that every endpoint link was proper-cased. To go even further, I added common case-variants to the Route's configuration:\n<br/>\n<br/>\napp/config/routes.php</p>\n\n<pre><code><?php\n// other routes..\n$instructions = ['controller'=>'Questionnaires','action'=>'loadAvertisement'];\nRouter::connect('/questionnaires/loadavertisement', $instructions);\nRouter::connect('/QUESTIONNARIES/LOADADVERTISEMENT', $instructions);\n// ..etc\n</code></pre>\n"
},
{
"answer_id": 29075468,
"author": "gdm",
"author_id": 778508,
"author_profile": "https://Stackoverflow.com/users/778508",
"pm_score": 0,
"selected": false,
"text": "<p>If you miss <code><something></code>, for example a View, Cake will trigger a missing <code><something></code> error and it will try to render its <code>Error View</code>. Therefore, <code>AppController</code> will be called twice. If you resolve the missing issue, <code>AppController</code> is called once.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a strange problem with my cake (cake\_1.2.0.7296-rc2).
My start()-action runs twice, under certain circumstances, even though only one request is made.
The triggers seem to be :
- loading an object like: `$this->Questionnaire->read(null, $questionnaire_id);`
- accessing $this-data
If I disable the call to `loadAvertisement()` from the `start()`-action, this does not happen.
If I disable the two calls inside `loadAdvertisement():`
```
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
$question = $this->Questionnaire->Question->read(null, $question_id);
```
... then it doesn't happen either.
Why?
See my code below, the Controller is "questionnaires\_controller".
```
function checkValidQuestionnaire($id)
{
$this->layout = 'questionnaire_frontend_layout';
if (!$id)
{
$id = $this->Session->read('Questionnaire.id');
}
if ($id)
{
$this->data = $this->Questionnaire->read(null, $id);
//echo "from ".$questionnaire['Questionnaire']['validFrom']." ".date("y.m.d");
//echo " - to ".$questionnaire['Questionnaire']['validTo']." ".date("y.m.d");
if ($this->data['Questionnaire']['isPublished'] != 1
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
)
{
$id = 0;
$this->flash(__('Ungültiges Quiz. Weiter zum Archiv...', true), array('action'=>'archive'));
}
}
else
{
$this->flash(__('Invalid Questionnaire', true), array('action'=>'intro'));
}
return $id;
}
function start($id = null) {
$this->log("start");
$id = $this->checkValidQuestionnaire($id);
//$questionnaire = $this->Questionnaire->read(null, $id);
$this->set('questionnaire', $this->data);
// reset flow-controlling session vars
$this->Session->write('Questionnaire',array('id' => $id));
$this->Session->write('Questionnaire'.$id.'currQuestion', null);
$this->Session->write('Questionnaire'.$id.'lastAnsweredQuestion', null);
$this->Session->write('Questionnaire'.$id.'correctAnswersNum', null);
$this->loadAdvertisement($id, 0);
$this->Session->write('Questionnaire'.$id.'previewMode', $this->params['named']['preview_mode']);
if (!$this->Session->read('Questionnaire'.$id.'previewMode'))
{
$questionnaire['Questionnaire']['participiantStartCount']++;
$this->Questionnaire->save($questionnaire);
}
}
function loadAdvertisement($questionnaire_id, $question_id)
{
//$questionnaire = array();
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
//$question = array();
$question = $this->Questionnaire->Question->read(null, $question_id);
if (isset($question['Question']['advertisement_id']) && $question['Question']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $question['Question']['advertisement_id']));
}
else if (isset($questionnaire['Questionnaire']['advertisement_id']) && $questionnaire['Questionnaire']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $questionnaire['Questionnaire']['advertisement_id']));
}
}
```
I really don't understand this... it don't think it's meant to be this way.
Any help would be greatly appreciated! :)
Regards,
Stu | Check your layout for non-existent links, for example a misconfigured link to favicon.ico will cause the controller action to be triggered for a second time. Make sure favicon.ico points towards the webroot rather than the local directory, or else requests will be generated for /controller/action/favicon.ico rather than /favicon.ico - and thus trigger your action.
This can also happen with images, stylesheets and javascript includes.
To counter check the $id is an int, then check to ensure $id exists as a primary key in the database before progressing on to any functionality. |
63,885 | <p>I am trying to create a rather simple effect on a set of images. When an image doesn't have the mouse over it, I'd like it to have a simple, gray border. When it does have an image over it, I'd like it to have a different, "selected", border.</p>
<p>The following CSS works great in Firefox:</p>
<pre class="lang-css prettyprint-override"><code>.myImage a img
{
border: 1px solid grey;
padding: 3px;
}
.myImage a:hover img
{
border: 3px solid blue;
padding: 1px;
}
</code></pre>
<p>However, in IE, borders do not appear when the mouse isn't hovered over the image. My Google-fu tells me there is a bug in IE that is causing this problem. Unfortunately, I can't seem to locate a way to fix that bug.</p>
| [
{
"answer_id": 64025,
"author": "hjdivad",
"author_id": 7538,
"author_profile": "https://Stackoverflow.com/users/7538",
"pm_score": 2,
"selected": true,
"text": "<p>Try using a different colour. I'm not sure IE understands 'grey' (instead, use 'gray').</p>\n"
},
{
"answer_id": 64098,
"author": "Eric DeLabar",
"author_id": 7556,
"author_profile": "https://Stackoverflow.com/users/7556",
"pm_score": 0,
"selected": false,
"text": "<p>IE has problems with the :hover pseudo-class on anything other than anchor elements so you need to change the element the hover is affecting to the anchor itself. So, if you added a class like \"image\" to your anchor and altered your markup to something like this:</p>\n\n<pre><code><div class=\"myImage\"><a href=\"...\" class=\"image\"><img .../></a></div>\n</code></pre>\n\n<p>You could then alter your CSS to look like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.myImage a.image\n{\n border: 1px solid grey;\n padding: 3px;\n}\n.myImage a.image:hover\n{\n border: 3px solid blue;\n padding: 1px;\n}\n</code></pre>\n\n<p>Which should mimic the desired effect by placing the border on the anchor instead of the image. Just as a note, you may need something like the following in your CSS to eliminate the image's default border:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.myImage a img {\n border: none;\n}\n</code></pre>\n"
},
{
"answer_id": 64134,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 1,
"selected": false,
"text": "<p>The following works in IE7, IE6, and FF3. The key was to use a:link:hover. IE6 turned the A element into a block element which is why I added the float stuff to shrink-wrap the contents.</p>\n\n<p>Note that it's in Standards mode. Dont' know what would happen in quirks mode.</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n <head>\n <title></title>\n <style type=\"text/css\">\n a, a:visited, a:link, a *, a:visited *, a:link * { border: 0; }\n .myImage a\n {\n float: left;\n clear: both;\n border: 0;\n margin: 3px;\n padding: 1px;\n }\n .myImage a:link:hover\n {\n float: left;\n clear: both;\n border: 3px solid blue;\n padding: 1px;\n margin: 0;\n display:block;\n }\n </style>\n </head>\n <body>\n <div class=\"myImage\"><a href=\"#\"><img src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\"></a></div>\n <div class=\"myImage\"><a href=\"#\"><img src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\"></a></div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 64149,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "<p>Try using the <em>background</em> instead of the <em>border</em>.</p>\n\n<p>It is not the same but it works in IE (take a look at the menu on my site: <a href=\"http://www.monex-finance.net/ENG/index.php\" rel=\"nofollow noreferrer\">www.monex-finance.net</a>).</p>\n"
},
{
"answer_id": 64150,
"author": "Jamie",
"author_id": 8391,
"author_profile": "https://Stackoverflow.com/users/8391",
"pm_score": 1,
"selected": false,
"text": "<p>In my experience IE doesn't work well with pseudo-classes. I think the most universal way to handle this is to use Javascript to apply the CSS class to the element.</p>\n\n<p>CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.standard_border\n{\n border: 1px solid grey;\n padding: 3px;\n}\n.hover_border\n{\n border: 3px solid blue;\n padding: 1px;\n}\n</code></pre>\n\n<p>Inline Javascript:</p>\n\n<pre><code><img src=\"image.jpg\" alt=\"\" class=\"standard_border\" onmouseover=\"this.className='hover_border'\" onmouseout=\"this.className='standard_border'\" />\n</code></pre>\n"
},
{
"answer_id": 64178,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code><!--[if lt IE 7]>\n<script src=\"http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js\" type=\"text/javascript\"></script>\n<![endif]-->\n</code></pre>\n\n<p>put that in your header, should fix some of the ie bugs.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7357/"
]
| I am trying to create a rather simple effect on a set of images. When an image doesn't have the mouse over it, I'd like it to have a simple, gray border. When it does have an image over it, I'd like it to have a different, "selected", border.
The following CSS works great in Firefox:
```css
.myImage a img
{
border: 1px solid grey;
padding: 3px;
}
.myImage a:hover img
{
border: 3px solid blue;
padding: 1px;
}
```
However, in IE, borders do not appear when the mouse isn't hovered over the image. My Google-fu tells me there is a bug in IE that is causing this problem. Unfortunately, I can't seem to locate a way to fix that bug. | Try using a different colour. I'm not sure IE understands 'grey' (instead, use 'gray'). |
63,897 | <p>I'm testing the VB function below that I got from a Google search. I plan to use it to generate hash codes for quick string comparison. However, there are occasions in which two different strings have the same hash code. For example, these strings</p>
<p>"122Gen 1 heap size (.NET CLR Memory w3wp):mccsmtpteweb025.20833333333333E-02"</p>
<p>"122Gen 2 heap size (.NET CLR Memory w3wp):mccsmtpteweb015.20833333333333E-02"</p>
<p>have the same hash code of 237117279.</p>
<p>Please tell me:
- What is wrong with the function?
- How can I fix it?</p>
<p>Thank you</p>
<p>martin</p>
<hr>
<pre><code>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As Any, src As Any, ByVal bytes As Long)
Private Function HashCode(Key As String) As Long
On Error GoTo ErrorGoTo
Dim lastEl As Long, i As Long
' copy ansi codes into an array of long'
lastEl = (Len(Key) - 1) \ 4
ReDim codes(lastEl) As Long
' this also converts from Unicode to ANSI'
CopyMemory codes(0), ByVal Key, Len(Key)
' XOR the ANSI codes of all characters'
For i = 0 To lastEl - 1
HashCode = HashCode Xor codes(i) 'Xor'
Next
ErrorGoTo:
Exit Function
End Function
</code></pre>
| [
{
"answer_id": 63929,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>Hash functions do not guarantee uniqueness of hash values. If the input value range (judging your sample strings) is larger than the output value range (eg 32 bit integer), then uniqueness is physically impossible.</p>\n"
},
{
"answer_id": 63933,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 3,
"selected": false,
"text": "<p>The two Strings have the same characters. (Note the '2' and the '1' that are flip-flopped)</p>\n\n<p>That is why the hash value is the same.</p>\n\n<p>Make sure that the hash function is taking into account the order of the characters.</p>\n"
},
{
"answer_id": 63936,
"author": "Magnus Akselvoll",
"author_id": 4683,
"author_profile": "https://Stackoverflow.com/users/4683",
"pm_score": 0,
"selected": false,
"text": "<p>I don't quite see the environment you work in. Is this .Net code? If you really want good hash codes, I would recommend looking into cryptographic hashes (proven algorithms) instead of trying to write your own.</p>\n\n<p>Btw, could you edit your post and paste the code in as a Code Sample (see toolbar)? This would make it easier to read.</p>\n"
},
{
"answer_id": 63958,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>\"Don't do that.\" </p>\n\n<p>Writing your own hash function is a big mistake, because your language certainly already has an implementation of SHA-1, which is a perfectly good hash function. If you only need 32 bits (instead of the 160 that SHA-1 provides), just use the last 32 bits of SHA-1. </p>\n"
},
{
"answer_id": 63964,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 4,
"selected": true,
"text": "<p>I'm betting there are more than just \"occasions\" when two strings generate the same hash using your function. In fact, it probably happens more often than you think.</p>\n\n<p>A few things to realize:</p>\n\n<p>First, there will be hash collisions. It happens. Even with really, really big spaces like MD5 (128 bits) there are still two strings that can generate the same resulting hash. You have to deal with those collisions by creating buckets.</p>\n\n<p>Second, a long integer isn't really a big hash space. You're going to get more collisions than you would if you used more bits.</p>\n\n<p>Thirdly, there are libraries available to you in Visual Basic (like .NET's <code>System.Security.Cryptography</code> namespace) that will do a much better job of hashing than most mere mortals.</p>\n"
},
{
"answer_id": 63967,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>No hash function can guarantee uniqueness. There are ~4 billion 32-bit integers, so even the best hash function will generate duplicates when presented with ~4 billion and 1 strings (and mostly likely long before).</p>\n\n<p>Moving to 64-bit hashes or even 128-bit hashes isn't really the solution, though it reduces the probability of a collision.</p>\n\n<p>If you want a better hash function you could look at the cryptographic hashes, but it would be better to reconsider you algorithm and decide if you can deal with the collisions some other way. </p>\n"
},
{
"answer_id": 63984,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx\" rel=\"nofollow noreferrer\">System.Security.Cryptography</a> namespace contains multiple classes which can do hashing for you (such as <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx\" rel=\"nofollow noreferrer\">MD5</a>) which will probably hash them better than you could yourself and will take much less effort.</p>\n\n<p>You don't always have to reinvent the wheel.</p>\n"
},
{
"answer_id": 63992,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 1,
"selected": false,
"text": "<p>Simple XOR is a bad hash: you'll find lots of strings which collide. The hash doesn't depend on the order of the letters in the string, for one thing.</p>\n\n<p>Try using the FNV hash <a href=\"http://isthe.com/chongo/tech/comp/fnv/\" rel=\"nofollow noreferrer\">http://isthe.com/chongo/tech/comp/fnv/</a></p>\n\n<p>This is really simple to implement. It shifts the hash code after each XOR, so the same letters in a different order will produce a different hash.</p>\n"
},
{
"answer_id": 64002,
"author": "ballpointpeon",
"author_id": 8269,
"author_profile": "https://Stackoverflow.com/users/8269",
"pm_score": 0,
"selected": false,
"text": "<p>There's a visual basic implementation of MD5 hashing here</p>\n\n<p><a href=\"http://www.bullzip.com/md5/vb/md5-visual-basic.htm\" rel=\"nofollow noreferrer\">http://www.bullzip.com/md5/vb/md5-visual-basic.htm</a></p>\n"
},
{
"answer_id": 64018,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I fixed the syntax highlighting for him. </p>\n\n<p>Also, for those who weren't sure about the environment or were suggesting a more-secure hash: it's Classic (pre-.Net) VB, because .Net would require parentheses for the the call to CopyMemory. </p>\n\n<p>IIRC, there aren't any secure hashes built in for Classic VB. There's not much out there on the web either, so this may be his best bet.</p>\n"
},
{
"answer_id": 64055,
"author": "user7936",
"author_id": 7936,
"author_profile": "https://Stackoverflow.com/users/7936",
"pm_score": 0,
"selected": false,
"text": "<p>This particular hash functions XORs all of the characters in a string. Unfortunately XOR is associative:</p>\n\n<pre><code>(a XOR b) XOR c = a XOR (b XOR c)\n</code></pre>\n\n<p>So any strings with the same input characters will result in the same hash code. The two strings provided are the same, except for the location of two characters, therefore they should have the same hashcode.</p>\n\n<p>You may need to find a better algorithm, MD5 would be a good choice.</p>\n"
},
{
"answer_id": 64158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The XOR operation is commutative; that is, when XORing all the chars in a string, the order of the chars does not matter. All anagrams of a string will produce the same XOR hash.</p>\n\n<p>In your example, your second string can be generated from your first by swapping the \"1\" after \"...Gen \" with the first \"2\" following it.</p>\n\n<p>There is nothing wrong with your function. All useful hashing functions will sometimes generate collisions, and your program must be prepared to resolve them.</p>\n\n<p>A collision occurs when an input hashes to a value already identified with an earlier input. If a hashing algorithm could not generate collisions, the hash values would need to be as large as the input values. Such a hashing algorithm would be of limited use compared to just storing the input values.</p>\n\n<p>-Al.</p>\n"
},
{
"answer_id": 64168,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>If the biggest problem is that it doesn't account for the position of the bytes, you could fix it like this:</p>\n\n<pre><code>Private Function HashCode(Key As String) As Long\n On Error GoTo ErrorGoTo\n\n Dim lastEl As Long, i As Long\n ' copy ansi codes into an array of long'\n lastEl = (Len(Key) - 1) \\ 4\n ReDim codes(lastEl) As Long\n ' this also converts from Unicode to ANSI'\n CopyMemory codes(0), ByVal Key, Len(Key)\n ' XOR the ANSI codes of all characters'\n\n For i = 0 To lastEl - 1\n HashCode = HashCode Xor (codes(i) + i) 'Xor'\n Next\n\nErrorGoTo:\n Exit Function\nEnd Function\n</code></pre>\n\n<p>The only difference is that it adds the characters position to it's byte value before the XOR.</p>\n"
},
{
"answer_id": 64737,
"author": "botismarius",
"author_id": 4528,
"author_profile": "https://Stackoverflow.com/users/4528",
"pm_score": 1,
"selected": false,
"text": "<p>Hash functions are not meant to return distinct values for distinct strings. However, a good hash function should return different values for strings that look alike. Hash functions are used to search for many reasons, including searching into a large collection. If the hash function is good and if it returns values from the range [0,N-1], then a large collection of M objects will be divide in N collections, each one having about M/N elements. This way, you need to search only in an array of M/N elements instead of searching in an array of M elements.</p>\n\n<p>But, if you only have 2 strings, it is <strong>not</strong> faster to compute the hash value for those! It is <strong>better</strong> to just compare the two strings.</p>\n\n<p>An interresing hash function could be:</p>\n\n<pre><code>\n\n unsigned int hash(const char* name) {\n unsigned mul=1;\n unsigned val=0;\n while(name[0]!=0) {\n val+=mul*((unsigned)name[0]);\n mul*=7; //you could use an arbitrary prime number, but test the hash dispersion afterwards\n name++;\n }\n return val;\n }\n\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
]
| I'm testing the VB function below that I got from a Google search. I plan to use it to generate hash codes for quick string comparison. However, there are occasions in which two different strings have the same hash code. For example, these strings
"122Gen 1 heap size (.NET CLR Memory w3wp):mccsmtpteweb025.20833333333333E-02"
"122Gen 2 heap size (.NET CLR Memory w3wp):mccsmtpteweb015.20833333333333E-02"
have the same hash code of 237117279.
Please tell me:
- What is wrong with the function?
- How can I fix it?
Thank you
martin
---
```
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As Any, src As Any, ByVal bytes As Long)
Private Function HashCode(Key As String) As Long
On Error GoTo ErrorGoTo
Dim lastEl As Long, i As Long
' copy ansi codes into an array of long'
lastEl = (Len(Key) - 1) \ 4
ReDim codes(lastEl) As Long
' this also converts from Unicode to ANSI'
CopyMemory codes(0), ByVal Key, Len(Key)
' XOR the ANSI codes of all characters'
For i = 0 To lastEl - 1
HashCode = HashCode Xor codes(i) 'Xor'
Next
ErrorGoTo:
Exit Function
End Function
``` | I'm betting there are more than just "occasions" when two strings generate the same hash using your function. In fact, it probably happens more often than you think.
A few things to realize:
First, there will be hash collisions. It happens. Even with really, really big spaces like MD5 (128 bits) there are still two strings that can generate the same resulting hash. You have to deal with those collisions by creating buckets.
Second, a long integer isn't really a big hash space. You're going to get more collisions than you would if you used more bits.
Thirdly, there are libraries available to you in Visual Basic (like .NET's `System.Security.Cryptography` namespace) that will do a much better job of hashing than most mere mortals. |
63,950 | <p>I program with Emacs on Ubuntu (Hardy Heron at the moment), and I like the default text coloration in the Emacs GUI. However, the default text coloration when Emacs is run in the terminal is different and garish.</p>
<p>How do I make the colors in the terminal match the colors in the GUI?</p>
| [
{
"answer_id": 63965,
"author": "HD.",
"author_id": 6525,
"author_profile": "https://Stackoverflow.com/users/6525",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think that is possible in such a general way. With the terminal you are usually bound to some pre-defined colors (with things like gnome-terminal you can adjust these colors -- but you are still stuck to a predefined, limited number of colors).</p>\n"
},
{
"answer_id": 63990,
"author": "pupeno",
"author_id": 6068,
"author_profile": "https://Stackoverflow.com/users/6068",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if it is possible, as the GUI may have more capabilities than the terminal (yes, I've seen GUI terminals with only 16 colors very recently). It may depend on how the terminal is set. At any rate I would play with <a href=\"http://www.emacswiki.org/cgi-bin/wiki?ColorTheme\" rel=\"nofollow noreferrer\">Color Theme</a>.</p>\n\n<p>Anyway, why are you using Emacs in both, the terminal and the GUI? Generally people find one or the other appealing and use only that one. If you are using Emacs remotely, maybe you want to run it locally and use <a href=\"http://www.gnu.org/software/tramp/\" rel=\"nofollow noreferrer\">Tramp</a> to open files remotely, or as root.</p>\n"
},
{
"answer_id": 64585,
"author": "insipid",
"author_id": 8649,
"author_profile": "https://Stackoverflow.com/users/8649",
"pm_score": 7,
"selected": false,
"text": "<p>You don't have to be stuck to your terminal's default 16 (or fewer) colours. Modern terminals will support 256 colours (which will get you pretty close to your GUI look).</p>\n\n<p>Unfortunately, getting your terminal to support 256 colours is the tricky part, and varies from term to term. <a href=\"http://www.xvx.ca/~awg/emacs-colors-howto.txt\" rel=\"noreferrer\">This page</a> helped me out a lot (but it <em>is</em> out of date; I've definitely gotten 256 colours working in gnome-terminal and xfce4-terminal; but you may have to build them from source.) </p>\n\n<p>Once you've got your terminal happily using 256 colours, the magic invocation is setting your terminal type to \"xterm-256color\" before you invoke emacs, e.g.:</p>\n\n<pre><code>env TERM=xterm-256color emacs -nw\n</code></pre>\n\n<p>Or, you can set TERM in your <code>.bashrc</code> file:</p>\n\n<pre><code>export TERM=xterm-256color\n</code></pre>\n\n<p>You can check if it's worked in emacs by doing <code>M-x list-colors-display</code>, which will show you either 16, or all 256 glorious colours.</p>\n\n<p>If it works, then look at <code>color-theme</code> like someone else suggested.</p>\n\n<p>(You'll probably get frustrated at some point; god knows I do every time I try to do something similar. But stick with it; it's worth it.)</p>\n"
},
{
"answer_id": 40964993,
"author": "Ali Zand",
"author_id": 1499655,
"author_profile": "https://Stackoverflow.com/users/1499655",
"pm_score": 0,
"selected": false,
"text": "<p>A little late response but I had the problem with the black background showing up as grey. I fixed it by playing around with palette.</p>\n\n<p>edit > Profile Preferences > Color > Palette</p>\n"
},
{
"answer_id": 60620286,
"author": "Arseniy Alekseyev",
"author_id": 8294974,
"author_profile": "https://Stackoverflow.com/users/8294974",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to get pretty close with emacs 26.</p>\n\n<p>I followed the Emacs FAQ to get 24-bit colors working:\n<a href=\"https://www.gnu.org/software/emacs/manual/html_mono/efaq.html#Colors-on-a-TTY\" rel=\"nofollow noreferrer\">https://www.gnu.org/software/emacs/manual/html_mono/efaq.html#Colors-on-a-TTY</a></p>\n\n<p>And then I changed the xterm-standard-colors variable:</p>\n\n<pre><code>(set 'xterm-standard-colors\n '((\"black\" 0 ( 0 0 0))\n (\"red\" 1 (255 0 0))\n (\"green\" 2 ( 0 255 0))\n (\"yellow\" 3 (255 255 0))\n (\"blue\" 4 ( 0 0 255))\n (\"magenta\" 5 (255 0 255))\n (\"cyan\" 6 ( 0 255 255))\n (\"white\" 7 (255 255 255))\n (\"brightblack\" 8 (127 127 127))\n (\"brightred\" 9 (255 0 0))\n (\"brightgreen\" 10 ( 0 255 0))\n (\"brightyellow\" 11 (255 255 0))\n (\"brightblue\" 12 (92 92 255))\n (\"brightmagenta\" 13 (255 0 255))\n (\"brightcyan\" 14 ( 0 255 255))\n (\"brightwhite\" 15 (255 255 255)))\n )\n</code></pre>\n\n<p>(I did not change the \"bright*\" colors because I don't use them, and they don't seem to be available in <code>list-colors-display</code> in X11 emacs, anyway)</p>\n\n<p>With those two changes, colors look pretty much identical between X11 and terminal for me.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I program with Emacs on Ubuntu (Hardy Heron at the moment), and I like the default text coloration in the Emacs GUI. However, the default text coloration when Emacs is run in the terminal is different and garish.
How do I make the colors in the terminal match the colors in the GUI? | You don't have to be stuck to your terminal's default 16 (or fewer) colours. Modern terminals will support 256 colours (which will get you pretty close to your GUI look).
Unfortunately, getting your terminal to support 256 colours is the tricky part, and varies from term to term. [This page](http://www.xvx.ca/~awg/emacs-colors-howto.txt) helped me out a lot (but it *is* out of date; I've definitely gotten 256 colours working in gnome-terminal and xfce4-terminal; but you may have to build them from source.)
Once you've got your terminal happily using 256 colours, the magic invocation is setting your terminal type to "xterm-256color" before you invoke emacs, e.g.:
```
env TERM=xterm-256color emacs -nw
```
Or, you can set TERM in your `.bashrc` file:
```
export TERM=xterm-256color
```
You can check if it's worked in emacs by doing `M-x list-colors-display`, which will show you either 16, or all 256 glorious colours.
If it works, then look at `color-theme` like someone else suggested.
(You'll probably get frustrated at some point; god knows I do every time I try to do something similar. But stick with it; it's worth it.) |
63,974 | <p>In my application I have a DataGridView control that displays data for the selected object. When I select a different object (in a combobox above), I need to update the grid. Unfortunately different objects have completely different data, even different columns, so I need to clear all the existing data and columns, create new columns and add all the rows. When this is done, the whole control flickers horribly and it takes ages. Is there a generic way to get the control in an update state so it doesn't repaint itself, and then repaint it after I finish all the updates? </p>
<p>It is certainly possible with TreeViews:</p>
<pre><code>myTreeView.BeginUpdate();
try
{
//do the updates
}
finally
{
myTreeView.EndUpdate();
}
</code></pre>
<p>Is there a generic way to do this with other controls, DataGridView in particular?</p>
<p>UPDATE: Sorry, I am not sure I was clear enough. I see the "flickering", because after single edit the control gets repainted on the screen, so you can see the scroll bar shrinking, etc.</p>
| [
{
"answer_id": 63986,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like you want double-buffering:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/graphics/DoubleBuffering.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/graphics/DoubleBuffering.aspx</a></p>\n\n<p>Although this is mainly used for individual controls, you can implement this in your Windows Forms control or Form.</p>\n"
},
{
"answer_id": 64007,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunatly, I think that thins might just be a by-product of the .net framework. I am experiencing similar flickering albeit with custom controls. Many of the reference material I have read indicates this, alongside the fact the the double buffering method failed to remove any flickering for me.</p>\n"
},
{
"answer_id": 64182,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": false,
"text": "<p>Double buffering won't help here since that only double buffers paint operations, the flickering the OP is seeing is the result of multiple paint operations:</p>\n\n<ul>\n<li>Clear control contents -> repaint</li>\n<li>Clear columns -> repaint</li>\n<li>Populate new columns -> repaint</li>\n<li>Add rows -> repaint</li>\n</ul>\n\n<p>so that's four repaints to update the control, hence the flicker. Unfortunately, not all the standard controls have the BeginUpdate/EndUpdate which would remove all the repaint calls until the EndUpdate is called. Here's what you can do:</p>\n\n<ol>\n<li>Have a different control for each data set and Show/Hide the controls,</li>\n<li>Remove the control from its parent, update and then add the control again,</li>\n<li>Write your own control.</li>\n</ol>\n\n<p>Options 1 and 2 would still flicker a bit.</p>\n\n<p>On the .Net GUI program I'm working on, I created a set of custom controls that eliminated all flicker. </p>\n"
},
{
"answer_id": 65578,
"author": "Ken Wootton",
"author_id": 7357,
"author_profile": "https://Stackoverflow.com/users/7357",
"pm_score": 3,
"selected": false,
"text": "<p>The .NET control supports the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout.aspx\" rel=\"noreferrer\">SuspendLayout</a> and <a href=\"http://msdn.microsoft.com/en-us/library/y53zat12.aspx\" rel=\"noreferrer\">ResumeLayout</a> methods. Pick the appropriate parent control (i.e. the control that hosts the controls you want to populate) and do something like the following:</p>\n\n<pre><code>this.SuspendLayout();\n\n// Do something interesting.\n\nthis.ResumeLayout();\n</code></pre>\n"
},
{
"answer_id": 70281,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": true,
"text": "<p>Rather than adding the rows of the data grid one at a time, use the <code>DataGridView.Rows.AddRange</code> method to add all the rows at once. That should only update the display once. There's also a <code>DataGridView.Columns.AddRange</code> to do the same for the columns.</p>\n"
},
{
"answer_id": 212197,
"author": "Brian Hasden",
"author_id": 28926,
"author_profile": "https://Stackoverflow.com/users/28926",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me. </p>\n\n<p><a href=\"http://www.syncfusion.com/faq/windowsforms/search/558.aspx\" rel=\"nofollow noreferrer\">http://www.syncfusion.com/faq/windowsforms/search/558.aspx</a></p>\n\n<p>Basically it involves deriving from the desired control and setting the following styles.</p>\n\n<pre><code>SetStyle(ControlStyles.UserPaint, true);\nSetStyle(ControlStyles.AllPaintingInWmPaint, true); \nSetStyle(ControlStyles.DoubleBuffer, true); \n</code></pre>\n"
},
{
"answer_id": 10887964,
"author": "Jon",
"author_id": 1435997,
"author_profile": "https://Stackoverflow.com/users/1435997",
"pm_score": 3,
"selected": false,
"text": "<p>People seem to forget a simple fix for this:</p>\n\n<pre><code>Object.Visible = false;\n\n//do update work\n\nObject.Visible = true;\n</code></pre>\n\n<p>I know it seems weird, but that works. When the object is not visible, it won't redraw itself. You still, however, need to do the <code>begin</code> and <code>end</code> update.</p>\n"
},
{
"answer_id": 45604941,
"author": "Ramgy Borja",
"author_id": 7978302,
"author_profile": "https://Stackoverflow.com/users/7978302",
"pm_score": 0,
"selected": false,
"text": "<p>You may also try this, its work.</p>\n\n<pre><code>public static void DoubleBuffered(Control formControl, bool setting)\n{\n Type conType = formControl.GetType();\n PropertyInfo pi = conType.GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic);\n pi.SetValue(formControl, setting, null);\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
]
| In my application I have a DataGridView control that displays data for the selected object. When I select a different object (in a combobox above), I need to update the grid. Unfortunately different objects have completely different data, even different columns, so I need to clear all the existing data and columns, create new columns and add all the rows. When this is done, the whole control flickers horribly and it takes ages. Is there a generic way to get the control in an update state so it doesn't repaint itself, and then repaint it after I finish all the updates?
It is certainly possible with TreeViews:
```
myTreeView.BeginUpdate();
try
{
//do the updates
}
finally
{
myTreeView.EndUpdate();
}
```
Is there a generic way to do this with other controls, DataGridView in particular?
UPDATE: Sorry, I am not sure I was clear enough. I see the "flickering", because after single edit the control gets repainted on the screen, so you can see the scroll bar shrinking, etc. | Rather than adding the rows of the data grid one at a time, use the `DataGridView.Rows.AddRange` method to add all the rows at once. That should only update the display once. There's also a `DataGridView.Columns.AddRange` to do the same for the columns. |
63,995 | <p>I would like to give a class a unique ID every time a new one is instantiated. For example with a class named Foo i would like to be able to do the following</p>
<pre><code>dim a as New Foo()
dim b as New Foo()
</code></pre>
<p>and a would get a unique id and b would get a unique ID. The ids only have to be unique over run time so i would just like to use an integer. I have found a way to do this BUT (and heres the caveat) I do NOT want to be able to change the ID from anywhere. My current idea for a way to implement this is the following:</p>
<pre><code>Public Class test
Private Shared ReadOnly _nextId As Integer
Private ReadOnly _id As Integer
Public Sub New()
_nextId = _nextId + 1
_id = _nextId
End Sub
End Class
</code></pre>
<p>However this will not compile because it throws an error on
_nextId = _nextId + 1
I don't see why this would be an error (because _Id is also readonly you're supposed to be able to change a read only variable in the constructor.) I think this has something to do with it being shared also. Any solution (hopefully not kludgy hehe) or an explanation of why this won't work will be accepted. The important part is i want both of the variables (or if there is a way to only have one that would even be better but i don't think that is possible) to be immutable after the object is initialized. Thanks!</p>
| [
{
"answer_id": 64015,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": -1,
"selected": false,
"text": "<p>It's likely throwing an error because you're never initializing _nextId to anything. It needs to have an initial value before you can safely add 1 to it.</p>\n"
},
{
"answer_id": 64033,
"author": "Magnus Akselvoll",
"author_id": 4683,
"author_profile": "https://Stackoverflow.com/users/4683",
"pm_score": 0,
"selected": false,
"text": "<p>It throws an error because _nextId is ReadOnly. Remove that.</p>\n\n<p><strong>Edit:</strong>\nAs you say, ReadOnly variables can be changed in a constructor, but not if they are Shared. Those can only be changed in shared constructors. Example:</p>\n\n<pre><code>Shared Sub New()\n _nextId = 0\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 64090,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>This design is vulnerable to multithreading issues. I'd strongly suggest using Guids for your IDs (Guid.NewGuid()). If you absolutely must use ints, check out the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx\" rel=\"nofollow noreferrer\">Interlocked</a> class. You can wrap all incrementing and Id logic up in a base class so that you're only accessing the ID generator in one location.</p>\n"
},
{
"answer_id": 64107,
"author": "Remi Despres-Smyth",
"author_id": 8169,
"author_profile": "https://Stackoverflow.com/users/8169",
"pm_score": 1,
"selected": false,
"text": "<p>ReadOnly variables must be initialized during object construction, and then cannot be updated afterwards. This won't compile because you can't increment _nextId for that reason. (Shared ReadOnly variables can only be assigned in Shared constructors.)</p>\n\n<p>As such, if you remove the ReadOnly modifier on the definition of _nextId, you should be ok.</p>\n"
},
{
"answer_id": 64108,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I'd do it like this.</p>\n\n<pre><code>Public MustInherit Class Unique\n Private _UID As Guid = Guid.NewGuid()\n Public ReadOnly Property UID() As Guid\n Get\n Return _UID\n End Get\n End Property\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 64115,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 0,
"selected": false,
"text": "<p>The shared integer shouldn't be read-only. A field marked <code>readonly</code> can only ever be assigned once and must be assigned before the constructor exits.</p>\n\n<p>As the shared field is private, there is no danger that the field will be changed by anything external anyway.</p>\n"
},
{
"answer_id": 64199,
"author": "Magnus Akselvoll",
"author_id": 4683,
"author_profile": "https://Stackoverflow.com/users/4683",
"pm_score": 3,
"selected": true,
"text": "<p>Consider the following code:</p>\n\n<pre><code>Public Class Foo \n Private ReadOnly _fooId As FooId \n\n Public Sub New() \n _fooId = New FooId() \n End Sub \n\n Public ReadOnly Property Id() As Integer \n Get \n Return _fooId.Id \n End Get \n End Property \nEnd Class \n\nPublic NotInheritable Class FooId \n Private Shared _nextId As Integer \n Private ReadOnly _id As Integer \n\n Shared Sub New() \n _nextId = 0 \n End Sub \n\n Public Sub New() \n SyncLock GetType(FooId) \n _id = System.Math.Max(System.Threading.Interlocked.Increment(_nextId),_nextId - 1) \n End SyncLock \n End Sub \n\n Public ReadOnly Property Id() As Integer \n Get \n Return _id \n End Get \n End Property \nEnd Class \n</code></pre>\n\n<p>Instead of storing an int inside Foo, you store an object of type FooId. This way you have full control over what can and cannot be done to the id.</p>\n\n<p>To protect our FooId against manipulation, it cannot be inherited, and has no methods except the constructor and a getter for the int. Furthermore, the variable _nextId is private to FooId and cannot be changed from the outside. Finally the SyncLock inside the constructor of FooId makes sure that it is never executed in parallell, guaranteeing that all IDs inside a process are unique (until you hit MaxInt :)).</p>\n"
},
{
"answer_id": 64261,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 0,
"selected": false,
"text": "<p>You said that \"this will not compile because it throws an error\" but never said what that error is.</p>\n\n<p>A shared variable is static, so there is only a single copy of it in memory that is accessible to all instances. You can only modify a static readonly (Shared ReadOnly) from a static (Shared) constructor (New()) so you probably want something like this:</p>\n\n<pre><code>Public Class test\n Private Shared ReadOnly _nextId As Integer\n Private ReadOnly _id As Integer\n\n Public Shared Sub New()\n _nextId = _nextId + 1\n End Sub\n\n Public Sub New()\n _id = _nextId\n End Sub\nEnd Class\n</code></pre>\n\n<p>(I think that's the right syntax in VB.) In C# it would look like this:</p>\n\n<pre><code>public class Test\n{\n private static readonly int _nextId;\n private readonly int _id;\n\n static Test()\n {\n _nextId++;\n }\n\n public Test()\n {\n _id = _nextId;\n }\n</code></pre>\n\n<p>}</p>\n\n<p>The only problem here is that the static constructor is only going to be called once, so _nextId is only going to be incremented one time. Since it is a static readonly variable you will only be able to initialize it the static constructor, so your new instances aren't going to be getting an incremented _id field like you want.</p>\n\n<p>What is the problem you are trying to solve with this scenario? Do these unique IDs have to be integer values? If not, you could use a Guid and in your contructor call Guid.</p>\n"
},
{
"answer_id": 64565,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 0,
"selected": false,
"text": "<p>I posted a <a href=\"https://stackoverflow.com/questions/41792/instance-constructor-sets-a-static-member-is-it-thread-safe\">similar question</a> that focused on the multithreading issues of setting a unique instance id. You can review it for details.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8054/"
]
| I would like to give a class a unique ID every time a new one is instantiated. For example with a class named Foo i would like to be able to do the following
```
dim a as New Foo()
dim b as New Foo()
```
and a would get a unique id and b would get a unique ID. The ids only have to be unique over run time so i would just like to use an integer. I have found a way to do this BUT (and heres the caveat) I do NOT want to be able to change the ID from anywhere. My current idea for a way to implement this is the following:
```
Public Class test
Private Shared ReadOnly _nextId As Integer
Private ReadOnly _id As Integer
Public Sub New()
_nextId = _nextId + 1
_id = _nextId
End Sub
End Class
```
However this will not compile because it throws an error on
\_nextId = \_nextId + 1
I don't see why this would be an error (because \_Id is also readonly you're supposed to be able to change a read only variable in the constructor.) I think this has something to do with it being shared also. Any solution (hopefully not kludgy hehe) or an explanation of why this won't work will be accepted. The important part is i want both of the variables (or if there is a way to only have one that would even be better but i don't think that is possible) to be immutable after the object is initialized. Thanks! | Consider the following code:
```
Public Class Foo
Private ReadOnly _fooId As FooId
Public Sub New()
_fooId = New FooId()
End Sub
Public ReadOnly Property Id() As Integer
Get
Return _fooId.Id
End Get
End Property
End Class
Public NotInheritable Class FooId
Private Shared _nextId As Integer
Private ReadOnly _id As Integer
Shared Sub New()
_nextId = 0
End Sub
Public Sub New()
SyncLock GetType(FooId)
_id = System.Math.Max(System.Threading.Interlocked.Increment(_nextId),_nextId - 1)
End SyncLock
End Sub
Public ReadOnly Property Id() As Integer
Get
Return _id
End Get
End Property
End Class
```
Instead of storing an int inside Foo, you store an object of type FooId. This way you have full control over what can and cannot be done to the id.
To protect our FooId against manipulation, it cannot be inherited, and has no methods except the constructor and a getter for the int. Furthermore, the variable \_nextId is private to FooId and cannot be changed from the outside. Finally the SyncLock inside the constructor of FooId makes sure that it is never executed in parallell, guaranteeing that all IDs inside a process are unique (until you hit MaxInt :)). |
63,998 | <p>Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.</p>
<p>Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden features of C#</a></li>
<li><a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden features of Java</a></li>
<li><a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript">Hidden features of JavaScript</a></li>
<li><a href="https://stackoverflow.com/questions/709679/hidden-features-of-ruby-on-rails">Hidden features of Ruby on Rails</a></li>
<li><a href="https://stackoverflow.com/questions/101268/hidden-features-of-python">Hidden features of Python</a></li>
</ul>
<p>(Please, just <em>one</em> hidden feature per answer.)</p>
<p>Thank you</p>
| [
{
"answer_id": 64080,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 5,
"selected": false,
"text": "<p>I find using the <strong>define_method</strong> command to dynamically generate methods to be quite interesting and not as well known. For example:</p>\n\n<pre><code>((0..9).each do |n|\n define_method \"press_#{n}\" do\n @number = @number.to_i * 10 + n\n end\n end\n</code></pre>\n\n<p>The above code uses the 'define_method' command to dynamically create the methods \"press1\" through \"press9.\" Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.</p>\n"
},
{
"answer_id": 64099,
"author": "CodingWithoutComments",
"author_id": 25,
"author_profile": "https://Stackoverflow.com/users/25",
"pm_score": 3,
"selected": false,
"text": "<p>The <strong>send()</strong> method is a general-purpose method that can be used on any Class or Object in Ruby. If not overridden, send() accepts a string and calls the name of the method whose string it is passed. For example, if the user clicks the “Clr” button, the ‘press_clear’ string will be sent to the send() method and the ‘press_clear’ method will be called. The send() method allows for a fun and dynamic way to call functions in Ruby.</p>\n\n<pre><code> %w(7 8 9 / 4 5 6 * 1 2 3 - 0 Clr = +).each do |btn|\n button btn, :width => 46, :height => 46 do\n method = case btn\n when /[0-9]/: 'press_'+btn\n when 'Clr': 'press_clear'\n when '=': 'press_equals'\n when '+': 'press_add'\n when '-': 'press_sub'\n when '*': 'press_times'\n when '/': 'press_div'\n end\n\n number.send(method)\n number_field.replace strong(number)\n end\n end\n</code></pre>\n\n<p>I talk more about this feature in <a href=\"http://www.codingwithoutcomments.com/2008/09/01/blogging-shoes-the-simple-calc-application/\" rel=\"nofollow noreferrer\">Blogging Shoes: The Simple-Calc Application</a></p>\n"
},
{
"answer_id": 64124,
"author": "manveru",
"author_id": 8367,
"author_profile": "https://Stackoverflow.com/users/8367",
"pm_score": 5,
"selected": false,
"text": "<p>Download Ruby 1.9 source, and issue <code>make golf</code>, then you can do things like this:</p>\n\n<pre><code>make golf\n\n./goruby -e 'h'\n# => Hello, world!\n\n./goruby -e 'p St'\n# => StandardError\n\n./goruby -e 'p 1.tf'\n# => 1.0\n\n./goruby19 -e 'p Fil.exp(\".\")'\n\"/home/manveru/pkgbuilds/ruby-svn/src/trunk\"\n</code></pre>\n\n<p>Read the <code>golf_prelude.c</code> for more neat things hiding away.</p>\n"
},
{
"answer_id": 64427,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 4,
"selected": false,
"text": "<p>use anything that responds to <code>===(obj)</code> for case comparisons:</p>\n\n<pre><code>case foo\nwhen /baz/\n do_something_with_the_string_matching_baz\nwhen 12..15\n do_something_with_the_integer_between_12_and_15\nwhen lambda { |x| x % 5 == 0 }\n # only works in Ruby 1.9 or if you alias Proc#call as Proc#===\n do_something_with_the_integer_that_is_a_multiple_of_5\nwhen Bar\n do_something_with_the_instance_of_Bar\nwhen some_object\n do_something_with_the_thing_that_matches_some_object\nend\n</code></pre>\n\n<p><code>Module</code> (and thus <code>Class</code>), <code>Regexp</code>, <code>Date</code>, and many other classes define an instance method :===(other), and can all be used.</p>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/questions/63998/hidden-features-of-ruby#65015\">Farrel</a> for the reminder of <code>Proc#call</code> being aliased as <code>Proc#===</code> in Ruby 1.9.</p>\n"
},
{
"answer_id": 64458,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 6,
"selected": false,
"text": "<p>Peter Cooper has a <a href=\"http://www.rubyinside.com/21-ruby-tricks-902.html\" rel=\"nofollow noreferrer\">good list</a> of Ruby tricks. Perhaps my favorite of his is allowing both single items and collections to be enumerated. (That is, treat a non-collection object as a collection containing just that object.) It looks like this:</p>\n\n<pre><code>[*items].each do |item|\n # ...\nend\n</code></pre>\n"
},
{
"answer_id": 64502,
"author": "Scott Holden",
"author_id": 8588,
"author_profile": "https://Stackoverflow.com/users/8588",
"pm_score": 3,
"selected": false,
"text": "<p>How about opening a file based on ARGV[0]?</p>\n\n<p><code>readfile.rb:</code></p>\n\n<pre><code>$<.each_line{|l| puts l}\n\nruby readfile.rb testfile.txt\n</code></pre>\n\n<p>It's a great shortcut for writing one-off scripts. There's a whole mess of pre-defined variables that most people don't know about. Use them wisely (read: don't litter a code base you plan to maintain with them, it can get messy).</p>\n"
},
{
"answer_id": 64956,
"author": "TALlama",
"author_id": 5657,
"author_profile": "https://Stackoverflow.com/users/5657",
"pm_score": 4,
"selected": false,
"text": "<p>A lot of the magic you see in Rubyland has to do with metaprogramming, which is simply writing code that writes code for you. Ruby's <code>attr_accessor</code>, <code>attr_reader</code>, and <code>attr_writer</code> are all simple metaprogramming, in that they create two methods in one line, following a standard pattern. Rails does a whole lot of metaprogramming with their relationship-management methods like <code>has_one</code> and <code>belongs_to</code>.</p>\n\n<p>But it's pretty simple to create your own metaprogramming tricks using <code>class_eval</code> to execute dynamically-written code.</p>\n\n<p>The following example allows a wrapper object to forwards certain methods along to an internal object:</p>\n\n<pre><code>class Wrapper\n attr_accessor :internal\n\n def self.forwards(*methods)\n methods.each do |method|\n define_method method do |*arguments, &block|\n internal.send method, *arguments, &block\n end\n end\n end\n\n forwards :to_i, :length, :split\nend\n\nw = Wrapper.new\nw.internal = \"12 13 14\"\nw.to_i # => 12\nw.length # => 8\nw.split('1') # => [\"\", \"2 \", \"3 \", \"4\"]\n</code></pre>\n\n<p>The method <code>Wrapper.forwards</code> takes symbols for the names of methods and stores them in the <code>methods</code> array. Then, for each of those given, we use <code>define_method</code> to create a new method whose job it is to send the message along, including all arguments and blocks.</p>\n\n<p>A great resource for metaprogramming issues is <a href=\"http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html\" rel=\"noreferrer\">Why the Lucky Stiff's \"Seeing Metaprogramming Clearly\"</a>.</p>\n"
},
{
"answer_id": 65015,
"author": "Farrel",
"author_id": 7889,
"author_profile": "https://Stackoverflow.com/users/7889",
"pm_score": 6,
"selected": false,
"text": "<p>From Ruby 1.9 Proc#=== is an alias to Proc#call, which means Proc objects can be used in case statements like so:</p>\n\n<pre><code>def multiple_of(factor)\n Proc.new{|product| product.modulo(factor).zero?}\nend\n\ncase number\n when multiple_of(3)\n puts \"Multiple of 3\"\n when multiple_of(7)\n puts \"Multiple of 7\"\nend\n</code></pre>\n"
},
{
"answer_id": 68037,
"author": "olegueret",
"author_id": 10421,
"author_profile": "https://Stackoverflow.com/users/10421",
"pm_score": 3,
"selected": false,
"text": "<p>Fool some class or module telling it has required something that it really hasn't required:</p>\n\n<pre><code>$\" << \"something\"\n</code></pre>\n\n<p>This is useful for example when requiring A that in turns requires B but we don't need B in our code (and A won't use it either through our code):</p>\n\n<p>For example, Backgroundrb's <code>bdrb_test_helper requires</code> <code>'test/spec'</code>, but you don't use it at all, so in your code:</p>\n\n<pre><code>$\" << \"test/spec\"\nrequire File.join(File.dirname(__FILE__) + \"/../bdrb_test_helper\")\n</code></pre>\n"
},
{
"answer_id": 68205,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 5,
"selected": false,
"text": "<p>The Symbol#to_proc function that Rails provides is really cool. </p>\n\n<p>Instead of</p>\n\n<pre><code>Employee.collect { |emp| emp.name }\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>Employee.collect(&:name)\n</code></pre>\n"
},
{
"answer_id": 69091,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Warning: this item was voted #1 <strong><em>Most Horrendous Hack of 2008</em></strong>, so use with care. Actually, avoid it like the plague, but it is most certainly Hidden Ruby.</p>\n\n<h2>Superators Add New Operators to Ruby</h2>\n\n<p>Ever want a super-secret handshake operator for some unique operation in your code? Like playing code golf? Try operators like\n -~+~-\nor\n <---\nThat last one is used in the examples for reversing the order of an item.</p>\n\n<p>I have nothing to do with the <a href=\"http://jicksta.com/posts/superators-add-new-operators-to-ruby\" rel=\"nofollow noreferrer\">Superators Project</a> beyond admiring it.</p>\n"
},
{
"answer_id": 70116,
"author": "Farrel",
"author_id": 7889,
"author_profile": "https://Stackoverflow.com/users/7889",
"pm_score": 5,
"selected": false,
"text": "<p>Another fun addition in 1.9 Proc functionality is Proc#curry which allows you to turn a Proc accepting n arguments into one accepting n-1. Here it is combined with the Proc#=== tip I mentioned above:</p>\n\n<pre><code>it_is_day_of_week = lambda{ |day_of_week, date| date.wday == day_of_week }\nit_is_saturday = it_is_day_of_week.curry[6]\nit_is_sunday = it_is_day_of_week.curry[0]\n\ncase Time.now\nwhen it_is_saturday\n puts \"Saturday!\"\nwhen it_is_sunday\n puts \"Sunday!\"\nelse\n puts \"Not the weekend\"\nend\n</code></pre>\n"
},
{
"answer_id": 70203,
"author": "astronautism",
"author_id": 11424,
"author_profile": "https://Stackoverflow.com/users/11424",
"pm_score": 6,
"selected": false,
"text": "<p>Don't know how hidden this is, but I've found it useful when needing to make a Hash out of a one-dimensional array:</p>\n\n<pre><code>fruit = [\"apple\",\"red\",\"banana\",\"yellow\"]\n=> [\"apple\", \"red\", \"banana\", \"yellow\"]\n\nHash[*fruit] \n=> {\"apple\"=>\"red\", \"banana\"=>\"yellow\"}\n</code></pre>\n"
},
{
"answer_id": 70286,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 6,
"selected": false,
"text": "<p>One trick I like is to use the splat (<code>*</code>) expander on objects other than Arrays. Here's an example on a regular expression match:</p>\n\n<pre><code>match, text, number = *\"Something 981\".match(/([A-z]*) ([0-9]*)/)\n</code></pre>\n\n<p>Other examples include:</p>\n\n<pre><code>a, b, c = *('A'..'Z')\n\nJob = Struct.new(:name, :occupation)\ntom = Job.new(\"Tom\", \"Developer\")\nname, occupation = *tom\n</code></pre>\n"
},
{
"answer_id": 85310,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 6,
"selected": false,
"text": "<p>Another tiny feature - convert a <code>Fixnum</code> into any base up to 36:</p>\n\n<pre><code>>> 1234567890.to_s(2)\n=> \"1001001100101100000001011010010\"\n\n>> 1234567890.to_s(8)\n=> \"11145401322\"\n\n>> 1234567890.to_s(16)\n=> \"499602d2\"\n\n>> 1234567890.to_s(24)\n=> \"6b1230i\"\n\n>> 1234567890.to_s(36)\n=> \"kf12oi\"\n</code></pre>\n\n<p>And as Huw Walters has commented, converting the other way is just as simple:</p>\n\n<pre><code>>> \"kf12oi\".to_i(36)\n=> 1234567890\n</code></pre>\n"
},
{
"answer_id": 86238,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 5,
"selected": false,
"text": "<p>One final one - in ruby you can use any character you want to delimit strings. Take the following code:</p>\n\n<pre><code>message = \"My message\"\ncontrived_example = \"<div id=\\\"contrived\\\">#{message}</div>\"\n</code></pre>\n\n<p>If you don't want to escape the double-quotes within the string, you can simply use a different delimiter:</p>\n\n<pre><code>contrived_example = %{<div id=\"contrived-example\">#{message}</div>}\ncontrived_example = %[<div id=\"contrived-example\">#{message}</div>]\n</code></pre>\n\n<p>As well as avoiding having to escape delimiters, you can use these delimiters for nicer multiline strings:</p>\n\n<pre><code>sql = %{\n SELECT strings \n FROM complicated_table\n WHERE complicated_condition = '1'\n}\n</code></pre>\n"
},
{
"answer_id": 116759,
"author": "newtonapple",
"author_id": 1376,
"author_profile": "https://Stackoverflow.com/users/1376",
"pm_score": 5,
"selected": false,
"text": "<h1>module_function</h1>\n\n<p>Module methods that are declared as <em>module_function</em> will create copies of themselves as <strong>private</strong> instance methods in the class that includes the Module:</p>\n\n<pre><code>module M\n def not!\n 'not!'\n end\n module_function :not!\nend\n\nclass C\n include M\n\n def fun\n not!\n end\nend\n\nM.not! # => 'not!\nC.new.fun # => 'not!'\nC.new.not! # => NoMethodError: private method `not!' called for #<C:0x1261a00>\n</code></pre>\n\n<p>If you use <em>module_function</em> without any arguments, then any module methods that comes after the module_function statement will automatically become module_functions themselves.</p>\n\n<pre><code>module M\n module_function\n\n def not!\n 'not!'\n end\n\n def yea!\n 'yea!'\n end\nend\n\n\nclass C\n include M\n\n def fun\n not! + ' ' + yea!\n end\nend\nM.not! # => 'not!'\nM.yea! # => 'yea!'\nC.new.fun # => 'not! yea!'\n</code></pre>\n"
},
{
"answer_id": 224276,
"author": "Justin Love",
"author_id": 30203,
"author_profile": "https://Stackoverflow.com/users/30203",
"pm_score": 4,
"selected": false,
"text": "<p><code>Class.new()</code></p>\n\n<p>Create a new class at run time. The argument can be a class to derive from, and the block is the class body. You might also want to look at <code>const_set/const_get/const_defined?</code> to get your new class properly registered, so that <code>inspect</code> prints out a name instead of a number.</p>\n\n<p>Not something you need every day, but quite handy when you do.</p>\n"
},
{
"answer_id": 327208,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 2,
"selected": false,
"text": "<p>Ruby has a <a href=\"http://gd.tuwien.ac.at/languages/scheme/tutorial-dsitaram/t-y-scheme-Z-H-14.html#%_sec_13.1\" rel=\"nofollow noreferrer\">call/cc</a> mechanism allowing one to freely hop up and down the stack.</p>\n\n<p>Simple example follows. This is certainly not how one would multiply a sequence in ruby, but it demonstrates how one might use call/cc to reach up the stack to short-circuit an algorithm. In this case, we're recursively multiplying a list of numbers until we either have seen every number or we see zero (the two cases where we know the answer). In the zero case, we can be arbitrarily deep in the list and terminate.</p>\n\n<pre><code>#!/usr/bin/env ruby\n\ndef rprod(k, rv, current, *nums)\n puts \"#{rv} * #{current}\"\n k.call(0) if current == 0 || rv == 0\n nums.empty? ? (rv * current) : rprod(k, rv * current, *nums)\nend\n\ndef prod(first, *rest)\n callcc { |k| rprod(k, first, *rest) }\nend\n\nputs \"Seq 1: #{prod(1, 2, 3, 4, 5, 6)}\"\nputs \"\"\nputs \"Seq 2: #{prod(1, 2, 0, 3, 4, 5, 6)}\"\n</code></pre>\n\n<p>You can see the output here:</p>\n\n<p><a href=\"http://codepad.org/Oh8ddh9e\" rel=\"nofollow noreferrer\">http://codepad.org/Oh8ddh9e</a></p>\n\n<p>For a more complex example featuring continuations moving the other direction on the stack, read the source to <a href=\"http://www.ruby-doc.org/stdlib/libdoc/generator/rdoc/index.html\" rel=\"nofollow noreferrer\">Generator</a>. </p>\n"
},
{
"answer_id": 474888,
"author": "Bo Jeanes",
"author_id": 56690,
"author_profile": "https://Stackoverflow.com/users/56690",
"pm_score": 6,
"selected": false,
"text": "<p>One of the cool things about ruby is that you can call methods and run code in places other languages would frown upon, such as in method or class definitions.</p>\n\n<p>For instance, to create a class that has an unknown superclass until run time, i.e. is random, you could do the following:</p>\n\n<pre><code>class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].sample\n\nend\n\nRandomSubclass.superclass # could output one of 6 different classes.\n</code></pre>\n\n<p>This uses the 1.9 <code>Array#sample</code> method (in 1.8.7-only, see <code>Array#choice</code>), and the example is pretty contrived but you can see the power here. </p>\n\n<p>Another cool example is the ability to put default parameter values that are non fixed (like other languages often demand):</p>\n\n<pre><code>def do_something_at(something, at = Time.now)\n # ...\nend\n</code></pre>\n\n<p>Of course the problem with the first example is that it is evaluated at definition time, not call time. So, once a superclass has been chosen, it stays that superclass for the remainder of the program. </p>\n\n<p>However, in the second example, each time you call <code>do_something_at</code>, the <code>at</code> variable will be the time that the method was called (well, very very close to it)</p>\n"
},
{
"answer_id": 827932,
"author": "Chirantan",
"author_id": 45942,
"author_profile": "https://Stackoverflow.com/users/45942",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class A\n\n private\n\n def my_private_method\n puts 'private method called'\n end\nend\n\na = A.new\na.my_private_method # Raises exception saying private method was called\na.send :my_private_method # Calls my_private_method and prints private method called'\n</code></pre>\n"
},
{
"answer_id": 1061004,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Short inject, like such:</p>\n\n<p><a href=\"http://weblog.raganwald.com/2008/02/1100inject.html\" rel=\"nofollow noreferrer\">Sum of range:</a></p>\n\n<pre><code>(1..10).inject(:+)\n=> 55\n</code></pre>\n"
},
{
"answer_id": 1061835,
"author": "August Lilleaas",
"author_id": 26051,
"author_profile": "https://Stackoverflow.com/users/26051",
"pm_score": 5,
"selected": false,
"text": "<p>Hashes with default values! An array in this case.</p>\n\n<pre><code>parties = Hash.new {|hash, key| hash[key] = [] }\nparties[\"Summer party\"]\n# => []\n\nparties[\"Summer party\"] << \"Joe\"\nparties[\"Other party\"] << \"Jane\"\n</code></pre>\n\n<p>Very useful in metaprogramming.</p>\n"
},
{
"answer_id": 1140464,
"author": "Ropez",
"author_id": 137627,
"author_profile": "https://Stackoverflow.com/users/137627",
"pm_score": 3,
"selected": false,
"text": "<p>I find this useful in some scripts. It makes it possible to use environment variables directly, like in shell scripts and Makefiles. Environment variables are used as fall-back for undefined Ruby constants.</p>\n\n<pre><code>>> class <<Object\n>> alias :old_const_missing :const_missing\n>> def const_missing(sym)\n>> ENV[sym.to_s] || old_const_missing(sym)\n>> end\n>> end\n=> nil\n\n>> puts SHELL\n/bin/zsh\n=> nil\n>> TERM == 'xterm'\n=> true\n</code></pre>\n"
},
{
"answer_id": 1224534,
"author": "horseyguy",
"author_id": 66725,
"author_profile": "https://Stackoverflow.com/users/66725",
"pm_score": 4,
"selected": false,
"text": "<p>create an array of consecutive numbers:</p>\n\n<pre><code>x = [*0..5]\n</code></pre>\n\n<p>sets x to [0, 1, 2, 3, 4, 5]</p>\n"
},
{
"answer_id": 1540615,
"author": "Jordan Running",
"author_id": 179125,
"author_profile": "https://Stackoverflow.com/users/179125",
"pm_score": 4,
"selected": false,
"text": "<p>I'm late to the party, but:</p>\n\n<p>You can easily take two equal-length arrays and turn them into a hash with one array supplying the keys and the other the values:</p>\n\n<pre><code>a = [:x, :y, :z]\nb = [123, 456, 789]\n\nHash[a.zip(b)]\n# => { :x => 123, :y => 456, :z => 789 }\n</code></pre>\n\n<p>(This works because Array#zip \"zips\" up the values from the two arrays:</p>\n\n<pre><code>a.zip(b) # => [[:x, 123], [:y, 456], [:z, 789]]\n</code></pre>\n\n<p>And Hash[] can take just such an array. I've seen people do this as well:</p>\n\n<pre><code>Hash[*a.zip(b).flatten] # unnecessary!\n</code></pre>\n\n<p>Which yields the same result, but the splat and flatten are wholly unnecessary--perhaps they weren't in the past?)</p>\n"
},
{
"answer_id": 1817710,
"author": "horseyguy",
"author_id": 66725,
"author_profile": "https://Stackoverflow.com/users/66725",
"pm_score": 5,
"selected": false,
"text": "<p>Use a Range object as an infinite lazy list:</p>\n\n<pre><code>Inf = 1.0 / 0\n\n(1..Inf).take(5) #=> [1, 2, 3, 4, 5]\n</code></pre>\n\n<p>More info here: <a href=\"http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/\" rel=\"nofollow noreferrer\">http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/</a></p>\n"
},
{
"answer_id": 1941479,
"author": "EmFi",
"author_id": 186039,
"author_profile": "https://Stackoverflow.com/users/186039",
"pm_score": 5,
"selected": false,
"text": "<p>Boolean operators on non boolean values.</p>\n\n<p><code>&&</code> and <code>||</code> </p>\n\n<p>Both return the value of the last expression evaluated.</p>\n\n<p>Which is why the <code>||=</code> will update the variable with the value returned expression on the right side if the variable is undefined. This is not explicitly documented, but common knowledge.</p>\n\n<p>However the <code>&&=</code> isn't quite so widely known about.</p>\n\n<pre><code>string &&= string + \"suffix\"\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>if string\n string = string + \"suffix\"\nend\n</code></pre>\n\n<p>It's very handy for destructive operations that should not proceed if the variable is undefined.</p>\n"
},
{
"answer_id": 1992744,
"author": "minaguib",
"author_id": 241953,
"author_profile": "https://Stackoverflow.com/users/241953",
"pm_score": 2,
"selected": false,
"text": "<p>James A. Rosen's tip is cool ([*items].each), but I find that it destroys hashes:</p>\n\n<pre><code>irb(main):001:0> h = {:name => \"Bob\"}\n=> {:name=>\"Bob\"}\nirb(main):002:0> [*h]\n=> [[:name, \"Bob\"]]\n</code></pre>\n\n<p>I prefer this way of handling the case when I accept a list of things to process but am lenient and allow the caller to supply one:</p>\n\n<pre><code>irb(main):003:0> h = {:name => \"Bob\"}\n=> {:name=>\"Bob\"}\nirb(main):004:0> [h].flatten\n=> [{:name=>\"Bob\"}]\n</code></pre>\n\n<p>This can be combined with a method signature like so nicely:</p>\n\n<pre><code>def process(*entries)\n [entries].flatten.each do |e|\n # do something with e\n end\nend\n</code></pre>\n"
},
{
"answer_id": 1992828,
"author": "minaguib",
"author_id": 241953,
"author_profile": "https://Stackoverflow.com/users/241953",
"pm_score": 4,
"selected": false,
"text": "<p>The \"ruby\" binary (at least MRI's) supports a lot of the switches that made perl one-liners quite popular.</p>\n\n<p>Significant ones:</p>\n\n<ul>\n<li>-n Sets up an outer loop with just \"gets\" - which magically works with given filename or STDIN, setting each read line in $_</li>\n<li>-p Similar to -n but with an automatic <code>put</code>s at the end of each loop iteration</li>\n<li>-a Automatic call to .split on each input line, stored in $F</li>\n<li>-i In-place edit input files</li>\n<li>-l Automatic call to .chomp on input</li>\n<li>-e Execute a piece of code</li>\n<li>-c Check source code</li>\n<li>-w With warnings</li>\n</ul>\n\n<p>Some examples:</p>\n\n<pre><code># Print each line with its number:\nruby -ne 'print($., \": \", $_)' < /etc/irbrc\n\n# Print each line reversed:\nruby -lne 'puts $_.reverse' < /etc/irbrc\n\n# Print the second column from an input CSV (dumb - no balanced quote support etc):\nruby -F, -ane 'puts $F[1]' < /etc/irbrc\n\n# Print lines that contain \"eat\"\nruby -ne 'puts $_ if /eat/i' < /etc/irbrc\n\n# Same as above:\nruby -pe 'next unless /eat/i' < /etc/irbrc\n\n# Pass-through (like cat, but with possible line-end munging):\nruby -p -e '' < /etc/irbrc\n\n# Uppercase all input:\nruby -p -e '$_.upcase!' < /etc/irbrc\n\n# Same as above, but actually write to the input file, and make a backup first with extension .bak - Notice that inplace edit REQUIRES input files, not an input STDIN:\nruby -i.bak -p -e '$_.upcase!' /etc/irbrc\n</code></pre>\n\n<p>Feel free to google \"ruby one-liners\" and \"perl one-liners\" for tons more usable and practical examples. It essentially allows you to use ruby as a fairly powerful replacement to awk and sed.</p>\n"
},
{
"answer_id": 2132820,
"author": "Trevoke",
"author_id": 234025,
"author_profile": "https://Stackoverflow.com/users/234025",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Auto-vivifying hashes in Ruby</strong></p>\n\n<pre><code>def cnh # silly name \"create nested hash\"\n Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}\nend\nmy_hash = cnh\nmy_hash[1][2][3] = 4\nmy_hash # => { 1 => { 2 => { 3 =>4 } } }\n</code></pre>\n\n<p>This can just be damn handy.</p>\n"
},
{
"answer_id": 2340767,
"author": "sickill",
"author_id": 264409,
"author_profile": "https://Stackoverflow.com/users/264409",
"pm_score": 3,
"selected": false,
"text": "<p><code>Fixnum#to_s(base)</code> can be really useful in some case. One such case is generating random (pseudo)unique tokens by converting random number to string using base of 36.</p>\n\n<p>Token of length 8:</p>\n\n<pre><code>rand(36**8).to_s(36) => \"fmhpjfao\"\nrand(36**8).to_s(36) => \"gcer9ecu\"\nrand(36**8).to_s(36) => \"krpm0h9r\"\n</code></pre>\n\n<p>Token of length 6:</p>\n\n<pre><code>rand(36**6).to_s(36) => \"bvhl8d\"\nrand(36**6).to_s(36) => \"lb7tis\"\nrand(36**6).to_s(36) => \"ibwgeh\"\n</code></pre>\n"
},
{
"answer_id": 2379114,
"author": "Fabiano Soriani",
"author_id": 250019,
"author_profile": "https://Stackoverflow.com/users/250019",
"pm_score": 2,
"selected": false,
"text": "<p>I just <em>love</em> the inline keyword <strong>rescue</strong> like this:<br>\n<strong>EDITED EXAMPLE:</strong></p>\n\n<pre><code>@user #=> nil (but I did't know)\[email protected] rescue \"Unknown\"\nlink_to( d.user.name, url_user( d.user.id, d.user.name)) rescue 'Account removed'\n</code></pre>\n\n<p>This avoid breaking my App and is way better than the feature released at Rails <em>.try()</em></p>\n"
},
{
"answer_id": 2792840,
"author": "haoqi",
"author_id": 131492,
"author_profile": "https://Stackoverflow.com/users/131492",
"pm_score": 1,
"selected": false,
"text": "<pre><code>@user #=> nil (but I did't know)\[email protected] rescue \"Unknown\"\n</code></pre>\n"
},
{
"answer_id": 2911455,
"author": "Judson",
"author_id": 349582,
"author_profile": "https://Stackoverflow.com/users/349582",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a fan of:</p>\n\n<pre><code>%w{An Array of strings} #=> [\"An\", \"Array\", \"of\", \"Strings\"]\n</code></pre>\n\n<p>It's sort of funny how often that's useful.</p>\n"
},
{
"answer_id": 3054688,
"author": "Konstantin Haase",
"author_id": 302187,
"author_profile": "https://Stackoverflow.com/users/302187",
"pm_score": 6,
"selected": false,
"text": "<p>Wow, no one mentioned the flip flop operator:</p>\n\n<pre><code>1.upto(100) do |i|\n puts i if (i == 3)..(i == 15)\nend\n</code></pre>\n"
},
{
"answer_id": 3341493,
"author": "mhd",
"author_id": 38515,
"author_profile": "https://Stackoverflow.com/users/38515",
"pm_score": 2,
"selected": false,
"text": "<p><strong>each_with_index</strong> method for any enumarable object ( array,hash,etc.) perhaps? </p>\n\n<pre><code>myarray = [\"la\", \"li\", \"lu\"]\nmyarray.each_with_index{|v,idx| puts \"#{idx} -> #{v}\"}\n\n#result:\n#0 -> la\n#1 -> li\n#2 -> lu\n</code></pre>\n\n<p>Maybe it's more well known than other answers but not that well known for all ruby programmers :)</p>\n"
},
{
"answer_id": 3823852,
"author": "horseyguy",
"author_id": 66725,
"author_profile": "https://Stackoverflow.com/users/66725",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Destructuring an Array</strong></p>\n\n<pre><code>(a, b), c, d = [ [:a, :b ], :c, [:d1, :d2] ]\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>a #=> :a\nb #=> :b\nc #=> :c\nd #=> [:d1, :d2]\n</code></pre>\n\n<p>Using this technique we can use simple assignment to get the exact values we want out of nested array of any depth.</p>\n"
},
{
"answer_id": 3834838,
"author": "horseyguy",
"author_id": 66725,
"author_profile": "https://Stackoverflow.com/users/66725",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Defining a method that accepts any number of parameters and just discards them all</strong></p>\n\n<pre><code>def hello(*)\n super\n puts \"hello!\"\nend\n</code></pre>\n\n<p>The above <code>hello</code> method only needs to <code>puts</code> <code>\"hello\"</code> on the screen and call <code>super</code> - but since the superclass <code>hello</code> defines parameters it has to as well - however since it doesn't actually need to use the parameters itself - it doesn't have to give them a name.</p>\n"
},
{
"answer_id": 4139641,
"author": "Kelvin",
"author_id": 498594,
"author_profile": "https://Stackoverflow.com/users/498594",
"pm_score": 2,
"selected": false,
"text": "<p>Calling a method defined anywhere in the inheritance chain, even if overridden</p>\n\n<p>ActiveSupport's objects sometimes masquerade as built-in objects.</p>\n\n<pre>\nrequire 'active_support'\ndays = 5.days\ndays.class #=> Fixnum\ndays.is_a?(Fixnum) #=> true\nFixnum === days #=> false (huh? what are you really?)\nObject.instance_method(:class).bind(days).call #=> ActiveSupport::Duration (aha!)\nActiveSupport::Duration === days #=> true\n</pre>\n\n<p>The above, of course, relies on the fact that active_support doesn't redefine Object#instance_method, in which case we'd really be up a creek. Then again, we could always save the return value of Object.instance_method(:class) before any 3rd party library is loaded.</p>\n\n<p>Object.instance_method(...) returns an UnboundMethod which you can then bind to an instance of that class. In this case, you can bind it to any instance of Object (subclasses included).</p>\n\n<p>If an object's class includes modules, you can also use the UnboundMethod from those modules.</p>\n\n<pre>\nmodule Mod\n def var_add(more); @var+more; end\nend\nclass Cla\n include Mod\n def initialize(var); @var=var; end\n # override\n def var_add(more); @var+more+more; end\nend\ncla = Cla.new('abcdef')\ncla.var_add('ghi') #=> \"abcdefghighi\"\nMod.instance_method(:var_add).bind(cla).call('ghi') #=> \"abcdefghi\"\n</pre>\n\n<p>This even works for singleton methods that override an instance method of the class the object belongs to.</p>\n\n<pre>\nclass Foo\n def mymethod; 'original'; end\nend\nfoo = Foo.new\nfoo.mymethod #=> 'original'\ndef foo.mymethod; 'singleton'; end\nfoo.mymethod #=> 'singleton'\nFoo.instance_method(:mymethod).bind(foo).call #=> 'original'\n\n# You can also call #instance method on singleton classes:\nclass << foo; self; end.instance_method(:mymethod).bind(foo).call #=> 'singleton'\n</pre>\n"
},
{
"answer_id": 4294367,
"author": "Ramiz Uddin",
"author_id": 134743,
"author_profile": "https://Stackoverflow.com/users/134743",
"pm_score": 2,
"selected": false,
"text": "<h2>Multiple return values</h2>\n\n<pre><code>def getCostAndMpg\n cost = 30000 # some fancy db calls go here\n mpg = 30\n return cost,mpg\nend\nAltimaCost, AltimaMpg = getCostAndMpg\nputs \"AltimaCost = #{AltimaCost}, AltimaMpg = #{AltimaMpg}\"\n</code></pre>\n\n<h2>Parallel Assignment</h2>\n\n<pre><code>i = 0\nj = 1\nputs \"i = #{i}, j=#{j}\"\ni,j = j,i\nputs \"i = #{i}, j=#{j}\"\n</code></pre>\n\n<h2>Virtual Attributes</h2>\n\n<pre><code>class Employee < Person\n def initialize(fname, lname, position)\n super(fname,lname)\n @position = position\n end\n def to_s\n super + \", #@position\"\n end\n attr_writer :position\n def etype\n if @position == \"CEO\" || @position == \"CFO\"\n \"executive\"\n else\n \"staff\"\n end\n end\nend\nemployee = Employee.new(\"Augustus\",\"Bondi\",\"CFO\")\nemployee.position = \"CEO\"\nputs employee.etype => executive\nemployee.position = \"Engineer\"\nputs employee.etype => staff\n</code></pre>\n\n<h2>method_missing - a wonderful idea</h2>\n\n<p><em>(In most languages when a method cannot be found and error is thrown and your program stops. In ruby you can actually catch those errors and perhaps do something intelligent with the situation)</em></p>\n\n<pre><code>class MathWiz\n def add(a,b) \n return a+b\n end\n def method_missing(name, *args)\n puts \"I don't know the method #{name}\"\n end\nend\nmathwiz = MathWiz.new\nputs mathwiz.add(1,4)\nputs mathwiz.subtract(4,2)\n</code></pre>\n\n<blockquote>\n <p>5</p>\n \n <p>I don't know the method subtract</p>\n \n <p>nil</p>\n</blockquote>\n"
},
{
"answer_id": 5333299,
"author": "Aaa",
"author_id": 636053,
"author_profile": "https://Stackoverflow.com/users/636053",
"pm_score": 2,
"selected": false,
"text": "<p>There are some aspects of symbol literals that people should know. One case solved by special symbol literals is when you need to create a symbol whose name causes a syntax error for some reason with the normal symbol literal syntax:</p>\n\n<pre><code>:'class'\n</code></pre>\n\n<p>You can also do symbol interpolation. In the context of an accessor, for example:</p>\n\n<pre><code>define_method :\"#{name}=\" do |value|\n instance_variable_set :\"@#{name}\", value\nend\n</code></pre>\n"
},
{
"answer_id": 6037067,
"author": "J-_-L",
"author_id": 169793,
"author_profile": "https://Stackoverflow.com/users/169793",
"pm_score": 3,
"selected": false,
"text": "<p>To combine multiple regexes with <code>|</code>, you can use</p>\n\n<pre><code>Regexp.union /Ruby\\d/, /test/i, \"cheat\"\n</code></pre>\n\n<p>to create a Regexp similar to:</p>\n\n<pre><code>/(Ruby\\d|[tT][eE][sS][tT]|cheat)/\n</code></pre>\n"
},
{
"answer_id": 6279466,
"author": "Szymon Jeż",
"author_id": 408011,
"author_profile": "https://Stackoverflow.com/users/408011",
"pm_score": 3,
"selected": false,
"text": "<pre><code>private unless Rails.env == 'test'\n# e.g. a bundle of methods you want to test directly\n</code></pre>\n\n<p>Looks like a cool and (in some cases) nice/useful hack/feature of Ruby.</p>\n"
},
{
"answer_id": 8933705,
"author": "Alex D",
"author_id": 960828,
"author_profile": "https://Stackoverflow.com/users/960828",
"pm_score": 2,
"selected": false,
"text": "<p>I just read all the answers... one notable omission was destructuring assignment:</p>\n\n<pre><code>> (a,b),c = [[1,2],3]\n=> [[1,2],3]\n> a\n=> 1\n</code></pre>\n\n<p>It also works for block parameters. This is useful when you have nested arrays, each element of which represents something distinct. Instead of writing code like \"array[0][1]\", you can break that nested array down and give a descriptive name to each element, in a single line of code.</p>\n"
},
{
"answer_id": 9214173,
"author": "iblue",
"author_id": 773690,
"author_profile": "https://Stackoverflow.com/users/773690",
"pm_score": 1,
"selected": false,
"text": "<h2>The sprintf shortcut</h2>\n\n<p>My favourite ruby feature. Syntax is <code>format_string % argument</code></p>\n\n<pre><code>\"%04d\" % 1 # => \"0001\"\n\"%0.2f\" % Math::PI # => \"3.14\"\n</code></pre>\n\n<p>Works as well for arrays (<code>format_string % array_of_arguments</code>)</p>\n\n<pre><code>\"%.2f %.3f %.4f\" % ([Math::PI]*3) \n# => \"3.14 3.142 3.1416\"\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/63998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7754/"
]
| Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.
Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.
See also:
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby on Rails](https://stackoverflow.com/questions/709679/hidden-features-of-ruby-on-rails)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
(Please, just *one* hidden feature per answer.)
Thank you | Peter Cooper has a [good list](http://www.rubyinside.com/21-ruby-tricks-902.html) of Ruby tricks. Perhaps my favorite of his is allowing both single items and collections to be enumerated. (That is, treat a non-collection object as a collection containing just that object.) It looks like this:
```
[*items].each do |item|
# ...
end
``` |
64,000 | <p>When launching a process from Java, both stderr and stdout can block on output if I don't read from the pipes. Currently I have a thread that pro-actively reads from one and the main thread blocks on the other.</p>
<p>Is there an easy way to join the two streams or otherwise cause the subprocess to continue while not losing the data in stderr? </p>
| [
{
"answer_id": 64145,
"author": "killdash10",
"author_id": 7621,
"author_profile": "https://Stackoverflow.com/users/7621",
"pm_score": 0,
"selected": false,
"text": "<p>Just have two threads, one reading from stdout, one from stderr?</p>\n"
},
{
"answer_id": 64183,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 3,
"selected": true,
"text": "<p>Set the redirectErrorStream property on ProcessBuilder to send stderr output to stdout:</p>\n\n<pre><code>ProcessBuilder builder = new ProcessBuilder(command);\nbuilder.redirectErrorStream(true);\n</code></pre>\n\n<p>You should then create a thread to deal with the process stream, something like the following:</p>\n\n<pre><code>Process p = builder.start();\n\nInputHandler outHandler = new InputHandler(p.getInputStream());\n</code></pre>\n\n<p>Where InputHandler is defined as:</p>\n\n<pre><code>private static class InputHandler extends Thread {\n\n private final InputStream is;\n\n private final ByteArrayOutputStream os;\n\n public InputHandler(InputStream input) {\n this.is = input;\n this.os = new ByteArrayOutputStream();\n }\n\n public void run() {\n try {\n int c;\n while ((c = is.read()) != -1) {\n os.write(c);\n }\n } catch (Throwable t) {\n throw new IllegalStateException(t);\n }\n }\n\n public String getOutput() {\n try {\n os.flush();\n } catch (Throwable t) {\n throw new IllegalStateException(t);\n }\n return os.toString();\n }\n\n}\n</code></pre>\n\n<p>Alternatively, just create two InputHandlers for the InputStream and ErrorStream. Knowing that the program will block if you don't read them is 90% of the battle :)</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4926/"
]
| When launching a process from Java, both stderr and stdout can block on output if I don't read from the pipes. Currently I have a thread that pro-actively reads from one and the main thread blocks on the other.
Is there an easy way to join the two streams or otherwise cause the subprocess to continue while not losing the data in stderr? | Set the redirectErrorStream property on ProcessBuilder to send stderr output to stdout:
```
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
```
You should then create a thread to deal with the process stream, something like the following:
```
Process p = builder.start();
InputHandler outHandler = new InputHandler(p.getInputStream());
```
Where InputHandler is defined as:
```
private static class InputHandler extends Thread {
private final InputStream is;
private final ByteArrayOutputStream os;
public InputHandler(InputStream input) {
this.is = input;
this.os = new ByteArrayOutputStream();
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
os.write(c);
}
} catch (Throwable t) {
throw new IllegalStateException(t);
}
}
public String getOutput() {
try {
os.flush();
} catch (Throwable t) {
throw new IllegalStateException(t);
}
return os.toString();
}
}
```
Alternatively, just create two InputHandlers for the InputStream and ErrorStream. Knowing that the program will block if you don't read them is 90% of the battle :) |
64,003 | <p>I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.</p>
<p>How would I make the year update automatically with <a href="http://en.wikipedia.org/wiki/PHP#History" rel="noreferrer">PHP 4</a> or <a href="http://en.wikipedia.org/wiki/PHP#History" rel="noreferrer">PHP 5</a>?</p>
| [
{
"answer_id": 64009,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 9,
"selected": false,
"text": "<pre><code><?php echo date(\"Y\"); ?>\n</code></pre>\n"
},
{
"answer_id": 64011,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "<pre><code>strftime(\"%Y\");\n</code></pre>\n\n<p>I love <a href=\"http://us3.php.net/manual/en/function.strftime.php\" rel=\"noreferrer\">strftime</a>. It's a great function for grabbing/recombining chunks of dates/times. </p>\n\n<p>Plus it respects locale settings which the date function doesn't do.</p>\n"
},
{
"answer_id": 64016,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/date\" rel=\"noreferrer\">http://us2.php.net/date</a></p>\n\n<pre><code>echo date('Y');\n</code></pre>\n"
},
{
"answer_id": 64027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>print date('Y');\n</code></pre>\n\n<p>For more information, check date() function documentation: <a href=\"https://secure.php.net/manual/en/function.date.php\" rel=\"noreferrer\">https://secure.php.net/manual/en/function.date.php</a></p>\n"
},
{
"answer_id": 64087,
"author": "Alexey Lebedev",
"author_id": 8338,
"author_profile": "https://Stackoverflow.com/users/8338",
"pm_score": 4,
"selected": false,
"text": "<p>This one gives you the local time:</p>\n\n<pre><code>$year = date('Y'); // 2008\n</code></pre>\n\n<p>And this one <strong>UTC</strong>:</p>\n\n<pre><code>$year = gmdate('Y'); // 2008\n</code></pre>\n"
},
{
"answer_id": 64097,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 11,
"selected": true,
"text": "<p>You can use either <a href=\"http://php.net/manual/en/function.date.php\" rel=\"noreferrer\">date</a> or <a href=\"http://php.net/manual/en/function.strftime.php\" rel=\"noreferrer\">strftime</a>. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)</p>\n\n<p>For example:</p>\n\n<pre><code><?php echo date(\"Y\"); ?>\n</code></pre>\n\n<p>On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the <a href=\"http://php.net/manual/en/function.date.php\" rel=\"noreferrer\">php manual</a> on date:</p>\n\n<blockquote>\n <p>To format dates in other languages,\n you should use the setlocale() and\n strftime() functions instead of\n date().</p>\n</blockquote>\n\n<p>From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.</p>\n"
},
{
"answer_id": 67737,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 8,
"selected": false,
"text": "<p>My super lazy version of showing a copyright line, that automatically stays updated:</p>\n\n<pre><code>&copy; <?php \n$copyYear = 2008; \n$curYear = date('Y'); \necho $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');\n?> Me, Inc.\n</code></pre>\n\n<p>This year (2008), it will say:</p>\n\n<blockquote>\n <p>© 2008 Me, Inc.</p>\n</blockquote>\n\n<p>Next year, it will say:</p>\n\n<blockquote>\n <p>© 2008-2009 Me, Inc.</p>\n</blockquote>\n\n<p>and forever stay updated with the current year.</p>\n\n<hr>\n\n<p>Or (PHP 5.3.0+) a compact way to do it using an anonymous function so you don't have variables leaking out and don't repeat code/constants:</p>\n\n<pre><code>&copy; \n<?php call_user_func(function($y){$c=date('Y');echo $y.(($y!=$c)?'-'.$c:'');}, 2008); ?> \nMe, Inc.\n</code></pre>\n"
},
{
"answer_id": 12201484,
"author": "PanicGrip",
"author_id": 1469934,
"author_profile": "https://Stackoverflow.com/users/1469934",
"pm_score": 3,
"selected": false,
"text": "<p>If your server supports Short Tags, or you use PHP 5.4, you can use:</p>\n\n<pre><code><?=date(\"Y\")?>\n</code></pre>\n"
},
{
"answer_id": 14126896,
"author": "Thomas Kelley",
"author_id": 266374,
"author_profile": "https://Stackoverflow.com/users/266374",
"pm_score": 6,
"selected": false,
"text": "<p>With PHP heading in a more object-oriented direction, I'm surprised nobody here has referenced the built-in <a href=\"http://php.net/manual/en/book.datetime.php\" rel=\"noreferrer\"><code>DateTime</code></a> class:</p>\n\n<pre><code>$now = new DateTime();\n$year = $now->format(\"Y\");\n</code></pre>\n\n<p>or one-liner with class member access on instantiation (php>=5.4):</p>\n\n<pre><code>$year = (new DateTime)->format(\"Y\");\n</code></pre>\n"
},
{
"answer_id": 21190124,
"author": "Abdul Rahman A Samad",
"author_id": 2065804,
"author_profile": "https://Stackoverflow.com/users/2065804",
"pm_score": 4,
"selected": false,
"text": "<p>Here's what I do: </p>\n\n<pre><code><?php echo date(\"d-m-Y\") ?>\n</code></pre>\n\n<p>below is a bit of explanation of what it does: </p>\n\n<pre><code>d = day\nm = month\nY = year\n</code></pre>\n\n<p>Y will gives you four digit (e.g. 1990) and y for two digit (e.g. 90)</p>\n"
},
{
"answer_id": 23005793,
"author": "kkarayat",
"author_id": 1979400,
"author_profile": "https://Stackoverflow.com/users/1979400",
"pm_score": 3,
"selected": false,
"text": "<p><code>echo date('Y')</code> gives you current year, and this will update automatically since <code>date()</code> give us the current date.</p>\n"
},
{
"answer_id": 26158785,
"author": "Gaurav",
"author_id": 4046430,
"author_profile": "https://Stackoverflow.com/users/4046430",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n$time_now=mktime(date('h')+5,date('i')+30,date('s'));\n$dateTime = date('d_m_Y h:i:s A',$time_now);\n\necho $dateTime;\n?>\n</code></pre>\n"
},
{
"answer_id": 26399196,
"author": "joan16v",
"author_id": 1398876,
"author_profile": "https://Stackoverflow.com/users/1398876",
"pm_score": 4,
"selected": false,
"text": "<p>For 4 digit representation:</p>\n\n<pre><code><?php echo date('Y'); ?>\n</code></pre>\n\n<p>2 digit representation:</p>\n\n<pre><code><?php echo date('y'); ?>\n</code></pre>\n\n<p>Check the php documentation for more info:\n<a href=\"https://secure.php.net/manual/en/function.date.php\" rel=\"noreferrer\">https://secure.php.net/manual/en/function.date.php</a></p>\n"
},
{
"answer_id": 40255730,
"author": "saadk",
"author_id": 2078007,
"author_profile": "https://Stackoverflow.com/users/2078007",
"pm_score": 3,
"selected": false,
"text": "<p>Just write:</p>\n\n<pre><code>date(\"Y\") // A full numeric representation of a year, 4 digits\n // Examples: 1999 or 2003\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>date(\"y\"); // A two digit representation of a year Examples: 99 or 03\n</code></pre>\n\n<p>And 'echo' this value...</p>\n"
},
{
"answer_id": 40836184,
"author": "Milan",
"author_id": 1438675,
"author_profile": "https://Stackoverflow.com/users/1438675",
"pm_score": 3,
"selected": false,
"text": "<p>BTW... there are a few proper ways how to display site copyright. Some people have tendency to make things redundant i.e.: Copyright © have both the same meaning. The important copyright parts are:</p>\n\n<pre><code>**Symbol, Year, Author/Owner and Rights statement.** \n</code></pre>\n\n<blockquote>\n <p>Using PHP + HTML:</p>\n</blockquote>\n\n<pre><code><p id='copyright'>&copy; <?php echo date(\"Y\"); ?> Company Name All Rights Reserved</p>\n</code></pre>\n\n<p>or</p>\n\n<pre><code><p id='copyright'>&copy; <?php echo \"2010-\".date(\"Y\"); ?> Company Name All Rights Reserved</p\n</code></pre>\n"
},
{
"answer_id": 41317983,
"author": "Ivan Barayev",
"author_id": 6293599,
"author_profile": "https://Stackoverflow.com/users/6293599",
"pm_score": 3,
"selected": false,
"text": "<p>For up to php 5.4+</p>\n\n<pre><code><?php\n $current= new \\DateTime();\n $future = new \\DateTime('+ 1 years');\n\n echo $current->format('Y'); \n //For 4 digit ('Y') for 2 digit ('y')\n?>\n</code></pre>\n\n<p>Or you can use it with one line</p>\n\n<pre><code>$year = (new DateTime)->format(\"Y\");\n</code></pre>\n\n<p>If you wanna increase or decrease the year another method; add modify line like below.</p>\n\n<pre><code><?PHP \n $now = new DateTime;\n $now->modify('-1 years'); //or +1 or +5 years \n echo $now->format('Y');\n //and here again For 4 digit ('Y') for 2 digit ('y')\n?>\n</code></pre>\n"
},
{
"answer_id": 42146098,
"author": "Wael Assaf",
"author_id": 6241797,
"author_profile": "https://Stackoverflow.com/users/6241797",
"pm_score": 3,
"selected": false,
"text": "<p>use a PHP function which is just called <code>date()</code>.</p>\n\n<p>It takes the current date and then you provide a format to it</p>\n\n<p>and the format is just going to be Y. Capital Y is going to be a four digit year.</p>\n\n<pre><code><?php echo date(\"Y\"); ?>\n</code></pre>\n"
},
{
"answer_id": 42261996,
"author": "Abdelkader Soudani",
"author_id": 720104,
"author_profile": "https://Stackoverflow.com/users/720104",
"pm_score": 3,
"selected": false,
"text": "<pre><code><?php echo date(\"Y\"); ?>\n</code></pre>\n\n<p>This code should do</p>\n"
},
{
"answer_id": 46127571,
"author": "imtaher",
"author_id": 6617609,
"author_profile": "https://Stackoverflow.com/users/6617609",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php date_default_timezone_set(\"Asia/Kolkata\");?><?=date(\"Y\");?>\n</code></pre>\n\n<p>You can use this in footer sections to get dynamic copyright year</p>\n"
},
{
"answer_id": 46232016,
"author": "Ganesh Udmale",
"author_id": 6790108,
"author_profile": "https://Stackoverflow.com/users/6790108",
"pm_score": 3,
"selected": false,
"text": "<p>Get full Year used:</p>\n\n<pre><code> <?php \n echo $curr_year = date('Y'); // it will display full year ex. 2017\n?>\n</code></pre>\n\n<p>Or get only two digit of year used like this:</p>\n\n<pre><code> <?php \n echo $curr_year = date('y'); // it will display short 2 digit year ex. 17\n?>\n</code></pre>\n"
},
{
"answer_id": 47216489,
"author": "Sushank Pokharel",
"author_id": 7599216,
"author_profile": "https://Stackoverflow.com/users/7599216",
"pm_score": 2,
"selected": false,
"text": "<p>My way to show the copyright, That keeps on updating automatically</p>\n\n<pre><code><p class=\"text-muted credit\">Copyright &copy;\n <?php\n $copyYear = 2017; // Set your website start date\n $curYear = date('Y'); // Keeps the second year updated\n echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');\n ?> \n</p> \n</code></pre>\n\n<p>It will output the results as</p>\n\n<pre><code>copyright @ 2017 //if $copyYear is 2017 \ncopyright @ 2017-201x //if $copyYear is not equal to Current Year.\n</code></pre>\n"
},
{
"answer_id": 53956475,
"author": "Sanu0786",
"author_id": 10143531,
"author_profile": "https://Stackoverflow.com/users/10143531",
"pm_score": 3,
"selected": false,
"text": "<p>use a PHP <code>date()</code> function.</p>\n\n<p>and the format is just going to be Y. Capital Y is going to be a four digit year.</p>\n\n<pre><code><?php echo date(\"Y\"); ?>\n</code></pre>\n"
},
{
"answer_id": 55187259,
"author": "Omid Ahmadyani",
"author_id": 7006183,
"author_profile": "https://Stackoverflow.com/users/7006183",
"pm_score": 2,
"selected": false,
"text": "<p>best shortcode for this section:</p>\n\n<pre><code><?= date(\"Y\"); ?>\n</code></pre>\n"
},
{
"answer_id": 56552509,
"author": "andcl",
"author_id": 3099449,
"author_profile": "https://Stackoverflow.com/users/3099449",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using the <a href=\"https://carbon.nesbot.com/\" rel=\"nofollow noreferrer\">Carbon PHP API extension for DateTime</a>, you can achieve it easy:</p>\n\n<p><code><?php echo Carbon::now()->year; ?></code></p>\n"
},
{
"answer_id": 60972190,
"author": "Hernán Eche",
"author_id": 231382,
"author_profile": "https://Stackoverflow.com/users/231382",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$year = date("Y", strtotime($yourDateVar));\n</code></pre>\n"
},
{
"answer_id": 64936968,
"author": "allenski",
"author_id": 9132582,
"author_profile": "https://Stackoverflow.com/users/9132582",
"pm_score": 1,
"selected": false,
"text": "<p>in my case the copyright notice in the footer of a wordpress web site needed updating.</p>\n<p>thought simple, but involved a step or more thann anticipated.</p>\n<ol>\n<li><p>Open <code>footer.php</code> in your theme's folder.</p>\n</li>\n<li><p>Locate copyright text, expected this to be all hard coded but found:</p>\n<pre class=\"lang-php prettyprint-override\"><code><div id="copyright">\n <?php the_field('copyright_disclaimer', 'options'); ?>\n</div>\n</code></pre>\n</li>\n<li><p>Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to <code>Options</code> on the left main admin menu:</p>\n<p><a href=\"https://i.stack.imgur.com/ZQ1CO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZQ1CO.png\" alt=\"enter image description here\" /></a> Then on next page go to the tab <code>Disclaimers</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/DjvU2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DjvU2.png\" alt=\"enter image description here\" /></a> and near the top you will find Copyright year:</p>\n<p><a href=\"https://i.stack.imgur.com/vBPDR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vBPDR.png\" alt=\"enter image description here\" /></a> DELETE the © symbol + year + the empty space following the year, then save your page with <code>Update</code> button at top-right of page.</p>\n</li>\n<li><p>With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in <strong>STEP 2</strong> found in <code>footer.php</code> and update that to this:</p>\n<pre class=\"lang-php prettyprint-override\"><code><div id="copyright">\n &copy;<?php echo date("Y"); ?> <?php the_field('copyright_disclaimer', 'options'); ?>\n</div>\n</code></pre>\n</li>\n<li><p><strong>Done!</strong> Just need to test to ensure changes have taken effect as expected.</p>\n</li>\n</ol>\n<p>this might not be the same case for many, however we've come across this pattern among quite a number of our client sites and thought it would be best to document here.</p>\n"
},
{
"answer_id": 65932045,
"author": "Billu",
"author_id": 7186739,
"author_profile": "https://Stackoverflow.com/users/7186739",
"pm_score": 0,
"selected": false,
"text": "<p>Print current month with M, day with D and year with Y.</p>\n<pre><code><?php echo date("M D Y"); ?>\n</code></pre>\n"
},
{
"answer_id": 65989381,
"author": "ephantus okumu",
"author_id": 11665231,
"author_profile": "https://Stackoverflow.com/users/11665231",
"pm_score": 3,
"selected": false,
"text": "<p>To get the current year using PHP’s date function, you can pass in the “Y” format character like so:</p>\n<pre><code>//Getting the current year using\n//PHP's date function.\n\n$year = date("Y");\necho $year;\n</code></pre>\n<p>The example above will print out the full 4-digit representation of the current year.</p>\n<p>If you only want to retrieve the 2-digit format, then you can use the lowercase “y” format character:</p>\n<pre><code>$year = date("y");\necho $year;\n1\n2\n$year = date("y");\necho $year;\n</code></pre>\n<p>The snippet above will print out 20 instead of 2020, or 19 instead of 2019, etc.</p>\n"
},
{
"answer_id": 66439431,
"author": "Pascal Tovohery",
"author_id": 7751011,
"author_profile": "https://Stackoverflow.com/users/7751011",
"pm_score": 0,
"selected": false,
"text": "<p>For more pricise in second param in date function\n<a href=\"https://www.php.net/manual/en/function.strtotime.php\" rel=\"nofollow noreferrer\">strtotime</a> return the timestamp passed by param</p>\n<pre><code>// This work when you get time as string\necho date('Y', strtotime("now"));\n\n// Get next years\necho date('Y', strtotime("+1 years"));\n\n// \necho strftime("%Y", strtotime("now"));\n</code></pre>\n<p>With datetime class</p>\n<pre><code>echo (new DateTime)->format('Y');\n</code></pre>\n"
},
{
"answer_id": 68000321,
"author": "Ayaz Khalid",
"author_id": 16232615,
"author_profile": "https://Stackoverflow.com/users/16232615",
"pm_score": 1,
"selected": false,
"text": "<p>In Laravel</p>\n<pre><code>$date = Carbon::now()->format('Y');\nreturn $date;\n</code></pre>\n<p>In PHP</p>\n<pre><code>echo date("Y");\n</code></pre>\n"
},
{
"answer_id": 69104109,
"author": "Md. Saifur Rahman",
"author_id": 14350717,
"author_profile": "https://Stackoverflow.com/users/14350717",
"pm_score": 0,
"selected": false,
"text": "<p>create a helper function and call it</p>\n<pre><code>getCurrentYear();\n\nfunction getCurrentYear(){\n return now()->year;\n}\n</code></pre>\n"
},
{
"answer_id": 70568985,
"author": "CodAIK",
"author_id": 14585422,
"author_profile": "https://Stackoverflow.com/users/14585422",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$dateYear = date('Y');\necho "Current Year: $dateYear";\n</code></pre>\n<blockquote>\n<p>Current Year: 2022</p>\n</blockquote>\n<pre><code>$dateYear = date('y');\necho $dateYear;\n</code></pre>\n<blockquote>\n<p>22</p>\n</blockquote>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1661459/"
]
| I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.
How would I make the year update automatically with [PHP 4](http://en.wikipedia.org/wiki/PHP#History) or [PHP 5](http://en.wikipedia.org/wiki/PHP#History)? | You can use either [date](http://php.net/manual/en/function.date.php) or [strftime](http://php.net/manual/en/function.strftime.php). In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)
For example:
```
<?php echo date("Y"); ?>
```
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the [php manual](http://php.net/manual/en/function.date.php) on date:
>
> To format dates in other languages,
> you should use the setlocale() and
> strftime() functions instead of
> date().
>
>
>
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best. |
64,041 | <p>How do I change font size on the DataGridView?</p>
| [
{
"answer_id": 64052,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>Use the Font-property on the gridview. See MSDN for details and samples:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx</a></p>\n"
},
{
"answer_id": 64167,
"author": "psamwel",
"author_id": 3089,
"author_profile": "https://Stackoverflow.com/users/3089",
"pm_score": 7,
"selected": true,
"text": "<pre><code> private void UpdateFont()\n {\n //Change cell font\n foreach(DataGridViewColumn c in dgAssets.Columns)\n {\n c.DefaultCellStyle.Font = new Font(\"Arial\", 8.5F, GraphicsUnit.Pixel);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 5843749,
"author": "Merin Nakarmi",
"author_id": 717955,
"author_profile": "https://Stackoverflow.com/users/717955",
"pm_score": 6,
"selected": false,
"text": "<p>In winform datagrid, right click to view its properties. It has a property called DefaultCellStyle. Click the ellipsis on DefaultCellStyle, then it will present Cell Style Builder window which has the option to change the font size.</p>\n\n<p>Its easy. </p>\n"
},
{
"answer_id": 8784349,
"author": "sankalp korde",
"author_id": 1138056,
"author_profile": "https://Stackoverflow.com/users/1138056",
"pm_score": 0,
"selected": false,
"text": "<p>Go to designer.cs file of the form in which you have the grid view and comment the following line: -\n//this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;</p>\n\n<p>if you are using vs 2008 or .net framework 3.5 as it will be by default applied to alternating rows.</p>\n"
},
{
"answer_id": 11940259,
"author": "Sylvio",
"author_id": 1596209,
"author_profile": "https://Stackoverflow.com/users/1596209",
"pm_score": 0,
"selected": false,
"text": "<pre><code>' Cell style\n With .DefaultCellStyle\n .BackColor = Color.Black\n .ForeColor = Color.White \n .Font = New System.Drawing.Font(\"Microsoft Sans Serif\", 11.0!,\n System.Drawing.FontStyle.Regular,\n System.Drawing.GraphicsUnit.Point, CType(0, Byte))\n .Alignment = DataGridViewContentAlignment.MiddleRight\n End With\n</code></pre>\n"
},
{
"answer_id": 14069480,
"author": "CVKrishna",
"author_id": 1934480,
"author_profile": "https://Stackoverflow.com/users/1934480",
"pm_score": 2,
"selected": false,
"text": "<p>I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 33985972,
"author": "Ashraf Sada",
"author_id": 2459714,
"author_profile": "https://Stackoverflow.com/users/2459714",
"pm_score": 5,
"selected": false,
"text": "<p>The straight forward approach:</p>\n\n<pre><code>this.dataGridView1.DefaultCellStyle.Font = new Font(\"Tahoma\", 15);\n</code></pre>\n"
},
{
"answer_id": 38587195,
"author": "Sheraz Latif",
"author_id": 6638735,
"author_profile": "https://Stackoverflow.com/users/6638735",
"pm_score": 2,
"selected": false,
"text": "<p><strong>1st Step:</strong>\nGo to the form where datagridview is added</p>\n\n<p><strong>2nd step:</strong>\nclick on the datagridview at the top right side there will be displayed a small button of like play icon or arrow to edit the datagridview.</p>\n\n<p><strong>3rd step:</strong>\nclick on that button and select edit columns now click the attributes you want to increase font size.</p>\n\n<p><strong>4th step:</strong>\non the right side of the property menu the first on the list column named defaultcellstyle click on its property a new window will open to change the font and font size.</p>\n"
},
{
"answer_id": 45228577,
"author": "Niraj Trivedi",
"author_id": 3839344,
"author_profile": "https://Stackoverflow.com/users/3839344",
"pm_score": 3,
"selected": false,
"text": "<p>For changing particular single column font size use following statement </p>\n\n<p><code>DataGridView.Columns[1].DefaultCellStyle.Font = new Font(\"Verdana\", 16, FontStyle.Bold);</code></p>\n"
},
{
"answer_id": 50976003,
"author": "Mahmut K.",
"author_id": 4431768,
"author_profile": "https://Stackoverflow.com/users/4431768",
"pm_score": 3,
"selected": false,
"text": "<p>I think it's easiest:</p>\n\n<p>First set any Label as you like (Italic, Bold, Size etc.)\n And:</p>\n\n<pre><code>yourDataGridView.Font = anyLabel.Font;\n</code></pre>\n"
},
{
"answer_id": 68499819,
"author": "Julio",
"author_id": 11564937,
"author_profile": "https://Stackoverflow.com/users/11564937",
"pm_score": 2,
"selected": false,
"text": "<p>In DataGridView, right click properties,\nIn RowTemplate > DefaultCellStyle change the Font Size,\nIt worked for me</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
]
| How do I change font size on the DataGridView? | ```
private void UpdateFont()
{
//Change cell font
foreach(DataGridViewColumn c in dgAssets.Columns)
{
c.DefaultCellStyle.Font = new Font("Arial", 8.5F, GraphicsUnit.Pixel);
}
}
``` |
64,059 | <p>I have some website which requires a logon and shows sensitive information.</p>
<p>The person goes to the page, is prompted to log in, then gets to see the information.</p>
<p>The person logs out of the site, and is redirected back to the login page.</p>
<p>The person then can hit "back" and go right back to the page where the sensitive information is contained. Since the browser just thinks of it as rendered HTML, it shows it to them no problem.</p>
<p>Is there a way to prevent that information from being displayed when the person hits the "back" button from the logged out screen? I'm not trying to disable the back button itself, I'm just trying to keep the sensitive information from being displayed again because the person is not logged into the site anymore.</p>
<p>For the sake of argument, the above site/scenario is in ASP.NET with Forms Authentication (so when the user goes to the first page, which is the page they want, they're redirected to the logon page - in case that makes a difference).</p>
| [
{
"answer_id": 64079,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://www.aspdev.org/asp.net/asp.net-disable-caching/\" rel=\"nofollow noreferrer\">aspdev.org</a>:</p>\n\n<p>Add the following line on top of the Page_Load event handler and your ASP.NET page will not be cached in the users browsers: </p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache)\n</code></pre>\n\n<p>Settings this property ensures that if the user hits the back-button the content will be gone, and if he presses \"refresh\" he will be redirected to the login-page.</p>\n"
},
{
"answer_id": 64081,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>You are looking for a no-cache directive:</p>\n\n<pre><code><META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">\n</code></pre>\n\n<p>If you've got a master page design going, this may be a little bit of a juggle, but I believe you can put this directive on a single page, without affecting the rest of your site (assuming that's what you want).</p>\n\n<p>If you've got this directive set, the browser will dutifully head back to the server looking for a brand new copy of the page, which will cause your server to see that the user is not authenticated and bump him to the login page.</p>\n"
},
{
"answer_id": 64086,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<p>Have the logout operation be a <code>POST</code>. Then the browser will prompt for \"Are you sure you want to re-post the form?\" rather than show the page.</p>\n"
},
{
"answer_id": 64091,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know how to do it in ASP.NET but in PHP I would do something like:</p>\n\n<pre><code>header(\"Expires: Mon, 26 Jul 1997 05:00:00 GMT\");\nheader(\"Cache-Control: no-cache\");\nheader(\"Pragma: no-cache\");\n</code></pre>\n\n<p>Which forces the browser to recheck that the item, so your authentication checking should be triggered, denying the user access.</p>\n"
},
{
"answer_id": 64093,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 0,
"selected": false,
"text": "<p>The correct answer involves use of setting the HTTP Cache-Control header on the response. If you want to ensure that they <b>never</b> cache the output, you can do Cache-Control: no-cache. This is often used in coordination with no-store as well.</p>\n\n<p>Other options, if you want limited caching, include setting an expires time and must-revalidate, but these could potentially all cause a cached page to be displayed again.</p>\n\n<p>See <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4\" rel=\"nofollow noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4</a></p>\n"
},
{
"answer_id": 64173,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 0,
"selected": false,
"text": "<p>It's a bit of a strain, but if you had a java applet or a flash application that was embedded and authentication was done through that you could make it so that they had to authenticate in, erm, 'real-time' with the server everytime they wanted to view the information.</p>\n\n<p>Using this you could also encrypt any information.</p>\n\n<p>There's always the possibility that someone can just save the page with the sensitive information on, having no cache isn't going to get around this situation (but then a screenshot can always be taken of a flash or java application).</p>\n"
},
{
"answer_id": 64196,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 0,
"selected": false,
"text": "<p>For completeness:</p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.SetNoStore();\nResponse.Cache.SetExpires(DateTime.Now.AddMinutes(-1));\n</code></pre>\n"
},
{
"answer_id": 64300,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "<p>DannySmurf, <meta> elements are extremely unreliable when it comes to controlling caching, and Pragma in particular even more so. <a href=\"http://www.mnot.net/cache_docs/#META\" rel=\"nofollow noreferrer\">Reference</a>.</p>\n"
},
{
"answer_id": 64322,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 1,
"selected": false,
"text": "<p>dannyp and others, no-cache does not stop caches from storing sensitive resources. It merely means that a cache cannot serve a resource it has stored without revalidating it first. If you wish to prevent sensitive resources from being cached, you need to use the no-store directive.</p>\n"
},
{
"answer_id": 65307,
"author": "Ivan Bosnic",
"author_id": 3221,
"author_profile": "https://Stackoverflow.com/users/3221",
"pm_score": 0,
"selected": false,
"text": "<p>Well, in a major brazilian bank corporation (Banco do Brasil) which is known by having one of the world´s most secure and efficient home banking software, they simply put history.go(1) in every page.So, if you hit the back button, you will be returned. Simple.</p>\n"
},
{
"answer_id": 88467,
"author": "Claus Thomsen",
"author_id": 15555,
"author_profile": "https://Stackoverflow.com/users/15555",
"pm_score": 5,
"selected": true,
"text": "<p>The short answer is that it cannot be done securely.</p>\n\n<p>There are, however, a lot of tricks that can be implemented to make it difficult for users to hit back and get sensitive data displayed.</p>\n\n<pre><code>Response.Cache.SetCacheability(HttpCacheability.NoCache);\nResponse.Cache.SetExpires(Now.AddSeconds(-1));\nResponse.Cache.SetNoStore();\nResponse.AppendHeader(\"Pragma\", \"no-cache\");\n</code></pre>\n\n<p>This will disable caching on client side, however this is <strong>not supported by all browsers</strong>.</p>\n\n<p>If you have the option of using AJAX then sensitive data can be retrieved using a updatepanel that is updated from client code and therefore it will not be displayed when hitting back unless client is still logged in.</p>\n"
},
{
"answer_id": 107330,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>Please look into the HTTP response headers. Most of the ASP code that people are posting looks to be setting those. Be sure.</p>\n\n<p>The <a href=\"http://oreilly.com/catalog/9781565925090/\" rel=\"nofollow noreferrer\">chipmunk book from O'Reilly</a> is the bible of HTTP, and <a href=\"http://www.informit.com/store/product.aspx?isbn=0672324547\" rel=\"nofollow noreferrer\">Chris Shiflett's HTTP book</a> is good as well.</p>\n"
},
{
"answer_id": 217117,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.13\" rel=\"noreferrer\">Cache and history are independent</a> and one shouldn't affect each other.</p>\n\n<p>The only exception <a href=\"http://my.opera.com/yngve/blog/2007/02/27/introducing-cache-contexts-or-why-the\" rel=\"noreferrer\">made for banks</a> is that combination of HTTPS and <code>Cache-Control: must-revalidate</code> forces refresh when navigating in history.</p>\n\n<p>In plain HTTP there's no way to do this except by exploiting browser bugs.</p>\n\n<p>You could hack around it using Javascript that checks <code>document.cookie</code> and redirects when a \"killer\" cookie is set, but I imagine this could go seriously wrong when browser doesn't set/clear cookies exactly as expected.</p>\n"
},
{
"answer_id": 417162,
"author": "Ed Griebel",
"author_id": 3889,
"author_profile": "https://Stackoverflow.com/users/3889",
"pm_score": 0,
"selected": false,
"text": "<p>You can have the web page with the sensitive be returned as an HTTP POST, then in most cases browsers will give you the message asking if you want want to resubmit the data. (Unfortunately I cannot find a canonical source for this behavior.)</p>\n"
},
{
"answer_id": 767611,
"author": "User",
"author_id": 62830,
"author_profile": "https://Stackoverflow.com/users/62830",
"pm_score": 0,
"selected": false,
"text": "<p>I just had the banking example in mind.</p>\n\n<p>The page of my bank has this in it:</p>\n\n<pre><code><meta http-equiv=\"expires\" content=\"0\" />\n</code></pre>\n\n<p>This should be about this I suppose.</p>\n"
},
{
"answer_id": 768884,
"author": "Jason Coyne",
"author_id": 56472,
"author_profile": "https://Stackoverflow.com/users/56472",
"pm_score": 1,
"selected": false,
"text": "<p>You could have a javascript function does a quick server check (ajax) and if the user is not logged in, erases the current page and replaces it with a message. This would obviously be vulnerable to a user whos javascript is off, but that is pretty rare. On the upside, this is both browser and server technology (asp/php etc) agnostic.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
]
| I have some website which requires a logon and shows sensitive information.
The person goes to the page, is prompted to log in, then gets to see the information.
The person logs out of the site, and is redirected back to the login page.
The person then can hit "back" and go right back to the page where the sensitive information is contained. Since the browser just thinks of it as rendered HTML, it shows it to them no problem.
Is there a way to prevent that information from being displayed when the person hits the "back" button from the logged out screen? I'm not trying to disable the back button itself, I'm just trying to keep the sensitive information from being displayed again because the person is not logged into the site anymore.
For the sake of argument, the above site/scenario is in ASP.NET with Forms Authentication (so when the user goes to the first page, which is the page they want, they're redirected to the logon page - in case that makes a difference). | The short answer is that it cannot be done securely.
There are, however, a lot of tricks that can be implemented to make it difficult for users to hit back and get sensitive data displayed.
```
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(Now.AddSeconds(-1));
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
```
This will disable caching on client side, however this is **not supported by all browsers**.
If you have the option of using AJAX then sensitive data can be retrieved using a updatepanel that is updated from client code and therefore it will not be displayed when hitting back unless client is still logged in. |
64,139 | <p>I have a usercontrol that has several public properties. These properties automatically show up in the properties window of the VS2005 designer under the "Misc" category. Except two of the properties which are enumerations don't show up correctly.</p>
<p>The first on uses the following enum:</p>
<pre><code>public enum VerticalControlAlign
{
Center,
Top,
Bottom
}
</code></pre>
<p>This does not show up in the designer <em>at all.</em></p>
<p>The second uses this enum:</p>
<pre><code>public enum AutoSizeMode
{
None,
KeepInControl
}
</code></pre>
<p>This one shows up, but the designer seems to think it's a bool and only shows True and False. And when you build a project using the controls it will say that it can't convert type bool to AutoSizeMode.</p>
<p>Also, these enums are declared globably to the Namespace, so they are accessible everywhere.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 64175,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": true,
"text": "<p>For starters, the second enum, AutoSizeMode is declared in System.Windows.Forms. So that might cause the designer some issues.</p>\n\n<p>Secondly, you might find the following page on MSDN useful:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx</a></p>\n"
},
{
"answer_id": 64188,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 0,
"selected": false,
"text": "<p>Some things to try (designer mode in VS2005 I have found to be somewhat flaky):</p>\n\n<ol>\n<li>Open your web.config and add: <code>batch=\"false\"</code> to your <code><compilation></code> tag.</li>\n<li><p>Try setting defaults to your enums:</p>\n\n<pre><code>public enum VerticalControlAlign\n{\n Center = 0,\n Top = 1,\n Bottom = 2\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 64210,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 0,
"selected": false,
"text": "<p>You do not need to make your enums global in order for them to be visible in the designer.</p>\n\n<p>Clarify please: </p>\n\n<ol>\n<li>if you add another value to your AutoSizeMode enum, does it still appear as a boolean? </li>\n<li>If (instead) you change the name of enum, does it still appear as a boolean?</li>\n</ol>\n"
},
{
"answer_id": 64326,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "<p>I made a little test with your problem (I'm not sure if I understood it correctly), and these properties shows up in the designer correctly, and all enums are shown appropriately. If this isn't what you're looking for, then please explain yourself further. </p>\n\n<p>Don't get hang up on the _Ugly part thrown in there. I just used it for a quick test.</p>\n\n<pre><code>using System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace SampleApplication\n{\n public partial class CustomUserControl : UserControl\n {\n public CustomUserControl()\n {\n InitializeComponent();\n }\n\n /// <summary>\n /// We're hiding AutoSizeMode in UserControl here.\n /// </summary>\n public new enum AutoSizeMode { None, KeepInControl }\n public enum VerticalControlAlign { Center, Top, Bottom }\n\n /// <summary>\n /// Note that you cannot have a property \n /// called VerticalControlAlign if it is \n /// already defined in the scope.\n /// </summary>\n [DisplayName(\"VerticalControlAlign\")]\n [Category(\"stackoverflow.com\")]\n [Description(\"Sets the vertical control align\")]\n public VerticalControlAlign VerticalControlAlign_Ugly\n {\n get { return m_align; }\n set { m_align = value; }\n }\n private VerticalControlAlign m_align; \n\n /// <summary>\n /// Note that you cannot have a property \n /// called AutoSizeMode if it is \n /// already defined in the scope.\n /// </summary>\n [DisplayName(\"AutoSizeMode\")]\n [Category(\"stackoverflow.com\")]\n [Description(\"Sets the auto size mode\")]\n public AutoSizeMode AutoSizeMode_Ugly\n {\n get { return m_autoSize; }\n set { m_autoSize = value; }\n }\n private AutoSizeMode m_autoSize; \n }\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
| I have a usercontrol that has several public properties. These properties automatically show up in the properties window of the VS2005 designer under the "Misc" category. Except two of the properties which are enumerations don't show up correctly.
The first on uses the following enum:
```
public enum VerticalControlAlign
{
Center,
Top,
Bottom
}
```
This does not show up in the designer *at all.*
The second uses this enum:
```
public enum AutoSizeMode
{
None,
KeepInControl
}
```
This one shows up, but the designer seems to think it's a bool and only shows True and False. And when you build a project using the controls it will say that it can't convert type bool to AutoSizeMode.
Also, these enums are declared globably to the Namespace, so they are accessible everywhere.
Any ideas? | For starters, the second enum, AutoSizeMode is declared in System.Windows.Forms. So that might cause the designer some issues.
Secondly, you might find the following page on MSDN useful:
<http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx> |
64,141 | <p>In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class? </p>
<p>So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class. </p>
<p>The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.</p>
| [
{
"answer_id": 64163,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 4,
"selected": true,
"text": "<p>A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.</p>\n\n<pre><code>class dog(object):\n def __init__(self, height, width, lenght):\n self.height = height\n self.width = width\n self.length = length\n\n def revert(self):\n self.height = 1\n self.width = 2\n self.length = 3\n\ndog1 = dog(5, 6, 7)\ndog2 = dog(2, 3, 4)\n\ndog1.revert()\n</code></pre>\n"
},
{
"answer_id": 64195,
"author": "Håkan",
"author_id": 8420,
"author_profile": "https://Stackoverflow.com/users/8420",
"pm_score": 1,
"selected": false,
"text": "<p>Classes don't have values. Objects do. Is what you want basically a class that can reset an instance (object) to a set of default values? </p>\n\n<p>How about just providing a reset method, that resets the properties of your object to whatever is the default?</p>\n\n<p>I think you should simplify your question, or tell us what you really want to do. It's not at all clear.</p>\n"
},
{
"answer_id": 64206,
"author": "eordano",
"author_id": 8393,
"author_profile": "https://Stackoverflow.com/users/8393",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are confused. You should re-check the meaning of \"class\" and \"instance\".</p>\n\n<p>I think you are trying to first declare a Instance of a certain Class, and then declare a instance of other Class, use the data from the first one, and then find a way to convert the data in the second instance and use it on the first instance...</p>\n\n<p>I recommend that you use operator overloading to assign the data.</p>\n"
},
{
"answer_id": 64216,
"author": "Drag0n",
"author_id": 8433,
"author_profile": "https://Stackoverflow.com/users/8433",
"pm_score": 1,
"selected": false,
"text": "<pre><code>class ABC(self):\n numbers = [0,1,2,3]\n\nclass DEF(ABC):\n def __init__(self):\n self.new_numbers = super(ABC,self).numbers\n\n def setnums(self, numbers):\n self.new_numbers = numbers\n\n def getnums(self):\n return self.new_numbers\n\n def reset(self):\n __init__()\n</code></pre>\n"
},
{
"answer_id": 64399,
"author": "pobk",
"author_id": 7829,
"author_profile": "https://Stackoverflow.com/users/7829",
"pm_score": 1,
"selected": false,
"text": "<p>Just FYI, here's an alternate implementation... Probably violates about 15 million pythonic rules, but I publish it per information/observation:</p>\n\n<pre><code>class Resettable(object):\n base_dict = {}\n def reset(self):\n self.__dict__ = self.__class__.base_dict\n\n def __init__(self):\n self.__dict__ = self.__class__.base_dict.copy()\n\nclass SomeClass(Resettable):\n base_dict = {\n 'number_one': 1,\n 'number_two': 2,\n 'number_three': 3,\n 'number_four': 4,\n 'number_five': 5,\n }\n def __init__(self):\n Resettable.__init__(self)\n\n\np = SomeClass()\np.number_one = 100\nprint p.number_one\np.reset()\nprint p.number_one\n</code></pre>\n"
},
{
"answer_id": 82969,
"author": "Steve Losh",
"author_id": 13498,
"author_profile": "https://Stackoverflow.com/users/13498",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another answer kind of like pobk's; it uses the instance's dict to do the work of saving/resetting variables, but doesn't require you to specify the names of them in your code. You can call save() at any time to save the state of the instance and reset() to reset to that state.</p>\n\n<pre><code>class MyReset:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.save()\n\n def save(self):\n self.saved = self.__dict__.copy()\n\n def reset(self):\n self.__dict__ = self.saved.copy()\n\na = MyReset(20, 30)\na.x = 50\nprint a.x\na.reset()\nprint a.x\n</code></pre>\n\n<p>Why do you want to do this? It might not be the best/only way.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8324/"
]
| In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class?
So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class.
The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable. | A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.
```
class dog(object):
def __init__(self, height, width, lenght):
self.height = height
self.width = width
self.length = length
def revert(self):
self.height = 1
self.width = 2
self.length = 3
dog1 = dog(5, 6, 7)
dog2 = dog(2, 3, 4)
dog1.revert()
``` |
64,146 | <p>When a script is saved as a bundle, it can use the <code>localized string</code> command to find the appropriate string, e.g. in <code>Contents/Resources/English.lproj/Localizable.strings</code>. If this is a format string, what is the best way to fill in the placeholders? In other words, what is the AppleScript equivalent of <code>+[NSString stringWithFormat:]</code>?</p>
<p>One idea I had was to use <code>do shell script</code> with <code>printf(1)</code>. Is there a better way?</p>
| [
{
"answer_id": 66899,
"author": "nlanza",
"author_id": 9373,
"author_profile": "https://Stackoverflow.com/users/9373",
"pm_score": 0,
"selected": false,
"text": "<p>As ugly as it is, calling out to <code>printf(1)</code> is the common solution.</p>\n\n<p>A cleaner, though somewhat more complex, solution is to use AppleScript Studio, which allows you to call into Objective-C objects/classes from your AppleScript code with the <code>call method</code> syntax documented <a href=\"http://developer.apple.com/documentation/AppleScript/Conceptual/StudioBuildingApps/chapter04/chapter_4_section_2.html#//apple_ref/doc/uid/20001251-TPXREF175\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>With that, you'd be able to use something like this:</p>\n\n<pre><code>call method \"stringWithFormat:\" of class \"NSString\" with parameters {formatString, arguments}\n</code></pre>\n\n<p>The downside of this, of course, is that you need to write an AppleScript Studio app instead of just writing a simple script. You do get a good bit more flexibility in general with Studio apps, though, so it's not all together a terrible route to go.</p>\n"
},
{
"answer_id": 41405599,
"author": "Minh Nguyễn",
"author_id": 4585461,
"author_profile": "https://Stackoverflow.com/users/4585461",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"https://developer.apple.com/library/content/releasenotes/AppleScript/RN-AppleScript/RN-10_10/RN-10_10.html\" rel=\"nofollow noreferrer\">Since OS X 10.10</a>, it’s been possible for any AppleScript script to use Objective-C. There are a few ways to call Objective-C methods from within AppleScript, as detailed in <a href=\"https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AppendixA-AppleScriptObjCQuickTranslationGuide.html\" rel=\"nofollow noreferrer\">this translation guide</a>. An Objective-C developer like me would gravitate toward this syntax, which interpolates the method's parameters with their values:</p>\n\n<pre><code>use framework \"Foundation\"\n\ntell the current application's NSWorkspace's sharedWorkspace to openFile:\"/Users/me/Desktop/filter.png\" withApplication:\"Preview\"\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>true\n</code></pre>\n\n<p><code>+[NSString stringWithFormat:]</code> is a tricky case. It takes a vararg list as its first parameter, so you need some way to force both the format string and its arguments into the same method parameter. The following results in an error, because AppleScript ends up passing a single NSArray into the parameter that expects, conceptually, a C array of NSStrings:</p>\n\n<pre><code>use framework \"Foundation\"\n\nthe current application's NSString's stringWithFormat:{\"%lu documents\", 8}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>error \"-[__NSArrayM length]: unrecognized selector sent to instance 0x7fd8d59f3bf0\" number -10000\n</code></pre>\n\n<p>Instead, you have to use an alternative syntax that looks more like an AppleScript handler call than an Objective-C message. You also need to coerce the return value (an NSString object) into a <code>text</code>:</p>\n\n<pre><code>use framework \"Foundation\"\n\nthe current application's NSString's stringWithFormat_(\"%lu documents\", 8) as text\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>\"2087 documents\"\n</code></pre>\n\n<p>The “with parameters” syntax that @nlanza mentions points to the fact that AppleScript is using something akin to <a href=\"https://developer.apple.com/reference/foundation/nsinvocation\" rel=\"nofollow noreferrer\">NSInvocation</a> under the hood. In Objective-C, NSInvocation allows you to send a message to an object, along with an array of parameter values, without necessarily matching each value to a particular parameter. (See <a href=\"http://theocacao.com/document.page/264\" rel=\"nofollow noreferrer\">this article</a> for some examples of using NSInvocation directly.)</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311/"
]
| When a script is saved as a bundle, it can use the `localized string` command to find the appropriate string, e.g. in `Contents/Resources/English.lproj/Localizable.strings`. If this is a format string, what is the best way to fill in the placeholders? In other words, what is the AppleScript equivalent of `+[NSString stringWithFormat:]`?
One idea I had was to use `do shell script` with `printf(1)`. Is there a better way? | [Since OS X 10.10](https://developer.apple.com/library/content/releasenotes/AppleScript/RN-AppleScript/RN-10_10/RN-10_10.html), it’s been possible for any AppleScript script to use Objective-C. There are a few ways to call Objective-C methods from within AppleScript, as detailed in [this translation guide](https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AppendixA-AppleScriptObjCQuickTranslationGuide.html). An Objective-C developer like me would gravitate toward this syntax, which interpolates the method's parameters with their values:
```
use framework "Foundation"
tell the current application's NSWorkspace's sharedWorkspace to openFile:"/Users/me/Desktop/filter.png" withApplication:"Preview"
```
Result:
```
true
```
`+[NSString stringWithFormat:]` is a tricky case. It takes a vararg list as its first parameter, so you need some way to force both the format string and its arguments into the same method parameter. The following results in an error, because AppleScript ends up passing a single NSArray into the parameter that expects, conceptually, a C array of NSStrings:
```
use framework "Foundation"
the current application's NSString's stringWithFormat:{"%lu documents", 8}
```
Result:
```
error "-[__NSArrayM length]: unrecognized selector sent to instance 0x7fd8d59f3bf0" number -10000
```
Instead, you have to use an alternative syntax that looks more like an AppleScript handler call than an Objective-C message. You also need to coerce the return value (an NSString object) into a `text`:
```
use framework "Foundation"
the current application's NSString's stringWithFormat_("%lu documents", 8) as text
```
Result:
```
"2087 documents"
```
The “with parameters” syntax that @nlanza mentions points to the fact that AppleScript is using something akin to [NSInvocation](https://developer.apple.com/reference/foundation/nsinvocation) under the hood. In Objective-C, NSInvocation allows you to send a message to an object, along with an array of parameter values, without necessarily matching each value to a particular parameter. (See [this article](http://theocacao.com/document.page/264) for some examples of using NSInvocation directly.) |
64,193 | <p>I am using the AJAX Control Toolkit Popup Calendar Control in a datagrid. When it is in the footer it looks fine. When it is in the edit side of the datagrid it is inheriting the style from the datagrid and looks completely different (i.e. too big). </p>
<p>Is there a way to alter the CSS so that it does not inherit the style from the datagrid?</p>
| [
{
"answer_id": 64245,
"author": "McKay",
"author_id": 8384,
"author_profile": "https://Stackoverflow.com/users/8384",
"pm_score": 0,
"selected": false,
"text": "<p>It uses the style from the grid, because it's in it. If you want to change it's style, change the style of the control. What do you want it to do?</p>\n"
},
{
"answer_id": 64317,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": 2,
"selected": true,
"text": "<p>Open the page in firefox. However, first, download the firebug extension. Then, right click on the offending version and go down to inspect element.</p>\n\n<p>Firebug is awesome because it let's you navigate the css of any element. You have two options here:</p>\n\n<p>1) Assign the topmost element an css class and work it that way. \nor\nIf that's not an option, you can use firebug to get the xpath to the offending element. \nXpaths look like body/table/tr/td/table/tr[2]</p>\n\n<p>what you want to do with that in css is</p>\n\n<pre><code>body table tr td table tr {\n /*css goes here */\n\n}\n</code></pre>\n\n<p>Option 1 is definitely the better pick. Option 2 is more of a dirty way of getting things\ndone when things like asp.net doesn't let us have the fine grain of control we want.</p>\n\n<p>It would be really awesome if you used a pastebin and posted the link to your rendered page's html. </p>\n"
},
{
"answer_id": 64842,
"author": "Travis",
"author_id": 7316,
"author_profile": "https://Stackoverflow.com/users/7316",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the pastebin link:</p>\n\n<p><a href=\"http://pastebin.com/m17d99f8a\" rel=\"nofollow noreferrer\">http://pastebin.com/m17d99f8a</a></p>\n\n<p>I am using a stylesheet for the grid that I got from Matt Berseth's blog located here:\n<a href=\"http://mattberseth.com/blog/2007/10/a_yui_datatable_styled_gridvie.html\" rel=\"nofollow noreferrer\">http://mattberseth.com/blog/2007/10/a_yui_datatable_styled_gridvie.html</a></p>\n\n<p>I am using a similar stylesheet for the calendar that I cannot find the link for anymore.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7316/"
]
| I am using the AJAX Control Toolkit Popup Calendar Control in a datagrid. When it is in the footer it looks fine. When it is in the edit side of the datagrid it is inheriting the style from the datagrid and looks completely different (i.e. too big).
Is there a way to alter the CSS so that it does not inherit the style from the datagrid? | Open the page in firefox. However, first, download the firebug extension. Then, right click on the offending version and go down to inspect element.
Firebug is awesome because it let's you navigate the css of any element. You have two options here:
1) Assign the topmost element an css class and work it that way.
or
If that's not an option, you can use firebug to get the xpath to the offending element.
Xpaths look like body/table/tr/td/table/tr[2]
what you want to do with that in css is
```
body table tr td table tr {
/*css goes here */
}
```
Option 1 is definitely the better pick. Option 2 is more of a dirty way of getting things
done when things like asp.net doesn't let us have the fine grain of control we want.
It would be really awesome if you used a pastebin and posted the link to your rendered page's html. |
64,214 | <p>I read everywhere that business logic belongs in the models and not in controller but where is the limit?
I am toying with a personnal accounting application. </p>
<pre><code>Account
Entry
Operation
</code></pre>
<p>When creating an operation it is only valid if the corresponding entries are created and linked to accounts so that the operation is balanced for exemple buy a 6-pack :</p>
<pre><code>o=Operation.new({:description=>"b33r", :user=>current_user, :date=>"2008/09/15"})
o.entries.build({:account_id=>1, :amount=>15})
o.valid? #=>false
o.entries.build({:account_id=>2, :amount=>-15})
o.valid? #=>true
</code></pre>
<p>Now the form shown to the user in the case of <em>basic operations</em> is simplified to hide away the entries details, the accounts are selected among 5 default by the kind of operation requested by the user (intialise account -> equity to accout, spend assets->expenses, earn revenues->assets, borrow liabilities->assets, pay debt assets->liabilities ...) I want the entries created from default values.</p>
<p>I also want to be able to create more complex operations (more than 2 entries). For this second use case I will have a different form where the additional complexity is exposed.This second use case prevents me from including a debit and credit field on the Operation and getting rid of the Entry link. </p>
<p>Which is the best form ? Using the above code in a SimpleOperationController as I do for the moment, or defining a new method on the Operation class so I can call Operation.new_simple_operation(params[:operation])</p>
<p>Isn't it breaking the separation of concerns to actually create and manipulate Entry objects from the Operation class ?</p>
<p>I am not looking for advice on my twisted accounting principles :)</p>
<p>edit -- It seems I didn't express myself too clearly.
I am not so concerned about the validation. I am more concerned about where the creation logic code should go : </p>
<p>assuming the operation on the controller is called spend, when using spend, the params hash would contain : amount, date, description. Debit and credit accounts would be derived from the action which is called, but then I have to create all the objects. Would it be better to have </p>
<pre><code>#error and transaction handling is left out for the sake of clarity
def spend
amount=params[:operation].delete(:amount)#remove non existent Operation attribute
op=Operation.new(params[:operation])
#select accounts in some way
...
#build entries
op.entries.build(...)
op.entries.build(...)
op.save
end
</code></pre>
<p>or to create a method on Operation that would make the above look like </p>
<pre><code>def spend
op=Operation.new_simple_operation(params)
op.save
end
</code></pre>
<p>this definitely give a much thinner controller and a fatter model, but then the model will create and store instances of other models which is where my problem is.</p>
| [
{
"answer_id": 64389,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It's easier to think in terms of each entity validating itself, and entities which depend on one another delegating their state to the state of their associated entries. In your case, for instance:</p>\n\n<pre><code>class Operation < ActiveRecord::Base\n has_many :entries\n validates_associated :entries\nend\n</code></pre>\n\n<p>validates_associated will check whether each associated entity is valid (in this case, all entries should if the operation is to be valid).</p>\n\n<p>It is very tempting to try to validate entire hierarchies of models as a whole, but as you said, the place where that would be most easily done is the controller, which should act more as a router of requests and responses than in dealing with business logic.</p>\n"
},
{
"answer_id": 66025,
"author": "Michael Latta",
"author_id": 9679,
"author_profile": "https://Stackoverflow.com/users/9679",
"pm_score": 0,
"selected": false,
"text": "<p>The way I look at it is that the controller should reflect the end-user view and translate requests into model operations and reponses while also doing formatting. In your case there are 2 kinds of operations that represent simple operations with a default account/entry, and more complex operations that have user selected entries and accounts. The forms should reflect the user view (2 forms with different fields), and there should be 2 actions in the controller to match. The controller however should have no logic relating to how the data is manipulated, only how to receive and respond. I would have class methods on the Operation class that take in the proper data from the forms and creates one or more object as needed, or place those class methods on a support class that is not an AR model, but has business logic that crosses model boundaries. The advantage of the separate utility class is that it keeps each model focused on one purpose, the down side is that the utility classes have no defined place to live. I put them in lib/ but Rails does not specify a place for model helpers as such.</p>\n"
},
{
"answer_id": 66985,
"author": "Sixty4Bit",
"author_id": 1681,
"author_profile": "https://Stackoverflow.com/users/1681",
"pm_score": 2,
"selected": false,
"text": "<p>Virtual Attributes (more info <a href=\"http://railscasts.com/episodes/16\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://railscasts.com/episodes/73\" rel=\"nofollow noreferrer\">here</a>) will help with this greatly. Passing the whole params back to the model keeps things simple in the controller. This will allow you to dynamically build your form and easily build the entries objects.</p>\n\n<pre><code>class Operation\n has_many :entries\n\n def entry_attributes=(entry_attributes)\n entry_attributes.each do |entry|\n entries.build(entry)\n end\n end\n\nend\n\nclass OperationController < ApplicationController\n def create\n @operation = Operation.new(params[:opertaion])\n if @operation.save\n flash[:notice] = \"Successfully saved operation.\"\n redirect_to operations_path\n else\n render :action => 'new'\n end\n end\nend\n</code></pre>\n\n<p>The save will fail if everything isn't valid. Which brings us to validation. Because each Entry stands alone and you need to check all entries at \"creation\" you should probably override validate in Operation:</p>\n\n<pre><code>class Operation\n # methods from above\n protected\n def validate\n total = 0\n entries.each { |e| t += e.amount }\n errors.add(\"entries\", \"unbalanced transfers\") unless total == 0\n end\nend\n</code></pre>\n\n<p>Now you will get an error message telling the user that the amounts are off and they should fix the problem. You can get really fancy here and add a lot of value by being specific about the problem, like tell them how much they are off.</p>\n"
},
{
"answer_id": 67077,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>but then the model will create and store instances of other models which is where my problem is.</p>\n</blockquote>\n\n<p>What is wrong with this? </p>\n\n<p>If your 'business logic' states that an Operation must have a valid set of Entries, then surely there is nothing wrong for the Operation class to know about, and deal with your Entry objects.</p>\n\n<p>You'll only get problems if you take this too far, and have your models manipulating things they <em>don't</em> need to know about, like an EntryHtmlFormBuilder or whatever :-)</p>\n"
},
{
"answer_id": 103811,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 0,
"selected": false,
"text": "<p>If you are concerned about embedding this logic into any particular model, why not put them into an observer class, that will keep the logic for your creation of the associated items separate from the classes being observed.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7898/"
]
| I read everywhere that business logic belongs in the models and not in controller but where is the limit?
I am toying with a personnal accounting application.
```
Account
Entry
Operation
```
When creating an operation it is only valid if the corresponding entries are created and linked to accounts so that the operation is balanced for exemple buy a 6-pack :
```
o=Operation.new({:description=>"b33r", :user=>current_user, :date=>"2008/09/15"})
o.entries.build({:account_id=>1, :amount=>15})
o.valid? #=>false
o.entries.build({:account_id=>2, :amount=>-15})
o.valid? #=>true
```
Now the form shown to the user in the case of *basic operations* is simplified to hide away the entries details, the accounts are selected among 5 default by the kind of operation requested by the user (intialise account -> equity to accout, spend assets->expenses, earn revenues->assets, borrow liabilities->assets, pay debt assets->liabilities ...) I want the entries created from default values.
I also want to be able to create more complex operations (more than 2 entries). For this second use case I will have a different form where the additional complexity is exposed.This second use case prevents me from including a debit and credit field on the Operation and getting rid of the Entry link.
Which is the best form ? Using the above code in a SimpleOperationController as I do for the moment, or defining a new method on the Operation class so I can call Operation.new\_simple\_operation(params[:operation])
Isn't it breaking the separation of concerns to actually create and manipulate Entry objects from the Operation class ?
I am not looking for advice on my twisted accounting principles :)
edit -- It seems I didn't express myself too clearly.
I am not so concerned about the validation. I am more concerned about where the creation logic code should go :
assuming the operation on the controller is called spend, when using spend, the params hash would contain : amount, date, description. Debit and credit accounts would be derived from the action which is called, but then I have to create all the objects. Would it be better to have
```
#error and transaction handling is left out for the sake of clarity
def spend
amount=params[:operation].delete(:amount)#remove non existent Operation attribute
op=Operation.new(params[:operation])
#select accounts in some way
...
#build entries
op.entries.build(...)
op.entries.build(...)
op.save
end
```
or to create a method on Operation that would make the above look like
```
def spend
op=Operation.new_simple_operation(params)
op.save
end
```
this definitely give a much thinner controller and a fatter model, but then the model will create and store instances of other models which is where my problem is. | >
> but then the model will create and store instances of other models which is where my problem is.
>
>
>
What is wrong with this?
If your 'business logic' states that an Operation must have a valid set of Entries, then surely there is nothing wrong for the Operation class to know about, and deal with your Entry objects.
You'll only get problems if you take this too far, and have your models manipulating things they *don't* need to know about, like an EntryHtmlFormBuilder or whatever :-) |
64,258 | <p>I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista:</p>
<pre><code>"Decryption failed. Key not valid for use in specified state."
</code></pre>
<p>As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update).</p>
<p>More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off.</p>
<p>Anyone seen this one before?</p>
| [
{
"answer_id": 64301,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/aa380882.aspx\" rel=\"nofollow noreferrer\">CryptUnprotectData function</a> documentation states that it usually only works when the user has the same logon credentials as the encrypter.</p>\n\n<p>This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens.</p>\n\n<p>Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers?</p>\n"
},
{
"answer_id": 64646,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 1,
"selected": false,
"text": "<p>Nice. Hopefully this is my bone-head move of the week! ;-)</p>\n\n<blockquote>\n <p>This suggests to me that maybe the key\n is tied to the user's current token.</p>\n</blockquote>\n\n<p>That was it. Turns out I was using encrypted data from another machine (the XP one) and trying to decrypt on the Vista machine.</p>\n\n<p>As the MSDN documentation states:</p>\n\n<blockquote>\n <p>Usually, only a user with the same\n logon credentials as the encrypter can\n decrypt the data. In addition, <strong>the\n encryption and decryption must be done\n on the same computer.</strong></p>\n</blockquote>\n\n<p>Once I re-encrypted the data on the Vista machine, decryption works as expected.</p>\n\n<p>Thanks.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
]
| I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista:
```
"Decryption failed. Key not valid for use in specified state."
```
As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update).
More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off.
Anyone seen this one before? | The [CryptUnprotectData function](http://msdn.microsoft.com/en-us/library/aa380882.aspx) documentation states that it usually only works when the user has the same logon credentials as the encrypter.
This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens.
Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers? |
64,272 | <p>I want to create a custom control in C#. But every time I have to fully redraw my control, it flickers, even if I use double buffering (drawing to an Image first, and blitting that).</p>
<p>How do I eliminate flicker when I have to fully redraw?</p>
| [
{
"answer_id": 64336,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 0,
"selected": false,
"text": "<p>You say you've tried double buffering, but then you say drawing to an Image first and blitting that. Have you tried setting DoubleBuffered = true in the constructor rather than doing it yourself with an Image?</p>\n"
},
{
"answer_id": 64507,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 5,
"selected": true,
"text": "<p>You could try putting the following in your constructor after the InitiliseComponent call. </p>\n\n<pre><code>SetStyle(ControlStyles.OptimizedDoubleBuffer | \n ControlStyles.UserPaint |\n ControlStyles.AllPaintingInWmPaint, true);\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>If you're giving this a go, if you can, remove your own double buffering code and just have the control draw itself in response to the appropriate virtual methods being called.</p>\n"
},
{
"answer_id": 80273,
"author": "Eric W",
"author_id": 14972,
"author_profile": "https://Stackoverflow.com/users/14972",
"pm_score": 1,
"selected": false,
"text": "<p>It may be good enough to just call </p>\n\n<pre><code>SetStyle(ControlStyles::UserPaint | ControlStyles::AllDrawingInWmPaint, true);\n</code></pre>\n\n<p>The flickering you are seeing most likely because Windows draws the background of the control first (via WM_ERASEBKGND), then asks your control to do whatever drawing you need to do (via WM_PAINT). By disabling the background paint and doing all painting in your OnPaint override can eliminate the problem in 99% of the cases without the need to use all the memory needed for double buffering.</p>\n"
},
{
"answer_id": 358239,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 3,
"selected": false,
"text": "<p>I pulled this from a working C# program. Other posters have syntax errors and clearly copied from C++ instead of C#</p>\n\n<pre><code>SetStyle(ControlStyles.OptimizedDoubleBuffer | \n ControlStyles.UserPaint |\n ControlStyles.AllPaintingInWmPaint, true);\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7305/"
]
| I want to create a custom control in C#. But every time I have to fully redraw my control, it flickers, even if I use double buffering (drawing to an Image first, and blitting that).
How do I eliminate flicker when I have to fully redraw? | You could try putting the following in your constructor after the InitiliseComponent call.
```
SetStyle(ControlStyles.OptimizedDoubleBuffer |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint, true);
```
EDIT:
If you're giving this a go, if you can, remove your own double buffering code and just have the control draw itself in response to the appropriate virtual methods being called. |
64,284 | <p>Let's say I have a list of categories for navigation on a web app. Rather than selecting from the database for every user, should I add a function call in the application_onStart of the global.asax to fetch that data into an array or collection that is re-used over and over. If my data does not change at all - (Edit - very often), would this be the best way?</p>
| [
{
"answer_id": 64307,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>I use a static collection as a private with a public static property that either loads or gets it from the database.</p>\n\n<p>Additionally you can add a static datetime that gets set when it gets loaded and if you call for it, past a certain amount of time, clear the static collection and requery it.</p>\n"
},
{
"answer_id": 64319,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 1,
"selected": false,
"text": "<p>If it never changes, it probably doesn't need to be in the database.</p>\n\n<p>If there isn't much data, you might put it in the web.config, or as en Enum in your code.</p>\n"
},
{
"answer_id": 64339,
"author": "Vadym Stetsiak",
"author_id": 6952,
"author_profile": "https://Stackoverflow.com/users/6952",
"pm_score": 1,
"selected": false,
"text": "<p>Fetching all may be expensive. Try lazy init, fetch only request data and then store it in the cache variable.</p>\n"
},
{
"answer_id": 64359,
"author": "Ryan Roper",
"author_id": 8273,
"author_profile": "https://Stackoverflow.com/users/8273",
"pm_score": 2,
"selected": false,
"text": "<p>Premature optimization is evil. That being a given, if you are having performance problems in your application and you have \"static\" information that you want to display to your users you can definitely load that data once into an array and store it in the Application Object. You want to be careful and balance memory usage with optimization.</p>\n\n<p>The problem you run into then is changing the database stored info and not having it update the cached version. You would probably want to have some kind of last changed date in the database that you store in the state along with the cached data. That way you can query for the greatest changed time and compare it. If it's newer than your cached date then you dump it and reload.</p>\n"
},
{
"answer_id": 64361,
"author": "Al.",
"author_id": 7921,
"author_profile": "https://Stackoverflow.com/users/7921",
"pm_score": 1,
"selected": false,
"text": "<p>In an application variable.</p>\n\n<p>Remember that an application variable can contain an object in .Net, so you can instantiate the object in the global.asax and then use it directly in the code.</p>\n\n<p>Since application variables are in-memory they are very quick (vs having to call a database)</p>\n\n<p>For example:</p>\n\n<pre><code>// Create and load the profile object\nx_siteprofile thisprofile = new x_siteprofile(Server.MapPath(String.Concat(config.Path, \"templates/\")));\nApplication.Add(\"SiteProfileX\", thisprofile);\n</code></pre>\n"
},
{
"answer_id": 64840,
"author": "ADB",
"author_id": 3610,
"author_profile": "https://Stackoverflow.com/users/3610",
"pm_score": 3,
"selected": true,
"text": "<p>You can store the list items in the Application object. You are right about the <code>application_onStart()</code>, simply call a method that will read your database and load the data to the Application object.</p>\n\n<p>In Global.asax</p>\n\n<pre><code>public class Global : System.Web.HttpApplication\n{\n // The key to use in the rest of the web site to retrieve the list\n public const string ListItemKey = \"MyListItemKey\";\n // a class to hold your actual values. This can be use with databinding\n public class NameValuePair\n { \n public string Name{get;set;} \n public string Value{get;set;}\n public NameValuePair(string Name, string Value)\n {\n this.Name = Name;\n this.Value = Value;\n }\n }\n\n protected void Application_Start(object sender, EventArgs e)\n {\n InitializeApplicationVariables();\n }\n\n\n protected void InitializeApplicationVariables()\n {\n List<NameValuePair> listItems = new List<NameValuePair>();\n // replace the following code with your data access code and fill in the collection\n listItems.Add( new NameValuePair(\"Item1\", \"1\"));\n listItems.Add( new NameValuePair(\"Item2\", \"2\"));\n listItems.Add( new NameValuePair(\"Item3\", \"3\"));\n // load it in the application object\n Application[ListItemKey] = listItems;\n }\n }\n</code></pre>\n\n<p>Now you can access your list in the rest of the project. For example, in default.aspx to load the values in a DropDownList:</p>\n\n<pre><code><asp:DropDownList runat=\"server\" ID=\"ddList\" DataTextField=\"Name\" DataValueField=\"Value\"></asp:DropDownList>\n</code></pre>\n\n<p>And in the code-behind file:</p>\n\n<pre><code>protected override void OnPreInit(EventArgs e)\n{\n ddList.DataSource = Application[Global.ListItemKey];\n ddList.DataBind();\n base.OnPreInit(e);\n}\n</code></pre>\n"
},
{
"answer_id": 64927,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I would store the data in the Application Cache (Cache object). And I wouldn't preload it, I would load it the first time it is requested. What is nice about the Cache is that ASP.NET will manage it including giving you options for expiring the cache entry after file changes, a time period, etc. And since the items are kept in memory, the objects don't get serialized/deserialized so usage is very fast.</p>\n\n<p>Usage is straightforward. There are Get and Add methods on the Cache object to retrieve and add items to the cache respectively.</p>\n"
},
{
"answer_id": 64957,
"author": "Smallinov",
"author_id": 8897,
"author_profile": "https://Stackoverflow.com/users/8897",
"pm_score": 0,
"selected": false,
"text": "<p>Caching is the way to go. And if your into design patterns, take a look at the singleton.</p>\n\n<p>Overall however I'm not sure I'd be worried about it until you notice performance degradation.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115144/"
]
| Let's say I have a list of categories for navigation on a web app. Rather than selecting from the database for every user, should I add a function call in the application\_onStart of the global.asax to fetch that data into an array or collection that is re-used over and over. If my data does not change at all - (Edit - very often), would this be the best way? | You can store the list items in the Application object. You are right about the `application_onStart()`, simply call a method that will read your database and load the data to the Application object.
In Global.asax
```
public class Global : System.Web.HttpApplication
{
// The key to use in the rest of the web site to retrieve the list
public const string ListItemKey = "MyListItemKey";
// a class to hold your actual values. This can be use with databinding
public class NameValuePair
{
public string Name{get;set;}
public string Value{get;set;}
public NameValuePair(string Name, string Value)
{
this.Name = Name;
this.Value = Value;
}
}
protected void Application_Start(object sender, EventArgs e)
{
InitializeApplicationVariables();
}
protected void InitializeApplicationVariables()
{
List<NameValuePair> listItems = new List<NameValuePair>();
// replace the following code with your data access code and fill in the collection
listItems.Add( new NameValuePair("Item1", "1"));
listItems.Add( new NameValuePair("Item2", "2"));
listItems.Add( new NameValuePair("Item3", "3"));
// load it in the application object
Application[ListItemKey] = listItems;
}
}
```
Now you can access your list in the rest of the project. For example, in default.aspx to load the values in a DropDownList:
```
<asp:DropDownList runat="server" ID="ddList" DataTextField="Name" DataValueField="Value"></asp:DropDownList>
```
And in the code-behind file:
```
protected override void OnPreInit(EventArgs e)
{
ddList.DataSource = Application[Global.ListItemKey];
ddList.DataBind();
base.OnPreInit(e);
}
``` |
64,291 | <p>I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene in an HTML page, by doing something like:</p>
<pre><code><img src="http://www.myserver.com/renderimage?scene=1&x=123&y=123&z=123">
</code></pre>
<p>My question is about what technologies to use to do the rendering. In a desktop application I would quite naturally use DirectX, but I'm afraid it might not be ideal for a server-side application that would be creating images for dozens or even hundreds of users in tandem. Does anyone have any experience with this? Is there a 3D API (preferably freely available) that would be ideal for this application? Is it better to write a software renderer from scratch?</p>
<p>My main concerns about using DirectX or OpenGL, is whether it will function well in a virtualized server environment, and whether it makes sense with typical server hardware (over which I have little control). </p>
| [
{
"answer_id": 64315,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 2,
"selected": false,
"text": "<p>Id say your best bet is have a Direct3D/OpenGL app running on the server (without stopping). THen making the server page send a request to the rendering app, and have the rendering app snend a jpg/png/whatever back.</p>\n\n<ul>\n<li>If Direct3D/OpenGL is to slow to render the scene in hardware, then any software solution will be worse</li>\n<li>By keep the rendering app running, you are avoiding the overhead of creating/destroying textures, backbuffers, vertex buffers, etc. You could potentialy render a simply scene 100's of times a second.</li>\n</ul>\n\n<p>However many servers do not have graphics cards. Direct3D is largly useless in software (there is an emulated device from Ms, but its only good for testing effects), never tried OpenGL in software.</p>\n"
},
{
"answer_id": 64409,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 0,
"selected": false,
"text": "<p>Not so much an API but rather a renderer; <a href=\"http://www.povray.org/\" rel=\"nofollow noreferrer\">Povray</a>? There also seem to exist a <a href=\"http://columbiegg.com/httpov/\" rel=\"nofollow noreferrer\">http</a> interface...</p>\n"
},
{
"answer_id": 64421,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "<p>Server side rendering only makes sense if the scene consists of a huge number of objects such that the download of the data set to the client for client rendering would be far too slow and the rendering is not expected to be in realtime. Client side rendering isn't too difficult if you use something like <a href=\"https://jogl.dev.java.net/\" rel=\"nofollow noreferrer\">jogl</a> coupled with progressive scene download (i.e. download foreground objects and render, then incrementally download objects based on distance from view point and re-render).</p>\n\n<p>If you really want to do server side rendering, you may want to separate the web server part and the rendering part onto two computers with each configured optimally for their task (renderer has OpenGL card, minimal HD and just enough RAM, server has lots of fast disks, lots of ram, backups and no OpenGL). I very much doubt you will be able to do hardware rendering on a virtualised server since the server probably doesn't have a GPU.</p>\n"
},
{
"answer_id": 69035,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 0,
"selected": false,
"text": "<p>Yafaray (<a href=\"http://www.yafaray.org/\" rel=\"nofollow noreferrer\">http://www.yafaray.org/</a>) might be a good first choice to consider for general 3D rendering. It's reasonably fast and the results look great. It can be used within other software, e.g. the Blender 3D modeler. The license is LPGL.</p>\n\n<p>If the server-side software happens to be written in Python, and the desired 3D scene is a visualization of scientific data, look into MayaVi2 <a href=\"http://mayavi.sourceforge.net/\" rel=\"nofollow noreferrer\">http://mayavi.sourceforge.net/</a>, or if not, go for a browse at <a href=\"http://www.vrplumber.com/py3d.py\" rel=\"nofollow noreferrer\">http://www.vrplumber.com/py3d.py</a></p>\n\n<p>Those who suggest the widely popular POV-Ray need to realize it's not a library or any kind of entity that offers an API. The server-side process would need to write a text scene file, execute a new process to run POV-Ray with the right options, and take the resulting image file. If that's easy to set up for a particular application, and if you've more expertise with POV-Ray than with other renderers, well go for it!</p>\n"
},
{
"answer_id": 124881,
"author": "AndrewR",
"author_id": 2994,
"author_profile": "https://Stackoverflow.com/users/2994",
"pm_score": 0,
"selected": false,
"text": "<p>You could also look at Java3D (<a href=\"https://java3d.dev.java.net/\" rel=\"nofollow noreferrer\">https://java3d.dev.java.net/</a>), which would be an elegant solution if your server architecture was Java-based already.</p>\n\n<p>I'd also recommend trying to get away with a software-only rendering solution if you can - trying to wrangle a whole lot of server processes that are all making concurrent demands on the 3D rendering hardware sounds like a lot of work.</p>\n"
},
{
"answer_id": 1266970,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>RealityServer by mental images is designed to do precisely what is described here. More details are available on the product page (including a downloadable Developer Edition).</p>\n\n<p><a href=\"http://www.migenius.com/doc/realityserver/latest/\" rel=\"nofollow noreferrer\">RealityServer docs</a></p>\n"
},
{
"answer_id": 12820722,
"author": "Janus Troelsen",
"author_id": 309483,
"author_profile": "https://Stackoverflow.com/users/309483",
"pm_score": 2,
"selected": false,
"text": "<p>You could wrap Pov-ray (here using POSIX and the Windows build). PHP example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nchdir(\"/tmp\");\n@unlink(\"demo.png\");\nsystem(\"~janus/.wine/drive_c/POV-Ray-v3.7-RC6/bin/pvengine-sse2.exe /render demo.pov /exit\");\nheader(\"Content-type: image/png\");\nfpassthru($f = fopen(\"demo.png\",\"r\"));\nfclose($f);\n?>\n</code></pre>\n\n<p><code>demo.pov</code> available <a href=\"http://www.csb.yale.edu/userguides/graphics/povray/demo.pov.html\" rel=\"nofollow\">here</a>.</p>\n\n<p>You could use a templating language like Jinja2 to insert your own camera coordinates.</p>\n"
},
{
"answer_id": 19776439,
"author": "Magdalena",
"author_id": 2953969,
"author_profile": "https://Stackoverflow.com/users/2953969",
"pm_score": -1,
"selected": false,
"text": "<p>Check out <a href=\"http://www.wgpu.net\" rel=\"nofollow\">wgpu.net</a>.</p>\n\n<p>I think it's very helpful.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8409/"
]
| I'm working on an application that needs to quickly render simple 3D scenes on the server, and then return them as a JPEG via HTTP. Basically, I want to be able to simply include a dynamic 3D scene in an HTML page, by doing something like:
```
<img src="http://www.myserver.com/renderimage?scene=1&x=123&y=123&z=123">
```
My question is about what technologies to use to do the rendering. In a desktop application I would quite naturally use DirectX, but I'm afraid it might not be ideal for a server-side application that would be creating images for dozens or even hundreds of users in tandem. Does anyone have any experience with this? Is there a 3D API (preferably freely available) that would be ideal for this application? Is it better to write a software renderer from scratch?
My main concerns about using DirectX or OpenGL, is whether it will function well in a virtualized server environment, and whether it makes sense with typical server hardware (over which I have little control). | RealityServer by mental images is designed to do precisely what is described here. More details are available on the product page (including a downloadable Developer Edition).
[RealityServer docs](http://www.migenius.com/doc/realityserver/latest/) |
64,311 | <p>The design for the website I am working on calls for a custom image on lists instead of a bullet. Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers. Does anyone know of a standard solution for this?</p>
| [
{
"answer_id": 64340,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried adding the following code in your CSS file?</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>li\n{\n background-image: URL('custom.png');\n background-repeat: no-repeat;\n background-position: center;\n}\n</code></pre>\n"
},
{
"answer_id": 64635,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>If you are referring to using a custom image bullet for your list this is the code you'll want to use, it will be vertically centered. I'm assuming here that the bullet image is 12px by 12px.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>ul li {\n background: transparent url(/link/to/custom/bullet.gif) no-repeat 0 50%; \n padding-left: 18px; \n}\n</code></pre>\n\n<p>The only problem with this is that sometimes on long multi-line list items it looks odd. In that case it might be best to assign the background position to a slight indent from the top and the left (i.e. no-repeat 0 7px). </p>\n\n<p>cheers, Bruce</p>\n"
},
{
"answer_id": 14220281,
"author": "dottwatson",
"author_id": 540283,
"author_profile": "https://Stackoverflow.com/users/540283",
"pm_score": 0,
"selected": false,
"text": "<p>set a specific line-height on the li element and a vertica align on the image.. worked for me </p>\n\n<pre class=\"lang-css prettyprint-override\"><code>li { height: 150px; line-height: 150px; }\nli img { vertical-align: middle; }\n</code></pre>\n\n<p>and the HTML code</p>\n\n<pre><code><li><img src=\"myimage.jpg\" /></li>\n</code></pre>\n\n<p>if you want adapt the image to a custon size, preserving the ratio</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>li img { max-width: 150px; max-height: 150px; width: auto; height: auto; }\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4284/"
]
| The design for the website I am working on calls for a custom image on lists instead of a bullet. Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers. Does anyone know of a standard solution for this? | If you are referring to using a custom image bullet for your list this is the code you'll want to use, it will be vertically centered. I'm assuming here that the bullet image is 12px by 12px.
```css
ul li {
background: transparent url(/link/to/custom/bullet.gif) no-repeat 0 50%;
padding-left: 18px;
}
```
The only problem with this is that sometimes on long multi-line list items it looks odd. In that case it might be best to assign the background position to a slight indent from the top and the left (i.e. no-repeat 0 7px).
cheers, Bruce |
64,351 | <p>I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.</p>
<p>The problem is that inside of my "popup" form, I need to <code>$(function()
{my function here});</code> syntax to do some stuff when the page loads,
along with registering some <code>.fn</code> extensions for some dynamic dropdowns
using ajax calls.</p>
<p>I have created my <code><script type="text/javascript" src="jquery.js"></code> but
I don't think these are being included, and also my <code>$(function)</code> is not
being called.</p>
<p>Is this possible to do or do I need to find another way of
accomplishing what I need to do? </p>
| [
{
"answer_id": 64515,
"author": "Alexey Lebedev",
"author_id": 8338,
"author_profile": "https://Stackoverflow.com/users/8338",
"pm_score": 3,
"selected": true,
"text": "<p>If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.\nSo, you load the popup form like this:</p>\n\n<pre><code>$.ajax({\n //...\n success: function(text) {\n // insert text into container\n // the code from $(function() {});\n }\n});\n</code></pre>\n"
},
{
"answer_id": 164960,
"author": "Ben Crouse",
"author_id": 6705,
"author_profile": "https://Stackoverflow.com/users/6705",
"pm_score": 0,
"selected": false,
"text": "<p>The script isn't getting run because the document's ready event has already been fired. Remove your code from within the </p>\n\n<pre><code>$()\n</code></pre>\n"
},
{
"answer_id": 184651,
"author": "Bopp",
"author_id": 21285,
"author_profile": "https://Stackoverflow.com/users/21285",
"pm_score": 0,
"selected": false,
"text": "<p>Use the livequery plugin. </p>\n\n<p>It allows you to bind events to elements that might be loaded later: <a href=\"http://brandonaaron.net/docs/livequery/\" rel=\"nofollow noreferrer\">http://brandonaaron.net/docs/livequery/</a></p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8534/"
]
| I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.
The problem is that inside of my "popup" form, I need to `$(function()
{my function here});` syntax to do some stuff when the page loads,
along with registering some `.fn` extensions for some dynamic dropdowns
using ajax calls.
I have created my `<script type="text/javascript" src="jquery.js">` but
I don't think these are being included, and also my `$(function)` is not
being called.
Is this possible to do or do I need to find another way of
accomplishing what I need to do? | If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.
So, you load the popup form like this:
```
$.ajax({
//...
success: function(text) {
// insert text into container
// the code from $(function() {});
}
});
``` |
64,360 | <p>When I cut (kill) text in Emacs 22.1.1 (in its own window on X, in KDE, on Kubuntu), I can't paste (yank) it in any other application.</p>
| [
{
"answer_id": 64406,
"author": "kfh",
"author_id": 6597,
"author_profile": "https://Stackoverflow.com/users/6597",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm, what platform and what version of emacs are you using? With GNU Emacs 22.1.1 on Windows Vista, it works fine for me.</p>\n\n<p>If, by any chance, you are doing this from windows to linux through a RealVNC viewer, make sure you are running \"vncconfig -iconic\" on the linux box first.....</p>\n"
},
{
"answer_id": 64410,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": -1,
"selected": false,
"text": "<p>What I do is to use a good terminal tool (PuTTY on Windows, Konsole or Terminal on Linux) that has copy facilities built-in.</p>\n\n<p>In PuTTY, you highlight the text you want with the mouse and then paste it elsewhere. Right-clicking in a PuTTY window pastes the contents of the Windows copy/paste buffer.</p>\n\n<p>In Konsole or Terminal on Linux, you highlight what you want then press Shift+Ctrl+C for copy and Shift+Ctrl+V for paste.</p>\n\n<p>In the win32 compile of emacs, yanking text does put it on the copy/paste buffer .. most of the time.</p>\n\n<p>On Mac OS X, the Apple-key chortcuts work fine, because Terminal traps them.</p>\n\n<p>There is no direct way of doing it on the commandline because the shell does not maintain a copy/paste buffer for each application. bash <em>does</em> maintain a copy/paste buffer for itself, and, by default, emacs ^k/^y shortcuts work.</p>\n"
},
{
"answer_id": 64412,
"author": "cannam",
"author_id": 8608,
"author_profile": "https://Stackoverflow.com/users/8608",
"pm_score": 0,
"selected": false,
"text": "<p>I always use quick paste -- drag selection in emacs, hit the middle mouse button in target window.</p>\n\n<p>(From the reference to kate, I take it you're on linux or similar and probably using emacs in X one way or another.)</p>\n"
},
{
"answer_id": 64415,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to specify what platform you are using. Is it on linux, unix, macosx, windows, ms-dos?</p>\n\n<p>I believe that for windows it should work. For MacOSX it will get added to the x-windows clipboard, which isn't the same thing as the macosx clipboard. For Linux, it depends on your flavour of window manager, but I believe that x-windows handles it in a nice way on most of them.</p>\n\n<p>So, please specify.</p>\n"
},
{
"answer_id": 64440,
"author": "cschol",
"author_id": 2386,
"author_profile": "https://Stackoverflow.com/users/2386",
"pm_score": 3,
"selected": false,
"text": "<p>There is <a href=\"http://www.emacswiki.org/emacs/CopyAndPaste\" rel=\"nofollow noreferrer\">an EmacsWiki article</a> that explains some issues with copy & pasting under X and how to configure it to work.</p>\n"
},
{
"answer_id": 64466,
"author": "pdq",
"author_id": 8598,
"author_profile": "https://Stackoverflow.com/users/8598",
"pm_score": 3,
"selected": false,
"text": "<p>I assume by emacs you are meaning Emacs under X (ie not inside a terminal window).</p>\n\n<p>There are two ways:</p>\n\n<ol>\n<li>(Applies to unix OS's only)\nHighlight the desired text with your\nmouse (this copies it to the X\nclipboard) and then middle click to\npaste.</li>\n<li>Highlight the desired text and then \"M-x clipboard-kill-ring-save\"\n(note you can bind this to an easier\nkey). Then just \"Edit->Paste\" in\nyour favorite app.</li>\n</ol>\n\n<p>Clipboard operations available:</p>\n\n<ul>\n<li>clipboard-kill-ring-save -- copy\nselection from Emacs to clipboard</li>\n<li>clipboard-kill-region -- cut\nselection from Emacs to clipboard</li>\n<li>clipboard-yank -- paste from\nclipboard to Emacs</li>\n</ul>\n"
},
{
"answer_id": 64558,
"author": "memius",
"author_id": 8522,
"author_profile": "https://Stackoverflow.com/users/8522",
"pm_score": 8,
"selected": true,
"text": "<p>Insert the following into your <code>.emacs</code> file:</p>\n\n<pre><code>(setq x-select-enable-clipboard t)\n</code></pre>\n"
},
{
"answer_id": 65473,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 7,
"selected": false,
"text": "<p>Let's be careful with our definitions here</p>\n\n<ul>\n<li>An <em>Emacs copy</em> is the command <code>kill-ring-save</code> (usually bound to <kbd>M-w</kbd>).</li>\n<li>A <em>system copy</em> is what you typically get from pressing <kbd>C-c</kbd> (or choosing \"Edit->Copy\" in a application window).</li>\n<li>An <em>X copy</em> is \"physically\" highlighting text with the mouse cursor.</li>\n<li>An <em>Emacs paste</em> is the command <code>yank</code> (usually bound to <kbd>C-y</kbd>).</li>\n<li>A <em>system paste</em> is what you typically get from pressing <kbd>C-v</kbd> (or choosing \"Edit-Paste\" in an application window).</li>\n<li>An <em>X paste</em> is pressing the \"center mouse button\" (simulated by pressing the left and right mouse buttons together).</li>\n</ul>\n\n<p>In my case (on GNOME):</p>\n\n<ul>\n<li>Both Emacs and system copy usually work with X paste.</li>\n<li>X copy usually works with Emacs paste.</li>\n<li><p>To make system copy work with Emacs paste and Emacs copy work with system paste, you need to add <code>(setq x-select-enable-clipboard t)</code> to your <code>.emacs</code>. Or try </p>\n\n<pre><code>META-X set-variable RET x-select-enable-clipboard RET t\n</code></pre></li>\n</ul>\n\n<p>I think this is pretty standard modern Unix behavior.</p>\n\n<p>It's also important to note (though you say you're using Emacs in a separate window) that when Emacs is running in a console, it is completely divorced from the system and X clipboards: cut and paste in that case is mediated by the terminal. For example, \"Edit->Paste\" in your terminal window should act exactly as if you typed the text from the clipboard into the Emacs buffer. </p>\n"
},
{
"answer_id": 69657,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 4,
"selected": false,
"text": "<p>I stick this in my .emacs:</p>\n\n<pre><code>(setq x-select-enable-clipboard t)\n(setq interprogram-paste-function 'x-cut-buffer-or-selection-value)\n</code></pre>\n\n<p>I subsequently have basically no problems cutting and pasting back and forth from anything in Emacs to any other X11 or Gnome application.</p>\n\n<p>Bonus: to get these things to happen in Emacs without having to reload your whole .emacs, do C-x C-e with the cursor just after the close paren of each of those expressions in the .emacs buffer.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 19625063,
"author": "RussellStewart",
"author_id": 2237635,
"author_profile": "https://Stackoverflow.com/users/2237635",
"pm_score": 4,
"selected": false,
"text": "<p>The difficulty with copy and paste in Emacs is that you want it to work independently from the internal kill/yank, and you want it to work both in terminal and the gui. There are existing robust solutions for either terminal or gui, but not both. After installing xsel (e.g. <code>sudo apt-get install xsel</code>), here is what I do for copy and paste to combine them:</p>\n\n<pre><code>(defun copy-to-clipboard ()\n (interactive)\n (if (display-graphic-p)\n (progn\n (message \"Yanked region to x-clipboard!\")\n (call-interactively 'clipboard-kill-ring-save)\n )\n (if (region-active-p)\n (progn\n (shell-command-on-region (region-beginning) (region-end) \"xsel -i -b\")\n (message \"Yanked region to clipboard!\")\n (deactivate-mark))\n (message \"No region active; can't yank to clipboard!\")))\n )\n\n(defun paste-from-clipboard ()\n (interactive)\n (if (display-graphic-p)\n (progn\n (clipboard-yank)\n (message \"graphics active\")\n )\n (insert (shell-command-to-string \"xsel -o -b\"))\n )\n )\n\n(global-set-key [f8] 'copy-to-clipboard)\n(global-set-key [f9] 'paste-from-clipboard)\n</code></pre>\n"
},
{
"answer_id": 28902747,
"author": "cevaris",
"author_id": 3538289,
"author_profile": "https://Stackoverflow.com/users/3538289",
"pm_score": 3,
"selected": false,
"text": "<p>This works with <code>M-w</code> on Mac OSX. Just add to your <strong>.emacs</strong> file.</p>\n\n<pre><code>(defun copy-from-osx ()\n (shell-command-to-string \"pbpaste\"))\n(defun paste-to-osx (text &optional push)\n (let ((process-connection-type nil))\n (let ((proc (start-process \"pbcopy\" \"*Messages*\" \"pbcopy\")))\n (process-send-string proc text)\n (process-send-eof proc))))\n\n(setq interprogram-cut-function 'paste-to-osx)\n(setq interprogram-paste-function 'copy-from-osx)\n</code></pre>\n\n<p>Source <a href=\"https://gist.github.com/the-kenny/267162\" rel=\"noreferrer\">https://gist.github.com/the-kenny/267162</a></p>\n"
},
{
"answer_id": 45417273,
"author": "user1404316",
"author_id": 1404316,
"author_profile": "https://Stackoverflow.com/users/1404316",
"pm_score": 1,
"selected": false,
"text": "<p>The code below, inspired by @RussellStewart's answer above, adds support for x-PRIMARY and x-SECONDARY, replaces <code>region-active-p</code> with <code>use-region-p</code> to cover the case of an empty region, does not return silently if xsel has not been installed (returns an error message), and includes a \"cut\" function (emacs C-y, windows C-x).</p>\n\n<pre><code>(defun my-copy-to-xclipboard(arg)\n (interactive \"P\")\n (cond\n ((not (use-region-p))\n (message \"Nothing to yank to X-clipboard\"))\n ((and (not (display-graphic-p))\n (/= 0 (shell-command-on-region\n (region-beginning) (region-end) \"xsel -i -b\")))\n (error \"Is program `xsel' installed?\"))\n (t\n (when (display-graphic-p)\n (call-interactively 'clipboard-kill-ring-save))\n (message \"Yanked region to X-clipboard\")\n (when arg\n (kill-region (region-beginning) (region-end)))\n (deactivate-mark))))\n\n(defun my-cut-to-xclipboard()\n (interactive)\n (my-copy-to-xclipboard t))\n\n(defun my-paste-from-xclipboard()\n \"Uses shell command `xsel -o' to paste from x-clipboard. With\none prefix arg, pastes from X-PRIMARY, and with two prefix args,\npastes from X-SECONDARY.\"\n (interactive)\n (if (display-graphic-p)\n (clipboard-yank)\n (let*\n ((opt (prefix-numeric-value current-prefix-arg))\n (opt (cond\n ((= 1 opt) \"b\")\n ((= 4 opt) \"p\")\n ((= 16 opt) \"s\"))))\n (insert (shell-command-to-string (concat \"xsel -o -\" opt))))))\n\n(global-set-key (kbd \"C-c C-w\") 'my-cut-to-xclipboard)\n(global-set-key (kbd \"C-c M-w\") 'my-copy-to-xclipboard)\n(global-set-key (kbd \"C-c C-y\") 'my-paste-from-xclipboard)\n</code></pre>\n"
},
{
"answer_id": 56587135,
"author": "asmeurer",
"author_id": 161801,
"author_profile": "https://Stackoverflow.com/users/161801",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following, based on the other answers here, to make <code>C-x C-w</code> and <code>C-x C-y</code> be copy and paste on both Mac and Linux (if someone knows the version for Windows feel free to add it). Note that on Linux you will have to install xsel and xclip with your package manager.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>;; Commands to interact with the clipboard\n\n(defun osx-copy (beg end)\n (interactive \"r\")\n (call-process-region beg end \"pbcopy\"))\n\n(defun osx-paste ()\n (interactive)\n (if (region-active-p) (delete-region (region-beginning) (region-end)) nil)\n (call-process \"pbpaste\" nil t nil))\n\n(defun linux-copy (beg end)\n (interactive \"r\")\n (call-process-region beg end \"xclip\" nil nil nil \"-selection\" \"c\"))\n\n(defun linux-paste ()\n (interactive)\n (if (region-active-p) (delete-region (region-beginning) (region-end)) nil)\n (call-process \"xsel\" nil t nil \"-b\"))\n\n(cond\n ((string-equal system-type \"darwin\") ; Mac OS X\n (define-key global-map (kbd \"C-x C-w\") 'osx-copy)\n (define-key global-map (kbd \"C-x C-y\") 'osx-paste))\n ((string-equal system-type \"gnu/linux\") ; linux\n (define-key global-map (kbd \"C-x C-w\") 'linux-copy)\n (define-key global-map (kbd \"C-x C-y\") 'linux-paste)))\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8522/"
]
| When I cut (kill) text in Emacs 22.1.1 (in its own window on X, in KDE, on Kubuntu), I can't paste (yank) it in any other application. | Insert the following into your `.emacs` file:
```
(setq x-select-enable-clipboard t)
``` |
64,387 | <p><strong>Emacs</strong>: <code>C-U (79) #</code> » a pretty 79 character length divider</p>
<p><strong>VIM</strong>: <code>79-i-#</code> » see above</p>
<p><strong><a href="http://macromates.com/" rel="nofollow noreferrer">Textmate</a></strong>: ????</p>
<p>Or is it just assumed that we'll make a Ruby call or have a snippet somewhere?</p>
| [
{
"answer_id": 64975,
"author": "pjbeardsley",
"author_id": 6812,
"author_profile": "https://Stackoverflow.com/users/6812",
"pm_score": 2,
"selected": false,
"text": "<p>I would create a bundle command to do this.</p>\n\n<p>You can take editor selection as input to your script, then replace it with the result of execution. This command, for example, will take a selected number and print the character '#' that number of times.</p>\n\n<pre><code>python -c \"print '#' * $TM_SELECTED_TEXT\"\n</code></pre>\n\n<p>Of course this example doesn't allow you to specify the character, but it gives you an idea of what's possible.</p>\n"
},
{
"answer_id": 91221,
"author": "Matt",
"author_id": 15368,
"author_profile": "https://Stackoverflow.com/users/15368",
"pm_score": 1,
"selected": false,
"text": "<p>By taking the</p>\n\n<pre><code>python -c \"print '#' * $TM_SELECTED_TEXT\"\n</code></pre>\n\n<p>a step further, you can duplicate the examples you gave in the question. </p>\n\n<p>Just make a snippet, called divider or something, set the <code>tab trigger</code> field to something appropriate <code>'--'</code> for example, then enter something like:</p>\n\n<pre><code>`python -c \"print '_' * $TM_COLUMNS\"`\n</code></pre>\n\n<p>Then when you type <code>--⇥</code> (dash dash tab), you should get a divider of the correct width. </p>\n\n<p>True, you've lost some of the terseness that you get from vim, but this is far easier to reuse, and you only have to type it once. You can also use whatever language you like.</p>\n"
},
{
"answer_id": 1676726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Inspired by the other answers. Make a snippet with the following:</p>\n\n<pre><code>`python -c \"print ':'.join('$TM_SELECTED_TEXT'.split(':')[:-1]) * int('$TM_SELECTED_TEXT'.split(':')[-1])\"`\n</code></pre>\n\n<p>and optionally assign a key sequence to it, e.g. CTRL-SHIFT-R</p>\n\n<p>If you type <code>-x:4</code>, select it, and call the snippet (by it's shortcut for example), you'll get \"-x-x-x-x\".</p>\n\n<p>You can also use <code>::4</code> to obtain \"::::\".</p>\n\n<p>The string you repeat is enclosed in single quotes, so to repeat ', you have to use \\'.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| **Emacs**: `C-U (79) #` » a pretty 79 character length divider
**VIM**: `79-i-#` » see above
**[Textmate](http://macromates.com/)**: ????
Or is it just assumed that we'll make a Ruby call or have a snippet somewhere? | I would create a bundle command to do this.
You can take editor selection as input to your script, then replace it with the result of execution. This command, for example, will take a selected number and print the character '#' that number of times.
```
python -c "print '#' * $TM_SELECTED_TEXT"
```
Of course this example doesn't allow you to specify the character, but it gives you an idea of what's possible. |
64,388 | <p>I'm trying to use Visual Studio 2008's extensibility to write an addin that will create a project folder with various messages in it after parsing an interface. I'm having trouble at the step of creating/adding the folder, however. I've tried using </p>
<pre><code>ProjectItem folder =
item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);
</code></pre>
<p>(item is my target file next to which I'm creating a folder with the same name but "Messages" appended to it) but it chokes when a folder already exists (no big surprise).</p>
<p>I tried deleting it if it already exists, such as: </p>
<pre><code>DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent +
newDirectoryName);
if (dirInfo.Exists)
{
dirInfo.Delete(true);
}
ProjectItem folder =
item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);
</code></pre>
<p>I can SEE that the folder gets deleted when in debug, but it still
seems to think the folder is still there and dies on a folder already
exists exception. </p>
<p>Any ideas??? </p>
<p>Thanks. </p>
<p>AK </p>
<p>.... Perhaps the answer would lie in programmatically refreshing the project after the delete? How might this be done?</p>
| [
{
"answer_id": 64901,
"author": "Andrew",
"author_id": 8586,
"author_profile": "https://Stackoverflow.com/users/8586",
"pm_score": 2,
"selected": false,
"text": "<p>Yup, that was it...</p>\n\n<pre><code>DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent + newDirectoryName);\n\nif (dirInfo.Exists)\n{\n dirInfo.Delete(true);\n item.DTE.ExecuteCommand(\"View.Refresh\", string.Empty);\n}\n\nProjectItem folder = item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);\n</code></pre>\n\n<p>If there's a more elegant way of doing this, it would be much appreciated...</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 1209338,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>here's an idea i thought of because i've been using NAnt for so long and thought it might work. </p>\n\n<p>Open the .csproj file in a text editor and add the directory as such:</p>\n\n<pre><code><ItemGroup>\n <compile include=\"\\path\\rootFolderToInclude\\**\\*.cs\" />\n</ItemGroup>\n</code></pre>\n\n<p>if an \"ItemGroup\" already esists, that's fine. Just add it into an existing one. Visual studio won't really know how to edit this entry, but it will scan the whole directory.</p>\n\n<p>edit to whatever you'd like. </p>\n"
},
{
"answer_id": 5586467,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ProjectItem pi = null;\nvar dir = Path.Combine(\n project.Properties.Item(\"LocalPath\").Value.ToString(), SubdirectoryName);\nif (Directory.Exists(dir))\n pi = target.ProjectItems.AddFromDirectory(dir);\nelse\n pi = target.ProjectItems.AddFolder(dir);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/envdte.projectitems.addfromdirectory%28v=vs.80%29.aspx\" rel=\"nofollow\">ProjectItems.AddFromDirectory</a> will add the directory and everything underneath the directory to the project.</p>\n"
},
{
"answer_id": 6512963,
"author": "isaacfi",
"author_id": 819963,
"author_profile": "https://Stackoverflow.com/users/819963",
"pm_score": 2,
"selected": false,
"text": "<p>This is my approach:</p>\n\n<pre><code>//Getting the current project\nprivate DTE2 _applicationObject;\nSystem.Array projs = (System.Array)_applicationObject.ActiveSolutionProjects;\nProject proy=(Project)projs.GetValue(0);\n//Getting the path\nstring path=proy.FullName.Substring(0,proy.FullName.LastIndexOf('\\\\'));\n//Valitating if the path exists\nbool existsDirectory= Directory.Exists(path + \"\\\\Directory\");\n//Deleting and creating the Directory\nif (existeClasses)\n Directory.Delete(path + \"\\\\Directory\", true);\nDirectory.CreateDirectory(path + \"\\\\Directory\");\n//Including in the project\nproy.ProjectItems.AddFromDirectory(path + \"\\\\Directory\");\n</code></pre>\n"
},
{
"answer_id": 64846113,
"author": "Persian Brat",
"author_id": 10132738,
"author_profile": "https://Stackoverflow.com/users/10132738",
"pm_score": 1,
"selected": false,
"text": "<p>I am developing an extension for Visual Studio 2019 and had a similar issue. The question asked in the following page helped me out:</p>\n<p><a href=\"https://social.msdn.microsoft.com/Forums/en-US/f4a4f73b-3e13-40bf-99df-9c1bba8fe44e/include-existing-folder-path-as-project-item?forum=vsx\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/en-US/f4a4f73b-3e13-40bf-99df-9c1bba8fe44e/include-existing-folder-path-as-project-item?forum=vsx</a></p>\n<p>If the folder does not physically exist, you can use <code>AddFolder(folderName)</code>. But if the folder is not included in the project while existing physically, you need to provide the full system path to the folder. (<code>AddFolder(fullPath)</code>)</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8586/"
]
| I'm trying to use Visual Studio 2008's extensibility to write an addin that will create a project folder with various messages in it after parsing an interface. I'm having trouble at the step of creating/adding the folder, however. I've tried using
```
ProjectItem folder =
item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);
```
(item is my target file next to which I'm creating a folder with the same name but "Messages" appended to it) but it chokes when a folder already exists (no big surprise).
I tried deleting it if it already exists, such as:
```
DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent +
newDirectoryName);
if (dirInfo.Exists)
{
dirInfo.Delete(true);
}
ProjectItem folder =
item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);
```
I can SEE that the folder gets deleted when in debug, but it still
seems to think the folder is still there and dies on a folder already
exists exception.
Any ideas???
Thanks.
AK
.... Perhaps the answer would lie in programmatically refreshing the project after the delete? How might this be done? | Yup, that was it...
```
DirectoryInfo dirInfo = new DirectoryInfo(newDirectoryParent + newDirectoryName);
if (dirInfo.Exists)
{
dirInfo.Delete(true);
item.DTE.ExecuteCommand("View.Refresh", string.Empty);
}
ProjectItem folder = item.ProjectItem.Collection.AddFolder(newDirectoryName, string.Empty);
```
If there's a more elegant way of doing this, it would be much appreciated...
Thanks. |
64,420 | <p>I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project?</p>
| [
{
"answer_id": 64493,
"author": "Sergey Mikhanov",
"author_id": 3894,
"author_profile": "https://Stackoverflow.com/users/3894",
"pm_score": 2,
"selected": false,
"text": "<p>You should have the native wrapper written in Objective C. This wrapper could contain really few lines of code (like, 10) necessary to create a WebView and navigate it to the given address in the internet (where your application resides). But in this case your application should be a full-featured web application (I mean, use not only the JavaScript, but also some HTML for markup).</p>\n"
},
{
"answer_id": 64499,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this same problem. I already have a game written entirely in Javascript. I would love to make an iPhone friendly version, but Obj-C is an overkill. What I ended up doing was using the WebView to point to a special url of the iphone app. After thinking about it, I suppose I could just move those files to the app directory and run them locally.</p>\n"
},
{
"answer_id": 64506,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There not way to do this with the current apple API's. Your closest bet is to write a simple native iPhone app that embeds the webkit browser. That will let you browse your xhtml/js application locally.</p>\n\n<p>If you want to store data, you'll need to take it a step further and include a light weight http server that servers up your app and provides calls to store and retrieve data. Probably not an ideal solution for you, but possibly less work than a full Obj-C app.</p>\n\n<p>As a side note, Obj-C is fairly easy to learn. There are tons of examples in the SDK. The community is strong and will answer well put questions without hesitation.</p>\n"
},
{
"answer_id": 64763,
"author": "Jeff",
"author_id": 8597,
"author_profile": "https://Stackoverflow.com/users/8597",
"pm_score": 7,
"selected": true,
"text": "<p>I found the answer after searching around. Here's what I have done:</p>\n\n<ol>\n<li><p>Create a new project in XCode. I think I used the view-based app.</p></li>\n<li><p>Drag a WebView object onto your interface and resize.</p></li>\n<li><p>Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad method:</p>\n\n<pre>NSString *filePath = [[NSBundle mainBundle] pathForResource:@\"index\" ofType:@\"html\"]; \nNSData *htmlData = [NSData dataWithContentsOfFile:filePath]; \nif (htmlData) { \n NSBundle *bundle = [NSBundle mainBundle]; \n NSString *path = [bundle bundlePath];\n NSString *fullPath = [NSBundle pathForResource:@\"index\" ofType:@\"html\" inDirectory:path];\n [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]];\n}</pre></li>\n<li><p>Now any files you have added as resources to the project are available for use in your web app. I've got an index.html file including javascript and css and image files with no problems. The only limitation I've found so far is that I can't create new folders so all the files clutter up the resources folder.</p></li>\n<li><p>Trick: make sure you've added the file as a resource in XCode or the file won't be available. I've been adding an empty file in XCode, then dragging my file on top in the finder. That's been working for me.</p></li>\n</ol>\n\n<p>Note: I realize that Obj-C must not be that hard to learn. But since I already have this app existing in JS and I know it works in Safari this is a much faster dev cycle for me. Some day I'm sure I'll have to break down and learn Obj-C.</p>\n\n<p>A few other resources I found helpful:</p>\n\n<p>Calling Obj-C from javascript: <a href=\"http://tetontech.wordpress.com/2008/08/14/calling-objective-c-from-javascript-in-an-iphone-uiwebview/\" rel=\"noreferrer\">calling objective-c from javascript</a></p>\n\n<p>Calling javascript from Obj-C: <a href=\"http://dominiek.com/articles/2008/7/19/iphone-app-development-for-web-hackers\" rel=\"noreferrer\">iphone app development for web hackers</a></p>\n\n<p>Reading files from application bundle: <a href=\"http://iphoneincubator.com/blog/tag/uiwebview\" rel=\"noreferrer\">uiwebview</a></p>\n"
},
{
"answer_id": 112537,
"author": "Robert Sanders",
"author_id": 16952,
"author_profile": "https://Stackoverflow.com/users/16952",
"pm_score": 3,
"selected": false,
"text": "<p>For those doing this on iPhone 2.1 (maybe 2.0), you do NOT need to create any special services for local data storage. MobileSafari appears to support the HTML5/WHATWG SQL database API. This is the same API supported by recent versions of desktop Safari and Firefox.</p>\n\n<p>If you're using a toolkit like Dojo or ExtJS that offers a storage abstraction, your code should work on just about any modern browser, including MobileSafari.</p>\n\n<p>To test, open <a href=\"http://robertsanders.name/dev/stackoverflow/html5.html\" rel=\"nofollow noreferrer\">http://robertsanders.name/dev/stackoverflow/html5.html</a> on your iPhone.</p>\n\n<p>If you open that page then look on the filesystem of a Jailbroken iPhone, you should see a database somewhere in /private/var/mobile/Library/WebKit/Databases/. There's even a directory of web-opened DBs there.</p>\n\n<blockquote>\n <p>root# sqlite3 /private/var/mobile/Library/WebKit/Databases/Databases.db\n SQLite version 3.5.9 Enter \".help\" for\n instructions</p>\n \n <p>sqlite> .databases \n seq name file </p>\n \n <hr>\n \n <p>0 main /private/var/mobile/Library/WebKit/Databases/Databases.db</p>\n \n <p>sqlite> .tables </p>\n \n <p>Databases Origins </p>\n \n <p>sqlite> select * from Databases;</p>\n \n <p>1|http_robertsanders.name_0|NoteTest|Database|API example|20000|0000000000000001.db</p>\n \n <p>sqlite> select * from Origins; </p>\n \n <p>http_robertsanders.name_0|5242880</p>\n</blockquote>\n"
},
{
"answer_id": 227821,
"author": "Chris Samuels",
"author_id": 30342,
"author_profile": "https://Stackoverflow.com/users/30342",
"pm_score": 5,
"selected": false,
"text": "<p>Check out PhoneGap at <a href=\"http://www.phonegap.com\" rel=\"noreferrer\">http://www.phonegap.com</a> they claim it allows you to embed JavaScript, HTML and CSS into a native iPhone app.</p>\n"
},
{
"answer_id": 232466,
"author": "Lee",
"author_id": 31063,
"author_profile": "https://Stackoverflow.com/users/31063",
"pm_score": 2,
"selected": false,
"text": "<p>You can create an application without knowing any obj-C. The QuickConnectiPhone framework allows you to do this. Check out <a href=\"http://tetontech.wordpress.com\" rel=\"nofollow noreferrer\">http://tetontech.wordpress.com</a> for how to use it as well as other ways of doing what you have asked.</p>\n"
},
{
"answer_id": 1003804,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I have been using phonegap for a while and it seems to have the best results for me. I will post my experience in a week or so with a link to my app as well.</p>\n"
},
{
"answer_id": 1849591,
"author": "Neo42",
"author_id": 125062,
"author_profile": "https://Stackoverflow.com/users/125062",
"pm_score": 0,
"selected": false,
"text": "<p>At least 2 others mentioned phonegap, but I thought I'd post this too and mention that Apple has approved the phonegap framework. So, now you won't get your app rejected by Apple just because you're using phonegap. </p>\n\n<p><a href=\"http://blogs.nitobi.com/jesse/2009/11/20/phonegapp-store-approval/\" rel=\"nofollow noreferrer\">Blog post about phonegap and Apple - http://blogs.nitobi.com/jesse/2009/11/20/phonegapp-store-approval/</a></p>\n\n<p><a href=\"http://phonegap.com/\" rel=\"nofollow noreferrer\">Phone Gap Home</a></p>\n"
},
{
"answer_id": 2580083,
"author": "Josh Brown",
"author_id": 2030,
"author_profile": "https://Stackoverflow.com/users/2030",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.appcelerator.com/products/titanium-mobile-application-development/\" rel=\"nofollow noreferrer\">Titanium Mobile</a> is also an option - it allows you to write JavaScript that gets translated into Objective-C.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8597/"
]
| I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project? | I found the answer after searching around. Here's what I have done:
1. Create a new project in XCode. I think I used the view-based app.
2. Drag a WebView object onto your interface and resize.
3. Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad method:
```
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
if (htmlData) {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]];
}
```
4. Now any files you have added as resources to the project are available for use in your web app. I've got an index.html file including javascript and css and image files with no problems. The only limitation I've found so far is that I can't create new folders so all the files clutter up the resources folder.
5. Trick: make sure you've added the file as a resource in XCode or the file won't be available. I've been adding an empty file in XCode, then dragging my file on top in the finder. That's been working for me.
Note: I realize that Obj-C must not be that hard to learn. But since I already have this app existing in JS and I know it works in Safari this is a much faster dev cycle for me. Some day I'm sure I'll have to break down and learn Obj-C.
A few other resources I found helpful:
Calling Obj-C from javascript: [calling objective-c from javascript](http://tetontech.wordpress.com/2008/08/14/calling-objective-c-from-javascript-in-an-iphone-uiwebview/)
Calling javascript from Obj-C: [iphone app development for web hackers](http://dominiek.com/articles/2008/7/19/iphone-app-development-for-web-hackers)
Reading files from application bundle: [uiwebview](http://iphoneincubator.com/blog/tag/uiwebview) |
64,436 | <p>I'm using Excel VBA to a write a UDF. I would like to overload my own UDF with a couple of different versions so that different arguments will call different functions. </p>
<p>As VBA doesn't seem to support this, could anyone suggest a good, non-messy way of achieving the same goal? Should I be using Optional arguments or is there a better way?</p>
| [
{
"answer_id": 64494,
"author": "theo",
"author_id": 7870,
"author_profile": "https://Stackoverflow.com/users/7870",
"pm_score": 0,
"selected": false,
"text": "<p>VBA is messy. I'm not sure there is an easy way to do fake overloads:</p>\n\n<p>In the past I've either used lots of Optionals, or used varied functions. For instance </p>\n\n<pre><code>Foo_DescriptiveName1()\n\nFoo_DescriptiveName2()\n</code></pre>\n\n<p>I'd say go with Optional arguments that have sensible defaults unless the argument list is going to get stupid, then create separate functions to call for your cases.</p>\n"
},
{
"answer_id": 65023,
"author": "Jon Fournier",
"author_id": 5106,
"author_profile": "https://Stackoverflow.com/users/5106",
"pm_score": 0,
"selected": false,
"text": "<p>You mighta also want to consider using a variant data type for your arguments list and then figure out what's what type using the TypeOf statement, and then call the appropriate functions when you figure out what's what...</p>\n"
},
{
"answer_id": 70526,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 7,
"selected": true,
"text": "<p>Declare your arguments as <code>Optional Variants</code>, then you can test to see if they're missing using <code>IsMissing()</code> or check their type using <code>TypeName()</code>, as shown in the following example:</p>\n\n<pre><code>Public Function Foo(Optional v As Variant) As Variant\n\n If IsMissing(v) Then\n Foo = \"Missing argument\"\n ElseIf TypeName(v) = \"String\" Then\n Foo = v & \" plus one\"\n Else\n Foo = v + 1\n End If\n\nEnd Function\n</code></pre>\n\n<p>This can be called from a worksheet as <strong>=FOO()</strong>, <strong>=FOO(<em>number</em>)</strong>, or <strong>=FOO(\"<em>string</em>\")</strong>.</p>\n"
},
{
"answer_id": 71162,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 3,
"selected": false,
"text": "<p>If you can distinguish by parameter count, then something like this would work:</p>\n\n<pre><code>Public Function Morph(ParamArray Args())\n\n Select Case UBound(Args)\n Case -1 '' nothing supplied\n Morph = Morph_NoParams()\n Case 0\n Morph = Morph_One_Param(Args(0))\n Case 1\n Morph = Two_Param_Morph(Args(0), Args(1))\n Case Else\n Morph = CVErr(xlErrRef)\n End Select\n\nEnd Function\n\nPrivate Function Morph_NoParams()\n Morph_NoParams = \"I'm parameterless\"\nEnd Function\n\nPrivate Function Morph_One_Param(arg)\n Morph_One_Param = \"I has a parameter, it's \" & arg\nEnd Function\n\nPrivate Function Two_Param_Morph(arg0, arg1)\n Two_Param_Morph = \"I is in 2-params and they is \" & arg0 & \",\" & arg1\nEnd Function\n</code></pre>\n\n<p>If the only way to distinguish the function is by types, then you're effectively going to have to do what C++ and other languages with overridden functions do, which is to call by signature. I'd suggest making the call look something like this:</p>\n\n<pre><code>Public Function MorphBySig(ParamArray args())\n\nDim sig As String\nDim idx As Long\nDim MorphInstance As MorphClass\n\n For idx = LBound(args) To UBound(args)\n sig = sig & TypeName(args(idx))\n Next\n\n Set MorphInstance = New MorphClass\n\n MorphBySig = CallByName(MorphInstance, \"Morph_\" & sig, VbMethod, args)\n\nEnd Function\n</code></pre>\n\n<p>and creating a class with a number of methods that match the signatures you expect. You'll probably need some error-handling though, and be warned that the types that are recognizable are limited: dates are TypeName Double, for example.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69157/"
]
| I'm using Excel VBA to a write a UDF. I would like to overload my own UDF with a couple of different versions so that different arguments will call different functions.
As VBA doesn't seem to support this, could anyone suggest a good, non-messy way of achieving the same goal? Should I be using Optional arguments or is there a better way? | Declare your arguments as `Optional Variants`, then you can test to see if they're missing using `IsMissing()` or check their type using `TypeName()`, as shown in the following example:
```
Public Function Foo(Optional v As Variant) As Variant
If IsMissing(v) Then
Foo = "Missing argument"
ElseIf TypeName(v) = "String" Then
Foo = v & " plus one"
Else
Foo = v + 1
End If
End Function
```
This can be called from a worksheet as **=FOO()**, **=FOO(*number*)**, or **=FOO("*string*")**. |
64,498 | <p>Can you specialize a template method within a template class without specializing the class template parameter?</p>
<p>Please note that the specialization is on the <em>value</em> of the template parameter, not its type.</p>
<p>This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4.</p>
<pre><code>#include <iostream>
using namespace std;
template <typename T>
class A
{
private:
template <bool b>
void testme();
template <>
void testme<true>() { cout << "true" << endl; };
template <>
void testme<false>() { cout << "false" << endl; };
public:
void test();
};
template<typename T> struct select {};
template<> struct select<int> { static const bool value = true; };
template<> struct select<double> { static const bool value = false; };
template <class T>
void A<T>::test() { testme<select<T>::value>(); }
int main(int argc, const char* argv[])
{
A<int> aInt;
A<double> aDouble;
aInt.test();
aDouble.test();
return 0;
}
</code></pre>
<p>GCC tells me:"error: explicit specialization in non-namespace scope ‘class A’"</p>
<p>If it is not supported in the standard, can anyone tell me why?</p>
| [
{
"answer_id": 64824,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 2,
"selected": false,
"text": "<p>It is not supported in the standard (and it is apparently a known bug with Visual Studio that you <em>can</em> do it).</p>\n\n<p>The standard doesn't allow an inner template (member function <em>or</em> class) to be specialized without the outer template being specialized as well. One of the reasons for this is that you can normally just overload the function:</p>\n\n<pre><code>template<typename ty>\nclass A\n{\npublic:\n void foo(bool b);\n void foo(int i);\n};\n</code></pre>\n\n<p>Is equivalent to:</p>\n\n<pre><code>template<typename ty>\nclass A\n{\npublic:\n template<typename ty2>\n void foo(ty2);\n\n template<>\n void foo(bool b);\n\n template<>\n void foo(int i);\n};\n</code></pre>\n"
},
{
"answer_id": 64884,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "<p>I've never heard of that being possible; it would make sense to me if it was <em>not</em> supported by all compilers. So here is an idea for a workaround:</p>\n\n<p>Implement a template function outside of your class which takes the same action as the method. Then you can specialize this function, and it call it from the method. Of course, you'll also have to pass in any member variables that it needs (and pointers thereto if you want to modify their values).</p>\n\n<p>You could also create another template class as a subclass, and specialize that one, although I've never done this myself and am not 100% sure it would work. (Please comment to augment this answer if you know whether or not this second approach would work!)</p>\n"
},
{
"answer_id": 67478,
"author": "Bronek",
"author_id": 10042,
"author_profile": "https://Stackoverflow.com/users/10042",
"pm_score": 2,
"selected": true,
"text": "<p>Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function.</p>\n\n<p>I think I learned this trick from Herb Sutter, but do not remember which book (or article) was that. For your needs it is probably overkill, but nonetheless ...</p>\n\n<pre><code>template <typename T>\nstruct select;\n\ntemplate <bool B>\nstruct testme_helper\n{\n void operator()();\n};\n\ntemplate <typename T>\nclass A\n{\nprivate:\n template <bool B> void testme()\n {\n testme_helper<B>()();\n }\n\npublic:\n void test()\n {\n testme<select<T>::value>();\n }\n};\n\ntemplate<> void testme_helper<true>::operator()()\n{\n std::cout << \"true\" << std::endl;\n}\n\ntemplate<> void testme_helper<false>::operator()()\n{\n std::cout << \"false\" << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 275212,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>here is how you do it:</p>\n\n<pre><code>template<typename A>\nstruct SomeTempl {\n template<bool C> typename enable_if<C>::type \n SomeOtherTempl() {\n std::cout << \"true!\";\n }\n\n template<bool C> typename enable_if<!C>::type \n SomeOtherTempl() {\n std::cout << \"false!\";\n }\n};\n</code></pre>\n\n<p>You can get <code>enable_if</code> from my other answer where i told them how to check for a member function's existance in a class using templates. or you can use boost, but remember to change <code>enable_if</code> to <code>enable_if_c</code> then.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8524/"
]
| Can you specialize a template method within a template class without specializing the class template parameter?
Please note that the specialization is on the *value* of the template parameter, not its type.
This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4.
```
#include <iostream>
using namespace std;
template <typename T>
class A
{
private:
template <bool b>
void testme();
template <>
void testme<true>() { cout << "true" << endl; };
template <>
void testme<false>() { cout << "false" << endl; };
public:
void test();
};
template<typename T> struct select {};
template<> struct select<int> { static const bool value = true; };
template<> struct select<double> { static const bool value = false; };
template <class T>
void A<T>::test() { testme<select<T>::value>(); }
int main(int argc, const char* argv[])
{
A<int> aInt;
A<double> aDouble;
aInt.test();
aDouble.test();
return 0;
}
```
GCC tells me:"error: explicit specialization in non-namespace scope ‘class A’"
If it is not supported in the standard, can anyone tell me why? | Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function.
I think I learned this trick from Herb Sutter, but do not remember which book (or article) was that. For your needs it is probably overkill, but nonetheless ...
```
template <typename T>
struct select;
template <bool B>
struct testme_helper
{
void operator()();
};
template <typename T>
class A
{
private:
template <bool B> void testme()
{
testme_helper<B>()();
}
public:
void test()
{
testme<select<T>::value>();
}
};
template<> void testme_helper<true>::operator()()
{
std::cout << "true" << std::endl;
}
template<> void testme_helper<false>::operator()()
{
std::cout << "false" << std::endl;
}
``` |
64,505 | <p>I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?</p>
<pre><code>from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
</code></pre>
| [
{
"answer_id": 64554,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 3,
"selected": false,
"text": "<p>The main gotcha I see is that you're not handling any errors: <code>.login()</code> and <code>.sendmail()</code> both have <a href=\"https://docs.python.org/3/library/smtplib.html#smtplib.SMTPException\" rel=\"nofollow noreferrer\">documented exceptions</a> that they can throw, and it seems like <code>.connect()</code> must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.</p>\n"
},
{
"answer_id": 64580,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>You should make sure you format the date in the correct format - <a href=\"http://www.faqs.org/rfcs/rfc2822.html\" rel=\"nofollow noreferrer\">RFC2822</a>.</p>\n"
},
{
"answer_id": 64673,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 3,
"selected": false,
"text": "<p>Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.</p>\n"
},
{
"answer_id": 64890,
"author": "Vincent Marchetti",
"author_id": 8935,
"author_profile": "https://Stackoverflow.com/users/8935",
"pm_score": 8,
"selected": true,
"text": "<p>The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.</p>\n\n<p>I rely on my ISP to add the date time header.</p>\n\n<p>My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at <a href=\"http://www1.cs.columbia.edu/~db2501/ssmtplib.py\" rel=\"noreferrer\">http://www1.cs.columbia.edu/~db2501/ssmtplib.py</a>)</p>\n\n<p>As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.</p>\n\n<p>=======================================</p>\n\n<pre><code>#! /usr/local/bin/python\n\n\nSMTPserver = 'smtp.att.yahoo.com'\nsender = 'me@my_email_domain.net'\ndestination = ['recipient@her_email_domain.com']\n\nUSERNAME = \"USER_NAME_FOR_INTERNET_SERVICE_PROVIDER\"\nPASSWORD = \"PASSWORD_INTERNET_SERVICE_PROVIDER\"\n\n# typical values for text_subtype are plain, html, xml\ntext_subtype = 'plain'\n\n\ncontent=\"\"\"\\\nTest message\n\"\"\"\n\nsubject=\"Sent from Python\"\n\nimport sys\nimport os\nimport re\n\nfrom smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)\n# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)\n\n# old version\n# from email.MIMEText import MIMEText\nfrom email.mime.text import MIMEText\n\ntry:\n msg = MIMEText(content, text_subtype)\n msg['Subject']= subject\n msg['From'] = sender # some SMTP servers will do this automatically, not all\n\n conn = SMTP(SMTPserver)\n conn.set_debuglevel(False)\n conn.login(USERNAME, PASSWORD)\n try:\n conn.sendmail(sender, destination, msg.as_string())\n finally:\n conn.quit()\n\nexcept:\n sys.exit( \"mail failed; %s\" % \"CUSTOM_ERROR\" ) # give an error message\n</code></pre>\n"
},
{
"answer_id": 275124,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Also if you want to do smtp auth with TLS as opposed to SSL then you just have to change the port (use 587) and do smtp.starttls(). This worked for me:</p>\n\n<pre><code>...\nsmtp.connect('YOUR.MAIL.SERVER', 587)\nsmtp.ehlo()\nsmtp.starttls()\nsmtp.ehlo()\nsmtp.login('USERNAME@DOMAIN', 'PASSWORD')\n...\n</code></pre>\n"
},
{
"answer_id": 11228560,
"author": "Satish",
"author_id": 1159538,
"author_profile": "https://Stackoverflow.com/users/1159538",
"pm_score": 3,
"selected": false,
"text": "<p>What about this? </p>\n\n<pre><code>import smtplib\n\nSERVER = \"localhost\"\n\nFROM = \"[email protected]\"\nTO = [\"[email protected]\"] # must be a list\n\nSUBJECT = \"Hello!\"\n\nTEXT = \"This message was sent with Python's smtplib.\"\n\n# Prepare actual message\n\nmessage = \"\"\"\\\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n\"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n\n# Send the mail\n\nserver = smtplib.SMTP(SERVER)\nserver.sendmail(FROM, TO, message)\nserver.quit()\n</code></pre>\n"
},
{
"answer_id": 17596848,
"author": "madman2890",
"author_id": 1813869,
"author_profile": "https://Stackoverflow.com/users/1813869",
"pm_score": 7,
"selected": false,
"text": "<p>The method I commonly use...not much different but a little bit</p>\n\n<pre><code>import smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\n\nmsg = MIMEMultipart()\nmsg['From'] = '[email protected]'\nmsg['To'] = '[email protected]'\nmsg['Subject'] = 'simple email in python'\nmessage = 'here is the email'\nmsg.attach(MIMEText(message))\n\nmailserver = smtplib.SMTP('smtp.gmail.com',587)\n# identify ourselves to smtp gmail client\nmailserver.ehlo()\n# secure our email with tls encryption\nmailserver.starttls()\n# re-identify ourselves as an encrypted connection\nmailserver.ehlo()\nmailserver.login('[email protected]', 'mypassword')\n\nmailserver.sendmail('[email protected]','[email protected]',msg.as_string())\n\nmailserver.quit()\n</code></pre>\n\n<p>That's it</p>\n"
},
{
"answer_id": 26191922,
"author": "Abdul Majeed",
"author_id": 5629004,
"author_profile": "https://Stackoverflow.com/users/5629004",
"pm_score": 3,
"selected": false,
"text": "<p>following code is working fine for me:</p>\n<pre><code>import smtplib\n \nto = '[email protected]'\ngmail_user = '[email protected]'\ngmail_pwd = 'yourpassword'\nsmtpserver = smtplib.SMTP("smtp.gmail.com",587)\nsmtpserver.ehlo()\nsmtpserver.starttls()\nsmtpserver.ehlo()\nsmtpserver.login(gmail_user, gmail_pwd)\nheader = 'To:' + to + '\\n' + 'From: ' + gmail_user + '\\n' + 'Subject:testing \\n'\nprint header\nmsg = header + '\\n this is test msg from mkyong.com \\n\\n'\nsmtpserver.sendmail(gmail_user, to, msg)\nprint 'done!'\nsmtpserver.quit()\n</code></pre>\n<p>Ref: <a href=\"http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/\" rel=\"nofollow noreferrer\">http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/</a></p>\n"
},
{
"answer_id": 29720511,
"author": "PascalVKooten",
"author_id": 1575066,
"author_profile": "https://Stackoverflow.com/users/1575066",
"pm_score": 2,
"selected": false,
"text": "<p>See all those lenghty answers? Please allow me to self promote by doing it all in a couple of lines.</p>\n\n<p>Import and Connect:</p>\n\n<pre><code>import yagmail\nyag = yagmail.SMTP('[email protected]', host = 'YOUR.MAIL.SERVER', port = 26)\n</code></pre>\n\n<p>Then it is just a one-liner:</p>\n\n<pre><code>yag.send('[email protected]', 'hello', 'Hello\\nThis is a mail from your server\\n\\nBye\\n')\n</code></pre>\n\n<p>It will actually close when it goes out of scope (or can be closed manually). Furthermore, it will allow you to register your username in your keyring such that you do not have to write out your password in your script (it really bothered me prior to writing <code>yagmail</code>!)</p>\n\n<p>For the package/installation, tips and tricks please look at <a href=\"https://github.com/kootenpv/yagmail\" rel=\"nofollow\">git</a> or <a href=\"https://pypi.python.org/pypi/yagmail/\" rel=\"nofollow\">pip</a>, available for both Python 2 and 3.</p>\n"
},
{
"answer_id": 50230501,
"author": "Skiller Dz",
"author_id": 8808047,
"author_profile": "https://Stackoverflow.com/users/8808047",
"pm_score": 2,
"selected": false,
"text": "<p>you can do like that</p>\n\n<pre><code>import smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n\n\nserver = smtplib.SMTP('mail.servername.com', 25)\nserver.ehlo()\nserver.starttls()\n\nserver.login('username', 'password')\nfrom = '[email protected]'\nto = '[email protected]'\nbody = 'That A Message For My Girl Friend For tell Him If We will go to eat Something This Nigth'\nsubject = 'Invite to A Diner'\nmsg = MIMEText(body,'plain','utf-8')\nmsg['Subject'] = Header(subject, 'utf-8')\nmsg['From'] = Header(from, 'utf-8')\nmsg['To'] = Header(to, 'utf-8')\nmessage = msg.as_string()\nserver.sendmail(from, to, message)\n</code></pre>\n"
},
{
"answer_id": 51680874,
"author": "Mark",
"author_id": 622306,
"author_profile": "https://Stackoverflow.com/users/622306",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a working example for Python 3.x</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom email.message import EmailMessage\nfrom getpass import getpass\nfrom smtplib import SMTP_SSL\nfrom sys import exit\n\nsmtp_server = 'smtp.gmail.com'\nusername = '[email protected]'\npassword = getpass('Enter Gmail password: ')\n\nsender = '[email protected]'\ndestination = '[email protected]'\nsubject = 'Sent from Python 3.x'\ncontent = 'Hello! This was sent to you via Python 3.x!'\n\n# Create a text/plain message\nmsg = EmailMessage()\nmsg.set_content(content)\n\nmsg['Subject'] = subject\nmsg['From'] = sender\nmsg['To'] = destination\n\ntry:\n s = SMTP_SSL(smtp_server)\n s.login(username, password)\n try:\n s.send_message(msg)\n finally:\n s.quit()\n\nexcept Exception as E:\n exit('Mail failed: {}'.format(str(E)))\n</code></pre>\n"
},
{
"answer_id": 55473040,
"author": "Hariharan AR",
"author_id": 8612590,
"author_profile": "https://Stackoverflow.com/users/8612590",
"pm_score": 2,
"selected": false,
"text": "<p>The example code which i did for send mail using SMTP.</p>\n\n<pre><code>import smtplib, ssl\n\nsmtp_server = \"smtp.gmail.com\"\nport = 587 # For starttls\nsender_email = \"sender@email\"\nreceiver_email = \"receiver@email\"\npassword = \"<your password here>\"\nmessage = \"\"\" Subject: Hi there\n\nThis message is sent from Python.\"\"\"\n\n\n# Create a secure SSL context\ncontext = ssl.create_default_context()\n\n# Try to log in to server and send email\nserver = smtplib.SMTP(smtp_server,port)\n\ntry:\n server.ehlo() # Can be omitted\n server.starttls(context=context) # Secure the connection\n server.ehlo() # Can be omitted\n server.login(sender_email, password)\n server.sendmail(sender_email, receiver_email, message)\nexcept Exception as e:\n # Print any error messages to stdout\n print(e)\nfinally:\n server.quit()\n</code></pre>\n"
},
{
"answer_id": 60511210,
"author": "Robert Lujo",
"author_id": 565525,
"author_profile": "https://Stackoverflow.com/users/565525",
"pm_score": 2,
"selected": false,
"text": "<p>Based on <a href=\"https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439\">this example</a> I made following function:</p>\n\n<pre><code>import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\ndef send_email(host, port, user, pwd, recipients, subject, body, html=None, from_=None):\n \"\"\" copied and adapted from\n https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python#12424439\n returns None if all ok, but if problem then returns exception object\n \"\"\"\n\n PORT_LIST = (25, 587, 465)\n\n FROM = from_ if from_ else user \n TO = recipients if isinstance(recipients, (list, tuple)) else [recipients]\n SUBJECT = subject\n TEXT = body.encode(\"utf8\") if isinstance(body, unicode) else body\n HTML = html.encode(\"utf8\") if isinstance(html, unicode) else html\n\n if not html:\n # Prepare actual message\n message = \"\"\"From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\n \"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n else:\n # https://stackoverflow.com/questions/882712/sending-html-email-using-python#882770\n msg = MIMEMultipart('alternative')\n msg['Subject'] = SUBJECT\n msg['From'] = FROM\n msg['To'] = \", \".join(TO)\n\n # Record the MIME types of both parts - text/plain and text/html.\n # utf-8 -> https://stackoverflow.com/questions/5910104/python-how-to-send-utf-8-e-mail#5910530\n part1 = MIMEText(TEXT, 'plain', \"utf-8\")\n part2 = MIMEText(HTML, 'html', \"utf-8\")\n\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n msg.attach(part1)\n msg.attach(part2)\n\n message = msg.as_string()\n\n\n try:\n if port not in PORT_LIST: \n raise Exception(\"Port %s not one of %s\" % (port, PORT_LIST))\n\n if port in (465,):\n server = smtplib.SMTP_SSL(host, port)\n else:\n server = smtplib.SMTP(host, port)\n\n # optional\n server.ehlo()\n\n if port in (587,): \n server.starttls()\n\n server.login(user, pwd)\n server.sendmail(FROM, TO, message)\n server.close()\n # logger.info(\"SENT_EMAIL to %s: %s\" % (recipients, subject))\n except Exception, ex:\n return ex\n\n return None\n</code></pre>\n\n<p>if you pass only <code>body</code> then plain text mail will be sent, but if you pass <code>html</code> argument along with <code>body</code> argument, html email will be sent (with fallback to text content for email clients that don't support html/mime types).</p>\n\n<p>Example usage:</p>\n\n<pre><code>ex = send_email(\n host = 'smtp.gmail.com'\n #, port = 465 # OK\n , port = 587 #OK\n , user = \"[email protected]\"\n , pwd = \"xxx\"\n , from_ = '[email protected]'\n , recipients = ['[email protected]']\n , subject = \"Test from python\"\n , body = \"Test from python - body\"\n )\nif ex: \n print(\"Mail sending failed: %s\" % ex)\nelse:\n print(\"OK - mail sent\"\n</code></pre>\n\n<p>Btw. If you want to use gmail as testing or production SMTP server, \nenable temp or permanent access to less secured apps:</p>\n\n<ul>\n<li>login to google mail/account</li>\n<li>go to: <a href=\"https://myaccount.google.com/lesssecureapps\" rel=\"nofollow noreferrer\">https://myaccount.google.com/lesssecureapps</a></li>\n<li>enable</li>\n<li>send email using this function or similar</li>\n<li>(recommended) go to: <a href=\"https://myaccount.google.com/lesssecureapps\" rel=\"nofollow noreferrer\">https://myaccount.google.com/lesssecureapps</a></li>\n<li>(recommended) disable</li>\n</ul>\n"
},
{
"answer_id": 65853330,
"author": "Milovan Tomašević",
"author_id": 13155046,
"author_profile": "https://Stackoverflow.com/users/13155046",
"pm_score": 2,
"selected": false,
"text": "<p>Or</p>\n<pre class=\"lang-py prettyprint-override\"><code>import smtplib\n \nfrom email.message import EmailMessage\nfrom getpass import getpass\n\n\npassword = getpass()\n\nmessage = EmailMessage()\nmessage.set_content('Message content here')\nmessage['Subject'] = 'Your subject here'\nmessage['From'] = "USERNAME@DOMAIN"\nmessage['To'] = "[email protected]"\n\ntry:\n smtp_server = None\n smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)\n smtp_server.ehlo()\n smtp_server.starttls()\n smtp_server.ehlo()\n smtp_server.login("USERNAME@DOMAIN", password)\n smtp_server.send_message(message)\nexcept Exception as e:\n print("Error: ", str(e))\nfinally:\n if smtp_server is not None:\n smtp_server.quit()\n</code></pre>\n<p>If you want to use Port 465 you have to create an <code>SMTP_SSL</code> object.</p>\n"
},
{
"answer_id": 72752742,
"author": "miksus",
"author_id": 13696660,
"author_profile": "https://Stackoverflow.com/users/13696660",
"pm_score": 0,
"selected": false,
"text": "<p>What about <a href=\"https://red-mail.readthedocs.io/\" rel=\"nofollow noreferrer\">Red Mail</a>?</p>\n<p>Install it:</p>\n<pre><code>pip install redmail\n</code></pre>\n<p>Then just:</p>\n<pre><code>from redmail import EmailSender\n\n# Configure the sender\nemail = EmailSender(\n host="YOUR.MAIL.SERVER", \n port=26,\n username='[email protected]',\n password='<PASSWORD>'\n)\n\n# Send an email:\nemail.send(\n subject="An example email",\n sender="[email protected]",\n receivers=['[email protected]'],\n text="Hello!",\n html="<h1>Hello!</h1>"\n)\n</code></pre>\n<p>It has quite a lot of features:</p>\n<ul>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/tutorials/attachments.html\" rel=\"nofollow noreferrer\">Email attachments from various sources</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/tutorials/body_content.html\" rel=\"nofollow noreferrer\">Embedding images and plots to the HTML body</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/tutorials/jinja_support.html\" rel=\"nofollow noreferrer\">Templating emails with Jinja</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/tutorials/config.html\" rel=\"nofollow noreferrer\">Preconfigured Gmail and Outlook</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/extensions/logging.html\" rel=\"nofollow noreferrer\">Logging handler</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/en/latest/extensions/flask.html\" rel=\"nofollow noreferrer\">Flask extension</a></li>\n</ul>\n<p>Links:</p>\n<ul>\n<li><a href=\"https://github.com/Miksus/red-mail\" rel=\"nofollow noreferrer\">Source code</a></li>\n<li><a href=\"https://red-mail.readthedocs.io/\" rel=\"nofollow noreferrer\">Documentation</a></li>\n<li><a href=\"https://pypi.org/project/redmail/\" rel=\"nofollow noreferrer\">Releases</a></li>\n</ul>\n"
},
{
"answer_id": 74403965,
"author": "foodog123",
"author_id": 19566293,
"author_profile": "https://Stackoverflow.com/users/19566293",
"pm_score": 0,
"selected": false,
"text": "<p>Based on madman2890, updated a few things as well as removed the need for mailserver.quit()</p>\n<pre><code>import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nmsg = MIMEMultipart()\nmsg['From'] = '[email protected]'\nmsg['To'] = '[email protected]'\nmsg['Subject'] = 'simple email in python'\nmessage = 'here is the email'\nmsg.attach(MIMEText(message))\n\nwith smtplib.SMTP('smtp-mail.outlook.com',587) as mail_server:\n # identify ourselves to smtp gmail client\n mail_server.ehlo()\n # secure our email with tls encryption\n mail_server.starttls()\n # re-identify ourselves as an encrypted connection\n mail_server.ehlo()\n mail_server.login('[email protected]', 'mypassword')\n mail_server.sendmail('[email protected]','[email protected]',msg.as_string())\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
]
| I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?
```
from smtplib import SMTP
import datetime
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')
from_addr = "John Doe <[email protected]>"
to_addr = "[email protected]"
subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
% ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
``` | The script I use is quite similar; I post it here as an example of how to use the email.\* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc.
I rely on my ISP to add the date time header.
My ISP requires me to use a secure smtp connection to send mail, I rely on the smtplib module (downloadable at <http://www1.cs.columbia.edu/~db2501/ssmtplib.py>)
As in your script, the username and password, (given dummy values below), used to authenticate on the SMTP server, are in plain text in the source. This is a security weakness; but the best alternative depends on how careful you need (want?) to be about protecting these.
=======================================
```
#! /usr/local/bin/python
SMTPserver = 'smtp.att.yahoo.com'
sender = 'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']
USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""\
Test message
"""
subject="Sent from Python"
import sys
import os
import re
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.quit()
except:
sys.exit( "mail failed; %s" % "CUSTOM_ERROR" ) # give an error message
``` |
64,508 | <p>What does the following Guile scheme code do?</p>
<pre><code>(eq? y '.)
(cons x '.)
</code></pre>
<p>The code is not valid in MzScheme, is there a portable equivalent across scheme implementations?</p>
<p>I am trying to port this code written by someone else. Guile seems to respond to '. with #{.}#, but I'm not sure what it means or how to do this in another scheme.</p>
| [
{
"answer_id": 64530,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>I'm surprised any Scheme system will accept a dot symbol at all. My advice is to use another symbol as (I'm sure you're aware) the dot is a shorthand to represent a pair, and even if you can find a Scheme that will take your code you will likely confuse anyone that has the unfortunate task of actually reading your code.</p>\n"
},
{
"answer_id": 66068,
"author": "Ali",
"author_id": 8689,
"author_profile": "https://Stackoverflow.com/users/8689",
"pm_score": 3,
"selected": true,
"text": "<p>Okay, it seems that '. is valid syntax for (string->symbol \".\") in Guile, whereas MzScheme at least requires |.| for the period as a symbol.</p>\n"
},
{
"answer_id": 15561595,
"author": "NalaGinrut",
"author_id": 259033,
"author_profile": "https://Stackoverflow.com/users/259033",
"pm_score": 1,
"selected": false,
"text": "<p><code>#{.}#</code> is Guile specific way to define the symbol contains some delimiters of Scheme.\n<a href=\"http://www.gnu.org/software/guile/manual/html_node/Symbol-Read-Syntax.html\" rel=\"nofollow\">http://www.gnu.org/software/guile/manual/html_node/Symbol-Read-Syntax.html</a></p>\n\n<p>For other Scheme dialect, there should be another way.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8689/"
]
| What does the following Guile scheme code do?
```
(eq? y '.)
(cons x '.)
```
The code is not valid in MzScheme, is there a portable equivalent across scheme implementations?
I am trying to port this code written by someone else. Guile seems to respond to '. with #{.}#, but I'm not sure what it means or how to do this in another scheme. | Okay, it seems that '. is valid syntax for (string->symbol ".") in Guile, whereas MzScheme at least requires |.| for the period as a symbol. |
64,559 | <p>I've started to work a bit with master pages for an ASP.net mvc site and I've come across a question. When I link in a stylesheet on the master page it seems to update the path to the sheet correctly. That is in the code I have</p>
<pre><code><link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</code></pre>
<p>but looking at the source once the page is fed to a browser I get</p>
<pre><code><link href="Content/Site.css" rel="stylesheet" type="text/css" />
</code></pre>
<p>which is perfect. However the same path translation doesn't seem to work for script files. </p>
<pre><code><script src="../../Content/menu.js" type="text/javascript"></script>
</code></pre>
<p>just comes out as the same thing. It still seems to work on a top level page but I suspect that is just the browser/web server correcting my error. Is there a way to get the src path to be globbed too? </p>
| [
{
"answer_id": 64586,
"author": "Iain Holder",
"author_id": 1122,
"author_profile": "https://Stackoverflow.com/users/1122",
"pm_score": 0,
"selected": false,
"text": "<p>Use this instead:</p>\n\n<pre><code><link href=\"~/Content/Site.css\" rel=\"stylesheet\" type=\"text/css\" />\n</code></pre>\n"
},
{
"answer_id": 66376,
"author": "Dane O'Connor",
"author_id": 1946,
"author_profile": "https://Stackoverflow.com/users/1946",
"pm_score": 1,
"selected": false,
"text": "<p>Make an extension method. Here's a method:</p>\n\n<pre><code>public static string ResolveUrl(this HtmlHelper helper, string virtualUrl)\n{\n HttpContextBase ctx = helper.ViewContext.HttpContext;\n string result = virtualUrl;\n\n if (virtualUrl.StartsWith(\"~/\"))\n {\n virtualUrl = virtualUrl.Remove(0, 2);\n\n //get the site root\n string siteRoot = ctx.Request.ApplicationPath;\n\n if (!siteRoot.EndsWith(\"/\"))\n siteRoot += \"/\";\n\n result = siteRoot + virtualUrl;\n }\n return result;\n}\n</code></pre>\n\n<p>You can then write your script ref like:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"<%= Html.ResolveUrl(\"~/Content/menu.js\")%>\"></script>\n</code></pre>\n"
},
{
"answer_id": 66632,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 0,
"selected": false,
"text": "<p>or you can use BASE tag in you HEAD section of page. All you links then are relative to location entered in \"base\" tag, and you don't have to use \"../../\" and \"~\" stuff. Except links in CSS files (background url,etc), where links are relative to location of css file. </p>\n"
},
{
"answer_id": 169158,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": true,
"text": "<pre><code><script src=\"<%= ResolveClientUrl(\"~/Content/menu.js\") %>\" type=\"text/javascript\"></script>\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
]
| I've started to work a bit with master pages for an ASP.net mvc site and I've come across a question. When I link in a stylesheet on the master page it seems to update the path to the sheet correctly. That is in the code I have
```
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
```
but looking at the source once the page is fed to a browser I get
```
<link href="Content/Site.css" rel="stylesheet" type="text/css" />
```
which is perfect. However the same path translation doesn't seem to work for script files.
```
<script src="../../Content/menu.js" type="text/javascript"></script>
```
just comes out as the same thing. It still seems to work on a top level page but I suspect that is just the browser/web server correcting my error. Is there a way to get the src path to be globbed too? | ```
<script src="<%= ResolveClientUrl("~/Content/menu.js") %>" type="text/javascript"></script>
``` |
64,570 | <p>PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:</p>
<pre><code>var_dump(explode('/', '1/2//3/'));
array(5) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(0) ""
[3]=>
string(1) "3"
[4]=>
string(0) ""
}
</code></pre>
<p>Is there some different function or option or anything that would return everything <em>except</em> the empty strings?</p>
<pre><code>var_dump(different_explode('/', '1/2//3/'));
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
</code></pre>
| [
{
"answer_id": 64606,
"author": "James Aylett",
"author_id": 6302,
"author_profile": "https://Stackoverflow.com/users/6302",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function not_empty_string($s) {\n return $s !== \"\";\n}\n\narray_filter(explode('/', '1/2//3/'), 'not_empty_string');\n</code></pre>\n"
},
{
"answer_id": 64608,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 7,
"selected": true,
"text": "<p>Try <a href=\"http://php.net/preg_split\" rel=\"nofollow noreferrer\">preg_split</a>.</p>\n<p><code>$exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);</code></p>\n"
},
{
"answer_id": 64619,
"author": "Dave Gregory",
"author_id": 5677,
"author_profile": "https://Stackoverflow.com/users/5677",
"pm_score": 5,
"selected": false,
"text": "<p>array_filter will remove the blank fields, here is an example without the filter:</p>\n\n<pre><code>print_r(explode('/', '1/2//3/'))\n</code></pre>\n\n<p>prints:</p>\n\n<pre><code>Array\n(\n [0] => 1\n [1] => 2\n [2] =>\n [3] => 3\n [4] =>\n)\n</code></pre>\n\n<p>With the filter:</p>\n\n<pre><code>php> print_r(array_filter(explode('/', '1/2//3/')))\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>Array\n(\n [0] => 1\n [1] => 2\n [3] => 3\n)\n</code></pre>\n\n<p>You'll get all values that resolve to \"false\" filtered out. </p>\n\n<p>see <a href=\"http://uk.php.net/manual/en/function.array-filter.php\" rel=\"noreferrer\">http://uk.php.net/manual/en/function.array-filter.php</a></p>\n"
},
{
"answer_id": 64623,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 0,
"selected": false,
"text": "<p>Write a wrapper function to strip them</p>\n\n<pre><code>function MyExplode($sep, $str)\n{\n $arr = explode($sep, $str);\n foreach($arr as $item)\n if(item != \"\")\n $out[] = $item;\n return $out;\n}\n</code></pre>\n"
},
{
"answer_id": 64629,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": -1,
"selected": false,
"text": "<p>I usually wrap it in a call to <a href=\"http://uk.php.net/manual/en/function.array-filter.php\" rel=\"nofollow noreferrer\">array_filter</a>, e.g.</p>\n\n<pre><code>var_dump(array_filter(explode('/', '1/2//3/'))\n=>\narray(3) {\n [0]=>\n string(1) \"1\"\n [1]=>\n string(1) \"2\"\n [3]=>\n string(1) \"3\"\n}\n</code></pre>\n\n<p>Be aware, of course, that array keys are maintained; if you <em>don't</em> want this behaviour, remember to add an outer wrapper call to array_values().</p>\n"
},
{
"answer_id": 64658,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": -1,
"selected": false,
"text": "<p>PHP's <a href=\"http://us2.php.net/manual/en/function.split.php\" rel=\"nofollow noreferrer\">split function</a> is similar to the explode function, except that it allows you to enter a regex pattern as the delimiter. Something to the effect of:</p>\n\n<pre><code>$exploded_arr = split('/\\/+/', '1/2//3/');\n</code></pre>\n"
},
{
"answer_id": 64728,
"author": "AntonioCS",
"author_id": 8715,
"author_profile": "https://Stackoverflow.com/users/8715",
"pm_score": 0,
"selected": false,
"text": "<p>Use this function to filter the output of the explode function</p>\n\n<pre><code> function filter_empty(&$arrayvar) {\n $newarray = array();\n foreach ($arrayvar as $k => $value)\n if ($value !== \"\")\n $newarray[$k] = $value;\n\n $arrayvar = $newarray;\n }\n</code></pre>\n"
},
{
"answer_id": 64821,
"author": "Glenn Moss",
"author_id": 5726,
"author_profile": "https://Stackoverflow.com/users/5726",
"pm_score": 3,
"selected": false,
"text": "<p>Just for variety:</p>\n\n<pre><code>array_diff(explode('/', '1/2//3/'), array(''))\n</code></pre>\n\n<p>This also works, but does mess up the array indexes unlike preg_split. Some people might like it better than having to declare a callback function to use array_filter.</p>\n"
},
{
"answer_id": 72886,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 0,
"selected": false,
"text": "<p>Regular expression solutions tend to be much slower than basic text replacement, so i'd replace double seperators with single seperators, trim the string of any whitespace and then use explode:</p>\n\n<pre><code>// assuming $source = '1/2//3/';\n$source = str_replace('//', '/', $source);\n$source = trim($source);\n$parts = explode('/', $source);\n</code></pre>\n"
},
{
"answer_id": 23419614,
"author": "Memochipan",
"author_id": 826500,
"author_profile": "https://Stackoverflow.com/users/826500",
"pm_score": 1,
"selected": false,
"text": "<p>I have used this in <a href=\"http://doc-typo3.ameos.com/4.1.0/incfile_8php-source.html#l00011\" rel=\"nofollow\">TYPO3</a>, look at the <code>$onlyNonEmptyValues</code> parameter:</p>\n\n<pre><code>function trimExplode($delim, $string, $onlyNonEmptyValues=0){\n $temp = explode($delim,$string);\n $newtemp=array();\n while(list($key,$val)=each($temp)) {\n if (!$onlyNonEmptyValues || strcmp(\"\",trim($val))) {\n $newtemp[]=trim($val);\n }\n }\n reset($newtemp);\n return $newtemp;\n}\n</code></pre>\n\n<p>It doesn't mess up the indexes:</p>\n\n<pre><code>var_dump(trimExplode('/', '1/2//3/',1));\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>array(3) {\n [0]=>\n string(1) \"1\"\n [1]=>\n string(1) \"2\"\n [2]=>\n string(1) \"3\"\n}\n</code></pre>\n"
},
{
"answer_id": 35928378,
"author": "That Realty Programmer Guy",
"author_id": 578023,
"author_profile": "https://Stackoverflow.com/users/578023",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution that should output a newly indexed array.</p>\n\n<pre><code>$result = array_deflate( explode( $delim, $array) );\n\nfunction array_deflate( $arr, $emptyval='' ){\n $ret=[];\n for($i=0,$L=count($arr); $i<$L; ++$i)\n if($arr[$i] !== $emptyval) $ret[]=$arr[$i];\n return $ret;\n}\n</code></pre>\n\n<p>While fairly similar to some other suggestion, this implementation has the benefit of generic use. For arrays with non-string elements, provide a typed empty value as the second argument. </p>\n\n<p><code>array_deflate( $objArray, new stdClass() );</code></p>\n\n<p><code>array_deflate( $databaseArray, NULL );</code></p>\n\n<p><code>array_deflate( $intArray, NULL );</code></p>\n\n<p><code>array_deflate( $arrayArray, [] );</code></p>\n\n<p><code>array_deflate( $assocArrayArray, [''=>NULL] );</code></p>\n\n<p><code>array_deflate( $processedArray, new Exception('processing error') );</code></p>\n\n<p>.</p>\n\n<p>.</p>\n\n<p>.</p>\n\n<p>With an optional filter argument..</p>\n\n<pre><code>function array_deflate( $arr, $trigger='', $filter=NULL, $compare=NULL){\n $ret=[];\n if ($filter === NULL) $filter = function($el) { return $el; };\n if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };\n\n for($i=0,$L=count($arr); $i<$L; ++$i)\n if( !$compare(arr[$i],$trigger) ) $ret[]=$arr[$i];\n else $filter($arr[$i]);\n return $ret;\n}\n</code></pre>\n\n<p>With usage..</p>\n\n<pre><code>function targetHandler($t){ /* .... */ } \narray_deflate( $haystack, $needle, targetHandler );\n</code></pre>\n\n<p>Turning array_deflate into a way of processing choice elements and removing them from your array. Also nicer is to turn the if statement into a comparison function that is also passed as an argument in case you get fancy.</p>\n\n<p><code>array_inflate</code> being the reverse, would take an extra array as the first parameter which matches are pushed to while non-matches are filtered.</p>\n\n<pre><code>function array_inflate($dest,$src,$trigger='', $filter=NULL, $compare=NULL){\n if ($filter === NULL) $filter = function($el) { return $el; };\n if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };\n\n for($i=0,$L=count($src); $i<$L; ++$i)\n if( $compare(src[$i],$trigger) ) $dest[]=$src[$i];\n else $filter($src[$i]);\n return $dest;\n}\n</code></pre>\n\n<p>With usage..</p>\n\n<pre><code>$smartppl=[]; \n$smartppl=array_inflate( $smartppl,\n $allppl,\n (object)['intelligence'=>110],\n cureStupid,\n isSmart);\n\nfunction isSmart($a,$threshold){\n if( isset($a->intellgence) ) //has intelligence?\n if( isset($threshold->intellgence) ) //has intelligence?\n if( $a->intelligence >= $threshold->intelligence )\n return true;\n else return INVALID_THRESHOLD; //error\n else return INVALID_TARGET; //error\n return false;\n}\n\nfunction cureStupid($person){\n $dangerous_chemical = selectNeurosteroid();\n applyNeurosteroid($person, $dangerous_chemical);\n\n if( isSmart($person,(object)['intelligence'=>110]) ) \n return $person;\n else \n lobotomize($person);\n\n return $person;\n}\n</code></pre>\n\n<p>Thus providing an ideal algorithm for the world's educational problems. Aaand I'll stop there before I tweak this into something else..</p>\n"
},
{
"answer_id": 36192965,
"author": "Jeff",
"author_id": 6107585,
"author_profile": "https://Stackoverflow.com/users/6107585",
"pm_score": 0,
"selected": false,
"text": "<p>No regex overhead - should be reasonably efficient, strlen just counts the bytes</p>\n\n<p>Drop the array_values() if you don't care about indexes</p>\n\n<p>Make it into function explode_interesting( $array, $fix_index = 0 ) if you want</p>\n\n<pre><code>$interesting = array_values( \n array_filter(\n explode('/', '/1//2//3///4/0/false' ),\n function ($val) { return strlen($val); }\n ));\n\necho \"<pre>\", var_export( $interesting, true ), \"</pre>\";\n</code></pre>\n\n<p>enjoy, Jeff</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5726/"
]
| PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:
```
var_dump(explode('/', '1/2//3/'));
array(5) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(0) ""
[3]=>
string(1) "3"
[4]=>
string(0) ""
}
```
Is there some different function or option or anything that would return everything *except* the empty strings?
```
var_dump(different_explode('/', '1/2//3/'));
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
``` | Try [preg\_split](http://php.net/preg_split).
`$exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);` |
64,581 | <p>Any information on how to display the ODBC connections dialog and get the chosen ODBC back?</p>
| [
{
"answer_id": 64978,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>OK since no one seems to have an answer, how about iterating throught the ODBC connections by DBSource, I.e. SQLServer or MySQL</p>\n"
},
{
"answer_id": 65161,
"author": "RyanBrady",
"author_id": 2555,
"author_profile": "https://Stackoverflow.com/users/2555",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// a_RootKey is Microsoft.Win32.RegistryKey \n// DSN is a class not provided in this code sample - you can see what properties are needed from the usage below.\n\nList<DSN> DsnList = new List<DSN>();\n\nMicrosoft.Win32.RegistryKey SearchKey = a_RootKey.OpenSubKey(\"SOFTWARE\\\\ODBC\\\\ODBC.INI\\\\ODBC Data Sources\");\n\nif (SearchKey != null)\n{\n\n foreach (string DsnName in SearchKey.GetValueNames() )\n { \n if ( (string)SearchKey.GetValue(DsnName) == \"SQL Server\" )\n {\n Microsoft.Win32.RegistryKey anotherkey = a_RootKey.OpenSubKey(\"SOFTWARE\\\\ODBC\\\\ODBC.INI\\\\\" + DSNName);\n DSN dsn = new DSN();\n dsn.Name = DSNName;\n dsn.Server = (string)anotherkey.GetValue(\"Server\");\n dsn.Database = (string)anotherkey.GetValue(\"Database\");\n dsn.Driver = (string)anotherkey.GetValue(\"Driver\");\n\n DsnList.Add(dsn);\n }\n\n }\n}\nreturn DsnList;\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Any information on how to display the ODBC connections dialog and get the chosen ODBC back? | ```
// a_RootKey is Microsoft.Win32.RegistryKey
// DSN is a class not provided in this code sample - you can see what properties are needed from the usage below.
List<DSN> DsnList = new List<DSN>();
Microsoft.Win32.RegistryKey SearchKey = a_RootKey.OpenSubKey("SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources");
if (SearchKey != null)
{
foreach (string DsnName in SearchKey.GetValueNames() )
{
if ( (string)SearchKey.GetValue(DsnName) == "SQL Server" )
{
Microsoft.Win32.RegistryKey anotherkey = a_RootKey.OpenSubKey("SOFTWARE\\ODBC\\ODBC.INI\\" + DSNName);
DSN dsn = new DSN();
dsn.Name = DSNName;
dsn.Server = (string)anotherkey.GetValue("Server");
dsn.Database = (string)anotherkey.GetValue("Database");
dsn.Driver = (string)anotherkey.GetValue("Driver");
DsnList.Add(dsn);
}
}
}
return DsnList;
``` |
64,602 | <p>There are three assembly version attributes. What are differences? Is it ok if I use <code>AssemblyVersion</code> and ignore the rest?</p>
<hr>
<p>MSDN says:</p>
<ul>
<li><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyversionattribute" rel="noreferrer">AssemblyVersion</a>:</p>
<blockquote>
<p>Specifies the version of the assembly being attributed. </p>
</blockquote></li>
<li><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyfileversionattribute" rel="noreferrer">AssemblyFileVersion</a>:</p>
<blockquote>
<p>Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number. </p>
</blockquote></li>
<li><p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyinformationalversionattribute" rel="noreferrer">AssemblyInformationalVersion</a>:</p>
<blockquote>
<p>Defines additional version information for an assembly manifest. </p>
</blockquote></li>
</ul>
<hr>
<p><em>This is a follow-up to <a href="https://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes">What are the best practices for using Assembly Attributes?</a></em></p>
| [
{
"answer_id": 64634,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 5,
"selected": false,
"text": "<p><code>AssemblyVersion</code> pretty much stays internal to .NET, while <code>AssemblyFileVersion</code> is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the <code>AssemblyFileVersion</code> is what you'll see up top. If you sort files by version, this is what's used by Explorer.</p>\n\n<p>The <code>AssemblyInformationalVersion</code> maps to the \"Product Version\" and is meant to be purely \"human-used\".</p>\n\n<p><code>AssemblyVersion</code> is certainly the most important, but I wouldn't skip <code>AssemblyFileVersion</code>, either. If you don't provide <code>AssemblyInformationalVersion</code>, the compiler adds it for you by stripping off the \"revision\" piece of your version number and leaving the major.minor.build.</p>\n"
},
{
"answer_id": 64642,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "<p><code>AssemblyInformationalVersion</code> and <code>AssemblyFileVersion</code> are displayed when you view the \"Version\" information on a file through Windows Explorer by viewing the file properties. These attributes actually get compiled in to a <code>VERSION_INFO</code> resource that is created by the compiler.</p>\n\n<p><code>AssemblyInformationalVersion</code> is the \"Product version\" value. <code>AssemblyFileVersion</code> is the \"File version\" value.</p>\n\n<p>The <code>AssemblyVersion</code> is specific to .NET assemblies and is used by the .NET assembly loader to know which version of an assembly to load/bind at runtime.</p>\n\n<p>Out of these, the only one that is absolutely required by .NET is the <code>AssemblyVersion</code> attribute. Unfortunately it can also cause the most problems when it changes indiscriminately, especially if you are strong naming your assemblies.</p>\n"
},
{
"answer_id": 65062,
"author": "Remy van Duijkeren",
"author_id": 8820,
"author_profile": "https://Stackoverflow.com/users/8820",
"pm_score": 11,
"selected": true,
"text": "<p><strong>AssemblyVersion</strong></p>\n<p>Where other assemblies that reference your assembly will look. If this number changes, other assemblies must update their references to your assembly! Only update this version if it breaks backward compatibility. The <code>AssemblyVersion</code> is required.</p>\n<p>I use the format: <em>major.minor</em> (and <em>major</em> for very stable codebases). This would result in:</p>\n<pre><code>[assembly: AssemblyVersion("1.3")]\n</code></pre>\n<p>If you're following <a href=\"https://semver.org/\" rel=\"noreferrer\">SemVer</a> strictly then this means you only update when the <em>major</em> changes, so 1.0, 2.0, 3.0, etc.</p>\n<p><strong>AssemblyFileVersion</strong></p>\n<p>Used for deployment (like setup programs). You can increase this number for every deployment. Use it to mark assemblies that have the same <code>AssemblyVersion</code> but are generated from different builds and/or code.</p>\n<p>In Windows, it can be viewed in the file properties.</p>\n<p>The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.</p>\n<p>I use the format: <em>major.minor.patch.build</em>, where I follow <a href=\"https://semver.org/\" rel=\"noreferrer\">SemVer</a> for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build).\nThis would result in:</p>\n<pre><code>[assembly: AssemblyFileVersion("1.3.2.42")]\n</code></pre>\n<p>Be aware that <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.version\" rel=\"noreferrer\">System.Version</a> names these parts as <code>major.minor.build.revision</code>!</p>\n<p><strong>AssemblyInformationalVersion</strong></p>\n<p>The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '<em>1.0 Release Candidate</em>'.</p>\n<p>The <code>AssemblyInformationalVersion</code> is optional. If not given, the AssemblyFileVersion is used.</p>\n<p>I use the format: <em>major.minor[.patch] [revision as string]</em>. This would result in:</p>\n<pre><code>[assembly: AssemblyInformationalVersion("1.3 RC1")]\n</code></pre>\n"
},
{
"answer_id": 802038,
"author": "Daniel Fortunov",
"author_id": 5975,
"author_profile": "https://Stackoverflow.com/users/5975",
"pm_score": 9,
"selected": false,
"text": "<p>Versioning of assemblies in .NET can be a confusing prospect given that there are currently at least three ways to specify a version for your assembly.</p>\n\n<p>Here are the three main version-related assembly attributes:</p>\n\n<pre><code>// Assembly mscorlib, Version 2.0.0.0\n[assembly: AssemblyFileVersion(\"2.0.50727.3521\")]\n[assembly: AssemblyInformationalVersion(\"2.0.50727.3521\")]\n[assembly: AssemblyVersion(\"2.0.0.0\")]\n</code></pre>\n\n<p>By convention, the four parts of the version are referred to as the <strong>Major Version</strong>, <strong>Minor Version</strong>, <strong>Build</strong>, and <strong>Revision</strong>.</p>\n\n<h1>The <code>AssemblyFileVersion</code> is intended to uniquely identify a build of the <em>individual assembly</em></h1>\n\n<p>Typically you’ll manually set the Major and Minor AssemblyFileVersion to reflect the version of the assembly, then increment the Build and/or Revision every time your build system compiles the assembly. The AssemblyFileVersion should allow you to uniquely identify a build of the assembly, so that you can use it as a starting point for debugging any problems.</p>\n\n<p>On my current project we have the build server encode the changelist number from our source control repository into the Build and Revision parts of the AssemblyFileVersion. This allows us to map directly from an assembly to its source code, for any assembly generated by the build server (without having to use labels or branches in source control, or manually keeping any records of released versions).</p>\n\n<p>This version number is stored in the Win32 version resource and can be seen when viewing the Windows Explorer property pages for the assembly.</p>\n\n<p><strong>The CLR does not care about nor examine the AssemblyFileVersion.</strong></p>\n\n<h1>The <code>AssemblyInformationalVersion</code> is intended to represent the version of your entire product</h1>\n\n<p>The AssemblyInformationalVersion is intended to allow coherent versioning of the entire product, which may consist of many assemblies that are independently versioned, perhaps with differing versioning policies, and potentially developed by disparate teams.</p>\n\n<blockquote>\n <p>“For example, version 2.0 of a product\n might contain several assemblies; one\n of these assemblies is marked as\n version 1.0 since it’s a new assembly\n that didn’t ship in version 1.0 of the\n same product. Typically, you set the\n major and minor parts of this version\n number to represent the public version\n of your product. Then you increment\n the build and revision parts each time\n you package a complete product with\n all its assemblies.”\n — Jeffrey Richter, [CLR via C# (Second Edition)] p. 57</p>\n</blockquote>\n\n<p><strong>The CLR does not care about nor examine the AssemblyInformationalVersion.</strong></p>\n\n<h1>The <code>AssemblyVersion</code> is the only version the CLR cares about (but it cares about the entire <code>AssemblyVersion</code>)</h1>\n\n<p>The AssemblyVersion is used by the CLR to bind to strongly named assemblies. It is stored in the AssemblyDef manifest metadata table of the built assembly, and in the AssemblyRef table of any assembly that references it.</p>\n\n<p>This is very important, because it means that when you reference a strongly named assembly, you are tightly bound to a specific AssemblyVersion of that assembly. The entire AssemblyVersion must be an exact match for the binding to succeed. For example, if you reference version 1.0.0.0 of a strongly named assembly at build-time, but only version 1.0.0.1 of that assembly is available at runtime, binding will fail! (You will then have to work around this using <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection\" rel=\"noreferrer\">Assembly Binding Redirection</a>.)</p>\n\n<h1>Confusion over whether the entire <code>AssemblyVersion</code> has to match. (Yes, it does.)</h1>\n\n<p>There is a little confusion around whether the entire AssemblyVersion has to be an exact match in order for an assembly to be loaded. Some people are under the false belief that only the Major and Minor parts of the AssemblyVersion have to match in order for binding to succeed. This is a sensible assumption, however it is ultimately incorrect (as of .NET 3.5), and it’s trivial to verify this for your version of the CLR. Just execute <a href=\"http://webjam-upload.s3.amazonaws.com/assemblybinding___fcbd12afca1d4bb3bf94bf88d1616d25__100__.rar\" rel=\"noreferrer\">this sample code</a>.</p>\n\n<p>On my machine the second assembly load fails, and the last two lines of the fusion log make it perfectly clear why:</p>\n\n<pre><code>.NET Framework Version: 2.0.50727.3521\n---\nAttempting to load assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f\nSuccessfully loaded assembly: Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f\n---\nAttempting to load assembly: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f\nAssembly binding for failed:\nSystem.IO.FileLoadException: Could not load file or assembly 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, \nPublicKeyToken=0b3305902db7183f' or one of its dependencies. The located assembly's manifest definition \ndoes not match the assembly reference. (Exception from HRESULT: 0x80131040)\nFile name: 'Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f'\n\n=== Pre-bind state information ===\nLOG: User = Phoenix\\Dani\nLOG: DisplayName = Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f\n (Fully-specified)\nLOG: Appbase = [...]\nLOG: Initial PrivatePath = NULL\nCalling assembly : AssemblyBinding, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.\n===\nLOG: This bind starts in default load context.\nLOG: No application configuration file found.\nLOG: Using machine configuration file from C:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727\\config\\machine.config.\nLOG: Post-policy reference: Rhino.Mocks, Version=3.5.0.1336, Culture=neutral, PublicKeyToken=0b3305902db7183f\nLOG: Attempting download of new URL [...].\nWRN: Comparing the assembly name resulted in the mismatch: Revision Number\nERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.\n</code></pre>\n\n<p>I think the source of this confusion is probably because Microsoft originally intended to be a little more lenient on this strict matching of the full AssemblyVersion, by matching only on the Major and Minor version parts:</p>\n\n<blockquote>\n <p>“When loading an assembly, the CLR will automatically find the latest\n installed servicing version that\n matches the major/minor version of the\n assembly being requested.”\n — Jeffrey Richter, [CLR via C# (Second Edition)] p. 56</p>\n</blockquote>\n\n<p>This was the behaviour in Beta 1 of the 1.0 CLR, however this feature was removed before the 1.0 release, and hasn’t managed to re-surface in .NET 2.0:</p>\n\n<blockquote>\n <p>“Note: I have just described how you\n should think of version numbers.\n Unfortunately, the CLR doesn’t treat\n version numbers this way. [In .NET\n 2.0], the CLR treats a version number as an opaque value, and if an assembly\n depends on version 1.2.3.4 of another\n assembly, the CLR tries to load\n version 1.2.3.4 only (unless a binding\n redirection is in place). However,\n <strong>Microsoft has plans to change the\n CLR’s loader in a future version so\n that it loads the latest\n build/revision for a given major/minor\n version of an assembly</strong>. For example,\n on a future version of the CLR, if the\n loader is trying to find version\n 1.2.3.4 of an assembly and version 1.2.5.0 exists, the loader with automatically pick up the latest\n servicing version. This will be a very\n welcome change to the CLR’s loader — I\n for one can’t wait.”\n — Jeffrey Richter, [CLR via C# (Second Edition)] p. 164 (Emphasis\n mine)</p>\n</blockquote>\n\n<p>As this change still hasn’t been implemented, I think it’s safe to assume that Microsoft had back-tracked on this intent, and it is perhaps too late to change this now. I tried to search around the web to find out what happened with these plans, but I couldn’t find any answers. I still wanted to get to the bottom of it.</p>\n\n<p>So I emailed Jeff Richter and asked him directly — I figured if anyone knew what happened, it would be him.</p>\n\n<p>He replied within 12 hours, on a Saturday morning no less, and clarified that the .NET 1.0 Beta 1 loader did implement this ‘automatic roll-forward’ mechanism of picking up the latest available Build and Revision of an assembly, but this behaviour was reverted before .NET 1.0 shipped. It was later intended to revive this but it didn’t make it in before the CLR 2.0 shipped. Then came Silverlight, which took priority for the CLR team, so this functionality got delayed further. In the meantime, most of the people who were around in the days of CLR 1.0 Beta 1 have since moved on, so it’s unlikely that this will see the light of day, despite all the hard work that had already been put into it.</p>\n\n<p>The current behaviour, it seems, is here to stay.</p>\n\n<p>It is also worth noting from my discussion with Jeff that AssemblyFileVersion was only added after the removal of the ‘automatic roll-forward’ mechanism — because after 1.0 Beta 1, any change to the AssemblyVersion was a breaking change for your customers, there was then nowhere to safely store your build number. AssemblyFileVersion is that safe haven, since it’s never automatically examined by the CLR. Maybe it’s clearer that way, having two separate version numbers, with separate meanings, rather than trying to make that separation between the Major/Minor (breaking) and the Build/Revision (non-breaking) parts of the AssemblyVersion.</p>\n\n<h1>The bottom line: Think carefully about when you change your <code>AssemblyVersion</code></h1>\n\n<p>The moral is that if you’re shipping assemblies that other developers are going to be referencing, you need to be extremely careful about when you do (and don’t) change the AssemblyVersion of those assemblies. Any changes to the AssemblyVersion will mean that application developers will either have to re-compile against the new version (to update those AssemblyRef entries) or use assembly binding redirects to manually override the binding.</p>\n\n<ul>\n<li><strong>Do not</strong> change the AssemblyVersion for a servicing release which is intended to be backwards compatible.</li>\n<li><strong>Do</strong> change the AssemblyVersion for a release that you know has breaking changes.</li>\n</ul>\n\n<p>Just take another look at the version attributes on mscorlib:</p>\n\n<pre><code>// Assembly mscorlib, Version 2.0.0.0\n[assembly: AssemblyFileVersion(\"2.0.50727.3521\")]\n[assembly: AssemblyInformationalVersion(\"2.0.50727.3521\")]\n[assembly: AssemblyVersion(\"2.0.0.0\")]\n</code></pre>\n\n<p>Note that it’s the AssemblyFileVersion that contains all the interesting servicing information (it’s the Revision part of this version that tells you what Service Pack you’re on), meanwhile the AssemblyVersion is fixed at a boring old 2.0.0.0. Any change to the AssemblyVersion would force every .NET application referencing mscorlib.dll to re-compile against the new version!</p>\n"
},
{
"answer_id": 9323308,
"author": "linquize",
"author_id": 1031218,
"author_profile": "https://Stackoverflow.com/users/1031218",
"pm_score": 2,
"selected": false,
"text": "<p>When a assembly' s AssemblyVersion is changed,\nIf it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load!\nIf it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory. </p>\n"
},
{
"answer_id": 20254633,
"author": "DavidM",
"author_id": 1422300,
"author_profile": "https://Stackoverflow.com/users/1422300",
"pm_score": 3,
"selected": false,
"text": "<p>It's worth noting some other things:</p>\n<ol>\n<li><p>As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.</p>\n<p>In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.</p>\n</li>\n<li><p>AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.</p>\n<p>Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.</p>\n</li>\n<li><p>I don't know the impact upon an installer of using something other than numeric file version numbers, though.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 37982586,
"author": "KCD",
"author_id": 516748,
"author_profile": "https://Stackoverflow.com/users/516748",
"pm_score": 3,
"selected": false,
"text": "<p>To keep this question current it is worth highlighting that <code>AssemblyInformationalVersion</code> is used by NuGet and reflects the <strong>package version</strong> including any pre-release suffix.</p>\n\n<p>For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli</p>\n\n<pre><code>dotnet pack --version-suffix ci-7 src/MyProject\n</code></pre>\n\n<p>Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:</p>\n\n<pre><code>CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
]
| There are three assembly version attributes. What are differences? Is it ok if I use `AssemblyVersion` and ignore the rest?
---
MSDN says:
* [AssemblyVersion](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyversionattribute):
>
> Specifies the version of the assembly being attributed.
>
>
>
* [AssemblyFileVersion](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyfileversionattribute):
>
> Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number.
>
>
>
* [AssemblyInformationalVersion](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyinformationalversionattribute):
>
> Defines additional version information for an assembly manifest.
>
>
>
---
*This is a follow-up to [What are the best practices for using Assembly Attributes?](https://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes)* | **AssemblyVersion**
Where other assemblies that reference your assembly will look. If this number changes, other assemblies must update their references to your assembly! Only update this version if it breaks backward compatibility. The `AssemblyVersion` is required.
I use the format: *major.minor* (and *major* for very stable codebases). This would result in:
```
[assembly: AssemblyVersion("1.3")]
```
If you're following [SemVer](https://semver.org/) strictly then this means you only update when the *major* changes, so 1.0, 2.0, 3.0, etc.
**AssemblyFileVersion**
Used for deployment (like setup programs). You can increase this number for every deployment. Use it to mark assemblies that have the same `AssemblyVersion` but are generated from different builds and/or code.
In Windows, it can be viewed in the file properties.
The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.
I use the format: *major.minor.patch.build*, where I follow [SemVer](https://semver.org/) for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build).
This would result in:
```
[assembly: AssemblyFileVersion("1.3.2.42")]
```
Be aware that [System.Version](https://learn.microsoft.com/en-us/dotnet/api/system.version) names these parts as `major.minor.build.revision`!
**AssemblyInformationalVersion**
The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '*1.0 Release Candidate*'.
The `AssemblyInformationalVersion` is optional. If not given, the AssemblyFileVersion is used.
I use the format: *major.minor[.patch] [revision as string]*. This would result in:
```
[assembly: AssemblyInformationalVersion("1.3 RC1")]
``` |
64,605 | <p>Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue).</p>
| [
{
"answer_id": 64638,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": true,
"text": "<p>Yeah, just separate them into different script tags:</p>\n\n<pre><code><script language=\"javascript\">\n // javascript code\n</script>\n\n<script language=\"vbscript\">\n ' vbscript code\n</script>\n</code></pre>\n\n<p>Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work.</p>\n\n<p>Edit: This is also true of ANY Windows Scripting technology. It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed.</p>\n\n<p>Edit: The specific \"gotcha\" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible \"gotchas\".</p>\n"
},
{
"answer_id": 14622356,
"author": "caglaror",
"author_id": 430447,
"author_profile": "https://Stackoverflow.com/users/430447",
"pm_score": 0,
"selected": false,
"text": "<p>Also you can give references between them. For example: \nat the background some function on vbscript handle with database and FSO issues, and let javascript create user interfaces and dialogs etc. with DOM in frontline.\nWhenever you need you can call both functions from each script sides.\nIn js you can call vbs function, and also in vbscript you can call js functions. Then you can use their returns where you call them.\nRegards</p>\n"
},
{
"answer_id": 37095721,
"author": "Dennis Bareis",
"author_id": 3972414,
"author_profile": "https://Stackoverflow.com/users/3972414",
"pm_score": 0,
"selected": false,
"text": "<p>Event handlers (like Onclick) should have the code prefixed with \"javascript:\" or \"vbscript:\"</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5616/"
]
| Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue). | Yeah, just separate them into different script tags:
```
<script language="javascript">
// javascript code
</script>
<script language="vbscript">
' vbscript code
</script>
```
Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work.
Edit: This is also true of ANY Windows Scripting technology. It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed.
Edit: The specific "gotcha" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible "gotchas". |
64,639 | <p>What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#?</p>
| [
{
"answer_id": 64662,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<pre><code>Double.Parse(\"1.234567E-06\", System.Globalization.NumberStyles.Float);\n</code></pre>\n"
},
{
"answer_id": 221197,
"author": "Jaymie Thomas",
"author_id": 7703,
"author_profile": "https://Stackoverflow.com/users/7703",
"pm_score": 4,
"selected": false,
"text": "<p>Also consider using</p>\n\n<pre><code>Double.TryParse(\"1.234567E-06\", System.Globalization.NumberStyles.Float, out MyFloat);\n</code></pre>\n\n<p>This will ensure that <code>MyFloat</code> is set to value 0 if, for whatever reason, the conversion could not be performed. Or you could wrap the <code>Double.Parse()</code> example in a <code>Try..Catch</code> block and set <code>MyFloat</code> to a value of your choosing when an exception is detected.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2488/"
]
| What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#? | ```
Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);
``` |
64,640 | <p>Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# <strong>should</strong> be as easy as </p>
<pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd");
</code></pre>
<p>but no, C# forces you to create an IFormatProvider.</p>
<p>Is there an app.config friendly way of setting this so I don't need to do this each time?</p>
<pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true));
</code></pre>
| [
{
"answer_id": 64655,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>The IFormatProvider argument can be null.</p>\n"
},
{
"answer_id": 64675,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>Create an extension method:</p>\n\n<pre><code>public static DateTime ParseExactDateTime(this string dateString, string formatString) {\n return DateTime.ParseExact(dateString, formatString, new CultureInfo(\"en-CA\", true));\n}\n</code></pre>\n"
},
{
"answer_id": 64701,
"author": "David J. Sokol",
"author_id": 1390,
"author_profile": "https://Stackoverflow.com/users/1390",
"pm_score": 3,
"selected": false,
"text": "<p>Use the current application culture:</p>\n\n<pre><code>DateTime.ParseExact(\"2008/12/05\", \"yyyy/MM/dd\", System.Globalization.CultureInfo.CurrentCulture);\n</code></pre>\n\n<p>You can set the application culture in the app.config using the Globalization tag. I think.</p>\n"
},
{
"answer_id": 64706,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 1,
"selected": false,
"text": "<p>You could also simply create the IFormatProvider once and store it for later use.</p>\n"
},
{
"answer_id": 64729,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 1,
"selected": false,
"text": "<p>You could also use the Convert class</p>\n\n<pre><code>Convert.ToDateTime(\"2008/11/25\");\n</code></pre>\n"
},
{
"answer_id": 64744,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>ParseExact needs a culture : consider \"yyyy MMM dd\". MMM will be a localized month name that uses the current culture.</p>\n"
},
{
"answer_id": 64757,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>It requires the format provider in order to determine the particular date and time symbols and strings (such as names of the days of the week in a particular language). You can use a null, in which case the CultureInfo object that corresponds to the current culture is used.</p>\n\n<p>If you don't want to have to specify it each time, create an extension method which either passes null or CultureInfo(\"en-CA\", true) as the format provider.</p>\n"
},
{
"answer_id": 421924,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>//Convert date to MySql compatible format</p>\n\n<p>DateTime DateValue = Convert.ToDateTime(datetimepicker.text);</p>\n\n<p>string datevalue = DateValue.ToString(\"yyyy-MM-dd\");</p>\n"
},
{
"answer_id": 2365139,
"author": "Nicholas Head",
"author_id": 22505,
"author_profile": "https://Stackoverflow.com/users/22505",
"pm_score": 0,
"selected": false,
"text": "<p>What's wrong with using Globalization.CultureInfo.InvariantCulture ?</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7311/"
]
| Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# **should** be as easy as
```
DateTime.ParseExact(theDate, "yyyy/MM/dd");
```
but no, C# forces you to create an IFormatProvider.
Is there an app.config friendly way of setting this so I don't need to do this each time?
```
DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true));
``` | The IFormatProvider argument can be null. |
64,649 | <p>If I issue the <a href="https://en.wikipedia.org/wiki/Find_(Unix)" rel="noreferrer">find</a> command as follows:</p>
<pre><code>find . -name *.ear
</code></pre>
<p>It prints out:</p>
<pre><code>./dir1/dir2/earFile1.ear
./dir1/dir2/earFile2.ear
./dir1/dir3/earFile1.ear
</code></pre>
<p>I want to 'print' the name and the size to the command line:</p>
<pre><code>./dir1/dir2/earFile1.ear 5000 KB
./dir1/dir2/earFile2.ear 5400 KB
./dir1/dir3/earFile1.ear 5400 KB
</code></pre>
| [
{
"answer_id": 64666,
"author": "Jeremy Weathers",
"author_id": 8794,
"author_profile": "https://Stackoverflow.com/users/8794",
"pm_score": 0,
"selected": false,
"text": "<pre><code>find . -name \"*.ear\" -exec ls -l {} \\;\n</code></pre>\n"
},
{
"answer_id": 64678,
"author": "Yaba",
"author_id": 7524,
"author_profile": "https://Stackoverflow.com/users/7524",
"pm_score": 1,
"selected": false,
"text": "<p>You could try this:</p>\n\n<pre><code>find. -name *.ear -exec du {} \\;\n</code></pre>\n\n<p>This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like</p>\n\n<pre><code>5000 ./dir1/dir2/earFile1.ear\n5400 ./dir1/dir2/earFile2.ear\n5400 ./dir1/dir3/earFile1.ear\n</code></pre>\n"
},
{
"answer_id": 64683,
"author": "killdash10",
"author_id": 7621,
"author_profile": "https://Stackoverflow.com/users/7621",
"pm_score": 1,
"selected": false,
"text": "<pre><code>find . -name \"*.ear\" | xargs ls -sh\n</code></pre>\n"
},
{
"answer_id": 64684,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 5,
"selected": false,
"text": "<p>A simple solution is to use the <em>-ls</em> option in <em>find</em>:</p>\n<pre><code>find . -name \\*.ear -ls\n</code></pre>\n<p>That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:</p>\n<pre><code>find . -name \\*.ear -printf "%p\\t%k KB\\n"\n</code></pre>\n<p>Which will give you the filename followed by the size in KB.</p>\n"
},
{
"answer_id": 64691,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 7,
"selected": false,
"text": "<p>You need to use -exec or -printf. Printf works like this:</p>\n\n<pre><code>find . -name *.ear -printf \"%p %k KB\\n\"\n</code></pre>\n\n<p>-exec is more powerful and lets you execute arbitrary commands - so you could use a version of 'ls' or 'wc' to print out the filename along with other information. 'man find' will show you the available arguments to printf, which can do a lot more than just filesize.</p>\n\n<p>[edit] -printf is not in the official POSIX standard, so check if it is supported on your version. However, most modern systems will use GNU find or a similarly extended version, so there is a good chance it will be implemented.</p>\n"
},
{
"answer_id": 64699,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 8,
"selected": true,
"text": "<pre><code>find . -name '*.ear' -exec ls -lh {} \\;\n</code></pre>\n\n<p>just the h extra from jer.drab.org's reply. saves time converting to MB mentally ;)</p>\n"
},
{
"answer_id": 64770,
"author": "dmazzoni",
"author_id": 7193,
"author_profile": "https://Stackoverflow.com/users/7193",
"pm_score": 5,
"selected": false,
"text": "<p>Using GNU find, I think this is what you want. It finds all real files and not directories (<em>-type f</em>), and for each one prints the filename (%p), a tab (\\t), the size in kilobytes (%k), the suffix " KB", and then a newline (\\n).</p>\n<pre><code>find . -type f -printf '%p\\t%k KB\\n'\n</code></pre>\n<p>If the <em>printf</em> command doesn't format things the way you want, you can use <em><a href=\"https://linux.die.net/man/1/exec\" rel=\"nofollow noreferrer\">exec</a></em>, followed by the command you want to execute on each file. Use {} for the filename, and terminate the command with a semicolon (;). On most shells, all three of those characters should be escaped with a backslash.</p>\n<p>Here's a simple solution that finds and prints them out using "ls -lh", which will show you the size in human-readable form (<em>k</em> for kilobytes and <em>M</em> for megabytes):</p>\n<pre><code>find . -type f -exec ls -lh \\{\\} \\;\n</code></pre>\n<p>As yet another alternative, "wc -c" will print the number of characters (bytes) in the file:</p>\n<pre><code>find . -type f -exec wc -c \\{\\} \\;\n</code></pre>\n"
},
{
"answer_id": 244894,
"author": "tpgould",
"author_id": 32161,
"author_profile": "https://Stackoverflow.com/users/32161",
"pm_score": 2,
"selected": false,
"text": "<p>Awk can fix up the output to give just what the questioner asked for. On my Solaris 10 system, find -ls prints size in KB as the second field, so:</p>\n\n<pre><code>% find . -name '*.ear' -ls | awk '{print $2, $11}'\n5400 ./dir1/dir2/earFile2.ear\n5400 ./dir1/dir2/earFile3.ear\n5400 ./dir1/dir2/earFile1.ear\n</code></pre>\n\n<p>Otherwise, use -exec ls -lh and pick out the size field from the output.\nAgain on Solaris 10:</p>\n\n<pre><code>% find . -name '*.ear' -exec ls -lh {} \\; | awk '{print $5, $9}'\n5.3M ./dir1/dir2/earFile2.ear\n5.3M ./dir1/dir2/earFile3.ear\n5.3M ./dir1/dir2/earFile1.ear\n</code></pre>\n"
},
{
"answer_id": 2008917,
"author": "scripter",
"author_id": 244232,
"author_profile": "https://Stackoverflow.com/users/244232",
"pm_score": 1,
"selected": false,
"text": "<pre>\n$ find . -name \"test*\" -exec du -sh {} \\;\n4.0K ./test1\n0 ./test2\n0 ./test3\n0 ./test4\n$\n</pre>\n\n<p><a href=\"http://www.scripterworld.com/2009/07/unix-find-command-with-examples-and.html\" rel=\"nofollow noreferrer\">Scripter World reference</a></p>\n"
},
{
"answer_id": 8364384,
"author": "Mike M",
"author_id": 1078432,
"author_profile": "https://Stackoverflow.com/users/1078432",
"pm_score": 2,
"selected": false,
"text": "<p>I struggled with this on Mac OS X where the find command doesn't support <code>-printf</code>.</p>\n\n<p>A solution that I found, that admittedly relies on the 'group' for all files being 'staff' was...</p>\n\n<pre><code>ls -l -R | sed 's/\\(.*\\)staff *\\([0-9]*\\)..............\\(.*\\)/\\2 \\3/'\n</code></pre>\n\n<p>This splits the ls long output into three tokens</p>\n\n<ol>\n<li>the stuff before the text 'staff'</li>\n<li>the file size</li>\n<li>the file name</li>\n</ol>\n\n<p>And then outputs tokens 2 and 3, i.e. output is number of bytes and then filename</p>\n\n<pre><code>8071 sections.php\n54681 services.php\n37961 style.css\n13260 thumb.php\n70951 workshops.php\n</code></pre>\n"
},
{
"answer_id": 14184795,
"author": "Andreas",
"author_id": 1953201,
"author_profile": "https://Stackoverflow.com/users/1953201",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use <strong>du -a</strong> ? E.g. </p>\n\n<pre><code>find . -name \"*.ear\" -exec du -a {} \\;\n</code></pre>\n\n<p>Works on a Mac</p>\n"
},
{
"answer_id": 21101734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>find . -name '*.ear' -exec du -h {} \\;\n</code></pre>\n\n<p>This gives you the filesize only, instead of all the unnecessary stuff.</p>\n"
},
{
"answer_id": 22691385,
"author": "adriano72",
"author_id": 988044,
"author_profile": "https://Stackoverflow.com/users/988044",
"pm_score": 2,
"selected": false,
"text": "<p>This should get you what you're looking for, formatting included (i.e. file name first and size afterward):</p>\n\n<pre><code>find . -type f -iname \"*.ear\" -exec du -ah {} \\; | awk '{print $2\"\\t\", $1}'\n</code></pre>\n\n<p>sample output (where I used <code>-iname \"*.php\"</code> to get some result):</p>\n\n<pre><code>./plugins/bat/class.bat.inc.php 20K\n./plugins/quotas/class.quotas.inc.php 8.0K\n./plugins/dmraid/class.dmraid.inc.php 8.0K\n./plugins/updatenotifier/class.updatenotifier.inc.php 4.0K\n./index.php 4.0K\n./config.php 12K\n./includes/mb/class.hwsensors.inc.php 8.0K\n</code></pre>\n"
},
{
"answer_id": 35129844,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following commands:</p>\n\n<p>GNU <code>stat</code>:</p>\n\n<pre><code>find . -type f -name *.ear -exec stat -c \"%n %s\" {} ';'\n</code></pre>\n\n<p>BSD <code>stat</code>:</p>\n\n<pre><code>find . -type f -name *.ear -exec stat -f \"%N %z\" {} ';'\n</code></pre>\n\n<p>however <code>stat</code> isn't standard, so <code>du</code> or <code>wc</code> could be a better approach:</p>\n\n<pre><code>find . -type f -name *.ear -exec sh -c 'echo \"{} $(wc -c < {})\"' ';'\n</code></pre>\n"
},
{
"answer_id": 62017923,
"author": "Damien C",
"author_id": 2261243,
"author_profile": "https://Stackoverflow.com/users/2261243",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to get total size, here is a script proposal</p>\n\n<pre><code>#!/bin/bash\ntotalSize=0\n\nallSizes=`find . -type f -name *.ear -exec stat -c \"%s\" {} \\;`\n\nfor fileSize in $allSizes; do\n totalSize=`echo \"$(($totalSize+$fileSize))\"`\ndone\necho \"Total size is $totalSize bytes\"\n</code></pre>\n"
},
{
"answer_id": 67577432,
"author": "NILESH KUMAR",
"author_id": 5036094,
"author_profile": "https://Stackoverflow.com/users/5036094",
"pm_score": -1,
"selected": false,
"text": "<p>You could try for loop:</p>\n<pre><code>for i in `find . -iname "*.ear"`; do ls -lh $i; done\n</code></pre>\n"
},
{
"answer_id": 69855684,
"author": "Craig",
"author_id": 529256,
"author_profile": "https://Stackoverflow.com/users/529256",
"pm_score": 2,
"selected": false,
"text": "<p>Just list the files (<code>-type f</code>) that match the pattern (<code>-name '*.ear</code>) using the disk-usage command (<code>du -h</code>) and sort the files by the human-readable file size (<code>sort -h</code>):</p>\n<pre><code>find . -type f -name '*.ear' -exec du -h {} \\; | sort -h\n</code></pre>\n<p>Output</p>\n<pre><code>5.0k ./dir1/dir2/earFile1.ear\n5.4k ./dir1/dir2/earFile2.ear\n5.4k ./dir1/dir3/earFile1.ear\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700/"
]
| If I issue the [find](https://en.wikipedia.org/wiki/Find_(Unix)) command as follows:
```
find . -name *.ear
```
It prints out:
```
./dir1/dir2/earFile1.ear
./dir1/dir2/earFile2.ear
./dir1/dir3/earFile1.ear
```
I want to 'print' the name and the size to the command line:
```
./dir1/dir2/earFile1.ear 5000 KB
./dir1/dir2/earFile2.ear 5400 KB
./dir1/dir3/earFile1.ear 5400 KB
``` | ```
find . -name '*.ear' -exec ls -lh {} \;
```
just the h extra from jer.drab.org's reply. saves time converting to MB mentally ;) |
64,653 | <p>I am trying to delete several rows from a MySQL 5.0.45 database:</p>
<pre><code>delete from bundle_inclusions;
</code></pre>
<p>The client works for a while and then returns the error:</p>
<pre><code>Lock wait timeout exceeded; try restarting transaction
</code></pre>
<p>It's possible there is some uncommitted transaction out there that has a lock on this table, but I need this process to trump any such locks. How do I break the lock in MySQL?</p>
| [
{
"answer_id": 64695,
"author": "Erik",
"author_id": 6733,
"author_profile": "https://Stackoverflow.com/users/6733",
"pm_score": 2,
"selected": false,
"text": "<p>Guessing: truncate table bundle_inclusions</p>\n"
},
{
"answer_id": 64771,
"author": "Matt Solnit",
"author_id": 6198,
"author_profile": "https://Stackoverflow.com/users/6198",
"pm_score": 6,
"selected": true,
"text": "<p>I agree with Erik; TRUNCATE TABLE is the way to go. However, if you can't use that for some reason (for example, if you don't <em>really</em> want to delete every row in the table), you can try the following options:</p>\n\n<ul>\n<li>Delete the rows in smaller batches (e.g. DELETE FROM bundle_inclusions WHERE id BETWEEN ? and ?)</li>\n<li>If it's a MyISAM table (actually, this may work with InnoDB too), try issuing a LOCK TABLE before the DELETE. This should guarantee that you have exclusive access.</li>\n<li>If it's an InnoDB table, then <em>after</em> the timeout occurs, use SHOW INNODB STATUS. This should give you some insight into why the lock acquisition failed.</li>\n<li>If you have the SUPER privilege you could try SHOW PROCESSLIST ALL to see what other connections (if any) are using the table, and then use KILL to get rid of the one(s) you're competing with.</li>\n</ul>\n\n<p>I'm sure there are many other possibilities; I hope one of these help.</p>\n"
},
{
"answer_id": 10704454,
"author": "Lars Bohl",
"author_id": 438960,
"author_profile": "https://Stackoverflow.com/users/438960",
"pm_score": 3,
"selected": false,
"text": "<p>Linux: In mysql configuration (/etc/my.cnf or /etc/mysql/my.cnf), insert / edit this line</p>\n\n<pre><code>innodb_lock_wait_timeout = 50\n</code></pre>\n\n<p>Increase the value sufficiently (it is in seconds), restart database, perform changes. Then revert the change and restart again.</p>\n"
},
{
"answer_id": 15539899,
"author": "Eric Cope",
"author_id": 256484,
"author_profile": "https://Stackoverflow.com/users/256484",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same issue, a rogue transaction without a end. I restarted the mysqld process. You don't need to truncate a table. You may lose data from that rogue transaction.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8344/"
]
| I am trying to delete several rows from a MySQL 5.0.45 database:
```
delete from bundle_inclusions;
```
The client works for a while and then returns the error:
```
Lock wait timeout exceeded; try restarting transaction
```
It's possible there is some uncommitted transaction out there that has a lock on this table, but I need this process to trump any such locks. How do I break the lock in MySQL? | I agree with Erik; TRUNCATE TABLE is the way to go. However, if you can't use that for some reason (for example, if you don't *really* want to delete every row in the table), you can try the following options:
* Delete the rows in smaller batches (e.g. DELETE FROM bundle\_inclusions WHERE id BETWEEN ? and ?)
* If it's a MyISAM table (actually, this may work with InnoDB too), try issuing a LOCK TABLE before the DELETE. This should guarantee that you have exclusive access.
* If it's an InnoDB table, then *after* the timeout occurs, use SHOW INNODB STATUS. This should give you some insight into why the lock acquisition failed.
* If you have the SUPER privilege you could try SHOW PROCESSLIST ALL to see what other connections (if any) are using the table, and then use KILL to get rid of the one(s) you're competing with.
I'm sure there are many other possibilities; I hope one of these help. |
64,689 | <p>Is this function declaration in C#:</p>
<pre><code>void foo(string mystring)
</code></pre>
<p>the same as this one in C:</p>
<pre><code>void foo(char *)
</code></pre>
<p>i.e. In C#, does the called function receive a pointer behind the scenes?</p>
| [
{
"answer_id": 64710,
"author": "Nate Kohari",
"author_id": 1282,
"author_profile": "https://Stackoverflow.com/users/1282",
"pm_score": 2,
"selected": false,
"text": "<p>Essentially, yes. In C#, string (actually System.String) is a reference type, so when foo() is called, it receives a pointer to the string in the heap.</p>\n"
},
{
"answer_id": 64713,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 5,
"selected": true,
"text": "<p>In this specific instance, it is more like:</p>\n\n<pre><code>void foo(const char *);\n</code></pre>\n\n<p>.Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes.</p>\n"
},
{
"answer_id": 64717,
"author": "CiNN",
"author_id": 2566,
"author_profile": "https://Stackoverflow.com/users/2566",
"pm_score": 1,
"selected": false,
"text": "<p>no in c# string is unicode.\nin c# it is not called a pointer, but a reference.</p>\n"
},
{
"answer_id": 64724,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you mean - will the method be allowed to access the contents of the character space, the answer is yes. </p>\n"
},
{
"answer_id": 64725,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, because a string is of dynamic size, so there must be heap memory behind the scenes</p>\n\n<p>However they are NOT the same.</p>\n\n<p>in c the pointer points to a string that may also be used elsewhere, so changing it will effect those other places.</p>\n"
},
{
"answer_id": 64727,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 2,
"selected": false,
"text": "<p>For value types (int, double, etc.), the function receives a copy of the value. For other objects, it's a reference pointing to the original object.</p>\n\n<p>Strings are special because they are immutable. Technically it means it will pass the reference, but in practice it will behave pretty much like a value type.</p>\n\n<p>You can force value types to pass a reference by using the <code>ref</code> keyword:</p>\n\n<pre><code>public void Foo(ref int value) { value = 12 }\npublic void Bar()\n{\n int val = 3;\n Foo(ref val);\n // val == 12\n}\n</code></pre>\n"
},
{
"answer_id": 64733,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>There are pointers behind the scenes in C#, though they are more like C++'s smart pointers, so the raw pointers are encapsulated. A char* isn't really the same as System.String since a pointer to a char usually means the start of a character array, and a C# string is an object with a length field <em>and</em> a character array. The pointer points to the outer structure which points into something like a <strong>wchar_t</strong> array, so there's some indirection with a C# string and wider characters for Unicode support.</p>\n"
},
{
"answer_id": 64755,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 3,
"selected": false,
"text": "<p>No. In C# (and all other .NET languages) the String is a first-class data type. It is not simply an array of characters. You can convert back and forth between them, but they do not behave the same. There are a number of string manipulation methods (like \"Substring()\" and \"StartsWith\") that are available to the String class, which don't apply to arrays in general, which an array of characters is simply an instance of.</p>\n"
},
{
"answer_id": 64809,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, all classes in C# (not sure about the others) are reference types.</p>\n"
},
{
"answer_id": 64924,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 1,
"selected": false,
"text": "<p>Anything that is not a \"value type\", which essentially covers enums, booleans, and built-in numeric types, will be passed \"by reference\", which is arguably the same as the C/C++ mechanism of passing by reference or pointer. Syntactically and semantically it is essentially identical to C/C++ passing by reference.</p>\n\n<p>Note, however, that in C# strings are immutable, so even though it is passed by reference you can't edit the string without creating a new one.</p>\n\n<p>Also note that you can't pass an argument as \"const\" in C#, regardless whether it is a value type or a reference type.</p>\n"
},
{
"answer_id": 65099,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 1,
"selected": false,
"text": "<p>While those are indeed equivalent in a semantic sense (i.e. the code is doing something with a string), C#, like Java, keeps pointers completely out of its everyday use, relegating them to areas such as transitions to native OS functions - even then, there are framework classes which wrap those up nicely, such as SafeFileHandle.</p>\n\n<p>Long story short, don't go out of your way thinking of pointers in C#.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
| Is this function declaration in C#:
```
void foo(string mystring)
```
the same as this one in C:
```
void foo(char *)
```
i.e. In C#, does the called function receive a pointer behind the scenes? | In this specific instance, it is more like:
```
void foo(const char *);
```
.Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes. |
64,693 | <p>Theres is a little problem I want to solve with Haskell:
let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:</p>
<pre><code>subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
-- "6.2^3 + 6.2 + sin(6.2)"
</code></pre>
| [
{
"answer_id": 65479,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 4,
"selected": true,
"text": "<p>You could use the <a href=\"http://hackage.haskell.org/package/regex-compat-0.95.1\" rel=\"nofollow noreferrer\">Text.Regex</a> package.</p>\n\n<p>Your example might look something like this:</p>\n\n<pre><code>import Text.Regex(mkRegex, subRegex)\n\nsubs :: String -> String -> String -> String\nsubs wildcard input value = subRegex (mkRegex wildcard) input value\n</code></pre>\n"
},
{
"answer_id": 65501,
"author": "jrudolph",
"author_id": 7647,
"author_profile": "https://Stackoverflow.com/users/7647",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"http://bluebones.net/2007/01/replace-in-haskell/\" rel=\"nofollow noreferrer\">http://bluebones.net/2007/01/replace-in-haskell/</a> for an example which looks exactly as the piece of code you are looking for.</p>\n"
},
{
"answer_id": 65520,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 1,
"selected": false,
"text": "<p>Use regular expressions (<code>Text.Regex.Posix</code>) and search-replace for <code>/\\Wx\\W/</code> (Perl notation). Simply replacing <code>x</code> to <code>6.2</code> will bring you trouble with <code>x + quux</code>.</p>\n\n<p><a href=\"http://lukeplant.me.uk/blog.php?id=1107301690\" rel=\"nofollow noreferrer\">Haskell Regex Replace</a> for more information (I think this should be imported to SO.</p>\n\n<p>For extra hard-core you could parse your expression as AST and do the replacement on that level. </p>\n"
},
{
"answer_id": 7175000,
"author": "Dmitry Bespalov",
"author_id": 905914,
"author_profile": "https://Stackoverflow.com/users/905914",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <strong>text-format-simple</strong> library for such cases:</p>\n\n<pre><code>import Text.Format\nformat \"{0}^3 + {0} + sin({0})\" [\"6.2\"]\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6766/"
]
| Theres is a little problem I want to solve with Haskell:
let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:
```
subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
-- "6.2^3 + 6.2 + sin(6.2)"
``` | You could use the [Text.Regex](http://hackage.haskell.org/package/regex-compat-0.95.1) package.
Your example might look something like this:
```
import Text.Regex(mkRegex, subRegex)
subs :: String -> String -> String -> String
subs wildcard input value = subRegex (mkRegex wildcard) input value
``` |
64,759 | <p>I have a pdf file of a logo, about 1"x2" in dimension. Can anybody provide the code snippet to import that PDF logo into another PDF file using the <a href="http://framework.zend.com/manual/en/zend.pdf.html" rel="nofollow noreferrer">Zend_PDF</a> API's? </p>
<p>Ideally, I'd like to be able to place it like the PNG, TIFF or JPG objects with the Zend_Pdf_Image object. </p>
<p>In other words, I want to be able to place the little 1x2" pdf document on top of a 8.5x11" page, not use the original pdf as a background. </p>
<p>Thanks!</p>
| [
{
"answer_id": 66011,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you can <a href=\"http://framework.zend.com/manual/en/zend.pdf.pages.html#zend.pdf.pages.cloning\" rel=\"nofollow noreferrer\">clone a page</a> --like a template. Not sure if this is enough for you, it does look like the preferred way to do things. Of course, if you have a pdf that you want to add a, say, watermark, to, uhh, this is clearly insufficient --but in this case a hi-res png would probably suffice.</p>\n"
},
{
"answer_id": 75021,
"author": "user6824",
"author_id": 6824,
"author_profile": "https://Stackoverflow.com/users/6824",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like as of this date, there's no way to do it using the Zend_PDF API's. The Zend_Pdf_Page class has a drawContentStream() which looked promising, but when I checked into it, the method body was empty. Maybe a later release of the API will support it. </p>\n\n<p>So, if you want place another PDF inside another dynamically generated PDF document like an image, use <a href=\"http://www.setasign.de/products/pdf-php-solutions/fpdi/demos/simple-demo/\" rel=\"nofollow noreferrer\">FPDI + FPDF/TCPDF</a>.</p>\n\n<pre><code>$pdf = & new FPDI ('P', 'in', 'Letter' );\n$pagecount = $pdf->setSourceFile ( APP . 'logo.pdf' );\n$tplidx = $pdf->importPage ( 1, '/MediaBox' );\n\n$pdf->addPage ();\n$pdf->useTemplate ( $tplidx, 1, 1 );\n$pdf->Output ( 'output.pdf', 'F' );\n</code></pre>\n"
},
{
"answer_id": 198422,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 0,
"selected": false,
"text": "<p>Not what you asked for, but probably what you need (:</p>\n\n<p>Convert the smaller logo pdf to a TIFF/PNG/WhatEver (using, for example, imagemagick's <code>convert</code>, or the GIMP). Then, place this image with the normal Zend API.</p>\n\n<p>This conversion could also be done on the fly, using the Imagick php class, I would imagine.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6824/"
]
| I have a pdf file of a logo, about 1"x2" in dimension. Can anybody provide the code snippet to import that PDF logo into another PDF file using the [Zend\_PDF](http://framework.zend.com/manual/en/zend.pdf.html) API's?
Ideally, I'd like to be able to place it like the PNG, TIFF or JPG objects with the Zend\_Pdf\_Image object.
In other words, I want to be able to place the little 1x2" pdf document on top of a 8.5x11" page, not use the original pdf as a background.
Thanks! | It looks like as of this date, there's no way to do it using the Zend\_PDF API's. The Zend\_Pdf\_Page class has a drawContentStream() which looked promising, but when I checked into it, the method body was empty. Maybe a later release of the API will support it.
So, if you want place another PDF inside another dynamically generated PDF document like an image, use [FPDI + FPDF/TCPDF](http://www.setasign.de/products/pdf-php-solutions/fpdi/demos/simple-demo/).
```
$pdf = & new FPDI ('P', 'in', 'Letter' );
$pagecount = $pdf->setSourceFile ( APP . 'logo.pdf' );
$tplidx = $pdf->importPage ( 1, '/MediaBox' );
$pdf->addPage ();
$pdf->useTemplate ( $tplidx, 1, 1 );
$pdf->Output ( 'output.pdf', 'F' );
``` |
64,781 | <p>I have a web application that receives messages through an HTTP interface, e.g.:</p>
<pre><code>http://server/application?source=123&destination=234&text=hello
</code></pre>
<p>This request contains the ID of the sender, the ID of the recipient and the text of the message.</p>
<p>This message should be processed like:</p>
<ul>
<li>finding the matching User object for both the source and the destination from the database</li>
<li>creating a tree of objects: a Message that contains a field for the message text and two User objects for the source and the destination</li>
<li>persisting this tree to a database.</li>
</ul>
<p>The tree will be loaded by other applications that I can't touch.</p>
<p>I use Oracle as the backing database and JPA with Toplink for the database handling tasks. If possible, I'd stay with these.</p>
<p>Without much optimization I can achieve ~30 requests/sec throughput in my environment. That's not much, I'd require ~300 requests/sec. So I measured where the performance bottleneck is and found that the calls to <code>em.persist()</code> takes most of the time. If I simply comment out that line, the throughput go well over 1000 requests/sec.</p>
<p>I tried to write a small test application that used simple JDBC calls to persist 1 million messages to the same database. I used batching, meaning I did 100 inserts then a commit, and repeated until all the records was in the database. I measured ~500 requests/sec throughput in this scenario, that would meet my needs.</p>
<p>It is clear that I need to optimize insert performance here. However as I mentioned earlier I would like to keep using JPA and Toplink for this, not pure JDBC.</p>
<p>Do you know a way to create batch inserts with JPA and Toplink? Can you recommend any other technique for improving JPA persist performance?</p>
<p><strong>ADDITIONAL INFO:</strong></p>
<p>"requests/sec" means here: total number of requests / total time from beginning of test to last record written to database.</p>
<p>I tried to make the calls to <code>em.persist()</code> asynchronous by creating an in-memory queue between the servlet stuff and the persister. It helped the performance greatly. However the queue did grow really fast and as the application will receive ~200 requests/second continuously, It is not an acceptable solution for me.</p>
<p>In this decoupled approach I collected requests for 100 msec and called <code>em.persist()</code> on all collected items before commiting the transaction. The EntityManagerFactory is cached between each transaction.</p>
| [
{
"answer_id": 65828,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 0,
"selected": false,
"text": "<p>What is your measure of \"requests/sec\"? In other words, what happens for the 31st request? What resource is being blocked? If it is the front-end/servlet/web portion, can you run em.persist() in another thread and return immediately?</p>\n\n<p>Also, are you creating transactions each time? Are you creating EntityManagerFactory objects with each request?</p>\n"
},
{
"answer_id": 66373,
"author": "Christian",
"author_id": 9817,
"author_profile": "https://Stackoverflow.com/users/9817",
"pm_score": 3,
"selected": true,
"text": "<p>You should decouple from the JPA interface and use the bare TopLink API. You can probably chuck the objects you're persisting into a UnitOfWork and commit the UnitOfWork on your schedule (sync or async). Note that one of the costs of em.persist() is the implicit clone that happens of the whole object graph. TopLink will work rather better if you uow.registerObject() your two user objects yourself, saving itself the identity tests it has to otherwise do. So you'll end up with:</p>\n\n<pre><code>uow=sess.acquireUnitOfWork();\nfor (job in batch) {\n thingyCl=uow.registerObject(new Thingy());\n user1Cl=uow.registerObject(user1);\n user2Cl=uow.registerObject(user2);\n thingyCl.setUsers(user1Cl,user2Cl);\n}\nuow.commit();\n</code></pre>\n\n<p>This is very old school TopLink btw ;)</p>\n\n<p>Note that the batch will help a lot, because batch writing and more especially batch writing with parameter binding will kick in which for this simple example will probably have a very large impact on your performance.</p>\n\n<p>Other things to look for: your sequencing size. A lot of the time spent writing objects in TopLink is actually spent reading sequencing information from the database, especially with the small defaults (I would probably have several hundred or even more as my sequence size).</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
]
| I have a web application that receives messages through an HTTP interface, e.g.:
```
http://server/application?source=123&destination=234&text=hello
```
This request contains the ID of the sender, the ID of the recipient and the text of the message.
This message should be processed like:
* finding the matching User object for both the source and the destination from the database
* creating a tree of objects: a Message that contains a field for the message text and two User objects for the source and the destination
* persisting this tree to a database.
The tree will be loaded by other applications that I can't touch.
I use Oracle as the backing database and JPA with Toplink for the database handling tasks. If possible, I'd stay with these.
Without much optimization I can achieve ~30 requests/sec throughput in my environment. That's not much, I'd require ~300 requests/sec. So I measured where the performance bottleneck is and found that the calls to `em.persist()` takes most of the time. If I simply comment out that line, the throughput go well over 1000 requests/sec.
I tried to write a small test application that used simple JDBC calls to persist 1 million messages to the same database. I used batching, meaning I did 100 inserts then a commit, and repeated until all the records was in the database. I measured ~500 requests/sec throughput in this scenario, that would meet my needs.
It is clear that I need to optimize insert performance here. However as I mentioned earlier I would like to keep using JPA and Toplink for this, not pure JDBC.
Do you know a way to create batch inserts with JPA and Toplink? Can you recommend any other technique for improving JPA persist performance?
**ADDITIONAL INFO:**
"requests/sec" means here: total number of requests / total time from beginning of test to last record written to database.
I tried to make the calls to `em.persist()` asynchronous by creating an in-memory queue between the servlet stuff and the persister. It helped the performance greatly. However the queue did grow really fast and as the application will receive ~200 requests/second continuously, It is not an acceptable solution for me.
In this decoupled approach I collected requests for 100 msec and called `em.persist()` on all collected items before commiting the transaction. The EntityManagerFactory is cached between each transaction. | You should decouple from the JPA interface and use the bare TopLink API. You can probably chuck the objects you're persisting into a UnitOfWork and commit the UnitOfWork on your schedule (sync or async). Note that one of the costs of em.persist() is the implicit clone that happens of the whole object graph. TopLink will work rather better if you uow.registerObject() your two user objects yourself, saving itself the identity tests it has to otherwise do. So you'll end up with:
```
uow=sess.acquireUnitOfWork();
for (job in batch) {
thingyCl=uow.registerObject(new Thingy());
user1Cl=uow.registerObject(user1);
user2Cl=uow.registerObject(user2);
thingyCl.setUsers(user1Cl,user2Cl);
}
uow.commit();
```
This is very old school TopLink btw ;)
Note that the batch will help a lot, because batch writing and more especially batch writing with parameter binding will kick in which for this simple example will probably have a very large impact on your performance.
Other things to look for: your sequencing size. A lot of the time spent writing objects in TopLink is actually spent reading sequencing information from the database, especially with the small defaults (I would probably have several hundred or even more as my sequence size). |
64,782 | <pre><code>int i = 4;
string text = "Player ";
cout << (text + i);
</code></pre>
<p>I'd like it to print <code>Player 4</code>.</p>
<p>The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?</p>
| [
{
"answer_id": 64794,
"author": "rupello",
"author_id": 635,
"author_profile": "https://Stackoverflow.com/users/635",
"pm_score": 0,
"selected": false,
"text": "<pre><code>cout << \"Player\" << i ;\n</code></pre>\n"
},
{
"answer_id": 64795,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>cout << text << i;\n</code></pre>\n"
},
{
"answer_id": 64796,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 3,
"selected": false,
"text": "<pre><code>cout << text << \" \" << i << endl;\n</code></pre>\n"
},
{
"answer_id": 64797,
"author": "introp",
"author_id": 8398,
"author_profile": "https://Stackoverflow.com/users/8398",
"pm_score": 0,
"selected": false,
"text": "<pre><code>cout << text << i;\n</code></pre>\n\n<p>The <code><<</code> operator for ostream returns a reference to the ostream, so you can just keep chaining the <code><<</code> operations. That is, the above is basically the same as:</p>\n\n<pre><code>cout << text;\ncout << i;\n</code></pre>\n"
},
{
"answer_id": 64804,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<pre><code>cout << text << \" \" << i << endl;\n</code></pre>\n"
},
{
"answer_id": 64805,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>For the record, you can also use a <a href=\"http://www.cplusplus.com/reference/iostream/stringstream/stringstream.html\" rel=\"nofollow noreferrer\"><code>std::stringstream</code></a> if you want to create the string before it's actually output.</p>\n"
},
{
"answer_id": 64811,
"author": "Fire Lancer",
"author_id": 6266,
"author_profile": "https://Stackoverflow.com/users/6266",
"pm_score": 4,
"selected": false,
"text": "<p>These work for general strings (in case you do not want to output to file/console, but store for later use or something).</p>\n\n<p>boost.lexical_cast</p>\n\n<pre><code>MyStr += boost::lexical_cast<std::string>(MyInt);\n</code></pre>\n\n<p>String streams</p>\n\n<pre><code>//sstream.h\nstd::stringstream Stream;\nStream.str(MyStr);\nStream << MyInt;\nMyStr = Stream.str();\n\n// If you're using a stream (for example, cout), rather than std::string\nsomeStream << MyInt;\n</code></pre>\n"
},
{
"answer_id": 64815,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 7,
"selected": false,
"text": "<pre><code>printf(\"Player %d\", i);\n</code></pre>\n\n<p>(Downvote my answer all you like; I still hate the C++ I/O operators.)</p>\n\n<p>:-P</p>\n"
},
{
"answer_id": 64817,
"author": "Sebastian Redl",
"author_id": 8922,
"author_profile": "https://Stackoverflow.com/users/8922",
"pm_score": 8,
"selected": false,
"text": "<p>Well, if you use cout you can just write the integer directly to it, as in</p>\n\n<pre><code>std::cout << text << i;\n</code></pre>\n\n<p>The C++ way of converting all kinds of objects to strings is through <a href=\"http://en.cppreference.com/w/cpp/io/basic_stringstream\" rel=\"noreferrer\">string streams</a>. If you don't have one handy, just create one.</p>\n\n<pre><code>#include <sstream>\n\nstd::ostringstream oss;\noss << text << i;\nstd::cout << oss.str();\n</code></pre>\n\n<p>Alternatively, you can just convert the integer and append it to the string.</p>\n\n<pre><code>oss << i;\ntext += oss.str();\n</code></pre>\n\n<p>Finally, the Boost libraries provide <a href=\"http://www.boost.org/doc/libs/release/doc/html/boost_lexical_cast.html\" rel=\"noreferrer\"><code>boost::lexical_cast</code></a>, which wraps around the stringstream conversion with a syntax like the built-in type casts.</p>\n\n<pre><code>#include <boost/lexical_cast.hpp>\n\ntext += boost::lexical_cast<std::string>(i);\n</code></pre>\n\n<p>This also works the other way around, i.e. to parse strings.</p>\n"
},
{
"answer_id": 65309,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>There are a few options, and which one you want depends on the context.</p>\n\n<p>The simplest way is</p>\n\n<pre><code>std::cout << text << i;\n</code></pre>\n\n<p>or if you want this on a single line</p>\n\n<pre><code>std::cout << text << i << endl;\n</code></pre>\n\n<p>If you are writing a single threaded program and if you aren't calling this code a lot (where \"a lot\" is thousands of times per second) then you are done.</p>\n\n<p>If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write \"Player 1\" and another is writing \"Player 2\". If you are lucky you will get the following:</p>\n\n<pre><code>Player 1\nPlayer 2\n</code></pre>\n\n<p>If you are unlucky you might get something like the following</p>\n\n<pre><code>Player Player 2\n1\n</code></pre>\n\n<p>The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:</p>\n\n<pre><code>std::cout << text;\nstd::cout << i;\nstd::cout << endl;\n</code></pre>\n\n<p>If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:</p>\n\n<pre><code>printf(\"Player %d\\n\", i);\n</code></pre>\n\n<p>Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.</p>\n\n<p>For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.</p>\n"
},
{
"answer_id": 941229,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 2,
"selected": false,
"text": "<p>Another possibility is <a href=\"http://www.boost.org/doc/libs/release/libs/format/doc/format.html\" rel=\"nofollow noreferrer\">Boost.Format</a>:</p>\n\n<pre><code>#include <boost/format.hpp>\n#include <iostream>\n#include <string>\n\nint main() {\n int i = 4;\n std::string text = \"Player\";\n std::cout << boost::format(\"%1% %2%\\n\") % text % i;\n}\n</code></pre>\n"
},
{
"answer_id": 6455164,
"author": "Brian Lenoski",
"author_id": 577587,
"author_profile": "https://Stackoverflow.com/users/577587",
"pm_score": 2,
"selected": false,
"text": "<p>For the record, you could also use Qt's <code>QString</code> class:</p>\n\n<pre><code>#include <QtCore/QString>\n\nint i = 4;\nQString qs = QString(\"Player %1\").arg(i);\nstd::cout << qs.toLocal8bit().constData(); // prints \"Player 4\"\n</code></pre>\n"
},
{
"answer_id": 6490852,
"author": "Mr. Y",
"author_id": 817063,
"author_profile": "https://Stackoverflow.com/users/817063",
"pm_score": -1,
"selected": false,
"text": "<p>If using Windows/MFC, and need the string for more than immediate output try:</p>\n\n<pre><code>int i = 4;\nCString strOutput;\nstrOutput.Format(\"Player %d\", i);\n</code></pre>\n"
},
{
"answer_id": 6705708,
"author": "Robert Parcus",
"author_id": 814180,
"author_profile": "https://Stackoverflow.com/users/814180",
"pm_score": 2,
"selected": false,
"text": "<p>Here a small working conversion/appending example, with some code I needed before.</p>\n\n<pre><code>#include <string>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nint main(){\nstring str;\nint i = 321;\nstd::stringstream ss;\nss << 123;\nstr = \"/dev/video\";\ncout << str << endl;\ncout << str << 456 << endl;\ncout << str << i << endl;\nstr += ss.str();\ncout << str << endl;\n}\n</code></pre>\n\n<p>the output will be:</p>\n\n<pre><code>/dev/video\n/dev/video456\n/dev/video321\n/dev/video123\n</code></pre>\n\n<p>Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.</p>\n"
},
{
"answer_id": 15182224,
"author": "user2037225",
"author_id": 2037225,
"author_profile": "https://Stackoverflow.com/users/2037225",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the following</p>\n\n<pre><code>int i = 4;\nstring text = \"Player \";\ntext+=(i+'0');\ncout << (text);\n</code></pre>\n"
},
{
"answer_id": 16600810,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 3,
"selected": false,
"text": "<p>Your example seems to indicate that you would like to display the a string followed by an integer, in which case:</p>\n\n<pre><code>string text = \"Player: \";\nint i = 4;\ncout << text << i << endl;\n</code></pre>\n\n<p>would work fine.</p>\n\n<p>But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:</p>\n\n<pre><code>#include <sstream>\n#include <iostream>\nusing namespace std;\n\nstd::string operator+(std::string const &a, int b) {\n std::ostringstream oss;\n oss << a << b;\n return oss.str();\n}\n\nint main() {\n int i = 4;\n string text = \"Player: \";\n cout << (text + i) << endl;\n}\n</code></pre>\n\n<p>In fact, you can use templates to make this approach more powerful:</p>\n\n<pre><code>template <class T>\nstd::string operator+(std::string const &a, const T &b){\n std::ostringstream oss;\n oss << a << b;\n return oss.str();\n}\n</code></pre>\n\n<p>Now, as long as object <code>b</code> has a defined stream output, you can append it to your string (or, at least, a copy thereof).</p>\n"
},
{
"answer_id": 18997915,
"author": "headmyshoulder",
"author_id": 625476,
"author_profile": "https://Stackoverflow.com/users/625476",
"pm_score": 8,
"selected": false,
"text": "<p>With C++11, you can write:</p>\n\n<pre><code>#include <string> // to use std::string, std::to_string() and \"+\" operator acting on strings \n\nint i = 4;\nstd::string text = \"Player \";\ntext += std::to_string(i);\n</code></pre>\n"
},
{
"answer_id": 32389356,
"author": "Saurabh Mishra",
"author_id": 5299089,
"author_profile": "https://Stackoverflow.com/users/5299089",
"pm_score": 1,
"selected": false,
"text": "<p>One method here is directly printing the output if its required in your problem.</p>\n\n<pre><code>cout << text << i;\n</code></pre>\n\n<p>Else, one of the safest method is to use </p>\n\n<pre><code>sprintf(count, \"%d\", i);\n</code></pre>\n\n<p>And then copy it to your \"text\" string .</p>\n\n<pre><code>for(k = 0; *(count + k); k++)\n{ \n text += count[k]; \n} \n</code></pre>\n\n<p>Thus, you have your required output string </p>\n\n<p>For more info on <code>sprintf</code>, follow:\n<a href=\"http://www.cplusplus.com/reference/cstdio/sprintf\" rel=\"nofollow\">http://www.cplusplus.com/reference/cstdio/sprintf</a></p>\n"
},
{
"answer_id": 33784419,
"author": "Code Black",
"author_id": 5367912,
"author_profile": "https://Stackoverflow.com/users/5367912",
"pm_score": 0,
"selected": false,
"text": "<p><strong>The easiest way I could figure this out is the following..</strong><br>\nIt will work as a <strong>single string</strong> and <strong>string array</strong>.\nI am considering a string array, as it is complicated (little bit same will be followed with string).\nI create a array of names and <strong>append</strong> some integer and char with it to show how easy it is to append some <strong>int</strong> and <strong>chars</strong> to string, hope it helps.\nlength is just to measure the size of array. If you are familiar with programming then <strong>size_t</strong> is a unsigned <strong>int</strong></p>\n\n<pre><code>#include<iostream>\n #include<string>\n using namespace std;\n int main() {\n\n string names[] = { \"amz\",\"Waq\",\"Mon\",\"Sam\",\"Has\",\"Shak\",\"GBy\" }; //simple array\n int length = sizeof(names) / sizeof(names[0]); //give you size of array\n int id;\n string append[7]; //as length is 7 just for sake of storing and printing output \n for (size_t i = 0; i < length; i++) {\n id = rand() % 20000 + 2;\n append[i] = names[i] + to_string(id);\n }\n for (size_t i = 0; i < length; i++) {\n cout << append[i] << endl;\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 37435228,
"author": "Евгений Яковлев",
"author_id": 6380629,
"author_profile": "https://Stackoverflow.com/users/6380629",
"pm_score": -1,
"selected": false,
"text": "<p>You also try concatenate player's number with <code>std::string::push_back</code> :</p>\n\n<p>Example with your code:</p>\n\n<pre><code>int i = 4;\nstring text = \"Player \";\ntext.push_back(i + '0');\ncout << text;\n</code></pre>\n\n<p>You will see in console: </p>\n\n<blockquote>\n <p>Player 4</p>\n</blockquote>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| ```
int i = 4;
string text = "Player ";
cout << (text + i);
```
I'd like it to print `Player 4`.
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes? | Well, if you use cout you can just write the integer directly to it, as in
```
std::cout << text << i;
```
The C++ way of converting all kinds of objects to strings is through [string streams](http://en.cppreference.com/w/cpp/io/basic_stringstream). If you don't have one handy, just create one.
```
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
```
Alternatively, you can just convert the integer and append it to the string.
```
oss << i;
text += oss.str();
```
Finally, the Boost libraries provide [`boost::lexical_cast`](http://www.boost.org/doc/libs/release/doc/html/boost_lexical_cast.html), which wraps around the stringstream conversion with a syntax like the built-in type casts.
```
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
```
This also works the other way around, i.e. to parse strings. |
64,786 | <p>What is your favorite method to handle errors in Bash?
The best example of handling errors I have found on the web was written by William Shotts, Jr at <a href="http://www.linuxcommand.org" rel="noreferrer">http://www.linuxcommand.org</a>. </p>
<p>He suggests using the following function for error handling in Bash:</p>
<pre><code>#!/bin/bash
# A slicker error handling routine
# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run. You can get this
# value from the first item on the command line ($0).
# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>
PROGNAME=$(basename $0)
function error_exit
{
# ----------------------------------------------------------------
# Function for exit due to fatal program error
# Accepts 1 argument:
# string containing descriptive error message
# ----------------------------------------------------------------
echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
exit 1
}
# Example call of the error_exit function. Note the inclusion
# of the LINENO environment variable. It contains the current
# line number.
echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."
</code></pre>
<p>Do you have a better error handling routine that you use in Bash scripts?</p>
| [
{
"answer_id": 64880,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 2,
"selected": false,
"text": "<p>I've used</p>\n\n<pre><code>die() {\n echo $1\n kill $$\n}\n</code></pre>\n\n<p>before; i think because 'exit' was failing for me for some reason. The above defaults seem like a good idea, though.</p>\n"
},
{
"answer_id": 69808,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 7,
"selected": false,
"text": "<p>That's a fine solution. I just wanted to add</p>\n\n<pre><code>set -e\n</code></pre>\n\n<p>as a rudimentary error mechanism. It will immediately stop your script if a simple command fails. I think this should have been the default behavior: since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.</p>\n"
},
{
"answer_id": 182080,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 3,
"selected": false,
"text": "<p>Another consideration is the exit code to return. Just \"<code>1</code>\" is pretty standard, although there are a handful of <a href=\"http://tldp.org/LDP/abs/html/exitcodes.html\" rel=\"noreferrer\">reserved exit codes that bash itself uses</a>, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards.</p>\n\n<p>You might also consider the bit vector approach that <code>mount</code> uses for its exit codes:</p>\n\n<pre><code> 0 success\n 1 incorrect invocation or permissions\n 2 system error (out of memory, cannot fork, no more loop devices)\n 4 internal mount bug or missing nfs support in mount\n 8 user interrupt\n16 problems writing or locking /etc/mtab\n32 mount failure\n64 some mount succeeded\n</code></pre>\n\n<p><code>OR</code>-ing the codes together allows your script to signal multiple simultaneous errors.</p>\n"
},
{
"answer_id": 185900,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 8,
"selected": false,
"text": "<p>Use a trap!</p>\n<pre><code>tempfiles=( )\ncleanup() {\n rm -f "${tempfiles[@]}"\n}\ntrap cleanup 0\n\nerror() {\n local parent_lineno="$1"\n local message="$2"\n local code="${3:-1}"\n if [[ -n "$message" ]] ; then\n echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"\n else\n echo "Error on or near line ${parent_lineno}; exiting with status ${code}"\n fi\n exit "${code}"\n}\ntrap 'error ${LINENO}' ERR\n</code></pre>\n<p>...then, whenever you create a temporary file:</p>\n<pre><code>temp_foo="$(mktemp -t foobar.XXXXXX)"\ntempfiles+=( "$temp_foo" )\n</code></pre>\n<p>and <code>$temp_foo</code> will be deleted on exit, and the current line number will be printed. (<code>set -e</code> will likewise give you exit-on-error behavior, <A HREF=\"http://mywiki.wooledge.org/BashFAQ/105\" rel=\"nofollow noreferrer\">though it comes with serious caveats</A> and weakens code's predictability and portability).</p>\n<p>You can either let the trap call <code>error</code> for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:</p>\n<pre><code>error ${LINENO} "the foobar failed" 2\n</code></pre>\n<p>will exit with status 2, and give an explicit message.</p>\n<p>Alternatively <code>shopt -s extdebug</code> and give the first lines of the trap a little modification to trap all non-zero exit codes across the board (mind <code>set -e</code> non-error non-zero exit codes):</p>\n<pre><code>error() {\n local last_exit_status="$?"\n local parent_lineno="$1"\n local message="${2:-(no message ($last_exit_status))}"\n local code="${3:-$last_exit_status}"\n # ... continue as above\n}\ntrap 'error ${LINENO}' ERR\nshopt -s extdebug\n</code></pre>\n<p>This then is also "compatible" with <code>set -eu</code>.</p>\n"
},
{
"answer_id": 1771722,
"author": "Michael Nooner",
"author_id": 215602,
"author_profile": "https://Stackoverflow.com/users/215602",
"pm_score": 4,
"selected": false,
"text": "<p>I prefer something really easy to call. So I use something that looks a little complicated, but is easy to use. I usually just copy-and-paste the code below into my scripts. An explanation follows the code.</p>\n\n<pre><code>#This function is used to cleanly exit any script. It does this displaying a\n# given error message, and exiting with an error code.\nfunction error_exit {\n echo\n echo \"$@\"\n exit 1\n}\n#Trap the killer signals so that we can exit with a good message.\ntrap \"error_exit 'Received signal SIGHUP'\" SIGHUP\ntrap \"error_exit 'Received signal SIGINT'\" SIGINT\ntrap \"error_exit 'Received signal SIGTERM'\" SIGTERM\n\n#Alias the function so that it will print a message with the following format:\n#prog-name(@line#): message\n#We have to explicitly allow aliases, we do this because they make calling the\n#function much easier (see example).\nshopt -s expand_aliases\nalias die='error_exit \"Error ${0}(@`echo $(( $LINENO - 1 ))`):\"'\n</code></pre>\n\n<p>I usually put a call to the cleanup function in side the error_exit function, but this varies from script to script so I left it out. The traps catch the common terminating signals and make sure everything gets cleaned up. The alias is what does the real magic. I like to check everything for failure. So in general I call programs in an \"if !\" type statement. By subtracting 1 from the line number the alias will tell me where the failure occurred. It is also dead simple to call, and pretty much idiot proof. Below is an example (just replace /bin/false with whatever you are going to call).</p>\n\n<pre><code>#This is an example useage, it will print out\n#Error prog-name (@1): Who knew false is false.\nif ! /bin/false ; then\n die \"Who knew false is false.\"\nfi\n</code></pre>\n"
},
{
"answer_id": 1877000,
"author": "Ben Scholbrock",
"author_id": 228321,
"author_profile": "https://Stackoverflow.com/users/228321",
"pm_score": 5,
"selected": false,
"text": "<p>An equivalent alternative to \"set -e\" is</p>\n\n<pre><code>set -o errexit\n</code></pre>\n\n<p>It makes the meaning of the flag somewhat clearer than just \"-e\".</p>\n\n<p>Random addition: to temporarily disable the flag, and return to the default (of continuing execution regardless of exit codes), just use</p>\n\n<pre><code>set +e\necho \"commands run here returning non-zero exit codes will not cause the entire script to fail\"\necho \"false returns 1 as an exit code\"\nfalse\nset -e\n</code></pre>\n\n<p>This precludes proper error handling mentioned in other responses, but is quick & effective (just like bash).</p>\n"
},
{
"answer_id": 6290175,
"author": "l0b0",
"author_id": 96588,
"author_profile": "https://Stackoverflow.com/users/96588",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://github.com/l0b0/tilde/blob/master/scripts/functions.sh\" rel=\"nofollow\">This</a> has served me well for a while now. It prints error or warning messages in red, one line per parameter, and allows an optional exit code.</p>\n\n<pre><code># Custom errors\nEX_UNKNOWN=1\n\nwarning()\n{\n # Output warning messages\n # Color the output red if it's an interactive terminal\n # @param $1...: Messages\n\n test -t 1 && tput setf 4\n\n printf '%s\\n' \"$@\" >&2\n\n test -t 1 && tput sgr0 # Reset terminal\n true\n}\n\nerror()\n{\n # Output error messages with optional exit code\n # @param $1...: Messages\n # @param $N: Exit code (optional)\n\n messages=( \"$@\" )\n\n # If the last parameter is a number, it's not part of the messages\n last_parameter=\"${messages[@]: -1}\"\n if [[ \"$last_parameter\" =~ ^[0-9]*$ ]]\n then\n exit_code=$last_parameter\n unset messages[$((${#messages[@]} - 1))]\n fi\n\n warning \"${messages[@]}\"\n\n exit ${exit_code:-$EX_UNKNOWN}\n}\n</code></pre>\n"
},
{
"answer_id": 11564455,
"author": "Olivier Delrieu",
"author_id": 769749,
"author_profile": "https://Stackoverflow.com/users/769749",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following trap code, it also allows <strong>errors to be traced through pipes and 'time' commands</strong></p>\n\n<pre><code>#!/bin/bash\nset -o pipefail # trace ERR through pipes\nset -o errtrace # trace ERR through 'time command' and other functions\nfunction error() {\n JOB=\"$0\" # job name\n LASTLINE=\"$1\" # line of error occurrence\n LASTERR=\"$2\" # error code\n echo \"ERROR in ${JOB} : line ${LASTLINE} with exit code ${LASTERR}\"\n exit 1\n}\ntrap 'error ${LINENO} ${?}' ERR\n</code></pre>\n"
},
{
"answer_id": 12414661,
"author": "Nelson Rodriguez",
"author_id": 1037940,
"author_profile": "https://Stackoverflow.com/users/1037940",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this will be helpful to you, but I modified some of the suggested functions here in order to include the check for the error (exit code from prior command) within it.\nOn each \"check\" I also pass as a parameter the \"message\" of what the error is for logging purposes.</p>\n\n<pre><code>#!/bin/bash\n\nerror_exit()\n{\n if [ \"$?\" != \"0\" ]; then\n log.sh \"$1\"\n exit 1\n fi\n}\n</code></pre>\n\n<p>Now to call it within the same script (or in another one if I use <code>export -f error_exit</code>) I simply write the name of the function and pass a message as parameter, like this:</p>\n\n<pre><code>#!/bin/bash\n\ncd /home/myuser/afolder\nerror_exit \"Unable to switch to folder\"\n\nrm *\nerror_exit \"Unable to delete all files\"\n</code></pre>\n\n<p>Using this I was able to create a really robust bash file for some automated process and it will stop in case of errors and notify me (<code>log.sh</code> will do that)</p>\n"
},
{
"answer_id": 13099228,
"author": "Luca Borrione",
"author_id": 1032370,
"author_profile": "https://Stackoverflow.com/users/1032370",
"pm_score": 7,
"selected": false,
"text": "<p>Reading all the answers on this page inspired me a lot.<br>\n<br>\nSo, here's my hint:<br>\n<br>\n<strong><em>file content: lib.trap.sh</em></strong></p>\n\n<pre><code>lib_name='trap'\nlib_version=20121026\n\nstderr_log=\"/dev/shm/stderr.log\"\n\n#\n# TO BE SOURCED ONLY ONCE:\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nif test \"${g_libs[$lib_name]+_}\"; then\n return 0\nelse\n if test ${#g_libs[@]} == 0; then\n declare -A g_libs\n fi\n g_libs[$lib_name]=$lib_version\nfi\n\n\n#\n# MAIN CODE:\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nset -o pipefail # trace ERR through pipes\nset -o errtrace # trace ERR through 'time command' and other functions\nset -o nounset ## set -u : exit the script if you try to use an uninitialised variable\nset -o errexit ## set -e : exit the script if any statement returns a non-true return value\n\nexec 2>\"$stderr_log\"\n\n\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n#\n# FUNCTION: EXIT_HANDLER\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nfunction exit_handler ()\n{\n local error_code=\"$?\"\n\n test $error_code == 0 && return;\n\n #\n # LOCAL VARIABLES:\n # ------------------------------------------------------------------\n # \n local i=0\n local regex=''\n local mem=''\n\n local error_file=''\n local error_lineno=''\n local error_message='unknown'\n\n local lineno=''\n\n\n #\n # PRINT THE HEADER:\n # ------------------------------------------------------------------\n #\n # Color the output if it's an interactive terminal\n test -t 1 && tput bold; tput setf 4 ## red bold\n echo -e \"\\n(!) EXIT HANDLER:\\n\"\n\n\n #\n # GETTING LAST ERROR OCCURRED:\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n #\n # Read last file from the error log\n # ------------------------------------------------------------------\n #\n if test -f \"$stderr_log\"\n then\n stderr=$( tail -n 1 \"$stderr_log\" )\n rm \"$stderr_log\"\n fi\n\n #\n # Managing the line to extract information:\n # ------------------------------------------------------------------\n #\n\n if test -n \"$stderr\"\n then \n # Exploding stderr on :\n mem=\"$IFS\"\n local shrunk_stderr=$( echo \"$stderr\" | sed 's/\\: /\\:/g' )\n IFS=':'\n local stderr_parts=( $shrunk_stderr )\n IFS=\"$mem\"\n\n # Storing information on the error\n error_file=\"${stderr_parts[0]}\"\n error_lineno=\"${stderr_parts[1]}\"\n error_message=\"\"\n\n for (( i = 3; i <= ${#stderr_parts[@]}; i++ ))\n do\n error_message=\"$error_message \"${stderr_parts[$i-1]}\": \"\n done\n\n # Removing last ':' (colon character)\n error_message=\"${error_message%:*}\"\n\n # Trim\n error_message=\"$( echo \"$error_message\" | sed -e 's/^[ \\t]*//' | sed -e 's/[ \\t]*$//' )\"\n fi\n\n #\n # GETTING BACKTRACE:\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n _backtrace=$( backtrace 2 )\n\n\n #\n # MANAGING THE OUTPUT:\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n local lineno=\"\"\n regex='^([a-z]{1,}) ([0-9]{1,})$'\n\n if [[ $error_lineno =~ $regex ]]\n\n # The error line was found on the log\n # (e.g. type 'ff' without quotes wherever)\n # --------------------------------------------------------------\n then\n local row=\"${BASH_REMATCH[1]}\"\n lineno=\"${BASH_REMATCH[2]}\"\n\n echo -e \"FILE:\\t\\t${error_file}\"\n echo -e \"${row^^}:\\t\\t${lineno}\\n\"\n\n echo -e \"ERROR CODE:\\t${error_code}\" \n test -t 1 && tput setf 6 ## white yellow\n echo -e \"ERROR MESSAGE:\\n$error_message\"\n\n\n else\n regex=\"^${error_file}\\$|^${error_file}\\s+|\\s+${error_file}\\s+|\\s+${error_file}\\$\"\n if [[ \"$_backtrace\" =~ $regex ]]\n\n # The file was found on the log but not the error line\n # (could not reproduce this case so far)\n # ------------------------------------------------------\n then\n echo -e \"FILE:\\t\\t$error_file\"\n echo -e \"ROW:\\t\\tunknown\\n\"\n\n echo -e \"ERROR CODE:\\t${error_code}\"\n test -t 1 && tput setf 6 ## white yellow\n echo -e \"ERROR MESSAGE:\\n${stderr}\"\n\n # Neither the error line nor the error file was found on the log\n # (e.g. type 'cp ffd fdf' without quotes wherever)\n # ------------------------------------------------------\n else\n #\n # The error file is the first on backtrace list:\n\n # Exploding backtrace on newlines\n mem=$IFS\n IFS='\n '\n #\n # Substring: I keep only the carriage return\n # (others needed only for tabbing purpose)\n IFS=${IFS:0:1}\n local lines=( $_backtrace )\n\n IFS=$mem\n\n error_file=\"\"\n\n if test -n \"${lines[1]}\"\n then\n array=( ${lines[1]} )\n\n for (( i=2; i<${#array[@]}; i++ ))\n do\n error_file=\"$error_file ${array[$i]}\"\n done\n\n # Trim\n error_file=\"$( echo \"$error_file\" | sed -e 's/^[ \\t]*//' | sed -e 's/[ \\t]*$//' )\"\n fi\n\n echo -e \"FILE:\\t\\t$error_file\"\n echo -e \"ROW:\\t\\tunknown\\n\"\n\n echo -e \"ERROR CODE:\\t${error_code}\"\n test -t 1 && tput setf 6 ## white yellow\n if test -n \"${stderr}\"\n then\n echo -e \"ERROR MESSAGE:\\n${stderr}\"\n else\n echo -e \"ERROR MESSAGE:\\n${error_message}\"\n fi\n fi\n fi\n\n #\n # PRINTING THE BACKTRACE:\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n test -t 1 && tput setf 7 ## white bold\n echo -e \"\\n$_backtrace\\n\"\n\n #\n # EXITING:\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #\n\n test -t 1 && tput setf 4 ## red bold\n echo \"Exiting!\"\n\n test -t 1 && tput sgr0 # Reset terminal\n\n exit \"$error_code\"\n}\ntrap exit_handler EXIT # ! ! ! TRAP EXIT ! ! !\ntrap exit ERR # ! ! ! TRAP ERR ! ! !\n\n\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n#\n# FUNCTION: BACKTRACE\n#\n###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##\n\nfunction backtrace\n{\n local _start_from_=0\n\n local params=( \"$@\" )\n if (( \"${#params[@]}\" >= \"1\" ))\n then\n _start_from_=\"$1\"\n fi\n\n local i=0\n local first=false\n while caller $i > /dev/null\n do\n if test -n \"$_start_from_\" && (( \"$i\" + 1 >= \"$_start_from_\" ))\n then\n if test \"$first\" == false\n then\n echo \"BACKTRACE IS:\"\n first=true\n fi\n caller $i\n fi\n let \"i=i+1\"\n done\n}\n\nreturn 0\n</code></pre>\n\n<p><br>\n<br>\n<strong>Example of usage:</strong><br>\nfile content: trap-test.sh</p>\n\n<pre><code>#!/bin/bash\n\nsource 'lib.trap.sh'\n\necho \"doing something wrong now ..\"\necho \"$foo\"\n\nexit 0\n</code></pre>\n\n<p><br>\nRunning:</p>\n\n<pre><code>bash trap-test.sh\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>doing something wrong now ..\n\n(!) EXIT HANDLER:\n\nFILE: trap-test.sh\nLINE: 6\n\nERROR CODE: 1\nERROR MESSAGE:\nfoo: unassigned variable\n\nBACKTRACE IS:\n1 main trap-test.sh\n\nExiting!\n</code></pre>\n\n<p><br>\nAs you can see from the screenshot below, the output is colored and the error message comes in the used language.<br>\n<br>\n<img src=\"https://i.stack.imgur.com/0uBOL.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 18118450,
"author": "Orwellophile",
"author_id": 912236,
"author_profile": "https://Stackoverflow.com/users/912236",
"pm_score": 2,
"selected": false,
"text": "<p>This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_ </p>\n\n<pre><code>function handle_error {\n status=$?\n last_call=$1\n\n # 127 is 'command not found'\n (( status != 127 )) && return\n\n echo \"you tried to call $last_call\"\n return\n}\n\n# Trap errors.\ntrap 'handle_error \"$_\"' ERR\n</code></pre>\n"
},
{
"answer_id": 30019669,
"author": "niieani",
"author_id": 595157,
"author_profile": "https://Stackoverflow.com/users/595157",
"pm_score": 4,
"selected": false,
"text": "<p>Inspired by the ideas presented here, I have developed a readable and convenient way to handle errors in bash scripts in my <a href=\"https://github.com/niieani/bash-oo-framework\" rel=\"noreferrer\">bash boilerplate project</a>. </p>\n\n<p>By simply sourcing the library, you get the following out of the box (i.e. it will halt execution on any error, as if using <code>set -e</code> thanks to a <code>trap</code> on <code>ERR</code> and some <em>bash-fu</em>):</p>\n\n<p><img src=\"https://i.stack.imgur.com/UJhwZ.png\" alt=\"bash-oo-framework error handling\"></p>\n\n<p>There are some extra features that help handle errors, such as <strong>try and catch</strong>, or the <strong>throw</strong> keyword, that allows you to break execution at a point to see the backtrace. Plus, if the terminal supports it, it spits out powerline emojis, colors parts of the output for great readability, and underlines the method that caused the exception in the context of the line of code.</p>\n\n<p>The downside is - it's not portable - the code works in bash, probably >= 4 only (but I'd imagine it could be ported with some effort to bash 3).</p>\n\n<p>The code is separated into multiple files for better handling, but I was inspired by the backtrace idea from <a href=\"https://stackoverflow.com/questions/64786/error-handling-in-bash/13099228#13099228\">the answer above by Luca Borrione</a>. </p>\n\n<p>To read more or take a look at the source, see GitHub:</p>\n\n<p><a href=\"https://github.com/niieani/bash-oo-framework#error-handling-with-exceptions-and-throw\" rel=\"noreferrer\">https://github.com/niieani/bash-oo-framework#error-handling-with-exceptions-and-throw</a></p>\n"
},
{
"answer_id": 34726287,
"author": "skozin",
"author_id": 804678,
"author_profile": "https://Stackoverflow.com/users/804678",
"pm_score": 1,
"selected": false,
"text": "\n\n<p>Using trap is not always an option. For example, if you're writing some kind of re-usable function that needs error handling and that can be called from any script (after sourcing the file with helper functions), that function cannot assume anything about exit time of the outer script, which makes using traps very difficult. Another disadvantage of using traps is bad composability, as you risk overwriting previous trap that might be set earlier up in the caller chain.</p>\n\n<p>There is a little trick that can be used to do proper error handling without traps. As you may already know from other answers, <code>set -e</code> doesn't work inside commands if you use <code>||</code> operator after them, even if you run them in a subshell; e.g., this wouldn't work:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n# prints:\n#\n# --> outer\n# --> inner\n# ./so_1.sh: line 16: some_failed_command: command not found\n# <-- inner\n# <-- outer\n\nset -e\n\nouter() {\n echo '--> outer'\n (inner) || {\n exit_code=$?\n echo '--> cleanup'\n return $exit_code\n }\n echo '<-- outer'\n}\n\ninner() {\n set -e\n echo '--> inner'\n some_failed_command\n echo '<-- inner'\n}\n\nouter\n</code></pre>\n\n<p>But <code>||</code> operator is needed to prevent returning from the outer function before cleanup. The trick is to run the inner command in background, and then immediately wait for it. The <code>wait</code> builtin will return the exit code of the inner command, and now you're using <code>||</code> after <code>wait</code>, not the inner function, so <code>set -e</code> works properly inside the latter:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\n# prints:\n#\n# --> outer\n# --> inner\n# ./so_2.sh: line 27: some_failed_command: command not found\n# --> cleanup\n\nset -e\n\nouter() {\n echo '--> outer'\n inner &\n wait $! || {\n exit_code=$?\n echo '--> cleanup'\n return $exit_code\n }\n echo '<-- outer'\n}\n\ninner() {\n set -e\n echo '--> inner'\n some_failed_command\n echo '<-- inner'\n}\n\nouter\n</code></pre>\n\n<p>Here is the generic function that builds upon this idea. It should work in all POSIX-compatible shells if you remove <code>local</code> keywords, i.e. replace all <code>local x=y</code> with just <code>x=y</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># [CLEANUP=cleanup_cmd] run cmd [args...]\n#\n# `cmd` and `args...` A command to run and its arguments.\n#\n# `cleanup_cmd` A command that is called after cmd has exited,\n# and gets passed the same arguments as cmd. Additionally, the\n# following environment variables are available to that command:\n#\n# - `RUN_CMD` contains the `cmd` that was passed to `run`;\n# - `RUN_EXIT_CODE` contains the exit code of the command.\n#\n# If `cleanup_cmd` is set, `run` will return the exit code of that\n# command. Otherwise, it will return the exit code of `cmd`.\n#\nrun() {\n local cmd=\"$1\"; shift\n local exit_code=0\n\n local e_was_set=1; if ! is_shell_attribute_set e; then\n set -e\n e_was_set=0\n fi\n\n \"$cmd\" \"$@\" &\n\n wait $! || {\n exit_code=$?\n }\n\n if [ \"$e_was_set\" = 0 ] && is_shell_attribute_set e; then\n set +e\n fi\n\n if [ -n \"$CLEANUP\" ]; then\n RUN_CMD=\"$cmd\" RUN_EXIT_CODE=\"$exit_code\" \"$CLEANUP\" \"$@\"\n return $?\n fi\n\n return $exit_code\n}\n\n\nis_shell_attribute_set() { # attribute, like \"x\"\n case \"$-\" in\n *\"$1\"*) return 0 ;;\n *) return 1 ;;\n esac\n}\n</code></pre>\n\n<p>Example of usage:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\nset -e\n\n# Source the file with the definition of `run` (previous code snippet).\n# Alternatively, you may paste that code directly here and comment the next line.\n. ./utils.sh\n\n\nmain() {\n echo \"--> main: $@\"\n CLEANUP=cleanup run inner \"$@\"\n echo \"<-- main\"\n}\n\n\ninner() {\n echo \"--> inner: $@\"\n sleep 0.5; if [ \"$1\" = 'fail' ]; then\n oh_my_god_look_at_this\n fi\n echo \"<-- inner\"\n}\n\n\ncleanup() {\n echo \"--> cleanup: $@\"\n echo \" RUN_CMD = '$RUN_CMD'\"\n echo \" RUN_EXIT_CODE = $RUN_EXIT_CODE\"\n sleep 0.3\n echo '<-- cleanup'\n return $RUN_EXIT_CODE\n}\n\nmain \"$@\"\n</code></pre>\n\n<p>Running the example:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ ./so_3 fail; echo \"exit code: $?\"\n\n--> main: fail\n--> inner: fail\n./so_3: line 15: oh_my_god_look_at_this: command not found\n--> cleanup: fail\n RUN_CMD = 'inner'\n RUN_EXIT_CODE = 127\n<-- cleanup\nexit code: 127\n\n$ ./so_3 pass; echo \"exit code: $?\"\n\n--> main: pass\n--> inner: pass\n<-- inner\n--> cleanup: pass\n RUN_CMD = 'inner'\n RUN_EXIT_CODE = 0\n<-- cleanup\n<-- main\nexit code: 0\n</code></pre>\n\n<p>The only thing that you need to be aware of when using this method is that all modifications of Shell variables done from the command you pass to <code>run</code> will not propagate to the calling function, because the command runs in a subshell.</p>\n"
},
{
"answer_id": 41852435,
"author": "xarxziux",
"author_id": 5463687,
"author_profile": "https://Stackoverflow.com/users/5463687",
"pm_score": 2,
"selected": false,
"text": "<p>This function has been serving me rather well recently:</p>\n\n<pre><code>action () {\n # Test if the first parameter is non-zero\n # and return straight away if so\n if test $1 -ne 0\n then\n return $1\n fi\n\n # Discard the control parameter\n # and execute the rest\n shift 1\n \"$@\"\n local status=$?\n\n # Test the exit status of the command run\n # and display an error message on failure\n if test ${status} -ne 0\n then\n echo Command \\\"\"$@\"\\\" failed >&2\n fi\n\n return ${status}\n}\n</code></pre>\n\n<p>You call it by appending 0 or the last return value to the name of the command to run, so you can chain commands without having to check for error values. With this, this statement block:</p>\n\n<pre><code>command1 param1 param2 param3...\ncommand2 param1 param2 param3...\ncommand3 param1 param2 param3...\ncommand4 param1 param2 param3...\ncommand5 param1 param2 param3...\ncommand6 param1 param2 param3...\n</code></pre>\n\n<p>Becomes this:</p>\n\n<pre><code>action 0 command1 param1 param2 param3...\naction $? command2 param1 param2 param3...\naction $? command3 param1 param2 param3...\naction $? command4 param1 param2 param3...\naction $? command5 param1 param2 param3...\naction $? command6 param1 param2 param3...\n\n<<<Error-handling code here>>>\n</code></pre>\n\n<p>If any of the commands fail, the error code is simply passed to the end of the block. I find it useful when you don't want subsequent commands to execute if an earlier one failed, but you also don't want the script to exit straight away (for example, inside a loop).</p>\n"
},
{
"answer_id": 68857236,
"author": "NITHIN KIRTHICK",
"author_id": 13744498,
"author_profile": "https://Stackoverflow.com/users/13744498",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes <code>set -e</code> , <code>trap ERR</code> ,<code>set -o</code> <code>,set -o pipefail</code> and <code>set -o errtrace</code> not work properly because they attempt to add <strong>automatic error detection</strong> to the shell. This does not work well in practice.</p>\n<p>In my opinion, instead of using <code>set -e</code> and other stuffs, you should write your own error checking code. If you wise to use <code>set -e</code>, be aware of potential gotchas.</p>\n<p>To avoid Error while running the code you can use <code>exec 1>/dev/null</code> or <code>exec 2>/dev/null</code><br />\n<code>/dev/null</code> in Linux is a null device file. This will discard anything written to it and will return EOF on reading. you can use this at end of the command</p>\n<p>For <code>try/catch</code> you can use <code>&&</code> or <code>||</code> to achieve Similar behaviour\nuse can use && like this</p>\n<pre><code>{ # try\n\n command &&\n # your command \n\n} || { \n # catch exception \n}\n</code></pre>\n<p>or you can use <code>if else</code> :</p>\n<pre><code>if [[ Condition ]]; then\n # if true\nelse\n # if false\nfi\n</code></pre>\n<p><code>$?</code> show output of the last command ,it return 1 or 0</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What is your favorite method to handle errors in Bash?
The best example of handling errors I have found on the web was written by William Shotts, Jr at <http://www.linuxcommand.org>.
He suggests using the following function for error handling in Bash:
```
#!/bin/bash
# A slicker error handling routine
# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run. You can get this
# value from the first item on the command line ($0).
# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>
PROGNAME=$(basename $0)
function error_exit
{
# ----------------------------------------------------------------
# Function for exit due to fatal program error
# Accepts 1 argument:
# string containing descriptive error message
# ----------------------------------------------------------------
echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
exit 1
}
# Example call of the error_exit function. Note the inclusion
# of the LINENO environment variable. It contains the current
# line number.
echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."
```
Do you have a better error handling routine that you use in Bash scripts? | Use a trap!
```
tempfiles=( )
cleanup() {
rm -f "${tempfiles[@]}"
}
trap cleanup 0
error() {
local parent_lineno="$1"
local message="$2"
local code="${3:-1}"
if [[ -n "$message" ]] ; then
echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
else
echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
fi
exit "${code}"
}
trap 'error ${LINENO}' ERR
```
...then, whenever you create a temporary file:
```
temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )
```
and `$temp_foo` will be deleted on exit, and the current line number will be printed. (`set -e` will likewise give you exit-on-error behavior, [though it comes with serious caveats](http://mywiki.wooledge.org/BashFAQ/105) and weakens code's predictability and portability).
You can either let the trap call `error` for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:
```
error ${LINENO} "the foobar failed" 2
```
will exit with status 2, and give an explicit message.
Alternatively `shopt -s extdebug` and give the first lines of the trap a little modification to trap all non-zero exit codes across the board (mind `set -e` non-error non-zero exit codes):
```
error() {
local last_exit_status="$?"
local parent_lineno="$1"
local message="${2:-(no message ($last_exit_status))}"
local code="${3:-$last_exit_status}"
# ... continue as above
}
trap 'error ${LINENO}' ERR
shopt -s extdebug
```
This then is also "compatible" with `set -eu`. |
64,813 | <p>These days, i came across a problem with Team System Unit Testing. I found that the automatically created accessor class ignores generic constraints - at least in the following case:</p>
<p>Assume you have the following class:</p>
<pre><code>namespace MyLibrary
{
public class MyClass
{
public Nullable<T> MyMethod<T>(string s) where T : struct
{
return (T)Enum.Parse(typeof(T), s, true);
}
}
}
</code></pre>
<p>If you want to test MyMethod, you can create a test project with the following test method:</p>
<pre><code>public enum TestEnum { Item1, Item2, Item3 }
[TestMethod()]
public void MyMethodTest()
{
MyClass c = new MyClass();
PrivateObject po = new PrivateObject(c);
MyClass_Accessor target = new MyClass_Accessor(po);
// The following line produces the following error:
// Unit Test Adapter threw exception: GenericArguments[0], 'T', on
// 'System.Nullable`1[T]' violates the constraint of type parameter 'T'..
TestEnum? e1 = target.MyMethod<TestEnum>("item2");
// The following line works great but does not work for testing private methods.
TestEnum? e2 = c.MyMethod<TestEnum>("item2");
}
</code></pre>
<p>Running the test will fail with the error mentioned in the comment of the snippet above. The problem is the accessor class created by Visual Studio. If you go into it, you will come up to the following code:</p>
<pre><code>namespace MyLibrary
{
[Shadowing("MyLibrary.MyClass")]
public class MyClass_Accessor : BaseShadow
{
protected static PrivateType m_privateType;
[Shadowing(".ctor@0")]
public MyClass_Accessor();
public MyClass_Accessor(PrivateObject __p1);
public static PrivateType ShadowedType { get; }
public static MyClass_Accessor AttachShadow(object __p1);
[Shadowing("MyMethod@1")]
public T? MyMethod(string s);
}
}
</code></pre>
<p>As you can see, there is no constraint for the generic type parameter of the MyMethod method.</p>
<p>Is that a bug? Is that by design? Who knows how to work around that problem?</p>
| [
{
"answer_id": 64877,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I vote bug. I don't see how this could be by design.</p>\n"
},
{
"answer_id": 168453,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 1,
"selected": false,
"text": "<p>I didn't verify everything, but it looks like the call to:</p>\n\n<pre><code>TestEnum? e1 = target.MyMethod(\"item2\");\n</code></pre>\n\n<p>uses type inference to determine the generic type param T. Try calling the method differently in the test if possible:</p>\n\n<pre><code>TestEnum? e1 = target.MyMethod<TestEnum>(\"item2\");\n</code></pre>\n\n<p>That may yield different results.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 217704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Search for unit tests with generics on msdn. This is a known limitation. Vote for a resolution on Microsoft Connect, as it is definately needs resolving.</p>\n"
},
{
"answer_id": 1196250,
"author": "Josh Heyse",
"author_id": 142347,
"author_profile": "https://Stackoverflow.com/users/142347",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a similar issue on connect for reference.\n<a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=324473&wa=wsignin1.0\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=324473&wa=wsignin1.0</a></p>\n"
},
{
"answer_id": 3570884,
"author": "Igor Zevaka",
"author_id": 129404,
"author_profile": "https://Stackoverflow.com/users/129404",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like a bug. The workaround would be to change the method to <code>internal</code> and add <code>[assembly: InternalsVisibleTo(\"MyLibrary.Test\")]</code> to the assembly containing class under test.</p>\n\n<p>This would be my preferred way of testing non-public methods as it produces much cleaner looking unit tests.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6777/"
]
| These days, i came across a problem with Team System Unit Testing. I found that the automatically created accessor class ignores generic constraints - at least in the following case:
Assume you have the following class:
```
namespace MyLibrary
{
public class MyClass
{
public Nullable<T> MyMethod<T>(string s) where T : struct
{
return (T)Enum.Parse(typeof(T), s, true);
}
}
}
```
If you want to test MyMethod, you can create a test project with the following test method:
```
public enum TestEnum { Item1, Item2, Item3 }
[TestMethod()]
public void MyMethodTest()
{
MyClass c = new MyClass();
PrivateObject po = new PrivateObject(c);
MyClass_Accessor target = new MyClass_Accessor(po);
// The following line produces the following error:
// Unit Test Adapter threw exception: GenericArguments[0], 'T', on
// 'System.Nullable`1[T]' violates the constraint of type parameter 'T'..
TestEnum? e1 = target.MyMethod<TestEnum>("item2");
// The following line works great but does not work for testing private methods.
TestEnum? e2 = c.MyMethod<TestEnum>("item2");
}
```
Running the test will fail with the error mentioned in the comment of the snippet above. The problem is the accessor class created by Visual Studio. If you go into it, you will come up to the following code:
```
namespace MyLibrary
{
[Shadowing("MyLibrary.MyClass")]
public class MyClass_Accessor : BaseShadow
{
protected static PrivateType m_privateType;
[Shadowing(".ctor@0")]
public MyClass_Accessor();
public MyClass_Accessor(PrivateObject __p1);
public static PrivateType ShadowedType { get; }
public static MyClass_Accessor AttachShadow(object __p1);
[Shadowing("MyMethod@1")]
public T? MyMethod(string s);
}
}
```
As you can see, there is no constraint for the generic type parameter of the MyMethod method.
Is that a bug? Is that by design? Who knows how to work around that problem? | I vote bug. I don't see how this could be by design. |
64,820 | <p>ASP.NET 2.0 web application, how to implement shortcut key combination of <kbd>CTRL + Letter</kbd>, preferably through JavaScript, to make web application ergonomically better? How to capture multiple-key keyboard events through JavaScript?</p>
| [
{
"answer_id": 64879,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>Javascript has support for <kbd>ctrl</kbd>+<kbd>alt</kbd>+<kbd>shift</kbd> keys. I assume you can figure out the rest. <a href=\"http://www.javascripter.net/faq/ctrl_alt.htm\" rel=\"nofollow noreferrer\">Link</a>.</p>\n"
},
{
"answer_id": 65212,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>Your event listener function, gets passed an Event object. That has a lot of useful information on it, including the properties \"altKey\", \"ctrlKey\", \"shiftKey\" and \"metaKey\". If any of the modifier keys are being held down when that event fires, the corresponding property is set to true.</p>\n\n<p>This applies to keyboard as well as mouse events (onclick, etc). Note that if you have a onkeydown event listener, the modifier key itself will fire the event.</p>\n\n<pre><code>window.onkeyup = function(e) {\n if (e.altKey) alert(\"Alt pressed\");\n if (e.shiftKey) alert(\"Shift pressed\");\n}\n</code></pre>\n\n<p>This tested on Firefox 3, Windows XP.</p>\n"
},
{
"answer_id": 65528,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application!</p>\n\n<p>Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that \"one-key shortcut\" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser.</p>\n\n<p>Moreover, if your visitors use a higly customisable browser, such as Firefox or Opera, There is a high risk that they have either configure their own shortcuts or use additional plug-ins that define some additional ones.</p>\n\n<p>Keep in mind that web applications are browser dependend and that you should NEVER assumes that if it works on your favorite-tweak-most-powerfull-browser, it will react the same way on your friend's one.</p>\n"
},
{
"answer_id": 235126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The short answer is that you use Javascript to capture a <strong>keydown</strong> event and use that event to fire off a function.\nRelevant articles:</p>\n\n<ul>\n<li><a href=\"http://www.openjs.com/scripts/events/keyboard_shortcuts/\" rel=\"noreferrer\">http://www.openjs.com/scripts/events/keyboard_shortcuts/</a></li>\n<li><a href=\"http://udayms.wordpress.com/2006/03/17/ajax-key-disabling-using-javascript/\" rel=\"noreferrer\">http://udayms.wordpress.com/2006/03/17/ajax-key-disabling-using-javascript/</a></li>\n<li><a href=\"http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html\" rel=\"noreferrer\">http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html</a></li>\n<li><a href=\"http://www.quirksmode.org/js/keys.html\" rel=\"noreferrer\">http://www.quirksmode.org/js/keys.html</a></li>\n</ul>\n\n<p>If you're using the <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery library</a>, I'd suggest you look at the <a href=\"http://plugins.jquery.com/project/hotkeys\" rel=\"noreferrer\">HotKeys plugin</a> for a cross-browser solution.</p>\n\n<blockquote>\n <blockquote>\n <p>I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application!</p>\n \n <p>Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that \"one-key shortcut\" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser.</p>\n </blockquote>\n</blockquote>\n\n<p>Gizmo makes a good point. There's some information about commonly-used accesskey assignments at <a href=\"http://www.clagnut.com/blog/193/\" rel=\"noreferrer\">http://www.clagnut.com/blog/193/</a>. </p>\n\n<p>If you do change the accesskeys, here are some articles with good suggestions for how to do it well:</p>\n\n<ul>\n<li><a href=\"http://www.alistapart.com/articles/accesskeys/\" rel=\"noreferrer\">Accesskeys: Unlocking Hidden Navigation</a></li>\n<li><a href=\"http://www.cs.tut.fi/~jkorpela/forms/accesskey.html\" rel=\"noreferrer\">Using accesskey attribute in HTML forms and links </a></li>\n</ul>\n\n<p>And you may find this page of <a href=\"http://www.accessfirefox.org/Firefox_Keyboard_and_Mouse_Shortcuts.html\" rel=\"noreferrer\">Firefox's default Keyboard and Mouse Shortcuts</a> useful (<a href=\"http://lesliefranke.com/files/reference/firefoxcheatsheet.html\" rel=\"noreferrer\">Another version</a> of same information). Keyboard shortcuts for <a href=\"http://www.keyxl.com/aaacd98/28/Microsoft-Internet-Explorer-7-Browser-keyboard-shortcuts.htm\" rel=\"noreferrer\">Internet Explorer 7</a> and <a href=\"http://www.keyxl.com/aaa29c1/29/Microsoft-Internet-Explorer-6-Browser-keyboard-shortcuts.htm\" rel=\"noreferrer\">Internet Explorer 6</a>. Keyboard shortcuts <a href=\"http://www.keyxl.com/aaade74/97/Opera-web-browser-keyboard-shortcuts.htm\" rel=\"noreferrer\">for Opera</a> <a href=\"http://www.keyxl.com/aaa8ceb/93/Apple-Safari-web-browser-keyboard-shortcuts.htm\" rel=\"noreferrer\">and Safari</a>.</p>\n\n<p>You're more likely to run into problems with <a href=\"http://www.keyxl.com/aaadc6c/406/jaws-keyboard-shortcuts.htm\" rel=\"noreferrer\">JAWS</a> or other screen readers that add more keyboard shortcuts.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8832/"
]
| ASP.NET 2.0 web application, how to implement shortcut key combination of `CTRL + Letter`, preferably through JavaScript, to make web application ergonomically better? How to capture multiple-key keyboard events through JavaScript? | Your event listener function, gets passed an Event object. That has a lot of useful information on it, including the properties "altKey", "ctrlKey", "shiftKey" and "metaKey". If any of the modifier keys are being held down when that event fires, the corresponding property is set to true.
This applies to keyboard as well as mouse events (onclick, etc). Note that if you have a onkeydown event listener, the modifier key itself will fire the event.
```
window.onkeyup = function(e) {
if (e.altKey) alert("Alt pressed");
if (e.shiftKey) alert("Shift pressed");
}
```
This tested on Firefox 3, Windows XP. |
64,827 | <p>I've created a learning application using <a href="http://jimneath.org/2008/09/09/bort-base-rails-application/" rel="noreferrer">Bort</a>, which is a base app that includes Restful Authentication and RSpec. I've got it up and running and added a new object that requires users to be logged in before they can do anything(<code>before_filter :login_required</code> in the controller). [edit: I should also mention that the user <code>has_many</code> of the new class and only the user should be able to see it.]</p>
<p>I've created the new model/controller using Rspec's generators which have created a number of default tests. They all pass if there is no <code>before_filter</code> but several fail, as should be expected, once the <code>before_filter</code> is in place.</p>
<p>How do I get the generated tests to run as if there is/is not a logged in user? Do I need a whole batch of matching not logged in - redirect tests? I assume it is some sort of mocking or fixture technique but I am new to RSpec and a bit adrift. Good RSpec tutorial links would also be appreciated.</p>
| [
{
"answer_id": 65748,
"author": "TALlama",
"author_id": 5657,
"author_profile": "https://Stackoverflow.com/users/5657",
"pm_score": 4,
"selected": true,
"text": "<p>I have a very similar setup, and below is the code I'm currently using to test this stuff. In each of the <code>describe</code>s I put in:</p>\n\n<pre><code>it_should_behave_like \"login-required object\"\ndef attempt_access; do_post; end\n</code></pre>\n\n<p>If all you need is a login, or</p>\n\n<pre><code>it_should_behave_like \"ownership-required object\"\ndef login_as_object_owner; login_as @product.user; end\ndef attempt_access; do_put; end\ndef successful_ownership_access\n response.should redirect_to(product_url(@product))\nend\n</code></pre>\n\n<p>If you need ownership. Obviously, the helper methods change (very little) with each turn, but this does most of the work for you. This is in my spec_helper.rb</p>\n\n<pre><code>shared_examples_for \"login-required object\" do\n it \"should not be able to access this without logging in\" do\n attempt_access\n\n response.should_not be_success\n respond_to do |format|\n format.html { redirect_to(login_url) }\n format.xml { response.status_code.should == 401 }\n end\n end\nend\n\nshared_examples_for \"ownership-required object\" do\n it_should_behave_like \"login-required object\"\n\n it \"should not be able to access this without owning it\" do\n attempt_access\n\n response.should_not be_success\n respond_to do |format|\n format.html { response.should be_redirect }\n format.xml { response.status_code.should == 401 }\n end\n end\n\n it \"should be able to access this if you own it\" do\n login_as_object_owner\n attempt_access\n\n if respond_to?(:successful_ownership_access)\n successful_ownership_access\n else\n response.should be_success\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 71633,
"author": "srboisvert",
"author_id": 6805,
"author_profile": "https://Stackoverflow.com/users/6805",
"pm_score": 2,
"selected": false,
"text": "<p>I found a few answers to my own question. Basically, I needed to understand how to mock out the user from <code>restful_authentication</code> so that the autogenerated rspec controller tests could pass even though I had added <code>before_filter: login_required</code>.</p>\n\n<p>Here are a few of my just found resources:</p>\n\n<p><a href=\"http://www.robbyonrails.com/articles/2008/08/19/rspec-it-should-behave-like\" rel=\"nofollow noreferrer\">RSpec: It Should Behave Like</a></p>\n\n<p><a href=\"http://matthewkwilliams.com/index.php/2008/08/19/rspec-restful_authentication-and-login_required/\" rel=\"nofollow noreferrer\">rspec, restful_authentication, and login_required</a></p>\n\n<p><a href=\"http://rubyforge.org/pipermail/rspec-users/2007-August/002834.html\" rel=\"nofollow noreferrer\">using restful_authentication current_user inside controller specs</a></p>\n\n<p><a href=\"http://edspencer.net/2008/08/drying-up-your-crud-controller-rspecs.html\" rel=\"nofollow noreferrer\">DRYing up your CRUD controller RSpecs</a> </p>\n"
},
{
"answer_id": 143976,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 1,
"selected": false,
"text": "<p>To mock a user being logged in, I hack into the controller to set <code>@current_user</code> manually:</p>\n\n<pre><code>module AuthHelper\n protected\n\n def login_as(model, id_or_attributes = {})\n attributes = id_or_attributes.is_a?(Fixnum) ? {:id => id} : id_or_attributes\n @current_user = stub_model(model, attributes)\n target = controller rescue template\n target.instance_variable_set '@current_user', @current_user\n\n if block_given?\n yield\n target.instance_variable_set '@current_user', nil\n end\n return @current_user\n end\n\n def login_as_user(id_or_attributes = {}, &block)\n login_as(User, id_or_attributes, &block)\n end\nend\n</code></pre>\n"
},
{
"answer_id": 1943616,
"author": "Marcos Oliveira",
"author_id": 127209,
"author_profile": "https://Stackoverflow.com/users/127209",
"pm_score": 3,
"selected": false,
"text": "<p>When not testing the authentication but testing the controllers that needs the user to be authenticated I usually stub the filter method:</p>\n\n<pre><code>before(:each) do\n controller.stub!(:authenticate).and_return(true)\nend\n</code></pre>\n\n<p>The above example works where my before_filter is set to the authenticate method:</p>\n\n<pre><code>before_filter :authenticate\n</code></pre>\n\n<p>and the authenticate in my app uses HTTP Basic Authentication, but it really can be any other authentication mechanism.</p>\n\n<pre><code>private\ndef authenticate\n authenticate_or_request_with_http_basic do |user,password|\n user == USER_NAME && password == PASSWORD\n end\nend\n</code></pre>\n\n<p>I think it's a pretty straightforward way to test.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805/"
]
| I've created a learning application using [Bort](http://jimneath.org/2008/09/09/bort-base-rails-application/), which is a base app that includes Restful Authentication and RSpec. I've got it up and running and added a new object that requires users to be logged in before they can do anything(`before_filter :login_required` in the controller). [edit: I should also mention that the user `has_many` of the new class and only the user should be able to see it.]
I've created the new model/controller using Rspec's generators which have created a number of default tests. They all pass if there is no `before_filter` but several fail, as should be expected, once the `before_filter` is in place.
How do I get the generated tests to run as if there is/is not a logged in user? Do I need a whole batch of matching not logged in - redirect tests? I assume it is some sort of mocking or fixture technique but I am new to RSpec and a bit adrift. Good RSpec tutorial links would also be appreciated. | I have a very similar setup, and below is the code I'm currently using to test this stuff. In each of the `describe`s I put in:
```
it_should_behave_like "login-required object"
def attempt_access; do_post; end
```
If all you need is a login, or
```
it_should_behave_like "ownership-required object"
def login_as_object_owner; login_as @product.user; end
def attempt_access; do_put; end
def successful_ownership_access
response.should redirect_to(product_url(@product))
end
```
If you need ownership. Obviously, the helper methods change (very little) with each turn, but this does most of the work for you. This is in my spec\_helper.rb
```
shared_examples_for "login-required object" do
it "should not be able to access this without logging in" do
attempt_access
response.should_not be_success
respond_to do |format|
format.html { redirect_to(login_url) }
format.xml { response.status_code.should == 401 }
end
end
end
shared_examples_for "ownership-required object" do
it_should_behave_like "login-required object"
it "should not be able to access this without owning it" do
attempt_access
response.should_not be_success
respond_to do |format|
format.html { response.should be_redirect }
format.xml { response.status_code.should == 401 }
end
end
it "should be able to access this if you own it" do
login_as_object_owner
attempt_access
if respond_to?(:successful_ownership_access)
successful_ownership_access
else
response.should be_success
end
end
end
``` |
64,833 | <p>I am writing a C# client that calls a web service written in Java (by another person). I have added a web reference to my client and I'm able to call methods in the web service ok.</p>
<p>The service was changed to return an array of objects, and the client does not properly parse the returned SOAP message.</p>
<pre><code>MyResponse[] MyFunc(string p)
class MyResponse
{
long id;
string reason;
}
</code></pre>
<p>When my generated C# proxy calls the web service (using SoapHttpClientProtocol.Invoke), I am expecting a MyResponse[] array with length of 1, ie a single element. What I am getting after the Invoke call is an element with id=0 and reason=null, regardless of what the service actually returns. Using a packet sniffer, I can see that the service is returning what appears to be a legitimate soap message with id and reason set to non-null values.</p>
<p>Is there some trick to getting a C# client to call a Java web service that returns someobject[] ? I will work on getting a sanitized demo if necessary.</p>
<p><strong>Edit</strong>: This is a web reference via "Add Web Reference...". VS 2005, .NET 3.0.</p>
| [
{
"answer_id": 64913,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 3,
"selected": true,
"text": "<p>It has been a while, but I seem to remember having trouble with the slight differences in how default namespaces were handled between .Net and Java web services.</p>\n\n<p>Double check the generated c# proxy class and any namespaces declared within (especially the defaults xmlns=\"\"), against what the Java service is expecting. There will be probably be very subtle differences which you will have to recreate.</p>\n\n<p>If this is the case then you will to provide more namespace declarations in the c# attributes.</p>\n"
},
{
"answer_id": 66296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>From your question, it looks like you had the client working at one point, and then the service was changed to return an array. Make sure you re-generate the proxy so the returned SOAP message is deserialized on the client. It wasn't clear you had done this - just making sure.</p>\n"
},
{
"answer_id": 66834,
"author": "David Chappelle",
"author_id": 7475,
"author_profile": "https://Stackoverflow.com/users/7475",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks to Xian, I have a solution.</p>\n\n<p>The wsdl for the service included a line</p>\n\n<pre><code><import namespace=\"http://mynamespace.company.com\"/>\n</code></pre>\n\n<p>The soap that the client sent to the server had the following attribute on all data elements:</p>\n\n<pre><code>xmlns=\"http://mynamespace.company.com\"\n</code></pre>\n\n<p>But the xml payload of the response (from the service back to the client) did <em>not</em> have this namespace included. By tinkering with the HTTP response (which I obtained with <strong>WireShark</strong>), I observed that the .NET proxy class correctly picked up the MyResponse values if I forced the xmlns attribute on every returned data element.</p>\n\n<p>Short of changing the service, which I don't control, the workaround is to edit the VS generated proxy class (eg Reference.cs) and look for lines like this:</p>\n\n<pre><code>[System.Xml.Serialization.XmlTypeAttribute(Namespace=\"http://mynamespace.company.com\")]\npublic partial class MyResponse {\n</code></pre>\n\n<p>and comment out the XmlType attribute line. This will tell the CLR to look for response elements in the default namespace rather than the one specied in the wsdl. You have to redo this whenever you update the reference, but at least it works.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7475/"
]
| I am writing a C# client that calls a web service written in Java (by another person). I have added a web reference to my client and I'm able to call methods in the web service ok.
The service was changed to return an array of objects, and the client does not properly parse the returned SOAP message.
```
MyResponse[] MyFunc(string p)
class MyResponse
{
long id;
string reason;
}
```
When my generated C# proxy calls the web service (using SoapHttpClientProtocol.Invoke), I am expecting a MyResponse[] array with length of 1, ie a single element. What I am getting after the Invoke call is an element with id=0 and reason=null, regardless of what the service actually returns. Using a packet sniffer, I can see that the service is returning what appears to be a legitimate soap message with id and reason set to non-null values.
Is there some trick to getting a C# client to call a Java web service that returns someobject[] ? I will work on getting a sanitized demo if necessary.
**Edit**: This is a web reference via "Add Web Reference...". VS 2005, .NET 3.0. | It has been a while, but I seem to remember having trouble with the slight differences in how default namespaces were handled between .Net and Java web services.
Double check the generated c# proxy class and any namespaces declared within (especially the defaults xmlns=""), against what the Java service is expecting. There will be probably be very subtle differences which you will have to recreate.
If this is the case then you will to provide more namespace declarations in the c# attributes. |
64,841 | <p>I believe I need a DTD to define the schema and an XSLT if I want to display it in a browser and have it look "pretty". But I'm not sure what else I would need to have a well-defined XML document that can be queried using XQuery and displayed in a web browser.</p>
| [
{
"answer_id": 64869,
"author": "Sebastian Redl",
"author_id": 8922,
"author_profile": "https://Stackoverflow.com/users/8922",
"pm_score": 2,
"selected": false,
"text": "<p>Strictly speaking, you need nothing. XML, even without a schema definition, works.</p>\n\n<p>A schema definition (in XSD, RelaxNG or DTD) helps various tools that work with the XML, because they can verify that the structure of the XML conforms to what you want.</p>\n\n<p>An XSLT translation to HTML is nice if the XML contains information you'll want to look at with a browser. It's far from necessary, though.</p>\n\n<p>To query the XML with XPath or XQuery, you need an XPath or XQuery processor.</p>\n"
},
{
"answer_id": 64942,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": true,
"text": "<p>For a XML document to be queryable using XQquery you do not have to define a DTD or XSD. The purpose of DTD or XSD is to define the strict structure of a XML document and to allow validation before usage.</p>\n\n<p>Modern browsers interpret XML files very nicely and show a DOM tree. If enhanced formatting of XML for browser display is necessary you have to create a XSLT transformation file and then add a directive to the original XML document pointing to the XSLT file. The browser picks that directive and uses the built-in XSLT processor to obtain the output that is then interpreted by the browser.</p>\n\n<p><strong>info.xml</strong></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"info.xslt\"?>\n<info>\n <appName>My App</appName>\n <version>1.0.129</version>\n <buildTime>10-09-2008 12:44:03</buildTime>\n</info>\n</code></pre>\n\n<p><strong>info.xslt</strong></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"/\">\n <html>\n <head>\n <title>Application</title>\n <style type=\"text/css\">\n body { font-family: Lucida Console; }\n #outer { text-align: left; }\n #name {\n font-weight: bold;\n font-size: 1.2em;\n }\n #logo {\n float: left;\n padding-right: 20px;\n padding-bottom: 200px;\n }\n </style>\n </head>\n <body>\n <xsl:apply-templates select=\"info\" />\n </body>\n </html>\n </xsl:template>\n\n <xsl:template match=\"info\">\n <img id=\"logo\" src=\"image.png\" />\n <div id=\"outer\">\n <div id=\"name\">\n <xsl:value-of select=\"appName\"/>\n </div>\n <div id=\"version\">\n <xsl:value-of select=\"version\"/>\n </div>\n <div id=\"date\">\n <xsl:value-of select=\"buildTime\"/>\n </div>\n </div>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
| I believe I need a DTD to define the schema and an XSLT if I want to display it in a browser and have it look "pretty". But I'm not sure what else I would need to have a well-defined XML document that can be queried using XQuery and displayed in a web browser. | For a XML document to be queryable using XQquery you do not have to define a DTD or XSD. The purpose of DTD or XSD is to define the strict structure of a XML document and to allow validation before usage.
Modern browsers interpret XML files very nicely and show a DOM tree. If enhanced formatting of XML for browser display is necessary you have to create a XSLT transformation file and then add a directive to the original XML document pointing to the XSLT file. The browser picks that directive and uses the built-in XSLT processor to obtain the output that is then interpreted by the browser.
**info.xml**
```
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="info.xslt"?>
<info>
<appName>My App</appName>
<version>1.0.129</version>
<buildTime>10-09-2008 12:44:03</buildTime>
</info>
```
**info.xslt**
```
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>Application</title>
<style type="text/css">
body { font-family: Lucida Console; }
#outer { text-align: left; }
#name {
font-weight: bold;
font-size: 1.2em;
}
#logo {
float: left;
padding-right: 20px;
padding-bottom: 200px;
}
</style>
</head>
<body>
<xsl:apply-templates select="info" />
</body>
</html>
</xsl:template>
<xsl:template match="info">
<img id="logo" src="image.png" />
<div id="outer">
<div id="name">
<xsl:value-of select="appName"/>
</div>
<div id="version">
<xsl:value-of select="version"/>
</div>
<div id="date">
<xsl:value-of select="buildTime"/>
</div>
</div>
</xsl:template>
</xsl:stylesheet>
``` |
64,851 | <p>How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?</p>
<pre>
#define is_this_type_signed (my_type) ...
</pre>
| [
{
"answer_id": 64908,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 5,
"selected": false,
"text": "<p>In C++, use <code>std::numeric_limits<type>::is_signed</code>.</p>\n<pre><code>#include <limits>\nstd::numeric_limits<int>::is_signed - returns true\nstd::numeric_limits<unsigned int>::is_signed - returns false\n</code></pre>\n<p>See <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed</a>.</p>\n"
},
{
"answer_id": 64911,
"author": "Fabio Ceconello",
"author_id": 8999,
"author_profile": "https://Stackoverflow.com/users/8999",
"pm_score": 6,
"selected": true,
"text": "<p>If what you want is a simple macro, this should do the trick:</p>\n\n<pre><code>#define is_type_signed(my_type) (((my_type)-1) < 0)\n</code></pre>\n"
},
{
"answer_id": 64915,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>For c++, there is boost::is_unsigned<T>. I'm curious why you need it though, there are few good reasons IMHO.</p>\n"
},
{
"answer_id": 64923,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 2,
"selected": false,
"text": "<p>Your requirement isn't exactly the best, but if you'd like to hack together a define, one option could be:</p>\n\n<pre><code>#define is_numeric_type_signed(typ) ( (((typ)0 - (typ)1)<(typ)0) && (((typ)0 - (typ)1) < (typ)1) )\n</code></pre>\n\n<p>However, this isn't considered <em>nice</em> or portable by any means.</p>\n"
},
{
"answer_id": 64963,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 1,
"selected": false,
"text": "<p>I was actually just wondering the same thing earlier today. The following seems to work:</p>\n\n<pre><code>#define is_signed(t) ( ((t)-1) < 0 )\n</code></pre>\n\n<p>I tested with:</p>\n\n<pre><code>#include <stdio.h>\n\n#define is_signed(t) ( ((t)-1) < 0 )\n#define psigned(t) printf( #t \" is %s\\n\", is_signed(t) ? \"signed\" : \"unsigned\" );\n\nint\nmain(void)\n{\n psigned( int );\n psigned( unsigned int );\n}\n</code></pre>\n\n<p>which prints:</p>\n\n<pre><code>int is signed\nunsigned int is unsigned\n</code></pre>\n"
},
{
"answer_id": 64964,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": -1,
"selected": false,
"text": "<p>You could do this better with a template function, less macro nasty business.</p>\n\n<pre><code> template <typename T>\n bool IsSignedType()\n {\n // A lot of assumptions on T here\n T instanceAsOne = 1;\n\n if (-instanceAsOne > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n\n<p>Forgive the formatting...</p>\n\n<p>I would try this out and see if it works...</p>\n"
},
{
"answer_id": 64985,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>In C++ you can do:</p>\n\n<pre><code>\nbool is_signed = std::numeric_limits<typeof(some_integer_variable)>::is_signed;\n</code></pre>\n\n<p>numeric_limits is defined in the <limits> header.</p>\n"
},
{
"answer_id": 64988,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": -1,
"selected": false,
"text": "<p>In C, you can't write a macro that works on as-yet unknown typedef's of fundamental integer types.</p>\n\n<p>In C++, you can as long as your type is a fundamental integer type or a typedef of a fundamental integer type. Here's what you'd do in C++:</p>\n\n<pre><code>template <typename T>\nstruct is_signed_integer\n{\n static const bool value = false;\n};\n\ntemplate <>\nstruct is_signed_integer<int>\n{\n static const bool value = true;\n};\n\ntemplate <>\nstruct is_signed_integer<short>\n{\n static const bool value = true;\n};\n\ntemplate <>\nstruct is_signed_integer<signed char>\n{\n static const bool value = true;\n};\n\ntemplate <>\nstruct is_signed_integer<long>\n{\n static const bool value = true;\n};\n\n// assuming your C++ compiler supports 'long long'...\ntemplate <>\nstruct is_signed_integer<long long>\n{\n static const bool value = true;\n};\n\n#define is_this_type_signed(my_type) is_signed_integer<my_type>::value\n</code></pre>\n"
},
{
"answer_id": 65240,
"author": "Calliphony",
"author_id": 9050,
"author_profile": "https://Stackoverflow.com/users/9050",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a macro then this should do the trick:</p>\n\n<pre><code>#define IS_SIGNED( T ) (((T)-1)<0)\n</code></pre>\n\n<p>Basically, cast -1 to your type and see if it's still -1. In C++ you don't need a macro. Just <code>#include <limits></code> and:</p>\n\n<pre><code>bool my_type_is_signed = std::numeric_limits<my_type>::is_signed;\n</code></pre>\n"
},
{
"answer_id": 67109,
"author": "Bronek",
"author_id": 10042,
"author_profile": "https://Stackoverflow.com/users/10042",
"pm_score": 1,
"selected": false,
"text": "<p>Althout <code>typeof</code> is not legal C++ at the moment, you can use template deduction instead. See sample code below:</p>\n\n<pre><code>#include <iostream>\n#include <limits>\n\ntemplate <typename T>\nbool is_signed(const T& t)\n{\n return std::numeric_limits<T>::is_signed;\n}\n\nint main()\n{\n std::cout << \n is_signed(1) << \" \" << \n is_signed((unsigned char) 0) << \" \" << \n is_signed((signed char) 0) << std::endl;\n}\n</code></pre>\n\n<p>This code will print</p>\n\n<pre><code> 1 0 1\n</code></pre>\n"
},
{
"answer_id": 41602832,
"author": "Mikhail",
"author_id": 314290,
"author_profile": "https://Stackoverflow.com/users/314290",
"pm_score": 0,
"selected": false,
"text": "<p>A more \"modern\" approach is to use <code>type_traits</code>:</p>\n\n<pre><code>#include <type_traits>\n#include <iostream>\nint main()\n{\n std::cout << ( std::is_signed<int>::value ? \"Signed\" : \"Unsigned\") <<std::endl;\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528/"
]
| How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?
```
#define is_this_type_signed (my_type) ...
``` | If what you want is a simple macro, this should do the trick:
```
#define is_type_signed(my_type) (((my_type)-1) < 0)
``` |
64,860 | <p>What is the fastest, easiest tool or method to convert text files between character sets?</p>
<p>Specifically, I need to convert from UTF-8 to ISO-8859-15 and vice versa.</p>
<p>Everything goes: one-liners in your favorite scripting language, command-line tools or other utilities for OS, web sites, etc.</p>
<h2>Best solutions so far:</h2>
<p>On Linux/UNIX/OS X/cygwin:</p>
<ul>
<li><p>Gnu <a href="http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html" rel="noreferrer">iconv</a> suggested by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64889">Troels Arvin</a> is best used <strong>as a filter</strong>. It seems to be universally available. Example:</p>
<pre><code> $ iconv -f UTF-8 -t ISO-8859-15 in.txt > out.txt
</code></pre>
<p>As pointed out by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64991">Ben</a>, there is an <a href="http://www.iconv.com/iconv.htm" rel="noreferrer">online converter using iconv</a>.</p>
</li>
<li><p><a href="https://github.com/rrthomas/recode/" rel="noreferrer">recode</a> (<a href="http://www.informatik.uni-hamburg.de/RZ/software/gnu/utilities/recode_toc.html" rel="noreferrer">manual</a>) suggested by <a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64888">Cheekysoft</a> will convert <strong>one or several files in-place</strong>. Example:</p>
<pre><code> $ recode UTF8..ISO-8859-15 in.txt
</code></pre>
<p>This one uses shorter aliases:</p>
<pre><code> $ recode utf8..l9 in.txt
</code></pre>
<p>Recode also supports <em>surfaces</em> which can be used to convert between different line ending types and encodings:</p>
<p>Convert newlines from LF (Unix) to CR-LF (DOS):</p>
<pre><code> $ recode ../CR-LF in.txt
</code></pre>
<p>Base64 encode file:</p>
<pre><code> $ recode ../Base64 in.txt
</code></pre>
<p>You can also combine them.</p>
<p>Convert a Base64 encoded UTF8 file with Unix line endings to Base64 encoded Latin 1 file with Dos line endings:</p>
<pre><code> $ recode utf8/Base64..l1/CR-LF/Base64 file.txt
</code></pre>
</li>
</ul>
<p>On Windows with <a href="https://learn.microsoft.com/en-us/powershell/" rel="noreferrer">Powershell</a> (<a href="https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937">Jay Bazuzi</a>):</p>
<ul>
<li><code>PS C:\> gc -en utf8 in.txt | Out-File -en ascii out.txt</code></li>
</ul>
<p>(No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.)</p>
<h2>Edit</h2>
<p>Do you mean iso-8859-1 support? Using "String" does this e.g. for vice versa</p>
<pre><code>gc -en string in.txt | Out-File -en utf8 out.txt
</code></pre>
<p>Note: The possible enumeration values are "Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii".</p>
<ul>
<li>CsCvt - <a href="http://www.cscvt.de" rel="noreferrer">Kalytta's Character Set Converter</a> is another great command line based conversion tool for Windows.</li>
</ul>
| [
{
"answer_id": 64878,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://linux.die.net/man/1/iconv\" rel=\"noreferrer\">iconv(1)</a></p>\n\n<pre><code>iconv -f FROM-ENCODING -t TO-ENCODING file.txt\n</code></pre>\n\n<p>Also there are iconv-based tools in many languages.</p>\n"
},
{
"answer_id": 64888,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": false,
"text": "<p>Under Linux you can use the very powerful <strong>recode</strong> command to try and convert between the different charsets as well as any line ending issues. <strong>recode -l</strong> will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.</p>\n"
},
{
"answer_id": 64889,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://linux.die.net/man/1/iconv\" rel=\"noreferrer\">Stand-alone utility</a> approach</p>\n<pre class=\"lang-none prettyprint-override\"><code>iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>-f ENCODING the encoding of the input\n-t ENCODING the encoding of the output\n</code></pre>\n<p>You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8.</p>\n"
},
{
"answer_id": 64937,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 5,
"selected": false,
"text": "<pre><code>Get-Content -Encoding UTF8 FILE-UTF8.TXT | Out-File -Encoding UTF7 FILE-UTF7.TXT\n</code></pre>\n\n<p>The shortest version, if you can assume that the input BOM is correct:</p>\n\n<pre><code>gc FILE.TXT | Out-File -en utf7 file-utf7.txt\n</code></pre>\n"
},
{
"answer_id": 80494,
"author": "user15096",
"author_id": 15096,
"author_profile": "https://Stackoverflow.com/users/15096",
"pm_score": 2,
"selected": false,
"text": "<p>PHP iconv()</p>\n\n<p><code>iconv(\"UTF-8\", \"ISO-8859-15\", $input);</code></p>\n"
},
{
"answer_id": 8401721,
"author": "Arne Evertsson",
"author_id": 16686,
"author_profile": "https://Stackoverflow.com/users/16686",
"pm_score": 4,
"selected": false,
"text": "<h1>Try iconv Bash function</h1>\n<p>I've put this into <code>.bashrc</code>:</p>\n<pre><code>utf8()\n{\n iconv -f ISO-8859-1 -t UTF-8 $1 > $1.tmp\n rm $1\n mv $1.tmp $1\n}\n</code></pre>\n<p>..to be able to convert files like so:</p>\n<pre><code>utf8 MyClass.java\n</code></pre>\n"
},
{
"answer_id": 10933885,
"author": "Jeremy Glover",
"author_id": 524314,
"author_profile": "https://Stackoverflow.com/users/524314",
"pm_score": 4,
"selected": false,
"text": "<h1>Try Notepad++</h1>\n<p>On Windows I was able to use Notepad++ to do the conversion from <strong>ISO-8859-1</strong> to <strong>UTF-8</strong>. Click <code>"Encoding"</code> and then <code>"Convert to UTF-8"</code>.</p>\n"
},
{
"answer_id": 17329039,
"author": "pi3",
"author_id": 478484,
"author_profile": "https://Stackoverflow.com/users/478484",
"pm_score": -1,
"selected": false,
"text": "<p>As described on <a href=\"https://stackoverflow.com/questions/132318/how-do-i-correct-the-character-encoding-of-a-file\">How do I correct the character encoding of a file?</a> <a href=\"http://www.synalysis.net\" rel=\"nofollow noreferrer\">Synalyze It!</a> lets you easily convert on OS X between all encodings supported by the <a href=\"http://icu-project.org\" rel=\"nofollow noreferrer\">ICU library</a>.</p>\n\n<p>Additionally you can display some bytes of a file translated to Unicode from all the encodings to see quickly which is the right one for your file.</p>\n"
},
{
"answer_id": 32861628,
"author": "Boop",
"author_id": 2282427,
"author_profile": "https://Stackoverflow.com/users/2282427",
"pm_score": 7,
"selected": false,
"text": "<h1>Try VIM</h1>\n<p>If you have <code>vim</code> you can use this:</p>\n<p>Not tested for every encoding.</p>\n<p>The cool part about this is that you don't have to know the source encoding</p>\n<pre><code>vim +"set nobomb | set fenc=utf8 | x" filename.txt\n</code></pre>\n<p>Be aware that this command modify directly the file</p>\n<hr />\n<h3>Explanation part!</h3>\n<ol>\n<li><code>+</code> : Used by vim to directly enter command when opening a file. Usualy used to open a file at a specific line: <code>vim +14 file.txt</code></li>\n<li><code>|</code> : Separator of multiple commands (like <code>;</code> in bash)</li>\n<li><code>set nobomb</code> : no utf-8 BOM</li>\n<li><code>set fenc=utf8</code> : Set new encoding to utf-8 <a href=\"https://vimhelp.org/options.txt.html#%27fileencoding%27\" rel=\"noreferrer\">doc link</a></li>\n<li><code>x</code> : Save and close file</li>\n<li><code>filename.txt</code> : path to the file</li>\n<li><code>"</code> : qotes are here because of pipes. (otherwise bash will use them as bash pipe)</li>\n</ol>\n"
},
{
"answer_id": 39195151,
"author": "Serge Stroobandt",
"author_id": 2192488,
"author_profile": "https://Stackoverflow.com/users/2192488",
"pm_score": 4,
"selected": false,
"text": "<h1>Oneliner using find, with automatic character set detection</h1>\n<p><strong>The character encoding</strong> of all matching text files <strong>gets detected automatically</strong> and all matching text files are converted to <code>utf-8</code> encoding:</p>\n<pre><code>$ find . -type f -iname *.txt -exec sh -c 'iconv -f $(file -bi "$1" |sed -e "s/.*[ ]charset=//") -t utf-8 -o converted "$1" && mv converted "$1"' -- {} \\;\n</code></pre>\n<p>To perform these steps, a sub shell <code>sh</code> is used with <code>-exec</code>, running a one-liner with the <code>-c</code> flag, and passing the filename as the positional argument <code>"$1"</code> with <code>-- {}</code>. In between, the <code>utf-8</code> output file is temporarily named <code>converted</code>.</p>\n<p>Whereby <a href=\"https://linux.die.net/man/1/file\" rel=\"noreferrer\"><code>file -bi</code></a> means:</p>\n<ul>\n<li><p><code>-b</code>, <code>--brief</code>\nDo not prepend filenames to output lines (brief mode).</p>\n</li>\n<li><p><code>-i</code>, <code>--mime</code>\nCauses the file command to output mime type strings rather than the more traditional human readable ones. Thus it may say for example <code>text/plain; charset=us-ascii</code> rather than <code>ASCII text</code>. The <code>sed</code> command cuts this to only <code>us-ascii</code> as is required by <code>iconv</code>.</p>\n</li>\n</ul>\n<p>The <code>find</code> command is very useful for such file management automation.\nClick here for <a href=\"http://hamwaves.com/find/en/index.html#list-the-character-encoding-of-textfiles\" rel=\"noreferrer\">more <code>find</code> galore</a>.</p>\n"
},
{
"answer_id": 40852057,
"author": "Maciel Escudero Bombonato",
"author_id": 1096326,
"author_profile": "https://Stackoverflow.com/users/1096326",
"pm_score": 1,
"selected": false,
"text": "<p>to write properties file (Java) normally I use this in linux (mint and ubuntu distributions):</p>\n\n<pre><code>$ native2ascii filename.properties\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>$ cat test.properties \nfirst=Execução número um\nsecond=Execução número dois\n\n$ native2ascii test.properties \nfirst=Execu\\u00e7\\u00e3o n\\u00famero um\nsecond=Execu\\u00e7\\u00e3o n\\u00famero dois\n</code></pre>\n\n<p>PS: I writed Execution number one/two in portugues to force special characters.</p>\n\n<p>In my case, in first execution I received this message:</p>\n\n<pre><code>$ native2ascii teste.txt \nThe program 'native2ascii' can be found in the following packages:\n * gcj-5-jdk\n * openjdk-8-jdk-headless\n * gcj-4.8-jdk\n * gcj-4.9-jdk\nTry: sudo apt install <selected package>\n</code></pre>\n\n<p>When I installed the first option (gcj-5-jdk) the problem was finished.</p>\n\n<p>I hope this help someone.</p>\n"
},
{
"answer_id": 44788426,
"author": "lalthomas",
"author_id": 2182047,
"author_profile": "https://Stackoverflow.com/users/2182047",
"pm_score": 2,
"selected": false,
"text": "<p>DOS/Windows: use <a href=\"https://en.wikipedia.org/wiki/Code_page\" rel=\"nofollow noreferrer\">Code page</a></p>\n\n<pre><code>chcp 65001>NUL\ntype ascii.txt > unicode.txt\n</code></pre>\n\n<p>Command <code>chcp</code> can be used to change the code page. Code page 65001 is Microsoft name for UTF-8. After setting code page, the output generated by following commands will be of code page set.</p>\n"
},
{
"answer_id": 51036143,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 1,
"selected": false,
"text": "<p>With ruby:</p>\n\n<pre><code>ruby -e \"File.write('output.txt', File.read('input.txt').encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: ''))\"\n</code></pre>\n\n<p>Source: <a href=\"https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences\" rel=\"nofollow noreferrer\">https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences</a></p>\n"
},
{
"answer_id": 51122390,
"author": "kinORnirvana",
"author_id": 2260864,
"author_profile": "https://Stackoverflow.com/users/2260864",
"pm_score": 0,
"selected": false,
"text": "<p>Use this Python script: <a href=\"https://github.com/goerz/convert_encoding.py\" rel=\"nofollow noreferrer\">https://github.com/goerz/convert_encoding.py</a>\nWorks on any platform. Requires Python 2.7.</p>\n"
},
{
"answer_id": 52366373,
"author": "yota",
"author_id": 495769,
"author_profile": "https://Stackoverflow.com/users/495769",
"pm_score": 0,
"selected": false,
"text": "<p>My favorite tool for this is Jedit (a java based text editor) which has two very convenient features :</p>\n\n<ul>\n<li>One which enables the user to reload a text with a different encoding (and, as such, to control visually the result)</li>\n<li>Another one which enables the user to explicitly choose the encoding (and end of line char) before saving</li>\n</ul>\n"
},
{
"answer_id": 52725747,
"author": "Nikolai Varankine",
"author_id": 1451029,
"author_profile": "https://Stackoverflow.com/users/1451029",
"pm_score": 1,
"selected": false,
"text": "<p>Simply change encoding of loaded file in IntelliJ IDEA IDE, on the right of status bar (bottom), where current charset is indicated. It prompts to Reload or Convert, use Convert. Make sure you backed up original file in advance.</p>\n"
},
{
"answer_id": 59119195,
"author": "tiennou",
"author_id": 444323,
"author_profile": "https://Stackoverflow.com/users/444323",
"pm_score": 0,
"selected": false,
"text": "<p>If macOS GUI applications are your bread and butter, <a href=\"https://subethaedit.net/\" rel=\"nofollow noreferrer\">SubEthaEdit</a> is the text editor I usually go to for encoding-wrangling — its \"conversion preview\" allows you to see all invalid characters in the output encoding, and fix/remove them.</p>\n\n<p>And it's <a href=\"https://github.com/subethaedit/SubEthaEdit\" rel=\"nofollow noreferrer\">open-source</a> now, so yay for them .</p>\n"
},
{
"answer_id": 62976460,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Try EncodingChecker</strong></p>\n<p><a href=\"https://github.com/amrali-eg/EncodingChecker\" rel=\"nofollow noreferrer\">EncodingChecker on github</a></p>\n<p>File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.</p>\n<p>File Encoding Checker requires .NET 4 or above to run.</p>\n<p>For encoding detection, File Encoding Checker uses the <a href=\"https://github.com/CharsetDetector/UTF-unknown\" rel=\"nofollow noreferrer\">UtfUnknown</a> Charset Detector library. UTF-16 text files without byte-order-mark (BOM) can be detected by heuristics.</p>\n<p><a href=\"https://i.stack.imgur.com/q1i52.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q1i52.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 63176205,
"author": "Amr Ali",
"author_id": 4208440,
"author_profile": "https://Stackoverflow.com/users/4208440",
"pm_score": 1,
"selected": false,
"text": "<p>In powershell:</p>\n<pre><code>function Recode($InCharset, $InFile, $OutCharset, $OutFile) {\n # Read input file in the source encoding\n $Encoding = [System.Text.Encoding]::GetEncoding($InCharset)\n $Text = [System.IO.File]::ReadAllText($InFile, $Encoding)\n \n # Write output file in the destination encoding\n $Encoding = [System.Text.Encoding]::GetEncoding($OutCharset) \n [System.IO.File]::WriteAllText($OutFile, $Text, $Encoding)\n}\n\nRecode Windows-1252 "$pwd\\in.txt" utf8 "$pwd\\out.txt" \n</code></pre>\n<p>For a list of supported encoding names:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding</a></p>\n"
},
{
"answer_id": 63465837,
"author": "Pavel Morshenyuk",
"author_id": 112936,
"author_profile": "https://Stackoverflow.com/users/112936",
"pm_score": 1,
"selected": false,
"text": "<p>There is also a web tool to convert file encoding: <a href=\"https://webtool.cloud/change-file-encoding\" rel=\"nofollow noreferrer\">https://webtool.cloud/change-file-encoding</a></p>\n<p>It supports wide range of encodings, including some rare ones, like IBM code page 37.</p>\n"
},
{
"answer_id": 64214053,
"author": "Marcelo Teixeira Ruggeri",
"author_id": 2368184,
"author_profile": "https://Stackoverflow.com/users/2368184",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming, you don't know the input encoding and still wish to automate most of the conversion, I concluded this <strong>one liner</strong> from summing up previous answers.</p>\n<pre><code>iconv -f $(chardetect input.text | awk '{print $2}') -t utf-8 -o output.text\n</code></pre>\n"
},
{
"answer_id": 71692418,
"author": "Alex Czarto",
"author_id": 67006,
"author_profile": "https://Stackoverflow.com/users/67006",
"pm_score": 0,
"selected": false,
"text": "<h2>Visual Studio Code</h2>\n<ol>\n<li><strong>Open your file</strong> in <a href=\"https://code.visualstudio.com\" rel=\"nofollow noreferrer\">Visual Studio Code</a></li>\n<li><strong>Reopen with Encoding</strong>: In the bottom status bar, to the right, you should see your current file encoding (eg "UTF-8"). Click this and select "Reopen with Encoding".</li>\n<li><strong>Select the correct encoding</strong> of the file (eg: ISO 8859-2).</li>\n<li><strong>Confirm</strong> that your content is displaying as expected.</li>\n<li><strong>Save with Encoding</strong>: The bottom status bar should now display your new encoding format (eg: ISO 8859-2). Click this and choose "Save with Encoding" and select UTF-8 (or whatever new encoding you want).</li>\n</ol>\n<p><strong>NOTE: THIS WILL OVERWRITE YOUR ORGINIAL FILE. MAKE A BACKUP FIRST.</strong></p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948/"
]
| What is the fastest, easiest tool or method to convert text files between character sets?
Specifically, I need to convert from UTF-8 to ISO-8859-15 and vice versa.
Everything goes: one-liners in your favorite scripting language, command-line tools or other utilities for OS, web sites, etc.
Best solutions so far:
----------------------
On Linux/UNIX/OS X/cygwin:
* Gnu [iconv](http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html) suggested by [Troels Arvin](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64889) is best used **as a filter**. It seems to be universally available. Example:
```
$ iconv -f UTF-8 -t ISO-8859-15 in.txt > out.txt
```
As pointed out by [Ben](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64991), there is an [online converter using iconv](http://www.iconv.com/iconv.htm).
* [recode](https://github.com/rrthomas/recode/) ([manual](http://www.informatik.uni-hamburg.de/RZ/software/gnu/utilities/recode_toc.html)) suggested by [Cheekysoft](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64888) will convert **one or several files in-place**. Example:
```
$ recode UTF8..ISO-8859-15 in.txt
```
This one uses shorter aliases:
```
$ recode utf8..l9 in.txt
```
Recode also supports *surfaces* which can be used to convert between different line ending types and encodings:
Convert newlines from LF (Unix) to CR-LF (DOS):
```
$ recode ../CR-LF in.txt
```
Base64 encode file:
```
$ recode ../Base64 in.txt
```
You can also combine them.
Convert a Base64 encoded UTF8 file with Unix line endings to Base64 encoded Latin 1 file with Dos line endings:
```
$ recode utf8/Base64..l1/CR-LF/Base64 file.txt
```
On Windows with [Powershell](https://learn.microsoft.com/en-us/powershell/) ([Jay Bazuzi](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937)):
* `PS C:\> gc -en utf8 in.txt | Out-File -en ascii out.txt`
(No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.)
Edit
----
Do you mean iso-8859-1 support? Using "String" does this e.g. for vice versa
```
gc -en string in.txt | Out-File -en utf8 out.txt
```
Note: The possible enumeration values are "Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii".
* CsCvt - [Kalytta's Character Set Converter](http://www.cscvt.de) is another great command line based conversion tool for Windows. | [Stand-alone utility](http://linux.die.net/man/1/iconv) approach
```none
iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt
```
```none
-f ENCODING the encoding of the input
-t ENCODING the encoding of the output
```
You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8. |
64,894 | <p>Is it possible to select from <code>show tables</code> in MySQL?</p>
<pre><code>SELECT * FROM (SHOW TABLES) AS `my_tables`
</code></pre>
<p>Something along these lines, though the above does not work (on 5.0.51a, at least).</p>
| [
{
"answer_id": 64918,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked into querying INFORMATION_SCHEMA.Tables? As in</p>\n\n<pre><code>SELECT ic.Table_Name,\n ic.Column_Name,\n ic.data_Type,\n IFNULL(Character_Maximum_Length,'') AS `Max`,\n ic.Numeric_precision as `Precision`,\n ic.numeric_scale as Scale,\n ic.Character_Maximum_Length as VarCharSize,\n ic.is_nullable as Nulls, \n ic.ordinal_position as OrdinalPos, \n ic.column_default as ColDefault, \n ku.ordinal_position as PK,\n kcu.constraint_name,\n kcu.ordinal_position,\n tc.constraint_type\nFROM INFORMATION_SCHEMA.COLUMNS ic\n left outer join INFORMATION_SCHEMA.key_column_usage ku\n on ku.table_name = ic.table_name\n and ku.column_name = ic.column_name\n left outer join information_schema.key_column_usage kcu\n on kcu.column_name = ic.column_name\n and kcu.table_name = ic.table_name\n left outer join information_schema.table_constraints tc\n on kcu.constraint_name = tc.constraint_name\norder by ic.table_name, ic.ordinal_position;\n</code></pre>\n"
},
{
"answer_id": 64921,
"author": "Andrew",
"author_id": 8871,
"author_profile": "https://Stackoverflow.com/users/8871",
"pm_score": 6,
"selected": false,
"text": "<p>I think you want <code>SELECT * FROM INFORMATION_SCHEMA.TABLES</code></p>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/tables-table.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/tables-table.html</a></p>\n"
},
{
"answer_id": 64922,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "<p>I think what you want is MySQL's information_schema view(s):\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/tables-table.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/tables-table.html</a></p>\n"
},
{
"answer_id": 64945,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES\n</code></pre>\n\n<p>That should be a good start. For more, check <a href=\"http://dev.mysql.com/doc/refman/5.0/en/information-schema.html\" rel=\"nofollow noreferrer\">INFORMATION_SCHEMA Tables</a>.</p>\n"
},
{
"answer_id": 64946,
"author": "Derek B. Bell",
"author_id": 8944,
"author_profile": "https://Stackoverflow.com/users/8944",
"pm_score": 1,
"selected": false,
"text": "<p>I don't understand why you want to use <code>SELECT * FROM</code> as part of the statement.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-tables.html\" rel=\"nofollow noreferrer\">12.5.5.30. SHOW TABLES Syntax</a></p>\n"
},
{
"answer_id": 64994,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 4,
"selected": false,
"text": "<p>Not that I know of, unless you select from <code>INFORMATION_SCHEMA</code>, as others have mentioned. </p>\n\n<p>However, the <code>SHOW</code> command is pretty flexible, \nE.g.:</p>\n\n<pre><code>SHOW tables like '%s%'\n</code></pre>\n"
},
{
"answer_id": 4108393,
"author": "Brian",
"author_id": 498605,
"author_profile": "https://Stackoverflow.com/users/498605",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT column_comment FROM information_schema.columns WHERE table_name = 'myTable' AND column_name = 'myColumnName'\n</code></pre>\n\n<p>This will return the comment on: myTable.myColumnName</p>\n"
},
{
"answer_id": 8561638,
"author": "Srdjan",
"author_id": 1105899,
"author_profile": "https://Stackoverflow.com/users/1105899",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, SELECT from table_schema could be very usefull for system administration. If you have lot of servers, databases, tables... sometimes you need to DROP or UPDATE bunch of elements. For example to create query for DROP all tables with prefix name \"wp_old_...\":</p>\n\n<pre><code>SELECT concat('DROP TABLE ', table_name, ';') FROM INFORMATION_SCHEMA.TABLES\nWHERE table_schema = '*name_of_your_database*'\nAND table_name LIKE 'wp_old_%';\n</code></pre>\n"
},
{
"answer_id": 16576049,
"author": "MT467",
"author_id": 2183883,
"author_profile": "https://Stackoverflow.com/users/2183883",
"pm_score": 2,
"selected": false,
"text": "<p>in MySql 5.1 you can try </p>\n\n<pre><code>show tables like 'user%';\n</code></pre>\n\n<p><strong>output:</strong></p>\n\n<pre><code>mysql> show tables like 'user%';\n\n+----------------------------+\n\n| Tables_in_test (user%) |\n\n+----------------------------+\n\n| user |\n\n| user_password |\n\n+----------------------------+\n\n2 rows in set (0.00 sec)\n</code></pre>\n"
},
{
"answer_id": 16576727,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": false,
"text": "<p>You can't put <code>SHOW</code> statements inside a subquery like in your example. The only statement that can go in a subquery is <code>SELECT</code>.</p>\n\n<p>As other answers have stated, you can query the INFORMATION_SCHEMA directly with <code>SELECT</code> and get a lot more flexibility that way.</p>\n\n<p>MySQL's <code>SHOW</code> statements are internally just queries against the INFORMATION_SCHEMA tables.</p>\n\n<p>User @physicalattraction has posted this comment on most other answers:</p>\n\n<blockquote>\n <p>This gives you (meta)information about the tables, not the contents of the table, as the OP intended. – physicalattraction</p>\n</blockquote>\n\n<p>On the contrary, the OP's question does <em>not</em> say that they want to select the data in all the tables. They say they want to select from the result of <code>SHOW TABLES</code>, which is just a list of table names.</p>\n\n<p>If the OP does want to select all data from all tables, then the answer is no, you can't do it with one query. Each query must name its tables explicitly. You can't make a table name be a variable or the result of another part of the same query. Also, all rows of a given query result must have the same columns.</p>\n\n<p>So the only way to select all data from all tables would be to run <code>SHOW TABLES</code> and then for each table named in that result, run another query.</p>\n"
},
{
"answer_id": 18019612,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 3,
"selected": false,
"text": "<p>You may be closer than you think — <a href=\"https://dev.mysql.com/doc/refman/en/show-tables.html\" rel=\"nofollow noreferrer\">SHOW TABLES</a> already behaves a lot like a SELECT statement. Here's a <a href=\"https://www.php.net/manual/en/class.pdo.php\" rel=\"nofollow noreferrer\">PHP</a> example of how you might fetch its "rows":</p>\n<pre class=\"lang-php prettyprint-override\"><code>$pdo = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);\nforeach ($pdo->query("SHOW TABLES") as $row) {\n print "Table $row[Tables_in_$dbname]\\n";\n}\n</code></pre>\n<p>SHOW TABLES behaves like a SELECT on a one-column table. That column name is <code>Tables_in_</code> plus the database name.</p>\n"
},
{
"answer_id": 28628228,
"author": "Ivan Ferrer",
"author_id": 3455502,
"author_profile": "https://Stackoverflow.com/users/3455502",
"pm_score": 4,
"selected": false,
"text": "<p>To count:</p>\n\n<pre><code>SELECT COUNT(*) as total FROM (SELECT TABLE_NAME as tab, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY tab) tables;\n</code></pre>\n\n<p>To list:</p>\n\n<pre><code>SELECT TABLE_NAME as table, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY table;\n</code></pre>\n"
},
{
"answer_id": 46242383,
"author": "Bridget Arrington",
"author_id": 355838,
"author_profile": "https://Stackoverflow.com/users/355838",
"pm_score": 2,
"selected": false,
"text": "<p>You can create a stored procedure and put the table names in a cursor, then loop through your table names to show the data. </p>\n\n<p>Getting started with stored procedure:\n<a href=\"http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx\" rel=\"nofollow noreferrer\">http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx</a></p>\n\n<p>Creating a cursor:\n<a href=\"http://www.mysqltutorial.org/mysql-cursor/\" rel=\"nofollow noreferrer\">http://www.mysqltutorial.org/mysql-cursor/</a></p>\n\n<p>For example, </p>\n\n<pre><code>CREATE PROCEDURE `ShowFromTables`()\nBEGIN\n\nDECLARE v_finished INTEGER DEFAULT 0;\nDECLARE c_table varchar(100) DEFAULT \"\";\n\nDECLARE table_cursor CURSOR FOR \nSELECT table_name FROM information_schema.tables WHERE table_name like 'wp_1%';\n\nDECLARE CONTINUE HANDLER \n FOR NOT FOUND SET v_finished = 1;\n\nOPEN table_cursor;\n\nget_data: LOOP\n\nFETCH table_cursor INTO c_table;\n\nIF v_finished = 1 THEN \nLEAVE get_data;\nEND IF;\n\nSET @s=CONCAT(\"SELECT * FROM \",c_table,\";\");\n\nPREPARE stmt FROM @s;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;\n\nEND LOOP get_data;\n\nCLOSE table_cursor;\n\nEND\n</code></pre>\n\n<p>Then call the stored procedure:</p>\n\n<pre><code>CALL ShowFromTables();\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is it possible to select from `show tables` in MySQL?
```
SELECT * FROM (SHOW TABLES) AS `my_tables`
```
Something along these lines, though the above does not work (on 5.0.51a, at least). | I think you want `SELECT * FROM INFORMATION_SCHEMA.TABLES`
See <http://dev.mysql.com/doc/refman/5.0/en/tables-table.html> |
64,904 | <p>I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.</p>
<p>Example:</p>
<pre><code>input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']
</code></pre>
<p>I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.</p>
<p>Any help would be greatly appreciated!</p>
| [
{
"answer_id": 65033,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 1,
"selected": false,
"text": "<pre><code>'foo bar \"lorem ipsum\" baz'.match(/\"[^\"]*\"|\\w+/g);\n</code></pre>\n\n<p>the bounding quotes get included though</p>\n"
},
{
"answer_id": 65085,
"author": "A Nony Mouse",
"author_id": 7182,
"author_profile": "https://Stackoverflow.com/users/7182",
"pm_score": 2,
"selected": false,
"text": "<p>A simple regular expression will do but leave the quotation marks. e.g.</p>\n\n<pre><code>'foo bar \"lorem ipsum\" baz'.match(/(\"[^\"]*\")|([^\\s\"]+)/g)\noutput: ['foo', 'bar', '\"lorem ipsum\"', 'baz']\n</code></pre>\n\n<p>edit: beaten to it by shyamsundar, sorry for the double answer</p>\n"
},
{
"answer_id": 65092,
"author": "davidnicol",
"author_id": 7420,
"author_profile": "https://Stackoverflow.com/users/7420",
"pm_score": 1,
"selected": false,
"text": "<p>how about,</p>\n\n<pre><code>output = /(\".+?\"|\\w+)/g.exec(input)\n</code></pre>\n\n<p>then do a pass on output to lose the quotes.</p>\n\n<p>alternately,</p>\n\n<pre><code>output = /\"(.+?)\"|(\\w+)/g.exec(input)\n</code></pre>\n\n<p>then do a pass n output to lose the empty captures.</p>\n"
},
{
"answer_id": 65177,
"author": "yoz",
"author_id": 9070,
"author_profile": "https://Stackoverflow.com/users/9070",
"pm_score": 5,
"selected": true,
"text": "<pre><code>var str = 'foo bar \"lorem ipsum\" baz'; \nvar results = str.match(/(\"[^\"]+\"|[^\"\\s]+)/g);\n</code></pre>\n\n<p>... returns the array you're looking for.<br>\nNote, however:</p>\n\n<ul>\n<li>Bounding quotes are included, so can be removed with <code>replace(/^\"([^\"]+)\"$/,\"$1\")</code> on the results.</li>\n<li>Spaces between the quotes will stay intact. So, if there are three spaces between <code>lorem</code> and <code>ipsum</code>, they'll be in the result. You can fix this by running <code>replace(/\\s+/,\" \")</code> on the results.</li>\n<li>If there's no closing <code>\"</code> after <code>ipsum</code> (i.e. an incorrectly-quoted phrase) you'll end up with: <code>['foo', 'bar', 'lorem', 'ipsum', 'baz']</code></li>\n</ul>\n"
},
{
"answer_id": 65338,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>var input = 'foo bar \"lorem ipsum\" baz';\nvar R = /(\\w|\\s)*\\w(?=\")|\\w+/g;\nvar output = input.match(R);\n\noutput is [\"foo\", \"bar\", \"lorem ipsum\", \"baz\"]\n</code></pre>\n\n<p>Note there are no extra double quotes around lorem ipsum</p>\n\n<p>Although it assumes the input has the double quotes in the right place:</p>\n\n<pre><code>var input2 = 'foo bar lorem ipsum\" baz'; var output2 = input2.match(R);\nvar input3 = 'foo bar \"lorem ipsum baz'; var output3 = input3.match(R);\n\noutput2 is [\"foo bar lorem ipsum\", \"baz\"]\noutput3 is [\"foo\", \"bar\", \"lorem\", \"ipsum\", \"baz\"]\n</code></pre>\n\n<p>And won't handle escaped double quotes (is that a problem?):</p>\n\n<pre><code>var input4 = 'foo b\\\"ar bar\\\" \\\"bar \"lorem ipsum\" baz';\nvar output4 = input4.match(R);\n\noutput4 is [\"foo b\", \"ar bar\", \"bar\", \"lorem ipsum\", \"baz\"]\n</code></pre>\n"
},
{
"answer_id": 65577,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks a lot for the quick responses!</p>\n\n<p>Here's a summary of the options, for posterity:</p>\n\n<pre><code>var input = 'foo bar \"lorem ipsum\" baz';\n\noutput = input.match(/(\"[^\"]+\"|[^\"\\s]+)/g);\noutput = input.match(/\"[^\"]*\"|\\w+/g);\noutput = input.match(/(\"[^\"]*\")|([^\\s\"]+)/g)\noutput = /(\".+?\"|\\w+)/g.exec(input);\noutput = /\"(.+?)\"|(\\w+)/g.exec(input);\n</code></pre>\n\n<p>For the record, here's the abomination I had come up with:</p>\n\n<pre><code>var input = 'foo bar \"lorem ipsum\" \"dolor sit amet\" baz';\nvar terms = input.split(\" \");\n\nvar items = [];\nvar buffer = [];\nfor(var i = 0; i < terms.length; i++) {\n if(terms[i].indexOf('\"') != -1) { // outer phrase fragment -- N.B.: assumes quote is either first or last character\n if(buffer.length === 0) { // beginning of phrase\n //console.log(\"start:\", terms[i]);\n buffer.push(terms[i].substr(1));\n } else { // end of phrase\n //console.log(\"end:\", terms[i]);\n buffer.push(terms[i].substr(0, terms[i].length - 1));\n items.push(buffer.join(\" \"));\n buffer = [];\n }\n } else if(buffer.length != 0) { // inner phrase fragment\n //console.log(\"cont'd:\", terms[i]);\n buffer.push(terms[i]);\n } else { // individual term\n //console.log(\"standalone:\", terms[i]);\n items.push(terms[i]);\n }\n //console.log(items, \"\\n\", buffer);\n}\nitems = items.concat(buffer);\n\n//console.log(items);\n</code></pre>\n"
},
{
"answer_id": 16945284,
"author": "tigerswithguitars",
"author_id": 726986,
"author_profile": "https://Stackoverflow.com/users/726986",
"pm_score": 0,
"selected": false,
"text": "<p>One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like </p>\n\n<p><code>\"hello my name is 'jon delaware smith fred' I have a 'long name'\"</code>....</p>\n\n<p>A bit like the answer by AC but a bit neater...</p>\n\n<pre><code>function split(input, delimiter, joiner){\n var output = [];\n var joint = [];\n input.split(delimiter).forEach(function(element){\n if (joint.length > 0 && element.indexOf(joiner) === element.length - 1)\n {\n output.push(joint.join(delimiter) + delimiter + element);\n joint = [];\n }\n if (joint.length > 0 || element.indexOf(joiner) === 0)\n {\n joint.push(element);\n }\n if (joint.length === 0 && element.indexOf(joiner) !== element.length - 1)\n {\n output.push(element);\n joint = [];\n }\n });\n return output;\n }\n</code></pre>\n"
},
{
"answer_id": 26626761,
"author": "Suganthan Madhavan Pillai",
"author_id": 2534236,
"author_profile": "https://Stackoverflow.com/users/2534236",
"pm_score": 0,
"selected": false,
"text": "<p>This might be a very late answer, but I am interested in answering</p>\n\n<pre><code>([\\w]+|\\\"[\\w\\s]+\\\")\n</code></pre>\n\n<p><a href=\"http://regex101.com/r/dZ1vT6/72\" rel=\"nofollow\">http://regex101.com/r/dZ1vT6/72</a></p>\n\n<p>Pure javascript example</p>\n\n<pre><code> 'The rain in \"SPAIN stays\" mainly in the plain'.match(/[\\w]+|\\\"[\\w\\s]+\\\"/g)\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>[\"The\", \"rain\", \"in\", \"\"SPAIN stays\"\", \"mainly\", \"in\", \"the\", \"plain\"]\n</code></pre>\n"
},
{
"answer_id": 46946542,
"author": "Tsuneo Yoshioka",
"author_id": 1309218,
"author_profile": "https://Stackoverflow.com/users/1309218",
"pm_score": 1,
"selected": false,
"text": "<p>ES6 solution supporting:</p>\n\n<ul>\n<li>Split by space except for inside quotes</li>\n<li>Removing quotes but not for backslash escaped quotes</li>\n<li>Escaped quote become quote</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>input.match(/\\\\?.|^$/g).reduce((p, c) => {\n if(c === '\"'){\n p.quote ^= 1;\n }else if(!p.quote && c === ' '){\n p.a.push('');\n }else{\n p.a[p.a.length-1] += c.replace(/\\\\(.)/,\"$1\");\n }\n return p;\n }, {a: ['']}).a\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[ 'foo', 'bar', 'lorem ipsum', 'baz' ]\n</code></pre>\n"
},
{
"answer_id": 64447893,
"author": "Rob Hawkins",
"author_id": 2636364,
"author_profile": "https://Stackoverflow.com/users/2636364",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding on the accepted answer, here's a search engine parser that,</p>\n<ul>\n<li>can match phrases or words</li>\n<li>treats phrases as regular expressions</li>\n<li>does a boolean OR across multiple properties (e.g. item.title and item.body)</li>\n<li>handles negation of words or phrases when they are prefixed with -</li>\n</ul>\n<p>Treating phrases as regular expressions makes the UI simpler for my purposes.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const matchOrIncludes = (str, search, useMatch = true) => {\n if (useMatch) {\n let result = false\n try {\n result = str.match(search)\n } catch (err) {\n return false\n }\n return result\n }\n return str.includes(search)\n}\n\n\nconst itemMatches = (item, searchString, fields) => {\n const keywords = searchString.toString().replace(/\\s\\s+/g, ' ').trim().toLocaleLowerCase().match(/(-?\"[^\"]+\"|[^\"\\s]+)/g) || []\n for (let i = 0; i < keywords.length; i++) {\n const negateWord = keywords[i].startsWith('-') ? true : false\n let word = keywords[i].replace(/^-/,'')\n const isPhraseRegex = word.startsWith('\"') ? true : false\n if (isPhraseRegex) {\n word = word.replace(/^\"(.+)\"$/,\"$1\")\n }\n let word_in_item = false\n for (const field of fields) {\n if (item[field] && matchOrIncludes(item[field].toLocaleLowerCase(), word, isPhraseRegex)) {\n word_in_item = true\n break\n }\n }\n if ((! negateWord && ! word_in_item) || (negateWord && word_in_item)) {\n return false\n }\n }\n return true\n}\n\nconst item = {title: 'My title', body: 'Some text'}\nconsole.log(itemMatches(item, 'text', ['title', 'body']))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.
Example:
```
input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']
```
I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.
Any help would be greatly appreciated! | ```
var str = 'foo bar "lorem ipsum" baz';
var results = str.match(/("[^"]+"|[^"\s]+)/g);
```
... returns the array you're looking for.
Note, however:
* Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results.
* Spaces between the quotes will stay intact. So, if there are three spaces between `lorem` and `ipsum`, they'll be in the result. You can fix this by running `replace(/\s+/," ")` on the results.
* If there's no closing `"` after `ipsum` (i.e. an incorrectly-quoted phrase) you'll end up with: `['foo', 'bar', 'lorem', 'ipsum', 'baz']` |
64,958 | <p>Yacc does not permit objects to be passed around. Because the %union can only contain POD types, complex objects must be new'd and passed around by pointer. If a syntax error occurs, the yacc parser just stops running, and references to all of those created objects are lost.</p>
<p>The only solution I've come up with is that all new'd object inherit a particular base class, be added to a container when allocated, and if there is an error everything in that container can be deleted.</p>
<p>Does anyone know of any better yacc tricks to solve this problem?</p>
<p>Please don't tell me to choose a different parser.</p>
| [
{
"answer_id": 65096,
"author": "Ron",
"author_id": 9100,
"author_profile": "https://Stackoverflow.com/users/9100",
"pm_score": 1,
"selected": false,
"text": "<p>If it suits your project, consider using the Boehm Garbage collector. That way you can freely allocate new objects and let the collector handle the deletes. Of course there are tradeoffs involved in using a garbage collector. You would have to weigh the costs and benefits.</p>\n"
},
{
"answer_id": 65098,
"author": "user7305",
"author_id": 7305,
"author_profile": "https://Stackoverflow.com/users/7305",
"pm_score": -1,
"selected": false,
"text": "<p>Use <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">smart pointers</a>!</p>\n\n<p>Or, if you're uncomfortable depending on yet another library, you can always use <a href=\"http://www.gotw.ca/publications/using_auto_ptr_effectively.htm\" rel=\"nofollow noreferrer\">auto_ptr</a> from the C++ standard library.</p>\n"
},
{
"answer_id": 65424,
"author": "Michael L Perry",
"author_id": 7668,
"author_profile": "https://Stackoverflow.com/users/7668",
"pm_score": 3,
"selected": true,
"text": "<p>I love Yacc, but the discriminating union stack does present a challenge.</p>\n\n<p>I don't know whether you are using C or C++. I've modified Yacc to generate C++ for my own purposes, but this solution can be adapted to C.</p>\n\n<p>My preferred solution is to pass an interface to the owner down the parse tree, rather than constructed objects up the stack. Do this by creating your own stack outside of Yacc's. Before you invoke a non-terminal that allocates an object, push the owner of that object to this stack.</p>\n\n<p>For example:</p>\n\n<pre><code>class IExpressionOwner\n{\npublic:\n virtual ExpressionAdd *newExpressionAdd() = 0;\n virtual ExpressionSubstract *newExpressionSubtract() = 0;\n virtual ExpressionMultiply *newExpressionMultiply() = 0;\n virtual ExpressionDivide *newExpressionDivide() = 0;\n};\n\nclass ExpressionAdd : public Expression, public IExpressionOwner\n{\nprivate:\n std::auto_ptr<Expression> left;\n std::auto_ptr<Expression> right;\n\npublic:\n ExpressionAdd *newExpressionAdd()\n {\n ExpressionAdd *newExpression = new ExpressionAdd();\n std::auto_ptr<Expression> autoPtr(newExpression);\n if (left.get() == NULL)\n left = autoPtr;\n else\n right = autoPtr;\n return newExpression;\n }\n\n ...\n};\n\nclass Parser\n{\nprivate:\n std::stack<IExpressionOwner *> expressionOwner;\n\n ...\n};\n</code></pre>\n\n<p>Everything that wants an expression has to implement the IExpressionOwner interface and push itself to the stack before invoking the expression non-terminal. It's a lot of extra code, but it controls object lifetime.</p>\n\n<p><strong>Update</strong></p>\n\n<p>The expression example is a bad one, since you don't know the operation until after you've reduced the left operand. Still, this technique works in many cases, and requires just a little tweaking for expressions.</p>\n"
},
{
"answer_id": 73202,
"author": "user12310",
"author_id": 12310,
"author_profile": "https://Stackoverflow.com/users/12310",
"pm_score": -1,
"selected": false,
"text": "<p>Why is using a different parser such a problem? Bison is readily available, and (at least on linux) yacc is usually implemented as bison. You shouldn't need any changes to your grammar to use it (except for adding %destructor to solve your issue).</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8566/"
]
| Yacc does not permit objects to be passed around. Because the %union can only contain POD types, complex objects must be new'd and passed around by pointer. If a syntax error occurs, the yacc parser just stops running, and references to all of those created objects are lost.
The only solution I've come up with is that all new'd object inherit a particular base class, be added to a container when allocated, and if there is an error everything in that container can be deleted.
Does anyone know of any better yacc tricks to solve this problem?
Please don't tell me to choose a different parser. | I love Yacc, but the discriminating union stack does present a challenge.
I don't know whether you are using C or C++. I've modified Yacc to generate C++ for my own purposes, but this solution can be adapted to C.
My preferred solution is to pass an interface to the owner down the parse tree, rather than constructed objects up the stack. Do this by creating your own stack outside of Yacc's. Before you invoke a non-terminal that allocates an object, push the owner of that object to this stack.
For example:
```
class IExpressionOwner
{
public:
virtual ExpressionAdd *newExpressionAdd() = 0;
virtual ExpressionSubstract *newExpressionSubtract() = 0;
virtual ExpressionMultiply *newExpressionMultiply() = 0;
virtual ExpressionDivide *newExpressionDivide() = 0;
};
class ExpressionAdd : public Expression, public IExpressionOwner
{
private:
std::auto_ptr<Expression> left;
std::auto_ptr<Expression> right;
public:
ExpressionAdd *newExpressionAdd()
{
ExpressionAdd *newExpression = new ExpressionAdd();
std::auto_ptr<Expression> autoPtr(newExpression);
if (left.get() == NULL)
left = autoPtr;
else
right = autoPtr;
return newExpression;
}
...
};
class Parser
{
private:
std::stack<IExpressionOwner *> expressionOwner;
...
};
```
Everything that wants an expression has to implement the IExpressionOwner interface and push itself to the stack before invoking the expression non-terminal. It's a lot of extra code, but it controls object lifetime.
**Update**
The expression example is a bad one, since you don't know the operation until after you've reduced the left operand. Still, this technique works in many cases, and requires just a little tweaking for expressions. |
64,977 | <p>How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?</p>
| [
{
"answer_id": 64995,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 2,
"selected": false,
"text": "<p>You bring up <em>Template Explorer</em> using Ctrl+Alt+T or trough <em>View > Template Explorer</em>. Then you can right click tree nodes to add new Templates or new folders to organize your new templates.</p>\n"
},
{
"answer_id": 64997,
"author": "Chris Woodruff",
"author_id": 7001,
"author_profile": "https://Stackoverflow.com/users/7001",
"pm_score": 5,
"selected": true,
"text": "<p>Another little nugget that I think will help people developing and being more productive in their database development. I am a fan of stored procedures and functions when I develop software solutions. I like my actual CRUD methods to be implemented at the database level. It allows me to balance out my work between the application software (business logic and data access) and the database itself. Not wanting to start a religious war, but I want to allow people to develop stored procedures more quickly and with best practices through templates.</p>\n\n<p>Let’s start with making your own templates in the SQL Server 2005 management Studio. First, you need to show the Template Explorer in the Studio.</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb10.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb10.png</a></p>\n\n<p>This will show the following:</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb11.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb11.png</a></p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb12.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb12.png</a></p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb13.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb13.png</a></p>\n\n<p>The IDE will create a blank template. To edit the template, right click on the template and select Edit. You will get a blank Query window in the IDE. You can now insert your template implementation. I have here the template of the new stored procedure to include a TRY CATCH. I like to include error handling in my stored procedures. With the new TRY CATCH addition to TSQL in SQL Server 2005, we should try to use this powerful exception handling mechanism through our code including database code. Save the template and you are all ready to use your new template for stored procedure creation.</p>\n\n<pre><code>-- ======================================================\n-- Create basic stored procedure template with TRY CATCH\n-- ======================================================\n\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- =============================================\n-- Author: <Author,,Name>\n-- Create date: <Create Date,,>\n-- Description: <Description,,>\n-- =============================================\nCREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>\n -- Add the parameters for the stored procedure here\n <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,\n <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>\nAS\n BEGIN TRY\n BEGIN TRANSACTION -- Start the transaction\n\n SELECT @p1, @p2\n\n -- If we reach here, success!\n COMMIT\n END TRY\n BEGIN CATCH\n -- there was an error\n IF @@TRANCOUNT > 0\n ROLLBACK\n\n -- Raise an error with the details of the exception\n DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int\n SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()\n\n RAISERROR(@ErrMsg, @ErrSeverity, 1)\n END CATCH\nGO\n</code></pre>\n"
},
{
"answer_id": 4149000,
"author": "Dhiraj",
"author_id": 489194,
"author_profile": "https://Stackoverflow.com/users/489194",
"pm_score": 2,
"selected": false,
"text": "<p>Database=>Table=>Programmability=>Procedures=>Right Clik Select New procedures</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7001/"
]
| How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio? | Another little nugget that I think will help people developing and being more productive in their database development. I am a fan of stored procedures and functions when I develop software solutions. I like my actual CRUD methods to be implemented at the database level. It allows me to balance out my work between the application software (business logic and data access) and the database itself. Not wanting to start a religious war, but I want to allow people to develop stored procedures more quickly and with best practices through templates.
Let’s start with making your own templates in the SQL Server 2005 management Studio. First, you need to show the Template Explorer in the Studio.
[alt text http://www.cloudsocket.com/images/image-thumb10.png](http://www.cloudsocket.com/images/image-thumb10.png)
This will show the following:
[alt text http://www.cloudsocket.com/images/image-thumb11.png](http://www.cloudsocket.com/images/image-thumb11.png)
[alt text http://www.cloudsocket.com/images/image-thumb12.png](http://www.cloudsocket.com/images/image-thumb12.png)
[alt text http://www.cloudsocket.com/images/image-thumb13.png](http://www.cloudsocket.com/images/image-thumb13.png)
The IDE will create a blank template. To edit the template, right click on the template and select Edit. You will get a blank Query window in the IDE. You can now insert your template implementation. I have here the template of the new stored procedure to include a TRY CATCH. I like to include error handling in my stored procedures. With the new TRY CATCH addition to TSQL in SQL Server 2005, we should try to use this powerful exception handling mechanism through our code including database code. Save the template and you are all ready to use your new template for stored procedure creation.
```
-- ======================================================
-- Create basic stored procedure template with TRY CATCH
-- ======================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
-- Add the parameters for the stored procedure here
<@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
<@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
AS
BEGIN TRY
BEGIN TRANSACTION -- Start the transaction
SELECT @p1, @p2
-- If we reach here, success!
COMMIT
END TRY
BEGIN CATCH
-- there was an error
IF @@TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH
GO
``` |
64,981 | <p>How do I create a unique constraint on an existing table in SQL Server 2005?</p>
<p>I am looking for both the TSQL and how to do it in the Database Diagram.</p>
| [
{
"answer_id": 65003,
"author": "Ivan Bosnic",
"author_id": 3221,
"author_profile": "https://Stackoverflow.com/users/3221",
"pm_score": 4,
"selected": false,
"text": "<pre><code>ALTER TABLE dbo.<tablename> ADD CONSTRAINT\n <namingconventionconstraint> UNIQUE NONCLUSTERED\n (\n <columnname>\n ) ON [PRIMARY]\n</code></pre>\n"
},
{
"answer_id": 65022,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 3,
"selected": false,
"text": "<p>You are looking for something like the following</p>\n\n<pre><code>ALTER TABLE dbo.doc_exz\nADD CONSTRAINT col_b_def\nUNIQUE column_b\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190273.aspx\" rel=\"noreferrer\">MSDN Docs</a></p>\n"
},
{
"answer_id": 65025,
"author": "Gibbons",
"author_id": 1506,
"author_profile": "https://Stackoverflow.com/users/1506",
"pm_score": 3,
"selected": false,
"text": "<p>In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose \"Check Constraints\", there you can add one.</p>\n"
},
{
"answer_id": 65036,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": false,
"text": "<p>I also found you can do this via, the database diagrams.</p>\n\n<p>By right clicking the table and selecting Indexes/Keys...</p>\n\n<p>Click the 'Add' button, and change the columns to the column(s) you wish make unique.</p>\n\n<p>Change Is Unique to Yes.</p>\n\n<p>Click close and save the diagram, and it will add it to the table.</p>\n"
},
{
"answer_id": 65047,
"author": "WildJoe",
"author_id": 9052,
"author_profile": "https://Stackoverflow.com/users/9052",
"pm_score": 5,
"selected": false,
"text": "<pre><code>ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])\n</code></pre>\n"
},
{
"answer_id": 65123,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 9,
"selected": true,
"text": "<p>The SQL command is:</p>\n\n<pre><code>ALTER TABLE <tablename> ADD CONSTRAINT\n <constraintname> UNIQUE NONCLUSTERED\n (\n <columnname>\n )\n</code></pre>\n\n<p>See the full syntax <a href=\"http://msdn.microsoft.com/en-us/library/ms190273.aspx\" rel=\"noreferrer\">here</a>.</p>\n\n<p>If you want to do it from a Database Diagram:</p>\n\n<ul>\n<li>right-click on the table and select 'Indexes/Keys'</li>\n<li>click the Add button to add a new index</li>\n<li>enter the necessary info in the Properties on the right hand side:\n\n<ul>\n<li>the columns you want (click the ellipsis button to select)</li>\n<li>set Is Unique to Yes</li>\n<li>give it an appropriate name</li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 537780,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 4,
"selected": false,
"text": "<p>Warning: Only one null row can be in the column you've set to be unique.</p>\n\n<p>You can do this with a filtered index in SQL 2008:</p>\n\n<pre><code>CREATE UNIQUE NONCLUSTERED INDEX idx_col1\nON dbo.MyTable(col1)\nWHERE col1 IS NOT NULL;\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/377798/field-value-must-be-unique-unless-it-is-null\">Field value must be unique unless it is NULL</a> for a range of answers.</p>\n"
},
{
"answer_id": 1313576,
"author": "James Lawruk",
"author_id": 88204,
"author_profile": "https://Stackoverflow.com/users/88204",
"pm_score": 6,
"selected": false,
"text": "<p>In SQL Server Management Studio Express:</p>\n\n<ul>\n<li>Right-click table, choose <strong>Modify</strong> or <strong>Design(For Later Versions)</strong></li>\n<li>Right-click field, choose <strong>Indexes/Keys...</strong></li>\n<li>Click <strong>Add</strong></li>\n<li>For <strong>Columns</strong>, select the <strong>field name</strong> you want to be unique.</li>\n<li>For <strong>Type</strong>, choose <strong>Unique Key</strong>.</li>\n<li>Click <strong>Close</strong>, <strong>Save</strong> the table.</li>\n</ul>\n"
},
{
"answer_id": 27223345,
"author": "Rafiq",
"author_id": 847501,
"author_profile": "https://Stackoverflow.com/users/847501",
"pm_score": 3,
"selected": false,
"text": "<p>To create a UNIQUE constraint on one or multiple columns when the table is already created, use the following SQL:</p>\n\n<pre><code>ALTER TABLE TableName ADd UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)\n</code></pre>\n\n<p>To allow naming of a UNIQUE constraint for above query</p>\n\n<pre><code>ALTER TABLE TableName ADD CONSTRAINT un_constaint_name UNIQUE (ColumnName1,ColumnName2, ColumnName3, ...)\n</code></pre>\n\n<p><em>The query supported by MySQL / SQL Server / Oracle / MS Access.</em></p>\n"
},
{
"answer_id": 49405468,
"author": "Mario Vázquez",
"author_id": 8928707,
"author_profile": "https://Stackoverflow.com/users/8928707",
"pm_score": 0,
"selected": false,
"text": "<p>In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:</p>\n\n<pre><code>IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')\n ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name> \nGO\n\nALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>) \nGO\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
]
| How do I create a unique constraint on an existing table in SQL Server 2005?
I am looking for both the TSQL and how to do it in the Database Diagram. | The SQL command is:
```
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
```
See the full syntax [here](http://msdn.microsoft.com/en-us/library/ms190273.aspx).
If you want to do it from a Database Diagram:
* right-click on the table and select 'Indexes/Keys'
* click the Add button to add a new index
* enter the necessary info in the Properties on the right hand side:
+ the columns you want (click the ellipsis button to select)
+ set Is Unique to Yes
+ give it an appropriate name |
64,992 | <p>I'm working with a support person who is supposed to be able to install SSL certs on a web server he maintains. He has local admin rights to the server via a domain security group. He also has permissions on our internal CA running Windows 2003 Server Certificate Authority: "Request cert" and "Issue and Manage certs".</p>
<p>The server he's working with is running Windows 2000 SP4 / IIS 5. When he attempts to create an online server cert the IIS wizard ends with "Failed to install. Access is Denied.". The event viewer is not working properly, so I can't find any details there. I suspect the permission issue is locally and not with the CA.</p>
<p>My account is a domain admin account and I know I am able to do this operation, however I need to make this work for others that are not domain admins.</p>
<p>Any ideas why he can't perform this operation?</p>
| [
{
"answer_id": 65542,
"author": "JWHEAT",
"author_id": 7079,
"author_profile": "https://Stackoverflow.com/users/7079",
"pm_score": 3,
"selected": false,
"text": "<p>I had this exact same issue a few months ago when I was setting up a cert for a client.</p>\n\n<p>There's a MachineKeys folder that the Administrator need rights -</p>\n\n<pre><code>\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Crypto\\RSA\\MachineKeys\n</code></pre>\n\n<p>give <strong>Administrator</strong> (or the Administrator group) <strong>Full Control</strong> over this directory. I don't think you have to restart IIS, but it never hurts .</p>\n\n<p>I have no idea why Admin doesn't control this as default.\nOnce this is changed, the Certificate Creation Wizard will successfully generate the certificate request.</p>\n\n<p>I think there's even a Microsoft KB article about it somewhere.</p>\n\n<p>EDIT: Here's the KB article : <a href=\"http://support.microsoft.com/kb/908572\" rel=\"noreferrer\">http://support.microsoft.com/kb/908572</a></p>\n\n<p>-Jon</p>\n"
},
{
"answer_id": 39781880,
"author": "Vincent",
"author_id": 1380479,
"author_profile": "https://Stackoverflow.com/users/1380479",
"pm_score": 1,
"selected": false,
"text": "<p>If you're renewing a certificate, then it's possible that you imported your new intermediate certificate (.pb7) before removing your existing (expired) certificate from IIS. You would get an access denied error because both the old and new certificates are for the same domain.</p>\n\n<p>So by the time you get this access denied error, there are three things you must do.</p>\n\n<ol>\n<li>Remove all certificates for this domain name from IIS, including the new one you just imported..</li>\n<li>Go back to Console1, and remove the certificate for your domain name from Local Computer\\Certificate Enrollment Requests\\Certificates.</li>\n<li>Start over.</li>\n</ol>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/64992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
]
| I'm working with a support person who is supposed to be able to install SSL certs on a web server he maintains. He has local admin rights to the server via a domain security group. He also has permissions on our internal CA running Windows 2003 Server Certificate Authority: "Request cert" and "Issue and Manage certs".
The server he's working with is running Windows 2000 SP4 / IIS 5. When he attempts to create an online server cert the IIS wizard ends with "Failed to install. Access is Denied.". The event viewer is not working properly, so I can't find any details there. I suspect the permission issue is locally and not with the CA.
My account is a domain admin account and I know I am able to do this operation, however I need to make this work for others that are not domain admins.
Any ideas why he can't perform this operation? | I had this exact same issue a few months ago when I was setting up a cert for a client.
There's a MachineKeys folder that the Administrator need rights -
```
\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
```
give **Administrator** (or the Administrator group) **Full Control** over this directory. I don't think you have to restart IIS, but it never hurts .
I have no idea why Admin doesn't control this as default.
Once this is changed, the Certificate Creation Wizard will successfully generate the certificate request.
I think there's even a Microsoft KB article about it somewhere.
EDIT: Here's the KB article : <http://support.microsoft.com/kb/908572>
-Jon |
65,008 | <p>I am experimenting with using the FaultException and FaultException<T> to determine the best usage pattern in our applications. We need to support WCF as well as non-WCF service consumers/clients, including SOAP 1.1 and SOAP 1.2 clients.</p>
<p>FYI: using FaultExceptions with wsHttpBinding results in SOAP 1.2 semantics whereas using FaultExceptions with basicHttpBinding results in SOAP 1.1 semantics. </p>
<p>I am using the following code to throw a FaultException<FaultDetails>:</p>
<pre><code> throw new FaultException<FaultDetails>(
new FaultDetails("Throwing FaultException<FaultDetails>."),
new FaultReason("Testing fault exceptions."),
FaultCode.CreateSenderFaultCode(new FaultCode("MySubFaultCode"))
);
</code></pre>
<p>The FaultDetails class is just a simple test class that contains a string "Message" property as you can see below.</p>
<p>When using wsHttpBinding the response is:</p>
<pre><code><?xml version="1.0" encoding="utf-16"?>
<Fault xmlns="http://www.w3.org/2003/05/soap-envelope">
<Code>
<Value>Sender</Value>
<Subcode>
<Value>MySubFaultCode</Value>
</Subcode>
</Code>
<Reason>
<Text xml:lang="en-US">Testing fault exceptions.</Text>
</Reason>
<Detail>
<FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Message>Throwing FaultException&lt;FaultDetails&gt;.</Message>
</FaultDetails>
</Detail>
</code></pre>
<p></p>
<p>This looks right according to the SOAP 1.2 specs. The main/root “Code” is “Sender”, which has a “Subcode” of “MySubFaultCode”. If the service consumer/client is using WCF the FaultException on the client side also mimics the same structure, with the faultException.Code.Name being “Sender” and faultException.Code.SubCode.Name being “MySubFaultCode”.</p>
<p>When using basicHttpBinding the response is:</p>
<pre><code><?xml version="1.0" encoding="utf-16"?>
<s:Fault xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>s:MySubFaultCode</faultcode>
<faultstring xml:lang="en-US">Testing fault exceptions.</faultstring>
<detail>
<FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Message>Throwing FaultException&lt;FaultDetails&gt;.</Message>
</FaultDetails>
</detail>
</s:Fault>
</code></pre>
<p>This does not look right. Looking at the SOAP 1.1 specs, I was expecting to see the “faultcode” to have a value of “s:Client.MySubFaultCode” when I use FaultCode.CreateSenderFaultCode(new FaultCode("MySubFaultCode")). Also a WCF client gets an incorrect structure. The faultException.Code.Name is “MySubFaultCode” instead of being “Sender”, and the faultException.Code.SubCode is null instead of faultException.Code.SubCode.Name being “MySubFaultCode”. Also, the faultException.Code.IsSenderFault is false.</p>
<p>Similar problem when using FaultCode.CreateReceiverFaultCode(new FaultCode("MySubFaultCode")):</p>
<ul>
<li>works as expected for SOAP 1.2</li>
<li>generates “s:MySubFaultCode” instead of “s:Server.MySubFaultCode” and the faultException.Code.IsReceiverFault is false for SOAP 1.1</li>
</ul>
<p>This item was also posted by someone else on <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=669420&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=669420&SiteID=1</a> in 2006 and no one has answered it. I find it very hard to believe that no one has run into this, yet. </p>
<p>Here is someone else having a similar problem: <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3883110&SiteID=1&mode=1" rel="nofollow noreferrer">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3883110&SiteID=1&mode=1</a></p>
<p>Microsoft Connect bug: <a href="https://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=367963" rel="nofollow noreferrer">https://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=367963</a></p>
<p>Description of how faults should work: <a href="http://blogs.msdn.com/drnick/archive/2006/12/19/creating-faults-part-3.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/drnick/archive/2006/12/19/creating-faults-part-3.aspx</a></p>
<p>Am I doing something wrong or is this truly a bug in WCF?</p>
| [
{
"answer_id": 69390,
"author": "wojo",
"author_id": 9022,
"author_profile": "https://Stackoverflow.com/users/9022",
"pm_score": 4,
"selected": true,
"text": "<p>This is my current workaround:</p>\n\n<pre><code> /// <summary>\n /// Replacement for the static methods on FaultCode to generate Sender and Receiver fault codes due\n /// to what seems like bugs in the implementation for basicHttpBinding (SOAP 1.1). wsHttpBinding \n /// (SOAP 1.2) seems to work just fine.\n /// \n /// The subCode parameter for FaultCode.CreateReceiverFaultCode and FaultCode.CreateSenderFaultCode\n /// seem to take over the main 'faultcode' value in the SOAP 1.1 response, whereas in SOAP 1.2 the\n /// subCode is correctly put under the 'Code->SubCode->Value' value in the XML response.\n /// \n /// This workaround is to create the FaultCode with Sender/Receiver (SOAP 1.2 terms, but gets\n /// translated by WCF depending on the binding) and an agnostic namespace found by using reflector\n /// on the FaultCode class. When that NS is passed in WCF seems to be able to generate the proper\n /// response with SOAP 1.1 (Client/Server) and SOAP 1.2 (Sender/Receiver) fault codes automatically.\n /// \n /// This means that it is not possible to create a FaultCode that works in both bindings with\n /// subcodes.\n /// </summary>\n /// <remarks>\n /// See http://stackoverflow.com/questions/65008/net-wcf-faults-generating-incorrect-soap-11-faultcode-values\n /// for more details.\n /// </remarks>\n public static class FaultCodeFactory\n {\n private const string _ns = \"http://schemas.microsoft.com/ws/2005/05/envelope/none\";\n\n /// <summary>\n /// Creates a sender fault code.\n /// </summary>\n /// <returns>A FaultCode object.</returns>\n /// <remarks>Does not support subcodes due to a WCF bug.</remarks>\n public static FaultCode CreateSenderFaultCode()\n {\n return new FaultCode(\"Sender\", _ns);\n }\n\n /// <summary>\n /// Creates a receiver fault code.\n /// </summary>\n /// <returns>A FaultCode object.</returns>\n /// <remarks>Does not support subcodes due to a WCF bug.</remarks>\n public static FaultCode CreateReceiverFaultCode()\n {\n return new FaultCode(\"Receiver\", _ns);\n }\n }\n</code></pre>\n\n<p>Sadly I don't see a way to use subcodes without breaking either SOAP 1.1 or 1.2 clients. </p>\n\n<p>If you use the Code.SubCode syntax, you can create SOAP 1.1 compatible faultcode values but it breaks SOAP 1.2.</p>\n\n<p>If you use the proper subcode support in .NET (either via the static FaultCode methods or one of the overloads) it breaks SOAP 1.1 but works in SOAP 1.2.</p>\n"
},
{
"answer_id": 206822,
"author": "wojo",
"author_id": 9022,
"author_profile": "https://Stackoverflow.com/users/9022",
"pm_score": 3,
"selected": false,
"text": "<p>Response from Microsoft:</p>\n\n<p>As discussed in <a href=\"http://msdn.microsoft.com/en-us/library/ms789039.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms789039.aspx</a>, there are two methods outlined in the Soap 1.1 specification for custom fault codes:</p>\n\n<p>(1) Using the \"dot\" notation as you describe</p>\n\n<p>(2) Defining entirely new fault codes</p>\n\n<p>Unfortunately, the \"dot\" notation should be avoided, as it's use is discouraged in the WS-I Basic Profile specification. Essentially, this means that there is no real equivalent of the Soap 1.2 fault SubCode when using Soap 1.1.</p>\n\n<p>So, when generating faults, you'll have to be cognizant of the MessageVersion defined in the binding, and generate faultcodes accordingly.</p>\n\n<p>Since \"sender\" and \"receiver\" are not vaild fault codes for Soap 1.1, and there is no real equivalent of a fault subcode, you shouldn't use the CreateSenderFaultCode and CreateReceiverFaultCode methods when generating custom fault codes for Soap 1.1.</p>\n\n<p>Instead, you'll need to define your own faultcode, using your own namespace and name:</p>\n\n<p>FaultCode customFaultCode = new FaultCode(localName, faultNamespace);</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9022/"
]
| I am experimenting with using the FaultException and FaultException<T> to determine the best usage pattern in our applications. We need to support WCF as well as non-WCF service consumers/clients, including SOAP 1.1 and SOAP 1.2 clients.
FYI: using FaultExceptions with wsHttpBinding results in SOAP 1.2 semantics whereas using FaultExceptions with basicHttpBinding results in SOAP 1.1 semantics.
I am using the following code to throw a FaultException<FaultDetails>:
```
throw new FaultException<FaultDetails>(
new FaultDetails("Throwing FaultException<FaultDetails>."),
new FaultReason("Testing fault exceptions."),
FaultCode.CreateSenderFaultCode(new FaultCode("MySubFaultCode"))
);
```
The FaultDetails class is just a simple test class that contains a string "Message" property as you can see below.
When using wsHttpBinding the response is:
```
<?xml version="1.0" encoding="utf-16"?>
<Fault xmlns="http://www.w3.org/2003/05/soap-envelope">
<Code>
<Value>Sender</Value>
<Subcode>
<Value>MySubFaultCode</Value>
</Subcode>
</Code>
<Reason>
<Text xml:lang="en-US">Testing fault exceptions.</Text>
</Reason>
<Detail>
<FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Message>Throwing FaultException<FaultDetails>.</Message>
</FaultDetails>
</Detail>
```
This looks right according to the SOAP 1.2 specs. The main/root “Code” is “Sender”, which has a “Subcode” of “MySubFaultCode”. If the service consumer/client is using WCF the FaultException on the client side also mimics the same structure, with the faultException.Code.Name being “Sender” and faultException.Code.SubCode.Name being “MySubFaultCode”.
When using basicHttpBinding the response is:
```
<?xml version="1.0" encoding="utf-16"?>
<s:Fault xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>s:MySubFaultCode</faultcode>
<faultstring xml:lang="en-US">Testing fault exceptions.</faultstring>
<detail>
<FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Message>Throwing FaultException<FaultDetails>.</Message>
</FaultDetails>
</detail>
</s:Fault>
```
This does not look right. Looking at the SOAP 1.1 specs, I was expecting to see the “faultcode” to have a value of “s:Client.MySubFaultCode” when I use FaultCode.CreateSenderFaultCode(new FaultCode("MySubFaultCode")). Also a WCF client gets an incorrect structure. The faultException.Code.Name is “MySubFaultCode” instead of being “Sender”, and the faultException.Code.SubCode is null instead of faultException.Code.SubCode.Name being “MySubFaultCode”. Also, the faultException.Code.IsSenderFault is false.
Similar problem when using FaultCode.CreateReceiverFaultCode(new FaultCode("MySubFaultCode")):
* works as expected for SOAP 1.2
* generates “s:MySubFaultCode” instead of “s:Server.MySubFaultCode” and the faultException.Code.IsReceiverFault is false for SOAP 1.1
This item was also posted by someone else on <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=669420&SiteID=1> in 2006 and no one has answered it. I find it very hard to believe that no one has run into this, yet.
Here is someone else having a similar problem: <http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3883110&SiteID=1&mode=1>
Microsoft Connect bug: <https://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=367963>
Description of how faults should work: <http://blogs.msdn.com/drnick/archive/2006/12/19/creating-faults-part-3.aspx>
Am I doing something wrong or is this truly a bug in WCF? | This is my current workaround:
```
/// <summary>
/// Replacement for the static methods on FaultCode to generate Sender and Receiver fault codes due
/// to what seems like bugs in the implementation for basicHttpBinding (SOAP 1.1). wsHttpBinding
/// (SOAP 1.2) seems to work just fine.
///
/// The subCode parameter for FaultCode.CreateReceiverFaultCode and FaultCode.CreateSenderFaultCode
/// seem to take over the main 'faultcode' value in the SOAP 1.1 response, whereas in SOAP 1.2 the
/// subCode is correctly put under the 'Code->SubCode->Value' value in the XML response.
///
/// This workaround is to create the FaultCode with Sender/Receiver (SOAP 1.2 terms, but gets
/// translated by WCF depending on the binding) and an agnostic namespace found by using reflector
/// on the FaultCode class. When that NS is passed in WCF seems to be able to generate the proper
/// response with SOAP 1.1 (Client/Server) and SOAP 1.2 (Sender/Receiver) fault codes automatically.
///
/// This means that it is not possible to create a FaultCode that works in both bindings with
/// subcodes.
/// </summary>
/// <remarks>
/// See http://stackoverflow.com/questions/65008/net-wcf-faults-generating-incorrect-soap-11-faultcode-values
/// for more details.
/// </remarks>
public static class FaultCodeFactory
{
private const string _ns = "http://schemas.microsoft.com/ws/2005/05/envelope/none";
/// <summary>
/// Creates a sender fault code.
/// </summary>
/// <returns>A FaultCode object.</returns>
/// <remarks>Does not support subcodes due to a WCF bug.</remarks>
public static FaultCode CreateSenderFaultCode()
{
return new FaultCode("Sender", _ns);
}
/// <summary>
/// Creates a receiver fault code.
/// </summary>
/// <returns>A FaultCode object.</returns>
/// <remarks>Does not support subcodes due to a WCF bug.</remarks>
public static FaultCode CreateReceiverFaultCode()
{
return new FaultCode("Receiver", _ns);
}
}
```
Sadly I don't see a way to use subcodes without breaking either SOAP 1.1 or 1.2 clients.
If you use the Code.SubCode syntax, you can create SOAP 1.1 compatible faultcode values but it breaks SOAP 1.2.
If you use the proper subcode support in .NET (either via the static FaultCode methods or one of the overloads) it breaks SOAP 1.1 but works in SOAP 1.2. |
65,034 | <p>How would I remove the border from an iframe embedded in my web app? An example of the iframe is:</p>
<pre><code><iframe src="myURL" width="300" height="300">Browser not compatible.</iframe>
</code></pre>
<p>I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.</p>
| [
{
"answer_id": 65052,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 11,
"selected": true,
"text": "<p>Add the <code>frameBorder</code> attribute (note the <strong>capital ‘B’</strong>).</p>\n\n<p>So it would look like:</p>\n\n<pre><code><iframe src=\"myURL\" width=\"300\" height=\"300\" frameBorder=\"0\">Browser not compatible.</iframe>\n</code></pre>\n"
},
{
"answer_id": 65126,
"author": "xenox",
"author_id": 8952,
"author_profile": "https://Stackoverflow.com/users/8952",
"pm_score": 6,
"selected": false,
"text": "<p>In addition to adding the frameBorder attribute you might want to consider setting the scrolling attribute to \"no\" to prevent scrollbars from appearing. </p>\n\n<pre><code><iframe src=\"myURL\" width=\"300\" height=\"300\" frameBorder=\"0\" scrolling=\"no\">Browser not compatible. </iframe > \n</code></pre>\n"
},
{
"answer_id": 257406,
"author": "Adam",
"author_id": 33503,
"author_profile": "https://Stackoverflow.com/users/33503",
"pm_score": 7,
"selected": false,
"text": "<p>After going mad trying to remove the border in IE7, I found that the frameBorder attribute is case sensitive.</p>\n\n<p>You have to set the frameBorder attribute with a capital <strong>B</strong>.</p>\n\n<pre><code><iframe frameBorder=\"0\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 4861373,
"author": "Marnix Bras",
"author_id": 598204,
"author_profile": "https://Stackoverflow.com/users/598204",
"pm_score": 5,
"selected": false,
"text": "<p>For browser specific issues also add <code>frameborder=\"0\" hspace=\"0\" vspace=\"0\" marginheight=\"0\" marginwidth=\"0\"</code> according to Dreamweaver:</p>\n\n<pre><code><iframe src=\"test.html\" name=\"banner\" width=\"300\" marginwidth=\"0\" height=\"300\" marginheight=\"0\" align=\"top\" scrolling=\"No\" frameborder=\"0\" hspace=\"0\" vspace=\"0\">Browser not compatible. </iframe>\n</code></pre>\n"
},
{
"answer_id": 8437926,
"author": "Roberto Chiaretti",
"author_id": 1088611,
"author_profile": "https://Stackoverflow.com/users/1088611",
"pm_score": 7,
"selected": false,
"text": "<p>As per <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe\" rel=\"noreferrer\">iframe</a> documentation, frameBorder is deprecated and using the \"border\" CSS attribute is preferred:</p>\n\n<pre><code><iframe src=\"test.html\" style=\"width: 100%; height: 400px; border: 0\"></iframe>\n</code></pre>\n\n<ul>\n<li>Note CSS border property does <strong>not</strong> achieve the desired results in IE6, 7 or 8.</li>\n</ul>\n"
},
{
"answer_id": 8979112,
"author": "FirstFraktal",
"author_id": 1165845,
"author_profile": "https://Stackoverflow.com/users/1165845",
"pm_score": 3,
"selected": false,
"text": "<p>You can also do it with JavaScript this way. It will find any iframe elements and remove their borders in IE and other browsers (though you can just set a style of "border : none;" in non-IE browsers instead of using JavaScript). AND it will work even if used AFTER the iframe is generated and in place in the document (e.g. iframes that are added in plain HTML and not JavaScript)!</p>\n<p>This appears to work because IE creates the border, not on the iframe element as you'd expect, but on the CONTENT of the iframe--after the iframe is created in the BOM. ($@&*#@!!! IE!!!)</p>\n<p>Note: The IE part will only work (of course) if the parent window and iframe are from the SAME origin (same domain, port, protocol etc.). Otherwise the script will get "access denied" errors in the IE error console. If that happens, your only option is to set it before it is generated, as others have noted, or use the non-standard frameBorder="0" attribute. (or just let IE look fugly--my current favorite option ;) )</p>\n<p>Took me MANY hours of working to the point of despair to figure this out...</p>\n<p>Enjoy. :)</p>\n<pre><code>// =========================================================================\n// Remove borders on iFrames\n\nvar iFrameElements = window.document.getElementsByTagName("iframe");\nfor (var i = 0; i < iFrameElements.length; i++)\n{\n iFrameElements[i].frameBorder="0"; // For other browsers.\n iFrameElements[i].setAttribute("frameBorder", "0"); // For other browsers (just a backup for the above).\n iFrameElements[i].contentWindow.document.body.style.border="none"; // For IE.\n}\n</code></pre>\n"
},
{
"answer_id": 17451583,
"author": "David Tuite",
"author_id": 574190,
"author_profile": "https://Stackoverflow.com/users/574190",
"pm_score": 3,
"selected": false,
"text": "<p>If the doctype of the page you are placing the iframe on is HTML5 then you can use the <code>seamless</code> attribute like so:</p>\n\n<pre><code><iframe src=\"...\" seamless=\"seamless\"></iframe>\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe\" rel=\"noreferrer\">Mozilla docs on the seamless attribute</a></p>\n"
},
{
"answer_id": 21143344,
"author": "master of dissaster",
"author_id": 3199154,
"author_profile": "https://Stackoverflow.com/users/3199154",
"pm_score": -1,
"selected": false,
"text": "<pre><code>iframe src=\"XXXXXXXXXXXXXXX\"\nmarginwidth=\"0\" marginheight=\"0\" width=\"xxx\" height=\"xxx\"\n</code></pre>\n\n<p>Works with Firefox ;)</p>\n"
},
{
"answer_id": 24192742,
"author": "th0ward",
"author_id": 3415690,
"author_profile": "https://Stackoverflow.com/users/3415690",
"pm_score": 3,
"selected": false,
"text": "<p>I tried all of the above and if that doesn't work for you try the below CSS resolved the issue for me. Which just tells the browsers to not add any padding or margin. </p>\n\n<pre><code>* {\n padding:0px;\n margin:0px;\n }\n</code></pre>\n"
},
{
"answer_id": 24671048,
"author": "Shubham Badal",
"author_id": 2634872,
"author_profile": "https://Stackoverflow.com/users/2634872",
"pm_score": 3,
"selected": false,
"text": "<p>Use the HTML iframe frameborder Attribute</p>\n\n<p><a href=\"http://www.w3schools.com/tags/att_iframe_frameborder.asp\" rel=\"noreferrer\">http://www.w3schools.com/tags/att_iframe_frameborder.asp</a></p>\n\n<p>Note: use frame<strong>B</strong>order (cap B) for IE, otherwise will not work. But, the iframe frameborder attribute is not supported in HTML5. So, Use CSS instead.</p>\n\n<pre><code><iframe src=\"http://example.org\" width=\"200\" height=\"200\" style=\"border:0\">\n</code></pre>\n\n<p>you can also remove scrolling using scrolling attribute\n<a href=\"http://www.w3schools.com/tags/att_iframe_scrolling.asp\" rel=\"noreferrer\">http://www.w3schools.com/tags/att_iframe_scrolling.asp</a></p>\n\n<pre><code><iframe src=\"http://example.org\" width=\"200\" height=\"200\" scrolling=\"no\" style=\"border:0\">\n</code></pre>\n\n<p>Also you can use seamless attribute which is new in HTML5. The seamless attribute of the iframe tag is only supported in Opera, Chrome and Safari. When present, it specifies that the iframe should look like it is a part of the containing document (no borders or scrollbars). As of now, The seamless attribute of the tag is only supported in Opera, Chrome and Safari. But in near future it will be the standard solution and will be compatible with all browsers. <a href=\"http://www.w3schools.com/tags/att_iframe_seamless.asp\" rel=\"noreferrer\">http://www.w3schools.com/tags/att_iframe_seamless.asp</a></p>\n"
},
{
"answer_id": 28573794,
"author": "Tropilac",
"author_id": 4391687,
"author_profile": "https://Stackoverflow.com/users/4391687",
"pm_score": 3,
"selected": false,
"text": "<p>In your stylesheet add</p>\n\n<pre><code>{\n padding:0px;\n margin:0px;\n border: 0px\n\n}\n</code></pre>\n\n<p>This is also a viable option.</p>\n"
},
{
"answer_id": 33294377,
"author": "Shan Eapen Koshy",
"author_id": 3284379,
"author_profile": "https://Stackoverflow.com/users/3284379",
"pm_score": 4,
"selected": false,
"text": "<p>You can use <code>style=\"border:0;\"</code> in your iframe code. That is the recommended way to remove border in HTML5. </p>\n\n<p>Check out my <a href=\"http://codegena.com/generator/iframe-code-generator\" rel=\"noreferrer\">html5 iframe generator</a> tool to customize your iframe without editing code.</p>\n"
},
{
"answer_id": 36028076,
"author": "Harden Rahul",
"author_id": 4956341,
"author_profile": "https://Stackoverflow.com/users/4956341",
"pm_score": 3,
"selected": false,
"text": "<p>Add the frameBorder attribute (Capital ‘B’).</p>\n\n<pre><code><iframe src=\"myURL\" width=\"300\" height=\"300\" frameBorder=\"0\">Browser not compatible. </iframe>\n</code></pre>\n"
},
{
"answer_id": 38487002,
"author": "Michael Herr",
"author_id": 6614949,
"author_profile": "https://Stackoverflow.com/users/6614949",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using the iFrame to fit the width and height of the entire screen, which I am assuming you are not based on the 300x300 size, you must also set the body margins to \"0\" like this:</p>\n\n<pre><code><body style=\"margin:0px;\">\n</code></pre>\n"
},
{
"answer_id": 39307736,
"author": "IamGuest",
"author_id": 6790845,
"author_profile": "https://Stackoverflow.com/users/6790845",
"pm_score": 3,
"selected": false,
"text": "<pre><code><iframe src=\"mywebsite\" frameborder=\"0\" style=\"border: 0px solid white;\">HTML iFrame is not compatible with your browser</iframe>\n</code></pre>\n\n<p>This code should work in both HTML 4 and 5.</p>\n"
},
{
"answer_id": 41484926,
"author": "Ajesh Kolakkadan",
"author_id": 7271451,
"author_profile": "https://Stackoverflow.com/users/7271451",
"pm_score": 2,
"selected": false,
"text": "<p>also set border=\"0px \" </p>\n\n<pre><code> <iframe src=\"yoururl\" width=\"100%\" height=\"100%\" frameBorder=\"0\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 42175307,
"author": "Arpan Saini",
"author_id": 7353562,
"author_profile": "https://Stackoverflow.com/users/7353562",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Style property can be used</strong> \nFor HTML5 if you want to remove the boder of your frame or anything you can use the style property. as given below </p>\n\n<p>Code goes here</p>\n\n<pre><code><iframe src=\"demo.htm\" style=\"border:none;\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 44858921,
"author": "Amaan Iqbal",
"author_id": 8176563,
"author_profile": "https://Stackoverflow.com/users/8176563",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code><iframe src=\"url\" style=\"border:none;\"></iframe>\n</code></pre>\n\n<p>This will remove the border of your frame.</p>\n"
},
{
"answer_id": 45252756,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>To remove border you can use CSS border property to none.</p>\n\n<pre><code><iframe src=\"myURL\" width=\"300\" height=\"300\" style=\"border: none\">Browser not compatible.</iframe>\n</code></pre>\n"
},
{
"answer_id": 46261906,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Use this</p>\n\n<pre><code>style=\"border:none;\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code><iframe src=\"your.html\" style=\"border:none;\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 48166005,
"author": "Divya Chugh",
"author_id": 9192311,
"author_profile": "https://Stackoverflow.com/users/9192311",
"pm_score": 3,
"selected": false,
"text": "<p>Either add the frameBorder attribute, or use style with border-width 0px;, or set border style equal to none.</p>\n\n<p>use any one from below 3:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><iframe src=\"myURL\" width=\"300\" height=\"300\" style=\"border-width:0px;\">Browser not compatible.</iframe>\r\n\r\n<iframe src=\"myURL\" width=\"300\" height=\"300\" frameborder=\"0\">Browser not compatible.</iframe>\r\n\r\n<iframe src=\"myURL\" width=\"300\" height=\"300\" style=\"border:none;\">Browser not compatible.</iframe></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48856587,
"author": "Chetan Chauhan",
"author_id": 7570937,
"author_profile": "https://Stackoverflow.com/users/7570937",
"pm_score": 2,
"selected": false,
"text": "<p>Its simple just add attribute in iframe tag frameborder = 0 \n<code><iframe src=\"\" width=\"200\" height=\"200\" frameborder=\"0\"></iframe></code></p>\n"
},
{
"answer_id": 52228749,
"author": "Md Shahriar",
"author_id": 4211947,
"author_profile": "https://Stackoverflow.com/users/4211947",
"pm_score": -1,
"selected": false,
"text": "<pre><code><iframe src=\"URL\" frameborder=\"0\" width=\"100%\" height=\"200\">\n<p>Your browser does not support iframes.</p>\n</iframe>\n\n<iframe frameborder=\"1|0\">\n\n(OR)\n\n<iframe src=\"URL\" width=\"100%\" height=\"300\" style=\"border: none\">Your browser \ndoes not support iframes.</iframe>\n\nThe <iframe> frameborder attribute is not supported in HTML5. Use CSS \ninstead.\n</code></pre>\n"
},
{
"answer_id": 60167355,
"author": "Samir Lakhani",
"author_id": 6128516,
"author_profile": "https://Stackoverflow.com/users/6128516",
"pm_score": 2,
"selected": false,
"text": "<p><strong>1.Via Inline Style set border:0</strong></p>\n\n<pre><code> <iframe src=\"display_file.html\" style=\"height: 400px; width:\n 100%;border: 0;\">HTML iFrame is not compatible with your browser\n </iframe>\n</code></pre>\n\n<p><strong>2. Via Tag Attribute frameBorder Set 0</strong></p>\n\n<pre><code><iframe src=\"display_file.html\" width=\"300\" height=\"300\" frameborder=\"0\">Browser not compatible.</iframe>\n</code></pre>\n\n<p><strong>3. if We have multiple I Frame We can give class and Put css in internal or externally.</strong></p>\n\n<p><strong>HTML:</strong> </p>\n\n<pre><code><iframe src=\"display_file.html\" class=\"no_border_iframe\">\n HTML iFrame is not compatible with your browser \n</iframe>\n</code></pre>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code><style>\n.no_border_iframe{\nborder: 0; /* or border:none; */\n}\n</style>\n</code></pre>\n"
},
{
"answer_id": 60772418,
"author": "menepet",
"author_id": 3074131,
"author_profile": "https://Stackoverflow.com/users/3074131",
"pm_score": 0,
"selected": false,
"text": "<p>I had an issue with bottom white border and i could not fix it with border, margin & padding rules ... So add <code>display:block;</code> because iframe is an inline element.</p>\n\n<p>This takes whitespace in your HTML into account.</p>\n"
},
{
"answer_id": 70296032,
"author": "Japi Sandhu",
"author_id": 7989522,
"author_profile": "https://Stackoverflow.com/users/7989522",
"pm_score": 2,
"selected": false,
"text": "<p>for me, adding worked perfectly</p>\n<pre class=\"lang-css prettyprint-override\"><code>.iframe{\nbox-shadow: none !important;\n}\n</code></pre>\n<p>this solution is particularly for a shopify theme I am editing. The shopify theme uses iframes in different ways throughout the whole theme and one of them glitched. I had to go into the css manually and overide the css attribute.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2650/"
]
| How would I remove the border from an iframe embedded in my web app? An example of the iframe is:
```
<iframe src="myURL" width="300" height="300">Browser not compatible.</iframe>
```
I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help. | Add the `frameBorder` attribute (note the **capital ‘B’**).
So it would look like:
```
<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>
``` |
65,035 | <p>Considering this code, can I be <em>absolutely sure</em> that the <code>finally</code> block always executes, no matter what <code>something()</code> is?</p>
<pre><code>try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
</code></pre>
| [
{
"answer_id": 65049,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 13,
"selected": true,
"text": "<p>Yes, <code>finally</code> will be called after the execution of the <code>try</code> or <code>catch</code> code blocks.</p>\n\n<p>The only times <code>finally</code> won't be called are:</p>\n\n<ol>\n<li>If you invoke <code>System.exit()</code></li>\n<li>If you invoke <code>Runtime.getRuntime().halt(exitStatus)</code></li>\n<li>If the JVM crashes first</li>\n<li>If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the <code>try</code> or <code>catch</code> block</li>\n<li>If the OS forcibly terminates the JVM process; e.g., <code>kill -9 <pid></code> on UNIX</li>\n<li>If the host system dies; e.g., power failure, hardware error, OS panic, et cetera</li>\n<li>If the <code>finally</code> block is going to be executed by a daemon thread and all other non-daemon threads exit before <code>finally</code> is called</li>\n</ol>\n"
},
{
"answer_id": 65056,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 4,
"selected": false,
"text": "<p>finally is always executed unless there is abnormal program termination (like calling System.exit(0)..). so, your sysout will get printed</p>\n"
},
{
"answer_id": 65059,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 3,
"selected": false,
"text": "<p>Yes it will get called. That's the whole point of having a finally keyword. If jumping out of the try/catch block could just skip the finally block it was the same as putting the System.out.println outside the try/catch.</p>\n"
},
{
"answer_id": 65185,
"author": "Kevin",
"author_id": 1058366,
"author_profile": "https://Stackoverflow.com/users/1058366",
"pm_score": 9,
"selected": false,
"text": "<p>Example code:</p>\n<pre><code>public static void main(String[] args) {\n System.out.println(Test.test());\n}\n\npublic static int test() {\n try {\n return 0;\n }\n finally {\n System.out.println("something is printed");\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>something is printed. \n0\n</code></pre>\n"
},
{
"answer_id": 65219,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": false,
"text": "<p>That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.</p>\n"
},
{
"answer_id": 65282,
"author": "user9189",
"author_id": 9189,
"author_profile": "https://Stackoverflow.com/users/9189",
"pm_score": 4,
"selected": false,
"text": "<p>The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to <code>System.exit(0)</code>.</p>\n\n<p>On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.</p>\n"
},
{
"answer_id": 65362,
"author": "MooBob42",
"author_id": 9271,
"author_profile": "https://Stackoverflow.com/users/9271",
"pm_score": 9,
"selected": false,
"text": "<p>Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:</p>\n\n<pre><code>try { return true; } finally { return false; }\n</code></pre>\n\n<p>Same thing with throwing exceptions from the finally block.</p>\n"
},
{
"answer_id": 65943,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 4,
"selected": false,
"text": "<p>Also a return in finally will throw away any exception. <a href=\"http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html\" rel=\"noreferrer\">http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html</a></p>\n"
},
{
"answer_id": 65949,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 5,
"selected": false,
"text": "<p>A logical way to think about this is:</p>\n\n<ol>\n<li>Code placed in a finally block must be executed <strong>whatever occurs</strong> within the try block</li>\n<li>So if code in the try block tries to return a value or throw an exception the item is placed 'on the shelf' till the finally block can execute</li>\n<li>Because code in the finally block has (by definition) a high priority it can return or throw whatever it likes. In which case anything left 'on the shelf' is discarded.</li>\n<li>The only exception to this is if the VM shuts down completely during the try block e.g. by 'System.exit'</li>\n</ol>\n"
},
{
"answer_id": 158141,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the point about return in finally replacing a return in the try block, the same is true of an exception. A finally block that throws an exception will replace a return or exception thrown from within the try block.</p>\n"
},
{
"answer_id": 296053,
"author": "vibhash",
"author_id": 38266,
"author_profile": "https://Stackoverflow.com/users/38266",
"pm_score": 7,
"selected": false,
"text": "<p>I tried the above example with slight modification-</p>\n\n<pre><code>public static void main(final String[] args) {\n System.out.println(test());\n}\n\npublic static int test() {\n int i = 0;\n try {\n i = 2;\n return i;\n } finally {\n i = 12;\n System.out.println(\"finally trumps return.\");\n }\n}\n</code></pre>\n\n<p>The above code outputs:</p>\n\n<blockquote>\n <p>finally trumps return.<br>\n 2</p>\n</blockquote>\n\n<p>This is because when <code>return i;</code> is executed <code>i</code> has a value 2. After this the <code>finally</code> block is executed where 12 is assigned to <code>i</code> and then <code>System.out</code> out is executed.</p>\n\n<p>After executing the <code>finally</code> block the <code>try</code> block returns 2, rather than returning 12, because this return statement is not executed again.</p>\n\n<p>If you will debug this code in Eclipse then you'll get a feeling that after executing <code>System.out</code> of <code>finally</code> block the <code>return</code> statement of <code>try</code> block is executed again. But this is not the case. It simply returns the value 2.</p>\n"
},
{
"answer_id": 2824754,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 4,
"selected": false,
"text": "<p>Finally is always run that's the whole point, just because it appears in the code after the return doesn't mean that that's how it's implemented. The Java runtime has the responsibility to run this code when exiting the <code>try</code> block.</p>\n\n<p>For example if you have the following:</p>\n\n<pre><code>int foo() { \n try {\n return 42;\n }\n finally {\n System.out.println(\"done\");\n }\n}\n</code></pre>\n\n<p>The runtime will generate something like this:</p>\n\n<pre><code>int foo() {\n int ret = 42;\n System.out.println(\"done\");\n return 42;\n}\n</code></pre>\n\n<p>If an uncaught exception is thrown the <code>finally</code> block will run and the exception will continue propagating. </p>\n"
},
{
"answer_id": 2824758,
"author": "Jay Riggs",
"author_id": 52249,
"author_profile": "https://Stackoverflow.com/users/52249",
"pm_score": 3,
"selected": false,
"text": "<p>Because a finally block will always be called unless you call <code>System.exit()</code> (or the thread crashes).</p>\n"
},
{
"answer_id": 2824759,
"author": "Chris Cooper",
"author_id": 300807,
"author_profile": "https://Stackoverflow.com/users/300807",
"pm_score": 6,
"selected": false,
"text": "<p>That is the whole idea of a finally block. It lets you make sure you do cleanups that might otherwise be skipped because you return, among other things, of course.</p>\n\n<p>Finally gets called <strong>regardless of what happens</strong> in the try block (<em>unless</em> you call <code>System.exit(int)</code> or the Java Virtual Machine kicks out for some other reason).</p>\n"
},
{
"answer_id": 2824762,
"author": "vodkhang",
"author_id": 227698,
"author_profile": "https://Stackoverflow.com/users/227698",
"pm_score": 2,
"selected": false,
"text": "<p>Because the final is always be called in whatever cases you have. You don't have exception, it is still called, catch exception, it is still called</p>\n"
},
{
"answer_id": 2824998,
"author": "Eyal Schneider",
"author_id": 196211,
"author_profile": "https://Stackoverflow.com/users/196211",
"pm_score": 7,
"selected": false,
"text": "<p>In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:</p>\n\n<pre><code>public static int getMonthsInYear() {\n try {\n return 10;\n }\n finally {\n return 12;\n }\n}\n</code></pre>\n\n<p>Similarly, the following method does not throw an exception:</p>\n\n<pre><code>public static int getMonthsInYear() {\n try {\n throw new RuntimeException();\n }\n finally {\n return 12;\n }\n}\n</code></pre>\n\n<p>While the following method does throw it:</p>\n\n<pre><code>public static int getMonthsInYear() {\n try {\n return 12; \n }\n finally {\n throw new RuntimeException();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2826472,
"author": "Gala101",
"author_id": 338082,
"author_profile": "https://Stackoverflow.com/users/338082",
"pm_score": 2,
"selected": false,
"text": "<p>Consider this in a normal course of execution (i.e without any Exception being thrown): if method is not 'void' then it always explicitly returns something, yet, finally always gets executed</p>\n"
},
{
"answer_id": 2902505,
"author": "Wasim",
"author_id": 349636,
"author_profile": "https://Stackoverflow.com/users/349636",
"pm_score": 3,
"selected": false,
"text": "<p>This is because you assigned the value of i as 12, but did not return the value of i to the function. The correct code is as follows:</p>\n\n<pre><code>public static int test() {\n int i = 0;\n try {\n return i;\n } finally {\n i = 12;\n System.out.println(\"finally trumps return.\");\n return i;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2902578,
"author": "polygenelubricants",
"author_id": 276101,
"author_profile": "https://Stackoverflow.com/users/276101",
"pm_score": 8,
"selected": false,
"text": "<p>Here's the official words from the Java Language Specification.</p>\n\n<p><a href=\"https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2\" rel=\"noreferrer\">14.20.2. Execution of try-finally and try-catch-finally</a></p>\n\n<blockquote>\n <p><strong>A <code>try</code> statement with a <code>finally</code> block is executed by first executing the <code>try</code> block. Then there is a choice:</strong></p>\n \n <ul>\n <li>If execution of the <code>try</code> block completes normally, [...]</li>\n <li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <em>V</em>, [...]</li>\n <li><strong>If execution of the <code>try</code> block completes abruptly for any other reason <em>R</em>, then the <code>finally</code> block is executed. Then there is a choice:</strong>\n \n <ul>\n <li>If the finally block completes normally, then the <code>try</code> statement completes abruptly for reason <em>R</em>. </li>\n <li>If the <code>finally</code> block completes abruptly for reason <em>S</em>, then the <code>try</code> statement completes abruptly for reason <em>S</em> (<strong>and reason <em>R</em> is discarded</strong>).</li>\n </ul></li>\n </ul>\n</blockquote>\n\n<p>The specification for <code>return</code> actually makes this explicit:</p>\n\n<p><a href=\"https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.17\" rel=\"noreferrer\">JLS 14.17 The return Statement</a></p>\n\n<blockquote>\n<pre><code>ReturnStatement:\n return Expression(opt) ;\n</code></pre>\n \n <p>A <code>return</code> statement with no <code>Expression</code> <strong>attempts</strong> to transfer control to the invoker of the method or constructor that contains it. </p>\n \n <p>A <code>return</code> statement with an <code>Expression</code> <strong>attempts</strong> to transfer control to the invoker of the method that contains it; the value of the <code>Expression</code> becomes the value of the method invocation.</p>\n \n <p>The preceding descriptions say \"<em><strong>attempts</strong> to transfer control</em>\" rather than just \"<em>transfers control</em>\" because if there are any <code>try</code> statements within the method or constructor whose <code>try</code> blocks contain the <code>return</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>return</code> statement.</p>\n</blockquote>\n"
},
{
"answer_id": 7756997,
"author": "Bhushan",
"author_id": 645226,
"author_profile": "https://Stackoverflow.com/users/645226",
"pm_score": 3,
"selected": false,
"text": "<p>If an exception is thrown, finally runs. If an exception is not thrown, finally runs. If the exception is caught, finally runs. If the exception is not caught, finally runs.</p>\n\n<p>Only time it does not run is when JVM exits.</p>\n"
},
{
"answer_id": 10188271,
"author": "eric2323223",
"author_id": 44512,
"author_profile": "https://Stackoverflow.com/users/44512",
"pm_score": 2,
"selected": false,
"text": "<p>Try this code, you will understand the <strong>code in finally block is get executed after return statement</strong>.</p>\n\n<pre><code>public class TestTryCatchFinally {\n static int x = 0;\n\n public static void main(String[] args){\n System.out.println(f1() );\n System.out.println(f2() );\n }\n\n public static int f1(){\n try{\n x = 1;\n return x;\n }finally{\n x = 2;\n }\n }\n\n public static int f2(){\n return x;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17634958,
"author": "Rajendra Jadi",
"author_id": 2287871,
"author_profile": "https://Stackoverflow.com/users/2287871",
"pm_score": 4,
"selected": false,
"text": "<p>No, not always one exception case is//\nSystem.exit(0);\nbefore the finally block prevents finally to be executed.</p>\n\n<pre><code> class A {\n public static void main(String args[]){\n DataInputStream cin = new DataInputStream(System.in);\n try{\n int i=Integer.parseInt(cin.readLine());\n }catch(ArithmeticException e){\n }catch(Exception e){\n System.exit(0);//Program terminates before executing finally block\n }finally{\n System.out.println(\"Won't be executed\");\n System.out.println(\"No error\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18272854,
"author": "Karthikeyan",
"author_id": 1927543,
"author_profile": "https://Stackoverflow.com/users/1927543",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it will. No matter what happens in your try or catch block unless otherwise System.exit() called or JVM crashed. if there is any return statement in the block(s),finally will be executed prior to that return statement.</p>\n"
},
{
"answer_id": 20363941,
"author": "WoodenKitty",
"author_id": 2684342,
"author_profile": "https://Stackoverflow.com/users/2684342",
"pm_score": 7,
"selected": false,
"text": "<p>Here's an elaboration of <a href=\"https://stackoverflow.com/a/65185/2684342\">Kevin's answer</a>. It's important to know that the expression to be returned is evaluated before <code>finally</code>, even if it is returned after.</p>\n<pre><code>public static void main(String[] args) {\n System.out.println(Test.test());\n}\n\npublic static int printX() {\n System.out.println("X");\n return 0;\n}\n\npublic static int test() {\n try {\n return printX();\n }\n finally {\n System.out.println("finally trumps return... sort of");\n return 42;\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>X\nfinally trumps return... sort of\n42\n</code></pre>\n"
},
{
"answer_id": 21125379,
"author": "abhig",
"author_id": 1596606,
"author_profile": "https://Stackoverflow.com/users/1596606",
"pm_score": 3,
"selected": false,
"text": "<p>Yes It will.\nOnly case it will not is JVM exits or crashes </p>\n"
},
{
"answer_id": 21824431,
"author": "Rohit Chugh",
"author_id": 3317784,
"author_profile": "https://Stackoverflow.com/users/3317784",
"pm_score": 2,
"selected": false,
"text": "<p>Finally block always execute whether exception handle or not .if any exception occurred before try block then finally block will not execute.</p>\n"
},
{
"answer_id": 26349456,
"author": "bikz05",
"author_id": 3149356,
"author_profile": "https://Stackoverflow.com/users/3149356",
"pm_score": 3,
"selected": false,
"text": "<p>Concisely, in the official Java Documentation (Click <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html\" rel=\"noreferrer\">here</a>), it is written that - </p>\n\n<blockquote>\n <p>If the JVM exits while the try or catch code is being executed, then\n the finally block may not execute. Likewise, if the thread executing\n the try or catch code is interrupted or killed, the finally block may\n not execute even though the application as a whole continues.</p>\n</blockquote>\n"
},
{
"answer_id": 27249545,
"author": "Gautam Viradiya",
"author_id": 4315585,
"author_profile": "https://Stackoverflow.com/users/4315585",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, finally block is always execute. Most of developer use this block the closing the database connection, resultset object, statement object and also uses into the java hibernate to rollback the transaction.</p>\n"
},
{
"answer_id": 27540550,
"author": "Utkarsh Bhatt",
"author_id": 3201107,
"author_profile": "https://Stackoverflow.com/users/3201107",
"pm_score": 3,
"selected": false,
"text": "<p><code>finally</code> will execute and that is for sure.</p>\n\n<p><code>finally</code> will not execute in below cases: </p>\n\n<p>case 1 :</p>\n\n<p>When you are executing <code>System.exit()</code>.</p>\n\n<p>case 2 :</p>\n\n<p>When your JVM / Thread crashes.</p>\n\n<p>case 3 : </p>\n\n<p>When your execution is stopped in between manually.</p>\n"
},
{
"answer_id": 30213111,
"author": "milton",
"author_id": 873900,
"author_profile": "https://Stackoverflow.com/users/873900",
"pm_score": 3,
"selected": false,
"text": "<p>I was very confused with all the answers provided on different forums and decided to finally code and see. The ouput is :</p>\n<p><strong>finally will be executed even if there is return in try and catch block.</strong></p>\n<pre><code>try { \n System.out.println("try"); \n return;\n //int i =5/0;\n //System.exit(0 ) ;\n} catch (Exception e) { \n System.out.println("catch");\n return;\n //int i =5/0;\n //System.exit(0 ) ;\n} finally { \n System.out.println("Print me FINALLY");\n}\n</code></pre>\n<p><strong>Output</strong></p>\n<blockquote>\n<p>try</p>\n<p>Print me FINALLY</p>\n</blockquote>\n<ol start=\"2\">\n<li>If return is replaced by <code>System.exit(0)</code> in try and catch block in above code and an exception occurs before it,for any reason.</li>\n</ol>\n"
},
{
"answer_id": 34240980,
"author": "Anonymous Coward",
"author_id": 956880,
"author_profile": "https://Stackoverflow.com/users/956880",
"pm_score": 4,
"selected": false,
"text": "<h1>NOT ALWAYS</h1>\n\n<p>The Java Language specification describes how <code>try</code>-<code>catch</code>-<code>finally</code> and <code>try</code>-<code>catch</code> blocks work at <a href=\"https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2\" rel=\"nofollow noreferrer\">14.20.2</a><br>\nIn no place it specifies that the <code>finally</code> block is always executed.\nBut for all cases in which the <code>try</code>-<code>catch</code>-<code>finally</code> and <code>try</code>-<code>finally</code> blocks complete it does specify that before completion <code>finally</code> must be executed.</p>\n\n<pre><code>try {\n CODE inside the try block\n}\nfinally {\n FIN code inside finally block\n}\nNEXT code executed after the try-finally block (may be in a different method).\n</code></pre>\n\n<p>The JLS does not guarantee that <strong>FIN</strong> is executed after <strong>CODE</strong>.\nThe JLS guarantees that if <strong>CODE</strong> and <strong>NEXT</strong> are executed then <strong>FIN</strong> will always be executed after <strong>CODE</strong> and before <strong>NEXT</strong>.</p>\n\n<p>Why doesn't the JLS guarantee that the <code>finally</code> block is always executed after the <code>try</code> block? <em>Because it is impossible.</em> It is unlikely but possible that the JVM will be aborted (kill, crash, power off) just after completing the <code>try</code> block but before execution of the <code>finally</code> block. There is nothing the JLS can do to avoid this.</p>\n\n<p>Thus, any software which for their proper behaviour depends on <code>finally</code> blocks always being executed after their <code>try</code> blocks complete are bugged.</p>\n\n<p><code>return</code> instructions in the <code>try</code> block are irrelevant to this issue. If execution reaches code after the <code>try</code>-<code>catch</code>-<code>finally</code> it is guaranteed that the <code>finally</code> block will have been executed before, with or without <code>return</code> instructions inside the <code>try</code> block.</p>\n"
},
{
"answer_id": 36116269,
"author": "dkb",
"author_id": 2987755,
"author_profile": "https://Stackoverflow.com/users/2987755",
"pm_score": 3,
"selected": false,
"text": "<p>I tried this,\nIt is single threaded.</p>\n\n<pre><code>public static void main(String args[]) throws Exception {\n Object obj = new Object();\n try {\n synchronized (obj) {\n obj.wait();\n System.out.println(\"after wait()\");\n }\n } catch (Exception ignored) {\n } finally {\n System.out.println(\"finally\");\n }\n}\n</code></pre>\n\n<p>The <code>main</code> <code>Thread</code> will be on <code>wait</code> state forever, hence <em><code>finally</code> will never be called</em>,</p>\n\n<p>so console output will not <code>print</code> <code>String</code>: after <code>wait()</code> or <code>finally</code></p>\n\n<p>Agreed with @Stephen C, the above example is one of the 3rd case mention <a href=\"https://stackoverflow.com/a/65049/2987755\">here</a>:</p>\n\n<p>Adding some more such infinite loop possibilities in following code:</p>\n\n<pre><code>// import java.util.concurrent.Semaphore;\n\npublic static void main(String[] args) {\n try {\n // Thread.sleep(Long.MAX_VALUE);\n // Thread.currentThread().join();\n // new Semaphore(0).acquire();\n // while (true){}\n System.out.println(\"after sleep join semaphore exit infinite while loop\");\n } catch (Exception ignored) {\n } finally {\n System.out.println(\"finally\");\n }\n}\n</code></pre>\n\n<p>Case 2: If the JVM crashes first</p>\n\n<pre><code>import sun.misc.Unsafe;\nimport java.lang.reflect.Field;\n\npublic static void main(String args[]) {\n try {\n unsafeMethod();\n //Runtime.getRuntime().halt(123);\n System.out.println(\"After Jvm Crash!\");\n } catch (Exception e) {\n } finally {\n System.out.println(\"finally\");\n }\n}\n\nprivate static void unsafeMethod() throws NoSuchFieldException, IllegalAccessException {\n Field f = Unsafe.class.getDeclaredField(\"theUnsafe\");\n f.setAccessible(true);\n Unsafe unsafe = (Unsafe) f.get(null);\n unsafe.putAddress(0, 0);\n}\n</code></pre>\n\n<p>Ref: <a href=\"https://stackoverflow.com/q/65200/2987755\">How do you crash a JVM?</a></p>\n\n<p>Case 6: If <code>finally</code> block is going to be executed by daemon <code>Thread</code> and all other non-daemon <code>Threads</code> exit before <code>finally</code> is called.</p>\n\n<pre><code>public static void main(String args[]) {\n Runnable runnable = new Runnable() {\n @Override\n public void run() {\n try {\n printThreads(\"Daemon Thread printing\");\n // just to ensure this thread will live longer than main thread\n Thread.sleep(10000);\n } catch (Exception e) {\n } finally {\n System.out.println(\"finally\");\n }\n }\n };\n Thread daemonThread = new Thread(runnable);\n daemonThread.setDaemon(Boolean.TRUE);\n daemonThread.setName(\"My Daemon Thread\");\n daemonThread.start();\n printThreads(\"main Thread Printing\");\n}\n\nprivate static synchronized void printThreads(String str) {\n System.out.println(str);\n int threadCount = 0;\n Set<Thread> threadSet = Thread.getAllStackTraces().keySet();\n for (Thread t : threadSet) {\n if (t.getThreadGroup() == Thread.currentThread().getThreadGroup()) {\n System.out.println(\"Thread :\" + t + \":\" + \"state:\" + t.getState());\n ++threadCount;\n }\n }\n System.out.println(\"Thread count started by Main thread:\" + threadCount);\n System.out.println(\"-------------------------------------------------\");\n}\n</code></pre>\n\n<p>output: This does not print \"finally\" which implies \"Finally block\" in \"daemon thread\" did not execute </p>\n\n<blockquote>\n<pre><code>main Thread Printing \nThread :Thread[My Daemon Thread,5,main]:state:BLOCKED \nThread :Thread[main,5,main]:state:RUNNABLE \nThread :Thread[Monitor Ctrl-Break,5,main]:state:RUNNABLE \nThread count started by Main thread:3 \n------------------------------------------------- \nDaemon Thread printing \nThread :Thread[My Daemon Thread,5,main]:state:RUNNABLE \nThread :Thread[Monitor Ctrl-Break,5,main]:state:RUNNABLE \nThread count started by Main thread:2 \n------------------------------------------------- \n\nProcess finished with exit code 0\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 36926373,
"author": "HopefullyHelpful",
"author_id": 5191731,
"author_profile": "https://Stackoverflow.com/users/5191731",
"pm_score": 2,
"selected": false,
"text": "<p><code>finally</code> can also be exited prematurely if an <code>Exception</code> is <code>throw</code>n inside a <em>nested <code>finally</code> block</em>. The compiler will warn you that the <code>finally</code> block does not complete normally or give an error that you have unreachable code. The error for unreachable code will be shown only if the <code>throw</code> is not behind a conditional statement or inside a loop.</p>\n\n<pre><code>try{\n}finally{\n try{\n }finally{\n //if(someCondition) --> no error because of unreachable code\n throw new RunTimeException();\n }\n int a = 5;//unreachable code\n}\n</code></pre>\n"
},
{
"answer_id": 38187529,
"author": "dibo",
"author_id": 6547976,
"author_profile": "https://Stackoverflow.com/users/6547976",
"pm_score": 2,
"selected": false,
"text": "<p>Same with the following code:</p>\n\n<pre><code>static int f() {\n while (true) {\n try {\n return 1;\n } finally {\n break;\n }\n }\n return 2;\n}\n</code></pre>\n\n<p>f will return 2!</p>\n"
},
{
"answer_id": 38930134,
"author": "Meet Vora",
"author_id": 5373110,
"author_profile": "https://Stackoverflow.com/users/5373110",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Answer is simple <strong>YES</strong>.</p>\n</blockquote>\n\n<p><strong>INPUT:</strong></p>\n\n<pre><code>try{\n int divideByZeroException = 5 / 0;\n} catch (Exception e){\n System.out.println(\"catch\");\n return; // also tried with break; in switch-case, got same output\n} finally {\n System.out.println(\"finally\");\n}\n</code></pre>\n\n<p><strong>OUTPUT:</strong></p>\n\n<pre><code>catch\nfinally\n</code></pre>\n"
},
{
"answer_id": 39462828,
"author": "Akash Manngroliya",
"author_id": 5089473,
"author_profile": "https://Stackoverflow.com/users/5089473",
"pm_score": 2,
"selected": false,
"text": "<p>Yes it will always called but in one situation it not call when you use System.exit()</p>\n\n<pre><code>try{\n//risky code\n}catch(Exception e){\n//exception handling code\n}\nfinally(){\n//It always execute but before this block if there is any statement like System.exit(0); then this block not execute.\n}\n</code></pre>\n"
},
{
"answer_id": 44085757,
"author": "Avinash Pande",
"author_id": 4295595,
"author_profile": "https://Stackoverflow.com/users/4295595",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>Finally Block always get executed. Unless and until\n<strong>System.exit()</strong> statement exists there (first statement in finally block).</li>\n<li>If <strong>system.exit()</strong> is first statement then finally block won't get executed and control come out of the finally block.\nWhenever System.exit() statement gets in finally block till that statement finally block executed and when System.exit() appears then control force fully come out of the finally block.</li>\n</ol>\n"
},
{
"answer_id": 44436111,
"author": "Vikas Suryawanshi",
"author_id": 7504001,
"author_profile": "https://Stackoverflow.com/users/7504001",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't handle exception, before terminating the program, JVM executes finally block. It will not executed only if normal execution of program will fail mean's termination of program due to these following reasons..</p>\n\n<ol>\n<li><p>By causing a fatal error that causes the process to abort.</p></li>\n<li><p>Termination of program due to memory corrupt.</p></li>\n<li><p>By calling System.exit()</p></li>\n<li><p>If program goes into infinity loop.</p></li>\n</ol>\n"
},
{
"answer_id": 47198461,
"author": "Sandip Solanki",
"author_id": 6826372,
"author_profile": "https://Stackoverflow.com/users/6826372",
"pm_score": 3,
"selected": false,
"text": "<p>The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.</p>\n\n<p>Let me try to answer your question in the easiest possible way.</p>\n\n<p><strong>Rule 1</strong> : The finally block always run\n (Though there are exceptions to it. But let's stick to this for sometime.)</p>\n\n<p><strong>Rule 2</strong> : the statements in the finally block run when control leaves a try or a catch block.The transfer of control can occur as a result of normal execution ,of execution of a break , continue, goto or a return statement, or of a propogation of an exception.</p>\n\n<p>In case of a return statement specifically (since its captioned), the control has to leave the calling method , And hence calls the finally block of the corresponding try-finally structure. The return statement is executed after the finally block.</p>\n\n<p>In case there's a return statement in the finally block also, it will definitely override the one pending at the try block , since its clearing the call stack.</p>\n\n<p>You can refer a better explanation here : <a href=\"http://msdn.microsoft.com/en-us/\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/</a>.... the concept is mostly same in all the high level languages.</p>\n"
},
{
"answer_id": 47847227,
"author": "Dávid Horváth",
"author_id": 3948862,
"author_profile": "https://Stackoverflow.com/users/3948862",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, because <strong>no control statement</strong> can prevent <code>finally</code> from being executed.</p>\n\n<p>Here is a reference example, where all code blocks will be executed:</p>\n\n<pre><code>| x | Current result | Code \n|---|----------------|------ - - -\n| | | \n| | | public static int finallyTest() {\n| 3 | | int x = 3;\n| | | try {\n| | | try {\n| 4 | | x++;\n| 4 | return 4 | return x;\n| | | } finally {\n| 3 | | x--;\n| 3 | throw | throw new RuntimeException(\"Ahh!\");\n| | | }\n| | | } catch (RuntimeException e) {\n| 4 | return 4 | return ++x;\n| | | } finally {\n| 3 | | x--;\n| | | }\n| | | }\n| | |\n|---|----------------|------ - - -\n| | Result: 4 |\n</code></pre>\n\n<p>In the variant below, <code>return x;</code> will be skipped. Result is still <code>4</code>:</p>\n\n<pre><code>public static int finallyTest() {\n int x = 3;\n try {\n try {\n x++;\n if (true) throw new RuntimeException(\"Ahh!\");\n return x; // skipped\n } finally {\n x--;\n }\n } catch (RuntimeException e) {\n return ++x;\n } finally {\n x--;\n }\n}\n</code></pre>\n\n<p>References, of course, track their status. This example returns a reference with <code>value = 4</code>:</p>\n\n<pre><code>static class IntRef { public int value; }\npublic static IntRef finallyTest() {\n IntRef x = new IntRef();\n x.value = 3;\n try {\n return x;\n } finally {\n x.value++; // will be tracked even after return\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49614632,
"author": "Danail Tsvetanov",
"author_id": 5635466,
"author_profile": "https://Stackoverflow.com/users/5635466",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, it is written <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html\" rel=\"noreferrer\">here</a></p>\n\n<blockquote>\n <p>If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.</p>\n</blockquote>\n"
},
{
"answer_id": 49752573,
"author": "Pradeep Kumaresan",
"author_id": 2851699,
"author_profile": "https://Stackoverflow.com/users/2851699",
"pm_score": 3,
"selected": false,
"text": "<p>Adding to <a href=\"https://stackoverflow.com/a/296053/4298200\">@vibhash's answer</a> as no other answer explains what happens in the case of a mutable object like the one below.</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(test().toString());\n}\n\npublic static StringBuffer test() {\n StringBuffer s = new StringBuffer();\n try {\n s.append(\"sb\");\n return s;\n } finally {\n s.append(\"updated \");\n }\n}\n</code></pre>\n\n<p>Will output</p>\n\n<blockquote>\n<pre><code>sbupdated \n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 49850492,
"author": "Poorna Senani Gamage",
"author_id": 8111997,
"author_profile": "https://Stackoverflow.com/users/8111997",
"pm_score": 3,
"selected": false,
"text": "<p><code>try</code>- <code>catch</code>- <code>finally</code> are the key words for using exception handling case.<br> \nAs normal explanotory</p>\n\n<pre><code>try {\n //code statements\n //exception thrown here\n //lines not reached if exception thrown\n} catch (Exception e) {\n //lines reached only when exception is thrown\n} finally {\n // always executed when the try block is exited\n //independent of an exception thrown or not\n}\n</code></pre>\n\n<p>The finally block prevent executing...</p>\n\n<ul>\n<li>When you called <code>System.exit(0);</code></li>\n<li>If JVM exits.</li>\n<li>Errors in the JVM</li>\n</ul>\n"
},
{
"answer_id": 49951065,
"author": "aliceangel",
"author_id": 6706261,
"author_profile": "https://Stackoverflow.com/users/6706261",
"pm_score": 2,
"selected": false,
"text": "<p>finally block is executed always even if you put a return statement in the try block. The finally block will be executed before the return statement.</p>\n"
},
{
"answer_id": 50096809,
"author": "sam",
"author_id": 7538821,
"author_profile": "https://Stackoverflow.com/users/7538821",
"pm_score": 3,
"selected": false,
"text": "<p>Consider the following program:</p>\n\n<pre><code>public class SomeTest {\n\n private static StringBuilder sb = new StringBuilder();\n\n public static void main(String args[]) {\n\n System.out.println(someString());\n System.out.println(\"---AGAIN---\");\n System.out.println(someString());\n System.out.println(\"---PRINT THE RESULT---\");\n System.out.println(sb.toString());\n }\n\n private static String someString() {\n\n try {\n sb.append(\"-abc-\");\n return sb.toString();\n\n } finally {\n sb.append(\"xyz\");\n }\n }\n}\n</code></pre>\n\n<p>As of Java 1.8.162, the above code block gives the following output:</p>\n\n<pre><code>-abc-\n---AGAIN---\n-abc-xyz-abc-\n---PRINT THE RESULT---\n-abc-xyz-abc-xyz\n</code></pre>\n\n<p>this means that using <code>finally</code> to free up objects is a good practice like the following code:</p>\n\n<pre><code>private static String someString() {\n\n StringBuilder sb = new StringBuilder();\n\n try {\n sb.append(\"abc\");\n return sb.toString();\n\n } finally {\n sb = null; // Just an example, but you can close streams or DB connections this way.\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50262581,
"author": "Rubin Luitel",
"author_id": 6929015,
"author_profile": "https://Stackoverflow.com/users/6929015",
"pm_score": 2,
"selected": false,
"text": "<p>Finally is always called at the end</p>\n\n<p>when you try, it executes some code, if something happens in try, then catch will catch that exception and you could print some mssg out or throw an error, then finally block is executed.</p>\n\n<p>Finally is normally used when doing cleanups, for instance, if you use a scanner in java, you should probably close the scanner as it leads to other problems such as not being able to open some file</p>\n"
},
{
"answer_id": 57402744,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 2,
"selected": false,
"text": "<p>Here are some conditions which can bypass a finally block:</p>\n\n<ol>\n<li>If the JVM exits while the try or catch code is being executed, then the finally block may not execute. More on <a href=\"http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html\" rel=\"nofollow noreferrer\">sun tutorial</a> </li>\n<li>Normal Shutdown - this occurs either when the last non-daemon thread exits OR when Runtime.exit() (<a href=\"http://geekexplains.blogspot.com/2008/06/jvm-shutdown-jvm-shutdown-sequence.html\" rel=\"nofollow noreferrer\">some good blog</a>). When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned finally blocks are not executed, stacks are not unwound the JVM just exits. Daemon threads should be used sparingly few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for \"housekeeping\" tasks, such as a background thread that periodically removes expired entries from an in-memory cache (<a href=\"https://rads.stackoverflow.com/amzn/click/com/0321349601\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">source</a>)</li>\n</ol>\n\n<p>Last non-daemon thread exits example: </p>\n\n<pre><code>public class TestDaemon {\n private static Runnable runnable = new Runnable() {\n @Override\n public void run() {\n try {\n while (true) {\n System.out.println(\"Is alive\");\n Thread.sleep(10);\n // throw new RuntimeException();\n }\n } catch (Throwable t) {\n t.printStackTrace();\n } finally {\n System.out.println(\"This will never be executed.\");\n }\n }\n };\n\n public static void main(String[] args) throws InterruptedException {\n Thread daemon = new Thread(runnable);\n daemon.setDaemon(true);\n daemon.start();\n Thread.sleep(100);\n // daemon.stop();\n System.out.println(\"Last non-daemon thread exits.\");\n }\n}\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>Is alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nLast non-daemon thread exits.\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\n</code></pre>\n"
},
{
"answer_id": 59932063,
"author": "hellzone",
"author_id": 1379734,
"author_profile": "https://Stackoverflow.com/users/1379734",
"pm_score": 3,
"selected": false,
"text": "<p><code>finally</code> block is always executed and before returning <code>x</code>'s (calculated) value.</p>\n<pre><code>System.out.println("x value from foo() = " + foo());\n\n...\n\nint foo() {\n int x = 2;\n try {\n return x++;\n } finally {\n System.out.println("x value in finally = " + x);\n }\n}\n</code></pre>\n<p>Output:</p>\n<blockquote>\n<p>x value in finally = 3<br />\nx value from foo() = 2</p>\n</blockquote>\n"
},
{
"answer_id": 60123997,
"author": "Youngrok Ko",
"author_id": 2862834,
"author_profile": "https://Stackoverflow.com/users/2862834",
"pm_score": 1,
"selected": false,
"text": "<p>try-with-resoruce example</p>\n\n<pre><code>static class IamAutoCloseable implements AutoCloseable {\n private final String name;\n IamAutoCloseable(String name) {\n this.name = name;\n }\n public void close() {\n System.out.println(name);\n }\n}\n\n@Test\npublic void withResourceFinally() {\n try (IamAutoCloseable closeable1 = new IamAutoCloseable(\"closeable1\");\n IamAutoCloseable closeable2 = new IamAutoCloseable(\"closeable2\")) {\n System.out.println(\"try\");\n } finally {\n System.out.println(\"finally\");\n }\n}\n</code></pre>\n\n<p>Test output:</p>\n\n<pre><code>try\ncloseable2\ncloseable1\nfinally\n</code></pre>\n"
},
{
"answer_id": 70623392,
"author": "kevinarpe",
"author_id": 257299,
"author_profile": "https://Stackoverflow.com/users/257299",
"pm_score": 0,
"selected": false,
"text": "<p>I am terribly late to answer here, but I am surprised that no one mentioned the Java debugger option to drop a stack frame. I am a heavy user of this feature in IntelliJ. (I am <em>sure</em> Eclipse and NetBeans has support for the same feature.)</p>\n<p>If I drop stack frame from a the try or catch block that is followed by a finally block, the IDE will prompt me: "Shall I execute the finally block?" Obviously, this is an artificial runtime environment -- a debugger!</p>\n<p>To answer your question, I would say you can only guarantee it runs if ignore when a debugger is attached, and (like others said) method <code>something()</code> does not (a) call Java method <code>System.exit(int)</code> or (b) C function <code>exit(int)</code> / <code>abort()</code> via JNI or (c) do something crazy like call <code>kill -9 $PID</code> on itself(!).</p>\n"
},
{
"answer_id": 70841158,
"author": "tquadrat",
"author_id": 1554195,
"author_profile": "https://Stackoverflow.com/users/1554195",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://stackoverflow.com/a/65049/1554195\">accepted answer</a> is true in nearly all aspects, but it is still only halve the truth at all (ok, 95% of the truth).</p>\n<p>Assume the following code:</p>\n<pre><code>private final Lock m_Lock = new ReentrantLock();\n…\npublic final SomeObject doSomething( final SomeObject arg )\n{\n final SomeObject retValue;\n try\n {\n lock.lock();\n retValue = SomeObject( arg );\n }\n finally\n {\n out.println( "Entering finally block");\n callingAnotherMethod( arg, retValue );\n lock.unlock();\n }\n \n return retValue;\n}\n…\ntry\n{\n final var result = doSomething( new SomeObject() );\n}\ncatch( final StackOverflowError e ) { /* Deliberately ignored */ }\n</code></pre>\n<p>Calling the method <code>doSomething()</code> will cause a <code>StackOverflowError</code> nearly immediately.</p>\n<p>And the <code>lock</code> will not be released!</p>\n<p>But how could this happen when the <code>finally</code> block is always executed (with the exceptions already listed in the <a href=\"https://stackoverflow.com/a/65049/1554195\">accepted answer</a>)?</p>\n<p>That is because there is <em>no guarantee</em> made that <em>all</em> statements in the <code>finally</code> block are <em>really</em> executed!</p>\n<p>This would be obvious if there would be a call to <code>System.exit()</code> or a <code>throws</code> statement before the call to <code>lock.unlock()</code>.</p>\n<p>But there is nothing like that in the sample code …</p>\n<p>Aside that the two other method calls in the <code>finally</code> block before the call to <code>lock.unlock()</code> will cause another <code>StackOverflowError</code> …</p>\n<p>And voilà, the lock is not released!</p>\n<p>Although the sample code as such is silly, similar patterns can be found a lot in many kinds of software. All works fine as long as nothing ugly happens in the <code>finally</code> block …</p>\n<p>Funny fact is that it does not work in later versions of Java (meaning that in later versions, the lock was released …). No idea when and why this changed.</p>\n<p>But you still have to make sure that the <code>finally</code> block always terminates normally, otherwise it might not matter if (that) it always get executed …</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/885027/"
]
| Considering this code, can I be *absolutely sure* that the `finally` block always executes, no matter what `something()` is?
```
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
``` | Yes, `finally` will be called after the execution of the `try` or `catch` code blocks.
The only times `finally` won't be called are:
1. If you invoke `System.exit()`
2. If you invoke `Runtime.getRuntime().halt(exitStatus)`
3. If the JVM crashes first
4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the `try` or `catch` block
5. If the OS forcibly terminates the JVM process; e.g., `kill -9 <pid>` on UNIX
6. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
7. If the `finally` block is going to be executed by a daemon thread and all other non-daemon threads exit before `finally` is called |
65,037 | <p>As far as I know, in gcc you can write something like:</p>
<pre><code>#define DBGPRINT(fmt...) printf(fmt);
</code></pre>
<p>Is there a way to do that in VC++?</p>
| [
{
"answer_id": 65067,
"author": "kfh",
"author_id": 6597,
"author_profile": "https://Stackoverflow.com/users/6597",
"pm_score": -1,
"selected": false,
"text": "<p>Almost. It's uglier than that though (and you probably don't want a trailing semi-colon in the macro itself:</p>\n\n<pre><code>#define DBGPRINT(DBGPRINT_ARGS) printf DBGPRINT_ARGS // note: do not use '(' & ')'\n</code></pre>\n\n<p>To use it:</p>\n\n<pre><code>DBGPRINT((\"%s\\n\", \"Hello World\"));\n</code></pre>\n\n<p>(was missing a pair of parens).</p>\n\n<p>Not sure why all the negatives, the original question didn't state a version of VC++, and variadic macros aren't supported by all compilers.</p>\n"
},
{
"answer_id": 65077,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can do this in Visual Studio C++ in versions 2005 and beyond (not sure about VS 2003). Take a look at <strong>VA_ARGS</strong>. You can basically do something like this:</p>\n\n<pre><code>#define DBGPRINTF(fmt, ...) printf(fmt, __VA_ARGS__)\n</code></pre>\n\n<p>and the variable arguments to the macro will get passed to the function provided as '...' args, where you can then us va_args to parse them out.</p>\n\n<p>There can be weird behavior with <strong>VA_ARGS</strong> and the use of macros. Because <strong>VA_ARGS</strong> is variable, that means that there can be 0 arguments. That might leave you with trailing commas where you didn't intend. </p>\n"
},
{
"answer_id": 65083,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What you're looking for are called [variadic macros](<a href=\"http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx)</a>.</p>\n\n<p>Summary of the link: yes, from VC++ 2005 on up.</p>\n"
},
{
"answer_id": 65087,
"author": "David Dolson",
"author_id": 8566,
"author_profile": "https://Stackoverflow.com/users/8566",
"pm_score": 0,
"selected": false,
"text": "<p>The following should work. (See link to <a href=\"http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx\" rel=\"nofollow noreferrer\">Variadic macros</a>)</p>\n\n<p>(Example below shows a fixed and variable arguments.)</p>\n\n<pre><code># define DBGPRINTF(fmt,...) \\\n do { \\\n printf(fmt, __VA_ARGS__); \\\n } while(0)\n</code></pre>\n"
},
{
"answer_id": 65103,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 6,
"selected": true,
"text": "<p>Yes but only since VC++ 2005. The syntax for your example would be:</p>\n\n<pre><code>#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)\n</code></pre>\n\n<p>A full reference is <a href=\"http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 65158,
"author": "James",
"author_id": 168235,
"author_profile": "https://Stackoverflow.com/users/168235",
"pm_score": 0,
"selected": false,
"text": "<p>Search for \"<strong>VA_ARGS</strong>\" and va_list in MSDN!</p>\n"
},
{
"answer_id": 65388,
"author": "yrp",
"author_id": 7228,
"author_profile": "https://Stackoverflow.com/users/7228",
"pm_score": 2,
"selected": false,
"text": "<p>If you do not want to use non-standard extensions, you've to provide extra brackets: </p>\n\n<pre><code>#define DBGPRINT(args) printf(args);\nDBGPRINT((\"%s\\n\", \"Hello World\"));\n</code></pre>\n"
},
{
"answer_id": 69151,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't actually need any of the features of macros (<code>__FILE__</code>, <code>__LINE__</code>, token-pasting, etc.) you may want to consider writing a variadic function using <code>stdargs.h</code>. Instead of calling <code>printf()</code>, a variadic function can call <code>vprintf()</code> in order to pass along variable argument lists.</p>\n"
},
{
"answer_id": 16365801,
"author": "amarcruz",
"author_id": 2347894,
"author_profile": "https://Stackoverflow.com/users/2347894",
"pm_score": 1,
"selected": false,
"text": "<p>For MSVC 7.1 (.NET 2003), this works:</p>\n\n<pre><code>#if defined(DETAILED_DEBUG)\n#define DBGPRINT fprintf\n#else\n__forceinline void __DBGPRINT(...){}\n#define DBGPRINT __DBGPRINT\n#endif\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9102/"
]
| As far as I know, in gcc you can write something like:
```
#define DBGPRINT(fmt...) printf(fmt);
```
Is there a way to do that in VC++? | Yes but only since VC++ 2005. The syntax for your example would be:
```
#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)
```
A full reference is [here](http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx). |
65,039 | <p>I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code. </p>
<p>There is heavy use of <code>CssClass='&hellip;'</code>, or sometimes just <code>class='&hellip;'</code>, but I can't seem to find a way to say id='…' and not have it swapped out by the server.</p>
<p>Here is an example:</p>
<pre><code><span id='position_title' runat='server'>Manager</span>
</code></pre>
<p>When the response comes back from the server, I get:</p>
<pre><code><span id='$aspnet$crap$here$position_title'>Manager</span></code></pre>
<p>Any help here?</p>
| [
{
"answer_id": 65051,
"author": "Matt Dawdy",
"author_id": 232,
"author_profile": "https://Stackoverflow.com/users/232",
"pm_score": 0,
"selected": false,
"text": "<p>.Net will always replace your id values with some mangled (every so slightly predictable, but still don't count on it) value. Do you really NEED to have that id runat=server? If you don't put in runat=server, then it won't mangle it...</p>\n\n<p>ADDED:\nLike leddt said, you can reference the span (or any runat=server with an id) by using ClientID, but I don't think that works in CSS.</p>\n\n<p>But I think that you have a larger problem if your CSS is using ID based selectors. You can't re-use an ID. You can't have multiple items on the same page with the same ID. .Net will complain about that.</p>\n\n<p>So, with that in mind, is your job of refactoring the CSS getting to be a bit larger in scope?</p>\n"
},
{
"answer_id": 65082,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 3,
"selected": false,
"text": "<p>The 'crap' placed in front of the id is related to the container(s) of the control and there is no way (as far as I know) to prevent this behavior, other than not putting it in any container. </p>\n\n<p>If you need to refer to the id in script, you can use the ClientID of the control, like so:</p>\n\n<pre><code><script type=\"text/javascript\">\n var theSpan = document.getElementById('<%= position_title.ClientID %>');\n</script>\n</code></pre>\n"
},
{
"answer_id": 65127,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I guess the jury is out on this one. </p>\n\n<p>@leddt, I already knew that the 'crap' was the containers surrounding it, but I thought maybe Microsoft would have left a backdoor to leave the ID alone. Regenerating CSS files on every use by including ClientIDs would be a horrible idea. </p>\n\n<p>I'm either left with using classes everywhere, or some garbled looking IDs hardcoded in the css.</p>\n"
},
{
"answer_id": 65138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Dawdy: There are some great uses for IDs in CSS, primarily when you want to style an element that you know only appears once in either the website or a page, such as a logout button or masthead.</p>\n"
},
{
"answer_id": 65147,
"author": "B0fh",
"author_id": 9159,
"author_profile": "https://Stackoverflow.com/users/9159",
"pm_score": 0,
"selected": false,
"text": "<p>If you are accessing the <code>span</code> or whatever tag is giving you problems from the C# or VB code behind, then the <code>runat=\"server\"</code> has to remain and you should use instead <code><span class=\"some_class\" id=\"someID\"></code>. If you are not accessing the tag in the code behind, then remove the <code>runat=\"server\"</code>.</p>\n"
},
{
"answer_id": 65174,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>The best thing to do here is give it a unique class name. </p>\n"
},
{
"answer_id": 65231,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>You're likely going to have to remove the runat=\"server\" from the span and then place a within the span so you can stylize the span and still have the dynamic internal content.</p>\n\n<p>Not an elegant or easy solution (and it requires a recompile), but it works.</p>\n"
},
{
"answer_id": 65327,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 3,
"selected": false,
"text": "<p>Use jQuery to select the element: </p>\n\n<pre><code>$(\"span[id$='position_title']\")....\n</code></pre>\n\n<p>jQuery's flexible selectors, especially its 'begins with'/'ends with selectors' (the 'end with' selector is shown above, provide a great way around ASP.NET's dom id munge.</p>\n\n<p>rp</p>\n"
},
{
"answer_id": 65586,
"author": "Joshua Carmody",
"author_id": 8409,
"author_profile": "https://Stackoverflow.com/users/8409",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of a way to stop .NET from mangling the ID, but I can think of a couple ways to work around it:</p>\n\n<p>1 - Nest spans, one with runat=\"server\", one without:</p>\n\n<pre><code><style type=\"text/css\">\n#position_title { // Whatever\n}\n<span id=\"position_titleserver\" runat=\"server\"><span id=\"position_title\">Manager</span></span>\n</code></pre>\n\n<p>2 - As Joel Coehoorn suggested, use a unique class name instead. Already using the class for something? Doesn't matter, you can use more than 1! This...</p>\n\n<pre><code><style type=\"text/css\">\n.position_title { font-weight: bold; }\n.foo { color: red; }\n.bar { font-style: italic; }\n</style>\n<span id=\"thiswillbemangled\" class=\"foo bar position_title\" runat=\"server\">Manager</span>\n</code></pre>\n\n<p>...will display this:</p>\n\n<p><b><i>Manager</i></b></p>\n\n<p>3 - Write a Javascript function to fix the IDs after the page loads</p>\n\n<pre><code>function fixIds()\n{\n var tagList = document.getElementsByTagName(\"*\");\n for(var i=0;i<tagList.length;i++)\n {\n if(tagList[i].id)\n {\n if(tagList[i].id.indexOf('$') > -1)\n {\n var tempArray = tagList[i].id.split(\"$\");\n tagList[i].id = tempArray[tempArray.length - 1];\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 66253,
"author": "NICCAI",
"author_id": 1629400,
"author_profile": "https://Stackoverflow.com/users/1629400",
"pm_score": 0,
"selected": false,
"text": "<p>If you're fearing classitus, try using an id on a parent or child selector that contains the element that you wish to style. This parent element should NOT have the runat server applied. Simply put, it's a good idea to plan your structural containers to not run code behind (ie. no runat), that way you can access major portions of your application/site using non-altered IDs. If it's too late to do so, add a wrapper div/span or use the class solution as mentioned.</p>\n"
},
{
"answer_id": 66325,
"author": "Scott Gowell",
"author_id": 6943,
"author_profile": "https://Stackoverflow.com/users/6943",
"pm_score": 0,
"selected": false,
"text": "<p>Is there a particular reason that you want the controls to be runat=\"server\"?</p>\n\n<p>If so, I second the use of < asp : Literal > . . . </p>\n\n<p>It should do the job for you as you will still be able to edit the data in code behind.</p>\n"
},
{
"answer_id": 66336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I usually make my own control that extends WebControl or HtmlGenericControl, and I override ClientID - returning the ID property instead of the generated ClientID. This will cause any transformation that .NET does to the ClientID because of naming containers to be reverted back to the original id that you specified in tag markup. This is great if you are using client side libraries like jQuery and need predictable unique ids, but tough if you rely on viewstate for anything server-side.</p>\n"
},
{
"answer_id": 72735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can embed your CSS within the page, sprinkled with some server tags to overcome the problem. At runtime the code blocks will be replaced with the ASP.NET generated IDs.</p>\n\n<p>For example:</p>\n\n<pre><code>[style type=\"text/css\"]\n #<%= AspNetId.ClientID %> {\n ... styles go here...\n }\n[/style]\n\n[script type=\"text/javascript\"]\n document.getElementById(\"<%= AspNetId.ClientID %>\");\n[/script]\n</code></pre>\n\n<p>You could go a bit further and have some code files that generate CSS too, if you wanted to have your CSS contained within a separate file.</p>\n\n<p>Also, I may be jumping the gun a bit here, but you could use the ASP.NET MVC stuff (not yet officially released as of this writing) which gets away from the Web Forms and gives you total control over the markup generated.</p>\n"
},
{
"answer_id": 112821,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the fixes suggested her are overkill for a very simple problem. Just have separate divs and spans that you target with CSS. Don't target the ASP.NET controls directly if you want to use IDs.</p>\n\n<pre><code> <span id=\"FooContainer\">\n <span runat=\"server\" id=\"Foo\" >\n ......\n <span>\n </span>\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code.
There is heavy use of `CssClass='…'`, or sometimes just `class='…'`, but I can't seem to find a way to say id='…' and not have it swapped out by the server.
Here is an example:
```
<span id='position_title' runat='server'>Manager</span>
```
When the response comes back from the server, I get:
```
<span id='$aspnet$crap$here$position_title'>Manager</span>
```
Any help here? | The 'crap' placed in front of the id is related to the container(s) of the control and there is no way (as far as I know) to prevent this behavior, other than not putting it in any container.
If you need to refer to the id in script, you can use the ClientID of the control, like so:
```
<script type="text/javascript">
var theSpan = document.getElementById('<%= position_title.ClientID %>');
</script>
``` |
65,060 | <p>If i have a simple named query defined, the preforms a count function, on one column:</p>
<pre><code> <query name="Activity.GetAllMiles">
<![CDATA[
select sum(Distance) from Activity
]]>
</query>
</code></pre>
<p>How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?</p>
<p>Here is my attempt (im unable to test it right now), would this work?</p>
<pre><code> public decimal Find(String namedQuery)
{
using (ISession session = NHibernateHelper.OpenSession())
{
IQuery query = session.GetNamedQuery(namedQuery);
return query.UniqueResult<decimal>();
}
}
</code></pre>
| [
{
"answer_id": 67675,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 2,
"selected": false,
"text": "<p>As an indirect answer to your question, here is how I do it without a named query.</p>\n\n<pre><code>var session = GetSession();\nvar criteria = session.CreateCriteria(typeof(Order))\n .Add(Restrictions.Eq(\"Product\", product))\n .SetProjection(Projections.CountDistinct(\"Price\"));\nreturn (int) criteria.UniqueResult();\n</code></pre>\n"
},
{
"answer_id": 84348,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 3,
"selected": true,
"text": "<p>Sorry! I actually wanted a sum, not a count, which explains alot. Iv edited the post accordingly</p>\n\n<p>This works fine:</p>\n\n<pre><code>var criteria = session.CreateCriteria(typeof(Activity))\n .SetProjection(Projections.Sum(\"Distance\"));\n return (double)criteria.UniqueResult();\n</code></pre>\n\n<p>The named query approach still dies, \"Errors in named queries: {Activity.GetAllMiles}\":</p>\n\n<pre><code> using (ISession session = NHibernateHelper.OpenSession())\n {\n IQuery query = session.GetNamedQuery(\"Activity.GetAllMiles\");\n\n\n return query.UniqueResult<double>();\n }\n</code></pre>\n"
},
{
"answer_id": 84424,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>I think in your original example, you just need to to query.UniqueResult(); the count will return an integer.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
| If i have a simple named query defined, the preforms a count function, on one column:
```
<query name="Activity.GetAllMiles">
<![CDATA[
select sum(Distance) from Activity
]]>
</query>
```
How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?
Here is my attempt (im unable to test it right now), would this work?
```
public decimal Find(String namedQuery)
{
using (ISession session = NHibernateHelper.OpenSession())
{
IQuery query = session.GetNamedQuery(namedQuery);
return query.UniqueResult<decimal>();
}
}
``` | Sorry! I actually wanted a sum, not a count, which explains alot. Iv edited the post accordingly
This works fine:
```
var criteria = session.CreateCriteria(typeof(Activity))
.SetProjection(Projections.Sum("Distance"));
return (double)criteria.UniqueResult();
```
The named query approach still dies, "Errors in named queries: {Activity.GetAllMiles}":
```
using (ISession session = NHibernateHelper.OpenSession())
{
IQuery query = session.GetNamedQuery("Activity.GetAllMiles");
return query.UniqueResult<double>();
}
``` |
65,071 | <p>Is there a performant equivalent to the isnull function for DB2?</p>
<p>Imagine some of our products are internal, so they don't have names:</p>
<pre><code>Select product.id, isnull(product.name, "Internal)
From product
</code></pre>
<p>Might return:</p>
<pre><code>1 Socks
2 Shoes
3 Internal
4 Pants
</code></pre>
| [
{
"answer_id": 65111,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not familiar with DB2, but have you tried COALESCE?</p>\n\n<p>ie:</p>\n\n<pre><code>\nSELECT Product.ID, COALESCE(product.Name, \"Internal\") AS ProductName\nFROM Product\n</code></pre>\n"
},
{
"answer_id": 163321,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 0,
"selected": false,
"text": "<p><code>COALESCE</code> function same <code>ISNULL</code> function\nNote. you must use <code>COALESCE</code> function with same data type of column that you check is null.</p>\n"
},
{
"answer_id": 256672,
"author": "venkatram",
"author_id": 33392,
"author_profile": "https://Stackoverflow.com/users/33392",
"pm_score": 0,
"selected": false,
"text": "<p>I think <code>COALESCE</code> function partially similar to the <code>isnull</code>, but try it.</p>\n\n<p>Why don't you go for null handling functions through application programs, it is better alternative. </p>\n"
},
{
"answer_id": 1122917,
"author": "MadMurf",
"author_id": 46527,
"author_profile": "https://Stackoverflow.com/users/46527",
"pm_score": 5,
"selected": false,
"text": "<p>For what its worth, COALESCE is similiar but </p>\n\n<pre><code>IFNULL(expr1, default)\n</code></pre>\n\n<p>is the exact match you're looking for in DB2. </p>\n\n<p>COALESCE allows multiple arguments, returning the first NON NULL expression, whereas IFNULL only permits the expression and the default.</p>\n\n<p>Thus</p>\n\n<pre><code>SELECT product.ID, IFNULL(product.Name, \"Internal\") AS ProductName\nFROM Product\n</code></pre>\n\n<p>Gives you what you're looking for as well as the previous answers, just adding for completeness.</p>\n"
},
{
"answer_id": 23872455,
"author": "Jnn",
"author_id": 2303472,
"author_profile": "https://Stackoverflow.com/users/2303472",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Select Product.ID, VALUE(product.Name, \"Internal\") AS ProductName from Product\n</code></pre>\n"
},
{
"answer_id": 43136634,
"author": "Md. Kamruzzaman",
"author_id": 4294974,
"author_profile": "https://Stackoverflow.com/users/4294974",
"pm_score": 3,
"selected": false,
"text": "<p>In DB2 there is a function NVL(field, value if null).</p>\n\n<p>Example:</p>\n\n<p>SELECT ID, NVL(NAME, \"Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;</p>\n"
},
{
"answer_id": 46464702,
"author": "turnmoil",
"author_id": 7755586,
"author_profile": "https://Stackoverflow.com/users/7755586",
"pm_score": 0,
"selected": false,
"text": "<p>hope this might help someone else out there</p>\n\n<pre><code> SELECT \n.... FROM XXX XX\nWHERE\n....\nAND(\n param1 IS NULL\n OR XX.param1 = param1\n )\n</code></pre>\n"
},
{
"answer_id": 69189273,
"author": "Rafael Rossi",
"author_id": 7129619,
"author_profile": "https://Stackoverflow.com/users/7129619",
"pm_score": 0,
"selected": false,
"text": "<p>Another option, in case you need to use if/else, is:</p>\n<pre><code>NVL2 (string_to_be_tested, string_if_not_null, string_if_null);\n</code></pre>\n<p>i.e.:</p>\n<pre><code>SELECT product.ID, NVL2(product.Name, "Internal", "External") AS ProductName\nFROM Product;\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056/"
]
| Is there a performant equivalent to the isnull function for DB2?
Imagine some of our products are internal, so they don't have names:
```
Select product.id, isnull(product.name, "Internal)
From product
```
Might return:
```
1 Socks
2 Shoes
3 Internal
4 Pants
``` | For what its worth, COALESCE is similiar but
```
IFNULL(expr1, default)
```
is the exact match you're looking for in DB2.
COALESCE allows multiple arguments, returning the first NON NULL expression, whereas IFNULL only permits the expression and the default.
Thus
```
SELECT product.ID, IFNULL(product.Name, "Internal") AS ProductName
FROM Product
```
Gives you what you're looking for as well as the previous answers, just adding for completeness. |
65,074 | <p>I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was looking for some better strategies for handling these problems.</p>
<p>I've been frequently running into the problem of duplicating almost every header file with a blank version in order to separate the class I'm testing in it's entirety, and then writing substantial stub/mock/fake code for objects that will need to be replaced since they're now undefined.</p>
<p>Anyone know some better practices?</p>
| [
{
"answer_id": 65121,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 1,
"selected": false,
"text": "<p>Since you're testing legacy code I'm assuming you can't refactor said code to have less dependencies (e.g. by using the <a href=\"http://www.gotw.ca/gotw/028.htm\" rel=\"nofollow noreferrer\">pimpl idiom</a>)</p>\n\n<p>That leaves you with little options I'm afraid. Every header that was included for a type or function will need a mock object for that type or function for everything to compile, there's little you can do...</p>\n"
},
{
"answer_id": 65166,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you keep writing stubs/mock/fake codes you risk doing unit testing on a class that has different behavior then when compiled on the main project.</p>\n\n<p>But if those includes are there and have no added behavior then it's Ok.</p>\n\n<p>I'd try not changing anything on the includes while doing the unit testing so you're sure (as far you can be on legacy code :) ) that you testing the real code.</p>\n"
},
{
"answer_id": 65168,
"author": "Jeroen Dirks",
"author_id": 7743,
"author_profile": "https://Stackoverflow.com/users/7743",
"pm_score": 1,
"selected": false,
"text": "<p>I am not answering your question directly but I am afraid that unit testing just may not be the thing to do if you work with large amounts of legacy code.</p>\n\n<p>After leading an XP team on a green field development project I really loved my Unit tests. Things happened and a few years later I find myself working on a large legacy code base that has lots of quality problems.</p>\n\n<p>I tried to find a way to add units tests to the application but in the end just got stuck in a catch-22:</p>\n\n<ol>\n<li>In order to write meaning full unit tests the code would need to be refactored.</li>\n<li>Without unit tests it will be too dangerous to refactor the code.</li>\n</ol>\n\n<p>If you feel like a hero and drink the cool-aid on unit testing then you may still give it a try but there is a real risk that you end up with just more test code of little value that now also needs to be maintained.</p>\n\n<p>Sometimes it is just best to work on the code in the way that is \"designed\" to be worked on.</p>\n"
},
{
"answer_id": 65258,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 0,
"selected": false,
"text": "<p>You're definitely between a rock and a hard place with legacy code with large dependencies. You've got a long hard slog ahead to sort it all out.</p>\n\n<p>From what you say, it seems you are trying to keep the source code intact for each module in turn, placing it in a test harness with external dependencies mocked out. My suggestion here would be to take the even braver step of attempting some refactoring to eliminate (or <a href=\"http://www.objectmentor.com/resources/articles/dip.pdf\" rel=\"nofollow noreferrer\" title=\"Dependency Inversion Princple\">invert</a>) the dependencies, which is probably the very step you are trying to avoid.</p>\n\n<p>I suggest this because I'm guessing the dependencies are going to kill you as you write tests. You will certainly be better off in the long term if you can eliminate the dependencies.</p>\n"
},
{
"answer_id": 65398,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if this will work for your project but\nyou might try to attack the problem from the <strong>link phase</strong> of your build.</p>\n\n<p>This would completely eliminate your #include problem.\nAll you would need to do is re-implement the interfaces in the included files to do what ever you want and then just link to the mock object files that you have created to implement the interfaces in the include file.</p>\n\n<p>The big disadvantage to this method is a more complected build system.</p>\n"
},
{
"answer_id": 65923,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": true,
"text": "<p>The depression in the responses is overwhelming... But don't fear, we've got <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131177052\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">the holy book to exorcise the demons of legacy C++ code</a>. Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code.</p>\n\n<p>Turn to page 127: <strong>The case of the horrible include dependencies.</strong> (Now I am not even within miles of Michael Feathers but here as-short-as-I-could-manage answer..)</p>\n\n<p><strong>Problem</strong>: In C++ if a classA needs to know about ClassB, Class B's declaration is straight-lifted / textually included in the ClassA's source file. And since we programmers love to take it to the wrong extreme, a file can recursively include a zillion others transitively. Builds take years.. but hey atleast it builds.. we can wait. </p>\n\n<p>Now to say 'instantiating ClassA under a test harness is difficult' is an understatement. (Quoting MF's example - Scheduler is our poster problem child with deps galore.)</p>\n\n<pre><code>#include \"TestHarness.h\"\n#include \"Scheduler.h\"\nTEST(create, Scheduler) // your fave C++ test framework macro\n{\n Scheduler scheduler(\"fred\");\n}\n</code></pre>\n\n<p>This will bring out the includes dragon with a flurry of build errors.<br>\n<strong>Blow#1 Patience-n-Persistence</strong>: Take on each include one at a time and decide if we really need that dependency. Let's assume SchedulerDisplay is one of them, whose displayEntry method is called in Scheduler's ctor.<br>\n<strong>Blow#2 Fake-it-till-you-make-it</strong> (Thanks RonJ):</p>\n\n<pre><code>#include \"TestHarness.h\"\n#include \"Scheduler.h\"\nvoid SchedulerDisplay::displayEntry(const string& entryDescription) {}\nTEST(create, Scheduler)\n{\n Scheduler scheduler(\"fred\");\n}\n</code></pre>\n\n<p>And pop goes the dependency and all its transitive includes. \nYou can also reuse the Fake methods by encapsulating it in a Fakes.h file to be included in your test files.<br>\n<strong>Blow#3 Practice</strong>: It may not be always that simple.. but you get the idea. After the first few duels, the process of breaking deps will get easy-n-mechanical</p>\n\n<p><strong>Caveats</strong> (Did I mention there are caveats? :) </p>\n\n<ul>\n<li>We need a separate build for test cases in this file ; we can have only 1 definition for the SchedulerDisplay::displayEntry method in a program. So create a separate program for scheduler tests.</li>\n<li>We aren't breaking any dependencies in the program, so we are not making the code cleaner.</li>\n<li>You need to maintain those fakes as long as we need the tests.</li>\n<li>Your sense of aesthetics may be offended for a while.. just bite your lip and 'bear with us for a better tomorrow' </li>\n</ul>\n\n<p>Use this technique for a very huge class with severe dependency issues. Don't use often or lightly.. <strong>Use this as a starting point for deeper refactorings.</strong> Over time this testing program can be taken behind the barn as you extract more classes (WITH their own tests).</p>\n\n<p>For more.. please do read the book. Invaluable. Fight on bro!</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8908/"
]
| I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was looking for some better strategies for handling these problems.
I've been frequently running into the problem of duplicating almost every header file with a blank version in order to separate the class I'm testing in it's entirety, and then writing substantial stub/mock/fake code for objects that will need to be replaced since they're now undefined.
Anyone know some better practices? | The depression in the responses is overwhelming... But don't fear, we've got [the holy book to exorcise the demons of legacy C++ code](https://rads.stackoverflow.com/amzn/click/com/0131177052). Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code.
Turn to page 127: **The case of the horrible include dependencies.** (Now I am not even within miles of Michael Feathers but here as-short-as-I-could-manage answer..)
**Problem**: In C++ if a classA needs to know about ClassB, Class B's declaration is straight-lifted / textually included in the ClassA's source file. And since we programmers love to take it to the wrong extreme, a file can recursively include a zillion others transitively. Builds take years.. but hey atleast it builds.. we can wait.
Now to say 'instantiating ClassA under a test harness is difficult' is an understatement. (Quoting MF's example - Scheduler is our poster problem child with deps galore.)
```
#include "TestHarness.h"
#include "Scheduler.h"
TEST(create, Scheduler) // your fave C++ test framework macro
{
Scheduler scheduler("fred");
}
```
This will bring out the includes dragon with a flurry of build errors.
**Blow#1 Patience-n-Persistence**: Take on each include one at a time and decide if we really need that dependency. Let's assume SchedulerDisplay is one of them, whose displayEntry method is called in Scheduler's ctor.
**Blow#2 Fake-it-till-you-make-it** (Thanks RonJ):
```
#include "TestHarness.h"
#include "Scheduler.h"
void SchedulerDisplay::displayEntry(const string& entryDescription) {}
TEST(create, Scheduler)
{
Scheduler scheduler("fred");
}
```
And pop goes the dependency and all its transitive includes.
You can also reuse the Fake methods by encapsulating it in a Fakes.h file to be included in your test files.
**Blow#3 Practice**: It may not be always that simple.. but you get the idea. After the first few duels, the process of breaking deps will get easy-n-mechanical
**Caveats** (Did I mention there are caveats? :)
* We need a separate build for test cases in this file ; we can have only 1 definition for the SchedulerDisplay::displayEntry method in a program. So create a separate program for scheduler tests.
* We aren't breaking any dependencies in the program, so we are not making the code cleaner.
* You need to maintain those fakes as long as we need the tests.
* Your sense of aesthetics may be offended for a while.. just bite your lip and 'bear with us for a better tomorrow'
Use this technique for a very huge class with severe dependency issues. Don't use often or lightly.. **Use this as a starting point for deeper refactorings.** Over time this testing program can be taken behind the barn as you extract more classes (WITH their own tests).
For more.. please do read the book. Invaluable. Fight on bro! |
65,076 | <p>I've trouble setting up Vim (7.1.xxx) for editing Python files (*.py).
Indenting seems to be broken (optimal 4 spaces).
I've followed some tutorials I found via Google. Still no effect :/
Please help.</p>
| [
{
"answer_id": 65122,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 6,
"selected": false,
"text": "<p>I use this on my macbook:</p>\n\n<pre><code>\" configure expanding of tabs for various file types\nau BufRead,BufNewFile *.py set expandtab\nau BufRead,BufNewFile *.c set expandtab\nau BufRead,BufNewFile *.h set expandtab\nau BufRead,BufNewFile Makefile* set noexpandtab\n\n\" --------------------------------------------------------------------------------\n\" configure editor with tabs and nice stuff...\n\" --------------------------------------------------------------------------------\nset expandtab \" enter spaces when tab is pressed\nset textwidth=120 \" break lines when line length increases\nset tabstop=4 \" use 4 spaces to represent tab\nset softtabstop=4\nset shiftwidth=4 \" number of spaces to use for auto indent\nset autoindent \" copy indent from current line when starting a new line\n\n\" make backspaces more powerfull\nset backspace=indent,eol,start\n\nset ruler \" show line and column number\nsyntax on \" syntax highlighting\nset showcmd \" show (partial) command in status line\n</code></pre>\n\n<p>(edited to only show stuff related to indent / tabs)</p>\n"
},
{
"answer_id": 66818,
"author": "Jamie",
"author_id": 3363,
"author_profile": "https://Stackoverflow.com/users/3363",
"pm_score": 2,
"selected": false,
"text": "<p>Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.</p>\n\n<p>In vim type</p>\n\n<p><code>:help vimrc</code></p>\n\n<p>and check your path to the _vimrc/.vimrc file with</p>\n\n<p><code>:echo $HOME</code></p>\n\n<p><code>:echo $VIM</code></p>\n\n<p>Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.</p>\n\n<p><code>:help source</code></p>\n"
},
{
"answer_id": 68002,
"author": "Gabor",
"author_id": 10485,
"author_profile": "https://Stackoverflow.com/users/10485",
"pm_score": 0,
"selected": false,
"text": "<p>for more advanced python editing consider installing the <a href=\"http://eigenclass.org/hiki/simplefold\" rel=\"nofollow noreferrer\">simplefold</a> vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.</p>\n"
},
{
"answer_id": 1868984,
"author": "Skylar Saveland",
"author_id": 177293,
"author_profile": "https://Stackoverflow.com/users/177293",
"pm_score": 3,
"selected": false,
"text": "<p>I use the vimrc in the python repo among other things:</p>\n\n<p><a href=\"http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc\" rel=\"nofollow noreferrer\">http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc</a></p>\n\n<p>I also add</p>\n\n<pre><code>set softtabstop=4\n</code></pre>\n\n<p><a href=\"http://github.com/skyl/vim-config-python-ide\" rel=\"nofollow noreferrer\">I have my old config here that I'm updating</a></p>\n"
},
{
"answer_id": 11830841,
"author": "thanos",
"author_id": 244849,
"author_profile": "https://Stackoverflow.com/users/244849",
"pm_score": 4,
"selected": false,
"text": "<p>I use:</p>\n\n<pre><code>$ cat ~/.vimrc\nsyntax on\nset showmatch\nset ts=4\nset sts=4\nset sw=4\nset autoindent\nset smartindent\nset smarttab\nset expandtab\nset number\n</code></pre>\n\n<p>But but I'm going to try Daren's entries</p>\n"
},
{
"answer_id": 44339554,
"author": "Teddy Belay",
"author_id": 4325298,
"author_profile": "https://Stackoverflow.com/users/4325298",
"pm_score": 4,
"selected": false,
"text": "<p>A simpler option: just uncomment the following part of the configuration (which is originally commented out) in the /etc/vim/vimrc file:</p>\n\n<pre><code> if has(\"autocmd\")\n filetype plugin indent on\n endif\n</code></pre>\n"
},
{
"answer_id": 60205582,
"author": "Flávio Brito",
"author_id": 6580920,
"author_profile": "https://Stackoverflow.com/users/6580920",
"pm_score": 1,
"selected": false,
"text": "<p>Combining the solutions proposed by Daren and Thanos we have a good .vimrc file. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>-----\r\n\" configure expanding of tabs for various file types\r\nau BufRead,BufNewFile *.py set expandtab\r\nau BufRead,BufNewFile *.c set noexpandtab\r\nau BufRead,BufNewFile *.h set noexpandtab\r\nau BufRead,BufNewFile Makefile* set noexpandtab\r\n\r\n\" --------------------------------------------------------------------------------\r\n\" configure editor with tabs and nice stuff...\r\n\" --------------------------------------------------------------------------------\r\nset expandtab \" enter spaces when tab is pressed\r\nset textwidth=120 \" break lines when line length increases\r\nset tabstop=4 \" use 4 spaces to represent tab\r\nset softtabstop=4\r\nset shiftwidth=4 \" number of spaces to use for auto indent\r\nset autoindent \" copy indent from current line when starting a new line\r\nset smartindent\r\nset smarttab\r\nset expandtab\r\nset number\r\n\r\n\" make backspaces more powerfull\r\nset backspace=indent,eol,start\r\n\r\nset ruler \" show line and column number\r\nsyntax on \" syntax highlighting\r\nset showcmd \" show (partial) command in status line</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9099/"
]
| I've trouble setting up Vim (7.1.xxx) for editing Python files (\*.py).
Indenting seems to be broken (optimal 4 spaces).
I've followed some tutorials I found via Google. Still no effect :/
Please help. | I use this on my macbook:
```
" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab
" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab " enter spaces when tab is pressed
set textwidth=120 " break lines when line length increases
set tabstop=4 " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4 " number of spaces to use for auto indent
set autoindent " copy indent from current line when starting a new line
" make backspaces more powerfull
set backspace=indent,eol,start
set ruler " show line and column number
syntax on " syntax highlighting
set showcmd " show (partial) command in status line
```
(edited to only show stuff related to indent / tabs) |
65,091 | <p>I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.</p>
<p>For example (where Foo is a PHP class of my making):</p>
<pre><code>$foo = new Foo();
$foo['fooKey'] = 'foo value';
echo $foo['fooKey'];
</code></pre>
<p>I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items. Python handles it by overloading __getitem__ and __setitem__.</p>
<p>Is there a way to do this in PHP? If it makes a difference, I'm running PHP 5.2.</p>
| [
{
"answer_id": 65136,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 6,
"selected": true,
"text": "<p>If you extend <code>ArrayObject</code> or implement <code>ArrayAccess</code> then you can do what you want.</p>\n\n<ul>\n<li><a href=\"http://php.net/arrayobject\" rel=\"noreferrer\">ArrayObject</a></li>\n<li><a href=\"http://php.net/arrayaccess\" rel=\"noreferrer\">ArrayAccess</a></li>\n</ul>\n"
},
{
"answer_id": 5986293,
"author": "Ron Cemer",
"author_id": 751626,
"author_profile": "https://Stackoverflow.com/users/751626",
"pm_score": 2,
"selected": false,
"text": "<p>Nope, casting just results in a normal PHP array -- losing whatever functionality your ArrayObject-derived class had. Check this out:</p>\n\n<pre><code>class CaseInsensitiveArray extends ArrayObject {\n public function __construct($input = array(), $flags = 0, $iterator_class = 'ArrayIterator') {\n if (isset($input) && is_array($input)) {\n $tmpargs = func_get_args();\n $tmpargs[0] = array_change_key_case($tmpargs[0], CASE_LOWER);\n return call_user_func_array(array('parent', __FUNCTION__), $tmp args);\n }\n return call_user_func_array(array('parent', __FUNCTION__), func_get_args());\n }\n\n public function offsetExists($index) {\n if (is_string($index)) return parent::offsetExists(strtolower($index));\n return parent::offsetExists($index);\n }\n\n public function offsetGet($index) {\n if (is_string($index)) return parent::offsetGet(strtolower($index));\n return parent::offsetGet($index);\n }\n\n public function offsetSet($index, $value) {\n if (is_string($index)) return parent::offsetSet(strtolower($index, $value));\n return parent::offsetSet($index, $value);\n }\n\n public function offsetUnset($index) {\n if (is_string($index)) return parent::offsetUnset(strtolower($index));\n return parent::offsetUnset($index);\n }\n}\n\n$blah = new CaseInsensitiveArray(array(\n 'A'=>'hello',\n 'bcD'=>'goodbye',\n 'efg'=>'Aloha',\n));\n\necho \"is array: \".is_array($blah).\"\\n\";\n\nprint_r($blah);\nprint_r(array_keys($blah));\n\necho $blah['a'].\"\\n\";\necho $blah['BCD'].\"\\n\";\necho $blah['eFg'].\"\\n\";\necho $blah['A'].\"\\n\";\n</code></pre>\n\n<p>As expected, the array_keys() call fails. In addition, is_array($blah) returns false. But if you change the constructor line to:</p>\n\n<pre><code>$blah = (array)new CaseInsensitiveArray(array(\n</code></pre>\n\n<p>then you just get a normal PHP array (is_array($blah) returns true, and array_keys($blah) works), but all of the functionality of the ArrayObject-derived subclass is lost (in this case, case-insensitive keys no longer work). Try running the above code both ways, and you'll see what I mean.</p>\n\n<p>PHP should either provide a native array in which the keys are case-insensitive, or make ArrayObject be castable to array without losing whatever functionality the subclass implements, or just make all array functions accept ArrayObject instances.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
| I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.
For example (where Foo is a PHP class of my making):
```
$foo = new Foo();
$foo['fooKey'] = 'foo value';
echo $foo['fooKey'];
```
I know that PHP has the \_get and \_set magic methods but those don't let you use array notation to access items. Python handles it by overloading \_\_getitem\_\_ and \_\_setitem\_\_.
Is there a way to do this in PHP? If it makes a difference, I'm running PHP 5.2. | If you extend `ArrayObject` or implement `ArrayAccess` then you can do what you want.
* [ArrayObject](http://php.net/arrayobject)
* [ArrayAccess](http://php.net/arrayaccess) |
65,095 | <p>What are the common algorithms being used to measure the processor frequency?</p>
| [
{
"answer_id": 65159,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure why you need assembly for this. If you're on a machine that has the /proc filesystem, then running:</p>\n\n<pre><code>> cat /proc/cpuinfo\n</code></pre>\n\n<p>might give you what you need.</p>\n"
},
{
"answer_id": 65178,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 1,
"selected": false,
"text": "<p>That was the intention of things like <A HREF=\"http://en.wikipedia.org/wiki/BogoMips\" rel=\"nofollow noreferrer\">BogoMIPS</A>, but CPUs are a lot more complicated nowadays. Superscalar CPUs can issue multiple instructions per clock, making any measurement based on counting clock cycles to execute a block of instructions highly inaccurate.</p>\n\n<p>CPU frequencies are also variable based on offered load and/or temperature. The fact that the CPU is currently running at 800 MHz does not mean it will always be running at 800 MHz, it might throttle up or down as needed.</p>\n\n<p>If you really need to know the clock frequency, it should be passed in as a parameter. An EEPROM on the board would supply the base frequency, and if the clock can vary you'd need to be able to read the CPUs power state registers (or make an OS call) to find out the frequency at that instant.</p>\n\n<p>With all that said, there may be other ways to accomplish what you're trying to do. For example if you want to make high-precision measurements of how long a particular codepath takes, the CPU likely has performance counters running at a fixed frequency which are a better measure of wall-clock time than reading a tick count register.</p>\n"
},
{
"answer_id": 65369,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 4,
"selected": false,
"text": "<p>Intel CPUs after Core Duo support two Model-Specific registers called IA32_MPERF and IA32_APERF.<br>\nMPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency.</p>\n\n<p>The actual frequency is given by:</p>\n\n<p><img src=\"https://chart.apis.google.com/chart?cht=tx&chl=%5CLARGE%5C%21freq%20%3D%20%5Cfrac%7Bmax%20frequency%20%5Ccdot%20APERF%7D%7BMPERF%7D\" alt=\"freq = max_frequency * APERF / MPERF\"></p>\n\n<p>You can read them with this flow</p>\n\n<pre><code>; read MPERF\nmov ecx, 0xe7\nrdmsr\nmov mperf_var_lo, eax\nmov mperf_var_hi, edx\n\n; read APERF\nmov ecx, 0xe8\nrdmsr\nmov aperf_var_lo, eax\nmov aperf_var_hi, edx\n</code></pre>\n\n<p>but note that rdmsr is a privileged instruction and can run only in ring 0.</p>\n\n<p>I don't know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface.</p>\n"
},
{
"answer_id": 118369,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 3,
"selected": false,
"text": "<p>I'm gonna date myself with various details in this answer, but what the heck...</p>\n\n<p>I had to tackle this problem years ago on Windows-based PCs, so I was dealing with Intel x86 series processors like 486, Pentium and so on. The standard algorithm in that situation was to do a long series of DIVide instructions, because those are typically the most CPU-bound single instructions in the Intel set. So memory prefetch and other architectural issues do not materially affect the instruction execution time -- the prefetch queue is always full and the instruction itself does not touch any other memory. </p>\n\n<p>You would time it using the highest resolution clock you could get access to in the environment you are running in. (In my case I was running near boot time on a PC compatible, so I was directly programming the timer chips on the motherboard. Not recommended in a real OS, usually there's some appropriate API to call these days).</p>\n\n<p>The main problem you have to deal with is different CPU types. At that time there was Intel, AMD and some smaller vendors like Cyrix making x86 processors. Each model had its own performance characteristics vis-a-vis that DIV instruction. My assembly timing function would just return a number of clock cycles taken by a certain fixed number of DIV instructions done in a tight loop.</p>\n\n<p>So what I did was to gather some timings (raw return values from that function) from actual PCs running each processor model I wanted to time, and record those in a spreadsheet against the known processor speed and processor type. I actually had a command-line tool that was just a thin shell around my timing function, and I would take a disk into computer stores and get the timings off of display models! (I worked for a very small company at the time).</p>\n\n<p>Using those raw timings, I could plot a theoretical graph of what timings I should get for any known speed of that particular CPU.</p>\n\n<p>Here was the trick: I always hated when you would run a utility and it would announce that your CPU was 99.8 Mhz or whatever. Clearly it was 100 Mhz and there was just a small round-off error in the measurement. In my spreadsheet I recorded the actual speeds that were sold by each processor vendor. Then I would use the plot of actual timings to estimate projected timings for any known speed. But I would build a table of points along the line where the timings should round to the next speed.</p>\n\n<p>In other words, if 100 ticks to do all that repeating dividing meant 500 Mhz, and 200 ticks meant 250 Mhz, then I would build a table that said that anything below 150 was 500 Mhz, and anything above that was 250 Mhz. (Assuming those were the only two speeds available from that chip vendor). It was nice because even if some odd piece of software on the PC was throwing off my timings, the end result would often still be dead on.</p>\n\n<p>Of course now, in these days of overclocking, dynamic clock speeds for power management, and other such trickery, such a scheme would be much less practical. At the very least you'd need to do something to make sure the CPU was in its highest dynamically chosen speed first before running your timing function.</p>\n\n<p>OK, I'll go back to shooing kids off my lawn now.</p>\n"
},
{
"answer_id": 418923,
"author": "Calyth",
"author_id": 45144,
"author_profile": "https://Stackoverflow.com/users/45144",
"pm_score": 0,
"selected": false,
"text": "<p>A quick google on <a href=\"http://www.amd.com/us-en/Processors/ProductInformation/0,,30_118_6291_965%5E871%5E2364,00.html\" rel=\"nofollow noreferrer\">AMD</a> and <a href=\"http://www.intel.com/assets/pdf/appnote/241618.pdf\" rel=\"nofollow noreferrer\">Intel</a> shows that CPUID should give you access to the CPU`s max frequency.</p>\n"
},
{
"answer_id": 689125,
"author": "Sam Liao",
"author_id": 75501,
"author_profile": "https://Stackoverflow.com/users/75501",
"pm_score": 1,
"selected": false,
"text": "<p>\"lmbench\" provides a cpu frequency algorithm portable for different architecture. </p>\n\n<p>It runs some different loops and the processor's clock speed is the greatest common divisor of the execution frequencies of the various loops.</p>\n\n<p>this method should always work when we are able to get loops with cycle counts that are relatively prime. </p>\n\n<p><a href=\"http://www.bitmover.com/lmbench/\" rel=\"nofollow noreferrer\">http://www.bitmover.com/lmbench/</a></p>\n"
},
{
"answer_id": 1048120,
"author": "matja",
"author_id": 115567,
"author_profile": "https://Stackoverflow.com/users/115567",
"pm_score": 2,
"selected": false,
"text": "<p>One way on x86 Intel CPU's since Pentium would be to use two samplings of the RDTSC instruction with a delay loop of known wall time, eg: </p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n#include <unistd.h>\n\nuint64_t rdtsc(void) {\n uint64_t result;\n __asm__ __volatile__ (\"rdtsc\" : \"=A\" (result));\n return result;\n}\n\nint main(void) {\n uint64_t ts0, ts1; \n ts0 = rdtsc();\n sleep(1);\n ts1 = rdtsc(); \n printf(\"clock frequency = %llu\\n\", ts1 - ts0);\n return 0;\n}\n</code></pre>\n\n<p>(on 32-bit platforms with GCC)</p>\n\n<p>RDTSC is available in ring 3 if the TSC flag in CR4 is set, which is common but not guaranteed. One shortcoming of this method is that it is vulnerable to frequency scaling changes affecting the result if they happen inside the delay. To mitigate that you could execute code that keeps the CPU busy and constantly poll the system time to see if your delay period has expired, to keep the CPU in the highest frequency state available.</p>\n"
},
{
"answer_id": 6953905,
"author": "Olof Forshell",
"author_id": 501673,
"author_profile": "https://Stackoverflow.com/users/501673",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following (pseudo)algorithm:</p>\n\n<pre><code>basetime=time(); /* time returns seconds */\n\nwhile (time()==basetime);\nstclk=rdtsc(); /* rdtsc is an assembly instruction */\n\nbasetime=time();\nwhile (time()==basetime\nendclk=rdtsc();\n\nnclks=encdclk-stclk;\n</code></pre>\n\n<p>At this point you might assume that you've determined the clock frequency but even though it appears correct it can be improved.</p>\n\n<p>All PCs contain a PIT (Programmable Interval Timer) device which contains counters which are (used to be) used for serial ports and the system clock. It was fed with a frequency of 1193182 Hz. The system clock counter was set to the highest countdown value (65536) resulting in a system clock tick frequency of 1193182/65536 => 18.2065 Hz or once every 54.925 milliseconds.</p>\n\n<p>The number of ticks necessary for the clock to increment to the next second will therefore depend. Usually 18 ticks are required and sometimes 19. This can be handled by performing the algorithm (above) twice and storing the results. The two results will either be equivalent to two 18 tick sequences or one 18 and one 19. Two 19s in a row won't occur. So by taking the smaller of the two results you will have an 18 tick second. Adjust this result by multiplying with 18.2065 and dividing by 18.0 or, using integer arithmetic, multiply by 182065, add 90000 and divide by 180000. 90000 is one half of 180000 and is there for rounding. If you choose the calculation with integer route make sure you are using 64-bit multiplication and division.</p>\n\n<p>You will now have a CPU clock speed x in Hz which can be converted to kHz ((x+500)/1000) or MHz ((x+5000000)/1000000). The 500 and 500000 are one half of 1000 and 1000000 respectively and are there for rounding. To calculate MHz do not go via the kHz value because rounding issues may arise. Use the Hz value and the second algorithm.</p>\n"
},
{
"answer_id": 33160613,
"author": "Patrick",
"author_id": 4919054,
"author_profile": "https://Stackoverflow.com/users/4919054",
"pm_score": 1,
"selected": false,
"text": "<p>One option is to sense the CPU frequency, by running code with known instructions per loop</p>\n\n<p>This functionality is contained in 7zip, since about v9.20 I think.</p>\n\n<pre><code>> 7z b\n7-Zip 9.38 beta Copyright (c) 1999-2014 Igor Pavlov 2015-01-03\n\nCPU Freq: 4266 4000 4266 4000 2723 4129 3261 3644 3362\n</code></pre>\n\n<p>The final number is meant to be correct (and on my PC and many others, I have found it to be quite correct - the test runs very quick so turbo may not kick in, and servers set in Balanced/Power Save modes most likely give readings of around 1ghz)</p>\n\n<p>The source code is at <a href=\"https://github.com/jljusten/LZMA-SDK/blob/master/CPP/7zip/UI/Common/Bench.cpp\" rel=\"nofollow\">GitHub</a> (Official source is a download from 7-zip.org)</p>\n\n<p>With the most significant portion being:</p>\n\n<pre><code>#define YY1 sum += val; sum ^= val;\n#define YY3 YY1 YY1 YY1 YY1\n#define YY5 YY3 YY3 YY3 YY3\n#define YY7 YY5 YY5 YY5 YY5\nstatic const UInt32 kNumFreqCommands = 128;\n\nEXTERN_C_BEGIN\n\nstatic UInt32 CountCpuFreq(UInt32 sum, UInt32 num, UInt32 val)\n{\n for (UInt32 i = 0; i < num; i++)\n {\n YY7\n }\n return sum;\n}\n\nEXTERN_C_END\n</code></pre>\n"
},
{
"answer_id": 61429118,
"author": "maxschlepzig",
"author_id": 427158,
"author_profile": "https://Stackoverflow.com/users/427158",
"pm_score": 1,
"selected": false,
"text": "<p>On Intel CPUs, a common method to get the current (average) CPU frequency is to calculate it from a few CPU counters:</p>\n\n<pre><code>CPU_freq = tsc_freq * (aperf_t1 - aperf_t0) / (mperf_t1 - mperf_t0)\n</code></pre>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Time_Stamp_Counter\" rel=\"nofollow noreferrer\">TSC</a> (Time Stamp Counter) can be read from userspace with dedicated x86 instructions, but its frequency has to be determined by calibration against a clock. The best approach is to <a href=\"https://stackoverflow.com/a/57835630/427158\">get the TSC frequency from the kernel</a> (which already has done the calibration).</p>\n\n<p>The aperf and mperf counters are model specific registers <a href=\"https://en.wikipedia.org/wiki/Model-specific_register\" rel=\"nofollow noreferrer\">MSRs</a> that require root privileges for access. Again, there are dedicated x86 instructions for accessing the MSRs.</p>\n\n<p>Since the mperf counter rate is directly proportional to the TSC rate and the aperf rate is directly proportional to the CPU frequency you get the CPU frequency with the above equation.</p>\n\n<p>Of course, if the CPU frequency changes in your <code>t0 - t1</code> time delta (e.g. due due frequency scaling) you get the average CPU frequency with this method.</p>\n\n<p>I wrote a small utility <a href=\"https://github.com/gsauthof/utility/blob/master/cpufreq.py\" rel=\"nofollow noreferrer\">cpufreq</a> which can be used to test this method.</p>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://lore.kernel.org/lkml/52f711be59539723358bea1aa3c368910a68b46d.1459485198.git.len.brown@intel.com/\" rel=\"nofollow noreferrer\">[PATCH] x86: Calculate MHz using APERF/MPERF for cpuinfo and scaling_cur_freq. 2016-04-01, LKML</a></li>\n<li><a href=\"https://lwn.net/Articles/816388/\" rel=\"nofollow noreferrer\">Frequency-invariant utilization tracking for x86. 2020-04-02, LWN.net</a></li>\n</ul>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What are the common algorithms being used to measure the processor frequency? | Intel CPUs after Core Duo support two Model-Specific registers called IA32\_MPERF and IA32\_APERF.
MPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency.
The actual frequency is given by:

You can read them with this flow
```
; read MPERF
mov ecx, 0xe7
rdmsr
mov mperf_var_lo, eax
mov mperf_var_hi, edx
; read APERF
mov ecx, 0xe8
rdmsr
mov aperf_var_lo, eax
mov aperf_var_hi, edx
```
but note that rdmsr is a privileged instruction and can run only in ring 0.
I don't know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface. |
65,097 | <p>I'm evaluating Server 2008. My C++ executable is getting this error. I've seen this error on MSDN that seems to have required a hot-fix for several previous OSes. Anyone else seen this? I get the same results for the 32 & 64 bit OS.</p>
<p>Code snippet:</p>
<pre><code>HRESULT GroupStart([in] short iClientId, [in] VARIANT GroupDataArray,
[out] short* pGroupInstance, [out] long* pCommandId);
</code></pre>
<p>Where the GroupDataArray VARIANT argument wraps a single-dimension SAFEARRAY of VARIANTs wrapping a DCAPICOM_GroupData struct entries:</p>
<pre><code>// DCAPICOM_GroupData
[
uuid(F1FE2605-2744-4A2A-AB85-1E1845C280EB),
helpstring("removed")
]
typedef struct DCAPICOM_GroupData {
[helpstring("removed")]
long m_lImageID;
[helpstring("removed")]
unsigned char m_ucHeadID;
[helpstring("removed")]
unsigned char m_ucPlateID;
} DCAPICOM_GroupData;
</code></pre>
| [
{
"answer_id": 66322,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>We ran into the same error recently with a client/server app communicating via DCOM. It turned out that the size of a marshalled interface pointer going across the wire (i.e., not local) had changed (gotten bigger). You might like to check whether your code is doing any special marshalling via CoMarshalInterface or the like.</p>\n"
},
{
"answer_id": 140746,
"author": "creohornet",
"author_id": 9111,
"author_profile": "https://Stackoverflow.com/users/9111",
"pm_score": 2,
"selected": false,
"text": "<p>After opening a support case with Microsoft, I can now answer my own question. This is (now) a recognized <strong>bug</strong>. The issue has to do with marshalling on the server side, but before the server code is called. Our structure is 6 bytes long, but this COM implementation is interpreting it as 8, so the marshalling fails, and this is the error you get back. The workaround, until a Service Pack is released to deal with this, is to add two extra bytes to the structure to pad it up to 8 bytes. We haven't run across any more instances that fail yet, but we still have a lot of testing to do still.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9111/"
]
| I'm evaluating Server 2008. My C++ executable is getting this error. I've seen this error on MSDN that seems to have required a hot-fix for several previous OSes. Anyone else seen this? I get the same results for the 32 & 64 bit OS.
Code snippet:
```
HRESULT GroupStart([in] short iClientId, [in] VARIANT GroupDataArray,
[out] short* pGroupInstance, [out] long* pCommandId);
```
Where the GroupDataArray VARIANT argument wraps a single-dimension SAFEARRAY of VARIANTs wrapping a DCAPICOM\_GroupData struct entries:
```
// DCAPICOM_GroupData
[
uuid(F1FE2605-2744-4A2A-AB85-1E1845C280EB),
helpstring("removed")
]
typedef struct DCAPICOM_GroupData {
[helpstring("removed")]
long m_lImageID;
[helpstring("removed")]
unsigned char m_ucHeadID;
[helpstring("removed")]
unsigned char m_ucPlateID;
} DCAPICOM_GroupData;
``` | We ran into the same error recently with a client/server app communicating via DCOM. It turned out that the size of a marshalled interface pointer going across the wire (i.e., not local) had changed (gotten bigger). You might like to check whether your code is doing any special marshalling via CoMarshalInterface or the like. |
65,170 | <p>What's the easiest way to get the filename associated with an open HANDLE in Win32?</p>
| [
{
"answer_id": 65252,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 0,
"selected": false,
"text": "<p>On unixes there is no real way of reliably doing this. In unix with the traditional unix filesystem, you can open a file and then unlink it (remove its entry from the directory) and use it, at which point the name isn't stored anywhere. In addition, because a file may have multiple hardlinks into the filesystem, each of the names are equivalent, so once you've got just the open handle it wouldn't be clear which filename you should map back towards.</p>\n\n<p>So, you may be able to do this on Win32 using the other answers, but should you ever need to port the application to a unix enviornment, you'll be out of luck. My advice to you is to refactor your program, if possible, so that you don't need the OS to be able to maintain an open resource to filename connection.</p>\n"
},
{
"answer_id": 65254,
"author": "Taylor Price",
"author_id": 3805,
"author_profile": "https://Stackoverflow.com/users/3805",
"pm_score": 2,
"selected": false,
"text": "<p><em>edit</em> Thanks for the comments about this being Vista or Server 2008 only. I missed that in the page. Guess I should have read the <em>whole</em> article ;)</p>\n\n<p>It looks like you can use <a href=\"http://msdn.microsoft.com/en-us/library/aa364953.aspx\" rel=\"nofollow noreferrer\">GetFileInformationByHandleEx()</a> to get this information.</p>\n\n<p>You'll likely want to do something like:</p>\n\n<pre><code>GetFileInformationByHandleEx( fileHandle, FILE_NAME_INFO, lpFileInformation, sizeof(FILE_NAME_INFO));\n</code></pre>\n\n<p>Double check the MSDN page to make sure I haven't misled you too badly :)</p>\n\n<p>Cheers,</p>\n\n<p>Taylor</p>\n"
},
{
"answer_id": 65417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to do this on Win32 pre-Vista or Server 2008, look at the <code>GetMappedFileName(...)</code> function, which is one of the best kept secrets in Win32. WIth a little <code>C/C++-</code><em>fu</em>, you can memory map a small portion of the file in question, and then pass that handle to this function.</p>\n\n<p>Also, on Win32, you cannot really delete a file that is open (the open/unlink issue mentioned on another answer) - you can mark it for deletion on close, but it will still hang around until its last open handle is closed. Dunno if mapping (via <code>mmap(...)</code>) the file in this case would help, because it has to point back to a physical file...</p>\n\n<p>-=- James.</p>\n"
},
{
"answer_id": 65775,
"author": "Max Caceres",
"author_id": 4842,
"author_profile": "https://Stackoverflow.com/users/4842",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, here's the same solution from the MSDN article suggested by Prakash in Python using the wonderful <a href=\"http://python.net/crew/theller/ctypes/\" rel=\"nofollow noreferrer\">ctypes</a>:</p>\n\n<pre><code>from ctypes import *\n# get handle to c:\\boot.ini to test\nhandle = windll.kernel32.CreateFileA(\"c:\\\\boot.ini\", 0x80000000, 3, 0, 3, 0x80, 0)\nhfilemap = windll.kernel32.CreateFileMappingA(handle, 0, 2, 0, 1, 0)\npmem = windll.kernel32.MapViewOfFile(hfilemap, 4, 0, 0, 1)\nname = create_string_buffer(1024)\nwindll.psapi.GetMappedFileNameA(windll.kernel32.GetCurrentProcess(), pmem, name, 1024)\nprint \"The name for the handle 0x%08x is %s\" % (handle, name.value)\n# convert device name to drive letter\nbuf = create_string_buffer(512)\nsize = windll.kernel32.GetLogicalDriveStringsA(511, buf)\nnames = buf.raw[0:size-1].split(\"\\0\")\nfor drive in names:\n windll.kernel32.QueryDosDeviceA(drive[0:2], buf, 512)\n if name.value.startswith(buf.value):\n print \"%s%s\" % (drive[0:2], name.value[len(buf.value):])\n break\n</code></pre>\n"
},
{
"answer_id": 5286888,
"author": "user541686",
"author_id": 541686,
"author_profile": "https://Stackoverflow.com/users/541686",
"pm_score": 4,
"selected": false,
"text": "<p>There is a correct (although undocumented) way to do this on Windows XP <strong>which also works with directories</strong> -- the same method <a href=\"http://msdn.microsoft.com/en-us/library/aa364962.aspx\" rel=\"noreferrer\">GetFinalPathNameByHandle</a> uses on Windows Vista and later.</p>\n\n<p>Here are the eneded declarations. Some of these are already in <code>WInternl.h</code> and <code>MountMgr.h</code> but I just put them here anyway:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include <Windows.h>\n#include <assert.h>\n\nenum OBJECT_INFORMATION_CLASS { ObjectNameInformation = 1 };\nenum FILE_INFORMATION_CLASS { FileNameInformation = 9 };\nstruct FILE_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; };\nstruct IO_STATUS_BLOCK { PVOID Dummy; ULONG_PTR Information; };\nstruct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; };\nstruct MOUNTMGR_TARGET_NAME { USHORT DeviceNameLength; WCHAR DeviceName[1]; };\nstruct MOUNTMGR_VOLUME_PATHS { ULONG MultiSzLength; WCHAR MultiSz[1]; };\n\nextern \"C\" NTSYSAPI NTSTATUS NTAPI NtQueryObject(IN HANDLE Handle OPTIONAL,\n IN OBJECT_INFORMATION_CLASS ObjectInformationClass,\n OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength,\n OUT PULONG ReturnLength OPTIONAL);\nextern \"C\" NTSYSAPI NTSTATUS NTAPI NtQueryInformationFile(IN HANDLE FileHandle,\n OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation,\n IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass);\n\n#define MOUNTMGRCONTROLTYPE ((ULONG) 'm')\n#define IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH \\\n CTL_CODE(MOUNTMGRCONTROLTYPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)\n\nunion ANY_BUFFER {\n MOUNTMGR_TARGET_NAME TargetName;\n MOUNTMGR_VOLUME_PATHS TargetPaths;\n FILE_NAME_INFORMATION NameInfo;\n UNICODE_STRING UnicodeString;\n WCHAR Buffer[USHRT_MAX];\n};\n</code></pre>\n\n<p>Here's the core function:</p>\n\n<pre><code>LPWSTR GetFilePath(HANDLE hFile)\n{\n static ANY_BUFFER nameFull, nameRel, nameMnt;\n ULONG returnedLength; IO_STATUS_BLOCK iosb; NTSTATUS status;\n status = NtQueryObject(hFile, ObjectNameInformation,\n nameFull.Buffer, sizeof(nameFull.Buffer), &returnedLength);\n assert(status == 0);\n status = NtQueryInformationFile(hFile, &iosb, nameRel.Buffer,\n sizeof(nameRel.Buffer), FileNameInformation);\n assert(status == 0);\n //I'm not sure how this works with network paths...\n assert(nameFull.UnicodeString.Length >= nameRel.NameInfo.FileNameLength);\n nameMnt.TargetName.DeviceNameLength = (USHORT)(\n nameFull.UnicodeString.Length - nameRel.NameInfo.FileNameLength);\n wcsncpy(nameMnt.TargetName.DeviceName, nameFull.UnicodeString.Buffer,\n nameMnt.TargetName.DeviceNameLength / sizeof(WCHAR));\n HANDLE hMountPointMgr = CreateFile(_T(\"\\\\\\\\.\\\\MountPointManager\"),\n 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n NULL, OPEN_EXISTING, 0, NULL);\n __try\n {\n DWORD bytesReturned;\n BOOL success = DeviceIoControl(hMountPointMgr,\n IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH, &nameMnt,\n sizeof(nameMnt), &nameMnt, sizeof(nameMnt),\n &bytesReturned, NULL);\n assert(success && nameMnt.TargetPaths.MultiSzLength > 0);\n wcsncat(nameMnt.TargetPaths.MultiSz, nameRel.NameInfo.FileName,\n nameRel.NameInfo.FileNameLength / sizeof(WCHAR));\n return nameMnt.TargetPaths.MultiSz;\n }\n __finally { CloseHandle(hMountPointMgr); }\n}\n</code></pre>\n\n<p>and here's an example usage:</p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n{\n HANDLE hFile = CreateFile(_T(\"\\\\\\\\.\\\\C:\\\\Windows\\\\Notepad.exe\"),\n 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);\n assert(hFile != NULL && hFile != INVALID_HANDLE_VALUE);\n __try\n {\n wprintf(L\"%s\\n\", GetFilePath(hFile));\n // Prints:\n // C:\\Windows\\notepad.exe\n }\n __finally { CloseHandle(hFile); }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 18792477,
"author": "Elmue",
"author_id": 1487529,
"author_profile": "https://Stackoverflow.com/users/1487529",
"pm_score": 4,
"selected": false,
"text": "<p>I tried the code posted by Mehrdad here. It works, but with limitations:</p>\n\n<ol>\n<li>It should not be used for network shares because the MountPointManager may hang for a very long time.</li>\n<li>It uses undocumented API (IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH) I don't like that very much</li>\n<li>It does not support USB devices that create virtual COM ports (I need that in my project)</li>\n</ol>\n\n<p>I also studied other approaches like <code>GetFileInformationByHandleEx()</code> and <code>GetFinalPathNameByHandle()</code>, but these are useless as they return only Path + Filename but without drive. Additionally <code>GetFinalPathNameByHandle()</code> also has the hanging bug.</p>\n\n<p>The <code>GetMappedFileName()</code> approach in the MSDN (posted by Max here) is also very limited:</p>\n\n<ol>\n<li>It works only with real files</li>\n<li>The file size must not be zero bytes</li>\n<li>Directories, Network and COM ports are not supported</li>\n<li>The code is clumsy</li>\n</ol>\n\n<p>So I wrote my own code. I tested it on Win XP and on Win 7, 8, and 10. It works perfectly.</p>\n\n<p>NOTE: You do NOT need any additional LIB file to compile this code!</p>\n\n<p><strong>CPP FILE:</strong></p>\n\n<pre><code>t_NtQueryObject NtQueryObject()\n{\n static t_NtQueryObject f_NtQueryObject = NULL;\n if (!f_NtQueryObject)\n {\n HMODULE h_NtDll = GetModuleHandle(L\"Ntdll.dll\"); // Ntdll is loaded into EVERY process!\n f_NtQueryObject = (t_NtQueryObject)GetProcAddress(h_NtDll, \"NtQueryObject\");\n }\n return f_NtQueryObject;\n}\n\n\n// returns\n// \"\\Device\\HarddiskVolume3\" (Harddisk Drive)\n// \"\\Device\\HarddiskVolume3\\Temp\" (Harddisk Directory)\n// \"\\Device\\HarddiskVolume3\\Temp\\transparent.jpeg\" (Harddisk File)\n// \"\\Device\\Harddisk1\\DP(1)0-0+6\\foto.jpg\" (USB stick)\n// \"\\Device\\TrueCryptVolumeP\\Data\\Passwords.txt\" (Truecrypt Volume)\n// \"\\Device\\Floppy0\\Autoexec.bat\" (Floppy disk)\n// \"\\Device\\CdRom1\\VIDEO_TS\\VTS_01_0.VOB\" (DVD drive)\n// \"\\Device\\Serial1\" (real COM port)\n// \"\\Device\\USBSER000\" (virtual COM port)\n// \"\\Device\\Mup\\ComputerName\\C$\\Boot.ini\" (network drive share, Windows 7)\n// \"\\Device\\LanmanRedirector\\ComputerName\\C$\\Boot.ini\" (network drive share, Windwos XP)\n// \"\\Device\\LanmanRedirector\\ComputerName\\Shares\\Dance.m3u\" (network folder share, Windwos XP)\n// \"\\Device\\Afd\" (internet socket)\n// \"\\Device\\Console000F\" (unique name for any Console handle)\n// \"\\Device\\NamedPipe\\Pipename\" (named pipe)\n// \"\\BaseNamedObjects\\Objectname\" (named mutex, named event, named semaphore)\n// \"\\REGISTRY\\MACHINE\\SOFTWARE\\Classes\\.txt\" (HKEY_CLASSES_ROOT\\.txt)\nDWORD GetNtPathFromHandle(HANDLE h_File, CString* ps_NTPath)\n{\n if (h_File == 0 || h_File == INVALID_HANDLE_VALUE)\n return ERROR_INVALID_HANDLE;\n\n // NtQueryObject() returns STATUS_INVALID_HANDLE for Console handles\n if (IsConsoleHandle(h_File))\n {\n ps_NTPath->Format(L\"\\\\Device\\\\Console%04X\", (DWORD)(DWORD_PTR)h_File);\n return 0;\n }\n\n BYTE u8_Buffer[2000];\n DWORD u32_ReqLength = 0;\n\n UNICODE_STRING* pk_Info = &((OBJECT_NAME_INFORMATION*)u8_Buffer)->Name;\n pk_Info->Buffer = 0;\n pk_Info->Length = 0;\n\n // IMPORTANT: The return value from NtQueryObject is bullshit! (driver bug?)\n // - The function may return STATUS_NOT_SUPPORTED although it has successfully written to the buffer.\n // - The function returns STATUS_SUCCESS although h_File == 0xFFFFFFFF\n NtQueryObject()(h_File, ObjectNameInformation, u8_Buffer, sizeof(u8_Buffer), &u32_ReqLength);\n\n // On error pk_Info->Buffer is NULL\n if (!pk_Info->Buffer || !pk_Info->Length)\n return ERROR_FILE_NOT_FOUND;\n\n pk_Info->Buffer[pk_Info->Length /2] = 0; // Length in Bytes!\n\n *ps_NTPath = pk_Info->Buffer;\n return 0;\n}\n\n// converts\n// \"\\Device\\HarddiskVolume3\" -> \"E:\"\n// \"\\Device\\HarddiskVolume3\\Temp\" -> \"E:\\Temp\"\n// \"\\Device\\HarddiskVolume3\\Temp\\transparent.jpeg\" -> \"E:\\Temp\\transparent.jpeg\"\n// \"\\Device\\Harddisk1\\DP(1)0-0+6\\foto.jpg\" -> \"I:\\foto.jpg\"\n// \"\\Device\\TrueCryptVolumeP\\Data\\Passwords.txt\" -> \"P:\\Data\\Passwords.txt\"\n// \"\\Device\\Floppy0\\Autoexec.bat\" -> \"A:\\Autoexec.bat\"\n// \"\\Device\\CdRom1\\VIDEO_TS\\VTS_01_0.VOB\" -> \"H:\\VIDEO_TS\\VTS_01_0.VOB\"\n// \"\\Device\\Serial1\" -> \"COM1\"\n// \"\\Device\\USBSER000\" -> \"COM4\"\n// \"\\Device\\Mup\\ComputerName\\C$\\Boot.ini\" -> \"\\\\ComputerName\\C$\\Boot.ini\"\n// \"\\Device\\LanmanRedirector\\ComputerName\\C$\\Boot.ini\" -> \"\\\\ComputerName\\C$\\Boot.ini\"\n// \"\\Device\\LanmanRedirector\\ComputerName\\Shares\\Dance.m3u\" -> \"\\\\ComputerName\\Shares\\Dance.m3u\"\n// returns an error for any other device type\nDWORD GetDosPathFromNtPath(const WCHAR* u16_NTPath, CString* ps_DosPath)\n{\n DWORD u32_Error;\n\n if (wcsnicmp(u16_NTPath, L\"\\\\Device\\\\Serial\", 14) == 0 || // e.g. \"Serial1\"\n wcsnicmp(u16_NTPath, L\"\\\\Device\\\\UsbSer\", 14) == 0) // e.g. \"USBSER000\"\n {\n HKEY h_Key; \n if (u32_Error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L\"Hardware\\\\DeviceMap\\\\SerialComm\", 0, KEY_QUERY_VALUE, &h_Key))\n return u32_Error;\n\n WCHAR u16_ComPort[50];\n\n DWORD u32_Type;\n DWORD u32_Size = sizeof(u16_ComPort); \n if (u32_Error = RegQueryValueEx(h_Key, u16_NTPath, 0, &u32_Type, (BYTE*)u16_ComPort, &u32_Size))\n {\n RegCloseKey(h_Key);\n return ERROR_UNKNOWN_PORT;\n }\n\n *ps_DosPath = u16_ComPort;\n RegCloseKey(h_Key);\n return 0;\n }\n\n if (wcsnicmp(u16_NTPath, L\"\\\\Device\\\\LanmanRedirector\\\\\", 25) == 0) // Win XP\n {\n *ps_DosPath = L\"\\\\\\\\\";\n *ps_DosPath += (u16_NTPath + 25);\n return 0;\n }\n\n if (wcsnicmp(u16_NTPath, L\"\\\\Device\\\\Mup\\\\\", 12) == 0) // Win 7\n {\n *ps_DosPath = L\"\\\\\\\\\";\n *ps_DosPath += (u16_NTPath + 12);\n return 0;\n }\n\n WCHAR u16_Drives[300];\n if (!GetLogicalDriveStrings(300, u16_Drives))\n return GetLastError();\n\n WCHAR* u16_Drv = u16_Drives;\n while (u16_Drv[0])\n {\n WCHAR* u16_Next = u16_Drv +wcslen(u16_Drv) +1;\n\n u16_Drv[2] = 0; // the backslash is not allowed for QueryDosDevice()\n\n WCHAR u16_NtVolume[1000];\n u16_NtVolume[0] = 0;\n\n // may return multiple strings!\n // returns very weird strings for network shares\n if (!QueryDosDevice(u16_Drv, u16_NtVolume, sizeof(u16_NtVolume) /2))\n return GetLastError();\n\n int s32_Len = (int)wcslen(u16_NtVolume);\n if (s32_Len > 0 && wcsnicmp(u16_NTPath, u16_NtVolume, s32_Len) == 0)\n {\n *ps_DosPath = u16_Drv;\n *ps_DosPath += (u16_NTPath + s32_Len);\n return 0;\n }\n\n u16_Drv = u16_Next;\n }\n return ERROR_BAD_PATHNAME;\n}\n</code></pre>\n\n<p><strong>HEADER FILE:</strong></p>\n\n<pre><code>#pragma warning(disable: 4996) // wcsnicmp deprecated\n#include <winternl.h>\n\n// This makro assures that INVALID_HANDLE_VALUE (0xFFFFFFFF) returns FALSE\n#define IsConsoleHandle(h) (((((ULONG_PTR)h) & 0x10000003) == 0x3) ? TRUE : FALSE)\n\nenum OBJECT_INFORMATION_CLASS \n{\n ObjectBasicInformation, \n ObjectNameInformation,\n ObjectTypeInformation, \n ObjectAllInformation, \n ObjectDataInformation\n};\n\nstruct OBJECT_NAME_INFORMATION \n{\n UNICODE_STRING Name; // defined in winternl.h\n WCHAR NameBuffer;\n};\n\ntypedef NTSTATUS (NTAPI* t_NtQueryObject)(HANDLE Handle, OBJECT_INFORMATION_CLASS Info, PVOID Buffer, ULONG BufferSize, PULONG ReturnLength); \n</code></pre>\n"
},
{
"answer_id": 35863703,
"author": "Holger",
"author_id": 4727717,
"author_profile": "https://Stackoverflow.com/users/4727717",
"pm_score": 1,
"selected": false,
"text": "<p>For Windows Vista and later I prefer to use \n<a href=\"https://msdn.microsoft.com/en-us/library/aa364962.aspx\" rel=\"nofollow noreferrer\">GetFinalPathNameByHandle()</a></p>\n\n<pre><code>char buf[MAX_PATH];\nGetFinalPathNameByHandleA(fileHandle, buf, sizeof(buf), VOLUME_NAME_DOS)\n</code></pre>\n\n<p>For Windows XP I prefer the <a href=\"https://stackoverflow.com/a/5286888/4727717.\">solution by Mehrdad</a>. </p>\n\n<p>So I load GetFinalPathNameByHandle() dynamically via GetProcAddress() and if this fails (because it's Windows XP) I go for Mehrdad's solution with NtQueryObject()</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4842/"
]
| What's the easiest way to get the filename associated with an open HANDLE in Win32? | There is a correct (although undocumented) way to do this on Windows XP **which also works with directories** -- the same method [GetFinalPathNameByHandle](http://msdn.microsoft.com/en-us/library/aa364962.aspx) uses on Windows Vista and later.
Here are the eneded declarations. Some of these are already in `WInternl.h` and `MountMgr.h` but I just put them here anyway:
```
#include "stdafx.h"
#include <Windows.h>
#include <assert.h>
enum OBJECT_INFORMATION_CLASS { ObjectNameInformation = 1 };
enum FILE_INFORMATION_CLASS { FileNameInformation = 9 };
struct FILE_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; };
struct IO_STATUS_BLOCK { PVOID Dummy; ULONG_PTR Information; };
struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; };
struct MOUNTMGR_TARGET_NAME { USHORT DeviceNameLength; WCHAR DeviceName[1]; };
struct MOUNTMGR_VOLUME_PATHS { ULONG MultiSzLength; WCHAR MultiSz[1]; };
extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryObject(IN HANDLE Handle OPTIONAL,
IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength,
OUT PULONG ReturnLength OPTIONAL);
extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryInformationFile(IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation,
IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass);
#define MOUNTMGRCONTROLTYPE ((ULONG) 'm')
#define IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH \
CTL_CODE(MOUNTMGRCONTROLTYPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
union ANY_BUFFER {
MOUNTMGR_TARGET_NAME TargetName;
MOUNTMGR_VOLUME_PATHS TargetPaths;
FILE_NAME_INFORMATION NameInfo;
UNICODE_STRING UnicodeString;
WCHAR Buffer[USHRT_MAX];
};
```
Here's the core function:
```
LPWSTR GetFilePath(HANDLE hFile)
{
static ANY_BUFFER nameFull, nameRel, nameMnt;
ULONG returnedLength; IO_STATUS_BLOCK iosb; NTSTATUS status;
status = NtQueryObject(hFile, ObjectNameInformation,
nameFull.Buffer, sizeof(nameFull.Buffer), &returnedLength);
assert(status == 0);
status = NtQueryInformationFile(hFile, &iosb, nameRel.Buffer,
sizeof(nameRel.Buffer), FileNameInformation);
assert(status == 0);
//I'm not sure how this works with network paths...
assert(nameFull.UnicodeString.Length >= nameRel.NameInfo.FileNameLength);
nameMnt.TargetName.DeviceNameLength = (USHORT)(
nameFull.UnicodeString.Length - nameRel.NameInfo.FileNameLength);
wcsncpy(nameMnt.TargetName.DeviceName, nameFull.UnicodeString.Buffer,
nameMnt.TargetName.DeviceNameLength / sizeof(WCHAR));
HANDLE hMountPointMgr = CreateFile(_T("\\\\.\\MountPointManager"),
0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, 0, NULL);
__try
{
DWORD bytesReturned;
BOOL success = DeviceIoControl(hMountPointMgr,
IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH, &nameMnt,
sizeof(nameMnt), &nameMnt, sizeof(nameMnt),
&bytesReturned, NULL);
assert(success && nameMnt.TargetPaths.MultiSzLength > 0);
wcsncat(nameMnt.TargetPaths.MultiSz, nameRel.NameInfo.FileName,
nameRel.NameInfo.FileNameLength / sizeof(WCHAR));
return nameMnt.TargetPaths.MultiSz;
}
__finally { CloseHandle(hMountPointMgr); }
}
```
and here's an example usage:
```
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hFile = CreateFile(_T("\\\\.\\C:\\Windows\\Notepad.exe"),
0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
assert(hFile != NULL && hFile != INVALID_HANDLE_VALUE);
__try
{
wprintf(L"%s\n", GetFilePath(hFile));
// Prints:
// C:\Windows\notepad.exe
}
__finally { CloseHandle(hFile); }
return 0;
}
``` |
65,173 | <p>I'm trying to run PHP from the command line under <a href="https://en.wikipedia.org/wiki/Windows_XP" rel="nofollow noreferrer">Windows XP</a>.</p>
<p>That works, except for the fact that I am not able to provide parameters to my PHP script.</p>
<p>My test case:</p>
<pre><code>echo "param = " . $param . "\n";
var_dump($argv);
</code></pre>
<p>I want to call this as:</p>
<pre><code>php.exe -f test.php -- param=test
</code></pre>
<p>But I never get the script to accept my parameter.</p>
<p>The result I get from the above script:</p>
<blockquote>
<p>PHP Notice: Undefined variable: param in C:\test.php on line 2</p>
</blockquote>
<pre><code>param = ''
array(2) {
[0]=> string(8) "test.php"
[1]=> string(10) "param=test"
}
</code></pre>
<p>I am trying this using PHP 5.2.6. Is this a bug in PHP 5?</p>
<p>The parameter passing is handled in the <a href="http://us3.php.net/features.commandline" rel="nofollow noreferrer">online help</a>:</p>
<blockquote>
<p>Note: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.</p>
</blockquote>
<p>This seemed to be working under PHP 4, but not under PHP 5.</p>
<p>Under PHP 4 I could use the same script that could run on the server without alteration on the command line. This is handy for local debugging, for example, saving the output in a file, to be studied.</p>
| [
{
"answer_id": 65233,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "<p>Why do you have any expectation that <em>param</em> will be set to the value?</p>\n<p>You're responsible for parsing the command line in the fashion you desire, from the <em>$argv</em> array.</p>\n"
},
{
"answer_id": 65269,
"author": "Ben",
"author_id": 5005,
"author_profile": "https://Stackoverflow.com/users/5005",
"pm_score": 0,
"selected": false,
"text": "<p>$argv is an array containing all your commandline parameters... You need to parse that array and set $param yourself.</p>\n\n<pre><code>$tmp = $argv[1]; // $tmp=\"param=test\"\n$tmp = explode(\"=\", $tmp); // $tmp=Array( 0 => param, 1 => test)\n\n$param = $tmp[1]; // $param = \"test\";\n</code></pre>\n"
},
{
"answer_id": 65299,
"author": "Jeremy Weathers",
"author_id": 8794,
"author_profile": "https://Stackoverflow.com/users/8794",
"pm_score": 1,
"selected": false,
"text": "<p>PHP does not parameterize your command line parameters for you. See the output where your second entry in <code>ARGV</code> is "param=test".</p>\n<p>You most likely want to use the PEAR package <a href=\"http://pear.php.net/package/Console_CommandLine\" rel=\"nofollow noreferrer\">Console_CommandLine</a>: "A full featured command line options and arguments parser".</p>\n<p>Or you can be masochistic and add code to go through your <code>ARGV</code> and set the parameters yourself. Here's a very simplistic snippet to get you started (this won't work if the first part isn't a valid variable name or there is more than 1 '=' in an <code>ARGV</code> part:</p>\n<pre><code>foreach($argv as $v) {\n if(false !== strpos($v, '=')) {\n $parts = explode('=', $v);\n ${$parts[0]} = $parts[1];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 65308,
"author": "Derek Kurth",
"author_id": 1418,
"author_profile": "https://Stackoverflow.com/users/1418",
"pm_score": 0,
"selected": false,
"text": "<p>You can do something like:</p>\n\n<pre><code>if($argc > 1){\n if($argv[1] == 'param=test'){\n $param = 'test';\n }\n}\n</code></pre>\n\n<p>Of course, you can get much more complicated than that as needed.</p>\n"
},
{
"answer_id": 65359,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>The parameter passing is handled in the online help Note: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch. This seemed to be working under PHP 4, but not under PHP 5.</p>\n</blockquote>\n<p>But PHP still doesn't parse those arguments. It just passes them to the script in the <em>$argv</em> array.</p>\n<p>The only reason for the <strong>--</strong> is so that PHP can tell which arguments are meant for the PHP executable and which arguments are meant for your script.</p>\n<p>That lets you do things like this:</p>\n<pre><code>php -e -n -f myScript.php -- -f -n -e\n</code></pre>\n<p>(The -f, -n, and -e options <strong>after</strong> the <code>--</code> are passed to file <em>myScript.php</em>. The ones before are passed to PHP itself).</p>\n"
},
{
"answer_id": 65709,
"author": "farzad",
"author_id": 9394,
"author_profile": "https://Stackoverflow.com/users/9394",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the $argv array. Like this:</p>\n<pre><code><?php\n echo $argv[1];\n?>\n</code></pre>\n<p>Remember that the first member of the <em>$argv</em> array (which is <em>$argv[0]</em>) is the name of the script itself, so in order to use the parameters for the application, you should start using members of the <em>$argv[]</em> from the '1'th index.</p>\n<p>When calling the application, use this syntax:</p>\n<pre><code>php myscript.php -- myValue\n</code></pre>\n<p>There isn't any need to put a name for the parameter. As you saw, what you called the <em>var_dump()</em> on the <em>$argv[]</em>, the second member (which is the first parameter) was the string <em>PARAM=TEST</em>. Right? So there isn't any need to put a name for the param. Just enter the <em>param</em> value.</p>\n"
},
{
"answer_id": 66690,
"author": "rcphq",
"author_id": 9114,
"author_profile": "https://Stackoverflow.com/users/9114",
"pm_score": 0,
"selected": false,
"text": "<p>You could use something like</p>\n<pre><code>if (isset($argv[1]) {\n $arg1 = $argv[1];\n $arg1 = explode("=", $arg1);\n $param = $arg1[1];\n}\n</code></pre>\n<p>(How to handle the lack of parameters is up to you.)</p>\n<p>Or if you need a more complex scenario, look into a command-line parser library, such as the one from <a href=\"http://pear.php.net/package/Console_CommandLine\" rel=\"nofollow noreferrer\">Pear</a>.</p>\n<p>Using the <code>${$parts[0]} = $parts[1];</code> posted in another solution lets you override any variable in your code, which <strong>doesn’t really sound safe</strong>.</p>\n"
},
{
"answer_id": 1557173,
"author": "kander",
"author_id": 151847,
"author_profile": "https://Stackoverflow.com/users/151847",
"pm_score": 0,
"selected": false,
"text": "<p>If you like living on the cutting edge, PHP 5.3 has the <a href=\"http://php.net/getopt\" rel=\"nofollow noreferrer\">getOpt()</a> command which will take care of all this messy business for you. Somewhat.</p>\n"
},
{
"answer_id": 5978116,
"author": "Chetan Sharma",
"author_id": 170445,
"author_profile": "https://Stackoverflow.com/users/170445",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://in2.php.net/getopt\" rel=\"nofollow noreferrer\">getopt()</a> function.</p>\n<p>Check blog post <em><a href=\"http://sharingphp.blogspot.com/2011/04/php-cli-script-and-command-line.html\" rel=\"nofollow noreferrer\">PHP CLI script and Command line arguments</a></em>.</p>\n"
},
{
"answer_id": 6156922,
"author": "Gerrit",
"author_id": 773654,
"author_profile": "https://Stackoverflow.com/users/773654",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to pass the parameters similar to GET variables, then you can use the <a href=\"http://us.php.net/manual/en/function.parse-str.php\" rel=\"nofollow noreferrer\">parse_str()</a> function. Something similar to this:</p>\n<pre><code><?php\n parse_str($argv[1]);\n?>\n</code></pre>\n<p>Would produce a variable, <em>$test</em>, with a value of <myValue>.</p>\n"
},
{
"answer_id": 26269594,
"author": "M.Hefny",
"author_id": 637718,
"author_profile": "https://Stackoverflow.com/users/637718",
"pm_score": 1,
"selected": false,
"text": "<p>Command-line example:</p>\n<pre class=\"lang-none prettyprint-override\"><code> php myserver.php host=192.168.1.4 port=9000\n</code></pre>\n<p>In file <em>myserver.php</em>, use the following lines:</p>\n<pre><code><?php\n parse_str(implode('&', array_slice($argv, 1)), $_GET);\n // Read arguments\n\n if (array_key_exists('host', $_GET))\n {\n $host = $_GET['host'];\n }\n\n if (array_key_exists('port', $_GET))\n {\n $port = $_GET['port'];\n }\n?>\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to run PHP from the command line under [Windows XP](https://en.wikipedia.org/wiki/Windows_XP).
That works, except for the fact that I am not able to provide parameters to my PHP script.
My test case:
```
echo "param = " . $param . "\n";
var_dump($argv);
```
I want to call this as:
```
php.exe -f test.php -- param=test
```
But I never get the script to accept my parameter.
The result I get from the above script:
>
> PHP Notice: Undefined variable: param in C:\test.php on line 2
>
>
>
```
param = ''
array(2) {
[0]=> string(8) "test.php"
[1]=> string(10) "param=test"
}
```
I am trying this using PHP 5.2.6. Is this a bug in PHP 5?
The parameter passing is handled in the [online help](http://us3.php.net/features.commandline):
>
> Note: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.
>
>
>
This seemed to be working under PHP 4, but not under PHP 5.
Under PHP 4 I could use the same script that could run on the server without alteration on the command line. This is handy for local debugging, for example, saving the output in a file, to be studied. | Why do you have any expectation that *param* will be set to the value?
You're responsible for parsing the command line in the fashion you desire, from the *$argv* array. |
65,205 | <p>What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order?</p>
| [
{
"answer_id": 65229,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": -1,
"selected": false,
"text": "<p>A list can be stored by having a column contain the offset (list index position) -- an insert in the middle is then incrementing all above the new parent and then doing an insert.</p>\n"
},
{
"answer_id": 65238,
"author": "Adrian Dunston",
"author_id": 8344,
"author_profile": "https://Stackoverflow.com/users/8344",
"pm_score": 5,
"selected": true,
"text": "<p>Store an integer column in your table called 'position'. Record a 0 for the first item in your list, a 1 for the second item, etc. Index that column in your database, and when you want to pull your values out, sort by that column.</p>\n\n<pre><code> alter table linked_list add column position integer not null default 0;\n alter table linked_list add index position_index (position);\n select * from linked_list order by position;\n</code></pre>\n\n<p>To insert a value at index 3, modify the positions of rows 3 and above, and then insert:</p>\n\n<pre><code> update linked_list set position = position + 1 where position >= 3;\n insert into linked_list (my_value, position) values (\"new value\", 3); \n</code></pre>\n"
},
{
"answer_id": 65276,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": false,
"text": "<p>Using Adrian's solution, but instead of incrementing by 1, increment by 10 or even 100. Then insertions can be calculated at half of the difference of what you're inserting between without having to update everything below the insertion. Pick a number large enough to handle your average number of insertions - if its too small then you'll have to fall back to updating all rows with a higher position during an insertion.</p>\n"
},
{
"answer_id": 65283,
"author": "user9252",
"author_id": 9252,
"author_profile": "https://Stackoverflow.com/users/9252",
"pm_score": 2,
"selected": false,
"text": "<p>A linked list can be stored using recursive pointers in the table. This is very much the same hierarchies are stored in Sql and this is using the recursive association pattern.</p>\n\n<p>You can learn more about it <a href=\"https://web.archive.org/web/20180729174436/http://www.tomjewett.com/dbdesign/dbdesign.php?page=recursive.php\" rel=\"nofollow noreferrer\">here</a> (Wayback Machine link).</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 65295,
"author": "B0fh",
"author_id": 9159,
"author_profile": "https://Stackoverflow.com/users/9159",
"pm_score": 4,
"selected": false,
"text": "<p>create a table with two self referencing columns PreviousID and NextID. If the item is the first thing in the list PreviousID will be null, if it is the last, NextID will be null. The SQL will look something like this:</p>\n\n<pre><code>create table tblDummy\n{\n PKColumn int not null, \n PreviousID int null, \n DataColumn1 varchar(50) not null, \n DataColumn2 varchar(50) not null, \n DataColumn3 varchar(50) not null, \n DataColumn4 varchar(50) not null, \n DataColumn5 varchar(50) not null, \n DataColumn6 varchar(50) not null, \n DataColumn7 varchar(50) not null, \n NextID int null\n}\n</code></pre>\n"
},
{
"answer_id": 65330,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest option would be creating a table with a row per list item, a column for the item position, and columns for other data in the item. Then you can use ORDER BY on the position column to retrieve in the desired order. </p>\n\n<pre><code>create table linked_list\n( list_id integer not null\n, position integer not null \n, data varchar(100) not null\n);\nalter table linked_list add primary key ( list_id, position );\n</code></pre>\n\n<p>To manipulate the list just update the position and then insert/delete records as needed. So to insert an item into list 1 at index 3:</p>\n\n<pre><code>begin transaction;\n\nupdate linked_list set position = position + 1 where position >= 3 and list_id = 1;\n\ninsert into linked_list (list_id, position, data)\nvalues (1, 3, \"some data\");\n\ncommit;\n</code></pre>\n\n<p>Since operations on the list can require multiple commands (eg an insert will require an INSERT and an UPDATE), ensure you always perform the commands within a transaction.</p>\n\n<p>A variation of this simple option is to have position incrementing by some factor for each item, say 100, so that when you perform an INSERT you don't always need to renumber the position of the following elements. However, this requires a little more effort to work out when to increment the following elements, so you lose simplicity but gain performance if you will have many inserts.</p>\n\n<p>Depending on your requirements other options might appeal, such as:</p>\n\n<ul>\n<li><p>If you want to perform lots of manipulations on the list and not many retrievals you may prefer to have an ID column pointing to the next item in the list, instead of using a position column. Then you need to iterative logic in the retrieval of the list in order to get the items in order. This can be relatively easily implemented in a stored proc.</p></li>\n<li><p>If you have many lists, a quick way to serialise and deserialise your list to text/binary, and you only ever want to store and retrieve the entire list, then store the entire list as a single value in a single column. Probably not what you're asking for here though.</p></li>\n</ul>\n"
},
{
"answer_id": 65428,
"author": "Mike Monette",
"author_id": 6166,
"author_profile": "https://Stackoverflow.com/users/6166",
"pm_score": 2,
"selected": false,
"text": "<p>There are a few approaches I can think of right off, each with differing levels of complexity and flexibility. I'm assuming your goal is to preserve an order in retrieval, rather than requiring storage as an actual linked list.</p>\n\n<p>The simplest method would be to assign an ordinal value to each record in the table (e.g. 1, 2, 3, ...). Then, when you retrieve the records, specify an order-by on the ordinal column to get them back in order. </p>\n\n<p>This approach also allows you to retrieve the records without regard to membership in a list, but allows for membership in only one list, and may require an additional \"list id\" column to indicate to which list the record belongs.</p>\n\n<p>An slightly more elaborate, but also more flexible approach would be to store information about membership in a list or lists in a separate table. The table would need 3 columns: The list id, the ordinal value, and a foreign key pointer to the data record. Under this approach, the underlying data knows nothing about its membership in lists, and can easily be included in multiple lists.</p>\n"
},
{
"answer_id": 7025913,
"author": "Poncho",
"author_id": 889912,
"author_profile": "https://Stackoverflow.com/users/889912",
"pm_score": 0,
"selected": false,
"text": "<p>I think its much simpler adding a created column of <code>Datetime</code> type and a position column of <code>int</code>, so now you can have duplicate positions, at the select statement use the <code>order by</code> position, created desc option and your list will be fetched in order.</p>\n"
},
{
"answer_id": 21038546,
"author": "FlyTigert",
"author_id": 657921,
"author_profile": "https://Stackoverflow.com/users/657921",
"pm_score": 2,
"selected": false,
"text": "<p>This post is old but still going to give my .02$. Updating every record in a table or record set sounds crazy to solve ordering. the amount of indexing also crazy, but it sounds like most have accepted it. </p>\n\n<p>Crazy solution i came up with to reduce updates and indexing is to create two tables (and in most use cases you don's sort all records in just one table anyway). Table A to hold the records of the list being sorted and table B to group and hold a record of the order as a string. the order string represents an array that can be used to order the selected records either on the web server or browser layer of a webpage application. </p>\n\n<pre><code>Create Table A{\nId int primary key identity(1,1),\nData varchar(10) not null\nB_Id int\n}\n\nCreate Table B{\nId int primary key Identity(1,1),\nGroupName varchat(10) not null,\nOrder varchar(max) null\n}\n</code></pre>\n\n<p>The format of the order sting should be id, position and some separator to split() your string by. in the case of jQuery UI the .sortable('serialize') function outputs an order string for you that is POST friendly that includes the id and position of each record in the list. </p>\n\n<p>The real magic is the way you choose to reorder the selected list using the saved ordering string. this will depend on the application you are building. here is an example again from jQuery to reorder the list of items: <a href=\"http://ovisdevelopment.com/oramincite/?p=155\" rel=\"nofollow\">http://ovisdevelopment.com/oramincite/?p=155</a> </p>\n"
},
{
"answer_id": 25908592,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://dba.stackexchange.com/questions/46238/linked-list-in-sql-and-trees\">https://dba.stackexchange.com/questions/46238/linked-list-in-sql-and-trees</a> suggests a trick of using floating-point position column for fast inserts and ordering.</p>\n\n<p>It also mentions specialized SQL Server 2014 <a href=\"http://technet.microsoft.com/en-us/library/bb677173.aspx\" rel=\"nofollow noreferrer\">hierarchyid</a> feature.</p>\n"
},
{
"answer_id": 29475498,
"author": "HumbleWebDev",
"author_id": 3496058,
"author_profile": "https://Stackoverflow.com/users/3496058",
"pm_score": 2,
"selected": false,
"text": "<p>This is something I've been trying to figure out for a while myself. The best way I've found so far is to create a single table for the linked list using the following format (this is pseudo code):</p>\n\n<p>LinkedList(</p>\n\n<ul>\n<li>key1, </li>\n<li>information, </li>\n<li>key2</li>\n</ul>\n\n<p>)</p>\n\n<p>key1 is the starting point. Key2 is a foreign key linking to itself in the next column. So your columns will link something link something like this</p>\n\n<p><strong>col1</strong> </p>\n\n<ul>\n<li>key1 = 0,</li>\n<li>information= 'hello'</li>\n<li>key2 = 1</li>\n</ul>\n\n<p><em>Key1 is primary key of col1. key2 is a foreign key leading to the key1 of col2</em></p>\n\n<p><strong>col2</strong></p>\n\n<ul>\n<li>key1 = 1,</li>\n<li>information= 'wassup'</li>\n<li>key2 = null</li>\n</ul>\n\n<p><em>key2 from col2 is set to null because it doesn't point to anything</em></p>\n\n<p>When you first enter a column in for the table, you'll need to make sure key2 is set to null or you'll get an error. After you enter the second column, you can go back and set key2 of the first column to the primary key of the second column.</p>\n\n<p>This makes the best method to enter many entries at a time, then go back and set the foreign keys accordingly (or build a GUI that just does that for you)</p>\n\n<p>Here's some actual code I've prepared (all actual code worked on MSSQL. You may want to do some research for the version of SQL you are using!):</p>\n\n<p><em>createtable.sql</em></p>\n\n<pre><code>create table linkedlist00 (\n\nkey1 int primary key not null identity(1,1),\n\ninfo varchar(10),\n\nkey2 int\n\n)\n</code></pre>\n\n<p><em>register_foreign_key.sql</em></p>\n\n<pre><code>alter table dbo.linkedlist00\n\nadd foreign key (key2) references dbo.linkedlist00(key1)\n</code></pre>\n\n<p>*I put them into two seperate files, because it has to be done in two steps. MSSQL won't let you do it in one step, because the table doesn't exist yet for the foreign key to reference.</p>\n\n<p>Linked List is especially powerful in <em>one-to-many</em> relationships. So if you've ever wanted to make an array of foreign keys? Well this is one way to do it! You can make a primary table that points to the first column in the linked-list table, and then instead of the \"information\" field, you can use a foreign key to the desired information table.</p>\n\n<p>Example:</p>\n\n<p>Let's say you have a Bureaucracy that keeps forms.</p>\n\n<p>Let's say they have a table called <em>file cabinet</em> </p>\n\n<p>FileCabinet(</p>\n\n<ul>\n<li>Cabinet ID (pk)</li>\n<li>Files ID (fk)\n)</li>\n</ul>\n\n<p><em>each column contains a primary key for the cabinet and a foreign key for the files. These files could be tax forms, health insurance papers, field trip permissions slips etc</em></p>\n\n<p>Files(</p>\n\n<ul>\n<li><p>Files ID (pk)</p></li>\n<li><p>File ID (fk)</p></li>\n<li><p>Next File ID (fk)</p></li>\n</ul>\n\n<p>)</p>\n\n<p><em>this serves as a container for the Files</em></p>\n\n<p>File(</p>\n\n<ul>\n<li><p>File ID (pk)</p></li>\n<li><p>Information on the file</p></li>\n</ul>\n\n<p>)</p>\n\n<p><em>this is the specific file</em></p>\n\n<p>There may be better ways to do this and there are, depending on your specific needs. The example just illustrates possible usage.</p>\n"
},
{
"answer_id": 34668848,
"author": "Stephen",
"author_id": 593238,
"author_profile": "https://Stackoverflow.com/users/593238",
"pm_score": 0,
"selected": false,
"text": "<p>Increment the SERIAL 'index' by 100, but manually add intermediate values with an 'index' equal to Prev+Next / 2. If you ever saturate the 100 rows, reorder the index back to 100s.</p>\n\n<p>This should maintain sequence with primary index.</p>\n"
},
{
"answer_id": 63198185,
"author": "Cal",
"author_id": 5785894,
"author_profile": "https://Stackoverflow.com/users/5785894",
"pm_score": -1,
"selected": false,
"text": "<p>You could implement it like a double ended queue (deque) to support fast push/pop/delete(if oridnal is known) and retrieval you would have two data structures. One with the actual data and another with the number of elements added over the history of the key. Tradeoff: This method would be slower for any insert into the middle of the linked list O(n).</p>\n<pre><code>create table queue (\n primary_key,\n queue_key\n ordinal,\n data\n)\n</code></pre>\n<p>You would have an index on queue_key+ordinal</p>\n<p>You would also have another table which stores the number of rows EVER added to the queue...</p>\n<pre><code>create table queue_addcount (\n primary_key,\n add_count\n)\n</code></pre>\n<p>When pushing a new item to either end of the queue (left or right) you would always increment the add_count.</p>\n<p>If you push to the back you could set the ordinal...</p>\n<pre><code>ordinal = add_count + 1\n</code></pre>\n<p>If you push to the front you could set the ordinal...</p>\n<pre><code>ordinal = -(add_count + 1)\n</code></pre>\n<p>update</p>\n<pre><code>add_count = add_count + 1\n</code></pre>\n<p>This way you can delete anywhere in the queue/list and it would still return in order and you could also continue to push new items maintaining the order.</p>\n<p>You could optionally rewrite the ordinal to avoid overflow if a lot of deletes have occurred.</p>\n<p>You could also have an index on the ordinal to support fast ordered retrieval of the list.</p>\n<p>If you want to support inserts into the middle you would need to find the ordinal which it needs to be insert at then insert with that ordinal. Then increment every ordinal by one following that insertion point. Also, increment the add_count as usual. If the ordinal is negative you could decrement all of the earlier ordinals to do fewer updates. This would be O(n)</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order? | Store an integer column in your table called 'position'. Record a 0 for the first item in your list, a 1 for the second item, etc. Index that column in your database, and when you want to pull your values out, sort by that column.
```
alter table linked_list add column position integer not null default 0;
alter table linked_list add index position_index (position);
select * from linked_list order by position;
```
To insert a value at index 3, modify the positions of rows 3 and above, and then insert:
```
update linked_list set position = position + 1 where position >= 3;
insert into linked_list (my_value, position) values ("new value", 3);
``` |
65,206 | <p>Using <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a>, how can I dynamically set the size attribute of a select box?</p>
<p>I would like to include it in this code:</p>
<pre><code>$("#mySelect").bind("click",
function() {
$("#myOtherSelect").children().remove();
var options = '' ;
for (var i = 0; i < myArray[this.value].length; i++) {
options += '<option value="' + myArray[this.value][i] + '">' + myArray[this.value][i] + '</option>';
}
$("#myOtherSelect").html(options).attr [... use myArray[this.value].length here ...];
});
});
</code></pre>
| [
{
"answer_id": 65239,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 6,
"selected": true,
"text": "<p>Oops, it's</p>\n\n<pre><code>$('#mySelect').attr('size', value)\n</code></pre>\n"
},
{
"answer_id": 65261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$(\"#mySelect\").bind(\"click\", function(){\n $(\"#myOtherSelect\").children().remove();\n var myArray = [ \"value1\", \"value2\", \"value3\" ];\n for (var i = 0; i < myArray.length; i++) {\n $(\"#myOtherSelect\").append( '<option value=\"' + myArray[i] + '\">' + myArray[i] + '</option>' );\n }\n $(\"#myOtherSelect\").attr( \"size\", myArray.length );\n});\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
| Using [jQuery](http://en.wikipedia.org/wiki/JQuery), how can I dynamically set the size attribute of a select box?
I would like to include it in this code:
```
$("#mySelect").bind("click",
function() {
$("#myOtherSelect").children().remove();
var options = '' ;
for (var i = 0; i < myArray[this.value].length; i++) {
options += '<option value="' + myArray[this.value][i] + '">' + myArray[this.value][i] + '</option>';
}
$("#myOtherSelect").html(options).attr [... use myArray[this.value].length here ...];
});
});
``` | Oops, it's
```
$('#mySelect').attr('size', value)
``` |
65,209 | <p>I was recently asked to come up with a script that will allow the end user to upload a PSD (Photoshop) file, and split it up and create images from each of the layers.</p>
<p>I would love to stay with PHP for this, but I am open to Python or Perl as well.</p>
<p>Any ideas would be greatly appreciated.</p>
| [
{
"answer_id": 65239,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 6,
"selected": true,
"text": "<p>Oops, it's</p>\n\n<pre><code>$('#mySelect').attr('size', value)\n</code></pre>\n"
},
{
"answer_id": 65261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$(\"#mySelect\").bind(\"click\", function(){\n $(\"#myOtherSelect\").children().remove();\n var myArray = [ \"value1\", \"value2\", \"value3\" ];\n for (var i = 0; i < myArray.length; i++) {\n $(\"#myOtherSelect\").append( '<option value=\"' + myArray[i] + '\">' + myArray[i] + '</option>' );\n }\n $(\"#myOtherSelect\").attr( \"size\", myArray.length );\n});\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9176/"
]
| I was recently asked to come up with a script that will allow the end user to upload a PSD (Photoshop) file, and split it up and create images from each of the layers.
I would love to stay with PHP for this, but I am open to Python or Perl as well.
Any ideas would be greatly appreciated. | Oops, it's
```
$('#mySelect').attr('size', value)
``` |
65,250 | <p>Convert a .doc or .pdf to an image and display a thumbnail in Ruby?<br>
Does anyone know how to generate document thumbnails in Ruby (or C, python...)</p>
| [
{
"answer_id": 65287,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure about .doc support in any open source library but ImageMagick (and the RMagick gem) can be compiled with pdf support (I think it's on by default)</p>\n"
},
{
"answer_id": 65344,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>PDF support is a little buggy in ImageMagick - but it's by far the best OS way for ruby. There's also a google summer of code project for pure Ruby PDF support.</p>\n\n<p>I've read stuff about using OpenOffice without the GUI to transform .doc files - but it'll be complicated at best.</p>\n"
},
{
"answer_id": 69015,
"author": "Federico Builes",
"author_id": 161,
"author_profile": "https://Stackoverflow.com/users/161",
"pm_score": 0,
"selected": false,
"text": "<p>As the 2 previous posters said, ImageMagick's probably the easiest way to generate the thumbnails.</p>\n\n<p>You could exec something like:</p>\n\n<pre><code>´convert -size 300x300 doc.pdf doc.png´\n</code></pre>\n\n<p>(The backquotes tell Ruby to shell it out).</p>\n\n<p>If you don't want to use exec to do the conversion you could use the RMagick gem to do it for you but it's probably a bit more of code.</p>\n"
},
{
"answer_id": 69804,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 6,
"selected": true,
"text": "<p>A simple RMagick example to convert a PDF to a PNG would be:</p>\n\n<pre><code>require 'RMagick'\npdf = Magick::ImageList.new(\"doc.pdf\")\nthumb = pdf.scale(300, 300)\nthumb.write \"doc.png\"\n</code></pre>\n\n<p>To convert a MS Word document, it won't be as easy. Your best option may be to first convert it to a PDF before generating the thumbnail. Your options for generating the PDF depend heavily on the OS you're running on. One might be to use OpenOffice and the <a href=\"http://www.artofsolving.com/opensource/pyodconverter\" rel=\"noreferrer\">Python Open Document Converter</a>. There are also online conversion services you could try, including <a href=\"http://Zamzar.com\" rel=\"noreferrer\">http://Zamzar.com</a>.</p>\n"
},
{
"answer_id": 24267898,
"author": "SciPhi",
"author_id": 765063,
"author_profile": "https://Stackoverflow.com/users/765063",
"pm_score": 2,
"selected": false,
"text": "<p>Sample code to answer the comment by @aisensiy above :</p>\n\n<pre><code>require 'rmagick'\npdf_path = \"/path/to/interesting/file.pdf\"\npage_index_path = pdf_path + \"[0]\" # first page in PDF\npdf_page = Magick::Image.read( page_index_path ).first # first item in Magick::ImageList\npdf_page.write( \"/tmp/indexed-page.png\" ) # implicit conversion based on file extension\n</code></pre>\n\n<p>Based on the path clue in answer to another question :</p>\n\n<p><a href=\"https://stackoverflow.com/a/6369524/765063\">https://stackoverflow.com/a/6369524/765063</a></p>\n"
},
{
"answer_id": 30388902,
"author": "Jan Klimo",
"author_id": 3678689,
"author_profile": "https://Stackoverflow.com/users/3678689",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't mind paying for Imgix, it <a href=\"https://www.imgix.com/docs/reference/pdf\" rel=\"nofollow\">handles PDFs</a> too. You get all the benefits of a fast CDN with it.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Convert a .doc or .pdf to an image and display a thumbnail in Ruby?
Does anyone know how to generate document thumbnails in Ruby (or C, python...) | A simple RMagick example to convert a PDF to a PNG would be:
```
require 'RMagick'
pdf = Magick::ImageList.new("doc.pdf")
thumb = pdf.scale(300, 300)
thumb.write "doc.png"
```
To convert a MS Word document, it won't be as easy. Your best option may be to first convert it to a PDF before generating the thumbnail. Your options for generating the PDF depend heavily on the OS you're running on. One might be to use OpenOffice and the [Python Open Document Converter](http://www.artofsolving.com/opensource/pyodconverter). There are also online conversion services you could try, including <http://Zamzar.com>. |
65,266 | <p>Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.</p>
<pre><code>a = re.compile("a.*b")
b = re.compile("c.*d")
...
</code></pre>
<p>Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p>
<p>Pickling the object simply does the following, causing compilation to happen anyway:</p>
<pre><code>>>> import pickle
>>> import re
>>> x = re.compile(".*")
>>> pickle.dumps(x)
"cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n."
</code></pre>
<p>And <code>re</code> objects are unmarshallable:</p>
<pre><code>>>> import marshal
>>> import re
>>> x = re.compile(".*")
>>> marshal.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unmarshallable object
</code></pre>
| [
{
"answer_id": 65333,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "<p>Note that each module initializes itself only once during the life of an app, no matter how many times you import it. So if you compile your expressions at the module's global scope (ie. not in a function) you should be fine.</p>\n"
},
{
"answer_id": 65440,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?</p>\n</blockquote>\n\n<p>Not easily. You'd have to write a custom serializer that hooks into the C <code>sre</code> implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required.</p>\n\n<p>First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory.</p>\n\n<p>If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above.</p>\n\n<p>Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application.</p>\n"
},
{
"answer_id": 65844,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": -1,
"selected": false,
"text": "<p>The <a href=\"http://docs.python.org/lib/module-shelve.html\" rel=\"nofollow noreferrer\">shelve</a> module appears to work just fine:</p>\n\n<pre><code>\nimport re\nimport shelve\na_pattern = \"a.*b\"\nb_pattern = \"c.*d\"\na = re.compile(a_pattern)\nb = re.compile(b_pattern)\n\nx = shelve.open('re_cache')\nx[a_pattern] = a\nx[b_pattern] = b\nx.close()\n\n# ...\nx = shelve.open('re_cache')\na = x[a_pattern]\nb = x[b_pattern]\nx.close()\n\n</code></pre>\n\n<p>You can then make a nice wrapper class that automatically handles the caching for you so that it becomes transparent to the user... an exercise left to the reader.</p>\n"
},
{
"answer_id": 66666,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": -1,
"selected": false,
"text": "<p>Hum,</p>\n\n<p>Doesn't shelve use pickle ?</p>\n\n<p>Anyway, I agree with the previous anwsers. Since a module is processed only once, I doubt compiling regexps will be your app bottle neck. And Python re module is wicked fast since it's coded in C :-)</p>\n\n<p>But the good news is that Python got a nice community, so I am sure you can find somebody currently hacking just what you need.</p>\n\n<p>I googled 5 sec and found : <a href=\"http://home.gna.org/oomadness/en/cerealizer/index.html\" rel=\"nofollow noreferrer\">http://home.gna.org/oomadness/en/cerealizer/index.html</a>.</p>\n\n<p>Don't know if it will do it but if not, good luck in you research :-)</p>\n"
},
{
"answer_id": 66846,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Open /usr/lib/python2.5/re.py and look for \"def _compile\". You'll find re.py's internal cache mechanism. </p>\n"
},
{
"answer_id": 396148,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, this is a clear limitation in the python re module. It causes a limit how much and how big regular expressions are reasonable. The limit is bigger with long running processes and smaller with short lived processes like command line applications.</p>\n\n<p>Some years ago I did look at it and it is possible to dig out the compilation result, pickle it and then unpickle it and reuse it. The problem is that it requires using the sre.py internals and so won't probably work in different python versions.</p>\n\n<p>I would like to have this kind of feature in my toolbox. I would also like to know, if there are any separate modules that could be used instead.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9241/"
]
| Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory.
```
a = re.compile("a.*b")
b = re.compile("c.*d")
...
```
Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?
Pickling the object simply does the following, causing compilation to happen anyway:
```
>>> import pickle
>>> import re
>>> x = re.compile(".*")
>>> pickle.dumps(x)
"cre\n_compile\np0\n(S'.*'\np1\nI0\ntp2\nRp3\n."
```
And `re` objects are unmarshallable:
```
>>> import marshal
>>> import re
>>> x = re.compile(".*")
>>> marshal.dumps(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unmarshallable object
``` | >
> Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?
>
>
>
Not easily. You'd have to write a custom serializer that hooks into the C `sre` implementation of the Python regex engine. Any performance benefits would be vastly outweighed by the time and effort required.
First, have you actually profiled the code? I doubt that compiling regexes is a significant part of the application's run-time. Remember that they are only compiled the first time the module is imported in the current execution -- thereafter, the module and its attributes are cached in memory.
If you have a program that basically spawns once, compiles a bunch of regexes, and then exits, you could try re-engineering it to perform multiple tests in one invocation. Then you could re-use the regexes, as above.
Finally, you could compile the regexes into C-based state machines and then link them in with an extension module. While this would likely be more difficult to maintain, it would eliminate regex compilation entirely from your application. |
65,310 | <p>I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:</p>
<blockquote>
<p>org.apache.axis.ConfigurationException: No service named <code><web service name></code> is available</p>
</blockquote>
<p>any idea?</p>
| [
{
"answer_id": 65575,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 0,
"selected": false,
"text": "<p>This is what my code looks like. It seems to work fine.\nAre you using a service locator or just creating your service?</p>\n\n<pre><code>SomeServiceLocator locator = new SomeServiceLocator();\nSomeService service = null;\ntry\n{\n service = locator.getSomeServiceImplPort();\n}\ncatch (ServiceException e)\n{\n e.printStackTrace();\n}\n</code></pre>\n"
},
{
"answer_id": 179414,
"author": "KC Baltz",
"author_id": 9910,
"author_profile": "https://Stackoverflow.com/users/9910",
"pm_score": 3,
"selected": true,
"text": "<p>Just a guess, but it looks like that error message is reporting that you've left the service name blank. I imagine the code that generates that error message looks like this:</p>\n\n<pre><code>throw new ConfigurationException(\"No service named\" + serviceName + \" is available\");\n</code></pre>\n"
},
{
"answer_id": 200824,
"author": "Vinze",
"author_id": 26859,
"author_profile": "https://Stackoverflow.com/users/26859",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know what version of Axis you're using but I'm using Axis2 for both server and client and the Java2WSDL create a default endpoint for the service on localhost. If you create the client stub with WSDL2Java, the default constructor of the stub will then point to localhost. If the service is on other endpoint you must use the constructor with the endpoint as parameter...\nMaybe the problem is not that at all but as said on other answers, without the WSDL you're using as WSDL2Java input it's hard to say.</p>\n"
},
{
"answer_id": 6496124,
"author": "arnonym",
"author_id": 817796,
"author_profile": "https://Stackoverflow.com/users/817796",
"pm_score": 1,
"selected": false,
"text": "<p>It is an exception used by Axis' control flow. </p>\n\n<p><a href=\"http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions\" rel=\"nofollow\">http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions</a>\n--> org.apache.axis.ConfigurationException: No service named XXX is available</p>\n"
},
{
"answer_id": 17981199,
"author": "kldavis4",
"author_id": 290918,
"author_profile": "https://Stackoverflow.com/users/290918",
"pm_score": 5,
"selected": false,
"text": "<p>According to the <a href=\"http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions\">documentation</a> linked to by @arnonym, this exception is somewhat misleading. In the first attempt to find the service a ConfigurationException is thrown and caught. It is logged at DEBUG level by the ConfigurationException class. Then another attempt is made using a different method to find the service that may then succeed. The workaround for this is to just change the log level on the ConfigurationException class to INFO in your log4j.properties:</p>\n\n<pre><code>log4j.logger.org.apache.axis.ConfigurationException = INFO\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
]
| I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:
>
> org.apache.axis.ConfigurationException: No service named `<web service name>` is available
>
>
>
any idea? | Just a guess, but it looks like that error message is reporting that you've left the service name blank. I imagine the code that generates that error message looks like this:
```
throw new ConfigurationException("No service named" + serviceName + " is available");
``` |
65,351 | <p>I have a generic method defined like this:</p>
<pre><code>public void MyMethod<T>(T myArgument)
</code></pre>
<p>The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:</p>
<pre><code>if (myArgument == default(T))
</code></pre>
<p>But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:</p>
<pre><code>if (myArgument.Equals(default(T)))
</code></pre>
<p>Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:</p>
<pre><code>if (myArgument == null || myArgument.Equals(default(T)))
</code></pre>
<p>Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?</p>
<p>I need to support <b>both</b> references types and value types.</p>
| [
{
"answer_id": 65423,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 5,
"selected": false,
"text": "<p>I was able to locate a <a href=\"http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx\" rel=\"noreferrer\">Microsoft Connect article</a> that discusses this issue in some detail:</p>\n<blockquote>\n<p>Unfortunately, this behavior is by design and there is not an easy solution to enable use of with type parameters that may contain value types.</p>\n<p>If the types are known to be reference types, the default overload of defined on object tests variables for reference equality, although a type may specify its own custom overload. The compiler determines which overload to use based on the static type of the variable (the determination is not polymorphic). Therefore, if you change your example to constrain the generic type parameter T to a non-sealed reference type (such as Exception), the compiler can determine the specific overload to use and the following code would compile:</p>\n</blockquote>\n<pre><code>public class Test<T> where T : Exception\n</code></pre>\n<blockquote>\n<p>If the types are known to be value types, performs specific value equality tests based on the exact types used. There is no good "default" comparison here since reference comparisons are not meaningful on value types and the compiler cannot know which specific value comparison to emit. The compiler could emit a call to ValueType.Equals(Object) but this method uses reflection and is quite inefficient compared to the specific value comparisons. Therefore, even if you were to specify a value-type constraint on T, there is nothing reasonable for the compiler to generate here:</p>\n</blockquote>\n<pre><code>public class Test<T> where T : struct\n</code></pre>\n<blockquote>\n<p>In the case you presented, where the compiler does not even know whether T is a value or reference type, there is similarly nothing to generate that would be valid for all possible types. A reference comparison would not be valid for value types and some sort of value comparison would be unexpected for reference types that do not overload.</p>\n</blockquote>\n<p>Here is what you can do...</p>\n<p>I have validated that both of these methods work for a generic comparison of reference and value types:</p>\n<pre><code>object.Equals(param, default(T))\n</code></pre>\n<p>or</p>\n<pre><code>EqualityComparer<T>.Default.Equals(param, default(T))\n</code></pre>\n<p>To do comparisons with the "==" operator you will need to use one of these methods:</p>\n<p>If all cases of T derive from a known base class you can let the compiler know using generic type restrictions.</p>\n<pre><code>public void MyMethod<T>(T myArgument) where T : MyBase\n</code></pre>\n<p>The compiler then recognizes how to perform operations on <code>MyBase</code> and will not throw the "Operator '==' cannot be applied to operands of type 'T' and 'T'" error that you are seeing now.</p>\n<p>Another option would be to restrict T to any type that implements <code>IComparable</code>.</p>\n<pre><code>public void MyMethod<T>(T myArgument) where T : IComparable\n</code></pre>\n<p>And then use the <code>CompareTo</code> method defined by the <a href=\"http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx\" rel=\"noreferrer\">IComparable interface</a>.</p>\n"
},
{
"answer_id": 65445,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 7,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>if (object.Equals(myArgument, default(T)))\n{\n //...\n}\n</code></pre>\n\n<p>Using the <code>static object.Equals()</code> method avoids the need for you to do the <code>null</code> check yourself. Explicitly qualifying the call with <code>object.</code> probably isn't necessary depending on your context, but I normally prefix <code>static</code> calls with the type name just to make the code more soluble.</p>\n"
},
{
"answer_id": 65457,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": -1,
"selected": false,
"text": "<p>Don't know if this works with your requirements or not, but you could constrain T to be a Type that implements an interface such as IComparable and then use the ComparesTo() method from that interface (which IIRC supports/handles nulls) like this:</p>\n\n<pre><code>public void MyMethod<T>(T myArgument) where T : IComparable\n...\nif (0 == myArgument.ComparesTo(default(T)))\n</code></pre>\n\n<p>There are probably other interfaces that you could use as well IEquitable, etc.</p>\n"
},
{
"answer_id": 65461,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>if (EqualityComparer<T>.Default.Equals(myArgument, default(T)))\n</code></pre>\n\n<p>that should compile, and do what you want.</p>\n"
},
{
"answer_id": 65498,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": -1,
"selected": false,
"text": "<p>@ilitirit:</p>\n\n<pre><code>public class Class<T> where T : IComparable\n{\n public T Value { get; set; }\n public void MyMethod(T val)\n {\n if (Value == val)\n return;\n }\n}\n</code></pre>\n\n<p>Operator '==' cannot be applied to operands of type 'T' and 'T'</p>\n\n<p>I can't think of a way to do this without the explicit null test followed by invoking the Equals method or object.Equals as suggested above.</p>\n\n<p>You can devise a solution using System.Comparison but really that's going to end up with way more lines of code and increase complexity substantially.</p>\n"
},
{
"answer_id": 677151,
"author": "Damian Powell",
"author_id": 30321,
"author_profile": "https://Stackoverflow.com/users/30321",
"pm_score": 1,
"selected": false,
"text": "<p>I think you probably need to split this logic into two parts and check for null first.</p>\n\n<pre><code>public static bool IsNullOrEmpty<T>(T value)\n{\n if (IsNull(value))\n {\n return true;\n }\n if (value is string)\n {\n return string.IsNullOrEmpty(value as string);\n }\n return value.Equals(default(T));\n}\n\npublic static bool IsNull<T>(T value)\n{\n if (value is ValueType)\n {\n return false;\n }\n return null == (object)value;\n}\n</code></pre>\n\n<p>In the IsNull method, we're relying on the fact that ValueType objects can't be null by definition so if value happens to be a class which derives from ValueType, we already know it's not null. On the other hand, if it's not a value type then we can just compare value cast to an object against null. We could avoid the check against ValueType by going straight to a cast to object, but that would mean that a value type would get boxed which is something we probably want to avoid since it implies that a new object is created on the heap.</p>\n\n<p>In the IsNullOrEmpty method, we're checking for the special case of a string. For all other types, we're comparing the value (which already know is <em>not</em> null) against it's default value which for all reference types is null and for value types is usually some form of zero (if they're integral).</p>\n\n<p>Using these methods, the following code behaves as you might expect:</p>\n\n<pre><code>class Program\n{\n public class MyClass\n {\n public string MyString { get; set; }\n }\n\n static void Main()\n {\n int i1 = 1; Test(\"i1\", i1); // False\n int i2 = 0; Test(\"i2\", i2); // True\n int? i3 = 2; Test(\"i3\", i3); // False\n int? i4 = null; Test(\"i4\", i4); // True\n\n Console.WriteLine();\n\n string s1 = \"hello\"; Test(\"s1\", s1); // False\n string s2 = null; Test(\"s2\", s2); // True\n string s3 = string.Empty; Test(\"s3\", s3); // True\n string s4 = \"\"; Test(\"s4\", s4); // True\n\n Console.WriteLine();\n\n MyClass mc1 = new MyClass(); Test(\"mc1\", mc1); // False\n MyClass mc2 = null; Test(\"mc2\", mc2); // True\n }\n\n public static void Test<T>(string fieldName, T field)\n {\n Console.WriteLine(fieldName + \": \" + IsNullOrEmpty(field));\n }\n\n // public static bool IsNullOrEmpty<T>(T value) ...\n\n // public static bool IsNull<T>(T value) ...\n}\n</code></pre>\n"
},
{
"answer_id": 864292,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>(Edited)</p>\n\n<p>Marc Gravell has the best answer, but I wanted to post a simple code snippet I worked up to demonstrate it. Just run this in a simple C# console app:</p>\n\n<pre><code>public static class TypeHelper<T>\n{\n public static bool IsDefault(T val)\n {\n return EqualityComparer<T>.Default.Equals(obj,default(T));\n }\n}\n\nstatic void Main(string[] args)\n{\n // value type\n Console.WriteLine(TypeHelper<int>.IsDefault(1)); //False\n Console.WriteLine(TypeHelper<int>.IsDefault(0)); // True\n\n // reference type\n Console.WriteLine(TypeHelper<string>.IsDefault(\"test\")); //False\n Console.WriteLine(TypeHelper<string>.IsDefault(null)); //True //True\n\n Console.ReadKey();\n}\n</code></pre>\n\n<p>One more thing: can someone with VS2008 try this as an extension method? I'm stuck with 2005 here and I'm curious to see if that would be allowed.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Here is how to get it working as an extension method:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nclass Program\n{\n static void Main()\n {\n // value type\n Console.WriteLine(1.IsDefault());\n Console.WriteLine(0.IsDefault());\n\n // reference type\n Console.WriteLine(\"test\".IsDefault());\n // null must be cast to a type\n Console.WriteLine(((String)null).IsDefault());\n }\n}\n\n// The type cannot be generic\npublic static class TypeHelper\n{\n // I made the method generic instead\n public static bool IsDefault<T>(this T val)\n {\n return EqualityComparer<T>.Default.Equals(val, default(T));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 864306,
"author": "Nick Farina",
"author_id": 66673,
"author_profile": "https://Stackoverflow.com/users/66673",
"pm_score": 3,
"selected": false,
"text": "<p>To handle all types of T, including where T is a primitive type, you'll need to compile in both methods of comparison:</p>\n\n<pre><code> T Get<T>(Func<T> createObject)\n {\n T obj = createObject();\n if (obj == null || obj.Equals(default(T)))\n return obj;\n\n // .. do a bunch of stuff\n return obj;\n }\n</code></pre>\n"
},
{
"answer_id": 864309,
"author": "Reed Copsey",
"author_id": 65358,
"author_profile": "https://Stackoverflow.com/users/65358",
"pm_score": 2,
"selected": false,
"text": "<p>There is going to be a problem here -</p>\n\n<p>If you're going to allow this to work for any type, default(T) will always be null for reference types, and 0 (or struct full of 0) for value types.</p>\n\n<p>This is probably not the behavior you're after, though. If you want this to work in a generic way, you probably need to use reflection to check the type of T, and handle value types different than reference types.</p>\n\n<p>Alternatively, you could put an interface constraint on this, and the interface could provide a way to check against the default of the class/struct.</p>\n"
},
{
"answer_id": 864860,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 10,
"selected": true,
"text": "<p>To avoid boxing, the best way to compare generics for equality is with <code>EqualityComparer<T>.Default</code>. This respects <code>IEquatable<T></code> (without boxing) as well as <code>object.Equals</code>, and handles all the <code>Nullable<T></code> \"lifted\" nuances. Hence:</p>\n\n<pre><code>if(EqualityComparer<T>.Default.Equals(obj, default(T))) {\n return obj;\n}\n</code></pre>\n\n<p>This will match:</p>\n\n<ul>\n<li>null for classes</li>\n<li>null (empty) for <code>Nullable<T></code></li>\n<li>zero/false/etc for other structs</li>\n</ul>\n"
},
{
"answer_id": 6857841,
"author": "Scott McKay",
"author_id": 684911,
"author_profile": "https://Stackoverflow.com/users/684911",
"pm_score": -1,
"selected": false,
"text": "<p>I think you were close.</p>\n\n<pre><code>if (myArgument.Equals(default(T)))\n</code></pre>\n\n<p>Now this compiles, but will fail if <code>myArgument</code> is null, which is part of what I'm testing for. I can add an explicit null check like this:</p>\n\n<p>You just need to reverse the object on which the equals is being called for an elegant null-safe approach.</p>\n\n<pre><code>default(T).Equals(myArgument);\n</code></pre>\n"
},
{
"answer_id": 51236830,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 0,
"selected": false,
"text": "<p>I use:</p>\n\n<pre><code>public class MyClass<T>\n{\n private bool IsNull() \n {\n var nullable = Nullable.GetUnderlyingType(typeof(T)) != null;\n return nullable ? EqualityComparer<T>.Default.Equals(Value, default(T)) : false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60281314,
"author": "dynamiclynk",
"author_id": 1427166,
"author_profile": "https://Stackoverflow.com/users/1427166",
"pm_score": 2,
"selected": false,
"text": "<p>Extension method based on accepted answer.</p>\n\n<pre><code> public static bool IsDefault<T>(this T inObj)\n {\n return EqualityComparer<T>.Default.Equals(inObj, default);\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> private bool SomeMethod(){\n var tValue = GetMyObject<MyObjectType>();\n if (tValue == null || tValue.IsDefault()) return false;\n }\n</code></pre>\n\n<p>Alternate with null to simplify:</p>\n\n<pre><code> public static bool IsNullOrDefault<T>(this T inObj)\n {\n if (inObj == null) return true;\n return EqualityComparer<T>.Default.Equals(inObj, default);\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> private bool SomeMethod(){\n var tValue = GetMyObject<MyObjectType>();\n if (tValue.IsNullOrDefault()) return false;\n }\n</code></pre>\n"
},
{
"answer_id": 66327304,
"author": "Kosmas",
"author_id": 2833737,
"author_profile": "https://Stackoverflow.com/users/2833737",
"pm_score": 0,
"selected": false,
"text": "<p>Just a hacky answer and as a reminder for myself.\nBut I find this quite helpful for my project.\nThe reason I write it like this is that because I don't want default integer 0 being marked as null if the value is 0</p>\n<pre><code>private static int o;\npublic static void Main()\n{\n //output: IsNull = False -> IsDefault = True\n Console.WriteLine( "IsNull = " + IsNull( o ) + " -> IsDefault = " + IsDefault(o)); \n}\n\npublic static bool IsNull<T>(T paramValue)\n{\n if( string.IsNullOrEmpty(paramValue + "" ))\n return true;\n return false;\n}\n\npublic static bool IsDefault<T>(T val)\n{\n return EqualityComparer<T>.Default.Equals(val, default(T));\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8739/"
]
| I have a generic method defined like this:
```
public void MyMethod<T>(T myArgument)
```
The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:
```
if (myArgument == default(T))
```
But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:
```
if (myArgument.Equals(default(T)))
```
Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:
```
if (myArgument == null || myArgument.Equals(default(T)))
```
Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?
I need to support **both** references types and value types. | To avoid boxing, the best way to compare generics for equality is with `EqualityComparer<T>.Default`. This respects `IEquatable<T>` (without boxing) as well as `object.Equals`, and handles all the `Nullable<T>` "lifted" nuances. Hence:
```
if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
return obj;
}
```
This will match:
* null for classes
* null (empty) for `Nullable<T>`
* zero/false/etc for other structs |
65,364 | <p>I've created a seperate assembly with a class that is intended to be
published through wmi. Then I've created a windows forms app that
references that assembly and attempts to publish the class. When I try to
publish the class, I get an exception of type
System.Management.Instrumentation.WmiProviderInstallationException. The
message of the exception says "Exception of type
'System.Management.Instrumentation.WMIInfraException' was thrown.". I have
no idea what this means. I've tried .Net2.0 and .Net3.5 (sp1 too) and get the same results.</p>
<p>Below is my wmi class, followed by the code I used to publish it.</p>
<pre><code>//Interface.cs in assembly WMI.Interface.dll
using System;
using System.Collections.Generic;
using System.Text;
[assembly: System.Management.Instrumentation.WmiConfiguration(@"root\Test",
HostingModel =
System.Management.Instrumentation.ManagementHostingModel.Decoupled)]
namespace WMI
{
[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller :
System.Management.Instrumentation.DefaultManagementInstaller { }
[System.Management.Instrumentation.ManagementEntity(Singleton = true)]
[System.Management.Instrumentation.ManagementQualifier("Description",
Value = "Obtain processor information.")]
public class Interface
{
[System.Management.Instrumentation.ManagementBind]
public Interface()
{
}
[System.Management.Instrumentation.ManagementProbe]
[System.Management.Instrumentation.ManagementQualifier("Descriiption",
Value="The number of processors.")]
public int ProcessorCount
{
get { return Environment.ProcessorCount; }
}
}
}
</code></pre>
<p><BR/></p>
<pre><code>//Button click in windows forms application to publish class
try
{
System.Management.Instrumentation.InstrumentationManager.Publish(new
WMI.Interface());
}
catch (System.Management.Instrumentation.InstrumentationException
exInstrumentation)
{
MessageBox.Show(exInstrumentation.ToString());
}
catch (System.Management.Instrumentation.WmiProviderInstallationException
exProvider)
{
MessageBox.Show(exProvider.ToString());
}
catch (Exception exPublish)
{
MessageBox.Show(exPublish.ToString());
}
</code></pre>
| [
{
"answer_id": 69618,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": true,
"text": "<p>I used gacutil - installutil to to test your class (as a dll). The gacutil part worked, but installutil (actually mofcomp) complained about a syntax error:</p>\n\n<p>...</p>\n\n<p>error SYNTAX 0X80044014:\nUnexpected character in class name (must be an identifier)</p>\n\n<p>Compiler returned error 0x80044014</p>\n\n<p>...</p>\n\n<p>So I changed the class name to 'MyInterface' the installutil part worked, but the class didn't return any instances. Finally I changed the hosting model to Network Service and got it to work.</p>\n"
},
{
"answer_id": 97083,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 2,
"selected": false,
"text": "<p>To summarize, this is the final code that works:</p>\n\n<p>Provider class, in it's own assembly:</p>\n\n<pre><code>// the namespace used for publishing the WMI classes and object instances \n[assembly: Instrumented(\"root/mytest\")]\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Management;\nusing System.Management.Instrumentation;\nusing System.Configuration.Install;\nusing System.ComponentModel;\n\nnamespace WMITest\n{\n\n [InstrumentationClass(System.Management.Instrumentation.InstrumentationType.Instance)] \n //[ManagementEntity()]\n //[ManagementQualifier(\"Description\",Value = \"Obtain processor information.\")]\n public class MyWMIInterface\n {\n //[System.Management.Instrumentation.ManagementBind]\n public MyWMIInterface()\n {\n }\n\n //[ManagementProbe]\n //[ManagementQualifier(\"Descriiption\", Value=\"The number of processors.\")]\n public int ProcessorCount\n {\n get { return Environment.ProcessorCount; }\n }\n }\n\n /// <summary>\n /// This class provides static methods to publish messages to WMI\n /// </summary>\n public static class InstrumentationProvider\n {\n /// <summary>\n /// publishes a message to the WMI repository\n /// </summary>\n /// <param name=\"MessageText\">the message text</param>\n /// <param name=\"Type\">the message type</param>\n public static MyWMIInterface Publish()\n {\n // create a new message\n MyWMIInterface pInterface = new MyWMIInterface();\n\n Instrumentation.Publish(pInterface);\n\n return pInterface;\n }\n\n /// <summary>\n /// revoke a previously published message from the WMI repository\n /// </summary>\n /// <param name=\"Message\">the message to revoke</param>\n public static void Revoke(MyWMIInterface pInterface)\n {\n Instrumentation.Revoke(pInterface);\n } \n }\n\n /// <summary>\n /// Installer class which will publish the InfoMessage to the WMI schema\n /// (the assembly attribute Instrumented defines the namespace this\n /// class gets published too\n /// </summary>\n [RunInstaller(true)]\n public class WMITestManagementInstaller :\n DefaultManagementProjectInstaller\n {\n }\n}\n</code></pre>\n\n<p>Windows forms application main form, publishes provider class:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Management;\nusing System.Management.Instrumentation;\n\nnamespace WMI\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n WMITest.MyWMIInterface pIntf_m;\n\n private void btnPublish_Click(object sender, EventArgs e)\n {\n try\n {\n pIntf_m = WMITest.InstrumentationProvider.Publish();\n }\n catch (ManagementException exManagement)\n {\n MessageBox.Show(exManagement.ToString());\n }\n catch (Exception exPublish)\n {\n MessageBox.Show(exPublish.ToString());\n }\n }\n }\n}\n</code></pre>\n\n<p>Test web application, consumer:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\nusing System.Management.Instrumentation;\nusing System.Management;\n\npublic partial class _Default : System.Web.UI.Page \n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n ManagementClass pWMIClass = null;\n\n pWMIClass = new ManagementClass(@\"root\\interiorhealth:MyWMIInterface\");\n\n lblOutput.Text = \"ClassName: \" + pWMIClass.ClassPath.ClassName + \"<BR/>\" +\n \"IsClass: \" + pWMIClass.ClassPath.IsClass + \"<BR/>\" +\n \"IsInstance: \" + pWMIClass.ClassPath.IsInstance + \"<BR/>\" +\n \"IsSingleton: \" + pWMIClass.ClassPath.IsSingleton + \"<BR/>\" +\n \"Namespace Path: \" + pWMIClass.ClassPath.NamespacePath + \"<BR/>\" +\n \"Path: \" + pWMIClass.ClassPath.Path + \"<BR/>\" +\n \"Relative Path: \" + pWMIClass.ClassPath.RelativePath + \"<BR/>\" +\n \"Server: \" + pWMIClass.ClassPath.Server + \"<BR/>\";\n\n //GridView control\n this.gvProperties.DataSource = pWMIClass.Properties;\n this.gvProperties.DataBind();\n\n //GridView control\n this.gvSystemProperties.DataSource = pWMIClass.SystemProperties;\n this.gvSystemProperties.DataBind();\n\n //GridView control\n this.gvDerivation.DataSource = pWMIClass.Derivation;\n this.gvDerivation.DataBind();\n\n //GridView control\n this.gvMethods.DataSource = pWMIClass.Methods;\n this.gvMethods.DataBind();\n\n //GridView control\n this.gvQualifiers.DataSource = pWMIClass.Qualifiers;\n this.gvQualifiers.DataBind();\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
]
| I've created a seperate assembly with a class that is intended to be
published through wmi. Then I've created a windows forms app that
references that assembly and attempts to publish the class. When I try to
publish the class, I get an exception of type
System.Management.Instrumentation.WmiProviderInstallationException. The
message of the exception says "Exception of type
'System.Management.Instrumentation.WMIInfraException' was thrown.". I have
no idea what this means. I've tried .Net2.0 and .Net3.5 (sp1 too) and get the same results.
Below is my wmi class, followed by the code I used to publish it.
```
//Interface.cs in assembly WMI.Interface.dll
using System;
using System.Collections.Generic;
using System.Text;
[assembly: System.Management.Instrumentation.WmiConfiguration(@"root\Test",
HostingModel =
System.Management.Instrumentation.ManagementHostingModel.Decoupled)]
namespace WMI
{
[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller :
System.Management.Instrumentation.DefaultManagementInstaller { }
[System.Management.Instrumentation.ManagementEntity(Singleton = true)]
[System.Management.Instrumentation.ManagementQualifier("Description",
Value = "Obtain processor information.")]
public class Interface
{
[System.Management.Instrumentation.ManagementBind]
public Interface()
{
}
[System.Management.Instrumentation.ManagementProbe]
[System.Management.Instrumentation.ManagementQualifier("Descriiption",
Value="The number of processors.")]
public int ProcessorCount
{
get { return Environment.ProcessorCount; }
}
}
}
```
```
//Button click in windows forms application to publish class
try
{
System.Management.Instrumentation.InstrumentationManager.Publish(new
WMI.Interface());
}
catch (System.Management.Instrumentation.InstrumentationException
exInstrumentation)
{
MessageBox.Show(exInstrumentation.ToString());
}
catch (System.Management.Instrumentation.WmiProviderInstallationException
exProvider)
{
MessageBox.Show(exProvider.ToString());
}
catch (Exception exPublish)
{
MessageBox.Show(exPublish.ToString());
}
``` | I used gacutil - installutil to to test your class (as a dll). The gacutil part worked, but installutil (actually mofcomp) complained about a syntax error:
...
error SYNTAX 0X80044014:
Unexpected character in class name (must be an identifier)
Compiler returned error 0x80044014
...
So I changed the class name to 'MyInterface' the installutil part worked, but the class didn't return any instances. Finally I changed the hosting model to Network Service and got it to work. |
65,400 | <p>How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":</p>
<pre><code>def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
dict["foobar"] = bar
return type(name, bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'
</code></pre>
<p>My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:</p>
<pre><code>dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
</code></pre>
<p>There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?</p>
| [
{
"answer_id": 65682,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 2,
"selected": false,
"text": "<p>I think what you want to do is this:</p>\n\n<pre><code>>>> class Foo():\n... def __init__(self, x):\n... self.x = x\n... \n>>> def bar(self):\n... print 'bar:', self.x\n... \n>>> bar.func_name = 'foobar'\n>>> Foo.foobar = bar\n>>> f = Foo(12)\n>>> f.foobar()\nbar: 12\n>>> f.foobar.func_name\n'foobar'\n</code></pre>\n\n<p>Now you are free to pass <code>Foo</code>s to a library that expects <code>Foo</code> instances to have a method named <code>foobar</code>.</p>\n\n<p>Unfortunately, (1) I don't know how to use metaclasses and (2) I'm not sure I read your question correctly, but I hope this helps. </p>\n\n<p>Note that <code>func_name</code> is only assignable in Python 2.4 and higher.</p>\n"
},
{
"answer_id": 65716,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": true,
"text": "<p>Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:</p>\n\n<pre><code>class Parent(object):\n def bar(self):\n print \"bar\"\n\nclass MetaFoo(type):\n def __new__(cls, name, bases, dict):\n return type(name, (Parent,) + bases, dict)\n\nclass Foo(object):\n __metaclass__ = MetaFoo\n\nif __name__ == \"__main__\":\n f = Foo()\n f.bar()\n print f.bar.func_name\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5179/"
]
| How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func\_name will still be "foo":
```
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
dict["foobar"] = bar
return type(name, bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'
```
My problem is that some library code actually uses the func\_name and later fails to find the 'bar' method of the Foo instance. I could do:
```
dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
```
There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here? | Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:
```
class Parent(object):
def bar(self):
print "bar"
class MetaFoo(type):
def __new__(cls, name, bases, dict):
return type(name, (Parent,) + bases, dict)
class Foo(object):
__metaclass__ = MetaFoo
if __name__ == "__main__":
f = Foo()
f.bar()
print f.bar.func_name
``` |
65,427 | <p>As I understand it, anything created with an <strong>alloc</strong>, <strong>new</strong>, or <strong>copy</strong> needs to be manually released. For example:</p>
<pre><code>int main(void) {
NSString *string;
string = [[NSString alloc] init];
/* use the string */
[string release];
}
</code></pre>
<p>My question, though, is wouldn't this be just as valid?:</p>
<pre><code>int main(void) {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
NSString *string;
string = [[[NSString alloc] init] autorelease];
/* use the string */
[pool drain];
}
</code></pre>
| [
{
"answer_id": 65483,
"author": "kperryua",
"author_id": 72126,
"author_profile": "https://Stackoverflow.com/users/72126",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, your second code snippit is perfectly valid.</p>\n\n<p>Every time -autorelease is sent to an object, it is added to the inner-most autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.</p>\n\n<p>Autorelease pools are simply a convenience that allows you to defer sending -release until \"later\". That \"later\" can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle.</p>\n"
},
{
"answer_id": 65517,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": -1,
"selected": false,
"text": "<p>Yes and no. You would end up releasing the string memory but \"leaking\" the NSAutoreleasePool object into memory by using drain instead of release if you ran this under a garbage collected (not memory managed) environment. This \"leak\" simply makes the instance of NSAutoreleasePool \"unreachable\" like any other object with no strong pointers under GC, and the object would be cleaned up the next time GC runs, which could very well be directly after the call to <code>-drain</code>:</p>\n\n<blockquote>\n <p>drain</p>\n \n <p>In a garbage collected environment, triggers garbage collection if memory allocated since last collection is greater than the current threshold; otherwise behaves as release.\n ...\n In a garbage-collected environment, this method ultimately calls <code>objc_collect_if_needed</code>.</p>\n</blockquote>\n\n<p>Otherwise, it's similar to how <code>-release</code> behaves under non-GC, yes. As others have stated, <code>-release</code> is a no-op under GC, so the only way to make sure the pool functions properly under GC is through <code>-drain</code>, and <code>-drain</code> under non-GC works exactly like <code>-release</code> under non-GC, and arguably communicates its functionality more clearly as well. </p>\n\n<p>I should point out that your statement \"anything called with new, alloc or init\" should not include \"init\" (but should include \"copy\"), because \"init\" doesn't allocate memory, it only sets up the object (constructor fashion). If you received an alloc'd object and your function only called init as such, you would not release it:</p>\n\n<pre><code>- (void)func:(NSObject*)allocd_but_not_init\n{\n [allocd_but_not_init init];\n}\n</code></pre>\n\n<p>That does not consume any more memory than it you already started with (assuming init doesn't instantiate objects, but you're not responsible for those anyway).</p>\n"
},
{
"answer_id": 68059,
"author": "kperryua",
"author_id": 72126,
"author_profile": "https://Stackoverflow.com/users/72126",
"pm_score": 3,
"selected": false,
"text": "<p>No, you're wrong. The documentation states clearly that under non-GC, -drain is equivalent to -release, meaning the NSAutoreleasePool will <strong>not</strong> be leaked.</p>\n"
},
{
"answer_id": 181043,
"author": "mmalc",
"author_id": 23233,
"author_profile": "https://Stackoverflow.com/users/23233",
"pm_score": 5,
"selected": false,
"text": "<h2>NSAutoreleasePool: drain vs. release</h2>\n\n<p>Since the function of <code>drain</code> and <code>release</code> seem to be causing confusion, it may be worth clarifying here (although this is covered in <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html#//apple_ref/occ/instm/NSAutoreleasePool/drain\" rel=\"noreferrer\">the documentation</a>...).</p>\n\n<p>Strictly speaking, from the big picture perspective <code>drain</code> is <em>not</em> equivalent to <code>release</code>:</p>\n\n<p>In a reference-counted environment, <code>drain</code> does perform the same operations as <code>release</code>, so the two are in that sense equivalent. To emphasise, this means you do <em>not</em> leak a pool if you use <code>drain</code> rather than <code>release</code>.</p>\n\n<p>In a garbage-collected environment, <code>release</code> is a no-op. Thus it has no effect. <code>drain</code>, on the other hand, contains a hint to the collector that it should \"collect if needed\". Thus in a garbage-collected environment, using <code>drain</code> helps the system balance collection sweeps.</p>\n"
},
{
"answer_id": 7991256,
"author": "Neovibrant",
"author_id": 655292,
"author_profile": "https://Stackoverflow.com/users/655292",
"pm_score": 4,
"selected": false,
"text": "<p>As already pointed out, your second code snippet is correct.</p>\n\n<p>I would like to suggest a more succinct way of using the autorelease pool that works on all environments (ref counting, GC, ARC) and also avoids the drain/release confusion:</p>\n\n<pre><code>int main(void) {\n @autoreleasepool {\n NSString *string;\n string = [[[NSString alloc] init] autorelease];\n /* use the string */\n }\n}\n</code></pre>\n\n<p>In the example above please note the <strong>@autoreleasepool</strong> block. This is documented <a href=\"http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 21909235,
"author": "Gagan_iOS",
"author_id": 3173478,
"author_profile": "https://Stackoverflow.com/users/3173478",
"pm_score": 0,
"selected": false,
"text": "<p>What I read from Apple:\n\"At the end of the autorelease pool block, objects that received an autorelease message within the block are sent a release message—an object receives a release message for each time it was sent an autorelease message within the block.\"</p>\n\n<p><a href=\"https://developer.apple.com/library/mac/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html\" rel=\"nofollow\">https://developer.apple.com/library/mac/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html</a></p>\n"
},
{
"answer_id": 24452608,
"author": "Hardik Mamtora",
"author_id": 2125928,
"author_profile": "https://Stackoverflow.com/users/2125928",
"pm_score": 0,
"selected": false,
"text": "<p>sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is drained (it may be longer if the object is subsequently retained). An object can be put into the same pool several times, in which case it receives a release message for each time it was put into the pool.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7979/"
]
| As I understand it, anything created with an **alloc**, **new**, or **copy** needs to be manually released. For example:
```
int main(void) {
NSString *string;
string = [[NSString alloc] init];
/* use the string */
[string release];
}
```
My question, though, is wouldn't this be just as valid?:
```
int main(void) {
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
NSString *string;
string = [[[NSString alloc] init] autorelease];
/* use the string */
[pool drain];
}
``` | Yes, your second code snippit is perfectly valid.
Every time -autorelease is sent to an object, it is added to the inner-most autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.
Autorelease pools are simply a convenience that allows you to defer sending -release until "later". That "later" can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle. |
65,431 | <p>Is there a reliable way to detect whether or not WinHelp is installed on Windows Vista or newer versions of Windows? If possible, I'd like a solution that's not specific to any particular version of Windows.</p>
<p>I've posted this question to other message boards and got back answers regarding the size of Winhlp32.exe before and after installing WinHelp and Registry entries that Microsoft has documented, but none of them were correct.</p>
| [
{
"answer_id": 65672,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "<p>I hate to say it, but move on from WinHelp. It's been deprecated for a reason. We were able to migrate to a .chm in only a few hours. It's pretty straight-forward to use the newer help authoring tools, and newer formats like .chm give you benefits like cascading style sheets. </p>\n"
},
{
"answer_id": 71393,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 0,
"selected": false,
"text": "<p>Other than trying to convince management of the problems of this approach, you can look into the windows registry.</p>\n\n<p>Basically, if WinHelp is registered, the following registry entries are present:</p>\n\n<ul>\n<li><p>HKEY_CLASSES_ROOT \\ .hlp -> (Default) = hlpfile</p></li>\n<li><p>HKEY_CLASSES_ROOT \\ hlpfile \\ shell \\ open \\ command \\ (Default) contains the string \"winhlp32.exe\"</p></li>\n</ul>\n\n<p>if both of these values are correct, then winhelp is available, and registered. You can also retrieve the location of winhlp32.exe from here.</p>\n"
},
{
"answer_id": 129698,
"author": "TrevH",
"author_id": 10124,
"author_profile": "https://Stackoverflow.com/users/10124",
"pm_score": 2,
"selected": false,
"text": "<p>The download for WinHelp from Microsoft appears to be a hotfix (.msu) that enables the WinHelp program. This would explain why the size/registry keys don't change as the hotfix is just a \"delta\" change from the orginal file. </p>\n\n<p>Since it's a hotfix, this means that you should be able to query the installed hotfixes for your OS.</p>\n\n<p>The following command generates a .htm document listing all of the installed hotfixes.</p>\n\n<pre><code>wmic qfe list full /format:htable >C:\\hotfixes.htm\n</code></pre>\n\n<p>The table generated lists the Knowledge Base articles corresponding to the hotfix that is installed. You can search for \"917607\" because that should be present if you've installed the WinHelp hotfix. You may be able to pass in different options to the utility to perform a better search. NOTE - The wmic command requires admin privileges to run.</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=6EBCFAD9-D3F5-4365-8070-334CD175D4BB&displaylang=en\" rel=\"nofollow noreferrer\">Link to Microsoft KB Article on WinHelp</a></p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Is there a reliable way to detect whether or not WinHelp is installed on Windows Vista or newer versions of Windows? If possible, I'd like a solution that's not specific to any particular version of Windows.
I've posted this question to other message boards and got back answers regarding the size of Winhlp32.exe before and after installing WinHelp and Registry entries that Microsoft has documented, but none of them were correct. | The download for WinHelp from Microsoft appears to be a hotfix (.msu) that enables the WinHelp program. This would explain why the size/registry keys don't change as the hotfix is just a "delta" change from the orginal file.
Since it's a hotfix, this means that you should be able to query the installed hotfixes for your OS.
The following command generates a .htm document listing all of the installed hotfixes.
```
wmic qfe list full /format:htable >C:\hotfixes.htm
```
The table generated lists the Knowledge Base articles corresponding to the hotfix that is installed. You can search for "917607" because that should be present if you've installed the WinHelp hotfix. You may be able to pass in different options to the utility to perform a better search. NOTE - The wmic command requires admin privileges to run.
[Link to Microsoft KB Article on WinHelp](http://www.microsoft.com/downloads/details.aspx?FamilyId=6EBCFAD9-D3F5-4365-8070-334CD175D4BB&displaylang=en) |
65,434 | <p>I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the <strong>window.onload</strong> event), but it's different for every browser.</p>
<p>Is there a definitive way to do this on all the browsers?</p>
<p>So far I know of:</p>
<ul>
<li><p><strong>DOMContentLoaded</strong> : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:</p>
<p>document.addEventListener( "DOMContentLoaded", [init function], false );</p></li>
<li><p><strong>Deferred script</strong>: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.</p></li>
<li><p><strong>Polling</strong>: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?</p></li>
</ul>
<p>I'd like to be able to go without using document.write or external files.</p>
<p>This can be done simply via jQuery:</p>
<pre><code>$(document).ready(function() { ... })
</code></pre>
<p>but, I'm writing a JS library and can't count on jQuery always being there.</p>
| [
{
"answer_id": 65455,
"author": "Sijin",
"author_id": 8884,
"author_profile": "https://Stackoverflow.com/users/8884",
"pm_score": 1,
"selected": false,
"text": "<p>Just take the relevant piece of code from jQuery, John Resig has covered most of the bases on this issue already in jQuery.</p>\n"
},
{
"answer_id": 65476,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": -1,
"selected": false,
"text": "<p>This works pretty well:</p>\n\n<pre><code>setTimeout(MyInitFunction, 0);\n</code></pre>\n"
},
{
"answer_id": 65527,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "<p>There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.</p>\n\n<p>Mozilla, Opera, and modern WebKit support the <code>DOMContentLoaded</code> event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's <code>bindReady()</code> function.</p>\n"
},
{
"answer_id": 65582,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 2,
"selected": false,
"text": "<p>YUI uses three tests to do this: for Firefox and recent WebKit there's a DOMContentLoaded event that is fired. For older Safari the document.readyState watched until it becomes \"loaded\" or \"complete\". For IE an HTML <P> tag is created and the \"doScroll()\" method called which should error out if the DOM is not ready. The source for <a href=\"http://developer.yahoo.com/yui/docs/Event.js.html\" rel=\"nofollow noreferrer\">YAHOO.util.Event</a> shows YUI-specific code. Search for \"doScroll\" in the Event.js.</p>\n"
},
{
"answer_id": 66209,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "<p>Using a library like jQuery will save you countless hours of browsers inconsistencies.</p>\n\n<p>In this case with jQuery you can just</p>\n\n<pre><code>$(document).ready ( function () {\n //your code here\n});\n</code></pre>\n\n<p>If you are curious you can take a look at the source to see how it is done, but is this day and age I don't think anyone should be reinventing this wheel when the library writer have done all the painful work for you.</p>\n"
},
{
"answer_id": 67157,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 2,
"selected": false,
"text": "<p>I found this page, which shows a compact self-contained solution. It seems to work on every browser and has an explanation on how:</p>\n\n<p><a href=\"http://www.kryogenix.org/days/2007/09/26/shortloaded\" rel=\"nofollow noreferrer\">http://www.kryogenix.org/days/2007/09/26/shortloaded</a></p>\n"
},
{
"answer_id": 70595,
"author": "hulver",
"author_id": 11496,
"author_profile": "https://Stackoverflow.com/users/11496",
"pm_score": -1,
"selected": false,
"text": "<p>Using setTimeout can work quite well, although when it's executed is up to the browser. If you pass zero as the timeout time, the browser will execute when things are \"settled\".</p>\n\n<p>The good thing about this is that you can have many of them, and don't have to worry about chaining onLoad events.</p>\n\n<pre><code>setTimeout(myFunction, 0);\nsetTimeout(anotherFunction, 0);\nsetTimeout(function(){ doSomething ...}, 0);\n</code></pre>\n\n<p>etc.</p>\n\n<p>They will all run when the document has finished loading, or if you set one up after the document is loaded, they will run after your script has finished running.</p>\n\n<p>The order they run in is not determined, and can change between browsers. So you can't count on <code>myFunction</code> being run before <code>anotherFunction</code> for example.</p>\n"
},
{
"answer_id": 71085,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 0,
"selected": false,
"text": "<p>Why not this: </p>\n\n<pre><code><body> \n <!-- various content --> \n <script type=\"text/javascript\"> \n <!-- \n myInit(); \n -->\n </script> \n</body> \n</code></pre>\n\n<p>If I understand things correctly, myInit is gonna get executed as soon as browser hit it in the page, which is last thing in a body.</p>\n"
},
{
"answer_id": 15338341,
"author": "Justus Romijn",
"author_id": 334243,
"author_profile": "https://Stackoverflow.com/users/334243",
"pm_score": 0,
"selected": false,
"text": "<p>The fancy crossbrowser solution you are looking for....doesn't exist... (imagine the sound of a big crowd saying 'aahhhh....').</p>\n\n<p><strong>DomContentLoaded</strong> is simply your best shot. You still need the <code>polling</code> technique for IE-oldies.</p>\n\n<ol>\n<li>Try to use addEventListener;</li>\n<li>If not available (IE obviously), check for frames;</li>\n<li>If not a frame, scroll until no error get's thrown (polling);</li>\n<li>If a frame, use IE event document.onreadystatechange;</li>\n<li>For other non-supportive browsers, use old document.onload event.</li>\n</ol>\n\n<p>I've found the following code sample on <a href=\"http://javascript.info/tutorial/onload-ondomcontentloaded#the-crossbrowser-domcontentloaded-handling-code\" rel=\"nofollow\">javascript.info</a> which you can use to cover all browsers:</p>\n\n<pre><code>function bindReady(handler){\n\n var called = false\n\n function ready() { \n if (called) return\n called = true\n handler()\n }\n\n if ( document.addEventListener ) { // native event\n document.addEventListener( \"DOMContentLoaded\", ready, false )\n } else if ( document.attachEvent ) { // IE\n\n try {\n var isFrame = window.frameElement != null\n } catch(e) {}\n\n // IE, the document is not inside a frame\n if ( document.documentElement.doScroll && !isFrame ) {\n function tryScroll(){\n if (called) return\n try {\n document.documentElement.doScroll(\"left\")\n ready()\n } catch(e) {\n setTimeout(tryScroll, 10)\n }\n }\n tryScroll()\n }\n\n // IE, the document is inside a frame\n document.attachEvent(\"onreadystatechange\", function(){\n if ( document.readyState === \"complete\" ) {\n ready()\n }\n })\n }\n\n // Old browsers\n if (window.addEventListener)\n window.addEventListener('load', ready, false)\n else if (window.attachEvent)\n window.attachEvent('onload', ready)\n else {\n var fn = window.onload // very old browser, copy old onload\n window.onload = function() { // replace by new onload and call the old one\n fn && fn()\n ready()\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
]
| I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the **window.onload** event), but it's different for every browser.
Is there a definitive way to do this on all the browsers?
So far I know of:
* **DOMContentLoaded** : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:
document.addEventListener( "DOMContentLoaded", [init function], false );
* **Deferred script**: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.
* **Polling**: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?
I'd like to be able to go without using document.write or external files.
This can be done simply via jQuery:
```
$(document).ready(function() { ... })
```
but, I'm writing a JS library and can't count on jQuery always being there. | There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.
Mozilla, Opera, and modern WebKit support the `DOMContentLoaded` event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's `bindReady()` function. |
65,447 | <p>A sample perl script that connects to an oracle database, does a simple SELECT query, and spits the results to stdout in CSV format would be great. Python or any other language available in a typical unix distribution would be fine too. </p>
<p>Note that I'm starting from scratch with nothing but a username/password for a remote Oracle database. Is there more to this than just having the right oracle connection library?</p>
<p>If there's a way to do this directly in mathematica, that would be ideal (presumably it should be possible with J/Link (mathematica's java integration thingy)).</p>
| [
{
"answer_id": 65568,
"author": "Jumpy",
"author_id": 9416,
"author_profile": "https://Stackoverflow.com/users/9416",
"pm_score": 3,
"selected": true,
"text": "<p>In perl you could do something like this, leaving out all the my local variable declarations and ... or die \"failmessage\" error handling for brevity.</p>\n\n<pre><code>use DBI; \nuse DBD::Oracle;\n\n$dbh = DBI->connect( \"dbi:Oracle:host=127.0.0.1;sid=XE\", \"username\", \"password\" );\n\n# some settings that you usually want for oracle 10\n$dbh->{LongReadLen} = 65535;\n$dbh->{PrintError} = 0; \n\n$sth = $dbh->prepare(\"SELECT * FROM PEOPLE\");\n\n$sth->execute();\n\n# one example for error handling just to show how it's done in principle\nif ( $dbh->err() ) { die $dbh->errstr(); }\n\n# you can also do other types of fetchrow, see perldoc DBI \nwhile ( $arrayref = $sth->fetchrow_arrayref ) {\n print join \";\", @$arrayref;\n print \"\\n\";\n}\n\n$dbh->disconnect();\n</code></pre>\n\n<p>Two notes, because people asked in comments:</p>\n\n<ul>\n<li>sid=XE is the oracle service id, that is like the name of your database. If you install the free version of oracle, it defaults to \"XE\", but you can change it. </li>\n<li>Installing DBD::Oracle needs the oracle client libraries on your system. Installing that will also set all the necessary environment variables.</li>\n</ul>\n"
},
{
"answer_id": 65689,
"author": "Galuvian",
"author_id": 1566663,
"author_profile": "https://Stackoverflow.com/users/1566663",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an implementation in Python:</p>\n\n<pre><code>import cx_Oracle, csv\n\norcl = cx_Oracle.connect('ohd/john@ohddb')\ncurs = orcl.cursor()\n\ncsv_file_dest = \"C:\\\\test.csv\"\n\noutput = csv.writer(open(csv_file_dest,'wb'))\n\nsql = \"select * from parameter\"\n\ncurs.execute(sql)\n\nheaders_printed = False\nfor row_data in curs: \n if not headers_printed:\n cols = []\n for col in curs.description:\n cols.append(col[0])\n output.writerow(cols)\n headers_printed = True\n\n output.writerow(row_data)\n</code></pre>\n"
},
{
"answer_id": 65713,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 0,
"selected": false,
"text": "<p>Mathematica has a package \"DatabaseLink\" built in that should make this easy but you need to find a driver for Oracle. Installing the \"oracle client libraries\" should do that...</p>\n"
},
{
"answer_id": 66028,
"author": "Sten Vesterli",
"author_id": 9363,
"author_profile": "https://Stackoverflow.com/users/9363",
"pm_score": 0,
"selected": false,
"text": "<p>Get Oracle Application Express. It's a browser-based tool that comes free with the database. It allows you to quickly click together reports and specify CSV (or Excel) as output format. (You can also use it to build complete applications). </p>\n\n<p>You find tons of documentation, demos etc. here: \n<a href=\"http://apex.oracle.com\" rel=\"nofollow noreferrer\">http://apex.oracle.com</a></p>\n\n<p>You can also download the tool at this URL, or you can register for a free workspace and play around with the tool on an Oracle server. </p>\n"
},
{
"answer_id": 84764,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a PERL programmer, but here's a little extra feature you might want to investigate. Have a look at the concept of external tables in Oracle. You create a table with a definition of something similar to the following:-</p>\n\n<blockquote>\n<pre><code>CREATE TABLE MY_TABLE\n(\n COL1 NUMBER(2),\n COL2 VARCHAR2(20 BYTE)\n)\nORGANIZATION EXTERNAL\n ( TYPE ORACLE_LOADER\n DEFAULT DIRECTORY SOME_DIRECTORY_NAME\n ACCESS PARAMETERS \n ( FIELDS TERMINATED BY ','\n MISSING FIELD VALUES ARE NULL\n )\n LOCATION (SOME_DIRECTORY_NAME:'my_file.csv')\n )\nREJECT LIMIT UNLIMITED;\n</code></pre>\n</blockquote>\n\n<p>Note this DDL statement assumes you have a directory already created called \"SOME_DIRECTORY_NAME\". You can then issue DML commands to get data into or out of this table, and once the commit has been done, the data is all nice and neat in your file my_file.csv. After that, do your PERL magic to get the file wherever you want it to be.</p>\n"
},
{
"answer_id": 110013,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>How about something as simple as creating the file from sqlplus...</p>\n\n<pre><code>set echo off heading off feedback off colsep ,;\nspool file.csv;\nselect owner, table_name\nfrom all_tables;\nspool off;\n</code></pre>\n"
},
{
"answer_id": 603665,
"author": "jfklein",
"author_id": 72919,
"author_profile": "https://Stackoverflow.com/users/72919",
"pm_score": 2,
"selected": false,
"text": "<p>As dreeves says, DatabaseLink makes this trivial. The part I don't know is the details of the JDBC declaration. But here's how things look for MySQL:</p>\n\n<p>Then from within Mathematica:</p>\n\n<pre><code>Needs[\"DatabaseLink`\"]\nconn = OpenSQLConnection[JDBC[\"mysql\",\"hostname/dbname\"], Username->\"user\", Password->\"secret\"]\nExport[\"file.csv\", SQLSelect[conn, \"MyTable\"]]\n</code></pre>\n\n<p>You could of course assign the SQLSelect to a variable first and examine it. It will be a list of lists holding the table data. You can pass conditions to SQLSelect, see the documentation for that (e.g. SQLColumn[\"Name\"]==\"joeuser\").</p>\n\n<p>The only thing Oracle-specific here is how you make the connection, in the JDBC expression. It is probably something like JDBC[\"oracle\", \"hostname/dbname\"].</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4234/"
]
| A sample perl script that connects to an oracle database, does a simple SELECT query, and spits the results to stdout in CSV format would be great. Python or any other language available in a typical unix distribution would be fine too.
Note that I'm starting from scratch with nothing but a username/password for a remote Oracle database. Is there more to this than just having the right oracle connection library?
If there's a way to do this directly in mathematica, that would be ideal (presumably it should be possible with J/Link (mathematica's java integration thingy)). | In perl you could do something like this, leaving out all the my local variable declarations and ... or die "failmessage" error handling for brevity.
```
use DBI;
use DBD::Oracle;
$dbh = DBI->connect( "dbi:Oracle:host=127.0.0.1;sid=XE", "username", "password" );
# some settings that you usually want for oracle 10
$dbh->{LongReadLen} = 65535;
$dbh->{PrintError} = 0;
$sth = $dbh->prepare("SELECT * FROM PEOPLE");
$sth->execute();
# one example for error handling just to show how it's done in principle
if ( $dbh->err() ) { die $dbh->errstr(); }
# you can also do other types of fetchrow, see perldoc DBI
while ( $arrayref = $sth->fetchrow_arrayref ) {
print join ";", @$arrayref;
print "\n";
}
$dbh->disconnect();
```
Two notes, because people asked in comments:
* sid=XE is the oracle service id, that is like the name of your database. If you install the free version of oracle, it defaults to "XE", but you can change it.
* Installing DBD::Oracle needs the oracle client libraries on your system. Installing that will also set all the necessary environment variables. |
65,452 | <p>This morning I ran into an issue with returning back a text string as result from a Web Service call. the Error I was getting is below</p>
<pre><code>************** Exception Text **************
System.ServiceModel.CommunicationException: Error in deserializing body of reply message for operation 'GetFilingTreeXML'. ---> System.InvalidOperationException: There is an error in XML document (1, 9201). ---> System.Xml.XmlException: The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 9201.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, Int32 maxStringContentLength)
at System.Xml.XmlDictionaryReader.ReadString(Int32 maxStringContentLength)
at System.Xml.XmlDictionaryReader.ReadString()
at System.Xml.XmlBaseReader.ReadElementString()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderImageServerClientInterfaceSoap.Read10_GetFilingTreeXMLResponse()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer9.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)
--- End of inner exception stack trace ---
</code></pre>
<p>I did a search and the results are below:
<a href="http://search.yahoo.com/search?p=This+quota+may+be+increased+by+changing+the+MaxStringContentLength+property+on+the+XmlDictionaryReaderQuotas+object+used+when+creating+the+XML+reader." rel="nofollow noreferrer">Search Results</a></p>
<p>Most of those are WCF related but were enough to point me in the right direction. I will post answer as reply.</p>
| [
{
"answer_id": 65499,
"author": "MikeScott8",
"author_id": 1889,
"author_profile": "https://Stackoverflow.com/users/1889",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://joewirtley.blogspot.com/2007/08/maximum-string-content-length-and.html\" rel=\"nofollow noreferrer\">Jow Wirtley's blog post</a> pointed me in the right direction.</p>\n\n<p>All I had to do was update the bindings in the app.config of the client app and it all works now.</p>\n"
},
{
"answer_id": 65511,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 6,
"selected": true,
"text": "<p>Try this blog post <a href=\"https://web.archive.org/web/20210128000850/http://geekswithblogs.net/niemguy/archive/2007/12/11/wcf-maxstringcontentlength-maxbuffersize-and-maxreceivedmessagesize.aspx\" rel=\"nofollow noreferrer\">here</a>. You can modify the MaxStringContentLength property in the Binding configuration.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1889/"
]
| This morning I ran into an issue with returning back a text string as result from a Web Service call. the Error I was getting is below
```
************** Exception Text **************
System.ServiceModel.CommunicationException: Error in deserializing body of reply message for operation 'GetFilingTreeXML'. ---> System.InvalidOperationException: There is an error in XML document (1, 9201). ---> System.Xml.XmlException: The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 9201.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, Int32 maxStringContentLength)
at System.Xml.XmlDictionaryReader.ReadString(Int32 maxStringContentLength)
at System.Xml.XmlDictionaryReader.ReadString()
at System.Xml.XmlBaseReader.ReadElementString()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderImageServerClientInterfaceSoap.Read10_GetFilingTreeXMLResponse()
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer9.Deserialize(XmlSerializationReader reader)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, XmlSerializer serializer, MessagePartDescription returnPart, MessagePartDescriptionCollection bodyParts, Object[] parameters, Boolean isRequest)
--- End of inner exception stack trace ---
```
I did a search and the results are below:
[Search Results](http://search.yahoo.com/search?p=This+quota+may+be+increased+by+changing+the+MaxStringContentLength+property+on+the+XmlDictionaryReaderQuotas+object+used+when+creating+the+XML+reader.)
Most of those are WCF related but were enough to point me in the right direction. I will post answer as reply. | Try this blog post [here](https://web.archive.org/web/20210128000850/http://geekswithblogs.net/niemguy/archive/2007/12/11/wcf-maxstringcontentlength-maxbuffersize-and-maxreceivedmessagesize.aspx). You can modify the MaxStringContentLength property in the Binding configuration. |
65,456 | <p>I'm specifically interested in tools that can be plugged into Vim to allow CScope-style source browsing (1-2 keystroke commands to locate function definitions, callers, global symbols and so on) for languages besides C/C++ such as Java and C# (since Vim and Cscope already integrate very well for browsing C/C++). I'm not interested in IDE-based tools since I know Microsoft and other vendors already address that space -- I prefer to use Vim for editing and browsing, but but don't know of tools for C# and/or Java that give me the same power as CScope.</p>
<p>The original answer to this question included a pointer to the CSWrapper application which apparently fixes a bug that some users experience integrating Vim and CScope. However, my Vim/CScope installation works fine; I'm just trying to expand the functionality to allow using Vim to edit code in other languages.</p>
| [
{
"answer_id": 65544,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": -1,
"selected": false,
"text": "<p>This may be what you're looking for:</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=1783\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=1783</a></p>\n\n<p>You can also mimic some CScope functionality in your own .vimrc file by using the various flavors of <a href=\"http://vimdoc.sourceforge.net/htmldoc/map.html\" rel=\"nofollow noreferrer\">map</a>.</p>\n"
},
{
"answer_id": 164864,
"author": "alps123",
"author_id": 22337,
"author_profile": "https://Stackoverflow.com/users/22337",
"pm_score": 3,
"selected": true,
"text": "<p>CScope does work for Java.</p>\n\n<p>From <a href=\"http://cscope.sourceforge.net/cscope_vim_tutorial.html\" rel=\"nofollow noreferrer\">http://cscope.sourceforge.net/cscope_vim_tutorial.html</a>:</p>\n\n<blockquote>\n <p>Although Cscope was originally intended only for use with C code, it's\n actually a very flexible tool that works well with languages like C++\n and Java. You can think of it as a generic 'grep' database, with the\n ability to recognize certain additional constructs like function calls\n and variable definitions. By default Cscope only parses C, lex, and\n yacc files (.c, .h, .l, .y) in the current directory (and\n subdirectories, if you pass the -R flag), and there's currently no way\n to change that list of file extensions (yes, we ought to change that).\n So instead you have to make a list of the files that you want to\n parse, and call it 'cscope.files' (you can call it anything you want\n if you invoke 'cscope -i foofile'). An easy (and very flexible) way to\n do this is via the trusty Unix 'find' command:</p>\n</blockquote>\n\n<pre><code>find . -name '*.java' > cscope.files\n</code></pre>\n\n<blockquote>\n <p>Now run 'cscope -b' to rebuild the database (the -b just builds the\n database without launching the Cscope GUI), and you'll be able to\n browse all the symbols in your Java files. Apparently there are folks\n out there using Cscope to browse and edit large volumes of\n documentation files, which shows how flexible Cscope's parser is.</p>\n</blockquote>\n"
},
{
"answer_id": 7197831,
"author": "Andrew",
"author_id": 379428,
"author_profile": "https://Stackoverflow.com/users/379428",
"pm_score": 3,
"selected": false,
"text": "<p>Claiming that Cscope supports Java is an extreme stretch. It seems to treat a method like a function, so it has no idea that A.foo(), A.foo(Object) and B.foo() are all different. This is a big problem with a large code base (including third-party libraries) with many same-named methods. (I haven't looked at the Cscope source, but this is what I found trying the latest Cscope, version 15.7a-3.3 from Debian unstable.)</p>\n\n<p>I tried Cscope on a large Java project, and it was not at all useful to me due to this limitation. It's sad that we cannot get a quick answer to a basic question like \"who calls this method\", using free software outside of the big IDEs, but we may as well accept it. (I would love it if I'm wrong. I resort to hacks like commenting out the method and recompiling.)</p>\n"
},
{
"answer_id": 18357900,
"author": "Yike Lu",
"author_id": 1197961,
"author_profile": "https://Stackoverflow.com/users/1197961",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Andrew - trying to get a call hierarchy for a method returns all calls of the same name, even if they are from a different class.</p>\n\n<p>You can use Eclim to plug Eclipse into VIM</p>\n\n<p><a href=\"http://eclim.org/\" rel=\"nofollow\">http://eclim.org/</a></p>\n\n<p>which supportrs call hierarchy</p>\n\n<p><a href=\"http://eclim.org/vim/java/inspection.html#call-hierarchy\" rel=\"nofollow\">http://eclim.org/vim/java/inspection.html#call-hierarchy</a></p>\n"
},
{
"answer_id": 32697656,
"author": "Evan",
"author_id": 3179857,
"author_profile": "https://Stackoverflow.com/users/3179857",
"pm_score": 2,
"selected": false,
"text": "<p>A bit late to the party here, but my <a href=\"https://github.com/eapache/starscope/\" rel=\"nofollow\">https://github.com/eapache/starscope/</a> project provides a nice framework for generating cscope databases for more languages. Currently it supports Ruby and Go, and Javascript is in progress. Adding Java/C# shouldn't be that difficult.</p>\n\n<p>Edit: Javascript is now fully supported.</p>\n"
}
]
| 2008/09/15 | [
"https://Stackoverflow.com/questions/65456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8998/"
]
| I'm specifically interested in tools that can be plugged into Vim to allow CScope-style source browsing (1-2 keystroke commands to locate function definitions, callers, global symbols and so on) for languages besides C/C++ such as Java and C# (since Vim and Cscope already integrate very well for browsing C/C++). I'm not interested in IDE-based tools since I know Microsoft and other vendors already address that space -- I prefer to use Vim for editing and browsing, but but don't know of tools for C# and/or Java that give me the same power as CScope.
The original answer to this question included a pointer to the CSWrapper application which apparently fixes a bug that some users experience integrating Vim and CScope. However, my Vim/CScope installation works fine; I'm just trying to expand the functionality to allow using Vim to edit code in other languages. | CScope does work for Java.
From <http://cscope.sourceforge.net/cscope_vim_tutorial.html>:
>
> Although Cscope was originally intended only for use with C code, it's
> actually a very flexible tool that works well with languages like C++
> and Java. You can think of it as a generic 'grep' database, with the
> ability to recognize certain additional constructs like function calls
> and variable definitions. By default Cscope only parses C, lex, and
> yacc files (.c, .h, .l, .y) in the current directory (and
> subdirectories, if you pass the -R flag), and there's currently no way
> to change that list of file extensions (yes, we ought to change that).
> So instead you have to make a list of the files that you want to
> parse, and call it 'cscope.files' (you can call it anything you want
> if you invoke 'cscope -i foofile'). An easy (and very flexible) way to
> do this is via the trusty Unix 'find' command:
>
>
>
```
find . -name '*.java' > cscope.files
```
>
> Now run 'cscope -b' to rebuild the database (the -b just builds the
> database without launching the Cscope GUI), and you'll be able to
> browse all the symbols in your Java files. Apparently there are folks
> out there using Cscope to browse and edit large volumes of
> documentation files, which shows how flexible Cscope's parser is.
>
>
> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.