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
65,491
<p>When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?</p>
[ { "answer_id": 65503, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://developer.yahoo.net/blog/archives/2007/07/high_performanc_8.html\" rel=\"nofollow noreferrer\">Minify</a>...
2008/09/15
[ "https://Stackoverflow.com/questions/65491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?
In addition to using server side compression, using intelligent coding is the best way to keep bandwidth costs low. You can always use tools like [Dean Edward's Javascript Packer](http://dean.edwards.name/download/#packer), but for CSS, take the time to learn [CSS Shorthand](http://www.webcredible.co.uk/user-friendly-resources/css/css-shorthand-properties.shtml "CSS Shorthand Examples"). E.g. use: ```css background: #fff url(image.gif) no-repeat top left; ``` ...instead of: ```css background-color: #fff; background-image: url(image.gif); background-repeat: no-repeat; background-position: top left; ``` Also, use the cascading nature of CSS. For example, if you know that your site will use one font-family, define that for all elements that are in the body tag like this: ```css body{font-family:arial;} ``` One other thing that can help is including your CSS and JavaScript as files instead of inline or at the head of each page. That way your server only has to serve them once to the browser after that browser will go from cache. ### Including Javascript ``` <script type="text/javascript" src="/scripts/loginChecker.js"></script> ``` ### Including CSS ``` <link rel="stylesheet" href="/css/myStyle.css" type="text/css" media="All" /> ```
65,512
<p>I've heard that <code>SELECT *</code> is generally bad practice to use when writing SQL commands because it is more efficient to <code>SELECT</code> columns you specifically need.</p> <p>If I need to <code>SELECT</code> every column in a table, should I use </p> <pre><code>SELECT * FROM TABLE </code></pre> <p>or </p> <pre><code>SELECT column1, colum2, column3, etc. FROM TABLE </code></pre> <p>Does the efficiency really matter in this case? I'd think <code>SELECT *</code> would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database.</p> <p>I'm curious to know what the best practice is in this case.</p> <p><strong>UPDATE:</strong> I probably should specify that the only situation where I would really <em>want</em> to do a <code>SELECT *</code> is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. </p> <p>Given the responses I've seen however, this still seems like a bad idea and <code>SELECT *</code> should never be used for a lot more technical reasons that I ever though about.</p>
[ { "answer_id": 65518, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>definitely defining the columns, because SQL Server will not have to do a lookup on the columns to pull them. If you def...
2008/09/15
[ "https://Stackoverflow.com/questions/65512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I've heard that `SELECT *` is generally bad practice to use when writing SQL commands because it is more efficient to `SELECT` columns you specifically need. If I need to `SELECT` every column in a table, should I use ``` SELECT * FROM TABLE ``` or ``` SELECT column1, colum2, column3, etc. FROM TABLE ``` Does the efficiency really matter in this case? I'd think `SELECT *` would be more optimal internally if you really need all of the data, but I'm saying this with no real understanding of database. I'm curious to know what the best practice is in this case. **UPDATE:** I probably should specify that the only situation where I would really *want* to do a `SELECT *` is when I'm selecting data from one table where I know all columns will always need to be retrieved, even when new columns are added. Given the responses I've seen however, this still seems like a bad idea and `SELECT *` should never be used for a lot more technical reasons that I ever though about.
One reason that selecting specific columns is better is that it raises the probability that SQL Server can access the data from indexes rather than querying the table data. Here's a post I wrote about it: [**The real reason select queries are bad index coverage**](http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx) It's also less fragile to change, since any code that consumes the data will be getting the same data structure regardless of changes you make to the table schema in the future.
65,524
<p>What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease. </p> <p>There are a lot of great answers here, I will be trying them all tonight to see what fits my problem the best. A few more words on what I'm doing. </p> <p>The graph is a collection of samples from an audio file. I use the graph as a Markov Chain to generate a new audio file from the old file. Since each vertex stores a few samples and points to another sample, and the samples are all short ints, it seemed natural to generate an ID from the data. Combining them into a long long sounds good, but maybe something as simple as just a 0 1 2 3 <code>generateID</code> is all I need. not sure how much space is necessary to guarantee uniqueness, if each vertex stores 2 16 bit samples, there are 2^32 possible combinations correct? and so if each vertex stores 4 samples, there are 2^64 possible combinations? </p> <p>Library and platform specific solutions not really relevant to this question. I don't want anyone else who might compile my program to have to download additional libraries or change the code to suit their OS. </p>
[ { "answer_id": 65551, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "<p>Well the only way to guarantee the ID is unique, is to make have more id combinations than what your gettings ids from...
2008/09/15
[ "https://Stackoverflow.com/questions/65524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264/" ]
What is the best way to generate a Unique ID from two (or more) short ints in C++? I am trying to uniquely identify vertices in a graph. The vertices contain two to four short ints as data, and ideally the ID would be some kind of a hash of them. Prefer portability and uniqueness over speed or ease. There are a lot of great answers here, I will be trying them all tonight to see what fits my problem the best. A few more words on what I'm doing. The graph is a collection of samples from an audio file. I use the graph as a Markov Chain to generate a new audio file from the old file. Since each vertex stores a few samples and points to another sample, and the samples are all short ints, it seemed natural to generate an ID from the data. Combining them into a long long sounds good, but maybe something as simple as just a 0 1 2 3 `generateID` is all I need. not sure how much space is necessary to guarantee uniqueness, if each vertex stores 2 16 bit samples, there are 2^32 possible combinations correct? and so if each vertex stores 4 samples, there are 2^64 possible combinations? Library and platform specific solutions not really relevant to this question. I don't want anyone else who might compile my program to have to download additional libraries or change the code to suit their OS.
A simple solution is to use a 64 bit integer where the lower 16 bits is the first vertex coordinate, next 16 bits is the second, and so on. This will be unique for all your vertices, though not very compact. So here's some half-assed code to do this. Hopefully I got the casts right. ``` uint64_t generateId( uint16_t v1, uint16_t v2, uint16_t v3, uint16_t v4) { uint64_t id; id = v1 | (((uint64_t)v2) << 16) | (((uint64_t)v3) << 32) | (((uint64_t)v4) << 48); return id; } ``` Optionally this could be done with a union (great idea from Leon Timmermans, see comment). Very clean this way: ```cpp struct vertex { uint16_t v1; uint16_t v2; uint16_t v3; uint16_t v4; }; union vertexWithId { vertex v; uint64_t id; }; int main() { vertexWithId vWithId; // Setup your vertices vWithId.v.v1 = 2; vWithId.v.v2 = 5; // Your id is automatically setup for you! std::cout << "Id is " << vWithId.id << std::endl; return 0; } ```
65,530
<p>In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) </p> <p>I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.</p>
[ { "answer_id": 65656, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 3, "selected": true, "text": "<p>In Tomcat 6.0 it should be something like:</p>\n\n<pre><code>org.apache.catalina.ServerFactory.getServer().getServices \n<...
2008/09/15
[ "https://Stackoverflow.com/questions/65530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.
In Tomcat 6.0 it should be something like: ``` org.apache.catalina.ServerFactory.getServer().getServices ``` to get the services. After that you might use ``` Service.findConnectors ``` which returns a Connector which finally has the method ``` Connector.getPort ``` See the [JavaDocs](http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/Connector.html) for the details.
65,536
<p>How would I get the <code>here</code> and <code>and here</code> to be on the right, on the same lines as the lorem ipsums? See the following:</p> <pre class="lang-none prettyprint-override"><code>Lorem Ipsum etc........here blah....................... blah blah.................. blah....................... lorem ipsums.......and here </code></pre>
[ { "answer_id": 65572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The first line would consist of 3 <code>&lt;div&gt;</code>s. One outer that contains two inner <code>&lt;div&gt;</code>s. Th...
2008/09/15
[ "https://Stackoverflow.com/questions/65536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
How would I get the `here` and `and here` to be on the right, on the same lines as the lorem ipsums? See the following: ```none Lorem Ipsum etc........here blah....................... blah blah.................. blah....................... lorem ipsums.......and here ```
```html <div style="position: relative; width: 250px;"> <div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;"> here </div> <div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;"> and here </div> Lorem Ipsum etc <br /> blah <br /> blah blah <br /> blah <br /> lorem ipsums </div> ``` Gets you pretty close, although you may need to tweak the "top" and "bottom" values.
65,566
<p>I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)...</p> <pre><code>UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id </code></pre> <p>...it would cycle through the querystring keys thusly:</p> <pre><code>For Each Key As String In Request.QueryString.Keys Command.Parameters.AddWithValue("@" &amp; Key, Request.QueryString(Key)) Next </code></pre> <p>HOWEVER, I'm now running into a situation where, under certain circumstances, some of these variables may not be present in the querystring. If I don't pass along val2 in the querystring, I get an error: <code>System.Data.SqlClient.SqlException: Must declare the scalar value "@val2"</code>.</p> <p>Attempts to detect the missing value in the SQL statement...</p> <pre><code>IF @val2 IS NOT NULL UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id </code></pre> <p>... have failed.</p> <p>What's the best way to attack this? Must I parse the SQL block with RegEx, scanning for variable names not present in the querystring? Or, is there a more elegant way to approach?</p> <p>UPDATE: Detecting null values in the VB codebehind defeats the purpose of decoupling the code from its context. I'd rather not litter my function with conditions for every conceivable variable that might be passed, or not passed.</p>
[ { "answer_id": 65629, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 3, "selected": false, "text": "<p>First of all, I would suggest against adding all entries on the querystring as parameter names, I'm not sure this is...
2008/09/15
[ "https://Stackoverflow.com/questions/65566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923/" ]
I have a control that, upon postback, saves form results back to the database. It populates the values to be saved by iterating through the querystring. So, for the following SQL statement (vastly simplified for the sake of discussion)... ``` UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id ``` ...it would cycle through the querystring keys thusly: ``` For Each Key As String In Request.QueryString.Keys Command.Parameters.AddWithValue("@" & Key, Request.QueryString(Key)) Next ``` HOWEVER, I'm now running into a situation where, under certain circumstances, some of these variables may not be present in the querystring. If I don't pass along val2 in the querystring, I get an error: `System.Data.SqlClient.SqlException: Must declare the scalar value "@val2"`. Attempts to detect the missing value in the SQL statement... ``` IF @val2 IS NOT NULL UPDATE MyTable SET MyVal1 = @val1, MyVal2 = @val2 WHERE @id = @id ``` ... have failed. What's the best way to attack this? Must I parse the SQL block with RegEx, scanning for variable names not present in the querystring? Or, is there a more elegant way to approach? UPDATE: Detecting null values in the VB codebehind defeats the purpose of decoupling the code from its context. I'd rather not litter my function with conditions for every conceivable variable that might be passed, or not passed.
After struggling to find a simpler solution, I gave up and wrote a routine to parse my SQL query for variable names: ``` Dim FieldRegEx As New Regex("@([A-Z_]+)", RegexOptions.IgnoreCase) Dim Fields As Match = FieldRegEx.Match(Query) Dim Processed As New ArrayList While Fields.Success Dim Key As String = Fields.Groups(1).Value Dim Val As Object = Request.QueryString(Key) If Val = "" Then Val = DBNull.Value If Not Processed.Contains(Key) Then Command.Parameters.AddWithValue("@" & Key, Val) Processed.Add(Key) End If Fields = Fields.NextMatch() End While ``` It's a bit of a hack, but it allows me to keep my code blissfully ignorant of the context of my SQL query.
65,607
<p>I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons. I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not. My idea of how this would be defined would be</p> <pre><code>(defmacro ++ (variable) (incf variable)) </code></pre> <p>but this gives me a SIMPLE-TYPE-ERROR when trying to use it. What would make it work?</p>
[ { "answer_id": 65641, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": true, "text": "<p>Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:</p>\n\n<pre><cod...
2008/09/15
[ "https://Stackoverflow.com/questions/65607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons. I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not. My idea of how this would be defined would be ``` (defmacro ++ (variable) (incf variable)) ``` but this gives me a SIMPLE-TYPE-ERROR when trying to use it. What would make it work?
Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote: ``` (defmacro ++ (variable) `(incf ,variable)) ```
65,627
<p>In a Flex <code>AdvancedDatGrid</code>, we're doing a lot of grouping. Most of the columns are the same for the parents and for the children, so I'd like to show the first value of the group as the summary rather than the MAX, MIN or AVG</p> <p>This code works on numerical but not textual values (without the commented line you get NaN's):</p> <pre><code>private function firstValue(itr:IViewCursor,field:String, str:String=null):Object { //if(isNaN(itr.current[field])) return 0 //Theory: Only works on Numeric Values? return itr.current[field] } </code></pre> <p>The XML:</p> <pre><code>(mx:GroupingField name="Offer") (mx:summaries) (mx:SummaryRow summaryPlacement="group") (mx:fields) (mx:SummaryField dataField="OfferDescription" label="OfferDescription" summaryFunction="firstValue"/) (mx:SummaryField dataField="OfferID" label="OfferID" summaryFunction="firstValue"/) (/mx:fields) (/mx:SummaryRow) (/mx:summaries) (/mx:GroupingField) </code></pre> <p><code>OfferID</code>'s work Correctly, <code>OfferDescription</code>s don't.</p>
[ { "answer_id": 69156, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 2, "selected": true, "text": "<p>It looks like the summaryFunction has to return a number. According to the <a href=\"https://bugs.adobe.com/jira/br...
2008/09/15
[ "https://Stackoverflow.com/questions/65627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9056/" ]
In a Flex `AdvancedDatGrid`, we're doing a lot of grouping. Most of the columns are the same for the parents and for the children, so I'd like to show the first value of the group as the summary rather than the MAX, MIN or AVG This code works on numerical but not textual values (without the commented line you get NaN's): ``` private function firstValue(itr:IViewCursor,field:String, str:String=null):Object { //if(isNaN(itr.current[field])) return 0 //Theory: Only works on Numeric Values? return itr.current[field] } ``` The XML: ``` (mx:GroupingField name="Offer") (mx:summaries) (mx:SummaryRow summaryPlacement="group") (mx:fields) (mx:SummaryField dataField="OfferDescription" label="OfferDescription" summaryFunction="firstValue"/) (mx:SummaryField dataField="OfferID" label="OfferID" summaryFunction="firstValue"/) (/mx:fields) (/mx:SummaryRow) (/mx:summaries) (/mx:GroupingField) ``` `OfferID`'s work Correctly, `OfferDescription`s don't.
It looks like the summaryFunction has to return a number. According to the [Adobe bug tracker](https://bugs.adobe.com/jira/browse/FLEXDOCS-431), it is a bug in the documentation: > > Comment from Sameer Bhatt: > > > In the documentation it is mentioned that - > The built-in summary functions for SUM, MIN, MAX, AVG, and COUNT all return a Number containing the summary data. > > > So people can get an idea but I agree with you that we should clearly mention that the return type should be a Number. > > > We kept it as an Object so that it'll be easy in the future to add more things in it. > > >
65,651
<p>I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this -</p> <pre><code>/src MyClass.java /test MyClassTest.java </code></pre> <p>and so on.</p> <p>When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.</p>
[ { "answer_id": 65754, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 2, "selected": false, "text": "<p>You need to modify PHP's include_path so that it knows where to find MyClass.php when you <code>include()</code> it...
2008/09/15
[ "https://Stackoverflow.com/questions/65651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8770/" ]
I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this - ``` /src MyClass.java /test MyClassTest.java ``` and so on. When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.
I think it's a good idea to keep your files separate. I normally use a folder structure like this: ``` /myapp/src/ <- my classes /myapp/tests/ <- my tests for the classes /myapp/public/ <- document root ``` In your case, for including the class in your test file, why not just pass the the whole path to the include method? ``` include('/path/to/myapp/src/MyClass.php'); ``` or ``` include('../src/MyClass.php'); ```
65,668
<p>Someone told me it's more efficient to use <code>StringBuffer</code> to concatenate strings in Java than to use the <code>+</code> operator for <code>String</code>s. What happens under the hood when you do that? What does <code>StringBuffer</code> do differently?</p>
[ { "answer_id": 65677, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 4, "selected": false, "text": "<p>One shouldn't be faster than the other. This wasn't true before Java 1.4.2, because when concatenating more than tw...
2008/09/15
[ "https://Stackoverflow.com/questions/65668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Someone told me it's more efficient to use `StringBuffer` to concatenate strings in Java than to use the `+` operator for `String`s. What happens under the hood when you do that? What does `StringBuffer` do differently?
It's better to use StringBuilder (it's an unsynchronized version; when do you build strings in parallel?) these days, in almost every case, but here's what happens: When you use + with two strings, it compiles code like this: ``` String third = first + second; ``` To something like this: ``` StringBuilder builder = new StringBuilder( first ); builder.append( second ); third = builder.toString(); ``` Therefore for just little examples, it usually doesn't make a difference. But when you're building a complex string, you've often got a lot more to deal with than this; for example, you might be using many different appending statements, or a loop like this: ``` for( String str : strings ) { out += str; } ``` In this case, a new `StringBuilder` instance, and a new `String` (the new value of `out` - `String`s are immutable) is required in each iteration. This is very wasteful. Replacing this with a single `StringBuilder` means you can just produce a single `String` and not fill up the heap with `String`s you don't care about.
65,683
<p>I would like to know how to write PHPUnit tests with Zend_Test and in general with PHP.</p>
[ { "answer_id": 66008, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 0, "selected": false, "text": "<p>I haven't used Zend_Test but I have written tests against apps using Zend_MVC and the like. The biggest part is gettin...
2008/09/15
[ "https://Stackoverflow.com/questions/65683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to know how to write PHPUnit tests with Zend\_Test and in general with PHP.
I'm using Zend\_Test to completely test all controllers. It's quite simple to set up, as you only have to set up your bootstrap file (the bootstrap file itself should NOT dispatch the front controller!). My base test-case class looks like this: ``` abstract class Controller_TestCase extends Zend_Test_PHPUnit_ControllerTestCase { protected function setUp() { $this->bootstrap=array($this, 'appBootstrap'); Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_NonPersistent()); parent::setUp(); } protected function tearDown() { Zend_Auth::getInstance()->clearIdentity(); } protected function appBootstrap() { Application::setup(); } } ``` where `Application::setup();` does all the setup up tasks which also set up the real application. A simple test then would look like this: ``` class Controller_IndexControllerTest extends Controller_TestCase { public function testShowist() { $this->dispatch('/'); $this->assertController('index'); $this->assertAction('list'); $this->assertQueryContentContains('ul li a', 'Test String'); } } ``` That's all...
65,724
<p>As everyone knows, the <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B" rel="nofollow noreferrer">Visual C++</a> runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since <code>0xFEEEFEEE != 0</code>.</p> <p>Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to <code>0xFEEEFEEE</code> instead of <code>NULL</code>. When I insert a proper check for <code>NULL</code>, as all good programs that manage their own memory should, I come up with problems as <code>0xFEEEFEEE</code> passes a <code>NULL</code> check without problems. Is there any good way, other than manually setting all pointers to <code>NULL</code> when deleting them, to detect when memory has already been freed? I would prefer to not use <a href="http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries" rel="nofollow noreferrer">Boost</a> simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.</p>
[ { "answer_id": 65760, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "<p>When you create a pointer, explicity initialize it to <code>NULL</code>. Likewise after a <code>delete</code>. Depending o...
2008/09/15
[ "https://Stackoverflow.com/questions/65724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8844/" ]
As everyone knows, the [Visual C++](http://en.wikipedia.org/wiki/Visual_C%2B%2B) runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since `0xFEEEFEEE != 0`. Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to `0xFEEEFEEE` instead of `NULL`. When I insert a proper check for `NULL`, as all good programs that manage their own memory should, I come up with problems as `0xFEEEFEEE` passes a `NULL` check without problems. Is there any good way, other than manually setting all pointers to `NULL` when deleting them, to detect when memory has already been freed? I would prefer to not use [Boost](http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries) simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.
It is not the responsibility of `delete` to reset all the pointers to the object to `NULL`. Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like `boost::shared_ptr<>` for pointers any way. That said, if you really want to **shoot your self in the foot** you can. You can **change** the **default fill** for the windows **DEBUG runtime** by using an allocator hook like this. This will only work on HEAP allocated object! ``` int main(int argc,char** arv) { // Call first to register hook _CrtSetAllocHook(&zero_fill); // Do other stuff malloc(100); } int zero_fill(int nAllocType, void* pvData, size_t nSize, int nBlockUse, long lRequest, const unsigned char *szFileName, int nLine ) { /// Very Importaint !! /// infinite recursion if this is removed !! /// _CRT_BLOCK must not do any thing but return TRUE /// even calling printf in the _CRT_BLOCK will cause /// infinite recursion if ( nBlockUse == _CRT_BLOCK ) return( TRUE ); switch(nAllocType) { case _HOOK_ALLOC: case _HOOK_REALLOC: // zero initialize the allocated space. memset(pvData,0,nSize); break; case _HOOK_FREE: break; } return TRUE; } ```
65,849
<p>I'm writing a web service, and I want to return the data as XHTML. Because it's data, not markup, I want to keep it very clean - no extra <code>&lt;div&gt;</code>s or <code>&lt;span&gt;</code>s. However, as a convenience to developers, I'd also like to make the returned data reasonably readable in a browser. To do so, I'm thinking a good way to go about it would be to use CSS. </p> <p>The thing I specifically want to do is to insert linebreaks at certain places. I'm aware of <code>display: block</code>, but it doesn't really work in the situation I'm trying to handle now - a <code>form</code> with <code>&lt;input&gt;</code> fields. Something like this: </p> <pre><code>&lt;form&gt; Thingy 1: &lt;input class="a" type="text" name="one" /&gt; Thingy 2: &lt;input class="a" type="text" name="two" /&gt; Thingy 3: &lt;input class="b" type="checkbox" name="three" /&gt; Thingy 4: &lt;input class="b" type="checkbox" name="four" /&gt; &lt;/form&gt; </code></pre> <p>I'd like it to render so that each label displays on the same line as the corresponding input field. I've tried this: </p> <pre class="lang-css prettyprint-override"><code>input.a:after { content: "\a" } </code></pre> <p>But that didn't seem to do anything. </p>
[ { "answer_id": 65871, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 2, "selected": false, "text": "<p>One option is to specify a XSLT template within your XML that (some) browsers will process allowing you to include present...
2008/09/15
[ "https://Stackoverflow.com/questions/65849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a web service, and I want to return the data as XHTML. Because it's data, not markup, I want to keep it very clean - no extra `<div>`s or `<span>`s. However, as a convenience to developers, I'd also like to make the returned data reasonably readable in a browser. To do so, I'm thinking a good way to go about it would be to use CSS. The thing I specifically want to do is to insert linebreaks at certain places. I'm aware of `display: block`, but it doesn't really work in the situation I'm trying to handle now - a `form` with `<input>` fields. Something like this: ``` <form> Thingy 1: <input class="a" type="text" name="one" /> Thingy 2: <input class="a" type="text" name="two" /> Thingy 3: <input class="b" type="checkbox" name="three" /> Thingy 4: <input class="b" type="checkbox" name="four" /> </form> ``` I'd like it to render so that each label displays on the same line as the corresponding input field. I've tried this: ```css input.a:after { content: "\a" } ``` But that didn't seem to do anything.
It'd be best to wrap all of your elements in label elements, then apply css to the labels. The :before and :after pseudo classes are not completely supported in a consistent way. Label tags have a lot of advantages including increased accessibility (on multiple levels) and more. ``` <label> Thingy one: <input type="text" name="one">; </label> ``` then use CSS on your label elements... ```css label {display:block;clear:both;} ```
65,925
<p>From time to time am I working in a completely disconnected environment with a Macbook Pro. For testing purposes I need to run a local DNS server in a VMWare session. I've configured the lookup system to use the DNS server (/etc/resolve.conf and through the network configuration panel, which is using configd underneath), and commands like "dig" and "nslookup" work. For example, my DNS server is configured to resolve www.example.com to 127.0.0.1, this is the output of "dig www.example.com":</p> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.3.5-P1 &lt;&lt;&gt;&gt; www.example.com ;; global options: printcmd ;; Got answer: ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 64859 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 86400 IN A 127.0.0.1 ;; Query time: 2 msec ;; SERVER: 172.16.35.131#53(172.16.35.131) ;; WHEN: Mon Sep 15 21:13:15 2008 ;; MSG SIZE rcvd: 49 </code></pre> <p>Unfortunately, if I try to ping or setup a connection in a browser, the DNS name is not resolved. This is the output of "ping www.example.com":</p> <pre><code>ping: cannot resolve www.example.com: Unknown host </code></pre> <p>It seems that those tools, that are more integrated within Mac OS X 10.4 (and up), are not using the "/etc/resolv.conf" system anymore. Configuring them through scutil is no help, because it seems that if the wireless or the buildin ethernet interface is <strong>inactive</strong>, basic network functions don't seem to work.</p> <p>In Linux (for example Ubuntu), it is possible to turn off the wireless adapter, without turning of the network capabilities. So in Linux it seems that I can work completely disconnected.</p> <p>A solution could be using an ethernet loopback connector, but I would rather like a software solution, as both Windows and Linux don't have this problem.</p>
[ { "answer_id": 66629, "author": "Mark Regensberg", "author_id": 6735, "author_profile": "https://Stackoverflow.com/users/6735", "pm_score": 0, "selected": false, "text": "<p>I run into this from time to time on different notebooks, and I have found the simplest is a low-tech, non softwar...
2008/09/15
[ "https://Stackoverflow.com/questions/65925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9504/" ]
From time to time am I working in a completely disconnected environment with a Macbook Pro. For testing purposes I need to run a local DNS server in a VMWare session. I've configured the lookup system to use the DNS server (/etc/resolve.conf and through the network configuration panel, which is using configd underneath), and commands like "dig" and "nslookup" work. For example, my DNS server is configured to resolve www.example.com to 127.0.0.1, this is the output of "dig www.example.com": ``` ; <<>> DiG 9.3.5-P1 <<>> www.example.com ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 64859 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;www.example.com. IN A ;; ANSWER SECTION: www.example.com. 86400 IN A 127.0.0.1 ;; Query time: 2 msec ;; SERVER: 172.16.35.131#53(172.16.35.131) ;; WHEN: Mon Sep 15 21:13:15 2008 ;; MSG SIZE rcvd: 49 ``` Unfortunately, if I try to ping or setup a connection in a browser, the DNS name is not resolved. This is the output of "ping www.example.com": ``` ping: cannot resolve www.example.com: Unknown host ``` It seems that those tools, that are more integrated within Mac OS X 10.4 (and up), are not using the "/etc/resolv.conf" system anymore. Configuring them through scutil is no help, because it seems that if the wireless or the buildin ethernet interface is **inactive**, basic network functions don't seem to work. In Linux (for example Ubuntu), it is possible to turn off the wireless adapter, without turning of the network capabilities. So in Linux it seems that I can work completely disconnected. A solution could be using an ethernet loopback connector, but I would rather like a software solution, as both Windows and Linux don't have this problem.
On OS X starting in 10.4, `/etc/resolv.conf` is no longer the canonical location for DNS IP addresses. Some Unix tools such as `dig` and `nslookup` will use it directly, but anything that uses Unix or Mac APIs to do DNS lookups will not. Instead, configd maintains a database which provides many more options, like using different nameservers for different domains. (A subset of this information is mirrored to `/etc/resolv.conf` for compatibility.) You can edit the nameserver info from code with `SCDynamicStore`, or use `scutil` interactively or from a script. I posted some links to sample scripts for both methods [here](http://njr.sabi.net/2005/11/07/alternate-openvpn-os-x-dns-updating-script/). [This thread](http://lists.apple.com/archives/Macnetworkprog/2005/Jun/msg00011.html) from when I was trying to figure this stuff out may also be of some use.
65,926
<p>When using a browser to transform XML (Google Chrome or IE7) is it possible to pass a parameter to the XSLT stylesheet through the URL?</p> <p>example:</p> <p><strong>data.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="sample.xsl"?&gt; &lt;root&gt; &lt;document type="resume"&gt; &lt;author&gt;John Doe&lt;/author&gt; &lt;/document&gt; &lt;document type="novella"&gt; &lt;author&gt;Jane Doe&lt;/author&gt; &lt;/document&gt; &lt;/root&gt; </code></pre> <p><strong>sample.xsl</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"&gt; &lt;xsl:output method="html" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:param name="doctype" /&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;List of &lt;xsl:value-of select="$doctype" /&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;xsl:for-each select="//document[@type = $doctype]"&gt; &lt;p&gt;&lt;xsl:value-of select="author" /&gt;&lt;/p&gt; &lt;/xsl:for-each&gt; &lt;/body&gt; &lt;/html&gt; &lt;/&lt;xsl:stylesheet&gt; </code></pre>
[ { "answer_id": 66017, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 3, "selected": true, "text": "<p>You can generate the XSLT server-side, even if the transformation is client-side.</p>\n\n<p>This allows you to use a...
2008/09/15
[ "https://Stackoverflow.com/questions/65926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9547/" ]
When using a browser to transform XML (Google Chrome or IE7) is it possible to pass a parameter to the XSLT stylesheet through the URL? example: **data.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="sample.xsl"?> <root> <document type="resume"> <author>John Doe</author> </document> <document type="novella"> <author>Jane Doe</author> </document> </root> ``` **sample.xsl** ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:output method="html" /> <xsl:template match="/"> <xsl:param name="doctype" /> <html> <head> <title>List of <xsl:value-of select="$doctype" /></title> </head> <body> <xsl:for-each select="//document[@type = $doctype]"> <p><xsl:value-of select="author" /></p> </xsl:for-each> </body> </html> </<xsl:stylesheet> ```
You can generate the XSLT server-side, even if the transformation is client-side. This allows you to use a dynamic script to handle the parameter. For example, you might specify: ``` <?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?> ``` And then in myscript.cfm you would output the XSL file, but with dynamic script handling the query string parameter (this would vary depending on which scripting language you use).
65,956
<p>Or vice versa.</p> <p>Update:<br> Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button. The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could <code>Button.PostBackURL = "Invoice.aspx"</code></p> <p>or I could do </p> <pre><code>Server.Transfer("Invoice.aspx") </code></pre> <p>(I also changed the title since the method is called Transfer and not TransferURL)</p>
[ { "answer_id": 65975, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 1, "selected": false, "text": "<p>Server.Transfer is done entirely from the server. Postback is initiated from the client for posting form contents and...
2008/09/15
[ "https://Stackoverflow.com/questions/65956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
Or vice versa. Update: Hmm, let's assume I have a shopping cart app, the user clicks on the Checkout button. The next thing I want to do is send the user to a Invoice.aspx page (or similar). When the user hits checkout, I could `Button.PostBackURL = "Invoice.aspx"` or I could do ``` Server.Transfer("Invoice.aspx") ``` (I also changed the title since the method is called Transfer and not TransferURL)
* Server.TransferURL will not result in a roundtrip of HTTP request/response. The address bar will not update, as far as the browser knows it has received only one document. Server.Transfer also retains execution context, so the script "keeps going" as opposed to "starts anew". * PostbackURL ensures an HTTP request, resulting in a possibly different URL and of course incurring network latency costs. Usually when you are attempting to "decide between the two" it means you are better off using PostbackURL. Feel free to expand your question with specifics and we can look at your precise needs.
65,994
<p>I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory.</p> <p>For Example, if the run directory looks like this:</p> <pre><code>. .. 1.2.1 1.2.2 1.3.0 run.sh current_version </code></pre> <p>And current_version contains:</p> <pre><code>1.2.2 </code></pre> <p>I want <code>run.sh</code> to descend into 1.2.2 and run the program <code>foo</code>.</p> <p>The current solution is this:</p> <pre><code>#!/bin/sh version = `cat current_version` cd $version ./foo </code></pre> <p>It works but is not very robust. It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc.</p> <p>What is the most survivable way to do this with either a shell or perl script?</p>
[ { "answer_id": 66055, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 3, "selected": false, "text": "<p>That's a common approach. You can check for dir/file existence using test operators such as \"if [ -d \"somedirectory\" ]...
2008/09/15
[ "https://Stackoverflow.com/questions/65994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7476/" ]
I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory. For Example, if the run directory looks like this: ``` . .. 1.2.1 1.2.2 1.3.0 run.sh current_version ``` And current\_version contains: ``` 1.2.2 ``` I want `run.sh` to descend into 1.2.2 and run the program `foo`. The current solution is this: ``` #!/bin/sh version = `cat current_version` cd $version ./foo ``` It works but is not very robust. It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc. What is the most survivable way to do this with either a shell or perl script?
That's a common approach. You can check for dir/file existence using test operators such as "if [ -d "somedirectory" ]; then" or [ -t "somefile" ] I use symbolic links more often, though. Then, you can just change your symbolic link to use the version you want. For example, ``` $ ln -s 1.2.2 current_version $ ls -al total 20 drwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 . drwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 .. drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1 drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2 drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0 lrwxrwxrwx 1 dbreese dbreese 6 2008-09-15 13:34 current_version -> 1.2.2/ ``` Then your script can just use "cd current\_version".
66,006
<p>Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it?</p> <p>Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).</p> <p><strong>Clarification:</strong> I do not mean HTML DOM scripting performed <em>after</em> the document is transformed, nor do I mean XSL transformations <em>initiated</em> by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.</p>
[ { "answer_id": 66050, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 1, "selected": false, "text": "<p>Yes. It's browser dependant but you can use Javascript. There is a small but practical tutorial on w3schools.com. It's part...
2008/09/15
[ "https://Stackoverflow.com/questions/66006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations? How is it done and how official is it? Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET). **Clarification:** I do not mean HTML DOM scripting performed *after* the document is transformed, nor do I mean XSL transformations *initiated* by JavaScript in the browser (e.g. what the W3Schools page shows). I am referring to actual script blocks located within the XSL during the transformation.
To embed JavaScript for the aid of transformation you can use <xsl:script>, but [it is limited](http://www.topxml.com/xsl/tutorials/intro/xsl10.asp) to Microsoft's XML objects implementation. Here's an [example](https://oxampleski.googlecode.com/svn/trunk/XSL): **scripted.xml**: ``` <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="scripted.xsl"?> <data a="v"> ding dong </data> ``` **scripted.xsl**: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <html xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl:script implements-prefix="local" language="JScript"><![CDATA[ function Title() { return "Scripted"; } function Body(text) { return "/" + text + "/"; } ]]></xsl:script> <head> <title><xsl:eval>Title()</xsl:eval></title> </head> <body> <xsl:for-each select="/data"><xsl:eval>Body(nodeTypedValue)</xsl:eval></xsl:for-each> </body> </html> ``` The result in Internet Explorer (or if you just use MSXML from COM/.NET) is: ``` <html> <head> <title>Scripted</titlte> </head> <body> /ding dong/ </body> </html> ``` It doesn't appear to support the usual XSL template constructs and adding the root node causes MSXML to go into some sort of standards mode where it won't work. I'm not sure if there's any equivalent functionality in standard XSL, but I can dream.
66,009
<p>I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.</p>
[ { "answer_id": 67644, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 5, "selected": true, "text": "<p>We are using an action filter for this. </p>\n\n<p>...</p>\n\n<pre><code> public override void OnActionExecuting(Acti...
2008/09/15
[ "https://Stackoverflow.com/questions/66009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.
We are using an action filter for this. ... ``` public override void OnActionExecuting(ActionExecutingContext filterContext) { var controller = (Controller) filterContext.Controller; Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText); controller.ViewData.Add(breadcrumbs); } ``` before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options. IBreadcrumbManager looks like this: ``` public interface IBreadcrumbManager { Breadcrumb[] PushBreadcrumb(string linkText); } ``` The implementation puts Breadcrumb objects into the Session. The Url is `HttpContext.Current.Request.RawUrl`
66,032
<p>The DOM method <code>getChildNodes()</code> returns a <code>NodeList</code> of the children of the current <code>Node</code>. Whilst a <code>NodeList</code> is ordered, is the list guaranteed to be in document order?</p> <p>For example, given <code>&lt;a&gt;&lt;b/&gt;&lt;c/&gt;&lt;d/&gt;&lt;/a&gt;</code> is <code>a.getChildNodes()</code> guaranteed to return a <code>NodeList</code> with <code>b</code>, <code>c</code> and <code>d</code> <em>in that order</em>?</p> <p>The <a href="http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()" rel="noreferrer">javadoc</a> isn't clear on this.</p>
[ { "answer_id": 66112, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>A document-ordered node list is the behavior in other implementations of the DOM, such as Javascript's or Python's. ...
2008/09/15
[ "https://Stackoverflow.com/questions/66032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332/" ]
The DOM method `getChildNodes()` returns a `NodeList` of the children of the current `Node`. Whilst a `NodeList` is ordered, is the list guaranteed to be in document order? For example, given `<a><b/><c/><d/></a>` is `a.getChildNodes()` guaranteed to return a `NodeList` with `b`, `c` and `d` *in that order*? The [javadoc](http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()) isn't clear on this.
In my experience, yes. The [DOM spec](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987) isn't any clearer. If you're paranoid, try something like ``` current = node.firstChild; while(null != current) { ... current = current.nextSibling; } ```
66,066
<p>I've seen examples like this: </p> <pre><code>public class MaxSeconds { public static final int MAX_SECONDS = 25; } </code></pre> <p>and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants. </p>
[ { "answer_id": 66076, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 10, "selected": true, "text": "<p>That is perfectly acceptable, probably even the standard.</p>\n\n<pre><code>(public/private) static final TYPE NAME = VALUE...
2008/09/15
[ "https://Stackoverflow.com/questions/66066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
I've seen examples like this: ``` public class MaxSeconds { public static final int MAX_SECONDS = 25; } ``` and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.
That is perfectly acceptable, probably even the standard. ``` (public/private) static final TYPE NAME = VALUE; ``` where `TYPE` is the type, `NAME` is the name in all caps with underscores for spaces, and `VALUE` is the constant value; I highly recommend NOT putting your constants in their own classes or interfaces. As a side note: Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object. For example: ``` public static final Point ORIGIN = new Point(0,0); public static void main(String[] args){ ORIGIN.x = 3; } ``` That is legal and `ORIGIN` would then be a point at (3, 0).
66,094
<p>Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?</p>
[ { "answer_id": 66119, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "<p>You cannot put more than one object/datasource on a datagrid. You will have to build a single ConceptObject that com...
2008/09/15
[ "https://Stackoverflow.com/questions/66094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9626/" ]
Have been trying out the new Dynamic Data site create tool that shipped with .NET 3.5. The tool uses LINQ Datasources to get the data from the database using a .dmbl context file for a reference. I am interseted in customizing a data grid but I need to show data from more than one table. Does anyone know how to do this using the LINQ Datasource object?
If the tables are connected by a foreign key, you can easily reference both tables as they will be joined by linq automatically (you can see easily if you look in your dbml and there is an arrow connecting the tables) - if not, see if you can add one. To do that, you can just use something like this: ``` <%# Bind("unit1.unit_name") %> ``` Where in the table, 'unit' has a foreign key that references another table and you pull that 'unit's property of 'unit\_name' I hope that makes sense.
66,107
<p>I need to get the number of digits containing the number 1. I know in java I can take the input as a <code>String</code> and use <code>charAt</code>, but I understand there is no implicit String function in C. How can I accomplish this?</p>
[ { "answer_id": 66122, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "<p>Division and modulus are your friends.</p>\n\n<pre><code>#include \"stdio.h\"\n\nint main(){\n int digits[] = {0,...
2008/09/15
[ "https://Stackoverflow.com/questions/66107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I need to get the number of digits containing the number 1. I know in java I can take the input as a `String` and use `charAt`, but I understand there is no implicit String function in C. How can I accomplish this?
Division and modulus are your friends. ``` #include "stdio.h" int main(){ int digits[] = {0,0,0,0,0,0,0,0,0,0}; int i = 11031; while(i > 0){ digits[i % 10]++; i = i / 10; } printf("There are %d ones.\n", digits[1]); } ```
66,164
<p>I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on <code>SQL Server 2005</code>. </p> <p>I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the <code>sysadmin</code> role on their login - it was a single line query for the latter.</p> <p>But how to find out which logins have a User Mapping to a particular (or any) database? </p> <p>I can find the <code>sys.database_principals</code> and <code>sys.server_principals</code> tables. I have located the <code>sys.databases table</code>. I haven't worked out how to find out which users have rights on a database, and if so, what. </p> <p>Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?</p>
[ { "answer_id": 66349, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 1, "selected": false, "text": "<pre><code>\nselect * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid\n</code></pre>\n\n<p>This w...
2008/09/15
[ "https://Stackoverflow.com/questions/66164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9727/" ]
I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on `SQL Server 2005`. I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the `sysadmin` role on their login - it was a single line query for the latter. But how to find out which logins have a User Mapping to a particular (or any) database? I can find the `sys.database_principals` and `sys.server_principals` tables. I have located the `sys.databases table`. I haven't worked out how to find out which users have rights on a database, and if so, what. Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?
Here's how to do this. I ended up finding reference to a sproc in the MSDN docs. I pulled this from the sproc and wrapped it in a loop of all the databases known to the instance. ``` select DbRole = g.name, MemberName = u.name from @NAME.sys.database_principals u, @NAME.sys.database_principals g, @NAME.sys.database_role_members m where g.principal_id = m.role_principal_id and u.principal_id = m.member_principal_id and g.name in (''db_ddladmin'', ''db_owner'', ''db_securityadmin'') and u.name not in (''dbo'') order by 1, 2 ``` This then reports the users that have DBO who perhaps shouldn't. I've already revoked some admin access from some users that they didn't need. Thanks everyone!
66,293
<p>I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.</p> <p>What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?</p>
[ { "answer_id": 67007, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 0, "selected": false, "text": "<p>In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at...
2008/09/15
[ "https://Stackoverflow.com/questions/66293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5626/" ]
I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart. What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?
We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following: ``` Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width Me.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height Dim loc As New Point loc.X = Me.PictureBoxIcon.Location.X loc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height Me.PictureBoxAbout.Location = loc Me.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width Me.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height ``` Hope this helps someone else!
66,363
<p>I need to find out the <strong>external</strong> IP of the computer a C# application is running on. </p> <p>In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?</p> <p><em>(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)</em></p> <p><strong>Solution:</strong><br> I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.</p> <pre><code>public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } </code></pre> <p>And then later (when I get a request from a client) just get the IP from the CallContext like this.</p> <pre><code>public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } </code></pre> <p>I can now send the IP back to the client.</p>
[ { "answer_id": 66393, "author": "Matt Michielsen", "author_id": 9769, "author_profile": "https://Stackoverflow.com/users/9769", "pm_score": -1, "selected": false, "text": "<p>You can basically parse the page returned by doing a WebRequest of <a href=\"http://whatismyipaddress.com\" rel=\...
2008/09/15
[ "https://Stackoverflow.com/questions/66363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936/" ]
I need to find out the **external** IP of the computer a C# application is running on. In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side? *(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)* **Solution:** I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext. ``` public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } ``` And then later (when I get a request from a client) just get the IP from the CallContext like this. ``` public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } ``` I can now send the IP back to the client.
I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext. ``` public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } ``` And then later (when I get a request from a client) just get the IP from the CallContext like this. ``` public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } ``` I can now send the IP back to the client.
66,382
<p>In the ContainsIngredients method in the following code, is it possible to cache the <em>p.Ingredients</em> value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside <em>p</em> eg. <em>p.InnerObject.ExpensiveMethod().Value</em></p> <p>edit: I'm using the PredicateBuilder from <a href="http://www.albahari.com/nutshell/predicatebuilder.html" rel="nofollow noreferrer">http://www.albahari.com/nutshell/predicatebuilder.html</a></p> <pre><code>public class IngredientBag { private readonly Dictionary&lt;string, string&gt; _ingredients = new Dictionary&lt;string, string&gt;(); public void Add(string type, string name) { _ingredients.Add(type, name); } public string Get(string type) { return _ingredients[type]; } public bool Contains(string type) { return _ingredients.ContainsKey(type); } } public class Potion { public IngredientBag Ingredients { get; private set;} public string Name {get; private set;} public Potion(string name) : this(name, null) { } public Potion(string name, IngredientBag ingredients) { Name = name; Ingredients = ingredients; } public static Expression&lt;Func&lt;Potion, bool&gt;&gt; ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False&lt;Potion&gt;(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or ( p =&gt; p.Ingredients != null &amp;&amp; p.Ingredients.Contains(ingredientType) &amp;&amp; p.Ingredients.Get(ingredientType).Contains(temp)); } return predicate; } } [STAThread] static void Main() { var potions = new List&lt;Potion&gt; { new Potion("Invisibility", new IngredientBag()), new Potion("Bonus"), new Potion("Speed", new IngredientBag()), new Potion("Strength", new IngredientBag()), new Potion("Dummy Potion") }; potions[0].Ingredients.Add("solid", "Eye of Newt"); potions[0].Ingredients.Add("liquid", "Gall of Peacock"); potions[0].Ingredients.Add("gas", "Breath of Spider"); potions[2].Ingredients.Add("solid", "Hair of Toad"); potions[2].Ingredients.Add("gas", "Peacock's anguish"); potions[3].Ingredients.Add("liquid", "Peacock Sweat"); potions[3].Ingredients.Add("gas", "Newt's aura"); var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad") .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion")); foreach (var result in from p in potions where(predicate).Compile()(p) select p) { Console.WriteLine(result.Name); } } </code></pre>
[ { "answer_id": 66710, "author": "Fake Jim", "author_id": 6199, "author_profile": "https://Stackoverflow.com/users/6199", "pm_score": 3, "selected": true, "text": "<p>Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.I...
2008/09/15
[ "https://Stackoverflow.com/questions/66382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
In the ContainsIngredients method in the following code, is it possible to cache the *p.Ingredients* value instead of explicitly referencing it several times? This is a fairly trivial example that I just cooked up for illustrative purposes, but the code I'm working on references values deep inside *p* eg. *p.InnerObject.ExpensiveMethod().Value* edit: I'm using the PredicateBuilder from <http://www.albahari.com/nutshell/predicatebuilder.html> ``` public class IngredientBag { private readonly Dictionary<string, string> _ingredients = new Dictionary<string, string>(); public void Add(string type, string name) { _ingredients.Add(type, name); } public string Get(string type) { return _ingredients[type]; } public bool Contains(string type) { return _ingredients.ContainsKey(type); } } public class Potion { public IngredientBag Ingredients { get; private set;} public string Name {get; private set;} public Potion(string name) : this(name, null) { } public Potion(string name, IngredientBag ingredients) { Name = name; Ingredients = ingredients; } public static Expression<Func<Potion, bool>> ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False<Potion>(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or ( p => p.Ingredients != null && p.Ingredients.Contains(ingredientType) && p.Ingredients.Get(ingredientType).Contains(temp)); } return predicate; } } [STAThread] static void Main() { var potions = new List<Potion> { new Potion("Invisibility", new IngredientBag()), new Potion("Bonus"), new Potion("Speed", new IngredientBag()), new Potion("Strength", new IngredientBag()), new Potion("Dummy Potion") }; potions[0].Ingredients.Add("solid", "Eye of Newt"); potions[0].Ingredients.Add("liquid", "Gall of Peacock"); potions[0].Ingredients.Add("gas", "Breath of Spider"); potions[2].Ingredients.Add("solid", "Hair of Toad"); potions[2].Ingredients.Add("gas", "Peacock's anguish"); potions[3].Ingredients.Add("liquid", "Peacock Sweat"); potions[3].Ingredients.Add("gas", "Newt's aura"); var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad") .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion")); foreach (var result in from p in potions where(predicate).Compile()(p) select p) { Console.WriteLine(result.Name); } } ```
Can't you simply write your boolean expression in a separate static function which you call from your lambda - passing p.Ingredients as a parameter... ``` private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient) { return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient); } public static Expression<Func<Potion, bool>> ContainsIngredients(string ingredientType, params string[] ingredients) { var predicate = PredicateBuilder.False<Potion>(); // Here, I'm accessing p.Ingredients several times in one // expression. Is there any way to cache this value and // reference the cached value in the expression? foreach (var ingredient in ingredients) { var temp = ingredient; predicate = predicate.Or( p => IsIngredientPresent(p.Ingredients, ingredientType, temp)); } return predicate; } ```
66,422
<p>I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?</p>
[ { "answer_id": 66449, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 0, "selected": false, "text": "<p>If you are running a linux system you can set a <a href=\"http://www.sitepoint.com/article/introducing-cron/\" rel=\"no...
2008/09/15
[ "https://Stackoverflow.com/questions/66422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9750/" ]
I need to rotate an image at 12 midnight every day from a group of 5-10 images. How can I go about doing this with JavaScript or jQuery or even PHP?
At a basic level what you want to do is define an array of image names then take the number of days from a given point in time then modulo (remainder after division) by the number of images and access that index in the array and set the image, e.g. (untested code) ``` var images = new Array("image1.gif", "image2.jpg", "sky.jpg", "city.png"); var dateDiff = new Date() - new Date(2008,01,01); var imageIndex = Math.Round(dateDiff/1000/60/60/24) % images.length; document.GetElementById('imageId').setAttribute('src', images[imageIndex]); ``` Bear in mind that any client-side solution will be using the date and time of the client so if your definition of midnight means in your timezone then you'll need to do something similar on your server in PHP.
66,438
<p>I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects. For example, the game menu is a Canvas object, and the actual game is a Canvas object too. I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.</p> <p>Is there anyway to avoid this?</p>
[ { "answer_id": 66742, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<p>Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (I...
2008/09/15
[ "https://Stackoverflow.com/questions/66438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771/" ]
I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects. For example, the game menu is a Canvas object, and the actual game is a Canvas object too. I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas. Is there anyway to avoid this?
I would say, that using multiple canvases is generally bad design. On some phones it will even crash. The best way would really be using one canvas with tracking state of the application. And then in paint method you would have ``` protected void paint(final Graphics g) { if(menu) { paintMenu(g); } else if (game) { paintGame(g); } } ``` There are better ways to handle application state with screen objects, that would make the design cleaner, but I think you got the idea :) /JaanusSiim
66,455
<p>For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents.</p> <p>Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1.</p> <p>With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example:</p> <p>With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10.</p> <p>This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm].</p> <p>There's gotta be an easier, and less fragile way. Please?</p> <p>EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid.</p> <p>Motto: All good programmers are basically lazy.</p>
[ { "answer_id": 66570, "author": "Alexandre Brasil", "author_id": 8841, "author_profile": "https://Stackoverflow.com/users/8841", "pm_score": 0, "selected": false, "text": "<p>The only way I know is to create a FocusListener and attach it to your component. If you want it this FocusListen...
2008/09/15
[ "https://Stackoverflow.com/questions/66455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391806/" ]
For most GUI's I've used, when a control that contains text gets the focus, the entire contents of the control are selected. This means if you just start typing, you completely replace the former contents. Example: You have spin control that is initialized with the value zero. You tab to it and type "1" The value in the control is now 1. With Swing, this doesn't happen. The text in the control is not selected and the carat appears at one end or another of the existing text. Continuing the above example: With a Swing JSpinner, when you tab to the spin control, the carat is at the left. You type "1" and the value in the control is now 10. This drives me, (and my users) up a wall, and I'd like to change it. Even more important, I'd like to change it globally so the new behavior applies to JTextField, JPasswordField, JFormattedTextField, JTextArea, JComboBox, JSpinner, and so on. The only way I have found to do this to add a FocusAdapter to each control and override the focusGained() method to Do The Right Thing[tm]. There's gotta be an easier, and less fragile way. Please? EDIT: One additional piece of information for this particular case. The form I am working with was generated using Idea's form designer. That means I normally don't actually write the code to create the components. It is possible to tell Idea that you want to create them yourself, but that's a hassle I'd like to avoid. Motto: All good programmers are basically lazy.
After reading the replies so far (Thanks!) I passed the outermost JPanel to the following method: ``` void addTextFocusSelect(JComponent component){ if(component instanceof JTextComponent){ component.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent event) { super.focusGained(event); JTextComponent component = (JTextComponent)event.getComponent(); // a trick I found on JavaRanch.com // Without this, some components don't honor selectAll component.setText(component.getText()); component.selectAll(); } }); } else { for(Component child: component.getComponents()){ if(child instanceof JComponent){ addTextFocusSelect((JComponent) child); } } } } ``` It works!
66,475
<p>I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.</p> <p>I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?</p> <p>(I really want the Cursor Position on that line, not 'column', per se)</p>
[ { "answer_id": 66500, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Off the top of my head, I think you want the SelectionStart property.</p>\n" }, { "answer_id": 66561, "a...
2008/09/15
[ "https://Stackoverflow.com/questions/66475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9857/" ]
I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does. I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line? (I really want the Cursor Position on that line, not 'column', per se)
``` int line = textbox.GetLineFromCharIndex(textbox.SelectionStart); int column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line); ```
66,492
<p>Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not.</p> <p>In Firefox/regular WebKit, this would be:</p> <pre><code>if(navigator.onLine) { onlineCode() } </code></pre>
[ { "answer_id": 66521, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 2, "selected": false, "text": "<p>That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2....
2008/09/15
[ "https://Stackoverflow.com/questions/66492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6842/" ]
Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not. In Firefox/regular WebKit, this would be: ``` if(navigator.onLine) { onlineCode() } ```
That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari. <https://bugs.webkit.org/show_bug.cgi?id=19105>
66,505
<p>I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).</p> <ol> <li>I define an interface ICommand</li> <li>I create an abstract base class CommandBase which implements ICommand, to contain common code.</li> <li>I create several implementation classes, each extending the base class (and by extension the interface).</li> </ol> <p>Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...</p> <p>For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:</p> <p>public abstract static const string Name;</p> <p>However (sadly) you cannot define static members in an interface.</p> <p>I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.</p> <hr> <p>UPDATE:</p> <ol> <li>I can't get the code formatting to work properly (Safari/Mac?). Apologies.</li> <li><p>The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).</p></li> <li><p>I forgot to mention - ideally I want to be able to query this information statically:</p> <p>string name = CommandHelp.Name;</p></li> </ol> <p>2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.</p>
[ { "answer_id": 66546, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 0, "selected": false, "text": "<p>[Suggested solution #1 of 3]</p>\n\n<ol>\n<li>Define an abstract property Name in the interface to force all implem...
2008/09/15
[ "https://Stackoverflow.com/questions/66505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here). 1. I define an interface ICommand 2. I create an abstract base class CommandBase which implements ICommand, to contain common code. 3. I create several implementation classes, each extending the base class (and by extension the interface). Now - suppose that the interface specifies that all commands implement the Name property and the Execute method... For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define: public abstract static const string Name; However (sadly) you cannot define static members in an interface. I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution. --- UPDATE: 1. I can't get the code formatting to work properly (Safari/Mac?). Apologies. 2. The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class). 3. I forgot to mention - ideally I want to be able to query this information statically: string name = CommandHelp.Name; 2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
You may consider to use attributes instead of fields. ``` [Command("HELP")] class HelpCommand : ICommand { } ```
66,518
<p>I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say. </p> <p>The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)</p> <p>Below is the code: (Alternatively someone could send me to a good example)</p> <pre><code>$img = imagecreatefromgif("./unit.gif"); $size_x = imagesx($img); $size_y = imagesy($img); $temp = imagecreatetruecolor($size_x, $size_y); imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y); if ($x) { $img = $temp; } else { die("Unable to flip image"); } header("Content-type: image/gif"); imagegif($img); imagedestroy($img); </code></pre>
[ { "answer_id": 66574, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 1, "selected": false, "text": "<p>If you can guarantee the presence of ImageMagick, you can use their <code>mogrify -flop</code> command. It preserves transp...
2008/09/15
[ "https://Stackoverflow.com/questions/66518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2490/" ]
I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say. The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white) Below is the code: (Alternatively someone could send me to a good example) ``` $img = imagecreatefromgif("./unit.gif"); $size_x = imagesx($img); $size_y = imagesy($img); $temp = imagecreatetruecolor($size_x, $size_y); imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y); if ($x) { $img = $temp; } else { die("Unable to flip image"); } header("Content-type: image/gif"); imagegif($img); imagedestroy($img); ```
Shouldn't this: ``` imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0)); imagealphablending($img, false); imagesavealpha($img, true); ``` ...be this: ``` imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0)); imagealphablending($temp, false); imagesavealpha($temp, true); ``` Note you should be calling these functions for the $temp image you have created, not the source image.
66,528
<p>I have the following Java 6 code:</p> <pre><code> Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) </code></pre> <p>I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 66697, "author": "Jim Kiley", "author_id": 7178, "author_profile": "https://Stackoverflow.com/users/7178", "pm_score": 2, "selected": true, "text": "<p>The Hibernate annotations docs (<a href=\"http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/\" rel=\...
2008/09/15
[ "https://Stackoverflow.com/questions/66528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have the following Java 6 code: ``` Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) ``` I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName". Similar syntax error from javac. What am I doing wrong?
The Hibernate annotations docs (<http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/>) suggest that this should be a class-level annotation rather than occurring inline within your code. And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration: ``` @SqlResultSetMapping( name="TripResults", entities={ @EntityResult( entityClass=TripEntity.class ), @EntityResult( entityClass=CommercialTripEntity.class ) } ) public class Foo { public void bogus() { Query q = em.createNativeQuery( "select T.* " + "from Trip T join Itinerary I on (T.itinerary_id=I.id) " + "where I.launchDate between :start and :end " + "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end", "TripResults" ); q.setParameter( "start", range.getStart(), TemporalType.DATE ); q.setParameter( "end", range.getEnd(), TemporalType.DATE ); } } ``` ...obviously I have no evidence that the above code will actually work. I have only verified that it doesn't cause compile errors.
66,542
<p>How do I get started?</p>
[ { "answer_id": 66676, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You'll need an interface to the Oracle SQL database. As Bob pointed out, Allegro CL has such an interface.</p>\n\n<p><a href...
2008/09/15
[ "https://Stackoverflow.com/questions/66542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9615/" ]
How do I get started?
I have found the easiest way to achieve this by using Clojure. Here is the example code: ``` (ns example (:require [clojure.contrib.sql :as sql]) (:import [java.sql Types])) ``` (def devdb {:classname "oracle.jdbc.driver.OracleDriver" :subprotocol "oracle" :subname "thin:username/password@localhost:1509:devdb" :create true}) (defn exec-ora-stored-proc [input-param db callback] (sql/with-connection db (with-open [stmt (.prepareCall (sql/connection) "{call some\_schema.some\_package.test\_proc(?, ?, ?)}")] (doto stmt (.setInt 1 input-param) (.registerOutParameter 2 Types/INTEGER) (.registerOutParameter 3 oracle.jdbc.driver.OracleTypes/CURSOR) (.execute)) (callback (. stmt getInt 2) (. stmt getObject 3))))) (exec-ora-stored-proc 123 ;;input param value devdb (fn [err-code res-cursor] (println (str "ret\_code: " err-code)) ;; prints returned refcursor rows (let [resultset (resultset-seq res-cursor)] (doseq [rec resultset] (println rec)))))
66,606
<p>I'm trying to find <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">ab - Apache HTTP server benchmarking tool</a> for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.</p>
[ { "answer_id": 66617, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 8, "selected": true, "text": "<pre><code>% sudo apt-get install apache2-utils</code></pre>\n\n<p>The command-not-found package in Ubuntu provides som...
2008/09/15
[ "https://Stackoverflow.com/questions/66606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339/" ]
I'm trying to find [ab - Apache HTTP server benchmarking tool](http://httpd.apache.org/docs/2.0/programs/ab.html) for Ubuntu, I'm hoping there's a package I can install for it. I decided I need to do some simple load testing on my applications.
``` % sudo apt-get install apache2-utils ``` The command-not-found package in Ubuntu provides some slick functionality where if you type a command that can't be resolved to an executable (or bash function or whatever) it will query your apt sources and find a package that contains the binary you tried to execute. So, in this case, I typed `ab` at the command prompt: ``` % ab The program 'ab' is currently not installed. You can install it by typing: sudo apt-get install apache2-utils bash: ab: command not found ```
66,610
<p>For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client?</p> <p>Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <a href="http://gnuwin32.sourceforge.net/packages/wget.htm" rel="noreferrer">http://gnuwin32.sourceforge.net/packages/wget.htm</a>.</p>
[ { "answer_id": 66623, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<p>Create the site as normal, then use spidering software to generate a HTML copy.</p>\n\n<p><a href=\"http://www.httr...
2008/09/15
[ "https://Stackoverflow.com/questions/66610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3741/" ]
For a particular project I have, no server side code is allowed. How can I create the web site in php (with includes, conditionals, etc) and then have that converted into a static html site that I can give to the client? Update: Thanks to everyone who suggested wget. That's what I used. I should have specified that I was on a PC, so I grabbed the windows version from here: <http://gnuwin32.sourceforge.net/packages/wget.htm>.
If you have a Linux system available to you use [wget](http://www.gnu.org/software/wget/): ``` wget -k -K -E -r -l 10 -p -N -F -nH http://website.com/ ``` Options * -k : convert links to relative * -K : keep an original versions of files without the conversions made by wget * -E : rename html files to .html (if they don’t already have an htm(l) extension) * -r : recursive… of course we want to make a recursive copy * -l 10 : the maximum level of recursion. if you have a really big website you may need to put a higher number, but 10 levels should be enough. * -p : download all necessary files for each page (css, js, images) * -N : Turn on time-stamping. * -F : When input is read from a file, force it to be treated as an HTML file. * -nH : By default, wget put files in a directory named after the site’s hostname. This will disabled creating of those hostname directories and put everything in the current directory. Source: [Jean-Pascal Houde's weblog](http://blog.jphoude.qc.ca/2007/10/16/creating-static-copy-of-a-dynamic-website/)
66,635
<p>I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. </p> <p><strong>Example</strong>: </p> <pre><code>Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories </code></pre> <p><strong>Question</strong>:<br> Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?</p>
[ { "answer_id": 66683, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": true, "text": "<p>Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent ...
2008/09/15
[ "https://Stackoverflow.com/questions/66635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces. **Example**: ``` Project = Tully.Saps.Data Folder = DataAccess/Interfaces Namespace = Tully.Saps.Data.DataAccess.Interfaces Folder = DataAccess/MbNetRepositories Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories ``` **Question**: Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
66,636
<p>I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class.</p> <p>Essentially, I am trying to accomplish the following:</p> <pre><code>class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) </code></pre>
[ { "answer_id": 66670, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the origi...
2008/09/15
[ "https://Stackoverflow.com/questions/66636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but **not** in the parent class. Essentially, I am trying to accomplish the following: ``` class foo(Object): def meth1(self, val): self.value = val class bar(foo): meth1 = classmethod(foo.meth1) ```
I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with: ``` def convert_to_classmethod(method): return classmethod(method.im_func) class bar(foo): meth1 = convert_to_classmethod(foo.meth1) ``` The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means. I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.
66,643
<p>Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?</p> <p>See the example below:</p> <pre><code> try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } </code></pre> <p>or is ignoring one of the exceptions the only thing you can do?</p> <p>In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.</p>
[ { "answer_id": 66664, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": -1, "selected": false, "text": "<p>No I do not believe so. The catch block will run to completion before the finally block.</p>\n\n<pre><code>try {\n // co...
2008/09/15
[ "https://Stackoverflow.com/questions/66643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5963/" ]
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown? See the example below: ``` try { // code that may or may not throw an exception } finally { SomeCleanupFunctionThatThrows(); // if currently executing an exception, exit the program, // otherwise just let the exception thrown by the function // above propagate } ``` or is ignoring one of the exceptions the only thing you can do? In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
Set a flag variable, then check for it in the finally clause, like so: ``` boolean exceptionThrown = true; try { mightThrowAnException(); exceptionThrown = false; } finally { if (exceptionThrown) { // Whatever you want to do } } ```
66,677
<p>I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal? </p> <p>I should note right now that I <strong>don't</strong> want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.</p>
[ { "answer_id": 66775, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 1, "selected": false, "text": "<p>If you're not afraid of perl, give <a href=\"http://www.mml.org.ua/\" rel=\"nofollow noreferrer\">Minimalist</a> a try.</p>\n...
2008/09/15
[ "https://Stackoverflow.com/questions/66677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6436/" ]
I'm looking for a dead simple mailing list (unix friendly). Robustness, fine-grained configurability, "enterprise-readiness" (whatever that means) are not requirements. I just need to set up a tiny mailing list for a few friends. Rather than hack something up myself, I was wondering if anybody knows of anything already out there with a similar goal? I should note right now that I **don't** want an externally hosted mailing list -- it needs to be software I can install and run on my server. I know of many places I can host a mailing list at (Google/Yahoo groups), but it would be nice to keep the data local.
Mailman is one of the simplest mailing list packages I've come across, so if Mailman is more than you want to deal with I'd suggest just adding an entry into `/etc/aliases` for your mailing list. Of course you have to manage it by hand, but you said it's only for a few friends so that may not be a problem. Just create an entry in `/etc/aliases` such as: ``` mylist: me@somedomain.com, myfriend@somedomain.com, \ myotherfriend@differentdomain.com ``` and then run `newaliases`. It doesn't get much simpler than that. If you want an archive you can create a dummy account on your mail server and add them to the list. It's not as user friendly as Mailman but it's simple and you can be up and running in 5 minutes.
66,727
<p>I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML</p> <pre><code>&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt; </code></pre> <p>I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. </p> <p>My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file.</p> <pre><code>$oDom = new DomDocument(); $oDom-&gt;loadHTML("&lt;strong&gt;This is an example of a &lt;pseud-template&gt;fake tag&lt;/pseud-template&gt;&lt;/strong&gt;"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... </code></pre> <p>The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name).</p> <p>Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP?</p> <p>(if it's not obvious, I don't consider regular expressions a valid solution here)</p> <p><strong>Update</strong>: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.</p>
[ { "answer_id": 66811, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 2, "selected": false, "text": "<p>I wonder if passing the \"bad\" HTML through <a href=\"http://www.w3.org/People/Raggett/tidy/\" rel=\"nofollow noreferr...
2008/09/15
[ "https://Stackoverflow.com/questions/66727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4668/" ]
I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML ``` <strong>This is an example of a <pseud-template>fake tag</pseud-template></strong> ``` I need to parse these files. PHP is the only only tool available. The documents don't come close to being well formed XML. My original thought was to use the loadHTML methods on PHPs DOMDocument. However, these methods choke on the make up HTML tags, and will refuse to parse the string/file. ``` $oDom = new DomDocument(); $oDom->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); //gives us DOMDocument::loadHTML() [function.loadHTML]: Tag pseud-template invalid in Entity, line: 1 occured in .... ``` The only solution I've been able to come up with is to pre-process the files with string replacement functions that will remove the invalid tags and replace them with a valid HTML tag (maybe a span with an id of the tag name). Is there a more elegant solution? A way to let DOMDocument know about additional tags to consider as valid? Is there a different, robust HTML parsing class/object out there for PHP? (if it's not obvious, I don't consider regular expressions a valid solution here) **Update**: The information in the fake tags is part of the goal here, so something like Tidy isn't an option. Also, I'm after something that does the some level, if not all, of well-formedness cleanup for me, which is why I was looking the DomDocument's loadHTML method in the first place.
You can suppress warnings with [`libxml_use_internal_errors`](http://www.php.net/manual/en/function.libxml-use-internal-errors.php), while loading the document. Eg.: ``` libxml_use_internal_errors(true); $doc = new DomDocument(); $doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template></strong>"); libxml_use_internal_errors(false); ``` If, for some reason, you need access to the warnings, use [`libxml_get_errors`](http://www.php.net/manual/en/function.libxml-get-errors.php)
66,730
<p>I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.</p>
[ { "answer_id": 66883, "author": "Sebastian Rittau", "author_id": 7779, "author_profile": "https://Stackoverflow.com/users/7779", "pm_score": 2, "selected": false, "text": "<p>Here is how:</p>\n\n<pre><code>import gobject\n\nclass MyGObjectClass(gobject.GObject):\n ...\n\ngobject.signa...
2008/09/15
[ "https://Stackoverflow.com/questions/66730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8453/" ]
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
You can also define signals inside the class definition: ``` class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } ``` The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`.
66,750
<p>Here is a quick test program:</p> <pre><code> public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } </code></pre> <p>The output is:</p> <p><code> Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag</code></p> <p>How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.</p>
[ { "answer_id": 66771, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": false, "text": "<p>You may not want to change the capitalization -- different cultures capitalize different words (for example, in Germ...
2008/09/15
[ "https://Stackoverflow.com/questions/66750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9661/" ]
Here is a quick test program: ``` public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); System.out.println("Days:"); printDate( "EEEE", "en", date ); printDate( "EEEE", "es", date ); printDate( "EEEE", "fr", date ); printDate( "EEEE", "de", date ); } public static void printDate( String format, String locale, Date date ) { System.out.println( locale + ": " + (new SimpleDateFormat( format, new Locale( locale ) )).format( date ) ); } ``` The output is: `Months: en: September es: septiembre fr: septembre de: September Days: en: Monday es: lunes fr: lundi de: Montag` How can I control the capitalization of the names. For some reason the Spanish and French always seem to return names that start with a lowercase letter.
Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it... [about.com on french capitalization](http://french.about.com/library/writing/bl-capitalization.htm)
66,819
<p>Are there any good solutions to represent a parameterized enum in <code>C# 3.0</code>? I am looking for something like <a href="http://www.ocaml.org" rel="nofollow noreferrer">OCaml</a> or <a href="http://www.haxe.org" rel="nofollow noreferrer">Haxe</a> has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas?</p> <p>See Ocaml example below in one of the replies, a Haxe code follows:</p> <pre><code>enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } </code></pre>
[ { "answer_id": 66895, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>C# (the .NET framework in general, as far as I know) doesn't support parametrized enums like Java does. That being said,...
2008/09/15
[ "https://Stackoverflow.com/questions/66819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
Are there any good solutions to represent a parameterized enum in `C# 3.0`? I am looking for something like [OCaml](http://www.ocaml.org) or [Haxe](http://www.haxe.org) has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas? See Ocaml example below in one of the replies, a Haxe code follows: ``` enum Tree { Node(left: Tree, right: Tree); Leaf(val: Int); } ```
Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the [Haxe enum documentation](https://haxe.org/manual/types-enum-instance.html) - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part. My understanding based on that is as follows: A 'normal' enum is basically a value which is restricted to the things that you have defined in your enum definition. C# Example: ``` enum Color{ Red, Green, Yellow, Blue }; Color c = Color.Red; ``` `c` can either be `Red`, `Green`, `Yellow`, or `Blue`, but nothing else. In Haxe, you can add complex types to enums, Contrived example from their page: ``` enum Cell<T>{ empty; cons( item : T, next : Cell<T> ) } Cell<int> c = <I don't know>; ``` What this *appears* to mean is that `c` is restricted to either being the literal value `empty` (like our old fashioned C# enums), or it can also be a complex type `cons(item, next)`, where `item` is a `T` and `next` is a `Cell<T>`. Not having ever used this it looks like it is probably generating some anonymous types (like how the C# compiler does when you do `new { Name='Joe'}`. Whenever you 'access' the enum value, you have to declare `item` and `next` when you do so, and it looks like they get bound to temporary local variables. Haxe example - You can see 'next' being used as a temporary local variable to pull data out of the anonymous cons structure: ``` switch( c ) { case empty : 0; case cons(item,next): 1 + cell_length(next); } ``` To be honest, this blew my mind when I 'clicked' onto what it seemed to be doing. It seems incredibly powerful, and I can see why you'd be looking for a similar feature in C#. C# enums are pretty much the same as C/++ enums from which they were originally copied. It's basically a nice way of saying `#define Red 1` so the compiler can do comparisons and storage with integers instead of strings when you are passing `Color` objects around. My stab at doing this in C# would be to use generics and interfaces. Something like this: ``` public interface ICell<T> { T Item{ get; set; } ICell<T>{ get; set; } } class Cons<T> : ICell<T> { public T Item{ get; set; } /* C#3 auto-backed property */ public Cell<T> Next{ get; set; } } class EmptyCell<T> : ICell<T>{ public T Item{ get{ return default(T); set{ /* do nothing */ }; } public ICell<T> Next{ get{ return null }; set{ /* do nothing */; } } ``` Then you could have a `List<ICell<T>>` which would contain items and next cell, and you could insert `EmptyCell` at the end (or just have the `Next` reference explicitly set to null). The advantages would be that because `EmptyCell` contains no member variables, it wouldn't require any storage space (like the `empty` in Haxe), whereas a `Cons` cell would. The compiler may also inline / optimize out the methods in `EmptyCell` as they do nothing, so there may be a speed increase over just having a `Cons` with it's member data set to null. I don't really know. I'd welcome any other possible solutions as I'm not particularly proud of my one :-)
66,837
<p>Are <strong>CDATA</strong> tags ever necessary in script tags and if so when?</p> <p>In other words, when and where is this:</p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ ...code... //]]&gt; &lt;/script&gt; </code></pre> <p>preferable to this:</p> <pre><code>&lt;script type="text/javascript"&gt; ...code... &lt;/script&gt; </code></pre>
[ { "answer_id": 66848, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://javascript.about.com/library/blxhtml.htm\" rel=\"nofollow noreferrer\">When you want it to validat...
2008/09/15
[ "https://Stackoverflow.com/questions/66837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
Are **CDATA** tags ever necessary in script tags and if so when? In other words, when and where is this: ``` <script type="text/javascript"> //<![CDATA[ ...code... //]]> </script> ``` preferable to this: ``` <script type="text/javascript"> ...code... </script> ```
A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) *and you want to be able to write literal `i<10` and `a && b` instead of `i&lt;10` and `a &amp;&amp; b`*, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will *probably* want to use a CDATA section. Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue. For a good writeup on the subject, see <https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm>
66,870
<p>I want a user-privileged (not root) process to launch new processes as user <code>nobody</code>. I've tried a straight call to <code>setuid</code> that fails with -1 <code>EPERM</code> on <code>Ubuntu 8.04</code>:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int main() { setuid(65534); while (1); return 0; } </code></pre> <p>How should I do this instead?</p>
[ { "answer_id": 66887, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "<p>As far as I know, you can't unless you're root or have sudo set up to allow you to switch users. Or, you can have your exe...
2008/09/15
[ "https://Stackoverflow.com/questions/66870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9947/" ]
I want a user-privileged (not root) process to launch new processes as user `nobody`. I've tried a straight call to `setuid` that fails with -1 `EPERM` on `Ubuntu 8.04`: ``` #include <sys/types.h> #include <unistd.h> int main() { setuid(65534); while (1); return 0; } ``` How should I do this instead?
You *will* require assistance and a lot of trust from your system administrator. Ordinary users are not able to run the executable of their choice on behalf on other users, period. She may add your application to `/etc/sudoers` with proper settings and you'll be able to run it as with `sudo -u nobody`. This will work for both scripts and binary executables. Another option is that she will do `chown nobody` and `chmod +s` on your binary executable and you'll be able to execute it directly. This task must be repeated each time your executable changes. This could also work for scripts if you'll create a tiny helper executable which simply does `exec("/home/you/bin/your-application")`. This executable can be made suid-nobody (see above) and you may freely modify `your-application`.
66,875
<p>We have a case where clients seem to be eternally caching versions of applets. We're making use of the <code>&lt;param name="cache_version"&gt;</code> tag correctly within our <code>&lt;object&gt;</code> tag, or so we think. We went from a version string of <code>7.1.0.40</code> to <code>7.1.0.42</code> and this triggered a download for only about half of our clients.</p> <p>It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6.</p> <p>Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the <code>cache_archive</code>'s "Last-Modified" and/or "Content-Length" values (as per <a href="http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html" rel="noreferrer">Sun's Site</a>)?</p> <p>FYI, object block looks like this:</p> <pre><code>&lt;object&gt; &lt;param name="ARCHIVE" value="foo.jar"&gt; &lt;param name="CODE" value="com.foo.class"&gt; &lt;param name="CODEBASE" value="."&gt; &lt;param name="cache_archive" value="foo.jar"&gt; &lt;param name="cache_version" value="7.1.0.40"&gt; &lt;param name="NAME" value="FooApplet"&gt; &lt;param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"&gt; &lt;param name="scriptable" value="true"&gt; &lt;param name="progressbar" value="true"/&gt; &lt;param name="boxmessage" value="Loading Web Worksheet Applet..."/&gt; &lt;/object&gt; </code></pre>
[ { "answer_id": 66942, "author": "MtotheThird", "author_id": 7069, "author_profile": "https://Stackoverflow.com/users/7069", "pm_score": 4, "selected": true, "text": "<p>Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and ...
2008/09/15
[ "https://Stackoverflow.com/questions/66875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have a case where clients seem to be eternally caching versions of applets. We're making use of the `<param name="cache_version">` tag correctly within our `<object>` tag, or so we think. We went from a version string of `7.1.0.40` to `7.1.0.42` and this triggered a download for only about half of our clients. It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6. Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the `cache_archive`'s "Last-Modified" and/or "Content-Length" values (as per [Sun's Site](http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html))? FYI, object block looks like this: ``` <object> <param name="ARCHIVE" value="foo.jar"> <param name="CODE" value="com.foo.class"> <param name="CODEBASE" value="."> <param name="cache_archive" value="foo.jar"> <param name="cache_version" value="7.1.0.40"> <param name="NAME" value="FooApplet"> <param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"> <param name="scriptable" value="true"> <param name="progressbar" value="true"/> <param name="boxmessage" value="Loading Web Worksheet Applet..."/> </object> ```
Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under [the most recent versions](http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html) of the JRE. The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system.
66,880
<p>After reading <a href="https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730">this answer</a>, I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.</p>
[ { "answer_id": 66890, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>Most payment gateways provide such numbers for testing their services, but they will generally only work on the staging...
2008/09/15
[ "https://Stackoverflow.com/questions/66880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314/" ]
After reading [this answer](https://stackoverflow.com/questions/63668/confessions-of-your-worst-wtf-moment-what-not-to-do#63730), I wonder if there's a way to get a "testing" credit card number. One that you can experiment with but that doesn't actually charge anything.
``` MasterCard: 5431111111111111 Amex: 341111111111111 Discover: 6011601160116611 American Express (15 digits) 378282246310005 American Express (15 digits) 371449635398431 American Express Corporate (15 digits) 378734493671000 Diners Club (14 digits) 30569309025904 Diners Club (14 digits) 38520000023237 Discover (16 digits) 6011111111111117 Discover (16 digits) 6011000990139424 JCB (16 digits) 3530111333300000 JCB (16 digits) 3566002020360505 MasterCard (16 digits) 5555555555554444 MasterCard (16 digits) 5105105105105100 Visa (16 digits) 4111111111111111 Visa (16 digits) 4012888888881881 Visa (13 digits) 4222222222222 ``` **Credit Card Prefix Numbers:** ``` Visa: 13 or 16 numbers starting with 4 MasterCard: 16 numbers starting with 5 Discover: 16 numbers starting with 6011 AMEX: 15 numbers starting with 34 or 37 ```
66,882
<p>Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?</p>
[ { "answer_id": 66892, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 2, "selected": false, "text": "<p>if (x * y) > 0...</p>\n\n<p>assuming non-zero and such.</p>\n" }, { "answer_id": 66908, "author": "Da...
2008/09/15
[ "https://Stackoverflow.com/questions/66882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?
Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x\*y>=0 doesn't work) ``` bool SameSign(int x, int y) { return (x >= 0) ^ (y < 0); } ``` Of course, you can geek out and template: ``` template <typename valueType> bool SameSign(typename valueType x, typename valueType y) { return (x >= 0) ^ (y < 0); } ``` Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.
66,912
<p>In a JSP page, I created a <code>&lt;h:form enctype="multipart/form-data"&gt;</code> with some elements: <code>&lt;t:inputText&gt;</code>, <code>&lt;t:inputDate&gt;</code>, etc. Also, I added some <code>&lt;t:message for="someElement"&gt;</code> And I wanted to allow the user upload several files (one at a time) within the form (using <code>&lt;t:inputFileUpload&gt;</code> ) At this point my code works fine.</p> <hr> <p>The headache comes when I try to put the form inside a <code>&lt;t:panelTabbedPane serverSideTabSwitch="false"&gt;</code> (and thus of course, inside a <code>&lt;t:panelTab&gt;</code> ) </p> <p>I copied the structure shown in the source code for TabbedPane example from <a href="http://www.irian.at/myfacesexamples/tabbedPane.jsf" rel="nofollow noreferrer">Tomahawk's examples</a>, by using the <code>&lt;f:subview&gt;</code> tag and putting the panelTab tag inside a new jsp page (using <code>&lt;jsp:include page="somePage.jsp"&gt;</code> directive)</p> <p>First at all, the <code>&lt;t:inputFileUpload&gt;</code> fails to load the file at the value assigned in the Managed Bean UploadedFile attribute <code>#{myBean.upFile}</code></p> <p>Then, <a href="http://markmail.org/message/b4nht4f6xb74noxp" rel="nofollow noreferrer" title="That has no answer when I readed it">googling for a clue</a>, I knew that <code>&lt;t:panelTabbedPane&gt;</code> generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the <code>&lt;h:form&gt;</code> out of the <code>&lt;t:panelTabbedPane&gt;</code> and eureka! file input worked again! (the autoform doesn't generate) </p> <p>But, oh surprise! oh terrible Murphy law! All my <code>&lt;h:message&gt;</code> begins to fail. The Eclipse console's output show me that all <code>&lt;t:message&gt;</code> are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change)</p> <p>At this point, I put a <code>&lt;t:mesagges&gt;</code> tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel.</p> <p>All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined.</p> <h3>¿How can I get the <code>&lt;t:message for="xyz"&gt;</code> working properly?</h3> <hr> <p>I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) </p> <hr> <h2>"SOLVED": This problem is an issue reported to myFaces forum.</h2> <p>Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) <a href="https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&amp;focusedCommentId=12567158#action_12567158" rel="nofollow noreferrer">See the issue</a></p> <hr> <p><strong>EDIT 1</strong></p> <p>1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the <code>&lt;t:message for="xyz"&gt;</code> tags work.</p> <p>What I did was:<br> 1. Having my tag <code>&lt;inputText id="name" forceId="true" required="true"&gt;</code> The <code>&lt;t:message&gt;</code> doesn't work.<br> 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: &lt;inputText id="<strong>namej_id_1</strong>" forceId="true" required="true"&gt;<br> 3. Then the <code>&lt;t:message&gt;</code> worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle)<br> 4. This implies that the user have to press 2 times the submit button to get the error messages on the page.<br> 5. And using the "j_id_1" phrase at the end of IDs is very weird. </p> <hr> <p><strong>EDIT 2</strong></p> <p>Ok, here comes the code, hope it not be annoying.</p> <p>1.- <strong>mainPage.jsp</strong> (here is the <code>&lt;t:panelTabbedPane&gt;</code> and <code>&lt;f:subview&gt;</code> tags) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;html&gt; &lt;body&gt; &lt;f:view&gt; &lt;h:form enctype="multipart/form-data"&gt; &lt;t:panelTabbedPane serverSideTabSwitch="false" &gt; &lt;f:subview id="subview_tab_detail"&gt; &lt;jsp:include page="detail.jsp"/&gt; &lt;/f:subview&gt; &lt;/t:panelTabbedPane&gt; &lt;/h:form&gt; &lt;/f:view&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br /> 2.- <strong>detail.jsp</strong> (here is the <code>&lt;t:panelTab&gt;</code> tag) </p> <pre><code>&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%&gt; &lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%&gt; &lt;%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%&gt; &lt;t:panelTab label="TAB_1"&gt; &lt;t:panelGrid columns="3"&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="CREATING A TICKET" /&gt; &lt;/f:facet&gt; &lt;t:outputLabel for="ticket_id" value="TICKET ID" /&gt; &lt;t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /&gt; &lt;t:message for="ticket_id" /&gt; &lt;t:outputLabel for="description" value="DESCRIPTION" /&gt; &lt;t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /&gt; &lt;t:message for="description" /&gt; &lt;t:outputLabel for="attachment" value="ATTACHMENTS" /&gt; &lt;t:panelGroup&gt; &lt;!-- This is for listing multiple file uploads --&gt; &lt;!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --&gt; &lt;t:panelGrid columns="3" binding="#{myBean.panelUpload}" /&gt; &lt;t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /&gt; &lt;t:commandButton value="ADD FILE" action="#{myBean.upload}" /&gt; &lt;/t:panelGroup&gt; &lt;t:message for="attachment" /&gt; &lt;t:commandButton action="#{myBean.create}" value="CREATE TICKET" /&gt; &lt;/t:panelGrid&gt; &lt;/t:panelTab&gt; </code></pre> <hr> <p><strong>EDIT 3</strong></p> <p>On response to Kyle Renfro follow-up:</p> <blockquote> <p>Kyle says:</p> <blockquote> <p>"At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." </p> </blockquote> </blockquote> <p>Here is the behavior found:<br> 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up.<br> 2.- The eclipse console shows me these internal errors: </p> <pre><code>ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. </code></pre> <p>Here is when I saw the <code>"j_id_1"</code> word at the generated IDs, for example, for the id "ticket_id": </p> <pre><code>j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 </code></pre> <p>And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): </p> <pre><code>&lt;input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"&gt; </code></pre> <hr>
[ { "answer_id": 72243, "author": "Kyle Renfro", "author_id": 8187, "author_profile": "https://Stackoverflow.com/users/8187", "pm_score": 1, "selected": false, "text": "<p>The <em>forceId</em> attribute of the tomahawk components should solve this problem.</p>\n\n<p>something like:</p>\n\n...
2008/09/15
[ "https://Stackoverflow.com/questions/66912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9818/" ]
In a JSP page, I created a `<h:form enctype="multipart/form-data">` with some elements: `<t:inputText>`, `<t:inputDate>`, etc. Also, I added some `<t:message for="someElement">` And I wanted to allow the user upload several files (one at a time) within the form (using `<t:inputFileUpload>` ) At this point my code works fine. --- The headache comes when I try to put the form inside a `<t:panelTabbedPane serverSideTabSwitch="false">` (and thus of course, inside a `<t:panelTab>` ) I copied the structure shown in the source code for TabbedPane example from [Tomahawk's examples](http://www.irian.at/myfacesexamples/tabbedPane.jsf), by using the `<f:subview>` tag and putting the panelTab tag inside a new jsp page (using `<jsp:include page="somePage.jsp">` directive) First at all, the `<t:inputFileUpload>` fails to load the file at the value assigned in the Managed Bean UploadedFile attribute `#{myBean.upFile}` Then, [googling for a clue](http://markmail.org/message/b4nht4f6xb74noxp "That has no answer when I readed it"), I knew that `<t:panelTabbedPane>` generates a form called "autoform", so I was getting nested forms. Ok, I fixed that creating the `<h:form>` out of the `<t:panelTabbedPane>` and eureka! file input worked again! (the autoform doesn't generate) But, oh surprise! oh terrible Murphy law! All my `<h:message>` begins to fail. The Eclipse console's output show me that all `<t:message>` are looking for nonexistents elements ID's (who have their ID's in part equals to they are looking for, but at the end of the ID's their names change) At this point, I put a `<t:mesagges>` tag (note the "s" at the end) to show me all validation errors at once at the beginning of the Panel, and it works fine. So, validation errors exists and they show properly at the beginning of the Panel. All validation error messages generated in this page are the JSF built-in validation messages. The backing bean at this moment doesn't have any validators defined. ### ¿How can I get the `<t:message for="xyz">` working properly? --- I'm using Tomahawk-1.1.6 with myFaces-impl-1.2.3 in a eclipse Ganymede project with Geronimo as Application Server (Geronimo gives me the myFaces jar implementation while I put the tomahawk jar in the WEB-INF/lib folder of application) --- "SOLVED": This problem is an issue reported to myFaces forum. ------------------------------------------------------------- Thanks to Kyle Renfro for the soon response and information. (Good job Kyle!) [See the issue](https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158) --- **EDIT 1** 1.- Thanks to Kyle Renfro for his soon response. The forceID attribute used inside the input element doesn't works at first time, but doing some very tricky tweaks I could make the `<t:message for="xyz">` tags work. What I did was: 1. Having my tag `<inputText id="name" forceId="true" required="true">` The `<t:message>` doesn't work. 2. Then, after looking the error messages on eclipse console, I renamed my "id" attribute to this: <inputText id="**namej\_id\_1**" forceId="true" required="true"> 3. Then the `<t:message>` worked!! but after pressing the "Submit" button of the form the second time. ¡The second time! (I suspect that something is going on at the JSF lifecycle) 4. This implies that the user have to press 2 times the submit button to get the error messages on the page. 5. And using the "j\_id\_1" phrase at the end of IDs is very weird. --- **EDIT 2** Ok, here comes the code, hope it not be annoying. 1.- **mainPage.jsp** (here is the `<t:panelTabbedPane>` and `<f:subview>` tags) ``` <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <html> <body> <f:view> <h:form enctype="multipart/form-data"> <t:panelTabbedPane serverSideTabSwitch="false" > <f:subview id="subview_tab_detail"> <jsp:include page="detail.jsp"/> </f:subview> </t:panelTabbedPane> </h:form> </f:view> </body> </html> ``` ``` <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <%@ taglib prefix="t" uri="http://myfaces.apache.org/tomahawk"%> <t:panelTab label="TAB_1"> <t:panelGrid columns="3"> <f:facet name="header"> <h:outputText value="CREATING A TICKET" /> </f:facet> <t:outputLabel for="ticket_id" value="TICKET ID" /> <t:inputText id="ticket_id" value="#{myBean.ticketId}" required="true" /> <t:message for="ticket_id" /> <t:outputLabel for="description" value="DESCRIPTION" /> <t:inputText id="description" value="#{myBean.ticketDescription}" required="true" /> <t:message for="description" /> <t:outputLabel for="attachment" value="ATTACHMENTS" /> <t:panelGroup> <!-- This is for listing multiple file uploads --> <!-- The panelGrid binding make attachment list grow as the user inputs several files (one at a time) --> <t:panelGrid columns="3" binding="#{myBean.panelUpload}" /> <t:inputFileUpload id="attachment" value="#{myBean.upFile}" storage="file" /> <t:commandButton value="ADD FILE" action="#{myBean.upload}" /> </t:panelGroup> <t:message for="attachment" /> <t:commandButton action="#{myBean.create}" value="CREATE TICKET" /> </t:panelGrid> </t:panelTab> ``` --- **EDIT 3** On response to Kyle Renfro follow-up: > > Kyle says: > > > > > > > "At the first view of the page, if you press the "CREATE TICKET" button with nothing in any of the inputTexts and no files uploaded, do the message tags work for the inputTexts? (ie. required = true) I'm just curious if the messages for the inputTexts are working but the message for the inputFileUpload is not." > > > > > > > > > Here is the behavior found: 1.- There is no validation error messages shown at all (the message tags don't work) Even when I try to test only one validation error message (for example, testing the message for the first input text) none of them shows up. 2.- The eclipse console shows me these internal errors: ``` ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'ticket_id' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'description' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_8j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ERROR [HtmlMessageRendererBase] Could not render Message. Unable to find component 'attachment' (calling findComponent on component 'j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_14j_id_1'). If the provided id was correct, wrap the message and its component into an h:panelGroup or h:panelGrid. ``` Here is when I saw the `"j_id_1"` word at the generated IDs, for example, for the id "ticket\_id": ``` j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:j_id_jsp_1716158401_5j_id_1 ``` And, viewing the resulting HTML generated page, I saw that the IDs names are like this (whitout using "ForceId" atribute): ``` <input id="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1" name="j_id_jsp_1383779881_1:subview_tab_detail:j_id_jsp_1716158401_0j_id_1:ticket_idj_id_1"> ``` ---
Looks like it may be related a bug in myfaces. There is a newer version of myfaces and tomahawk that you might try. I would remove the subview functionality as a quick test - copy the detail.jsp page back into the main page. <https://issues.apache.org/jira/browse/MYFACES-1807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=12567158#action_12567158>
66,921
<p>Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:</p> <pre><code>tasksForm.Visible = false; tasksForm.Show(); </code></pre> <p>Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.</p> <p>When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:</p> <pre><code>tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); </code></pre> <p>I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.</p>
[ { "answer_id": 66945, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>It sounds to me like you need to sit down and re-think your approach here. I cannot imagine a single reason your public me...
2008/09/15
[ "https://Stackoverflow.com/questions/66921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
Short version: I want to trigger the Form\_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property: ``` tasksForm.Visible = false; tasksForm.Show(); ``` Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form. When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form\_Load() event. The only way I can find to trigger Form\_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state: ``` tasksForm.WindowState = FormWindowState.Minimized; tasksForm.Show(); ``` I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist. It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.
66,923
<p>So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?</p> <p>Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.</p>
[ { "answer_id": 66944, "author": "Sam", "author_id": 9406, "author_profile": "https://Stackoverflow.com/users/9406", "pm_score": 5, "selected": true, "text": "<p>You can use a regular expression with this pattern:</p>\n\n<pre><code>\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.(25[0-5]|2[...
2008/09/15
[ "https://Stackoverflow.com/questions/66923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10059/" ]
So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java? Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.
You can use a regular expression with this pattern: ``` \b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b ``` That will tell you if it's an IPv4 address.
66,934
<p>We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports. We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me)</p> <p>The code to add a textbox is:</p> <pre><code>ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#) </code></pre> <p>but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?</p>
[ { "answer_id": 67740, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 4, "selected": true, "text": "<p>If you have the cell name or position, you can do:</p>\n\n<pre><code>With ActiveSheet\n .Shapes.AddTextbox msoTextOrien...
2008/09/15
[ "https://Stackoverflow.com/questions/66934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports. We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me) The code to add a textbox is: ``` ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#) ``` but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?
If you have the cell name or position, you can do: ``` With ActiveSheet .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height End With ``` This will add a textbox over cell B3. When B3 is resized, the textbox is also.
66,964
<p>For example:</p> <blockquote> <p>This is main body of my content. I have a footnote link for this line [1]. Then, I have some more content. Some of it is interesting and it has some footnotes as well [2].</p> <p>[1] Here is my first footnote.</p> <p>[2] Another footnote.</p> </blockquote> <p>So, if I click on the "[1]" link it directs the web page to the first footnote reference and so on. How exactly do I accomplish this in HTML?</p>
[ { "answer_id": 66977, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 0, "selected": false, "text": "<p>anchor tags using named anchors</p>\n\n<p><a href=\"http://www.w3schools.com/HTML/html_links.asp\" rel=\"nofollow nor...
2008/09/15
[ "https://Stackoverflow.com/questions/66964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
For example: > > This is main body of my content. I have a > footnote link for this line [1]. Then, I have some more > content. Some of it is interesting and it > has some footnotes as well [2]. > > > [1] Here is my first footnote. > > > [2] Another footnote. > > > So, if I click on the "[1]" link it directs the web page to the first footnote reference and so on. How exactly do I accomplish this in HTML?
Give a container an id, then use `#` to refer to that Id. e.g. ```html <p>This is main body of my content. I have a footnote link for this line <a href="#footnote-1">[1]</a>. Then, I have some more content. Some of it is interesting and it has some footnotes as well <a href="#footnote-2">[2]</a>.</p> <p id="footnote-1">[1] Here is my first footnote.</p> <p id="footnote-2">[2] Another footnote.</p> ```
67,021
<p>I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project.</p> <p>I want to give the framework a Bazaar repository of its own. How do I do it?</p>
[ { "answer_id": 67126, "author": "jamuraa", "author_id": 9805, "author_profile": "https://Stackoverflow.com/users/9805", "pm_score": 0, "selected": false, "text": "<p>As far as I know, there is not a way to do this easily with bazaar. One possibility is to take the original project, bra...
2008/09/15
[ "https://Stackoverflow.com/questions/67021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project. I want to give the framework a Bazaar repository of its own. How do I do it?
You use the split command: ``` bzr split sub_folder ``` This creates an independant tree in the subfolder, which you can now export and work on separately.
67,093
<p>The MySQL manual at <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">MySQL</a> covers this.</p> <p>Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently <code>RENAME {DATABASE | SCHEMA} db_name TO new_db_name;</code> <a href="http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html" rel="noreferrer">does bad things, exists only in a handful of versions, and is a bad idea overall</a>.</p> <p>This needs to work with <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a>, which stores things very differently than <a href="http://en.wikipedia.org/wiki/MyISAM" rel="noreferrer">MyISAM</a>.</p>
[ { "answer_id": 67123, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 4, "selected": false, "text": "<p>When you rename a database in PHPMyAdmin it creates a dump, then drops and recreates the database with the new name.</p>\n...
2008/09/15
[ "https://Stackoverflow.com/questions/67093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
The MySQL manual at [MySQL](http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html) covers this. Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently `RENAME {DATABASE | SCHEMA} db_name TO new_db_name;` [does bad things, exists only in a handful of versions, and is a bad idea overall](http://web.archive.org/web/20160504181056/https://dev.mysql.com/doc/refman/5.1/en/rename-database.html). This needs to work with [InnoDB](http://en.wikipedia.org/wiki/InnoDB), which stores things very differently than [MyISAM](http://en.wikipedia.org/wiki/MyISAM).
For **InnoDB**, the following seems to work: create the new empty database, then rename each table in turn into the new database: ``` RENAME TABLE old_db.table TO new_db.table; ``` You will need to adjust the permissions after that. For scripting in a shell, you can use either of the following: ``` mysql -u username -ppassword old_db -sNe 'show tables' | while read table; \ do mysql -u username -ppassword -sNe "rename table old_db.$table to new_db.$table"; done ``` OR ``` for table in `mysql -u root -ppassword -s -N -e "use old_db;show tables from old_db;"`; do mysql -u root -ppassword -s -N -e "use old_db;rename table old_db.$table to new_db.$table;"; done; ``` --- Notes: * There is no space between the option `-p` and the password. If your database has no password, remove the `-u username -ppassword` part. * If some table has a trigger, it cannot be moved to another database using above method (will result `Trigger in wrong schema` error). If that is the case, use a traditional way to clone a database and then drop the old one: `mysqldump old_db | mysql new_db` * If you have stored procedures, you can copy them afterwards: `mysqldump -R old_db | mysql new_db`
67,141
<p>Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x?</p> <p>Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005.</p> <p>We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. </p> <p>I'm talking about the no-compromise usage, that is, with migrations and all.</p> <p>Thank you,</p>
[ { "answer_id": 67962, "author": "Aupajo", "author_id": 10407, "author_profile": "https://Stackoverflow.com/users/10407", "pm_score": 1, "selected": false, "text": "<p>I would strongly suggest you weigh up migrating from the legacy database. You'll probably find yourself in a world of pai...
2008/09/15
[ "https://Stackoverflow.com/questions/67141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7754/" ]
Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x? Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005. We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. I'm talking about the no-compromise usage, that is, with migrations and all. Thank you,
Have you considered using JRuby? Microsoft has a [JDBC driver for SQL Server](http://msdn.microsoft.com/en-us/data/aa937724.aspx) that can be run on UNIX variants (it's pure Java AFAIK). I was able to get the 2.0 technology preview working with JRuby and Rails 2.1 today. I haven't tried migrations yet, but so far the driver seems to be working quite well. Here's a rough sketch of how to get it working: 1. Make sure Java 6 is installed 2. Install JRuby using the instructions on the [JRuby website](http://www.jruby.org/) 3. Install Rails using gem (`jruby -S gem install rails`) 4. Download the UNIX package of [Microsoft's SQL Server JDBC driver](http://msdn.microsoft.com/en-us/data/aa937724.aspx) (Version 2.0) 5. Unpack Microsoft's SQL Server driver 6. Find sqljdbc4.jar and copy it to JRuby's lib directory 7. `jruby -S gem install activerecord-jdbcmssql-adapter` 8. Create a rails project (`jruby -S rails hello`) 9. Put the proper settings in database.yml (example below) 10. You're all set! Try running `jruby script/console` and creating a model. ``` development: host: localhost adapter: jdbc username: sa password: kitteh driver: com.microsoft.sqlserver.jdbc.SQLServerDriver url: jdbc:sqlserver://localhost;databaseName=mydb timeout: 5000 ``` Note: I'm not sure you can use Windows Authentication with the JDBC driver. You may need to use SQL Server Authentication. Best of luck to you! Ben
67,219
<p>When I use the PrintOut method to print a Worksheet object to a printer, the "Printing" dialog (showing filename, destination printer, pages printed and a Cancel button) is displayed even though I have set DisplayAlerts = False. The code below works in an Excel macro but the same thing happens if I use this code in a VB or VB.Net application (with the reference changes required to use the Excel object).</p> <pre><code>Public Sub TestPrint() Dim vSheet As Worksheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set vSheet = ActiveSheet vSheet.PrintOut Preview:=False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub </code></pre> <p>EDIT: The answer below sheds more light on this (that it may be a Windows dialog and not an Excel dialog) but does not answer my question. Does anyone know how to prevent it from being displayed?</p> <p>EDIT: Thank you for your extra research, Kevin. It looks very much like this is what I need. Just not sure I want to blindly accept API code like that. Does anyone else have any knowledge about these API calls and that they're doing what the author purports?</p>
[ { "answer_id": 69726, "author": "Kevin Haines", "author_id": 10410, "author_profile": "https://Stackoverflow.com/users/10410", "pm_score": 2, "selected": true, "text": "<p>When you say the \"Printing\" Dialog, I assume you mean the \"Now printing xxx on \" dialog rather than standard pri...
2008/09/15
[ "https://Stackoverflow.com/questions/67219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7209/" ]
When I use the PrintOut method to print a Worksheet object to a printer, the "Printing" dialog (showing filename, destination printer, pages printed and a Cancel button) is displayed even though I have set DisplayAlerts = False. The code below works in an Excel macro but the same thing happens if I use this code in a VB or VB.Net application (with the reference changes required to use the Excel object). ``` Public Sub TestPrint() Dim vSheet As Worksheet Application.ScreenUpdating = False Application.DisplayAlerts = False Set vSheet = ActiveSheet vSheet.PrintOut Preview:=False Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub ``` EDIT: The answer below sheds more light on this (that it may be a Windows dialog and not an Excel dialog) but does not answer my question. Does anyone know how to prevent it from being displayed? EDIT: Thank you for your extra research, Kevin. It looks very much like this is what I need. Just not sure I want to blindly accept API code like that. Does anyone else have any knowledge about these API calls and that they're doing what the author purports?
When you say the "Printing" Dialog, I assume you mean the "Now printing xxx on " dialog rather than standard print dialog (select printer, number of copies, etc). Taking your example above & trying it out, that is the behaviour I saw - "Now printing..." was displayed briefly & then auto-closed. What you're trying to control may not be tied to Excel, but instead be Windows-level behaviour. If it is controllable, you'd need to a) disable it, b) perform your print, c) re-enable. If your code fails, there is a risk this is not re-enabled for other applications. EDIT: Try this solution: [How do you prevent printing dialog when using Excel PrintOut method](http://www.mrexcel.com/archive2/11900/13336.htm). It seems to describe exactly what you are after.
67,244
<p>How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?</p>
[ { "answer_id": 67417, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>You can try something like this. Note, I believe 3 is EXECUTE.</p>\n\n<pre><code>SELECT\ngrantee_principal.name AS [Grant...
2008/09/15
[ "https://Stackoverflow.com/questions/67244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?
In 7.0 or 2000, you can modify and use the following code: ``` SELECT convert(varchar(100), 'GRANT ' + CASE WHEN actadd & 32 = 32 THEN 'EXECUTE' ELSE CASE WHEN actadd & 1 = 1 THEN 'SELECT' + CASE WHEN actadd & (8|2|16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 8 = 8 THEN 'INSERT' + CASE WHEN actadd & (2|16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 2 = 2 THEN 'UPDATE' + CASE WHEN actadd & (16) > 0 THEN ', ' ELSE '' END ELSE '' END + CASE WHEN actadd & 16 = 16 THEN 'DELETE' ELSE '' END END + ' ON [' + o.name + '] TO [' + u.name + ']') AS '--Permissions--' FROM syspermissions p INNER JOIN sysusers u ON u.uid = p.grantee INNER JOIN sysobjects o ON p.id = o.id WHERE o.type <> 'S' AND o.name NOT LIKE 'dt%' --AND o.name = '<specific procedure/table>' --AND u.name = '<specific user>' ORDER BY u.name, o.name ```
67,273
<p>How do you iterate through every file/directory recursively in standard C++?</p>
[ { "answer_id": 67286, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>You need to call OS-specific functions for filesystem traversal, like <code>open()</code> and <code>readdir()</code>...
2008/09/15
[ "https://Stackoverflow.com/questions/67273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
How do you iterate through every file/directory recursively in standard C++?
In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using [Boost.FileSystem](http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm). This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard. An example, taken straight from the website: ``` bool find_file( const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found ) // placing path here if found { if ( !exists( dir_path ) ) return false; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if ( is_directory(itr->status()) ) { if ( find_file( itr->path(), file_name, path_found ) ) return true; } else if ( itr->leaf() == file_name ) // see below { path_found = itr->path(); return true; } } return false; } ```
67,275
<p>I am trying to read a single file from a <code>java.util.zip.ZipInputStream</code>, and copy it into a <code>java.io.ByteArrayOutputStream</code> (so that I can then create a <code>java.io.ByteArrayInputStream</code> and hand that to a 3rd party library that will end up closing the stream, and I don't want my <code>ZipInputStream</code> getting closed).</p> <p>I'm probably missing something basic here, but I never enter the while loop here:</p> <pre><code>ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } </code></pre> <p>What am I missing that will allow me to copy the stream?</p> <p><strong>Edit:</strong></p> <p>I should have mentioned earlier that this <code>ZipInputStream</code> is not coming from a file, so I don't think I can use a <code>ZipFile</code>. It is coming from a file uploaded through a servlet.</p> <p>Also, I have already called <code>getNextEntry()</code> on the <code>ZipInputStream</code> before getting to this snippet of code. If I don't try copying the file into another <code>InputStream</code> (via the <code>OutputStream</code> mentioned above), and just pass the <code>ZipInputStream</code> to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.</p>
[ { "answer_id": 67367, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": -1, "selected": false, "text": "<p>Check if the input stream is positioned in the begging.</p>\n\n<p>Otherwise, as implementation: I do not think that...
2008/09/15
[ "https://Stackoverflow.com/questions/67275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
I am trying to read a single file from a `java.util.zip.ZipInputStream`, and copy it into a `java.io.ByteArrayOutputStream` (so that I can then create a `java.io.ByteArrayInputStream` and hand that to a 3rd party library that will end up closing the stream, and I don't want my `ZipInputStream` getting closed). I'm probably missing something basic here, but I never enter the while loop here: ``` ByteArrayOutputStream streamBuilder = new ByteArrayOutputStream(); int bytesRead; byte[] tempBuffer = new byte[8192*2]; try { while ((bytesRead = zipStream.read(tempBuffer)) != -1) { streamBuilder.write(tempBuffer, 0, bytesRead); } } catch (IOException e) { // ... } ``` What am I missing that will allow me to copy the stream? **Edit:** I should have mentioned earlier that this `ZipInputStream` is not coming from a file, so I don't think I can use a `ZipFile`. It is coming from a file uploaded through a servlet. Also, I have already called `getNextEntry()` on the `ZipInputStream` before getting to this snippet of code. If I don't try copying the file into another `InputStream` (via the `OutputStream` mentioned above), and just pass the `ZipInputStream` to my 3rd party library, the library closes the stream, and I can't do anything more, like dealing with the remaining files in the stream.
Your loop looks valid - what does the following code (just on it's own) return? ``` zipStream.read(tempBuffer) ``` if it's returning -1, then the zipStream is closed before you get it, and all bets are off. It's time to use your debugger and make sure what's being passed to you is actually valid. When you call getNextEntry(), does it return a value, and is the data in the entry meaningful (i.e. does getCompressedSize() return a valid value)? IF you are just reading a Zip file that doesn't have read-ahead zip entries embedded, then ZipInputStream isn't going to work for you. Some useful tidbits about the Zip format: Each file embedded in a zip file has a header. This header can contain useful information (such as the compressed length of the stream, it's offset in the file, CRC) - or it can contain some magic values that basically say 'The information isn't in the stream header, you have to check the Zip post-amble'. Each zip file then has a table that is attached to the end of the file that contains all of the zip entries, along with the real data. The table at the end is mandatory, and the values in it must be correct. In contrast, the values embedded in the stream do not have to be provided. If you use ZipFile, it reads the table at the end of the zip. If you use ZipInputStream, I suspect that getNextEntry() attempts to use the entries embedded in the stream. If those values aren't specified, then ZipInputStream has no idea how long the stream might be. The inflate algorithm is self terminating (you actually don't need to know the uncompressed length of the output stream in order to fully recover the output), but it's possible that the Java version of this reader doesn't handle this situation very well. I will say that it's fairly unusual to have a servlet returning a ZipInputStream (it's much more common to receive an inflatorInputStream if you are going to be receiving compressed content.
67,300
<p>If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly.</p> <p>I know Microsoft doesn't want it to be set. <a href="http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>: '<i>This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.</i>' A control property just for color which supports the .NET infrastructure? ...hard to believe.</p> <p>I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution?</p> <p>What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?</p>
[ { "answer_id": 214082, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The background color of the tab seems to be controlled by the OS's Display Properties. Specifically the under the appearan...
2008/09/15
[ "https://Stackoverflow.com/questions/67300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9470/" ]
If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly. I know Microsoft doesn't want it to be set. [MSDN](http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx): '*This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.*' A control property just for color which supports the .NET infrastructure? ...hard to believe. I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution? What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?
The solution in Rajesh's blog is really useful, but it colours the tab part of the control only. In my case I had a tabcontrol on a different coloured background. The tabs themselves were grey which wasn't a problem, but the area to the right of the tabs was displaying as a grey strip. To change this colour to the colour of your background you need to add the following code to the DrawItem method (as described in Rajesh's solution). I'm using VB.Net: ``` ... Dim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1) Dim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5) Dim b As Brush = New SolidBrush(Color.White) e.Graphics.FillRectangle(b, rf) ... ``` Basically you need to get the rectangle made of the right hand side of the last tab to the right hand side of the tab control and then fill it to your desired colour.
67,354
<p>I have an iframe. The content is wider than the width I am setting so the iframe gets a horizontal scroll bar. I can't increase the width of the iframe so I want to just remove the scroll bar. I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one. I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.</p>
[ { "answer_id": 67568, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 3, "selected": false, "text": "<p>You could try putting the iframe inside a div and then use the div for the scrolling. You can control the scrolling o...
2008/09/15
[ "https://Stackoverflow.com/questions/67354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
I have an iframe. The content is wider than the width I am setting so the iframe gets a horizontal scroll bar. I can't increase the width of the iframe so I want to just remove the scroll bar. I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one. I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.
``` scrolling="yes" horizontalscrolling="no" verticalscrolling="yes" ``` Put that in your iFrame tag. You don't need to mess around with trying to format this in CSS.
67,370
<p>I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: </p> <pre><code>IProxy proxy = ChannelFactory&lt;IProxy&gt;.CreateChannel(...); </code></pre> <p>In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. </p> <p>Another way of restating this problem in very simple terms would be that I'm attempting to do something like this:</p> <pre><code>string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List&lt;t&gt; myIntegers = new List&lt;&gt;(); // does not compile, expects a "type" List&lt;typeof(t)&gt; myIntegers = new List&lt;typeof(t)&gt;(); // interesting - type must resolve at compile time? </code></pre> <p>Is there an approach to this I can leverage within C#?</p>
[ { "answer_id": 67530, "author": "IDisposable", "author_id": 2076, "author_profile": "https://Stackoverflow.com/users/2076", "pm_score": 6, "selected": true, "text": "<p>What you are looking for is MakeGenericType</p>\n\n<pre><code>string elementTypeName = Console.ReadLine();\nType elemen...
2008/09/15
[ "https://Stackoverflow.com/questions/67370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: ``` IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...); ``` In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. Another way of restating this problem in very simple terms would be that I'm attempting to do something like this: ``` string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List<t> myIntegers = new List<>(); // does not compile, expects a "type" List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time? ``` Is there an approach to this I can leverage within C#?
What you are looking for is MakeGenericType ``` string elementTypeName = Console.ReadLine(); Type elementType = Type.GetType(elementTypeName); Type[] types = new Type[] { elementType }; Type listType = typeof(List<>); Type genericType = listType.MakeGenericType(types); IProxy proxy = (IProxy)Activator.CreateInstance(genericType); ``` So what you are doing is getting the type-definition of the generic "template" class, then building a specialization of the type using your runtime-driving types.
67,410
<p><code>GNU sed version 4.1.5</code> seems to fail with International chars. Here is my input file:</p> <pre><code>Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X &lt;br&gt; Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y </code></pre> <p>(Note the umlaut in the second line.)</p> <p>And when I do</p> <pre><code>sed 's/.*| //' &lt; in </code></pre> <p>I would expect to see only the <code>X</code> and <code>Y</code>, as I've asked to remove ALL chars up to the <code>'|'</code> and space beyond it. Instead, I get:</p> <pre><code>X&lt;br&gt; Gras Och Stenar Trad - From M? Y </code></pre> <p>I know I can use tr to remove the International chars. first, but is there a way to just use sed?</p>
[ { "answer_id": 67470, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><code>sed</code> is not very well setup for non-ASCII text. However you can use (almost) the same code in <code>perl</code> ...
2008/09/15
[ "https://Stackoverflow.com/questions/67410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10251/" ]
`GNU sed version 4.1.5` seems to fail with International chars. Here is my input file: ``` Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X <br> Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y ``` (Note the umlaut in the second line.) And when I do ``` sed 's/.*| //' < in ``` I would expect to see only the `X` and `Y`, as I've asked to remove ALL chars up to the `'|'` and space beyond it. Instead, I get: ``` X<br> Gras Och Stenar Trad - From M? Y ``` I know I can use tr to remove the International chars. first, but is there a way to just use sed?
I think the error occurs if the input encoding of the file is different from the preferred encoding of your environment. Example: `in` is UTF-8 ``` $ LANG=de_DE.UTF-8 sed 's/.*| //' < in X Y $ LANG=de_DE.iso88591 sed 's/.*| //' < in X Y ``` UTF-8 can safely be interpreted as ISO-8859-1, you'll get strange characters but apart from that everything is fine. Example: `in` is ISO-8859-1 ``` $ LANG=de_DE.UTF-8 sed 's/.*| //' < in X Gras Och Stenar Trad - From MöY $ LANG=de_DE.iso88591 sed 's/.*| //' < in X Y ``` ISO-8859-1 cannot be interpreted as UTF-8, decoding the input file fails. The strange match is probably due to the fact that sed tries to recover rather than fail completely. The answer is based on Debian Lenny/Sid and sed 4.1.5.
67,418
<p>I have a "watcher" module that is currently using global hierarchies inside it. I need to instantiate a second instance of this with a second global hierarchy.</p> <p>Currently:</p> <pre><code>module watcher; wire sig = `HIER.sig; wire bar = `HIER.foo.bar; ... endmodule watcher w; // instantiation </code></pre> <p>Desired:</p> <pre><code>module watcher(input base_hier); wire sig = base_hier.sig; wire bar = base_hier.foo.bar; ... endmodule watcher w1(`HIER1); // instantiation watcher w2(`HIER2); // second instantiation, except with a different hierarchy </code></pre> <p>My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?</p>
[ { "answer_id": 68376, "author": "DMC", "author_id": 3148, "author_profile": "https://Stackoverflow.com/users/3148", "pm_score": 3, "selected": false, "text": "<p>My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no...
2008/09/15
[ "https://Stackoverflow.com/questions/67418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598/" ]
I have a "watcher" module that is currently using global hierarchies inside it. I need to instantiate a second instance of this with a second global hierarchy. Currently: ``` module watcher; wire sig = `HIER.sig; wire bar = `HIER.foo.bar; ... endmodule watcher w; // instantiation ``` Desired: ``` module watcher(input base_hier); wire sig = base_hier.sig; wire bar = base_hier.foo.bar; ... endmodule watcher w1(`HIER1); // instantiation watcher w2(`HIER2); // second instantiation, except with a different hierarchy ``` My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?
My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no other functionality. All other modules in your testbench that require probes then connect to that "probe module". Use SystemVerilog interfaces in preference to raw wires if that's an option for you. This circumvents your problem since no watcher will require global hierarchies and your testbench on the whole will be considerably easier to maintain. See the [Law of Demeter](http://en.wikipedia.org/wiki/Law_of_Demeter "Law of Demeter"). Alternatively... (but this puts hierarchy in your instantiations...) ``` module watcher(sig, bar); input sig; input bar; ... endmodule watcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation watcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy ``` Subsequently you can also: ``` `define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig) `WATCHER_INST(w1, `HIER1); `WATCHER_INST(w2, `HIER2); ```
67,492
<p>Let's say the first N integers divisible by 3 starting with 9.</p> <p>I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.</p>
[ { "answer_id": 67552, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>I can't say this is any good, I'm not a C# expert and I just whacked it out, but I think it's probably a canonica...
2008/09/15
[ "https://Stackoverflow.com/questions/67492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Let's say the first N integers divisible by 3 starting with 9. I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.
Just to be different (and to avoid using a where statement) you could also do: ``` var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9); ``` **Update** This also has the benefit of not running out of numbers.
67,518
<p>I am trying to get the <code>Edit with Vim</code> context menu to open files in a new tab of the previously opened Gvim instance (if any).</p> <p>Currently, using <code>Regedit</code> I have modified this key:</p> <pre><code>\HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*" </code></pre> <p>The registry key type is <code>REG_SZ</code>.</p> <p>This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled <code>\W\S\--literal</code> and the file seems to be trying to open the following file. </p> <pre><code>C:\Windows\System32\--literal </code></pre> <p>I think the problem is around the <code>"%*"</code> - I tried changing that to <code>"%1"</code> but if i do that I get an extra tab called <code>%1</code>.</p> <p><strong>Affected version</strong></p> <ul> <li>Vim version 7.2 (same behaviour on 7.1) </li> <li>Windows vista home premium</li> </ul> <p>Thanks for any help. </p> <p>David. </p>
[ { "answer_id": 69920, "author": "kobusb", "author_id": 1620, "author_profile": "https://Stackoverflow.com/users/1620", "pm_score": 4, "selected": true, "text": "<p>Try setting it to: \"C:\\Programs\\Vim \\vim72\\gvim.exe\" -p --remote-tab-silent \"%1\" \"%*\"</p>\n\n<p>See: <a href=\"htt...
2008/09/15
[ "https://Stackoverflow.com/questions/67518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10171/" ]
I am trying to get the `Edit with Vim` context menu to open files in a new tab of the previously opened Gvim instance (if any). Currently, using `Regedit` I have modified this key: ``` \HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*" ``` The registry key type is `REG_SZ`. This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled `\W\S\--literal` and the file seems to be trying to open the following file. ``` C:\Windows\System32\--literal ``` I think the problem is around the `"%*"` - I tried changing that to `"%1"` but if i do that I get an extra tab called `%1`. **Affected version** * Vim version 7.2 (same behaviour on 7.1) * Windows vista home premium Thanks for any help. David.
Try setting it to: "C:\Programs\Vim \vim72\gvim.exe" -p --remote-tab-silent "%1" "%\*" See: <http://www.vim.org/tips/tip.php?tip_id=1314> EDIT: As pointed out by Thomas, vim.org tips moved to: <http://vim.wikia.com/> See: <http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows>
67,561
<p>The <a href="http://en.wikipedia.org/wiki/Law_Of_Demeter" rel="noreferrer">wikipedia article</a> about <a href="http://c2.com/cgi/wiki?LawOfDemeter" rel="noreferrer">Law of Demeter</a> says:</p> <blockquote> <p>The law can be stated simply as "use only one dot".</p> </blockquote> <p>However a <a href="http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx" rel="noreferrer">simple example</a> of a <a href="http://en.wikipedia.org/wiki/Fluent_interface" rel="noreferrer">fluent interface</a> may look like this:</p> <pre><code>static void Main(string[] args) { new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png"); } </code></pre> <p>So does this goes together?</p>
[ { "answer_id": 67593, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>Yes, although you have to apply some pragmatism to the situation. I always take the Law of Demeter as a guideline as o...
2008/09/15
[ "https://Stackoverflow.com/questions/67561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
The [wikipedia article](http://en.wikipedia.org/wiki/Law_Of_Demeter) about [Law of Demeter](http://c2.com/cgi/wiki?LawOfDemeter) says: > > The law can be stated simply as "use only one dot". > > > However a [simple example](http://weblogs.asp.net/jgalloway/archive/2006/12/06/a-simple-example-of-a-fluent-interface.aspx) of a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface) may look like this: ``` static void Main(string[] args) { new ZRLabs.Yael.Pipeline("cat.jpg") .Rotate(90) .Watermark("Monkey") .RoundCorners(100, Color.Bisque) .Save("test.png"); } ``` So does this goes together?
Well, the short definition of the law shortens it too much. The real "law" (in reality advice on good API design) basically says: Only access objects you created yourself, or were passed to you as an argument. Do not access objects indirectly through other objects. Methods of fluent interfaces often return the object itself, so they don't violate the law, if you use the object again. Other methods create objects for you, so there's no violation either. Also note that the "law" is only a best practices advice for "classical" APIs. Fluent interfaces are a completely different approach to API design and can't be evaluated with the Law of Demeter.
67,612
<p>In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?</p>
[ { "answer_id": 67642, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 3, "selected": true, "text": "<p>Using jQuery, it's as simple as:</p>\n\n<pre><code>$(\"a\").each(function() {\n var link = $(this);\n var top = link.offs...
2008/09/15
[ "https://Stackoverflow.com/questions/67612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ]
In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?
Using jQuery, it's as simple as: ``` $("a").each(function() { var link = $(this); var top = link.offset().top; var left = link.offset().left; var width = link.offset.width(); var height = link.offset.height(); }); ```
67,631
<p>How do I load a Python module given its full path?</p> <p>Note that the file can be anywhere in the filesystem where the user has access rights.</p> <hr /> <p><sub><strong>See also:</strong> <a href="https://stackoverflow.com/questions/301134">How to import a module given its name as string?</a></sub></p>
[ { "answer_id": 67672, "author": "Matt", "author_id": 10035, "author_profile": "https://Stackoverflow.com/users/10035", "pm_score": 3, "selected": false, "text": "<p>I believe you can use <a href=\"https://docs.python.org/2/library/imp.html#imp.find_module\" rel=\"noreferrer\"><code>imp.f...
2008/09/15
[ "https://Stackoverflow.com/questions/67631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286/" ]
How do I load a Python module given its full path? Note that the file can be anywhere in the filesystem where the user has access rights. --- **See also:** [How to import a module given its name as string?](https://stackoverflow.com/questions/301134)
For Python 3.5+ use ([docs](https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly)): ``` import importlib.util import sys spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) sys.modules["module.name"] = foo spec.loader.exec_module(foo) foo.MyClass() ``` For Python 3.3 and 3.4 use: ``` from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module.name", "/path/to/file.py").load_module() foo.MyClass() ``` (Although this has been deprecated in Python 3.4.) For Python 2 use: ``` import imp foo = imp.load_source('module.name', '/path/to/file.py') foo.MyClass() ``` There are equivalent convenience functions for compiled Python files and DLLs. See also <http://bugs.python.org/issue21436>.
67,676
<p>How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?</p>
[ { "answer_id": 67696, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": true, "text": "<p>The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Loca...
2008/09/15
[ "https://Stackoverflow.com/questions/67676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
How can I use .NET DataSet.Select method to search records that match a DateTime? What format should I use to enter my dates in?
The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals. ``` ds.select(DBDate = '15 Sep 2008') ``` You can use the DateFormat function to convert to long date format as well and this will work fine too.
67,682
<p>I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that?</p> <p>I'm a DOM Newbie so I don't know too much about how to do this. </p> <p>Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari</p> <p>Added: I'm using a program called JQuery to help me learn</p>
[ { "answer_id": 67697, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": -1, "selected": false, "text": "<p>you can use offsetLeft and offsetTop</p>\n" }, { "answer_id": 67717, "author": "Lucas Oman", "author_id": ...
2008/09/15
[ "https://Stackoverflow.com/questions/67682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that? I'm a DOM Newbie so I don't know too much about how to do this. Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari Added: I'm using a program called JQuery to help me learn
To get the x-y location of where a user clicked on a page, use the following jQuery code: ``` <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $("#special").click(function(e){ $('#status2').html(e.pageX +', '+ e.pageY); }); }); </script> </head> <body> <h2 id="status2"> 0, 0 </h2> <div style="width: 100px; height: 100px; background:#ccc;" id="special"> Click me anywhere! </div> </body> </html> ```
67,685
<p>I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row.</p> <p>That should be easy enough, right? There's even a full code example in the <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">ffmpeg FAQ</a>.</p> <p>Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays <a href="http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv" rel="noreferrer">extremely fast</a>. The example script thus becomes:</p> <pre><code>ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - &gt; temp.a &lt; /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - &gt; temp.v &lt; /dev/null cat temp.v temp.v &gt; all.v cat temp.a temp.a &gt; all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv </code></pre> <p>Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5.</p> <p>a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting?</p> <p>b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed?</p> <p>The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs:</p> <pre><code>mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv </code></pre> <p>I get a Floating point exception...</p> <pre><code>MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception </code></pre> <p>c) Is there a way for mencoder to decode and encode flvs correctly?</p> <p>So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis:</p> <pre><code>ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv </code></pre> <p>d) There must be a better way to achieve this... Which one?</p> <p>e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">facebook</a>) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like <a href="http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv" rel="noreferrer">this one</a> or <a href="http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv" rel="noreferrer">this one</a>). Is there a way to do this for these flvs too?</p> <p>Any help would be very appreciated.</p>
[ { "answer_id": 70991, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 0, "selected": false, "text": "<p>You'll encounter a very subtle problem here because most video and audio formats (especially in ordinary containers...
2008/09/15
[ "https://Stackoverflow.com/questions/67685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8279/" ]
I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row. That should be easy enough, right? There's even a full code example in the [ffmpeg FAQ](http://ffmpeg.mplayerhq.hu/faq.html#SEC31). Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays [extremely fast](http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv). The example script thus becomes: ``` ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - > temp.a < /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - > temp.v < /dev/null cat temp.v temp.v > all.v cat temp.a temp.a > all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv ``` Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5. a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting? b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed? The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs: ``` mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv ``` I get a Floating point exception... ``` MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception ``` c) Is there a way for mencoder to decode and encode flvs correctly? So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis: ``` ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv ``` d) There must be a better way to achieve this... Which one? e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through [facebook](http://ffmpeg.mplayerhq.hu/faq.html#SEC31)) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like [this one](http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv) or [this one](http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv)). Is there a way to do this for these flvs too? Any help would be very appreciated.
I thought it would be a nice learning exercise to rewrite it in Ruby. It was. Six months later and three gems later, [here's the released product](http://github.com/marcandre/flvedit). I'll still be working a bit on it, but it works.
67,699
<p>My <code>master</code> and <code>development</code> branches are tracked remotely on <a href="http://en.wikipedia.org/wiki/GitHub" rel="noreferrer">GitHub</a>. How do I clone both these branches?</p>
[ { "answer_id": 67712, "author": "MattoxBeckman", "author_id": 10354, "author_profile": "https://Stackoverflow.com/users/10354", "pm_score": 5, "selected": false, "text": "<p>A <code>git clone</code> is supposed to copy the entire repository. Try cloning it, and then run <code>git branch...
2008/09/15
[ "https://Stackoverflow.com/questions/67699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
My `master` and `development` branches are tracked remotely on [GitHub](http://en.wikipedia.org/wiki/GitHub). How do I clone both these branches?
First, clone a remote [Git](http://en.wikipedia.org/wiki/Git_%28software%29) repository and [`cd`](http://en.wikipedia.org/wiki/Cd_%28command%29) into it: ``` $ git clone git://example.com/myproject $ cd myproject ``` Next, look at the local branches in your repository: ``` $ git branch * master ``` But there are other branches hiding in your repository! See these using the `-a` flag: ``` $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental ``` To take a quick peek at an upstream branch, check it out directly: ``` $ git checkout origin/experimental ``` To work on that branch, create a local tracking branch, which is done automatically by: ``` $ git checkout experimental Branch experimental set up to track remote branch experimental from origin. Switched to a new branch 'experimental' ``` Here, "new branch" simply means that the branch is taken from the index and created locally for you. As the *previous* line tells you, the branch is being set up to track the remote branch, which usually means the origin/branch\_name branch. Your local branches should now show: ``` $ git branch * experimental master ``` You can track more than one remote repository using `git remote`: ``` $ git remote add win32 git://example.com/users/joe/myproject-win32-port $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/v1.0-stable remotes/origin/experimental remotes/win32/master remotes/win32/new-widgets ``` At this point, things are getting pretty crazy, so run `gitk` to see what's going on: ``` $ gitk --all & ```
67,713
<p>In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience.</p> <p>I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So...</p> <p>Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?</p>
[ { "answer_id": 67897, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 0, "selected": false, "text": "<p>At it's very basic level it will be using <code>createElement</code> to create the elements to insert into the page and...
2008/09/15
[ "https://Stackoverflow.com/questions/67713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10155/" ]
In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience. I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So... Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?
Aupajo has it right. I will, however, point you towards a bookmarklet framework I worked up for our site ([www.iminta.com](http://www.iminta.com)). The bookmarklet itself reads as follows: ``` javascript:void((function(){ var e=document.createElement('script'); e.setAttribute('type','text/javascript'); e.setAttribute('src','http://www.iminta.com/javascripts/new_bookmarklet.js?noCache='+new%20Date().getTime()); document.body.appendChild(e) })()) ``` This just injects a new script into the document that includes this file: <http://www.iminta.com/javascripts/new_bookmarklet.js> It's important to note that the bookmarklet creates an iframe, positions it, and adds events to the document to allow the user to do things like hit escape (to close the window) or to scroll (so it stays visible). It also hides elements that don't play well with z-positioning (flash, for example). Finally, it facilitates communicating across to the javascript that is running within the iframe. In this way, you can have a close button in the iframe that tells the parent document to remove the iframe. This kind of cross-domain stuff is a bit hacky, but it's the only way (I've seen) to do it. Not for the feint of heart; if you're not good at JavaScript, prepare to struggle.
67,734
<p>I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code.</p> <p>It's easier to define things that I'm not trying to do:</p> <ul> <li><p>I'm not trying to call a JavaScript function on a web page from my code behind.</p></li> <li><p>I'm not trying to load a WebBrowser control.</p></li> <li><p>I don't want to have the JavaScript perform an AJAX call to a server.</p></li> </ul> <p>What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task.</p> <p>I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas?</p> <p>update: <a href="http://blogs.msdn.com/brada/articles/239857.aspx" rel="nofollow noreferrer">From Brad Abrams blog</a></p> <pre><code>namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. " + "Please see the ICodeCompiler documentation for additional help. " + "http://go.microsoft.com/fwlink/?linkid=14202")] </code></pre> <p>Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.</p>
[ { "answer_id": 67755, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>You can use the Microsoft Javascript engine for <a href=\"http://www.west-wind.com/WebLog/posts/10688.aspx\" rel=\"no...
2008/09/15
[ "https://Stackoverflow.com/questions/67734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
I'd like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code. It's easier to define things that I'm not trying to do: * I'm not trying to call a JavaScript function on a web page from my code behind. * I'm not trying to load a WebBrowser control. * I don't want to have the JavaScript perform an AJAX call to a server. What I want to do is write unit tests in JavaScript and have then unit tests output JSON, even plain text would be fine. Then I want to have a generic C# class/executible that can load the file containing the JS, run the JS unit tests, scrap/load the results, and return a pass/fail with details during a post-build task. I think it's possible using the old ActiveX ScriptControl, but it seems like there ought to be a .NET way to do this without using SilverLight, the DLR, or anything else that hasn't shipped yet. Anyone have any ideas? update: [From Brad Abrams blog](http://blogs.msdn.com/brada/articles/239857.aspx) ``` namespace Microsoft.JScript.Vsa { [Obsolete("There is no replacement for this feature. " + "Please see the ICodeCompiler documentation for additional help. " + "http://go.microsoft.com/fwlink/?linkid=14202")] ``` Clarification: We have unit tests for our JavaScript functions that are written in JavaScript using the JSUnit framework. Right now during our build process, we have to manually load a web page and click a button to ensure that all of the JavaScript unit tests pass. I'd like to be able to execute the tests during the post-build process when our automated C# unit tests are run and report the success/failure alongside of out C# unit tests and use them as an indicator as to whether or not the build is broken.
You can run your JSUnit from inside Nant using the JSUnit server, it's written in java and there is not a Nant task but you can run it from the command prompt, the results are logged as XML and you can them integrate them with your build report process. This won't be part of your Nunit result but an extra report. We fail the build if any of those test fails. We are doing exactly that using CC.Net.
67,760
<p>Has anyone got <a href="http://perldoc.perl.org/Sys/Syslog.html" rel="nofollow noreferrer">Sys::Syslog</a> to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me:</p> <pre><code>openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; </code></pre> <p>Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.</p>
[ { "answer_id": 68121, "author": "rjbs", "author_id": 10478, "author_profile": "https://Stackoverflow.com/users/10478", "pm_score": 2, "selected": false, "text": "<p>By default, Sys::Syslog is going to try to connect with one of the following socket types:</p>\n\n<pre><code>[ 'tcp', 'udp'...
2008/09/15
[ "https://Stackoverflow.com/questions/67760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Has anyone got [Sys::Syslog](http://perldoc.perl.org/Sys/Syslog.html) to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me: ``` openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; ``` Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.
By default, Sys::Syslog is going to try to connect with one of the following socket types: ``` [ 'tcp', 'udp', 'unix', 'stream' ] ``` On Solaris, though, you'll need to use an inet socket. Call: ``` setlogsock('inet', $hostname); ``` and things should start working.
67,761
<p>Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background.</p> <p>This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network).</p> <pre><code> bool done; void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); done = false; ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns); while (done == false) Thread.Sleep(10); }   public void myWriteCallBack(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; ns.EndWrite(ar); done = true; } </code></pre> <p>How can I tell when the data has actually been sent to the client?</p> <p>I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card.</p> <p>The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond.</p> <p>I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?</p>
[ { "answer_id": 67773, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 0, "selected": false, "text": "<p>How about using the Flush() method.</p>\n\n<pre><code>ns.Flush()\n</code></pre>\n\n<p>That should ensure the data is writt...
2008/09/15
[ "https://Stackoverflow.com/questions/67761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4495/" ]
Despite the documentation, NetworkStream.Write does not appear to wait until the data has been sent. Instead, it waits until the data has been copied to a buffer and then returns. That buffer is transmitted in the background. This is the code I have at the moment. Whether I use ns.Write or ns.BeginWrite doesn't matter - both return immediately. The EndWrite also returns immediately (which makes sense since it is writing to the send buffer, not writing to the network). ``` bool done; void SendData(TcpClient tcp, byte[] data) { NetworkStream ns = tcp.GetStream(); done = false; ns.BeginWrite(bytWriteBuffer, 0, data.Length, myWriteCallBack, ns); while (done == false) Thread.Sleep(10); } public void myWriteCallBack(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; ns.EndWrite(ar); done = true; } ``` How can I tell when the data has actually been sent to the client? I want to wait for 10 seconds(for example) for a response from the server after sending my data otherwise I'll assume something was wrong. If it takes 15 seconds to send my data, then it will always timeout since I can only start counting from when NetworkStream.Write returns - which is before the data has been sent. I want to start counting 10 seconds from when the data has left my network card. The amount of data and the time to send it could vary - it could take 1 second to send it, it could take 10 seconds to send it, it could take a minute to send it. The server does send an response when it has received the data (it's a smtp server), but I don't want to wait forever if my data was malformed and the response will never come, which is why I need to know if I'm waiting for the data to be sent, or if I'm waiting for the server to respond. I might want to show the status to the user - I'd like to show "sending data to server", and "waiting for response from server" - how could I do that?
I'm not a C# programmer, but the way you've asked this question is slightly misleading. The only way to know when your data has been "received", for any useful definition of "received", is to have a specific acknowledgment message in your protocol which indicates the data has been fully processed. The data does not "leave" your network card, exactly. The best way to think of your program's relationship to the network is: > > your program -> lots of confusing stuff -> the peer program > > > A list of things that might be in the "lots of confusing stuff": * the CLR * the operating system kernel * a virtualized network interface * a switch * a software firewall * a hardware firewall * a router performing network address translation * a router on the peer's end performing network address translation So, if you are on a virtual machine, which is hosted under a different operating system, that has a software firewall which is controlling the virtual machine's network behavior - when has the data "really" left your network card? Even in the best case scenario, many of these components may drop a packet, which your network card will need to re-transmit. Has it "left" your network card when the first (unsuccessful) attempt has been made? Most networking APIs would say no, it hasn't been "sent" until the other end has sent a TCP acknowledgement. That said, [the documentation for NetworkStream.Write](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write.aspx) seems to indicate that it will not return until it has at least initiated the 'send' operation: > > The Write method blocks until the requested number of bytes is sent or a SocketException is thrown. > > > Of course, "is sent" is somewhat vague for the reasons I gave above. There's also the possibility that the data will be "really" sent by your program and received by the peer program, but the peer will crash or otherwise not actually process the data. So you should do a `Write` followed by a `Read` of a message that will only be emitted by your peer when it has actually processed the message.
67,790
<p>I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication.</p> <p>I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...</p>
[ { "answer_id": 67809, "author": "JohnnyLambada", "author_id": 9648, "author_profile": "https://Stackoverflow.com/users/9648", "pm_score": 0, "selected": false, "text": "<p>One way to do this is to have a type field as the first byte of the structure. Your receiving function looks at thi...
2008/09/15
[ "https://Stackoverflow.com/questions/67790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10394/" ]
I have some code with multiple functions very similar to each other to look up an item in a list based on the contents of one field in a structure. The only difference between the functions is the type of the structure that the look up is occurring in. If I could pass in the type, I could remove all the code duplication. I also noticed that there is some mutex locking happening in these functions as well, so I think I might leave them alone...
If you ensure that the field is placed in the same place in each such structure, you can simply cast a pointer to get at the field. This technique is used in lots of low level system libraries e.g. BSD sockets. ``` struct person { int index; }; struct clown { int index; char *hat; }; /* we're not going to define a firetruck here */ struct firetruck; struct fireman { int index; struct firetruck *truck; }; int getindexof(struct person *who) { return who->index; } int main(int argc, char *argv[]) { struct fireman sam; /* somehow sam gets initialised */ sam.index = 5; int index = getindexof((struct person *) &sam); printf("Sam's index is %d\n", index); return 0; } ``` You lose type safety by doing this, but it's a valuable technique. [ I have now actually tested the above code and fixed the various minor errors. It's much easier when you have a compiler. ]
67,798
<p>I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". <code>^From:\s*(.*)$</code> works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line).</p> <pre> Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! </pre>
[ { "answer_id": 67840, "author": "Sebastian Redl", "author_id": 8922, "author_profile": "https://Stackoverflow.com/users/8922", "pm_score": 0, "selected": false, "text": "<p>Writing complicated regular expressions for such jobs is a bad idea IMO. It's better to combine several simple quer...
2008/09/15
[ "https://Stackoverflow.com/questions/67798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392/" ]
I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". `^From:\s*(.*)$` works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line). ``` Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! ```
I'm not sure of the syntax of C# regular expressions but you should have a way to anchor to the beginning of the string (not the beginning of the line such as ^). I'll call that "\A" in my example: ``` \A.*?\r?\n\r?\n.*?^From:\s*([^\r\n]+)$ ``` Make sure you turn the multiline matching option on, however that works, to make "." match \n
67,819
<p>In php, how can I get the number of apache children that are currently available <br>(<code>status = SERVER_READY</code> in the apache scoreboard)?</p> <p>I'm really hoping there is a simple way to do this in php that I am missing.</p>
[ { "answer_id": 67832, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>You could execute a shell command of <code>ps aux | grep httpd</code> or <code>ps aux | grep apache</code> and coun...
2008/09/15
[ "https://Stackoverflow.com/questions/67819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In php, how can I get the number of apache children that are currently available (`status = SERVER_READY` in the apache scoreboard)? I'm really hoping there is a simple way to do this in php that I am missing.
You could execute a shell command of `ps aux | grep httpd` or `ps aux | grep apache` and count the number of lines in the output. ``` exec('ps aux | grep apache', $output); $processes = count($output); ``` I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.
67,835
<p>Using VBA, how can I:</p> <ol> <li>test whether a file exists, and if so,</li> <li>delete it?</li> </ol>
[ { "answer_id": 67853, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": false, "text": "<p>In VB its normally <code>Dir</code> to find the directory of the file. If it's not blank then it exists and then use <co...
2008/09/15
[ "https://Stackoverflow.com/questions/67835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
Using VBA, how can I: 1. test whether a file exists, and if so, 2. delete it?
1.) Check [here](http://www.tek-tips.com/faqs.cfm?fid=1936). Basically do this: ``` Function FileExists(ByVal FileToTest As String) As Boolean FileExists = (Dir(FileToTest) <> "") End Function ``` I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering: * Check for an empty string being passed. * Check for a string containing characters illegal in a file name/path 2.) How To Delete a File. Look at [this.](http://word.mvps.org/faqs/macrosvba/DeleteFiles.htm) Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you: ``` Sub DeleteFile(ByVal FileToDelete As String) If FileExists(FileToDelete) Then 'See above ' First remove readonly attribute, if set SetAttr FileToDelete, vbNormal ' Then delete the file Kill FileToDelete End If End Sub ``` Again, I'll leave the error handling to you and again these are the things I'd consider: * Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory? * Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set? --- EDIT: Marking this answer as community wiki so anyone can modify it if need be.
67,859
<p>I am trying to create a query string of variable assignments separated by the <code>&amp;</code> symbol (ex: <code>"var1=x&amp;var2=y&amp;..."</code>). I plan to pass this string into an embedded flash file.</p> <p>I am having trouble getting an <code>&amp;</code> symbol to show up in XSLT. If I just type <code>&amp;</code> with no tags around it, there is a problem rendering the XSLT document. If I type <code>&amp;amp;</code> with no tags around it, then the output of the document is <code>&amp;amp;</code> with no change. If I type <code>&lt;xsl:value-of select="&amp;" /&gt;</code> or <code>&lt;xsl:value-of select="&amp;amp;" /&gt;</code> I also get an error. Is this possible? Note: I have also tried <code>&amp;amp;amp;</code> with no success.</p>
[ { "answer_id": 67876, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 3, "selected": false, "text": "<p>Use <code>disable-output-escaping=\"yes\"</code> in your <code>value-of</code> tag</p>\n" }, { "answer_id": 67886...
2008/09/15
[ "https://Stackoverflow.com/questions/67859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to create a query string of variable assignments separated by the `&` symbol (ex: `"var1=x&var2=y&..."`). I plan to pass this string into an embedded flash file. I am having trouble getting an `&` symbol to show up in XSLT. If I just type `&` with no tags around it, there is a problem rendering the XSLT document. If I type `&amp;` with no tags around it, then the output of the document is `&amp;` with no change. If I type `<xsl:value-of select="&" />` or `<xsl:value-of select="&amp;" />` I also get an error. Is this possible? Note: I have also tried `&amp;amp;` with no success.
You can combine `disable-output-escaping` with a `CDATA` section. Try this: ``` <xsl:text disable-output-escaping="yes"><![CDATA[&]]></xsl:text> ```
67,890
<p>I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores.</p> <p>Any suggestions on the best way to solve this problem?</p> <p>Thanks!</p>
[ { "answer_id": 67900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://ruby-doc.org/stdlib/libdoc/digest/rdoc/index.html\" rel=\"nofollow noreferrer\">Digest::MD5</a> from Ru...
2008/09/15
[ "https://Stackoverflow.com/questions/67890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10461/" ]
I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores. Any suggestions on the best way to solve this problem? Thanks!
Depending on how long a string you would like you can use a few alternatives: ``` require 'digest' Digest.hexencode('http://foo-bar.com/yay/?foo=bar&a=22') # "687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232" require 'digest/md5' Digest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "43facc5eb5ce09fd41a6b55dba3fe2fe" require 'digest/sha1' Digest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5" require 'digest/sha2' Digest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22') # "e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2" ``` Note that this won't be unguessable, you may have to combine it with some other (secret but static) data to salt the string: ``` salt = 'foobar' Digest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&a=22') # "dbf43aff5e808ae471aa1893c6ec992088219bbb" ``` Now it becomes much harder to generate this hash for someone who doesn't know the original content and has no access to your source.
67,894
<p>Why do we need to use:</p> <pre><code>extern "C" { #include &lt;foo.h&gt; } </code></pre> <p><strong>Specifically:</strong> </p> <ul> <li><p>When should we use it?</p></li> <li><p>What is happening at the compiler/linker level that requires us to use it? </p></li> <li><p>How in terms of compilation/linking does this solve the problems which require us to use it?</p></li> </ul>
[ { "answer_id": 67919, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": false, "text": "<p>It has to do with the way the different compilers perform name-mangling. A C++ compiler will mangle the name of a...
2008/09/15
[ "https://Stackoverflow.com/questions/67894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
Why do we need to use: ``` extern "C" { #include <foo.h> } ``` **Specifically:** * When should we use it? * What is happening at the compiler/linker level that requires us to use it? * How in terms of compilation/linking does this solve the problems which require us to use it?
C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data. (To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling `printf()` without flagging the prototype as a C function, the C++ will actually generate code calling `_Zprintf`, plus extra crap at the end.) So: use `extern "C" {...}` when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the `extern` because most system C headers will already account for the fact that they might be included by C++ code and already `extern "C"` their code.
67,916
<p>I have something that is driving me absolutely crazy...</p> <pre><code> Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function </code></pre> <p>The line <code>parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))</code> has this error...</p> <blockquote> <p>Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. </p> </blockquote> <p>but I really can't see how it is any different from this code from Rob Connery</p> <pre><code>public IList&lt;Category&gt; GetCategories() { IList&lt;Category&gt; rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p =&gt; { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; } </code></pre> <p>which compiles perfectly... what am I doing incorrectly?</p>
[ { "answer_id": 68795, "author": "Jeff Moser", "author_id": 1869, "author_profile": "https://Stackoverflow.com/users/1869", "pm_score": 0, "selected": false, "text": "<p>I haven't used VB.NET since moving to C# 3.0, but it seems like it could be a type inference issue. The error is a bit ...
2008/09/15
[ "https://Stackoverflow.com/questions/67916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10479/" ]
I have something that is driving me absolutely crazy... ``` Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function ``` The line `parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))` has this error... > > Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. > > > but I really can't see how it is any different from this code from Rob Connery ``` public IList<Category> GetCategories() { IList<Category> rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p => { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; } ``` which compiles perfectly... what am I doing incorrectly?
Lambda's in VB.Net have to return a value, so your equal sign ('=') is being intepreted as a comparison (so that the lambda returns a boolean), rather than an assignment.
67,959
<p>I've run into a few gotchas when doing C# XML serialization that I thought I'd share:</p> <ul> <li>You can't serialize items that are read-only (like KeyValuePairs)</li> <li>You can't serialize a generic dictionary. Instead, try this wrapper class (from <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx" rel="noreferrer">http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx</a>):</li> </ul> <hr/> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } </code></pre> <p>Any other XML Serialization gotchas out there?</p>
[ { "answer_id": 68005, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 2, "selected": false, "text": "<p>Private variables/properties are not serialized in the default mechanism for XML serialization, but are in binary s...
2008/09/15
[ "https://Stackoverflow.com/questions/67959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
I've run into a few gotchas when doing C# XML serialization that I thought I'd share: * You can't serialize items that are read-only (like KeyValuePairs) * You can't serialize a generic dictionary. Instead, try this wrapper class (from <http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx>): --- ``` using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } ``` Any other XML Serialization gotchas out there?
I can't make comments yet, so I will comment on Dr8k's post and make another observation. Private variables that are exposed as public getter/setter properties, and do get serialized/deserialized as such through those properties. We did it at my old job al the time. One thing to note though is that if you have any logic in those properties, the logic is run, so sometimes, the order of serialization actually matters. The members are *implicitly* ordered by how they are ordered in the code, but there are no guarantees, especially when you are inheriting another object. Explicitly ordering them is a pain in the rear. I've been burnt by this in the past.
68,012
<p>I am relatively new to JavaScript and am trying to understand how to use it correctly.</p> <p>If I wrap JavaScript code in an anonymous function to avoid making variables <code>public</code> the functions within the JavaScript are not available from within the html that includes the JavaScript. </p> <p>On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using <code>httprequest</code> to get that from a PHP file and passes the returned data to a callback function that in <em>onsuccess</em> processes the data, if I could call the function that does the <code>httprequest</code> from within the html in a </p> <pre><code>&lt;script type="text/javascript" &gt;&lt;/script&gt; </code></pre> <p>block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.</p>
[ { "answer_id": 68026, "author": "HitScan", "author_id": 9490, "author_profile": "https://Stackoverflow.com/users/9490", "pm_score": 0, "selected": false, "text": "<p>It might be best not to wrap everything in an anonymous function and just hope that it is executed. You could name the fun...
2008/09/15
[ "https://Stackoverflow.com/questions/68012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am relatively new to JavaScript and am trying to understand how to use it correctly. If I wrap JavaScript code in an anonymous function to avoid making variables `public` the functions within the JavaScript are not available from within the html that includes the JavaScript. On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using `httprequest` to get that from a PHP file and passes the returned data to a callback function that in *onsuccess* processes the data, if I could call the function that does the `httprequest` from within the html in a ``` <script type="text/javascript" ></script> ``` block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.
If you aren't using a javascript framework, I strongly suggest it. I use MooTools, but there are many others that are very solid (Prototype, YUI, jQuery, etc). These include methods for attaching functionality to the DomReady event. The problem with: ``` window.onload = function(){...}; ``` is that you can only ever have one function attached to that event (subsequent assignments will overwrite this one). Frameworks provide more appropriate methods for doing this. For example, in MooTools: ``` window.addEvent('domready', function(){...}); ``` Finally, there are other ways to avoid polluting the global namespace. Just namespacing your own code (mySite.foo = function...) will help you avoid any potential conflicts. One more thing. I'm not 100% sure from your comment that the problem you have is specific to the page load event. Are you saying that the code needs to be executed when the ajax returns as well? Please edit your question if this is the case.
68,018
<p>If I have a Resource bundle property file:</p> <p>A.properties:</p> <pre><code>thekey={0} This is a test </code></pre> <p>And then I have java code that loads the resource bundle:</p> <pre><code>ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale); labels.getString("thekey"); </code></pre> <p>How can I replace the {0} text with some value</p> <pre><code>labels.getString("thekey", "Yes!!!"); </code></pre> <p>Such that the output comes out as:</p> <pre><code>Yes!!! This is a test. </code></pre> <p>There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.</p>
[ { "answer_id": 68075, "author": "user10544", "author_id": 10544, "author_profile": "https://Stackoverflow.com/users/10544", "pm_score": 5, "selected": true, "text": "<p>The class you're looking for is java.text.MessageFormat; specifically, calling</p>\n\n<pre><code>MessageFormat.format(\...
2008/09/15
[ "https://Stackoverflow.com/questions/68018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
If I have a Resource bundle property file: A.properties: ``` thekey={0} This is a test ``` And then I have java code that loads the resource bundle: ``` ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale); labels.getString("thekey"); ``` How can I replace the {0} text with some value ``` labels.getString("thekey", "Yes!!!"); ``` Such that the output comes out as: ``` Yes!!! This is a test. ``` There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.
The class you're looking for is java.text.MessageFormat; specifically, calling ``` MessageFormat.format("{0} This {1} a test", new Object[] {"Yes!!!", "is"}); ``` or ``` MessageFormat.format("{0} This {1} a test", "Yes!!!", "is"); ``` will return ``` "Yes!!! This is a test" ``` [Unfortunately, I can't help with the Struts connection, although [this](http://www.jguru.com/faq/view.jsp?EID=915891) looks relevant.]
68,042
<p>Let's say that on the C++ side my function takes a variable of type <code>jstring</code> named <code>myString</code>. I can convert it to an ANSI string as follows:</p> <pre><code>const char* ansiString = env-&gt;GetStringUTFChars(myString, 0); </code></pre> <p>is there a way of getting</p> <p><code>const wchar_t* unicodeString =</code> ...</p>
[ { "answer_id": 68065, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>A portable and robust solution is to use <a href=\"http://www.gnu.org/software/libiconv/\" rel=\"nofollow noreferrer\">ico...
2008/09/15
[ "https://Stackoverflow.com/questions/68042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Let's say that on the C++ side my function takes a variable of type `jstring` named `myString`. I can convert it to an ANSI string as follows: ``` const char* ansiString = env->GetStringUTFChars(myString, 0); ``` is there a way of getting `const wchar_t* unicodeString =` ...
If this helps someone... I've used this function for an Android project: ``` std::wstring Java_To_WStr(JNIEnv *env, jstring string) { std::wstring value; const jchar *raw = env->GetStringChars(string, 0); jsize len = env->GetStringLength(string); const jchar *temp = raw; while (len > 0) { value += *(temp++); len--; } env->ReleaseStringChars(string, raw); return value; } ``` An improved solution could be (Thanks for the feedback): ``` std::wstring Java_To_WStr(JNIEnv *env, jstring string) { std::wstring value; const jchar *raw = env->GetStringChars(string, 0); jsize len = env->GetStringLength(string); value.assign(raw, raw + len); env->ReleaseStringChars(string, raw); return value; } ```
68,067
<p>I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file:</p> <p><code>external_link_list_url : "example_link_list.js"</code></p> <p>this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed.</p> <p>Thanks!</p>
[ { "answer_id": 68117, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 0, "selected": false, "text": "<p>If you can't change the file extension (and just return plain text, the caller shouldn't care about the file extension, j...
2008/09/15
[ "https://Stackoverflow.com/questions/68067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173/" ]
I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file: `external_link_list_url : "example_link_list.js"` this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed. Thanks!
I would create an HTTPHandler that responds with the desired data read from the db. Just associate the HTTPHandler with the particular filename 'example\_link\_list.js' in your web-config. Make sure you set ``` context.Response.ContentType = "text/javascript"; ``` then just context.Response.Write(); your list of external links
68,103
<p>I have a XULRunner application that needs to copy image data to the clipboard. I have figured out how to handle copying text to the clipboard, and I can paste PNG data from the clipboard. What I can't figure out is how to get data from a data URL into the clipboard so that it can be pasted into other applications.</p> <p>This is the code I use to copy text (well, XUL):</p> <pre><code>var transferObject=Components.classes["@mozilla.org/widget/transferable;1"]. createInstance(Components.interfaces.nsITransferable); var stringWrapper=Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); var systemClipboard=Components.classes["@mozilla.org/widget/clipboard;1"]. createInstance(Components.interfaces.nsIClipboard); var objToSerialize=aDOMNode; transferObject.addDataFlavor("text/xul"); var xmls=new XMLSerializer(); var serializedObj=xmls.serializeToString(objToSerialize); stringWrapper.data=serializedObj; transferObject.setTransferData("text/xul",stringWrapper,serializedObj.length*2); </code></pre> <p>And, as I said, the data I'm trying to transfer is a PNG as a data URL. So I'm looking for the equivalent to the above that will allow, e.g. Paint.NET to paste my app's data.</p>
[ { "answer_id": 69119, "author": "pc1oad1etter", "author_id": 525, "author_profile": "https://Stackoverflow.com/users/525", "pm_score": 2, "selected": false, "text": "<p>Neal Deakin has an <a href=\"http://developer.mozilla.org/en/Using_the_Clipboard\" rel=\"nofollow noreferrer\">article ...
2008/09/16
[ "https://Stackoverflow.com/questions/68103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
I have a XULRunner application that needs to copy image data to the clipboard. I have figured out how to handle copying text to the clipboard, and I can paste PNG data from the clipboard. What I can't figure out is how to get data from a data URL into the clipboard so that it can be pasted into other applications. This is the code I use to copy text (well, XUL): ``` var transferObject=Components.classes["@mozilla.org/widget/transferable;1"]. createInstance(Components.interfaces.nsITransferable); var stringWrapper=Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); var systemClipboard=Components.classes["@mozilla.org/widget/clipboard;1"]. createInstance(Components.interfaces.nsIClipboard); var objToSerialize=aDOMNode; transferObject.addDataFlavor("text/xul"); var xmls=new XMLSerializer(); var serializedObj=xmls.serializeToString(objToSerialize); stringWrapper.data=serializedObj; transferObject.setTransferData("text/xul",stringWrapper,serializedObj.length*2); ``` And, as I said, the data I'm trying to transfer is a PNG as a data URL. So I'm looking for the equivalent to the above that will allow, e.g. Paint.NET to paste my app's data.
Here's a workaround that I ended up using that solves the problem pretty well. The variable `dataURL` is the image I was trying to get to the clipboard in the first place. ``` var newImg=document.createElement('img'); newImg.src=dataURL; document.popupNode=newImg; var command='cmd_copyImageContents' var controller=document.commandDispatcher.getControllerForCommand(command); if(controller && controller.isCommandEnabled(command)){ controller.doCommand(command); } ``` That copies the image to the clipboard as an 'image/jpg'.
68,120
<p>I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good.</p> <p>However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following:</p> <pre><code>&lt;Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /&gt; &lt;Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /&gt; </code></pre> <p>However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem.</p> <p>Currently:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/&gt; &lt;ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>Replaced with something like:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?</p>
[ { "answer_id": 68140, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 7, "selected": true, "text": "<p>I've had some luck with <a href=\"http://wrapper.tanukisoftware.org/doc/english/introduction.html\" rel=\"noreferrer\">the ...
2008/09/16
[ "https://Stackoverflow.com/questions/68120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ]
I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good. However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following: ``` <Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /> <Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /> ``` However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem. Currently: ``` <ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/> <ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/> ``` Replaced with something like: ``` <ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/> ``` However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?
I've had some luck with [the Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/introduction.html)
68,160
<p>Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. </p> <p>If this is possible, what commands would you use? (I'm trying to do this on a Linux box)</p>
[ { "answer_id": 68190, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 7, "selected": true, "text": "<pre>\n$ gdb --pid=26426\n(gdb) gcore\nSaved corefile core.26426\n(gdb) detach\n</pre>\n" }, { "answer_id": 14279282, ...
2008/09/16
[ "https://Stackoverflow.com/questions/68160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. If this is possible, what commands would you use? (I'm trying to do this on a Linux box)
``` $ gdb --pid=26426 (gdb) gcore Saved corefile core.26426 (gdb) detach ```
68,165
<p>I have a link on a long HTML page. When I click it, I wish a <code>div</code> on another part of the page to be visible in the window by scrolling into view.</p> <p>A bit like <code>EnsureVisible</code> in other languages.</p> <p>I've checked out <code>scrollTop</code> and <code>scrollTo</code> but they seem like red herrings.</p> <p>Can anyone help?</p>
[ { "answer_id": 68168, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 2, "selected": false, "text": "<p>Why not a named anchor?</p>\n" }, { "answer_id": 68175, "author": "mjallday", "author_id": 6084, ...
2008/09/16
[ "https://Stackoverflow.com/questions/68165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a link on a long HTML page. When I click it, I wish a `div` on another part of the page to be visible in the window by scrolling into view. A bit like `EnsureVisible` in other languages. I've checked out `scrollTop` and `scrollTo` but they seem like red herrings. Can anyone help?
old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element; ``` document.getElementById('youridhere').scrollIntoView(); ``` and what's even better; according to the great compatibility-tables on quirksmode, this is [supported by all major browsers](http://www.quirksmode.org/dom/w3c_cssom.html#t23)!
68,234
<p>Let’s say I'm developing a helpdesk application that will be used by multiple departments. Every URL in the application will include a key indicating the specific department. The key will always be the first parameter of every action in the system. For example</p> <pre><code>http://helpdesk/HR/Members http://helpdesk/HR/Members/PeterParker http://helpdesk/HR/Categories http://helpdesk/Finance/Members http://helpdesk/Finance/Members/BruceWayne http://helpdesk/Finance/Categories </code></pre> <p>The problem is that in each action on each request, I have to take this parameter and then retrieve the Helpdesk Department model from the repository based on that key. From that model I can retrieve the list of members, categories etc., which is different for each Helpdesk Department. This obviously violates DRY.</p> <p>My question is, how can I create a base controller, which does this for me so that the particular Helpdesk Department specified in the URL is available to all derived controllers, and I can just focus on the actions?</p>
[ { "answer_id": 68348, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "<p><em>Disclaimer: I'm currently running MVC Preview 5, so some of this may be new.</em></p>\n\n<p>The best-practices way:...
2008/09/16
[ "https://Stackoverflow.com/questions/68234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Let’s say I'm developing a helpdesk application that will be used by multiple departments. Every URL in the application will include a key indicating the specific department. The key will always be the first parameter of every action in the system. For example ``` http://helpdesk/HR/Members http://helpdesk/HR/Members/PeterParker http://helpdesk/HR/Categories http://helpdesk/Finance/Members http://helpdesk/Finance/Members/BruceWayne http://helpdesk/Finance/Categories ``` The problem is that in each action on each request, I have to take this parameter and then retrieve the Helpdesk Department model from the repository based on that key. From that model I can retrieve the list of members, categories etc., which is different for each Helpdesk Department. This obviously violates DRY. My question is, how can I create a base controller, which does this for me so that the particular Helpdesk Department specified in the URL is available to all derived controllers, and I can just focus on the actions?
I have a similar scenario in one of my projects, and I'd tend to use a ModelBinder rather than using a separate inheritance hierarchy. You can make a ModelBinder attribute to fetch the entity/entites from the RouteData: ``` public class HelpdeskDepartmentBinder : CustomModelBinderAttribute, IModelBinder { public override IModelBinder GetBinder() { return this; } public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) { //... extract appropriate value from RouteData and fetch corresponding entity from database. } } ``` ...then you can use it to make the HelpdeskDepartment available to all your actions: ``` public class MyController : Controller { public ActionResult Index([HelpdeskDepartmentBinder] HelpdeskDepartment department) { return View(); } } ```
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
[ { "answer_id": 68320, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 6, "selected": false, "text": "<p>It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or ad...
2008/09/16
[ "https://Stackoverflow.com/questions/68282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
When defining a method on a class in Python, it looks something like this: ``` class MyClass(object): def __init__(self, x, y): self.x = x self.y = y ``` But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?
I like to quote Peters' Zen of Python. "Explicit is better than implicit." In Java and C++, '`this.`' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't. Python elects to make things like this explicit rather than based on a rule. Additionally, since nothing is implied or assumed, parts of the implementation are exposed. `self.__class__`, `self.__dict__` and other "internal" structures are available in an obvious way.