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>&lt;% form_for( :fmfile, :url =&gt; '/fmfiles', :html =&gt; { :method =&gt; :post, :name =&gt; 'Form_Import_DDR', :enctype =&gt; 'multipart/form-data' } ) do |f| %&gt; &lt;%= f.file_field :document, :accept =&gt; 'text/xml', :name =&gt; 'fmfile_document' %&gt; &lt;%= submit_tag 'Import DDR' %&gt; &lt;% end %&gt; </code></pre> <p>Results in the following HTML form</p> <pre><code>&lt;form action="/fmfiles" enctype="multipart/form-data" method="post" name="Form_Import_DDR"&gt;&lt;div style="margin:0;padding:0"&gt;&lt;input name="authenticity_token" type="hidden" value="3da97372885564a4587774e7e31aaf77119aec62" /&gt; &lt;input accept="text/xml" id="fmfile_document" name="fmfile_document" size="30" type="file" /&gt; &lt;input name="commit" type="submit" value="Import DDR" /&gt; &lt;/form&gt; </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"=&gt;"Import DDR", "authenticity_token"=&gt;"3da97372885564a4587774e7e31aaf77119aec62", "action"=&gt;"create", "fmfile_document"=&gt;#&lt;File:/var/folders/LU/LU50A0vNHA07S4rxDAOk4E+++TI/-Tmp-/CGI.3001.1&gt;, "controller"=&gt;"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 (#&lt;Iconv::InvalidCharacter: "਼䙍偒数 (followed by a few thousand similar looking chinese characters) 䙍偒数潲琾", ["\n"]&gt; /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...
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" }, { ...
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().addShutd...
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&lt;int&gt; frac = new Fraction&lt;int&gt;(1,2)</code> and/or <code>Fraction&lt;double&gt; frac = new Fraction&lt;double&gt;(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\...
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 behavi...
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>O...
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>...
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><c...
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...
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 &lt;&lt;= 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&gt;&gt;= 1, bit_setter&lt;&lt;= 1) if (arg &amp; 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 bi...
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>\ / &lt; &gt; ? * : </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 t...
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 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 ...
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-&gt;Questionnaire-&gt;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-&gt;Questionnaire-&gt;read(null, $questionnaire_id); $question = $this-&gt;Questionnaire-&gt;Question-&gt;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-&gt;layout = 'questionnaire_frontend_layout'; if (!$id) { $id = $this-&gt;Session-&gt;read('Questionnaire.id'); } if ($id) { $this-&gt;data = $this-&gt;Questionnaire-&gt;read(null, $id); //echo "from ".$questionnaire['Questionnaire']['validFrom']." ".date("y.m.d"); //echo " - to ".$questionnaire['Questionnaire']['validTo']." ".date("y.m.d"); if ($this-&gt;data['Questionnaire']['isPublished'] != 1 //|| $this-&gt;data['Questionnaire']['validTo'] &lt; date("y.m.d") //|| $this-&gt;data['Questionnaire']['validTo'] &lt; date("y.m.d") ) { $id = 0; $this-&gt;flash(__('Ungültiges Quiz. Weiter zum Archiv...', true), array('action'=&gt;'archive')); } } else { $this-&gt;flash(__('Invalid Questionnaire', true), array('action'=&gt;'intro')); } return $id; } function start($id = null) { $this-&gt;log("start"); $id = $this-&gt;checkValidQuestionnaire($id); //$questionnaire = $this-&gt;Questionnaire-&gt;read(null, $id); $this-&gt;set('questionnaire', $this-&gt;data); // reset flow-controlling session vars $this-&gt;Session-&gt;write('Questionnaire',array('id' =&gt; $id)); $this-&gt;Session-&gt;write('Questionnaire'.$id.'currQuestion', null); $this-&gt;Session-&gt;write('Questionnaire'.$id.'lastAnsweredQuestion', null); $this-&gt;Session-&gt;write('Questionnaire'.$id.'correctAnswersNum', null); $this-&gt;loadAdvertisement($id, 0); $this-&gt;Session-&gt;write('Questionnaire'.$id.'previewMode', $this-&gt;params['named']['preview_mode']); if (!$this-&gt;Session-&gt;read('Questionnaire'.$id.'previewMode')) { $questionnaire['Questionnaire']['participiantStartCount']++; $this-&gt;Questionnaire-&gt;save($questionnaire); } } function loadAdvertisement($questionnaire_id, $question_id) { //$questionnaire = array(); $questionnaire = $this-&gt;Questionnaire-&gt;read(null, $questionnaire_id); //$question = array(); $question = $this-&gt;Questionnaire-&gt;Question-&gt;read(null, $question_id); if (isset($question['Question']['advertisement_id']) &amp;&amp; $question['Question']['advertisement_id'] &gt; 0) { $this-&gt;set('advertisement', $this-&gt;Questionnaire-&gt;Question-&gt;Advertisement-&gt;read(null, $question['Question']['advertisement_id'])); } else if (isset($questionnaire['Questionnaire']['advertisement_id']) &amp;&amp; $questionnaire['Questionnaire']['advertisement_id'] &gt; 0) { $this-&gt;set('advertisement', $this-&gt;Questionnaire-&gt;Question-&gt;Advertisement-&gt;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....
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": 6...
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 t...
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 (wi...
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.a...
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 v...
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 ...
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": ...
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>&lt;?php echo date(\"Y\"); ?&gt;\n</code></pre>\n" }, { "answer_id": 64011, "author": "Mark Bi...
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/...
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...
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 is...
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...
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 c...
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...
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=&gt;"b33r", :user=&gt;current_user, :date=&gt;"2008/09/15"}) o.entries.build({:account_id=&gt;1, :amount=&gt;15}) o.valid? #=&gt;false o.entries.build({:account_id=&gt;2, :amount=&gt;-15}) o.valid? #=&gt;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 st...
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\">CryptUnprotectDat...
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...
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 databas...
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>&lt;img src="http://www.myserver.com/renderimage?scene=1&amp;x=123&amp;y=123&amp;z=123"&gt; </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 pa...
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 ...
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>&lt;script type="text/javascript" src="jquery.js"&gt;</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.\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>...
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> &raquo; a pretty 79 character length divider</p> <p><strong>VIM</strong>: <code>79-i-#</code> &raquo; 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 repl...
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\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 (li...
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 Optional...
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 &lt;iostream&gt; using namespace std; template &lt;typename T&gt; class A { private: template &lt;bool b&gt; void testme(); template &lt;&gt; void testme&lt;true&gt;() { cout &lt;&lt; "true" &lt;&lt; endl; }; template &lt;&gt; void testme&lt;false&gt;() { cout &lt;&lt; "false" &lt;&lt; endl; }; public: void test(); }; template&lt;typename T&gt; struct select {}; template&lt;&gt; struct select&lt;int&gt; { static const bool value = true; }; template&lt;&gt; struct select&lt;double&gt; { static const bool value = false; }; template &lt;class T&gt; void A&lt;T&gt;::test() { testme&lt;select&lt;T&gt;::value&gt;(); } int main(int argc, const char* argv[]) { A&lt;int&gt; aInt; A&lt;double&gt; 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>...
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 &lt;john@doe.net&gt;" to_addr = "foo@bar.com" 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 ...
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 <john@doe.net>" to_addr = "foo@bar.com" 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...
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>&lt;link href="../../Content/Site.css" rel="stylesheet" type="text/css" /&gt; </code></pre> <p>but looking at the source once the page is fed to a browser I get</p> <pre><code>&lt;link href="Content/Site.css" rel="stylesheet" type="text/css" /&gt; </code></pre> <p>which is perfect. However the same path translation doesn't seem to work for script files. </p> <pre><code>&lt;script src="../../Content/menu.js" type="text/javascript"&gt;&lt;/script&gt; </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>&lt;link href=\"~/Content/Site.css\" rel=\"stylesheet\" type=\"text/css\" /&gt;\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]=&gt; string(1) &quot;1&quot; [1]=&gt; string(1) &quot;2&quot; [2]=&gt; string(0) &quot;&quot; [3]=&gt; string(1) &quot;3&quot; [4]=&gt; string(0) &quot;&quot; } </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]=&gt; string(1) &quot;1&quot; [1]=&gt; string(1) &quot;2&quot; [2]=&gt; string(1) &quot;3&quot; } </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...
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 My...
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 s...
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>&lt;script language=\"javascript\"&gt;\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": ...
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_i...
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":...
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_...
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 p...
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 -&gt; String -&gt; String -&gt; 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.Rege...
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=\"nofollo...
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&amp;destination=234&amp;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...
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 &lt;&lt; (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 &lt;&lt; \"Player\" &lt;&lt; i ;\n</code></pre>\n" }, { "answer_id": 64795, "author": "Community", ...
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 &lt;http://www.linuxcommand.org/wss0150.php&gt; 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&gt;&amp;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' w...
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&lt;T&gt; MyMethod&lt;T&gt;(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&lt;TestEnum&gt;("item2"); // The following line works great but does not work for testing private methods. TestEnum? e2 = c.MyMethod&lt;TestEnum&gt;("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"...
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. <...
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</c...
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 ...
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 (i...
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&lt;type&gt;::is_signed</code>.</p>\n<pre><code>#include &lt;limits&gt;\nstd::numeric_...
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 &gt; 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:\&gt; 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 &quot;String&quot; 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 &quot;Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii&quot;.</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-ENCOD...
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,...
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 thoug...
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 th...
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 ...
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.&lt;tablename&gt; ADD CONSTRAINT\n &lt;namingconventionconstraint&gt; UNIQUE NONCLU...
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 fol...
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&lt;T&gt; 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&lt;FaultDetails&gt;:</p> <pre><code> throw new FaultException&lt;FaultDetails&gt;( new FaultDetails("Throwing FaultException&lt;FaultDetails&gt;."), 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>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;Fault xmlns="http://www.w3.org/2003/05/soap-envelope"&gt; &lt;Code&gt; &lt;Value&gt;Sender&lt;/Value&gt; &lt;Subcode&gt; &lt;Value&gt;MySubFaultCode&lt;/Value&gt; &lt;/Subcode&gt; &lt;/Code&gt; &lt;Reason&gt; &lt;Text xml:lang="en-US"&gt;Testing fault exceptions.&lt;/Text&gt; &lt;/Reason&gt; &lt;Detail&gt; &lt;FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;Message&gt;Throwing FaultException&amp;lt;FaultDetails&amp;gt;.&lt;/Message&gt; &lt;/FaultDetails&gt; &lt;/Detail&gt; </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>&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;s:Fault xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;faultcode&gt;s:MySubFaultCode&lt;/faultcode&gt; &lt;faultstring xml:lang="en-US"&gt;Testing fault exceptions.&lt;/faultstring&gt; &lt;detail&gt; &lt;FaultDetails xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;Message&gt;Throwing FaultException&amp;lt;FaultDetails&amp;gt;.&lt;/Message&gt; &lt;/FaultDetails&gt; &lt;/detail&gt; &lt;/s:Fault&gt; </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&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=669420&amp;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&amp;SiteID=1&amp;mode=1" rel="nofollow noreferrer">http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3883110&amp;SiteID=1&amp;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> /// &lt;summary&gt;\n /// Replacement for the static methods on FaultC...
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&lt;FaultDetails&gt;.</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&lt;FaultDetails&gt;.</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>&lt;iframe src="myURL" width="300" height="300"&gt;Browser not compatible.&lt;/iframe&gt; </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:...
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.<...
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><cod...
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='&amp;hellip;'</code>, or sometimes just <code>class='&amp;hellip;'</code>, but I can't seem to find a way to say id='&hellip;' and not have it swapped out by the server.</p> <p>Here is an example:</p> <pre><code>&lt;span id='position_title' runat='server'&gt;Manager&lt;/span&gt; </code></pre> <p>When the response comes back from the server, I get:</p> <pre><code>&lt;span id='$aspnet$crap$here$position_title'&gt;Manager&lt;/span&gt;</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) va...
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='&hellip;'`, or sometimes just `class='&hellip;'`, 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> &lt;query name="Activity.GetAllMiles"&gt; &lt;![CDATA[ select sum(Distance) from Activity ]]&gt; &lt;/query&gt; </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&lt;decimal&gt;(); } } </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 = GetS...
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, COALESC...
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 ...
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,BufNewF...
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 &amp; 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>...
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>...
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: ![freq = max_frequency * APERF / MPERF](https://chart.apis.google.com/chart?cht=tx&chl=%5CLARGE%5C%21freq%20%3D%20%5Cfrac%7Bmax%20frequency%20%5Ccdot%20APERF%7D%7BMPERF%7D) 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 &amp; 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 ...
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...
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 &quot;param = &quot; . $param . &quot;\n&quot;; 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]=&gt; string(8) &quot;test.php&quot; [1]=&gt; string(10) &quot;param=test&quot; } </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 t...
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 th...
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 &lt; myArray[this.value].length; i++) { options += '&lt;option value="' + myArray[this.value][i] + '"&gt;' + myArray[this.value][i] + '&lt;/option&gt;'; } $("#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, ...
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, ...
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 ...
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>&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; 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>&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re.compile(".*") &gt;&gt;&gt; marshal.dumps(x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; 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...
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>&lt;web service name&gt;</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?<...
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&lt;T&gt;(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=\...
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) co...
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 &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.foobar() bar &gt;&gt;&gt; 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>&gt;&gt;&gt; class Foo():\n... def __init__(self, ...
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...
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 ...
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.<...
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\" e...
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'. ---&gt; System.InvalidOperationException: There is an error in XML document (1, 9201). ---&gt; 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\">J...
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=\"...
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. > > >