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 |
|---|---|---|---|---|---|---|
109,464 | <p>I have a report that I built for a client where I need to plot x 0-100, y 0-100. Let's imagine I have these points:</p>
<pre><code> 0, 0
2, 24
50, 70
100, 100
</code></pre>
<p>I need to represent these as a smoothed line chart, as the application of it is a dot gain graph for printing presses.</p>
<p>Here's the problem. The line draws fine from 100,100 (top right) down to 2,24. But then what happens is from 2,24 to 0,0 the line curves out off the left of the graph and then to down to 0,0. Imagine it putting a point at -10,10.</p>
<p>I understand this is because of the generic <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="nofollow noreferrer">Bézier curve</a> algorithm it is using and the large separation of control points, thus heavily weighting it.</p>
<p>I was wondering however if anyone knows a way I can control it. I have tried adding in averaged points between the existing control points, but it still curves off the graph as if it's still heavily weighted.</p>
<p>The only other answer I can think of is custom drawing a graph or looking into <a href="https://en.wikipedia.org/wiki/Dundas_Data_Visualization#History" rel="nofollow noreferrer">Dundas Charts</a> and using its <a href="https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP" rel="nofollow noreferrer">GDI+</a> drawing support.</p>
<p>But before I go that route, anyone have any thoughts?</p>
<hr>
<p>Here's the thing. I know how to draw the curve manually. The problem lies in the fact that there is such a high weighting between 2 and 50. I tried to add points in at the lows and the mids, but it was still bowing off the edge. I will have to go check out the source and modify the graph back and see if I can get a screenshot up.</p>
<p>Right now I just have the graph stop at 2 until I can get this solved.</p>
| [
{
"answer_id": 109537,
"author": "bkane",
"author_id": 17097,
"author_profile": "https://Stackoverflow.com/users/17097",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg\" rel=\"nofollow noreferrer\">alt text http://i... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14642/"
] | I have a report that I built for a client where I need to plot x 0-100, y 0-100. Let's imagine I have these points:
```
0, 0
2, 24
50, 70
100, 100
```
I need to represent these as a smoothed line chart, as the application of it is a dot gain graph for printing presses.
Here's the problem. The line draws fine from 100,100 (top right) down to 2,24. But then what happens is from 2,24 to 0,0 the line curves out off the left of the graph and then to down to 0,0. Imagine it putting a point at -10,10.
I understand this is because of the generic [Bézier curve](http://en.wikipedia.org/wiki/B%C3%A9zier_curve) algorithm it is using and the large separation of control points, thus heavily weighting it.
I was wondering however if anyone knows a way I can control it. I have tried adding in averaged points between the existing control points, but it still curves off the graph as if it's still heavily weighted.
The only other answer I can think of is custom drawing a graph or looking into [Dundas Charts](https://en.wikipedia.org/wiki/Dundas_Data_Visualization#History) and using its [GDI+](https://en.wikipedia.org/wiki/Graphics_Device_Interface#Windows_XP) drawing support.
But before I go that route, anyone have any thoughts?
---
Here's the thing. I know how to draw the curve manually. The problem lies in the fact that there is such a high weighting between 2 and 50. I tried to add points in at the lows and the mids, but it was still bowing off the edge. I will have to go check out the source and modify the graph back and see if I can get a screenshot up.
Right now I just have the graph stop at 2 until I can get this solved. | [alt text http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg](http://img140.imageshack.us/img140/1279/smoothlinebezierxl0.jpg)
(Providing a picture of the behaviour to help you get a better answer).
For those with a theory, you can try this out in Excel as well (not just Reporting Services).
You mentioned adding points in your question, but it seems like adding in interpolated points near the problem area has the desired effect (e.g. { (1,12), (1.5, 18) }). This is a clumsy "solution" at best though. |
109,480 | <p>I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.</p>
<p>I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get <code>"User::getFavoriteThreads|1471"</code>. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.</p>
<p><strong>However, and here comes the problem:</strong></p>
<p>I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example</p>
<pre><code>"Forum::getThreads|$iForumId|$iLimit|$iOffset".
</code></pre>
<p>Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under <code>"Forum::getThreads|$iForumId"</code>, no matter what the limit and offset is.</p>
<p>What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.</p>
<p>Thanks.</p>
| [
{
"answer_id": 109532,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 2,
"selected": false,
"text": "<p>You're essentially trying to cache a view, which is always going to get tricky. You should instead try to cache data onl... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11167/"
] | I've created a forum, and we're implementing an apc and memcache caching solution to save the database some work.
I started implementing the cache layer with keys like "Categories::getAll", and if I had user-specific data, I'd append the keys with stuff like the user ID, so you'd get `"User::getFavoriteThreads|1471"`. When a user added a new favorite thread, I'd delete the cache key, and it would recreate the entry.
**However, and here comes the problem:**
I wanted to cache the threads in a forum. Simple enough, "Forum::getThreads|$iForumId". But... With pagination, I'd have to split this into several cache entries, for example
```
"Forum::getThreads|$iForumId|$iLimit|$iOffset".
```
Which is alright, until someone posts a new thread in the forum. I will now have to delete all the keys under `"Forum::getThreads|$iForumId"`, no matter what the limit and offset is.
What would be a good way of solving this problem? I'd really rather not loop through every possible limit and offset until I find something that doesn't match anymore.
Thanks. | You might also want to have a look at the cost of storing the cache data, in terms of your effort and CPU cost, against how what the cache will buy you.
If you find that 80% of your forum views are looking at the first page of threads, then you could decide to cache that page only. That would mean both cache reads and writes are much simpler to implment.
Likewise with the list of a user's favourite threads. If this is something that each person visits rarely then cache might not improve performance too much. |
109,488 | <p>I keep hearing that <code>div</code> tags should be used for layout purposes and not <code>table</code> tags. So does that also apply to form layout? I know a form layout is still a layout, but it seems like creating form layouts with <code>div</code>s requires more <code>html</code> and <code>css</code>. So with that in mind, should forms layouts use <code>div</code> tags instead?</p>
| [
{
"answer_id": 109493,
"author": "John Fiala",
"author_id": 9143,
"author_profile": "https://Stackoverflow.com/users/9143",
"pm_score": 2,
"selected": false,
"text": "<p>It's certainly easier to use table than div to layout a table, but keep in mind that a table is supposed to mean somet... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] | I keep hearing that `div` tags should be used for layout purposes and not `table` tags. So does that also apply to form layout? I know a form layout is still a layout, but it seems like creating form layouts with `div`s requires more `html` and `css`. So with that in mind, should forms layouts use `div` tags instead? | Yes, it does apply for form layouts. Keep in mind that there are also tags like FIELDSET and LABEL which exist specifically for adding structure to a form, so it's not really a question of just using DIV. You should be able to markup a form with pretty minimal HTML, and let CSS do the rest of the work. E.g.:
```
<fieldset>
<div>
<label for="nameTextBox">Name:</label>
<input id="nameTextBox" type="text" />
</div>
...
</fieldset>
``` |
109,491 | <p>I keep getting compiler errors when I try to access flashVars in an AS3 class.</p>
<p>Here's a stripped version of the code:</p>
<pre><code>package myPackage {
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
public class myClass {
public function CTrafficHandler() {
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}}
</code></pre>
<p>And I get a compilation error:</p>
<p><em>1119: Access of possibly undefined property root through a reference with static type source:myClass.</em></p>
<p>When I change the class row to</p>
<pre><code>public class myClass extends Sprite {
</code></pre>
<p>I don't get a compiler error, but I do get this in the output window:</p>
<p><em>TypeError: Error #1009: Cannot access a property or method of a null object reference.</em></p>
<p>Via the debugger (as suggested) I can see that <strong>this.root</strong> is null.</p>
<p>How can I solve this problem?</p>
| [
{
"answer_id": 109505,
"author": "Michael Pliskin",
"author_id": 9777,
"author_profile": "https://Stackoverflow.com/users/9777",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should extend from Sprite, but be sure to initialize it first and maybe put to the stage. Try to enab... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18790/"
] | I keep getting compiler errors when I try to access flashVars in an AS3 class.
Here's a stripped version of the code:
```
package myPackage {
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
public class myClass {
public function CTrafficHandler() {
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myFvar;}}}
```
And I get a compilation error:
*1119: Access of possibly undefined property root through a reference with static type source:myClass.*
When I change the class row to
```
public class myClass extends Sprite {
```
I don't get a compiler error, but I do get this in the output window:
*TypeError: Error #1009: Cannot access a property or method of a null object reference.*
Via the debugger (as suggested) I can see that **this.root** is null.
How can I solve this problem? | I found what the problem was. The class in question wasn't the main class used in the project, but rather a secondary class.
I've moved the code to the main class to get the parameters and after I got them, I sent them to the class constructor function. |
109,520 | <p>I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP?</p>
<p>Note: I've tried both of the following methods within my ActionMailer (just in case):</p>
<pre><code>@from = me@mydomain.com
from 'me@mydomain.com'
</code></pre>
| [
{
"answer_id": 109539,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 4,
"selected": true,
"text": "<p>I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a t... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6432/"
] | I've got my Rails (2.1) app setup to send email via Gmail, however whenever I send an email no matter what I set the from address to in my ActionMailer the emails always come as if sent from my Gmail email address. Is this a security restriction they've put in place at Gmail to stop spammers using their SMTP?
Note: I've tried both of the following methods within my ActionMailer (just in case):
```
@from = me@mydomain.com
from 'me@mydomain.com'
``` | I believe it's just something Gmail does when mail is sent through its SMTP, as it was mentioned that they do this on a tutorial about using their SMTP to send mail. |
109,580 | <p>I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible?</p>
<p>Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page.</p>
| [
{
"answer_id": 109597,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 0,
"selected": false,
"text": "<p>I believe flash objects have functions accessible through javascript, so if there's no easier way, you could at least us... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] | I'm looking to grab cookie values for the same domain within a Flash movie. Is this possible?
Let's see I let a user set a variable foo and I store it using any web programming language. I can access it easily via that language, but I would like to access it via the Flash movie without passing it in via printing it within the HTML page. | If you just want to store and retrieve data, you probably want to use the SharedObject class. See [Adobe's SharedObject reference](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html) for more details of that.
If you want to access the HTTP cookies, you'll need to use ExternalInterface to talk to javascript. The way we do that here is to have a helper class called HTTPCookies.
HTTPCookies.as:
```
import flash.external.ExternalInterface;
public class HTTPCookies
{
public static function getCookie(key:String):*
{
return ExternalInterface.call("getCookie", key);
}
public static function setCookie(key:String, val:*):void
{
ExternalInterface.call("setCookie", key, val);
}
}
```
You need to make sure you enable javascript using the 'allowScriptAccess' parameter in your flash object.
Then you need to create a pair of javascript functions, getCookie and setCookie, as follows (with thanks to [quirksmode.org](http://www.quirksmode.org/js/cookies.html))
HTTPCookies.js:
```
function getCookie(key)
{
var cookieValue = null;
if (key)
{
var cookieSearch = key + "=";
if (document.cookie)
{
var cookieArray = document.cookie.split(";");
for (var i = 0; i < cookieArray.length; i++)
{
var cookieString = cookieArray[i];
// skip past leading spaces
while (cookieString.charAt(0) == ' ')
{
cookieString = cookieString.substr(1);
}
// extract the actual value
if (cookieString.indexOf(cookieSearch) == 0)
{
cookieValue = cookieString.substr(cookieSearch.length);
}
}
}
}
return cookieValue;
}
function setCookie(key, val)
{
if (key)
{
var date = new Date();
if (val != null)
{
// expires in one year
date.setTime(date.getTime() + (365*24*60*60*1000));
document.cookie = key + "=" + val + "; expires=" + date.toGMTString();
}
else
{
// expires yesterday
date.setTime(date.getTime() - (24*60*60*1000));
document.cookie = key + "=; expires=" + date.toGMTString();
}
}
}
```
Once you have HTTPCookies.as in your flash project, and HTTPCookies.js loaded from your web page, you should be able to call getCookie and setCookie from within your flash movie to get or set HTTP cookies.
This will only work for very simple values - strings or numbers - but for anything more complicated you really should be using SharedObject. |
109,592 | <p>In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly. Any suggestions optimization for image serving?</p>
<p>Here is my server.xml:</p>
<pre><code> <Service name="Catalina">
<Connector port="8009" protocol="AJP/1.3" />
<Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" />
<Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
<Host name="hostname.whatever" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
...context
</Host>
</Engine>
</Service>
</code></pre>
| [
{
"answer_id": 109679,
"author": "user19113",
"author_id": 19113,
"author_profile": "https://Stackoverflow.com/users/19113",
"pm_score": 2,
"selected": false,
"text": "<p>If you have the option, you could add a reverse proxy in advance of your application. At work I have an Apache web s... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18159/"
] | In tomcat 6 i have a servlet running openbluedragon, everything compiles and servers up quik, with the exception of images, they really lag significantly. Any suggestions optimization for image serving?
Here is my server.xml:
```
<Service name="Catalina">
<Connector port="8009" protocol="AJP/1.3" />
<Connector port="8080" maxThreads="100" protocol="HTTP/1.1" connectionTimeout="20000" />
<Engine name="Standalone" defaultHost="hostname.whatever" jvmRoute="ajp13">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
<Host name="hostname.whatever" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
...context
</Host>
</Engine>
</Service>
``` | Another option is to use apache as a frontend, connecting tomcat with mod\_jk. This way you can let apache serve static content (e.g. images, css, javascript) and let tomcat generate the dynamic content. Might leave a bit of work to separate the static content from the dynamic ones, but works great for me.
On Unix, having an apache as frontend is a nice option because being bound to port 80 you're often forced to run as root. Apache knows how to drop root permissions after binding a port, Tomcat doesn't. You don't want a server faced to the public to run as root.
(This is similar to the reverse proxy answer, but doesn't involve a proxy but mod\_jk) |
109,608 | <p>When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml:</p>
<pre><code><System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="0" Margin="0">
<System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left">
<ContentControl>
<Grid Width="400" Height="200" Background="White"/>
</ContentControl>
</System_Windows_Controls:TabItem>
</System_Windows_Controls:TabControl>
</code></pre>
<p>will produce:</p>
<p><img src="https://i.stack.imgur.com/y5LuN.jpg" alt="alt text"></p>
<p>How do I position the content at 0,0?</p>
| [
{
"answer_id": 110046,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 2,
"selected": false,
"text": "<p>Check the control template of your TabItem , it might have some default Margin of 10. Just a guess</p>\n"
},
{
"... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4244/"
] | When I place a control on a tabpage in Silverlight the control is placed ~10 pixels down and ~10 pixels right. For example, the following xaml:
```
<System_Windows_Controls:TabControl x:Name=TabControlMain Canvas.Left="0" Canvas.Top="75" Width="800" Height="525" Background="Red" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="0" Margin="0">
<System_Windows_Controls:TabItem Header="Test" VerticalContentAlignment="Top" BorderThickness="0" Margin="0" Padding="0" HorizontalContentAlignment="Left">
<ContentControl>
<Grid Width="400" Height="200" Background="White"/>
</ContentControl>
</System_Windows_Controls:TabItem>
</System_Windows_Controls:TabControl>
```
will produce:

How do I position the content at 0,0? | Look at the control template, it has a margin of that size. Use blend to modify the a copy of the tab control's template. |
109,618 | <p>I want the following layout to appear on the screen:</p>
<pre><code>FieldName 1 [Field input 1]
FieldName 2 is longer [Field input 2]
. .
. .
FieldName N [Field input N]
</code></pre>
<p>Requirements:</p>
<ul>
<li>Field names and field inputs must align on the left edges</li>
<li>Both columns must dynamically size themselves to their content</li>
<li>Must work cross-browsers</li>
</ul>
<p>I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.</p>
| [
{
"answer_id": 109628,
"author": "Héctor Ramos",
"author_id": 19617,
"author_profile": "https://Stackoverflow.com/users/19617",
"pm_score": -1,
"selected": false,
"text": "<p>FieldName objects should be contained in SPANs with style attributes of float: left and a width that is wide enou... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2284/"
] | I want the following layout to appear on the screen:
```
FieldName 1 [Field input 1]
FieldName 2 is longer [Field input 2]
. .
. .
FieldName N [Field input N]
```
Requirements:
* Field names and field inputs must align on the left edges
* Both columns must dynamically size themselves to their content
* Must work cross-browsers
I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS. | I think most of the answers are missing the point that the original questioner wanted the columns widths to depend on the width of the content. I believe the only way to do this with pure CSS is by using 'display: table', 'display: table-row' and 'display: table-cell', but that isn't supported by IE. But I'm not sure that this property is desirable, I find that creating a wide columns because there is a single long field name makes the layout less aesthetically pleasing and harder to use. Wrapped lines are fine in my opinion, so I think the answers that I just suggested were incorrect are probably the way to go.
[Robertc's example](https://stackoverflow.com/questions/109618/how-would-you-achieve-this-table-based-layout-using-css-instead-of-html-tables#109714) is ideal but if you really must use tables, I think you can make it a little more 'semantic' by using `<th>` for the field names. I'm not sure about this so please someone correct me if I'm wrong.
```
<table>
<tr><th scope="row"><label for="field1">FieldName 1</label></th>
<td><input id="field1" name="field1"></td></tr>
<tr><th scope="row"><label for="field2">FieldName 2 is longer</label></th>
<td><input id="field2" name="field2"></td></tr>
<!-- ....... -->
</table>
```
Update: I haven't been following this closely, but IE8 apparently supports CSS tables, so some are suggesting that we should start using them. There's an [article on 24 ways](http://24ways.org/2008/the-first-tool-you-reach-for) which contains a relevant example at the end. |
109,644 | <p><code>temp2</code>, <code>temp1</code> are pointers to some struct x:</p>
<pre><code>struct FunkyStruct x;
struct FunkyStruct *temp1 = &x, *temp2 = &x;
</code></pre>
<p>Now, after execution of following lines:</p>
<pre><code>temp2=temp1;
temp1=temp1->nxt;
</code></pre>
<p>...Will <code>temp2</code> and <code>temp1</code> still point to the same memory location? If not, please explain why they would be different. </p>
| [
{
"answer_id": 109649,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 2,
"selected": false,
"text": "<p>temp2 will not be updated, but temp1 will point to the next item. So if temp1 is 0x89abcdef and temp1->next is 0x89b0000... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19790/"
] | `temp2`, `temp1` are pointers to some struct x:
```
struct FunkyStruct x;
struct FunkyStruct *temp1 = &x, *temp2 = &x;
```
Now, after execution of following lines:
```
temp2=temp1;
temp1=temp1->nxt;
```
...Will `temp2` and `temp1` still point to the same memory location? If not, please explain why they would be different. | Initially, `temp1` and `temp2` both contain the memory address of `x`.
`temp2 = temp1` means "assign the value of `temp1` to `temp2`". Since they have the same value to start with, this command does nothing.
The expression `temp1->next` means "Look inside the data structure that `temp1` points to, and return the value of the field `next`." So `temp1 = temp1->next` assigns the value of `temp1->next` to `temp1`. (Of course, the lookup happen *before* the assignment.) `temp1` will now contain whatever value the `next` field happened to contain. It could be the same as the old value, or it could be different. |
109,705 | <p>The following program is very simple: it outputs a single dot each half a second. If it recieves a <strong>SIGQUIT</strong>, it proceeds to output ten <strong>Q</strong>s. If it recieves a <strong>SIGTSTP</strong> <em>(<kbd>Ctrl</kbd>-<kbd>Z</kbd>)</em>, it outputs ten <strong>Z</strong>s.</p>
<p>If it recieves a <strong>SIGTSTP</strong> while printing <strong>Q</strong>s, it will print ten <strong>Z</strong>s after it's done with the ten <strong>Q</strong>s. This is a good thing.</p>
<p>However, if it recieves a <strong>SIGQUIT</strong> while printing <strong>Z</strong>s, it fails to print <strong>Q</strong>s after them. Instead, it prints them out only after I manually terminate execution via a KeyboardInterrupt. I want the <strong>Q</strong>s to be printed immediately after the <strong>Z</strong>s.</p>
<p>This happens using Python2.3.</p>
<p>What am I doing wrong?</p>
<pre><code>#!/usr/bin/python
from signal import *
from time import sleep
from sys import stdout
def write(text):
stdout.write(text)
stdout.flush()
def process_quit(signum, frame):
for i in range(10):
write("Q")
sleep(0.5)
def process_tstp(signum, frame):
for i in range(10):
write("Z")
sleep(0.5)
signal(SIGQUIT, process_quit)
signal(SIGTSTP, process_tstp)
while 1:
write('.')
sleep(0.5)
</code></pre>
| [
{
"answer_id": 109783,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 4,
"selected": true,
"text": "<p>Your larger problem is blocking in signal handlers.</p>\n\n<p>This is usually discouraged since it can lead to strange... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The following program is very simple: it outputs a single dot each half a second. If it recieves a **SIGQUIT**, it proceeds to output ten **Q**s. If it recieves a **SIGTSTP** *(`Ctrl`-`Z`)*, it outputs ten **Z**s.
If it recieves a **SIGTSTP** while printing **Q**s, it will print ten **Z**s after it's done with the ten **Q**s. This is a good thing.
However, if it recieves a **SIGQUIT** while printing **Z**s, it fails to print **Q**s after them. Instead, it prints them out only after I manually terminate execution via a KeyboardInterrupt. I want the **Q**s to be printed immediately after the **Z**s.
This happens using Python2.3.
What am I doing wrong?
```
#!/usr/bin/python
from signal import *
from time import sleep
from sys import stdout
def write(text):
stdout.write(text)
stdout.flush()
def process_quit(signum, frame):
for i in range(10):
write("Q")
sleep(0.5)
def process_tstp(signum, frame):
for i in range(10):
write("Z")
sleep(0.5)
signal(SIGQUIT, process_quit)
signal(SIGTSTP, process_tstp)
while 1:
write('.')
sleep(0.5)
``` | Your larger problem is blocking in signal handlers.
This is usually discouraged since it can lead to strange timing conditions. But it's not quite the cause of your problem since the timing condition you're vulnerable to exists because of your choice of signal handlers.
Anyway, here's how to at least minimize the timing condition by only setting flags in your handlers and leaving the main while loop to do the actual work. The explanation for why your code is behaving strangely is described after the code.
```
#!/usr/bin/python
from signal import *
from time import sleep
from sys import stdout
print_Qs = 0
print_Zs = 0
def write(text):
stdout.write(text)
stdout.flush()
def process_quit(signum, frame):
global print_Qs
print_Qs = 10
def process_tstp(signum, frame):
global print_Zs
print_Zs = 10
signal(SIGQUIT, process_quit)
signal(SIGTSTP, process_tstp)
while 1:
if print_Zs:
print_Zs -= 1
c = 'Z'
elif print_Qs:
print_Qs -= 1
c = 'Q'
else:
c = '.'
write(c)
sleep(0.5)
```
Anyway, here's what's going on.
SIGTSTP is more special than SIGQUIT.
SIGTSTP masks the other signals from being delivered while its signal handler is running. When the kernel goes to deliver SIGQUIT and sees that SIGTSTP's handler is still running, it simply saves it for later. Once another signal comes through for delivery, such as SIGINT when you `CTRL`+`C` (aka KeyboardInterrupt), the kernel remembers that it never delivered SIGQUIT and delivers it now.
You will notice if you change `while 1:` to `for i in range(60):` in the main loop and do your test case again, the program will exit without running the SIGTSTP handler since exit doesn't re-trigger the kernel's signal delivery mechanism.
Good luck! |
109,710 | <p>I've been digging through some parts of the Linux kernel, and found calls like this:</p>
<pre><code>if (unlikely(fd < 0))
{
/* Do something */
}
</code></pre>
<p>or</p>
<pre><code>if (likely(!err))
{
/* Do something */
}
</code></pre>
<p>I've found the definition of them:</p>
<pre><code>#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
</code></pre>
<p>I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).</p>
| [
{
"answer_id": 109718,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>They're hints to the compiler to generate the hint prefixes on branches. On x86/x64, they take up one byte, so... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9232/"
] | I've been digging through some parts of the Linux kernel, and found calls like this:
```
if (unlikely(fd < 0))
{
/* Do something */
}
```
or
```
if (likely(!err))
{
/* Do something */
}
```
I've found the definition of them:
```
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
```
I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course). | They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.
Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate. |
109,717 | <p>In C#, if you have multiple constructors, you can do something like this:</p>
<pre><code>public MyClass(Guid inputId, string inputName){
// do something
}
public MyClass(Guid inputId): this(inputId, "foo") {}
</code></pre>
<p>The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor:</p>
<pre><code>public MyClass(MyOtherClass inputObject)
{
Guid inputId = inputObject.ID;
MyThirdClass mc = inputObject.CreateHelper();
string inputText = mc.Text;
mc.Dispose();
// Need to call the main Constructor now with inputId and inputText
}
</code></pre>
<p>The caveat here is that I need to create an object that <strong>has</strong> to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)</p>
<p>However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?</p>
<p>Or is it possible to use</p>
<pre><code>public MyClass(MyOtherClass inputObject): this(inputObject.ID,
inputObject.CreateHelper().Text)
{}
</code></pre>
<p>Would this automatically Dispose the generated Object from CreateHelper()?</p>
<p><strong>Edit:</strong> Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach.</p>
| [
{
"answer_id": 109728,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>The object would only be automatically disposed when garbage collection runs. If you want the dispose to run as ... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | In C#, if you have multiple constructors, you can do something like this:
```
public MyClass(Guid inputId, string inputName){
// do something
}
public MyClass(Guid inputId): this(inputId, "foo") {}
```
The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor:
```
public MyClass(MyOtherClass inputObject)
{
Guid inputId = inputObject.ID;
MyThirdClass mc = inputObject.CreateHelper();
string inputText = mc.Text;
mc.Dispose();
// Need to call the main Constructor now with inputId and inputText
}
```
The caveat here is that I need to create an object that **has** to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)
However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?
Or is it possible to use
```
public MyClass(MyOtherClass inputObject): this(inputObject.ID,
inputObject.CreateHelper().Text)
{}
```
Would this automatically Dispose the generated Object from CreateHelper()?
**Edit:** Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0...). I do control my own class though, and since I've just started writing it, I have no problem refactoring the constructors if there is a good approach. | The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick.
```
public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {}
private static string GetHelperText(MyOtherClass o)
{
using (var helper = o.CreateHelper())
return helper.Text;
}
``` |
109,759 | <p>I've just switched an application to use ar_mailer and when I run ar_sendmail (after a long pause) I get the following error:</p>
<pre><code>Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4
</code></pre>
<p>I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp_settings just installed ar_mailer.</p>
<p>Versions: </p>
<p>Rails: 2.1, ar_mailer: 1.3.1</p>
| [
{
"answer_id": 109763,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 0,
"selected": false,
"text": "<p>What version of ar_mailer are you using? A gmail specific bug was fixed in 1.3.1, as shown here:</p>\n\n<p><a href=\"h... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6432/"
] | I've just switched an application to use ar\_mailer and when I run ar\_sendmail (after a long pause) I get the following error:
```
Unhandled exception 530 5.7.0 Must issue a STARTTLS command first. h7sm16260325nfh.4
```
I am using Gmail SMTP to send the emails and I haven't changed any of the ActionMailer::Base.smtp\_settings just installed ar\_mailer.
Versions:
Rails: 2.1, ar\_mailer: 1.3.1 | Did some digging in the lib and it seems that if you want to use TLS (as you do with Gmail) then it adds a new option to the ActionMailer::Base.smtp\_settings of :tls (default of which is false) which you should set to true.
The only thing the installation instructions mention regarding TLS is to remove any other smtp\_tls files, but the one I had didn't require the tls option to work. |
109,761 | <p>I have the following config in my lighttpd.conf:</p>
<pre><code>$HTTP["host"] == "trac.domain.tld" {
server.document-root = "/usr/home/daniels/trac/htdocs/"
fastcgi.server = ( "/trac" =>
( "trac" =>
( "socket" => "/tmp/trac-fastcgi.sock",
"bin-path" => "/usr/home/daniels/trac/cgi-bin/trac.fcgi",
"check-local" => "disable",
"bin-environment" =>
( "TRAC_ENV" => "/usr/home/daniels/trac" )
)
)
)
}
</code></pre>
<p>And it runs at trac.domain.tld/trac.
How can i make it to run at trac.domain.tld/ so i will have trac.domain.tld/wiki, trac.domain.tld/timeline, etc instead of trac.domain.tld/trac/wiki, etc...</p>
| [
{
"answer_id": 109841,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 1,
"selected": true,
"text": "<p>Look for \"For top level setup: ...\" <a href=\"http://trac.lighttpd.net/trac/wiki/HowToSetupTrac\" rel=\"nofollo... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9789/"
] | I have the following config in my lighttpd.conf:
```
$HTTP["host"] == "trac.domain.tld" {
server.document-root = "/usr/home/daniels/trac/htdocs/"
fastcgi.server = ( "/trac" =>
( "trac" =>
( "socket" => "/tmp/trac-fastcgi.sock",
"bin-path" => "/usr/home/daniels/trac/cgi-bin/trac.fcgi",
"check-local" => "disable",
"bin-environment" =>
( "TRAC_ENV" => "/usr/home/daniels/trac" )
)
)
)
}
```
And it runs at trac.domain.tld/trac.
How can i make it to run at trac.domain.tld/ so i will have trac.domain.tld/wiki, trac.domain.tld/timeline, etc instead of trac.domain.tld/trac/wiki, etc... | Look for "For top level setup: ..." [here](http://trac.lighttpd.net/trac/wiki/HowToSetupTrac). |
109,769 | <p>I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located <a href="http://www.thomasfrank.se/classier_json.html" rel="nofollow noreferrer">ClassyJSON</a>. Any thoughts?</p>
| [
{
"answer_id": 109785,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p>Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799/"
] | I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of the collection object as well. So far I've located [ClassyJSON](http://www.thomasfrank.se/classier_json.html). Any thoughts? | I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.
I do believe though that `"f = "+function() {}` will yield you a to string version that you can eval:
```
var test = "f = " + function() { alert("Hello"); };
eval(test)
```
And for good json handling, I would recommend prototype, which has great methods for serializing objects to json. |
109,776 | <p>What's the best way to create recurring tasks?</p>
<p>Should I create some special syntax and parse it, kind of similar to Cronjobs on Linux or should I much rather just use a cronjob that runs every hour to create more of those recurring tasks with no end?</p>
<p>Keep in mind, that you can have endless recurring tasks and tasks with an enddate.</p>
| [
{
"answer_id": 109785,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p>Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9535/"
] | What's the best way to create recurring tasks?
Should I create some special syntax and parse it, kind of similar to Cronjobs on Linux or should I much rather just use a cronjob that runs every hour to create more of those recurring tasks with no end?
Keep in mind, that you can have endless recurring tasks and tasks with an enddate. | I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.
I do believe though that `"f = "+function() {}` will yield you a to string version that you can eval:
```
var test = "f = " + function() { alert("Hello"); };
eval(test)
```
And for good json handling, I would recommend prototype, which has great methods for serializing objects to json. |
109,781 | <p>What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?</p>
<p>These objects are stored in ActiveRecord so using AR's methods would be fine too. </p>
| [
{
"answer_id": 109794,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 3,
"selected": false,
"text": "<p>I had originally suggested using the <code>select</code> method on Array. To wit:</p>\n\n<p><code>[1, 2, 3, 4, 5, 6, 7].se... | 2008/09/20 | [
"https://Stackoverflow.com/questions/109781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227001/"
] | What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?
These objects are stored in ActiveRecord so using AR's methods would be fine too. | Use [`Array#uniq`](http://ruby-doc.org/core-1.9.2/Array.html#method-i-uniq) with a block:
```
@photos = @photos.uniq { |p| p.album_id }
``` |
109,859 | <p>I am reading a .NET book, and in one of the code examples there is a class definition with this field:</p>
<pre><code>private DateTime? startdate
</code></pre>
<p>What does <code>DateTime?</code> mean?</p>
| [
{
"answer_id": 109862,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 5,
"selected": false,
"text": "<p>It's a nullable DateTime. <code>?</code> after a primitive type/structure indicates that it is the nullable version.... | 2008/09/21 | [
"https://Stackoverflow.com/questions/109859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7148/"
] | I am reading a .NET book, and in one of the code examples there is a class definition with this field:
```
private DateTime? startdate
```
What does `DateTime?` mean? | Since `DateTime` is a `struct`, not a `class`, you get a `DateTime` *object*, not a *reference*, when you declare a field or variable of that type.
And, in the same way as an `int` cannot be `null`, so this `DateTime` object can never be `null`, because it's not a reference.
Adding the question mark turns it into a [*nullable type*](http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx), which means that *either* it is a `DateTime` object, *or* it is `null`.
`DateTime?` is syntactic sugar for `Nullable<DateTime>`, where [`Nullable`](http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx) is itself a `struct`. |
109,880 | <p>Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like </p>
<pre><code>for my $item ( map { ... } @list ) {
}
</code></pre>
<p>into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? </p>
<p><strong>Note:</strong> I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. </p>
| [
{
"answer_id": 109899,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 2,
"selected": false,
"text": "<p>If I remember correctly, for/foreach do get the whole list first anyways, so a lazily evaluated list would be read comp... | 2008/09/21 | [
"https://Stackoverflow.com/questions/109880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
] | Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like
```
for my $item ( map { ... } @list ) {
}
```
into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop?
**Note:** I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. | As mentioned previously, for(each) is an eager loop, so it wants to evaluate the entire list before starting.
For simplicity, I would recommend using an iterator object or closure rather than trying to have a lazily evaluated array. While you *can* use a tie to have a lazily evaluated infinite list, you can run into troubles if you ever ask (directly or indirectly, as in the foreach above) for the entire list (or even the size of the entire list).
Without writing a full class or using any modules, you can make a simple iterator factory just by using closures:
```
sub make_iterator {
my ($value, $max, $step) = @_;
return sub {
return if $value > $max; # Return undef when we overflow max.
my $current = $value;
$value += $step; # Increment value for next call.
return $current; # Return current iterator value.
};
}
```
And then to use it:
```
# All the even numbers between 0 - 100.
my $evens = make_iterator(0, 100, 2);
while (defined( my $x = $evens->() ) ) {
print "$x\n";
}
```
There's also the [Tie::Array::Lazy](http://search.cpan.org/perldoc?Tie::Array::Lazy) module on the CPAN, which provides a much richer and fuller interface to lazy arrays. I've not used the module myself, so your mileage may vary.
All the best,
Paul |
109,916 | <p>To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.</p>
<p>Here are some sample file names, of which - naturally - only the first group should be matched:</p>
<pre><code>yes.rar
yes.part1.rar
yes.part01.rar
yes.part001.rar
no.part2.rar
no.part02.rar
no.part002.rar
no.part011.rar
</code></pre>
<p>One (limited) way to do it with PCRE compatible regexps is this:</p>
<pre><code>.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)
</code></pre>
<p>This did not work in Ruby when I tested it at <a href="http://www.projects.aphexcreations.net/rejax/" rel="nofollow noreferrer">Rejax</a> however.</p>
<p>How would you write one <strong>Ruby compatible</strong> regular expression to match only the first file in a set of RAR files?</p>
| [
{
"answer_id": 110120,
"author": "Matthew Encinas",
"author_id": 14433,
"author_profile": "https://Stackoverflow.com/users/14433",
"pm_score": 0,
"selected": false,
"text": "<p>I am no regex expert but here is my attempt</p>\n\n<pre><code>^(yes|no)\\.(rar|part0*1\\.rar)$\n</code></pre>\n... | 2008/09/21 | [
"https://Stackoverflow.com/questions/109916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19392/"
] | To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.
Here are some sample file names, of which - naturally - only the first group should be matched:
```
yes.rar
yes.part1.rar
yes.part01.rar
yes.part001.rar
no.part2.rar
no.part02.rar
no.part002.rar
no.part011.rar
```
One (limited) way to do it with PCRE compatible regexps is this:
```
.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)
```
This did not work in Ruby when I tested it at [Rejax](http://www.projects.aphexcreations.net/rejax/) however.
How would you write one **Ruby compatible** regular expression to match only the first file in a set of RAR files? | The short answer is that it's not possible to construct a single regex to satisfy your problem. Ruby 1.8 does not have lookaround assertions (the (?<! stuff in your example regex) which is why your regex doesn't work. This leaves you with two options.
1) Use more than one regex to do it.
```
def is_first_rar(filename)
if ((filename =~ /part(\d+)\.rar$/) == nil)
return (filename =~ /\.rar$/) != nil
else
return $1.to_i == 1
end
end
```
2) Use the regex engine for ruby 1.9, [Oniguruma](http://www.geocities.jp/kosako3/oniguruma/). It supports lookaround assertions, and you can [install it as a gem for ruby 1.8](http://oniguruma.rubyforge.org/). After that, you can do something like this:
```
def is_first_rar(filename)
reg = Oniguruma::ORegexp.new('.*(?:(?<!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar)')
match = reg.match(filename)
return match != nil
end
``` |
109,934 | <p>I've got a generic<> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?</p>
<p>So equivalent to the sql: select *, 'bar' as Foo from items</p>
<pre><code>foreach (var item in items)
{
var newItem = new {
item, // I'd like just the properties here, not the 'item' object!
Foo = "bar"
};
newItems.Add(newItem);
}
</code></pre>
| [
{
"answer_id": 109967,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 0,
"selected": false,
"text": "<pre><code>from item in items\nwhere someConditionOnItem\nselect\n{\n propertyOne,\n propertyTwo\n};\n</code></p... | 2008/09/21 | [
"https://Stackoverflow.com/questions/109934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] | I've got a generic<> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?
So equivalent to the sql: select \*, 'bar' as Foo from items
```
foreach (var item in items)
{
var newItem = new {
item, // I'd like just the properties here, not the 'item' object!
Foo = "bar"
};
newItems.Add(newItem);
}
``` | There's no easy way of doing what you're suggesting, as all types in C# are strong-typed, even the anonymous ones like you're using. However it's not impossible to pull it off. To do it you would have to utilize reflection and emit your own assembly in memory, adding a new module and type that contains the specific properties you want. It's possible to obtain a list of properties from your anonymous item using:
```
foreach(PropertyInfo info in item.GetType().GetProperties())
Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null));
``` |
109,948 | <p>just a quick question:</p>
<p>I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: </p>
<pre><code>dictionary = new ArrayList<String>();
</code></pre>
<p>I get the following error: <b>generics are not supported in -source 1.3</b>.</p>
<p>I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0_13. </p>
<p>Thank you.</p>
| [
{
"answer_id": 109957,
"author": "user7305",
"author_id": 7305,
"author_profile": "https://Stackoverflow.com/users/7305",
"pm_score": 0,
"selected": false,
"text": "<p>Generics are introduced in Java 5, so you can't use generics with -source 1.3 option.</p>\n"
},
{
"answer_id": 1... | 2008/09/21 | [
"https://Stackoverflow.com/questions/109948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013/"
] | just a quick question:
I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList:
```
dictionary = new ArrayList<String>();
```
I get the following error: **generics are not supported in -source 1.3**.
I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0\_13.
Thank you. | Java support in Xcode is obsolete and unmaintained; it's the only bit of Xcode that still uses the "old" build system inherited from Project Builder. Even Apple suggests using Eclipse instead. For Java, both Eclipse and NetBeans work quite well on the Mac; if you want to try native Mac programming, use Objective-C and Cocoa, for which Xcode is fine.
That said, the problem is that javac is targeting Java 1.3, which doesn't have generics. You can modify the javac reference in the Ant buildfile (build.xml) as follows:
```
<target name="compile" depends="init" description="Compile code">
<mkdir dir="${bin}"/>
<javac deprecation="on" srcdir="${src}" destdir="${bin}"
source="1.3" target="1.2"
```
Change "source" and "target" to "1.5". |
110,078 | <p>I need to store app specific configuration in rails. But it has to be:</p>
<ul>
<li>reachable in any file (model, view, helpers and controllers</li>
<li>environment specified (or not), that means each environment can overwrite the configs specified in environment.rb</li>
</ul>
<p>I've tried to use environment.rb and put something like</p>
<pre><code>USE_USER_APP = true
</code></pre>
<p>that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block.</p>
<p>So, anyone?</p>
| [
{
"answer_id": 110103,
"author": "Ricardo Acras",
"author_id": 19224,
"author_profile": "https://Stackoverflow.com/users/19224",
"pm_score": 0,
"selected": false,
"text": "<p>I found a good way <a href=\"http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] | I need to store app specific configuration in rails. But it has to be:
* reachable in any file (model, view, helpers and controllers
* environment specified (or not), that means each environment can overwrite the configs specified in environment.rb
I've tried to use environment.rb and put something like
```
USE_USER_APP = true
```
that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block.
So, anyone? | I was helping a friend set up [the solution mentioned by Ricardo](http://kpumuk.info/ruby-on-rails/flexible-application-configuration-in-ruby-on-rails/) yesterday. We hacked it a bit by loading the YAML file with something similar to this (going from memory here):
```
require 'ostruct'
require 'yaml'
require 'erb'
#config = OpenStruct.new(YAML.load_file("#{RAILS_ROOT}/config/config.yml"))
config = OpenStruct.new(YAML.load(ERB.new(File.read("#{RAILS_ROOT}/config/config.yml")).result))
env_config = config.send(RAILS_ENV)
config.common.update(env_config) unless env_config.nil?
::AppConfig = OpenStruct.new(config.common)
```
This allowed him to embed Ruby code in the config, like in Rhtml:
```
development:
path_to_something: <%= RAILS_ROOT %>/config/something.yml
``` |
110,083 | <pre><code>String s = "";
for(i=0;i<....){
s = some Assignment;
}
</code></pre>
<p>or</p>
<pre><code>for(i=0;i<..){
String s = some Assignment;
}
</code></pre>
<p>I don't need to use 's' outside the loop ever again.
The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself.</p>
<p>EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through.</p>
<p>Also, the question isn't because I'm worried about memory management. Just want to know which is better.</p>
| [
{
"answer_id": 110090,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 5,
"selected": false,
"text": "<p>In <em>theory</em>, it's a waste of resources to declare the string inside the loop. \nIn <em>practice</em>, however,... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16485/"
] | ```
String s = "";
for(i=0;i<....){
s = some Assignment;
}
```
or
```
for(i=0;i<..){
String s = some Assignment;
}
```
I don't need to use 's' outside the loop ever again.
The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself.
EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through.
Also, the question isn't because I'm worried about memory management. Just want to know which is better. | ### Limited Scope is Best
Use your second option:
```
for ( ... ) {
String s = ...;
}
```
### Scope Doesn't Affect Performance
If you disassemble code the compiled from each (with the JDK's `javap` tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that [Brian R. Bondy's](https://stackoverflow.com/questions/110083/which-of-these-loops-is-better-code-in-terms-of-performance-garbage-collection#110095) "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases.
### Avoid Premature Initialization
The only difference between the two cases is that, in the first example, the variable `s` is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to `s`, and a good JIT compiler will probably elide it at runtime.
You could fix this simply by using an empty declaration (i.e., `String s;`), but this is considered bad practice and has another side-effect discussed below.
Often a bogus value like `null` is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value.
### Conserve Stack Slots
As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope:
```
void x(String[] strings, Integer[] integers) {
String s;
for (int i = 0; i < strings.length; ++i) {
s = strings[0];
...
}
Integer n;
for (int i = 0; i < integers.length; ++i) {
n = integers[i];
...
}
}
```
The variables `s` and `n` could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller.
### What Really Matters
However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application.
The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have. |
110,121 | <p>Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.</p>
<pre><code>object me = new Person();
</code></pre>
<p>Therefore, following this through to its logical conclusion, a group of People would also be a group of objects:</p>
<pre><code>List<Person> people = new List<Person>();
people.Add(me);
people.Add(you);
List<object> things = people; // Ooops.
</code></pre>
<p>Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator). </p>
<p>The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour?</p>
<p>For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely.</p>
| [
{
"answer_id": 110136,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 2,
"selected": false,
"text": "<p>you can use linq to cast it:</p>\n\n<pre><code>IEnumerable<Person> oldList = someIenumarable;\nIEnumerable<ob... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] | Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.
```
object me = new Person();
```
Therefore, following this through to its logical conclusion, a group of People would also be a group of objects:
```
List<Person> people = new List<Person>();
people.Add(me);
people.Add(you);
List<object> things = people; // Ooops.
```
Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator).
The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour?
For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely. | OK, everyone who has used generics in .net must have run into this at one point or another.
Yes, intuitively it should work. No, in the current version of the C# compiler it doesn't.
Eric Lippert has a really good explanation of this issue (it's in eleven parts or something and will bend you mind in places, but it's well worth the read). See [here](http://blogs.msdn.com/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx).
### edit:
dug out another relevant link, this one discusses how java handles this. See [here](http://etymon.blogspot.com/2007/02/java-generics-and-covariance-and.html) |
110,123 | <p>I'm using ASP.NET Web Forms for blog style comments. </p>
<p>Edit 1: This looks way more complicated then I first thought. How do you filter the src?<br>
I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?</p>
| [
{
"answer_id": 110146,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p>Use an XML parser to validate your input, and drop or encode all elements, and attributes, that you do not want to allow... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] | I'm using ASP.NET Web Forms for blog style comments.
Edit 1: This looks way more complicated then I first thought. How do you filter the src?
I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that? | If IMG is the only thing you'd allow, I'd suggest you use a simple square-bracket syntax to allow it. This would eliminate the need for a parser and reduce a load of other dangerous edge cases with the parser as well. Say, something like:
```
Look at this! [http://a.b.c/m.jpg]
```
Which would get converted to
```
Look at this! <img src="http://a.b.c/m.jpg" />
```
You should filter the SRC address so that no malicious things get passed in the SRC part too. Like maybe
```
Look at this! [javascript:alert('pwned!')]
``` |
110,157 | <p>This is one of the possible ways I come out:</p>
<pre><code>struct RetrieveKey
{
template <typename T>
typename T::first_type operator()(T keyValuePair) const
{
return keyValuePair.first;
}
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());
// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));
</code></pre>
<p>Of course, we can also retrieve all values from the map by defining another functor <strong>RetrieveValues</strong>.</p>
<p>Is there any other way to achieve this easily? (I'm always wondering why <code>std::map</code> does not include a member function for us to do so.)</p>
| [
{
"answer_id": 110170,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>The SGI STL has an extension called <a href=\"http://www.sgi.com/tech/stl/select1st.html\" rel=\"noreferrer\"><code>selec... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18638/"
] | This is one of the possible ways I come out:
```
struct RetrieveKey
{
template <typename T>
typename T::first_type operator()(T keyValuePair) const
{
return keyValuePair.first;
}
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());
// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));
```
Of course, we can also retrieve all values from the map by defining another functor **RetrieveValues**.
Is there any other way to achieve this easily? (I'm always wondering why `std::map` does not include a member function for us to do so.) | While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.
I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:
```
std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
key.push_back(it->first);
value.push_back(it->second);
std::cout << "Key: " << it->first << std::endl();
std::cout << "Value: " << it->second << std::endl();
}
```
Or even simpler, if you are using Boost:
```
map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
v.push_back(me.first);
cout << me.first << "\n";
}
```
Personally, I like the BOOST\_FOREACH version because there is less typing and it is very explicit about what it is doing. |
110,163 | <p>I have a rails model that looks something like this:</p>
<pre><code>class Recipe < ActiveRecord::Base
has_many :ingredients
attr_accessor :ingredients_string
attr_accessible :title, :directions, :ingredients, :ingredients_string
before_save :set_ingredients
def ingredients_string
ingredients.join("\n")
end
private
def set_ingredients
self.ingredients.each { |x| x.destroy }
self.ingredients_string ||= false
if self.ingredients_string
self.ingredients_string.split("\n").each do |x|
ingredient = Ingredient.create(:ingredient_string => x)
self.ingredients << ingredient
end
end
end
end
</code></pre>
<p>The idea is that when I create the ingredient from the webpage, I pass in the <code>ingredients_string</code> and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the <code>ingredient_string</code> is defined in the <code>set_ingredients</code> method?</p>
| [
{
"answer_id": 110170,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": false,
"text": "<p>The SGI STL has an extension called <a href=\"http://www.sgi.com/tech/stl/select1st.html\" rel=\"noreferrer\"><code>selec... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] | I have a rails model that looks something like this:
```
class Recipe < ActiveRecord::Base
has_many :ingredients
attr_accessor :ingredients_string
attr_accessible :title, :directions, :ingredients, :ingredients_string
before_save :set_ingredients
def ingredients_string
ingredients.join("\n")
end
private
def set_ingredients
self.ingredients.each { |x| x.destroy }
self.ingredients_string ||= false
if self.ingredients_string
self.ingredients_string.split("\n").each do |x|
ingredient = Ingredient.create(:ingredient_string => x)
self.ingredients << ingredient
end
end
end
end
```
The idea is that when I create the ingredient from the webpage, I pass in the `ingredients_string` and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient\_string (elegantly) and still check to see if the `ingredient_string` is defined in the `set_ingredients` method? | While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.
I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:
```
std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
key.push_back(it->first);
value.push_back(it->second);
std::cout << "Key: " << it->first << std::endl();
std::cout << "Value: " << it->second << std::endl();
}
```
Or even simpler, if you are using Boost:
```
map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
v.push_back(me.first);
cout << me.first << "\n";
}
```
Personally, I like the BOOST\_FOREACH version because there is less typing and it is very explicit about what it is doing. |
110,175 | <p>How can you automatically import the latest build/revision number in subversion?</p>
<p>The goal would be to have that number visible on your webpage footer like SO does.</p>
| [
{
"answer_id": 110182,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "<p>Well, you can run 'svn info' to determine the current revision number, and you could probably extract that pretty easily... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | How can you automatically import the latest build/revision number in subversion?
The goal would be to have that number visible on your webpage footer like SO does. | ```
svn info <Repository-URL>
```
or
```
svn info --xml <Repository-URL>
```
Then look at the result. For xml, parse /info/entry/@revision for the revision of the repository (151 in this example) or /info/entry/commit/@revision for the revision of the last commit against this path (133, useful when working with tags):
```
<?xml version="1.0"?>
<info>
<entry
kind="dir"
path="cmdtools"
revision="151">
<url>http://myserver/svn/stumde/cmdtools</url>
<repository>
<root>http://myserver/svn/stumde</root>
<uuid>a148ce7d-da11-c240-b47f-6810ff02934c</uuid>
</repository>
<commit
revision="133">
<author>mstum</author>
<date>2008-07-12T17:09:08.315246Z</date>
</commit>
</entry>
</info>
```
I wrote a tool ([cmdnetsvnrev](http://www.stum.de/various-tools/cmdtools/), source code included) for myself which replaces the Revision in my AssemblyInfo.cs files. It's limited to that purpose though, but generally svn info and then processing is the way to go. |
110,205 | <p>I want to download this open source application, and they are using Git. What do I need to download the code base?</p>
<p><b>Update</b>
How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it.</p>
| [
{
"answer_id": 110209,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "<p>Download <a href=\"http://code.google.com/p/msysgit/\" rel=\"noreferrer\">Git on Msys</a>. Then:</p>\n\n<pre><code>git ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I want to download this open source application, and they are using Git. What do I need to download the code base?
**Update**
How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it. | Download [Git on Msys](http://code.google.com/p/msysgit/). Then:
```
git clone git://project.url.here
``` |
110,232 | <p>I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go:</p>
<p>I have a three table structure for registering users: <code>Users</code>, <code>Addresses</code> and <code>Contacts</code>. I have to build a view with info of all three tables like:</p>
<pre>
Full Name: [ ] (from Users)
Shipping Address: [ ] (from Address)
Mobile Phone: [ ] (from Contact)
e-Mail Address: [ ] (from Contact)
</pre>
<p>What is the best way to deal with this situation. <em>Specially for saving</em>. Creating a new Model to represent this, that will have a <code>save()</code> method itself (Maybe a sql view in the database) Create a Controller to deal with this View that <code>bind</code>s or <code>unbind</code>s info</p>
<p>I wonder still how I will handle both contacts as they will be 2 different <code>INSERT</code>'s</p>
<p>Any hint or resources I can dig of I will be glad.</p>
| [
{
"answer_id": 110432,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 2,
"selected": false,
"text": "<p>CakePHP allows you to easily maintains link between your models using relationship, see <a href=\"http://book.cakephp.org/v... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] | I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go:
I have a three table structure for registering users: `Users`, `Addresses` and `Contacts`. I have to build a view with info of all three tables like:
```
Full Name: [ ] (from Users)
Shipping Address: [ ] (from Address)
Mobile Phone: [ ] (from Contact)
e-Mail Address: [ ] (from Contact)
```
What is the best way to deal with this situation. *Specially for saving*. Creating a new Model to represent this, that will have a `save()` method itself (Maybe a sql view in the database) Create a Controller to deal with this View that `bind`s or `unbind`s info
I wonder still how I will handle both contacts as they will be 2 different `INSERT`'s
Any hint or resources I can dig of I will be glad. | If your using the latest 1.2 code, check out Model::saveAll in the api
eg. Your view might look something like this:
```
echo $form->create('User', array('action' => 'add');
echo $form->input('User.name');
echo $form->input('Address.line_1');
echo $form->input('Contact.tel');
echo $form->end('Save');
```
Then in your Users controller add method you'd have something like:
```
...
if($this->User->saveAll($this->data)) {
$this->Session->setFlash('Save Successful');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Please review the form for errors');
}
...
```
In your User model you will need something like:
```
var $hasOne = array('Address', 'Contact');
```
Hope that helps!
<http://api.cakephp.org/class_model.html#49f295217028004b5a723caf086a86b1> |
110,249 | <p>Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (<a href="http://www.ddj.com/windows/184406482" rel="nofollow noreferrer">http://www.ddj.com/windows/184406482</a>). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ?</p>
<p>Basically, where can I find any kind of specification instead of MS jargon ?</p>
<p>Thank you to everyone who answered, this was really helpful, </p>
| [
{
"answer_id": 110266,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I've encountered some of these issues, so perhaps some of my comments will be helpful.</p>\n\n<ol>\n<li>The manifes... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11465/"
] | Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (<http://www.ddj.com/windows/184406482>). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ?
Basically, where can I find any kind of specification instead of MS jargon ?
Thank you to everyone who answered, this was really helpful, | We use a simple include file in all our applications & DLL's, vcmanifest.h, then set all projects to embedded the manifest file.
vcmanifest.h
```
/*----------------------------------------------------------------------------*/
#if _MSC_VER >= 1400
/*----------------------------------------------------------------------------*/
#pragma message ( "Setting up manifest..." )
/*----------------------------------------------------------------------------*/
#ifndef _CRT_ASSEMBLY_VERSION
#include <crtassem.h>
#endif
/*----------------------------------------------------------------------------*/
#ifdef WIN64
#pragma message ( "processorArchitecture=amd64" )
#define MF_PROCESSORARCHITECTURE "amd64"
#else
#pragma message ( "processorArchitecture=x86" )
#define MF_PROCESSORARCHITECTURE "x86"
#endif
/*----------------------------------------------------------------------------*/
#pragma message ( "Microsoft.Windows.Common-Controls=6.0.0.0")
#pragma comment ( linker,"/manifestdependency:\"type='win32' " \
"name='Microsoft.Windows.Common-Controls' " \
"version='6.0.0.0' " \
"processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \
"publicKeyToken='6595b64144ccf1df'\"" )
/*----------------------------------------------------------------------------*/
#ifdef _DEBUG
#pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT=" _CRT_ASSEMBLY_VERSION )
#pragma comment(linker,"/manifestdependency:\"type='win32' " \
"name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".DebugCRT' " \
"version='" _CRT_ASSEMBLY_VERSION "' " \
"processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \
"publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
#else
#pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT=" _CRT_ASSEMBLY_VERSION )
#pragma comment(linker,"/manifestdependency:\"type='win32' " \
"name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT' " \
"version='" _CRT_ASSEMBLY_VERSION "' " \
"processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \
"publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
#endif
/*----------------------------------------------------------------------------*/
#ifdef _MFC_ASSEMBLY_VERSION
#ifdef _DEBUG
#pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION )
#pragma comment(linker,"/manifestdependency:\"type='win32' " \
"name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \
"version='" _MFC_ASSEMBLY_VERSION "' " \
"processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \
"publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
#else
#pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC=" _CRT_ASSEMBLY_VERSION )
#pragma comment(linker,"/manifestdependency:\"type='win32' " \
"name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".MFC' " \
"version='" _MFC_ASSEMBLY_VERSION "' " \
"processorArchitecture='" MF_PROCESSORARCHITECTURE "' " \
"publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
#endif
#endif /* _MFC_ASSEMBLY_VERSION */
/*----------------------------------------------------------------------------*/
#endif /* _MSC_VER */
/*----------------------------------------------------------------------------*/
``` |
110,259 | <p>I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory.
Google search shows a commercial one is <a href="http://www.softwareverify.com/python/memory/index.html" rel="noreferrer">Python Memory Validator</a> (Windows only).</p>
<p>And open source ones are <a href="http://pysizer.8325.org/" rel="noreferrer">PySizer</a> and <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="noreferrer">Heapy</a>.</p>
<p>I haven't tried anyone, so I wanted to know which one is the best considering:</p>
<ol>
<li><p>Gives most details.</p></li>
<li><p>I have to do least or no changes to my code.</p></li>
</ol>
| [
{
"answer_id": 110272,
"author": "sanxiyn",
"author_id": 18382,
"author_profile": "https://Stackoverflow.com/users/18382",
"pm_score": 6,
"selected": false,
"text": "<p>I recommend <a href=\"http://www.aminus.net/wiki/Dowser\" rel=\"noreferrer\">Dowser</a>. It is very easy to setup, and ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6946/"
] | I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory.
Google search shows a commercial one is [Python Memory Validator](http://www.softwareverify.com/python/memory/index.html) (Windows only).
And open source ones are [PySizer](http://pysizer.8325.org/) and [Heapy](http://guppy-pe.sourceforge.net/#Heapy).
I haven't tried anyone, so I wanted to know which one is the best considering:
1. Gives most details.
2. I have to do least or no changes to my code. | [guppy3](https://github.com/zhuyifei1999/guppy3/) is quite simple to use. At some point in your code, you have to write the following:
```
from guppy import hpy
h = hpy()
print(h.heap())
```
This gives you some output like this:
```
Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 35144 27 2140412 26 2140412 26 str
1 38397 29 1309020 16 3449432 42 tuple
2 530 0 739856 9 4189288 50 dict (no owner)
```
You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.
There is a graphical browser as well, written in Tk.
For Python 2.x, use [Heapy](http://guppy-pe.sourceforge.net/). |
110,281 | <p>How can I make a style have all of the properties of the style defined in <code>.a .b .c</code> except for <code>background-color</code> (or some other property)? This does not seem to work.</p>
<pre><code>.a .b .c
{
background-color: #0000FF;
color: #ffffff;
border: 1px solid #c0c0c0;
margin-top: 4px;
padding: 3px;
text-align: center;
font-weight: bold;
}
.a .b .c .d
{
background-color: green;
}
</code></pre>
| [
{
"answer_id": 110287,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<pre><code>.a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] | How can I make a style have all of the properties of the style defined in `.a .b .c` except for `background-color` (or some other property)? This does not seem to work.
```
.a .b .c
{
background-color: #0000FF;
color: #ffffff;
border: 1px solid #c0c0c0;
margin-top: 4px;
padding: 3px;
text-align: center;
font-weight: bold;
}
.a .b .c .d
{
background-color: green;
}
``` | You would add the .d class selector as a selector for your first rule, then add a rule to redefine the background color for .d:
```
.a .b .c,
.d {
background-color: #0000FF;
color: #ffffff;
border: 1px solid #c0c0c0;
margin-top: 4px;
padding: 3px;
text-align: center;
font-weight: bold;
}
.d {
background-color: green;
}
```
That is the answer to the question that you've asked, but I have a feeling that this is not what you are looking for. Maybe you should post an example of your markup and tell us what styles you would like to see applied so we can help you better. |
110,305 | <p>I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox?</p>
<p>You can view the live page <a href="http://www.taxminimiser.com/beta/whats_included.php" rel="nofollow noreferrer">here</a>. I know, I'm working on positioning the sidebar. Ignore that for now.</p>
<p>Markup is as follows:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/whats_included.css" />
<script type="text/javascript" src="script/compliant_target_blank.js"></script>
<!--[if lte IE 5]>
<script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script>
<![endif]-->
<!--[if gt IE 5]>
<link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" />
<![endif]-->
<title>
The Daily Plan-It, LLC - Home of the Tax MiniMiser
</title>
</head>
<body>
<?php include("includes/nav_bar.php") ?>
<div id="content">
<img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" />
<div id="bordered_wrapper">
<h1>Here's What You Get With The Tax MiniMiser!</h1>
<h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2>
<ol>
<li class="main_item">
Business Income &amp; Expense Record
<div class="preview_image">
<a href="previews/large/bier/front.html" rel="external">
<img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes with all the income &amp; expense columns you need to transform your planner or binder into a daily tax journal!</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the &quot;20 Column Heading Guidelines&quot;, <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Vehicle Mileage &amp; Expense Record
<div class="preview_image">
<a href="previews/large/vme/front.html" rel="external">
<img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the &quot;Instructions for Vehicle Mileage &amp; Expense Record&quot;, <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Annual Business Summary of Income and Expense
<div class="preview_image">
<a href="previews/large/cover/inside.html" rel="external">
<img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li>
</ul>
</div>
</li>
</ol>
<p class="end">To see previews of the small (6&quot; x 8&frac12;&quot;) Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p>
</div>
</div>
<?php include("includes/footer.php") ?>
</body>
</html>
</code></pre>
<p>And the CSS:</p>
<pre><code>#content {
background-color: white;
}
#bordered_wrapper {
margin-left: 26px;
background: top left no-repeat url(../images/borders/yellow-box-top.gif);
}
#bordered_wrapper h1, #bordered_wrapper h2 {
margin-left: 20px;
}
#bordered_wrapper h1 {
padding-top: 15px;
margin-bottom: 0;
}
#bordered_wrapper h2 {
margin-top: 0;
font-size: 1.3em;
}
ol {
font-size: 1.1em;
}
ul {
list-style-type: disc;
}
li.main_item {
width: 700px;
clear: right;
}
li p {
clear: both;
margin-bottom: 20px;
}
.preview_image {
width: 200px;
float: right;
text-align: center;
margin-bottom: 10px;
}
.preview_image a {
text-decoration: none;
}
.preview_image img {
border-style: none;
}
.end {
clear: right;
padding-bottom: 25px;
padding-left: 20px;
background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif);
}
</code></pre>
| [
{
"answer_id": 110331,
"author": "Abhi Beckert",
"author_id": 19851,
"author_profile": "https://Stackoverflow.com/users/19851",
"pm_score": 0,
"selected": false,
"text": "<p>I just tested your example html in firefox 3/webkit nightly/internet explorer 7 and all of them rendered exactly t... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10140/"
] | I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox?
You can view the live page [here](http://www.taxminimiser.com/beta/whats_included.php). I know, I'm working on positioning the sidebar. Ignore that for now.
Markup is as follows:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/whats_included.css" />
<script type="text/javascript" src="script/compliant_target_blank.js"></script>
<!--[if lte IE 5]>
<script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script>
<![endif]-->
<!--[if gt IE 5]>
<link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" />
<![endif]-->
<title>
The Daily Plan-It, LLC - Home of the Tax MiniMiser
</title>
</head>
<body>
<?php include("includes/nav_bar.php") ?>
<div id="content">
<img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" />
<div id="bordered_wrapper">
<h1>Here's What You Get With The Tax MiniMiser!</h1>
<h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2>
<ol>
<li class="main_item">
Business Income & Expense Record
<div class="preview_image">
<a href="previews/large/bier/front.html" rel="external">
<img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes with all the income & expense columns you need to transform your planner or binder into a daily tax journal!</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the "20 Column Heading Guidelines", <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Vehicle Mileage & Expense Record
<div class="preview_image">
<a href="previews/large/vme/front.html" rel="external">
<img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the "Instructions for Vehicle Mileage & Expense Record", <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Annual Business Summary of Income and Expense
<div class="preview_image">
<a href="previews/large/cover/inside.html" rel="external">
<img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li>
</ul>
</div>
</li>
</ol>
<p class="end">To see previews of the small (6" x 8½") Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p>
</div>
</div>
<?php include("includes/footer.php") ?>
</body>
</html>
```
And the CSS:
```
#content {
background-color: white;
}
#bordered_wrapper {
margin-left: 26px;
background: top left no-repeat url(../images/borders/yellow-box-top.gif);
}
#bordered_wrapper h1, #bordered_wrapper h2 {
margin-left: 20px;
}
#bordered_wrapper h1 {
padding-top: 15px;
margin-bottom: 0;
}
#bordered_wrapper h2 {
margin-top: 0;
font-size: 1.3em;
}
ol {
font-size: 1.1em;
}
ul {
list-style-type: disc;
}
li.main_item {
width: 700px;
clear: right;
}
li p {
clear: both;
margin-bottom: 20px;
}
.preview_image {
width: 200px;
float: right;
text-align: center;
margin-bottom: 10px;
}
.preview_image a {
text-decoration: none;
}
.preview_image img {
border-style: none;
}
.end {
clear: right;
padding-bottom: 25px;
padding-left: 20px;
background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif);
}
``` | Congratulations, you are the victim of IE's [hasLayout](http://msdn.microsoft.com/en-us/library/ms533776.aspx) property.
Short version: You've got it easy this time. Changes these rules:
```
...
ol {
font-size: 1.1em;
}
...
li.main_item {
width: 700px;
clear: right;
}
...
```
To this:
```
...
ol {
font-size: 1.1em;
width: 700px;
}
...
li.main_item {
clear: right;
}
...
```
And it's all good.
Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called "hasLayout" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use [conditional comments](http://www.quirksmode.org/css/condcom.html) to fix it just for IE. Here are some CSS rules that add "hasLayout" to an element that doesn't already have it:
* position: absolute
* float: left|right
* display: inline-block
* height: any value other than 'auto'
* zoom: any value other than 'normal' (MS proprietary)
* writing-mode: tb-rl (MS proprietary)
As of IE7, overflow became a trigger for hasLayout.
* overflow: hidden|scroll|auto
Longest version: read the following articles.
1. Here's all the neat things Microsoft would like you do [by triggering "hasLayout"](http://msdn.microsoft.com/en-us/library/bb250481.aspx).
2. Here's the clean-language version of [what web designers thought about hasLayout](http://www.satzansatz.de/cssd/onhavinglayout) when they found out what was going on. Some of the same content, but includes CSS hacks and stuff. |
110,313 | <p>If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure?</p>
<p>With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups.</p>
<p>Note that I don't consider it a good option to "make the developers push branches to a server" -- that's <a href="http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html" rel="nofollow noreferrer">tedious</a> and the developers will end up not doing it.</p>
<p>Is there a common way around this problem?</p>
<p><strong>Some clarification:</strong></p>
<p>With a natively-central-server VCS then <em>everything</em> has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately.</p>
<p>If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server".</p>
<p>So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe?</p>
| [
{
"answer_id": 110319,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>It's not uncommon to use a \"central\" server as an authority in DVCS, which also provides you the place to do your b... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] | If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure?
With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups.
Note that I don't consider it a good option to "make the developers push branches to a server" -- that's [tedious](http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html) and the developers will end up not doing it.
Is there a common way around this problem?
**Some clarification:**
With a natively-central-server VCS then *everything* has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately.
If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server".
So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe? | I think that you will find that in practice developers will prefer to use a central repository than pushing and pulling between each other's local repositories. Once you've cloned a central repository, while working on any tracking branches, fetching and pushing are trivial commands. Adding half a dozen remotes to all your colleagues' local repositories is a pain and these repositories may not always be accessible (switched off, on a laptop taken home, etc.).
At some point, if you are all working on the same project, all the work needs to be integrated. This means that you need an integration branch where all the changes come together. This naturally needs to be somewhere accessible by all the developers, it doesn't belong, for example, on the lead developer's laptop.
Once you've set up a central repository you can use a cvs/svn style workflow to check in and update. cvs update becomes git fetch and rebase if you have local changes or just git pull if you don't. cvs commit becomes git commit and git push.
With this setup you are in a similar position with your fully centralized VCS system. Once developers submit their changes (git push), which they need to do to be visible to the rest of the team, they are on the central server and will be backed up.
What takes discipline in both cases is preventing developers keeping long running changes out of the central repository. Most of us have probably worked in a situation where one developer is working on feature 'x' which needs a fundamental change in some core code. The change will cause everyone else to need to completely rebuild but the feature isn't ready for the main stream yet so he just keeps it checked out until a suitable point in time.
The situation is very similar in both situations although there are some practical differences. Using git, because you get to perform local commits and can manage local history, the need to push to the central repository may not be felt as much by the individual developer as with something like cvs.
On the other hand, the use of local commits can be used as an advantage. Pushing all local commits to a safe place on the central repository should not be very difficult. Local branches can be stored in a developer specific tag namespace.
For example, for Joe Bloggs, An alias could be made in his local repository to perform something like the following in response to (e.g.) `git mybackup`.
```
git push origin +refs/heads/*:refs/jbloggs/*
```
This is a single command that can be used at any point (such as the end of the day) to make sure that all his local changes are safely backed up.
This helps with all sorts of disasters. Joe's machine blows up and he can use another machine and fetch is saved commits and carry on from where he left off. Joe's ill? Fred can fetch Joe's branches to grab that 'must have' fix that he made yesterday but didn't have a chance to test against master.
To go back to the original question. Does there need to be a difference between dVCS and centralized VCS? You say that half-implemented features and bugfixes will not end up on the central repository in the dVCS case but I would contend that there need be no difference.
I have seen many cases where a half-implemented feature stays on one developers working box when using centralized VCS. It either takes a policy that allows half written features to be checked in to the main stream or a decision has to be made to create a central branch.
In the dVCS the same thing can happen, but the same decision should be made. If there is important but incomplete work, it needs to be saved centrally. The advantage of git is that creating this central branch is almost trivial. |
110,314 | <p>So, I am using the Linq entity framework. I have 2 entities: <code>Content</code> and <code>Tag</code>. They are in a many-to-many relationship with one another. <code>Content</code> can have many <code>Tags</code> and <code>Tag</code> can have many <code>Contents</code>. So I am trying to write a query to select all contents where any tags names are equal to <code>blah</code></p>
<p>The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for <code>Contains</code> (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1</a></p>
<h2>Edit 1</h2>
<p><a href="https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551">I ended up finding my own answer.</a></p>
| [
{
"answer_id": 110348,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "<pre><code>tags.Select(testTag => testTag.Name)\n</code></pre>\n\n<p>Where does the tags variable gets initialized from? ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19854/"
] | So, I am using the Linq entity framework. I have 2 entities: `Content` and `Tag`. They are in a many-to-many relationship with one another. `Content` can have many `Tags` and `Tag` can have many `Contents`. So I am trying to write a query to select all contents where any tags names are equal to `blah`
The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for `Contains` (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&SiteID=1>
Edit 1
------
[I ended up finding my own answer.](https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551) | After reading about the [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx), reading all of the wonderful posts that people sent to me, posting on other sites, and then reading more on [Combining Predicates](http://blogs.msdn.com/meek/archive/2008/05/02/linq-to-entities-combining-predicates.aspx) and [Canonical Function Mapping](http://msdn.microsoft.com/en-us/library/bb738681.aspx).. oh and I picked up a bit from [Calling functions in LINQ queries](http://tomasp.net/blog/linq-expand.aspx) (some of these classes were taken from these pages).
I FINALLY have a solution!!! Though there is a piece that is a bit hacked...
Let's get the hacked piece over with :(
I had to use reflector and copy the ExpressionVisitor class that is marked as internal. I then had to make some minor changes to it, to get it to work. I had to create two exceptions (because it was newing internal exceptions. I also had to change the ReadOnlyCollection() method's return from:
```
return sequence.ToReadOnlyCollection<Expression>();
```
To:
```
return sequence.AsReadOnly();
```
I would post the class, but it is quite large and I don't want to clutter this post any more than it's already going to be. I hope that in the future that class can be removed from my library and that Microsoft will make it public. Moving on...
I added a ParameterRebinder class:
```
public class ParameterRebinder : ExpressionVisitor {
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) {
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) {
return new ParameterRebinder(map).Visit(exp);
}
internal override Expression VisitParameter(ParameterExpression p) {
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement)) {
p = replacement;
}
return base.VisitParameter(p);
}
}
```
Then I added a ExpressionExtensions class:
```
public static class ExpressionExtensions {
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) {
// build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) {
return first.Compose(second, Expression.And);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) {
return first.Compose(second, Expression.Or);
}
}
```
And the last class I added was PredicateBuilder:
```
public static class PredicateBuilder {
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
}
```
This is my result... I was able to execute this code and get back the resulting "content" entities that have matching "tag" entities from the tags that I was searching for!
```
public static IList<Content> GetAllContentByTags(IList<Tag> tags) {
IQueryable<Content> contentQuery = ...
Expression<Func<Content, bool>> predicate = PredicateBuilder.False<Content>();
foreach (Tag individualTag in tags) {
Tag tagParameter = individualTag;
predicate = predicate.Or(p => p.Tags.Any(tag => tag.Name.Equals(tagParameter.Name)));
}
IQueryable<Content> resultExpressions = contentQuery.Where(predicate);
return resultExpressions.ToList();
}
```
Please let me know if anyone needs help with this same thing, if you would like me to send you files for this, or just need more info. |
110,325 | <p>Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.</p>
| [
{
"answer_id": 110372,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 4,
"selected": true,
"text": "<p>Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fail... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19857/"
] | Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped. | Create a trigger that processes on INSERT. This trigger will do a validation check on your date field. If it fails the validation, then do an insert into your separate table, and you can also choose to continue the insert or not allow it to go through.
an **important** note: by default triggers do not fire on bulk inserts (BCP & SSIS included). To get this to work, you'll need to specify that you want the trigger to fire, using something like:
```
BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS )
``` |
110,332 | <p>I have an <code>NSArray</code> and I'd like to create a new <code>NSArray</code> with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a <code>BOOL</code>.</p>
<p>I can create an <code>NSMutableArray</code>, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.</p>
<p>Is there a better way?</p>
| [
{
"answer_id": 110343,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 8,
"selected": true,
"text": "<p><code>NSArray</code> and <code>NSMutableArray</code> provide methods to filter array contents. <code>NSArray</code> provides... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] | I have an `NSArray` and I'd like to create a new `NSArray` with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a `BOOL`.
I can create an `NSMutableArray`, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.
Is there a better way? | `NSArray` and `NSMutableArray` provide methods to filter array contents. `NSArray` provides **filteredArrayUsingPredicate:** which returns a new array containing objects in the receiver that match the specified predicate. `NSMutableArray` adds **filterUsingPredicate:** which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.
```
NSMutableArray *array =
[NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSPredicate *bPredicate =
[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
[array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.
NSPredicate *sPredicate =
[NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filteredArrayUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }
``` |
110,336 | <p>Here's my issue: I need to close a process, already running, from a C# program.
The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never
have a main window. </p>
<p>The other requirement that I have is that the application be <strong>closed</strong> not <strong>killed</strong>. I need it to write it's memory buffers to disk - and killing it causes data loss.</p>
<p>Here's what I tried so far:</p>
<pre><code> foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.ToLower().StartsWith("myapp"))
{
if (proc.MainWindowHandle.ToInt32() != 0)
{
proc.CloseMainWindow();
proc.Close();
//proc.Kill(); <--- not good!
}
}
}
</code></pre>
<p>I've added the <strong>if</strong> clause, after discovering that <strong>MainWindowHandle == 0</strong> when the window was minimized. Removing the <strong>if</strong> doesn't help. Neither the <strong>CloseMainWindow()</strong> nor the <strong>Close()</strong> work. The <strong>Kill()</strong> does, but as mentioned above - it's not what I need.</p>
<p>Any idea would be accepted, including the use of arcane Win32 API functions :)</p>
| [
{
"answer_id": 110401,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "<p>If it's on the taskbar, it'll have a window. Or did you mean that it's in the taskbar notification area (aka the ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19856/"
] | Here's my issue: I need to close a process, already running, from a C# program.
The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never
have a main window.
The other requirement that I have is that the application be **closed** not **killed**. I need it to write it's memory buffers to disk - and killing it causes data loss.
Here's what I tried so far:
```
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.ToLower().StartsWith("myapp"))
{
if (proc.MainWindowHandle.ToInt32() != 0)
{
proc.CloseMainWindow();
proc.Close();
//proc.Kill(); <--- not good!
}
}
}
```
I've added the **if** clause, after discovering that **MainWindowHandle == 0** when the window was minimized. Removing the **if** doesn't help. Neither the **CloseMainWindow()** nor the **Close()** work. The **Kill()** does, but as mentioned above - it's not what I need.
Any idea would be accepted, including the use of arcane Win32 API functions :) | Here are some answers and clarifications:
**rpetrich**:
Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0.
**Roger**:
Yes, I did mean the taskbar notification area - thanks for the clarification.
I *NEED* to call PostQuitMessage. I just don't know how, given a processs only, and not a Window.
**Craig**:
I'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'.
Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it.
Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down.
Hope that clarifies my situation, and again, thanks everyone who's trying to help! |
110,341 | <p>Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option.</p>
<p>The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client.</p>
<p>So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK_RAW, and not SOCK_STREAM)? I would be very grateful.</p>
<hr>
<p>MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH!</p>
<p>The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this:</p>
<pre><code>iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP
</code></pre>
| [
{
"answer_id": 110349,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a tutorial, but I recently used <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wiresha... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19860/"
] | Ok, I realize this situation is somewhat unusual, but I need to establish a TCP connection (the 3-way handshake) using only raw sockets (in C, in linux) -- i.e. I need to construct the IP headers and TCP headers myself. I'm writing a server (so I have to first respond to the incoming SYN packet), and for whatever reason I can't seem to get it right. Yes, I realize that a SOCK\_STREAM will handle this for me, but for reasons I don't want to go into that isn't an option.
The tutorials I've found online on using raw sockets all describe how to build a SYN flooder, but this is somewhat easier than actually establishing a TCP connection, since you don't have to construct a response based on the original packet. I've gotten the SYN flooder examples working, and I can read the incoming SYN packet just fine from the raw socket, but I'm still having trouble creating a valid SYN/ACK response to an incoming SYN from the client.
So, does anyone know a good tutorial on using raw sockets that goes beyond creating a SYN flooder, or does anyone have some code that could do this (using SOCK\_RAW, and not SOCK\_STREAM)? I would be very grateful.
---
MarkR is absolutely right -- the problem is that the kernel is sending reset packets in response to the initial packet because it thinks the port is closed. The kernel is beating me to the response and the connection dies. I was using tcpdump to monitor the connection already -- I should have been more observant and noticed that there were TWO replies one of which was a reset that was screwing things up, as well as the response my program created. D'OH!
The solution that seems to work best is to use an iptables rule, as suggested by MarkR, to block the outbound packets. However, there's an easier way to do it than using the mark option, as suggested. I just match whether the reset TCP flag is set. During the course of a normal connection this is unlikely to be needed, and it doesn't really matter to my application if I block all outbound reset packets from the port being used. This effectively blocks the kernel's unwanted response, but not my own packets. If the port my program is listening on is 9999 then the iptables rule looks like this:
```
iptables -t filter -I OUTPUT -p tcp --sport 9999 --tcp-flags RST RST -j DROP
``` | You want to implement part of a TCP stack in userspace... this is ok, some other apps do this.
One problem you will come across is that the kernel will be sending out (generally negative, unhelpful) replies to incoming packets. This is going to screw up any communication you attempt to initiate.
One way to avoid this is to use an IP address and interface that the kernel does not have its own IP stack using- which is fine but you will need to deal with link-layer stuff (specifically, arp) yourself. That would require a socket lower than IPPROTO\_IP, SOCK\_RAW - you need a packet socket (I think).
It may also be possible to block the kernel's responses using an iptables rule- but I rather suspect that the rules will apply to your own packets as well somehow, unless you can manage to get them treated differently (perhaps applying a netfilter "mark" to your own packets?)
Read the man pages
socket(7)
ip(7)
packet(7)
Which explain about various options and ioctls which apply to types of sockets.
Of course you'll need a tool like Wireshark to inspect what's going on. You will need several machines to test this, I recommend using vmware (or similar) to reduce the amount of hardware required.
Sorry I can't recommend a specific tutorial.
Good luck. |
110,354 | <p>I want to do this:</p>
<pre><code>e.className = t;
</code></pre>
<p>Where t is the name of a style I have defined in a stylesheet.</p>
| [
{
"answer_id": 110357,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15059/"
] | I want to do this:
```
e.className = t;
```
Where t is the name of a style I have defined in a stylesheet. | If `e` is a reference to a DOM element and you have a class like this: `.t {color:green;}` then you want reference the class name as a string:
```
e.className = 't';
``` |
110,378 | <p>How can I change the width of a textarea form element if I used ModelForm to create it?</p>
<p>Here is my product class:</p>
<pre><code>class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
</code></pre>
<p>And the template code...</p>
<pre><code>{% for f in form %}
{{ f.name }}:{{ f }}
{% endfor %}
</code></pre>
<p><code>f</code> is the actual form element...</p>
| [
{
"answer_id": 110414,
"author": "zuber",
"author_id": 9812,
"author_profile": "https://Stackoverflow.com/users/9812",
"pm_score": 8,
"selected": true,
"text": "<p><strong>The easiest way for your use case is to use CSS</strong>. It's a language meant for defining presentation. Look at t... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] | How can I change the width of a textarea form element if I used ModelForm to create it?
Here is my product class:
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
And the template code...
```
{% for f in form %}
{{ f.name }}:{{ f }}
{% endfor %}
```
`f` is the actual form element... | **The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.
Example for `long_desc` field in your ProductForm (when your form does not have a custom prefix):
```
#id_long_desc {
width: 300px;
height: 200px;
}
```
**Second approach** is to pass the `attrs` keyword to your widget constructor.
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
It's [described in Django documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs).
**Third approach** is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
# Edit by bryan
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
self.fields['long_desc'].widget.attrs['cols'] = 10
self.fields['long_desc'].widget.attrs['rows'] = 20
```
This approach has the following advantages:
* You can define widget attributes for fields that are generated automatically from your model without redefining whole fields.
* It doesn't depend on the prefix of your form. |
110,384 | <p>I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?</p>
<p>Doesn't work:</p>
<pre><code> [AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = View("User/Login");
}
}
}
</code></pre>
| [
{
"answer_id": 110630,
"author": "Jeremy Skinner",
"author_id": 8560,
"author_profile": "https://Stackoverflow.com/users/8560",
"pm_score": 2,
"selected": true,
"text": "<p>You can instantiate the appropriate ActionResult directly, then set it on the context. For example:</p>\n\n<pre><co... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?
Doesn't work:
```
[AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = View("User/Login");
}
}
}
``` | You can instantiate the appropriate ActionResult directly, then set it on the context. For example:
```
public void OnAuthorization(AuthorizationContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new ViewResult { ViewName = "Whatever" };
}
}
``` |
110,385 | <p>I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below.</p>
<p>I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue.</p>
<ul>
<li>Is there a better way to do this?</li>
<li>Is it a good idea to unhook are rehook the event handlers like I did.</li>
</ul>
<p>Here's the code. </p>
<pre><code>private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>();
private const int MaxFavoredAttributes = 5;
private void favoredAttributes_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
if (cb.Checked)
{
if (favAttributesLimiter.Count == MaxFavoredAttributes)
{
CheckBox oldest = favAttributesLimiter.Dequeue();
oldest.CheckedChanged -= favoredAttributes_CheckedChanged;
oldest.Checked = false;
oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged);
}
favAttributesLimiter.Enqueue(cb);
}
else // cb.Checked == false
{
if (favAttributesLimiter.Contains(cb))
{
var list = favAttributesLimiter.ToList();
list.Remove(cb);
favAttributesLimiter=new Queue<CheckBox>(list);
}
}
}
</code></pre>
<p>Edit: <br />
<a href="https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398">Chakrit</a> answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.</p>
| [
{
"answer_id": 110398,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": true,
"text": "<p>I think you are looking for a <a href=\"http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx\" rel=\"nofollow noreferrer\... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880/"
] | I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below.
I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue.
* Is there a better way to do this?
* Is it a good idea to unhook are rehook the event handlers like I did.
Here's the code.
```
private Queue<CheckBox> favAttributesLimiter - new Queue<CheckBox>();
private const int MaxFavoredAttributes = 5;
private void favoredAttributes_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
if (cb.Checked)
{
if (favAttributesLimiter.Count == MaxFavoredAttributes)
{
CheckBox oldest = favAttributesLimiter.Dequeue();
oldest.CheckedChanged -= favoredAttributes_CheckedChanged;
oldest.Checked = false;
oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged);
}
favAttributesLimiter.Enqueue(cb);
}
else // cb.Checked == false
{
if (favAttributesLimiter.Contains(cb))
{
var list = favAttributesLimiter.ToList();
list.Remove(cb);
favAttributesLimiter=new Queue<CheckBox>(list);
}
}
}
```
Edit:
[Chakrit](https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398) answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user. | I think you are looking for a [LinkedList](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx).
Use `AddLast` instead of `Enqueue` and `RemoveFirst` instead of `Dequeue` and for removing something in the middle, just use a normal `Remove`. |
110,430 | <p>Do you write one test per function/method, with multiple checks in the test, or a test for each check?</p>
| [
{
"answer_id": 110434,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 2,
"selected": false,
"text": "<p>A test case for each check. It's more granular. It makes it much easier to see what specific test case failed.</p>\n... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
] | Do you write one test per function/method, with multiple checks in the test, or a test for each check? | One test per check and super descriptive names, per instance:
```
@Test
public void userCannotVoteDownWhenScoreIsLessThanOneHundred() {
...
}
```
Both only one assertion and using good names gives me a better report when a test fails. They scream to me: "You broke THAT rule!". |
110,436 | <p>Any recommended practices for cleaning up "header spaghetti" which is causing extremely
slow compilation times (Linux/Unix)?</p>
<p>Is there any equvalent to "#pragma once" with GCC?<br>
(found conflicting messages regarding this)</p>
<p>Thanks.</p>
| [
{
"answer_id": 110448,
"author": "andreas buykx",
"author_id": 19863,
"author_profile": "https://Stackoverflow.com/users/19863",
"pm_score": 1,
"selected": false,
"text": "<p>In headers: include headers only if you can't use forward declaration, but always #include any file that you need... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Any recommended practices for cleaning up "header spaghetti" which is causing extremely
slow compilation times (Linux/Unix)?
Is there any equvalent to "#pragma once" with GCC?
(found conflicting messages regarding this)
Thanks. | Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards.
It was discussed in "[Large Scale C++ Software Design](http://vig.pearsoned.com/store/product/1,1207,store-15080_isbn-0201633620,00.html)". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor parsing required to ignore the header from the 2nd time on (i.e. it still has to parse and look for the start and end of the include guard. With external include guards you place the #ifdef's around the #include line itself.
So it looks like this:
```
#ifndef MY_HEADER
#include "myheader.h"
#endif
```
and of course within the H file you have the classic include guard
```
#ifndef MY_HEADER
#define MY_HEADER
// content of header
#endif
```
This way the myheader.h file isn't even opened / parsed by the preprocessor, and it can save you a lot of time in large projects, especially when header files sit on shared remote locations, as they sometimes do.
again, it's all in that book. hth |
110,451 | <p>I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There <em>are</em> templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere?</p>
| [
{
"answer_id": 110502,
"author": "adondai",
"author_id": 19713,
"author_profile": "https://Stackoverflow.com/users/19713",
"pm_score": 2,
"selected": false,
"text": "<p>If you are a student you could get the full Visual Studio 2008 from <a href=\"http://dreamspark.com\" rel=\"nofollow no... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14607/"
] | I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There *are* templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere? | If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default):
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress
```
The VC# templates live in:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress
```
Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ProjectTemplates\1033
```
into:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress\ProjectTemplates\CSharp\Windows\1033
```
The templates won't appear straight away in the template browser. For VWD you need to run:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplates
```
For VC# you run:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress.exe /installvstemplates
``` |
110,498 | <p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
| [
{
"answer_id": 110547,
"author": "olt",
"author_id": 19759,
"author_profile": "https://Stackoverflow.com/users/19759",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://linux.die.net/diveintopython/html/http_web_services/redirects.html\" rel=\"nofollow noreferrer\">Dive Int... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple. | Here is the [Requests](http://docs.python-requests.org/en/latest/) way:
```
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])
``` |
110,512 | <p>I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.</p>
<p>I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.</p>
<p>As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.</p>
<p>What configuration gotchas should I look out for with this type of setup?</p>
| [
{
"answer_id": 110799,
"author": "tomtaylor",
"author_id": 19079,
"author_profile": "https://Stackoverflow.com/users/19079",
"pm_score": 3,
"selected": true,
"text": "<p>I would probably just move all the apps to mod_rails, as the performance seems comparable to Mongrel and there's less ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10596/"
] | I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.
I'd like to move 7 of these applications to mod\_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.
As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.
What configuration gotchas should I look out for with this type of setup? | I would probably just move all the apps to mod\_rails, as the performance seems comparable to Mongrel and there's less administration overhead.
With regards to configuration gotchas, just make sure that you allow your public directory, or you'll find static assets failing:
```
<Directory "/var/www/app/current/public">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
```
Aside from that, if you know how to configure Apache, mod\_rails is very painless. |
110,536 | <p>I have the following code:</p>
<pre><code>string prefix = "OLD:";
Func<string, string> prependAction = (x => prefix + x);
prefix = "NEW:";
Console.WriteLine(prependAction("brownie"));
</code></pre>
<p>Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.</p>
<p>Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:</p>
<pre><code>Func<string, string> prependAction = (x => "OLD:" + x);
</code></pre>
<p>The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. </p>
<p>The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:</p>
<pre><code>string prefix = "NEW:";
var prepender = new Prepender {Prefix = prefix};
Func<string, string> prependAction = prepender.Prepend;
prefix = "OLD:";
Console.WriteLine(prependAction("brownie"));
</code></pre>
<p>With helper class:</p>
<pre><code>[Serializable]
public class Prepender
{
public string Prefix { get; set; }
public string Prepend(string str)
{
return Prefix + str;
}
}
</code></pre>
<p>This seems like a lot of extra work to get the compiler to be "dumb".</p>
| [
{
"answer_id": 110540,
"author": "Dested",
"author_id": 11137,
"author_profile": "https://Stackoverflow.com/users/11137",
"pm_score": -1,
"selected": false,
"text": "<p>What about this</p>\n\n<pre><code>string prefix = \"OLD:\";\nstring _prefix=prefix;\nFunc<string, string> prepend... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6600/"
] | I have the following code:
```
string prefix = "OLD:";
Func<string, string> prependAction = (x => prefix + x);
prefix = "NEW:";
Console.WriteLine(prependAction("brownie"));
```
Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.
Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:
```
Func<string, string> prependAction = (x => "OLD:" + x);
```
The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize.
The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:
```
string prefix = "NEW:";
var prepender = new Prepender {Prefix = prefix};
Func<string, string> prependAction = prepender.Prepend;
prefix = "OLD:";
Console.WriteLine(prependAction("brownie"));
```
With helper class:
```
[Serializable]
public class Prepender
{
public string Prefix { get; set; }
public string Prepend(string str)
{
return Prefix + str;
}
}
```
This seems like a lot of extra work to get the compiler to be "dumb". | I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization".
There is an explanation of it [here](http://social.msdn.microsoft.com/Forums/en-US/67f63b9a-ea44-4428-aea0-5dcdb61e918b/binding-lambdas-when-they-are-closures). |
110,562 | <p>I need to write a function that receives a property as a parameter and execute its getter.</p>
<p>If I needed to pass a function/delegate I would have used:</p>
<pre><code>delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate function, T param, ...)
{
...
return function.Invoke(param);
}
</code></pre>
<p>Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?</p>
| [
{
"answer_id": 110569,
"author": "Martijn",
"author_id": 17439,
"author_profile": "https://Stackoverflow.com/users/17439",
"pm_score": 2,
"selected": false,
"text": "<p>Properties are simply syntactic sugar for methods.</p>\n\n<p>I don't think you can modify a property such that it becom... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361/"
] | I need to write a function that receives a property as a parameter and execute its getter.
If I needed to pass a function/delegate I would have used:
```
delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate function, T param, ...)
{
...
return function.Invoke(param);
}
```
Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code? | You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method.
The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code:
For example to get the value of property Foo of object obj you can write:
```
value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null);
```
to set it:
```
obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value});
```
So you can pass obj.GetType().GetProperty("Foo").GetAccessors()[0] to your method and execute it's Invoke method.
an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example:
```
delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate<T,RET> function, T param, ...)
{
...
return function(param);
}
```
for a property named Foo of type int that is part of a class SomeClass:
```
SomeClass obj = new SomeClass();
func<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj);
``` |
110,575 | <p>Earlier today a question was asked regarding <a href="https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d">input validation strategies in web apps</a>.</p>
<p>The top answer, at time of writing, suggests in <code>PHP</code> just using <code>htmlspecialchars</code> and <code>mysql_real_escape_string</code>. </p>
<p>My question is: Is this always enough? Is there more we should know? Where do these functions break down?</p>
| [
{
"answer_id": 110576,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 9,
"selected": true,
"text": "<p>When it comes to database queries, always try and use prepared parameterised queries. The <code>mysqli</code> and <code... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] | Earlier today a question was asked regarding [input validation strategies in web apps](https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d).
The top answer, at time of writing, suggests in `PHP` just using `htmlspecialchars` and `mysql_real_escape_string`.
My question is: Is this always enough? Is there more we should know? Where do these functions break down? | When it comes to database queries, always try and use prepared parameterised queries. The `mysqli` and `PDO` libraries support this. This is infinitely safer than using escaping functions such as `mysql_real_escape_string`.
Yes, `mysql_real_escape_string` is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.
Imagine the following SQL:
```
$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
```
You should be able to see that this is vulnerable to exploit.
Imagine the `id` parameter contained the common attack vector:
```
1 OR 1=1
```
There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:
```
SELECT fields FROM table WHERE id= 1 OR 1=1
```
Which is a lovely SQL injection vector and would allow the attacker to return all the rows.
Or
```
1 or is_admin=1 order by id limit 1
```
which produces
```
SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1
```
Which allows the attacker to return the first administrator's details in this completely fictional example.
Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that `1 OR 1=1` is not a valid literal.
As for `htmlspecialchars()`. That's a minefield of its own.
There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what.
Firstly, if you are inside an HTML tag, you are in real trouble. Look at
```
echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />';
```
We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be `javascript:alert(document.cookie)`
Now resultant HTML looks like
```
<img src= "javascript:alert(document.cookie)" />
```
The attack gets straight through.
It gets worse. Why? because `htmlspecialchars` (when called this way) only encodes double quotes and not single. So if we had
```
echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />";
```
Our evil attacker can now inject whole new parameters
```
pic.png' onclick='location.href=xxx' onmouseover='...
```
gives us
```
<img src='pic.png' onclick='location.href=xxx' onmouseover='...' />
```
In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the [XSS cheat sheet](http://ha.ckers.org/xss.html) for examples on how diverse vectors can be
Even if you use `htmlspecialchars($string)` outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors.
The most effective you can be is to use the a combination of mb\_convert\_encoding and htmlentities as follows.
```
$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
```
Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off.
For a more in-depth study to the multibyte problems, see <https://stackoverflow.com/a/12118602/1820> |
110,584 | <p>I have a document library with about 50 available content types. This document library is divided into several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong?</p>
<p>private void CreateFolder(SPFolder parent, string name)
{
SPFolder z = parent.SubFolders.Add(name);
List col = new List();</p>
<pre><code> foreach (SPContentType type in myDocumentLibrary.ContentTypes)
{
if (ContentTypeMatchesName(name, type))
{
col.Add(type);
}
}
z.UniqueContentTypeOrder = col;
z.Update();
}
</code></pre>
| [
{
"answer_id": 110711,
"author": "Magnus Johansson",
"author_id": 3584,
"author_profile": "https://Stackoverflow.com/users/3584",
"pm_score": 3,
"selected": true,
"text": "<p>Have you looked at <a href=\"http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2D... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19884/"
] | I have a document library with about 50 available content types. This document library is divided into several folders. When a user cliks the "New" button in a folder, all available content types are offered. I need to limit the content types according to the folder. For example, in the folder "Legal" a want to have only content types containing legal documents. I tried to use the UniqueContentTypeOrder property of SPFolder but it does not work. What is wrong?
private void CreateFolder(SPFolder parent, string name)
{
SPFolder z = parent.SubFolders.Add(name);
List col = new List();
```
foreach (SPContentType type in myDocumentLibrary.ContentTypes)
{
if (ContentTypeMatchesName(name, type))
{
col.Add(type);
}
}
z.UniqueContentTypeOrder = col;
z.Update();
}
``` | Have you looked at [this](http://www.tonstegeman.com/Blog/Lists/Posts/Post.aspx?List=70640fe5%2D28d9%2D464f%2Db1c9%2D91e07c8f7e47&ID=56) article by Ton Stegeman? |
110,587 | <p>in a DB2 trigger, I need to compare the value of a CLOB field.
Something like:</p>
<pre><code>IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD
</code></pre>
<p>but "!=" does not work for comparing CLOBs.</p>
<p>What is the way to compare it?</p>
<p><strong>Edited to add:</strong></p>
<p>My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code.
<strong>I'm looking for some detailed information on how this can be done</strong></p>
| [
{
"answer_id": 110797,
"author": "Mat Mannion",
"author_id": 6282,
"author_profile": "https://Stackoverflow.com/users/6282",
"pm_score": 1,
"selected": false,
"text": "<p>I believe it's not possible to use these kind of operators on CLOB fields, because of the way they're stored.</p>\n"
... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11710/"
] | in a DB2 trigger, I need to compare the value of a CLOB field.
Something like:
```
IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD
```
but "!=" does not work for comparing CLOBs.
What is the way to compare it?
**Edited to add:**
My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code.
**I'm looking for some detailed information on how this can be done** | Calculate the md5 (or other) hash of the clobs and then compare these. Initial calculation will be slow but comparison is fast and easy. This could be a good method if the bulk of your data doesn't change very often.
One way to calculate md5 is through a java statement in your trigger. Save these in the same table (if possible) or build a simple auxiliary table. |
110,749 | <p>How would you write a regular expression to convert mark down into HTML? For example, you would type in the following:</p>
<pre><code>This would be *italicized* text and this would be **bold** text
</code></pre>
<p>This would then need to be converted to:</p>
<pre><code>This would be <em>italicized</em> text and this would be <strong>bold</strong> text
</code></pre>
<p>Very similar to the mark down edit control used by stackoverflow.</p>
<p><strong>Clarification</strong></p>
<p>For what it is worth, I am using C#. Also, these are the <strong>only</strong> real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so.</p>
| [
{
"answer_id": 110754,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "<p>A single regex won't do. Every text markup will have it's own html translator. Better look into how the existing converters... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] | How would you write a regular expression to convert mark down into HTML? For example, you would type in the following:
```
This would be *italicized* text and this would be **bold** text
```
This would then need to be converted to:
```
This would be <em>italicized</em> text and this would be <strong>bold</strong> text
```
Very similar to the mark down edit control used by stackoverflow.
**Clarification**
For what it is worth, I am using C#. Also, these are the **only** real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so. | The best way is to find a version of the Markdown library ported to whatever language you are using (you did not specify in your question).
---
Now that you have clarified that you only want STRONG and EM to be processed, and that you are using C#, I recommend you take a look at [Markdown.NET](http://www.aspnetresources.com/blog/markdown_announced.aspx) to see how those tags are implemented. As you can see, it is in fact two expressions. Here is the code:
```
private string DoItalicsAndBold (string text)
{
// <strong> must go first:
text = Regex.Replace (text, @"(\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1",
new MatchEvaluator (BoldEvaluator),
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
// Then <em>:
text = Regex.Replace (text, @"(\*|_) (?=\S) (.+?) (?<=\S) \1",
new MatchEvaluator (ItalicsEvaluator),
RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
return text;
}
private string ItalicsEvaluator (Match match)
{
return string.Format ("<em>{0}</em>", match.Groups[2].Value);
}
private string BoldEvaluator (Match match)
{
return string.Format ("<strong>{0}</strong>", match.Groups[2].Value);
}
``` |
110,763 | <p>I've built a wrapper over NumbericUpDown control.
The wrapper is generic and can support int? and double?</p>
<p>I would like to write a method that will do the following.</p>
<pre><code>public partial class NullableNumericUpDown<T> : UserControl where T : struct
{
private NumbericUpDown numericUpDown;
private T? Getvalue()
{
T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question
return value;
}}
</code></pre>
<p>of course there is no cast between decimal and double? or int? so I need to use a certain way of converting.
I would like to avoid switch or if expressions.</p>
<p>What would you do?</p>
<p>To clarify my question I've provided more code...</p>
| [
{
"answer_id": 110772,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>It's not clear how you gonna use it.\nIf you want double create GetDouble() method, for integers - GetInteger()</p>\n\n<p>EDI... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11659/"
] | I've built a wrapper over NumbericUpDown control.
The wrapper is generic and can support int? and double?
I would like to write a method that will do the following.
```
public partial class NullableNumericUpDown<T> : UserControl where T : struct
{
private NumbericUpDown numericUpDown;
private T? Getvalue()
{
T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question
return value;
}}
```
of course there is no cast between decimal and double? or int? so I need to use a certain way of converting.
I would like to avoid switch or if expressions.
What would you do?
To clarify my question I've provided more code... | It's not clear how you gonna use it.
If you want double create GetDouble() method, for integers - GetInteger()
EDIT:
Ok, now I think I understand your use case
Try this:
```
using System;
using System.ComponentModel;
static Nullable<T> ConvertFromString<T>(string value) where T:struct
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null && !string.IsNullOrEmpty(value))
{
try
{
return (T)converter.ConvertFrom(value);
}
catch (Exception e) // Unfortunately Converter throws general Exception
{
return null;
}
}
return null;
}
...
double? @double = ConvertFromString<double>("1.23");
Console.WriteLine(@double); // prints 1.23
int? @int = ConvertFromString<int>("100");
Console.WriteLine(@int); // prints 100
long? @long = ConvertFromString<int>("1.1");
Console.WriteLine(@long.HasValue); // prints False
``` |
110,801 | <p>I've tried cpan and cpanp shell and I keep getting:</p>
<pre><code>ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't
seem to be in your PATH. Is it correctly installed?
</code></pre>
<p>What is the pkg-config utility and how do I install it? </p>
<p>Updates: </p>
<ul>
<li>OS: Windows</li>
<li>This module is a prerequisite for the File::Extractor module</li>
</ul>
| [
{
"answer_id": 110840,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://pkgconfig.freedesktop.org/wiki/\" rel=\"nofollow noreferrer\">http://pkgconfig.freedesktop.org/wiki/</a>... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9411/"
] | I've tried cpan and cpanp shell and I keep getting:
```
ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't
seem to be in your PATH. Is it correctly installed?
```
What is the pkg-config utility and how do I install it?
Updates:
* OS: Windows
* This module is a prerequisite for the File::Extractor module | look here:
<http://gtk2-perl.sourceforge.net/win32/howto_build_gtk2perl_win32.html>
I found this page by googling for ExtUtils::PkgConfig and "PPM" (Actvestates Perl Package Manager). |
110,867 | <p>I have a public property set in my form of type <code>ListE<T></code> where:</p>
<pre><code>public class ListE<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
</code></pre>
<p>Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection.</p>
<blockquote>
<p>Arithmetic operation resulted in an overflow.</p>
</blockquote>
<p>Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas?</p>
<p>EDIT: Yes, I can use the property successfully, well even manually, ie. in the <code>OnLoad</code> handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :(</p>
| [
{
"answer_id": 111065,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 0,
"selected": false,
"text": "<p>One place to start would be that it may be doing math with your ListE`1::Count property. If that has some subtle flaw (i... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] | I have a public property set in my form of type `ListE<T>` where:
```
public class ListE<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
```
Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection.
>
> Arithmetic operation resulted in an overflow.
>
>
>
Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas?
EDIT: Yes, I can use the property successfully, well even manually, ie. in the `OnLoad` handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :( | I can't understand what's motivating you to attempt to reinvent the List<T> wheel in that way, but to answer your question: I would add a line "System.Diagnostics.Debugger.Break()" to the constructor of your class.
Then try to use it in the designer, and you'll get a popup asking you if you want to attach a debugger. Attach a second instance of Visual Studio as a debugger, and you'll be able to set some breakpoints in your code and start debugging. |
110,887 | <p>Is there a way to read a module's configuration ini file? </p>
<p>For example I installed php-eaccelerator (<a href="http://eaccelerator.net" rel="nofollow noreferrer">http://eaccelerator.net</a>) and it put a <code>eaccelerator.ini</code> file in <code>/etc/php.d</code>. My PHP installation wont read this <code>.ini</code> file because the <code>--with-config-file-scan-dir</code> option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?</p>
| [
{
"answer_id": 110899,
"author": "Alister Bulman",
"author_id": 6216,
"author_profile": "https://Stackoverflow.com/users/6216",
"pm_score": 1,
"selected": false,
"text": "<p>The standard way in this instance is to copy the relevant .ini lines to the bottom of the php.ini file. There is ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983/"
] | Is there a way to read a module's configuration ini file?
For example I installed php-eaccelerator (<http://eaccelerator.net>) and it put a `eaccelerator.ini` file in `/etc/php.d`. My PHP installation wont read this `.ini` file because the `--with-config-file-scan-dir` option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings? | This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a `<?php phpinfo(); ?>` and check where it's located.
For example, try this:
```
[eAccelerator]
extension="eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmp"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
```
Another thing you could do is set all the settings on run-time using ini\_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure. |
110,894 | <p>I've got C# code that accesses MySQL through ODBC.</p>
<p>It creates a transaction, does a few thousand insert commands, and then commits.
Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?</p>
| [
{
"answer_id": 110915,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 0,
"selected": false,
"text": "<p>It's hard to say without seeing your code, but I'm assuming you are executing the statements one at a time. So, you... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
] | I've got C# code that accesses MySQL through ODBC.
It creates a transaction, does a few thousand insert commands, and then commits.
Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way? | MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time:
```
INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015);
```
I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself. |
110,923 | <p>How do I end a Tkinter program? Let's say I have this code:</p>
<pre><code>from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
</code></pre>
<p>How should I define the <code>quit</code> function to exit my application?</p>
| [
{
"answer_id": 110929,
"author": "Matt Gregory",
"author_id": 10577,
"author_profile": "https://Stackoverflow.com/users/10577",
"pm_score": 6,
"selected": false,
"text": "<pre><code>def quit()\n root.quit()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>def quit()\n root.destroy()\n</co... | 2008/09/21 | [
"https://Stackoverflow.com/questions/110923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
] | How do I end a Tkinter program? Let's say I have this code:
```
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
```
How should I define the `quit` function to exit my application? | **You should use `destroy()` to close a Tkinter window.**
```py
from Tkinter import *
#use tkinter instead of Tkinter (small, not capital T) if it doesn't work
#as it was changed to tkinter in newer Python versions
root = Tk()
Button(root, text="Quit", command=root.destroy).pack() #button to close the window
root.mainloop()
```
---
**Explanation:**
```py
root.quit()
```
The above line just ***bypasses*** the `root.mainloop()`, i.e., `root.mainloop()` will still be running ***in the background*** if `quit()` command is executed.
```py
root.destroy()
```
While `destroy()` command vanishes out `root.mainloop()`, i.e., `root.mainloop()` stops. `<window>.destroy()` ***completely*** destroys and *closes* the window.
So, if you want to exit and close the program completely, you should use `root.destroy()`, as it stops the `mainloop()` and destroys the window and all its widgets.
But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the `root.mainloop()` line, you should use `root.quit()`. Example:
```py
from Tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
Button(root, text="Quit", command=quit).pack()
root.mainloop()
#do something
```
See [What is the difference between root.destroy() and root.quit()?](https://stackoverflow.com/questions/2307464/what-is-the-difference-between-root-destroy-and-root-quit). |
111,026 | <p>Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array?</p>
<p>We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program. </p>
<p>Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector.</p>
<p>Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question.</p>
| [
{
"answer_id": 111046,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 3,
"selected": false,
"text": "<p>For best array performance, make sure you're using a single dimension array with lower index of 0.</p>\n\n<p>T... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4044/"
] | Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array?
We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program.
Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector.
Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question. | For best array performance, make sure you're using a single dimension array with lower index of 0.
To access the elements of the array as fast as possible, you can use unsafe pointers like so:
```
int[] array = Enumerable.Range(0, 1000).ToArray();
int count = 0;
unsafe {
fixed (int* pArray = array) {
for (int i = 0; i < array.Length; i++) {
count += *(pArray + i);
}
}
}
```
**EDIT** Drat! Didn't notice you said 2D array. This trick won't work with a multi-dimensional array so I'm not sure how much help it will be. Although you could turn any array into a single-dimension array by doing some arithmetic on the array index. Just depends on if you care about the performance hit in indexing the array or in iterating over the array. |
111,097 | <p><strong>EDIT:</strong> This was formerly more explicitly titled: - "<strong>Best solution to stop Kontiki's KHOST.EXE from loading automatically at start-up on Windows XP?</strong>"</p>
<p>Essentially, whenever the <strong><a href="http://www.channel4.com/4od/index.html" rel="nofollow noreferrer">40D</a></strong> application is run it sets up <strong>khost.exe</strong> to automatically start-up with Windows. This is annoying as it increases my boot up time by a couple of minutes and I don't even use the P2P aspect of 4OD anyway.</p>
<p>The registry keys that are set are:</p>
<pre><code>Command: C:\Program Files\Kontiki\KHost.exe -all
Description: kdx
Location: HKU\S-1-5-21-1757981266-1960408961-839522115-1003\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Name: kdx
Setting ID:
User: LAPTOP\Me
Command: "C:\Program Files\Kontiki\KHost.exe" -all
Description: 4oD
Location: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Name: 4oD
Setting ID:
User: All Users
</code></pre>
<p>I'm assuming some kind of <strong>start-up</strong> or <strong>shut-down</strong> <strong>script</strong> to delete these registry keys would be the best solution, but I'm not that up with <strong>.vbs</strong> or <strong>.bat</strong> scripting or where I'd put them to automatically run at an appropriate time.</p>
<p>I know there is a <strong><a href="http://odmonitor.blogspot.com/" rel="nofollow noreferrer">TV On-Demand Monitor application</a></strong>, but I don't really need to be running yet another process, I just need to delete the registry keys as I describe above.</p>
| [
{
"answer_id": 111134,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just copy the executable to some other name, and put a do-nothing exe in its place. Then change your shortcut... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17759/"
] | **EDIT:** This was formerly more explicitly titled: - "**Best solution to stop Kontiki's KHOST.EXE from loading automatically at start-up on Windows XP?**"
Essentially, whenever the **[40D](http://www.channel4.com/4od/index.html)** application is run it sets up **khost.exe** to automatically start-up with Windows. This is annoying as it increases my boot up time by a couple of minutes and I don't even use the P2P aspect of 4OD anyway.
The registry keys that are set are:
```
Command: C:\Program Files\Kontiki\KHost.exe -all
Description: kdx
Location: HKU\S-1-5-21-1757981266-1960408961-839522115-1003\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Name: kdx
Setting ID:
User: LAPTOP\Me
Command: "C:\Program Files\Kontiki\KHost.exe" -all
Description: 4oD
Location: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Name: 4oD
Setting ID:
User: All Users
```
I'm assuming some kind of **start-up** or **shut-down** **script** to delete these registry keys would be the best solution, but I'm not that up with **.vbs** or **.bat** scripting or where I'd put them to automatically run at an appropriate time.
I know there is a **[TV On-Demand Monitor application](http://odmonitor.blogspot.com/)**, but I don't really need to be running yet another process, I just need to delete the registry keys as I describe above. | for the vb script you would use something like this:
```
Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")
'repeat the line below for each key to delete
WSHShell.RegDelete "[Location of Key]"
```
Just drop the code into a text file and re-name it something like shutdown,vbs.
As for when to run it, if you are in a corporate environment you could use a group policy and set it as a machine shutdown script. Alternatively, see this page [here](http://www.msfn.org/board/lofiversion/index.php/t40945.html) about adding it manually |
111,102 | <p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p>
<p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
| [
{
"answer_id": 111111,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 14,
"selected": true,
"text": "<p>A closure is a pairing of:</p>\n<ol>\n<li>A function and</li>\n<li>A reference to that function's outer scope (lexical... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] | How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?
I have seen [the Scheme example](http://en.wikipedia.org/wiki/Scheme_%28programming_language%29) given on Wikipedia, but unfortunately it did not help. | A closure is a pairing of:
1. A function and
2. A reference to that function's outer scope (lexical environment)
A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.
Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.
If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.
In the following code, `inner` forms a closure with the lexical environment of the execution context created when `foo` is invoked, *closing over* variable `secret`:
```js
function foo() {
const secret = Math.trunc(Math.random() * 100)
return function inner() {
console.log(`The secret number is ${secret}.`)
}
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`
```
In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.
And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.
If JavaScript did not have closures, then more states would have to be passed between functions *explicitly*, making parameter lists longer and code noisier.
So, if you want a function to always have access to a private piece of state, you can use a closure.
...and frequently we *do* want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.
In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, `secret` remains available to the function object `inner`, *after* it has been returned from `foo`.
Uses of Closures
----------------
Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.
### Private Instance Variables
In the following code, the function `toString` closes over the details of the car.
```js
function Car(manufacturer, model, year, color) {
return {
toString() {
return `${manufacturer} ${model} (${year}, ${color})`
}
}
}
const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')
console.log(car.toString())
```
### Functional Programming
In the following code, the function `inner` closes over both `fn` and `args`.
```js
function curry(fn) {
const args = []
return function inner(arg) {
if(args.length === fn.length) return fn(...args)
args.push(arg)
return inner
}
}
function add(a, b) {
return a + b
}
const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)()) // 5
```
### Event-Oriented Programming
In the following code, function `onClick` closes over variable `BACKGROUND_COLOR`.
```js
const $ = document.querySelector.bind(document)
const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'
function onClick() {
$('body').style.background = BACKGROUND_COLOR
}
$('button').addEventListener('click', onClick)
```
```html
<button>Set background color</button>
```
### Modularization
In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions `tick` and `toString` close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code.
```js
let namespace = {};
(function foo(n) {
let numbers = []
function format(n) {
return Math.trunc(n)
}
function tick() {
numbers.push(Math.random() * 100)
}
function toString() {
return numbers.map(format)
}
n.counter = {
tick,
toString
}
}(namespace))
const counter = namespace.counter
counter.tick()
counter.tick()
console.log(counter.toString())
```
Examples
--------
### Example 1
This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables *themselves*. It is as though the stack-frame stays alive in memory even after the outer function exits.
```js
function foo() {
let x = 42
let inner = () => console.log(x)
x = x + 1
return inner
}
foo()() // logs 43
```
### Example 2
In the following code, three methods `log`, `increment`, and `update` all close over the same lexical environment.
And every time `createObject` is called, a new execution context (stack frame) is created and a completely new variable `x`, and a new set of functions (`log` etc.) are created, that close over this new variable.
```js
function createObject() {
let x = 42;
return {
log() { console.log(x) },
increment() { x++ },
update(value) { x = value }
}
}
const o = createObject()
o.increment()
o.log() // 43
o.update(5)
o.log() // 5
const p = createObject()
p.log() // 42
```
### Example 3
If you are using variables declared using `var`, be careful you understand which variable you are closing over. Variables declared using `var` are hoisted. This is much less of a problem in modern JavaScript due to the introduction of `let` and `const`.
In the following code, each time around the loop, a new function `inner` is created, which closes over `i`. But because `var i` is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of `i` (3) is printed, three times.
```js
function foo() {
var result = []
for (var i = 0; i < 3; i++) {
result.push(function inner() { console.log(i) } )
}
return result
}
const result = foo()
// The following will print `3`, three times...
for (var i = 0; i < 3; i++) {
result[i]()
}
```
Final points:
-------------
* Whenever a function is declared in JavaScript closure is created.
* Returning a `function` from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
* Whenever you use `eval()` inside a function, a closure is used. The text you `eval` can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using `eval('var foo = …')`.
* When you use `new Function(…)` (the [Function constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
* A closure in JavaScript is like keeping a reference (**NOT** a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
* A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
* A new set of local variables is created every time a function is called.
Links
-----
* Douglas Crockford's simulated [private attributes and private methods](http://www.crockford.com/javascript/private.html) for an object, using closures.
* A great explanation of how closures can [cause memory leaks in IE](https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited) if you are not careful.
* MDN documentation on [JavaScript Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). |
111,129 | <p>I have a table which is referenced by foreign keys on many other tables. In my program if I want to delete one of these rows I need to first search for dependencies and present them to the user - "This object depends on x from table y, z from table q, etc". I also expect the number of tables which have foreign keys to this table to grow considerably over time. </p>
<p>Is the information_schema database a good way to do a search for all dependencies? I tried to query it to retrieve a list of all tables which have foreign keys to my table, then iterate over the result and select all entries from each table where the foreign key value matches the value the user is trying to delete. The query I have is as follows:</p>
<pre><code>SELECT * FROM `KEY_COLUMN_USAGE` kcu
LEFT JOIN TABLE_CONSTRAINTS tc
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE tc.CONSTRAINT_TYPE='FOREIGN KEY'
AND (kcu.REFERENCED_TABLE_SCHEMA='db')
AND (kcu.REFERENCED_TABLE_NAME = 'testtable')
</code></pre>
<p>which works perfectly for determining the tables which I need to search, however it is <em>very</em> slow. The query takes around 1 to 2 seconds at best to execute on my development machine, which will reduce a lot when I run it on my production server, but will still be quite slow.</p>
<p>I need to know if it's a bad idea to use information_schema in this way. If not, how I can extract better performance from the query. Is the query I'm using solid or is there a better way to do it? If so, how best should I tackle this problem from a maintainability perspective.</p>
| [
{
"answer_id": 111146,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is exactly the sort of thing that INFORMATION_SCHEMA is intended for.</p>\n"
},
{
"answer_id": 1111... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15004/"
] | I have a table which is referenced by foreign keys on many other tables. In my program if I want to delete one of these rows I need to first search for dependencies and present them to the user - "This object depends on x from table y, z from table q, etc". I also expect the number of tables which have foreign keys to this table to grow considerably over time.
Is the information\_schema database a good way to do a search for all dependencies? I tried to query it to retrieve a list of all tables which have foreign keys to my table, then iterate over the result and select all entries from each table where the foreign key value matches the value the user is trying to delete. The query I have is as follows:
```
SELECT * FROM `KEY_COLUMN_USAGE` kcu
LEFT JOIN TABLE_CONSTRAINTS tc
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE tc.CONSTRAINT_TYPE='FOREIGN KEY'
AND (kcu.REFERENCED_TABLE_SCHEMA='db')
AND (kcu.REFERENCED_TABLE_NAME = 'testtable')
```
which works perfectly for determining the tables which I need to search, however it is *very* slow. The query takes around 1 to 2 seconds at best to execute on my development machine, which will reduce a lot when I run it on my production server, but will still be quite slow.
I need to know if it's a bad idea to use information\_schema in this way. If not, how I can extract better performance from the query. Is the query I'm using solid or is there a better way to do it? If so, how best should I tackle this problem from a maintainability perspective. | Dvorak is right, INFORMATION\_SCHEMA is intended for that.
Concerning your performance concerns, there are several ways you can improve the performance
* Easy way, but not much improvement will come from it:
Store the info in a static variable. At least the query will occur only once per page
* Use persistent caching : The alternative PHP cache can help you (see <http://fr3.php.net/manual/en/book.apc.php>).
The info you'll get from the information schema is a good candidate to store in a persistent cache.
* Use a ORM library, such as doctrine (<http://www.doctrine-project.org/>)
A look at the file lib/Doctrine/Import/Mysql.php will show that it does exactly what you need, and much more. |
111,135 | <p>I write my app in VS 2008 and so use all the fanciful stuffs such as LINQ, object initializers etc. Now can my app run on machines that have only .Net 2.0 runtime, but no .Net 3.5 runtime? .Net 3.5 runtime is a huge download, as all of you might know.</p>
| [
{
"answer_id": 111143,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": -1,
"selected": false,
"text": "<p>No, they can not.</p>\n"
},
{
"answer_id": 111145,
"author": "aku",
"author_id": 1196,
"author_profi... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I write my app in VS 2008 and so use all the fanciful stuffs such as LINQ, object initializers etc. Now can my app run on machines that have only .Net 2.0 runtime, but no .Net 3.5 runtime? .Net 3.5 runtime is a huge download, as all of you might know. | What you can use is for example the *var* keyword, auto-getters and auto-setters, object initializers. I.e. syntactic sugar that is compiled to 2.0 code.
What you can't use is functionality that resides in .Net framework 3.0 and 3.5 library. For example LINQ.
You can try for yourself what you can and can't use by setting target platform in Visual Studio to .Net Framework 2.0. The compiler will complain when you use things from Framework 3.0 and 3.5.
You can use Extension Methods with a little trick: Creating this class to your project
```
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}
```
Extension Methods are actually also compiled to 2.0 code, but the compiler needs this class to be defined. Read about it [here](http://www.danielmoth.com/Blog/2007/05/using-extension-methods-in-fx-20.html) |
111,155 | <p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
| [
{
"answer_id": 111160,
"author": "Matt Gregory",
"author_id": 10577,
"author_profile": "https://Stackoverflow.com/users/10577",
"pm_score": 8,
"selected": false,
"text": "<p>Tkinter supports a mechanism called <a href=\"http://web.archive.org/web/20201111215134/http://effbot.org/tkinterb... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
] | How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program? | Tkinter supports a mechanism called [*protocol handlers*](http://web.archive.org/web/20201111215134/http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm#protocols). Here, the term *protocol* refers to the interaction between the application and the window manager. The most commonly used protocol is called `WM_DELETE_WINDOW`, and is used to define what happens when the user explicitly closes a window using the window manager.
You can use the `protocol` method to *install a handler* for this protocol (the widget must be a `Tk` or `Toplevel` widget):
Here you have a concrete example:
```
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
``` |
111,194 | <p>I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.</p>
<p>The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.</p>
<p>The client (a C# web app), reads the data:</p>
<pre><code> private NetworkStream stream_;
public void WriteDocument(HttpResponse response)
{
while (stream_.DataAvailable)
{
const int bufsize = 4 * 1024;
byte[] buffer = new byte[bufsize];
int nbytes = stream_.Read(buffer, 0, bufsize);
if (nbytes > 0)
{
if (nbytes < bufsize)
Array.Resize<byte>(ref buffer, nbytes);
response.BinaryWrite(buffer);
}
}
response.End();
}
</code></pre>
<p>This seems to always exit the read loop before all the data has arrived. What am I doing wrong?</p>
| [
{
"answer_id": 111212,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I do. Usually the content length is desired to know when to end the data storing loop. If your protoc... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] | I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.
The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.
The client (a C# web app), reads the data:
```
private NetworkStream stream_;
public void WriteDocument(HttpResponse response)
{
while (stream_.DataAvailable)
{
const int bufsize = 4 * 1024;
byte[] buffer = new byte[bufsize];
int nbytes = stream_.Read(buffer, 0, bufsize);
if (nbytes > 0)
{
if (nbytes < bufsize)
Array.Resize<byte>(ref buffer, nbytes);
response.BinaryWrite(buffer);
}
}
response.End();
}
```
This seems to always exit the read loop before all the data has arrived. What am I doing wrong? | I would use the `OutputStream` directly with a general-purpose function. With the `Stream`, you can control `Flush`.
```
public void WriteDocument(HttpResponse response) {
StreamCopy(response.OutputStream, stream_);
response.End();
}
public static void StreamCopy(Stream dest, Stream src) {
byte[] buffer = new byte[4 * 1024];
int n = 1;
while (n > 0) {
n = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, n);
}
dest.Flush();
}
``` |
111,234 | <p>Now that it's clear <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p>
<p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p>
<p>Could you give me some explanations, including examples with the magic method ?</p>
| [
{
"answer_id": 111251,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 4,
"selected": false,
"text": "<p>A Callable is an object that has the <code>__call__</code> method. This means you can fake callable ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] | Now that it's clear [what a metaclass is](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python), there is an associated concept that I use all the time without knowing what it really means.
I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using `__init__` and `__new__` lead to wonder what this bloody `__call__` can be used for.
Could you give me some explanations, including examples with the magic method ? | A callable is anything that can be called.
The [built-in *callable* (PyCallable\_Check in objects.c)](http://svn.python.org/projects/python/trunk/Objects/object.c) checks if the argument is either:
* an instance of a class with a `__call__` method or
* is of a type that has a non null *tp\_call* (c struct) member which indicates callability otherwise (such as in functions, methods etc.)
The method named `__call__` is ([according to the documentation](https://docs.python.org/3/reference/datamodel.html#object.__call__))
>
> Called when the instance is ''called'' as a function
>
>
>
Example
-------
```
class Foo:
def __call__(self):
print 'called'
foo_instance = Foo()
foo_instance() #this is calling the __call__ method
``` |
111,281 | <ul>
<li>VMware server 1.0.7 installed with vmware-package</li>
<li>Debian GNU/Linux testing (lenny)</li>
<li>Kernel 2.6.26-1-686</li>
</ul>
<p>There were several compile problems when trying to build the binary kernel modules from the vmware-server-kernel-source package made by vmware-package from the VMware server tarball. Recently VMware has updated their kernel module sources so as to make them compatible with kernel 2.6.25, but they broke again with 2.6.26.</p>
<pre><code>vmmon-only/linux/driver.c:146: error: unknown field 'nopage' specified in initializer
vmmon-only/linux/driver.c:147: warning: initialization from incompatible pointer type
vmmon-only/linux/driver.c:150: error: unknown field 'nopage' specified in initializer
vmmon-only/linux/driver.c:151: warning: initialization from incompatible pointer type
</code></pre>
<p>That's only the first error, but there are other compile problems (in vmnet-only).</p>
<p>Many advice on forums are to use vmware-any-any instead, but that has its own problems (see <a href="https://stackoverflow.com/questions/109877/unknown-ioctl-2062-2065-2066-from-vmmon-when-starting-a-vm-vmware-server-107-fo">my other question</a>).</p>
<p>As you can see from my own answer below, I've solved the problem by fixing the incompatiblities, and came up with a <a href="http://pastebin.com/f200c4eb0" rel="nofollow noreferrer">patch</a>. Now I'd like VMware to include it in future releases, to save me and others trouble of applying it by hand after every VMware or kernel upgrade. Question: where/how do I submit such fixes to VMware?</p>
| [
{
"answer_id": 111309,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try searching the <a href=\"http://www.vmware.com/support/\" rel=\"nofollow noreferrer\">VMware support website</a>?... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10682/"
] | * VMware server 1.0.7 installed with vmware-package
* Debian GNU/Linux testing (lenny)
* Kernel 2.6.26-1-686
There were several compile problems when trying to build the binary kernel modules from the vmware-server-kernel-source package made by vmware-package from the VMware server tarball. Recently VMware has updated their kernel module sources so as to make them compatible with kernel 2.6.25, but they broke again with 2.6.26.
```
vmmon-only/linux/driver.c:146: error: unknown field 'nopage' specified in initializer
vmmon-only/linux/driver.c:147: warning: initialization from incompatible pointer type
vmmon-only/linux/driver.c:150: error: unknown field 'nopage' specified in initializer
vmmon-only/linux/driver.c:151: warning: initialization from incompatible pointer type
```
That's only the first error, but there are other compile problems (in vmnet-only).
Many advice on forums are to use vmware-any-any instead, but that has its own problems (see [my other question](https://stackoverflow.com/questions/109877/unknown-ioctl-2062-2065-2066-from-vmmon-when-starting-a-vm-vmware-server-107-fo)).
As you can see from my own answer below, I've solved the problem by fixing the incompatiblities, and came up with a [patch](http://pastebin.com/f200c4eb0). Now I'd like VMware to include it in future releases, to save me and others trouble of applying it by hand after every VMware or kernel upgrade. Question: where/how do I submit such fixes to VMware? | I wrote a support request to VMware, and they assured me that my patch will reach the VMware server team. |
111,282 | <p>I'm modifying some code in which the original author built a web page by using an array thusly:</p>
<pre><code> $output[]=$stuff_from_database;
$output[]='more stuff';
// etc
echo join('',$output);
</code></pre>
<p>Can anyone think of a reason why this would be preferable (or vice versa) to:</p>
<pre><code> $output =$stuff_from_database;
$output .='more stuff';
// etc
echo $output;
</code></pre>
| [
{
"answer_id": 111289,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 0,
"selected": false,
"text": "<p>The bottom will reallocate the $output string repeatedly, whereas I believe the top will just store each piece in an arr... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm modifying some code in which the original author built a web page by using an array thusly:
```
$output[]=$stuff_from_database;
$output[]='more stuff';
// etc
echo join('',$output);
```
Can anyone think of a reason why this would be preferable (or vice versa) to:
```
$output =$stuff_from_database;
$output .='more stuff';
// etc
echo $output;
``` | It was probably written by someone who comes from a language where strings are immutable and thus concatenation is expensive. PHP is not one of them as the following tests show. So the second approach is performance wise, better. The only other reason that I can think of to use the first approach is to be able to replace some part of the array with another, but that means to keep track of the indexes, which is not specified.
```
~$ cat join.php
<?php
for ($i=0;$i<50000;$i++) {
$output[] = "HI $i\n";
}
echo join('',$output);
?>
~$ time for i in `seq 100`; do php join.php >> outjoin ; done
real 0m19.145s
user 0m12.045s
sys 0m3.216s
~$ cat dot.php
<?php
for ($i=0;$i<50000;$i++) {
$output.= "HI $i\n";
}
echo $output;
?>
~$ time for i in `seq 100`; do php dot.php >> outdot ; done
real 0m15.530s
user 0m8.985s
sys 0m2.260s
``` |
111,287 | <p>Is it possible to put the results from more than one query on more than one table into a TClientDataset?</p>
<p>Just something like</p>
<pre><code>SELECT * from t1;
SELECT * from t2;
SELECT * from t3;
</code></pre>
<p>I can't seem to figure out a way to get a data provider (SetProvider) to pull in results from more than one table at a time.</p>
| [
{
"answer_id": 111305,
"author": "Chris Woodruff",
"author_id": 7001,
"author_profile": "https://Stackoverflow.com/users/7001",
"pm_score": 1,
"selected": true,
"text": "<p>There is not a way to have multiple table data in the same TClientDataSet like you referenced. The TClientDataSet h... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19658/"
] | Is it possible to put the results from more than one query on more than one table into a TClientDataset?
Just something like
```
SELECT * from t1;
SELECT * from t2;
SELECT * from t3;
```
I can't seem to figure out a way to get a data provider (SetProvider) to pull in results from more than one table at a time. | There is not a way to have multiple table data in the same TClientDataSet like you referenced. The TClientDataSet holds a single cursor for a single dataset. |
111,341 | <p>I've got two tables:</p>
<pre><code>TableA
------
ID,
Name
TableB
------
ID,
SomeColumn,
TableA_ID (FK for TableA)
</code></pre>
<p>The relationship is one row of <code>TableA</code> - many of <code>TableB</code>.</p>
<p>Now, I want to see a result like this:</p>
<pre><code>ID Name SomeColumn
1. ABC X, Y, Z (these are three different rows)
2. MNO R, S
</code></pre>
<p>This won't work (multiple results in a subquery):</p>
<pre><code>SELECT ID,
Name,
(SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID)
FROM TableA
</code></pre>
<p>This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of <code>TableA</code>. </p>
<p>Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of <code>TableA</code>. </p>
<p>I'm not sure if a UDF, utilizing COALESCE or something similar might work?</p>
| [
{
"answer_id": 111347,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 4,
"selected": false,
"text": "<p>I think you are on the right track with COALESCE. See here for an example of building a comma-delimited string:</p... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6939/"
] | I've got two tables:
```
TableA
------
ID,
Name
TableB
------
ID,
SomeColumn,
TableA_ID (FK for TableA)
```
The relationship is one row of `TableA` - many of `TableB`.
Now, I want to see a result like this:
```
ID Name SomeColumn
1. ABC X, Y, Z (these are three different rows)
2. MNO R, S
```
This won't work (multiple results in a subquery):
```
SELECT ID,
Name,
(SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID)
FROM TableA
```
This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of `TableA`.
Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of `TableA`.
I'm not sure if a UDF, utilizing COALESCE or something similar might work? | ### 1. Create the UDF:
```
CREATE FUNCTION CombineValues
(
@FK_ID INT -- The foreign key from TableA which is used
-- to fetch corresponding records
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @SomeColumnList VARCHAR(8000);
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB C
WHERE C.FK_ID = @FK_ID;
RETURN
(
SELECT @SomeColumnList
)
END
```
### 2. Use in subquery:
```
SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA
```
### 3. If you are using stored procedure you can do like this:
```
CREATE PROCEDURE GetCombinedValues
@FK_ID int
As
BEGIN
DECLARE @SomeColumnList VARCHAR(800)
SELECT @SomeColumnList =
COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20))
FROM TableB
WHERE FK_ID = @FK_ID
Select *, @SomeColumnList as SelectedIds
FROM
TableA
WHERE
FK_ID = @FK_ID
END
``` |
111,345 | <p>Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):</p>
<pre><code>using System;
using System.Drawing;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Image img = new Bitmap("test.png");
System.Console.WriteLine(img.Width + " x " + img.Height);
}
}
}
</code></pre>
| [
{
"answer_id": 111349,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 4,
"selected": false,
"text": "<p>Have you tried using the WPF Imaging classes? <code>System.Windows.Media.Imaging.BitmapDecoder</code>, etc.?</p>\n\n<... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716/"
] | Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):
```
using System;
using System.Drawing;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Image img = new Bitmap("test.png");
System.Console.WriteLine(img.Width + " x " + img.Height);
}
}
}
``` | Your best bet as always is to find a well tested library. However, you said that is difficult, so here is some dodgy largely untested code that should work for a fair number of cases:
```
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
namespace ImageDimensions
{
public static class ImageHelper
{
const string errorMessage = "Could not recognize image format.";
private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()
{
{ new byte[]{ 0x42, 0x4D }, DecodeBitmap},
{ new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },
{ new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },
{ new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },
{ new byte[]{ 0xff, 0xd8 }, DecodeJfif },
};
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="path">The path of the image to get the dimensions of.</param>
/// <returns>The dimensions of the specified image.</returns>
/// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
public static Size GetDimensions(string path)
{
using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)))
{
try
{
return GetDimensions(binaryReader);
}
catch (ArgumentException e)
{
if (e.Message.StartsWith(errorMessage))
{
throw new ArgumentException(errorMessage, "path", e);
}
else
{
throw e;
}
}
}
}
/// <summary>
/// Gets the dimensions of an image.
/// </summary>
/// <param name="path">The path of the image to get the dimensions of.</param>
/// <returns>The dimensions of the specified image.</returns>
/// <exception cref="ArgumentException">The image was of an unrecognized format.</exception>
public static Size GetDimensions(BinaryReader binaryReader)
{
int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;
byte[] magicBytes = new byte[maxMagicBytesLength];
for (int i = 0; i < maxMagicBytesLength; i += 1)
{
magicBytes[i] = binaryReader.ReadByte();
foreach(var kvPair in imageFormatDecoders)
{
if (magicBytes.StartsWith(kvPair.Key))
{
return kvPair.Value(binaryReader);
}
}
}
throw new ArgumentException(errorMessage, "binaryReader");
}
private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes)
{
for(int i = 0; i < thatBytes.Length; i+= 1)
{
if (thisBytes[i] != thatBytes[i])
{
return false;
}
}
return true;
}
private static short ReadLittleEndianInt16(this BinaryReader binaryReader)
{
byte[] bytes = new byte[sizeof(short)];
for (int i = 0; i < sizeof(short); i += 1)
{
bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt16(bytes, 0);
}
private static int ReadLittleEndianInt32(this BinaryReader binaryReader)
{
byte[] bytes = new byte[sizeof(int)];
for (int i = 0; i < sizeof(int); i += 1)
{
bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();
}
return BitConverter.ToInt32(bytes, 0);
}
private static Size DecodeBitmap(BinaryReader binaryReader)
{
binaryReader.ReadBytes(16);
int width = binaryReader.ReadInt32();
int height = binaryReader.ReadInt32();
return new Size(width, height);
}
private static Size DecodeGif(BinaryReader binaryReader)
{
int width = binaryReader.ReadInt16();
int height = binaryReader.ReadInt16();
return new Size(width, height);
}
private static Size DecodePng(BinaryReader binaryReader)
{
binaryReader.ReadBytes(8);
int width = binaryReader.ReadLittleEndianInt32();
int height = binaryReader.ReadLittleEndianInt32();
return new Size(width, height);
}
private static Size DecodeJfif(BinaryReader binaryReader)
{
while (binaryReader.ReadByte() == 0xff)
{
byte marker = binaryReader.ReadByte();
short chunkLength = binaryReader.ReadLittleEndianInt16();
if (marker == 0xc0)
{
binaryReader.ReadByte();
int height = binaryReader.ReadLittleEndianInt16();
int width = binaryReader.ReadLittleEndianInt16();
return new Size(width, height);
}
binaryReader.ReadBytes(chunkLength - 2);
}
throw new ArgumentException(errorMessage);
}
}
}
```
Hopefully the code is fairly obvious. To add a new file format you add it to `imageFormatDecoders` with the key being an array of the "magic bits" which appear at the beginning of every file of the given format and the value being a function which extracts the size from the stream. Most formats are simple enough, the only real stinker is jpeg. |
111,405 | <p>I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.</p>
<p>Thanks in advance,
Yet another LaTeX user</p>
| [
{
"answer_id": 111506,
"author": "finrod",
"author_id": 8295,
"author_profile": "https://Stackoverflow.com/users/8295",
"pm_score": 2,
"selected": true,
"text": "<p>If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG for... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11464/"
] | I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.
Thanks in advance,
Yet another LaTeX user | If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code:
```
%in the document preamble
\usepackage{graphicx}
%in the document, in the place where you want to put your image
\includegraphics{image_filename_without_extension}
```
When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS).
Of course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS.
Hope that helps. |
111,407 | <p>I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.</p>
<p>Does anyone know of a fix for this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 111409,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(document).ready(function() {\n // Fix background image caching problem\n if (jQuery.browser.msie) {\n ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
] | I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.
Does anyone know of a fix for this?
Thanks! | Apologies for the extra comment (I can't upvote or comment on Pavel's answer), but adding a DOCTYPE fixed this issue for me, and the slideUp/Down/Toggle effects now work correctly in IE7.
See [A List Apart](http://www.alistapart.com/articles/doctype/) for more information on DOCTYPES, or you can try specifying the fairly lenient 4/Transitional:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
``` |
111,426 | <p>I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. </p>
<p>I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks.</p>
| [
{
"answer_id": 111444,
"author": "David Ameller",
"author_id": 19689,
"author_profile": "https://Stackoverflow.com/users/19689",
"pm_score": 0,
"selected": false,
"text": "<p>A good example could be when your boss tells you to do some program and you can demonstrate by using the computat... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
] | I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer.
I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks. | O(1): Plain code without loops. Just flows through. Lookups in a lookup table are O(1), too.
O(log(n)): efficiently optimized algorithms. Example: binary tree algorithms and binary search. Usually doesn't hurt. You're lucky if you have such an algorithm at hand.
O(n): a single loop over data. Hurts for very large n.
O(n\*log(n)): an algorithm that does some sort of divide and conquer strategy. Hurts for large n. Typical example: merge sort
O(n\*n): a nested loop of some sort. Hurts even with small n. Common with naive matrix calculations. You want to avoid this sort of algorithm if you can.
O(n^x for x>2): a wicked construction with multiple nested loops. Hurts for very small n.
O(x^n, n! and worse): freaky (and often recursive) algorithms you don't want to have in production code except in very controlled cases, for very small n and if there really is no better alternative. Computation time may explode with n=n+1.
Moving your algorithm down from a higher complexity class can make your algorithm fly. Think of Fourier transformation which has an O(n\*n) algorithm that was unusable with 1960s hardware except in rare cases. Then Cooley and Tukey made some clever complexity reductions by re-using already calculated values. That led to the widespread introduction of FFT into signal processing. And in the end it's also why Steve Jobs made a fortune with the iPod.
Simple example: Naive C programmers write this sort of loop:
```
for (int cnt=0; cnt < strlen(s) ; cnt++) {
/* some code */
}
```
That's an O(n\*n) algorithm because of the implementation of strlen(). Nesting loops leads to multiplication of complexities inside the big-O. O(n) inside O(n) gives O(n\*n). O(n^3) inside O(n) gives O(n^4). In the example, precalculating the string length will immediately turn the loop into O(n). [Joel has also written about this.](http://www.joelonsoftware.com/articles/fog0000000319.html)
Yet the complexity class is not everything. You have to keep an eye on the size of n. Reworking an O(n\*log(n)) algorithm to O(n) won't help if the number of (now linear) instructions grows massively due to the reworking. And if n is small anyway, optimizing won't give much bang, too. |
111,436 | <p>I want to have my PHP application labeled with the revision number which it uses, but I don't want to use <a href="http://en.wikipedia.org/wiki/CruiseControl" rel="nofollow noreferrer">CruiseControl</a> or update a file and upload it every time. How should I do it?</p>
| [
{
"answer_id": 111459,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": false,
"text": "<p>Assuming your webroot is a checked-out copy of the subversion tree, you could parse the /.svn/entries file and hook out the... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
] | I want to have my PHP application labeled with the revision number which it uses, but I don't want to use [CruiseControl](http://en.wikipedia.org/wiki/CruiseControl) or update a file and upload it every time. How should I do it? | SVN keywords is not a good solution. As others pointed out adding $Revision$ in a file only affects **the specific file**, which may not change for a long time.
Remembering to "edit" a file (by adding or removing a blank line) before every commit is pointless. You could as well just type the revision by hand.
One good way to do it (that I know of) is to have an automated deployment process (which is always a good thing) and using the command svnversion. Here is what I do:
Wherever I need the revision I do an include: `<?php include 'version.php'; ?>`. This "version.php" file only has the revision number. Moreover it is not part of the repository (it set to be ignored). Here is how I create it:
1) On projects where SVN is installed on the server, I also use it for deployment. Getting the latest version to the server I have a script that among other things does the following (it runs on the server):
```
cd /var/www/project
svn update
rm version.php
svnversion > version.php
```
2) On projects where SVN is not installed my deployment script is more complex: it creates the version.php file locally, zips the code, uploads and extracts it |
111,460 | <p>I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this?</p>
| [
{
"answer_id": 111468,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>Why not just use an array of bytes instead? It would have none of the encoding problems you're likely to suffer wi... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20007/"
] | I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this? | Latin-1 aka ISO-8859-1 aka codepage 28591 is a useful codepage for this scenario, as it maps values in the range 128-255 unchanged. The following are interchangeable:
```
Encoding.GetEncoding(28591)
Encoding.GetEncoding("Latin1")
Encoding.GetEncoding("iso-8859-1")
```
The following code illustrates the fact that for Latin1, unlike Encoding.Default, all characters in the range 0-255 are mapped unchanged:
```
static void Main(string[] args)
{
Console.WriteLine("Test Default Encoding returned {0}", TestEncoding(Encoding.Default));
Console.WriteLine("Test Latin1 Encoding returned {0}", TestEncoding(Encoding.GetEncoding("Latin1")));
Console.ReadLine();
return;
}
private static bool CompareBytes(char[] chars, byte[] bytes)
{
bool result = true;
if (chars.Length != bytes.Length)
{
Console.WriteLine("Length mismatch {0} bytes and {1} chars" + bytes.Length, chars.Length);
return false;
}
for (int i = 0; i < chars.Length; i++)
{
int charValue = (int)chars[i];
if (charValue != (int)bytes[i])
{
Console.WriteLine("Byte at index {0} value {1:X4} does not match char {2:X4}", i, (int) bytes[i], charValue);
result = false;
}
}
return result;
}
private static bool TestEncoding(Encoding encoding)
{
byte[] inputBytes = new byte[256];
for (int i = 0; i < 256; i++)
{
inputBytes[i] = (byte) i;
}
char[] outputChars = encoding.GetChars(inputBytes);
Console.WriteLine("Comparing input bytes and output chars");
if (!CompareBytes(outputChars, inputBytes)) return false;
byte[] outputBytes = encoding.GetBytes(outputChars);
Console.WriteLine("Comparing output bytes and output chars");
if (!CompareBytes(outputChars, outputBytes)) return false;
return true;
}
``` |
111,461 | <p>I see a lot of example code for C# classes that does this:</p>
<pre><code>public class Point {
public int x { get; set; }
public int y { get; set; }
}
</code></pre>
<p>Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:</p>
<pre><code>public class Point {
private int _x;
private int _y;
public int x {
get { return _x; }
set { _x = value; }
}
public int y {
get { return _y; }
set { _y = value; }
}
}
</code></pre>
<p>My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?</p>
<pre><code>public class Point {
public int x;
public int y;
}
</code></pre>
<p>To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.</p>
| [
{
"answer_id": 111474,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 3,
"selected": false,
"text": "<p>It encapsulates setting and accessing of those members. If some time from now a developer for the code needs to chang... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19688/"
] | I see a lot of example code for C# classes that does this:
```
public class Point {
public int x { get; set; }
public int y { get; set; }
}
```
Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:
```
public class Point {
private int _x;
private int _y;
public int x {
get { return _x; }
set { _x = value; }
}
public int y {
get { return _y; }
set { _y = value; }
}
}
```
My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?
```
public class Point {
public int x;
public int y;
}
```
To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose. | I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.
[Jeff Atwood](https://blog.codinghorror.com/properties-vs-public-variables/) dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a [breaking change](http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx) in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems. |
111,478 | <p>Why is it wrong to use <code>std::auto_ptr<></code> with standard containers?</p>
| [
{
"answer_id": 111492,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 6,
"selected": false,
"text": "<p>The <strong>copy semantics</strong> of <code>auto_ptr</code> are not compatible with the containers.</p>\n\n<p>Specif... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19129/"
] | Why is it wrong to use `std::auto_ptr<>` with standard containers? | The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. `std::auto_ptr` does not fulfill this requirement.
Take for example this code:
```
class X
{
};
std::vector<std::auto_ptr<X> > vecX;
vecX.push_back(new X);
std::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL.
```
To overcome this limitation, you should use the [`std::unique_ptr`](http://msdn.microsoft.com/en-us/library/ee410601.aspx), [`std::shared_ptr`](http://msdn.microsoft.com/en-us/library/bb982026.aspx) or [`std::weak_ptr`](http://msdn.microsoft.com/en-us/library/bb982126.aspx) smart pointers or the boost equivalents if you don't have C++11. [Here is the boost library documentation for these smart pointers.](http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/smart_ptr.htm) |
111,504 | <p>I'm trying to create a UDF in <code>SQL Server 2005 Express</code> as below:</p>
<pre><code>CREATE FUNCTION [CombineValues] ()
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @CuisineList VARCHAR(8000);
RETURN
(
SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') +
CAST(Cuisine AS varchar(20))
FROM Cuisines
)
END
</code></pre>
<p>Cuisines has the structure:</p>
<pre><code>CuisineID INT PK,
Cuisine VARCHAR(20)
</code></pre>
<p>When I try to create the function as above, I get an error: </p>
<blockquote>
<p>Msg 102, Level 15, State 1, Procedure CombineValues, Line 10 Incorrect
syntax near '='.</p>
</blockquote>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 111509,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 0,
"selected": false,
"text": "<p>try changing SELECT to SET and then end your function by SELECT (ing) your @CuisineList</p>\n"
},
{... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6939/"
] | I'm trying to create a UDF in `SQL Server 2005 Express` as below:
```
CREATE FUNCTION [CombineValues] ()
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @CuisineList VARCHAR(8000);
RETURN
(
SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') +
CAST(Cuisine AS varchar(20))
FROM Cuisines
)
END
```
Cuisines has the structure:
```
CuisineID INT PK,
Cuisine VARCHAR(20)
```
When I try to create the function as above, I get an error:
>
> Msg 102, Level 15, State 1, Procedure CombineValues, Line 10 Incorrect
> syntax near '='.
>
>
>
What am I doing wrong? | This answer is from the original poster, Wild Thing. Please do not vote it up or down.
```
CREATE FUNCTION [CombineValues] ()
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @CuisineList VARCHAR(8000);
SELECT @CuisineList = COALESCE(@CuisineList + ', ', '') + CAST(Cuisine AS varchar(20)) FROM Cuisines;
RETURN
(
SELECT @CuisineList
)
END
``` |
111,529 | <p>Is there any way to create the <em>query parameters</em> for doing a <em>GET request</em> in JavaScript?</p>
<p>Just like in Python you have <a href="http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html" rel="noreferrer"><code>urllib.urlencode()</code></a>, which takes in a dictionary (or list of two tuples) and creates a string like <code>'var1=value1&var2=value2'</code>.</p>
| [
{
"answer_id": 111533,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using <a href=\"http://www.prototypejs.org\" rel=\"noreferrer\">Prototype</a> there is <a href=\"ht... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Is there any way to create the *query parameters* for doing a *GET request* in JavaScript?
Just like in Python you have [`urllib.urlencode()`](http://web.archive.org/web/20080926234926/http://docs.python.org:80/lib/module-urllib.html), which takes in a dictionary (or list of two tuples) and creates a string like `'var1=value1&var2=value2'`. | Here you go:
```
function encodeQueryData(data) {
const ret = [];
for (let d in data)
ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
return ret.join('&');
}
```
Usage:
```
const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
const querystring = encodeQueryData(data);
``` |
111,587 | <p>How do I name a result group in a Regex? (.Net)</p>
| [
{
"answer_id": 111594,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<pre><code>(?<NameOfGroup>[a-z]*)\n</code></pre>\n\n<p>Use the ? syntax like in the sample above.</p>\n"
},
{
"a... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] | How do I name a result group in a Regex? (.Net) | ```
(?<NAME>EXPRESSION) or (?'NAME'EXPRESSION)
``` |
111,630 | <p>Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):</p>
<pre><code>HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL);
</code></pre>
<p>I'm using native C++ with the Windows API, no managed code.</p>
| [
{
"answer_id": 111661,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 3,
"selected": true,
"text": "<p>I believe it has got nothing to do with your code, but you need to set up a proper <strong>manifest</strong> file... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1467/"
] | Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):
```
HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL);
```
I'm using native C++ with the Windows API, no managed code. | I believe it has got nothing to do with your code, but you need to set up a proper **manifest** file to get the themed controls.
Some info here: [@msdn.com](http://msdn.microsoft.com/en-us/library/aa374191(VS.85).aspx) and here: [@blogs.msdn.com](http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx)
You can see a difference between application with and without manifest here: [heaventools.com](http://www.heaventools.com/PE_Explorer_resource_XP_Wizard.htm) |
111,687 | <p>Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?</p>
<p>If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:</p>
<pre><code>class Foo
def initialize
@@log = Syslog.open("foo")
end
end
</code></pre>
<p>I don't immediately see the place where the <code>Syslog.close</code> call should be, but what do you recommend?</p>
| [
{
"answer_id": 111724,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 3,
"selected": true,
"text": "<p>The open method accepts a block. Do something like this:</p>\n\n<pre><code>class Foo\n def do_something\n Sy... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?
If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:
```
class Foo
def initialize
@@log = Syslog.open("foo")
end
end
```
I don't immediately see the place where the `Syslog.close` call should be, but what do you recommend? | The open method accepts a block. Do something like this:
```
class Foo
def do_something
Syslog.open do
# work with the syslog here
end
end
end
``` |
111,700 | <p>It's the weekend, so I relax from spending all week programming by writing a hobby project.</p>
<p>I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)</p>
<p>I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.</p>
<p>I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.</p>
<p>The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode, </p>
<pre><code>0 - BRK
1 - ORA (D,X)
2 - COP b
</code></pre>
<p>etc</p>
<p>However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short. </p>
<p>Is anyone familiar with this CPU's memory model?</p>
<p>EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.</p>
<p><strong>EDIT:</strong> Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)</p>
<p>I uploaded the source:</p>
<p><a href="https://archive.codeplex.com/?p=cpu6502" rel="nofollow noreferrer">https://archive.codeplex.com/?p=cpu6502</a></p>
<p>If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :)</p>
| [
{
"answer_id": 111737,
"author": "Brendan Kidwell",
"author_id": 13958,
"author_profile": "https://Stackoverflow.com/users/13958",
"pm_score": 1,
"selected": false,
"text": "<p>This book might help: <a href=\"http://www.atariarchives.org/mlb/\" rel=\"nofollow noreferrer\">http://www.atar... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | It's the weekend, so I relax from spending all week programming by writing a hobby project.
I wrote the framework of a MOS 6502 CPU emulator yesterday, the registers, stack, memory and all the opcodes are implemented. (Link to source below)
I can manually run a series of operations in the debugger I wrote, but I'd like to load a NES rom and just point the program counter at its instructions, I figured that this would be the fastest way to find flawed opcodes.
I wrote a quick NES rom loader and loaded the ROM banks into the CPU memory.
The problem is that I don't know how the opcodes are encoded. I know that the opcodes themselves follow a pattern of one byte per opcode that uniquely identifies the opcode,
```
0 - BRK
1 - ORA (D,X)
2 - COP b
```
etc
However I'm not sure where I'm supposed to find the opcode argument. Is it the the byte directly following? In absolute memory, I suppose it might not be a byte but a short.
Is anyone familiar with this CPU's memory model?
EDIT: I realize that this is probably shot in the dark, but I was hoping there were some oldschool Apple and Commodore hackers lurking here.
**EDIT:** Thanks for your help everyone. After I implemented the proper changes to align each operation the CPU can load and run Mario Brothers. It doesn't do anything but loop waiting for Start, but its a good sign :)
I uploaded the source:
<https://archive.codeplex.com/?p=cpu6502>
If anyone has ever wondered how an emulator works, its pretty easy to follow. Not optimized in the least, but then again, I'm emulating a CPU that runs at 2mhz on a 2.4ghz machine :) | The opcode takes one byte, and the operands are in the following bytes. Check out the byte size column [here](http://www.atariarchives.org/2bml/chapter_10.php), for instance. |
111,769 | <p>I searched the net and handbook, but I only managed to learn what is the masked package, and not how to install it. I did find some commands, but they don't seem to work on 2008 (looking at it, it seems those are for earlier versions). I have something like this:</p>
<pre><code>localhost ~ # emerge flamerobin
Calculating dependencies
!!! All ebuilds that could satisfy "dev-db/flamerobin" have been masked.
!!! One of the following masked packages is required to complete your request:
- dev-db/flamerobin-0.8.6 (masked by: ~x86 keyword)
- dev-db/flamerobin-0.8.3 (masked by: ~x86 keyword)
</code></pre>
<p>I would like to install version 0.8.6, but don't know how? I found some instructions, but they tell me to edit or write to some files under /etc/portage. However, I don't have /etc/portage on my system:</p>
<pre><code>localhost ~ # ls /etc/portage
ls: cannot access /etc/portage: No such file or directory
</code></pre>
| [
{
"answer_id": 111779,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Simply mkdir /etc/portage and edit as mentioned here: <a href=\"http://gentoo-wiki.com/TIP_Dealing_with_masked_packages#But_... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] | I searched the net and handbook, but I only managed to learn what is the masked package, and not how to install it. I did find some commands, but they don't seem to work on 2008 (looking at it, it seems those are for earlier versions). I have something like this:
```
localhost ~ # emerge flamerobin
Calculating dependencies
!!! All ebuilds that could satisfy "dev-db/flamerobin" have been masked.
!!! One of the following masked packages is required to complete your request:
- dev-db/flamerobin-0.8.6 (masked by: ~x86 keyword)
- dev-db/flamerobin-0.8.3 (masked by: ~x86 keyword)
```
I would like to install version 0.8.6, but don't know how? I found some instructions, but they tell me to edit or write to some files under /etc/portage. However, I don't have /etc/portage on my system:
```
localhost ~ # ls /etc/portage
ls: cannot access /etc/portage: No such file or directory
``` | Simply mkdir /etc/portage and edit as mentioned here: <http://gentoo-wiki.com/TIP_Dealing_with_masked_packages#But_you_want_to_install_the_package_anyway>... |
111,792 | <p>For example:</p>
<pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 });
</code></pre>
<p>or:</p>
<pre><code>root.Nodes.Add(new TNode() { Foo1 = bar1,
Foo2 = bar2,
Foo3 = bar3 });
</code></pre>
| [
{
"answer_id": 111803,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 3,
"selected": true,
"text": "<p>I've done it both ways.. IMO it depends on the complexity of the initialization.</p>\n\n<p>If it is simple 2 or... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] | For example:
```
root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 });
```
or:
```
root.Nodes.Add(new TNode() { Foo1 = bar1,
Foo2 = bar2,
Foo3 = bar3 });
``` | I've done it both ways.. IMO it depends on the complexity of the initialization.
If it is simple 2 or 3 properties I will initialize on one line generally, but if i'm setting up an object with values for insertion into a database or something that has alot of properties i'll break it out like your second example.
```
Income income = new Income
{
Initials = something,
CheckNumber = something,
CheckDate = something,
BranchNumber = something
};
```
or
```
return new Report.ReportData { ReportName = something, Formulas = something};
``` |
111,866 | <p>In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?</p>
<p>Thanks,</p>
<p>Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;</p>
<pre><code>iterator it = someList.begin();
while (it != someList.end())
{
if (shouldRemove(it))
it = someList.erase(it);
}
</code></pre>
| [
{
"answer_id": 111890,
"author": "Nathan Kinsinger",
"author_id": 20045,
"author_profile": "https://Stackoverflow.com/users/20045",
"pm_score": 3,
"selected": false,
"text": "<p>Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.</p>\n"
... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?
Thanks,
Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;
```
iterator it = someList.begin();
while (it != someList.end())
{
if (shouldRemove(it))
it = someList.erase(it);
}
``` | For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax:
```
NSMutableArray *discardedItems = [NSMutableArray array];
for (SomeObjectClass *item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addObject:item];
}
[originalArrayOfItems removeObjectsInArray:discardedItems];
```
Then there is no question about whether indices are being updated correctly, or other little bookkeeping details.
Edited to add:
It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. [See a good analysis here:](http://ridiculousfish.com/blog/posts/array.html)
The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs.
For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it. |
111,928 | <p>I can print with <code>printf</code> as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?</p>
<p>I am running gcc.</p>
<pre><code>printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
</code></pre>
| [
{
"answer_id": 111938,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": false,
"text": "<p>There is no formatting function in the C standard library to output binary like that. All the format operations t... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8959/"
] | I can print with `printf` as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?
I am running gcc.
```
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
``` | Hacky but works for me:
```
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
```
```
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));
```
For multi-byte types
```
printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));
```
You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to `BYTE_TO_BINARY`) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here. |
111,934 | <p>I want to create some text in a canvas:</p>
<pre><code>myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")
</code></pre>
<p>Now how do I find the width and height of <code>myText</code>?</p>
| [
{
"answer_id": 111974,
"author": "skymt",
"author_id": 18370,
"author_profile": "https://Stackoverflow.com/users/18370",
"pm_score": 5,
"selected": true,
"text": "<pre><code>bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)\nwidth = bounds[2] - bounds[0]\nheight ... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10577/"
] | I want to create some text in a canvas:
```
myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")
```
Now how do I find the width and height of `myText`? | ```
bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
```
See the [TkInter reference](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/canvas-methods.html). |
111,945 | <p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p>
| [
{
"answer_id": 111952,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "<p>Have you taken a look at <a href=\"http://inamidst.com/proj/put/put.py\" rel=\"nofollow noreferrer\">put.py</a>?... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161922/"
] | I need to upload some data to a server using HTTP `PUT` in python. From my brief reading of the urllib2 docs, it only does HTTP `POST`. Is there any way to do an HTTP `PUT` in python? | I've used a variety of python HTTP libs in the past, and I've settled on [requests](https://requests.readthedocs.io/) as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
```
payload = {'username': 'bob', 'email': 'bob@bob.com'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
```
You can then check the response status code with:
```
r.status_code
```
or the response with:
```
r.content
```
Requests has a lot synactic sugar and shortcuts that'll make your life easier. |
111,954 | <p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p>
<pre><code># File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
</code></pre>
<p>Which yields:</p>
<pre><code>$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
</code></pre>
<p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p>
<p>Is there a portable way to get an array filled with the directory listing?</p>
<p>(The array should only have the folder names.)</p>
| [
{
"answer_id": 111966,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 8,
"selected": true,
"text": "<p>Try using <a href=\"https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst\" rel=\"noreferrer\"><code>ftp.... | 2008/09/21 | [
"https://Stackoverflow.com/questions/111954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:
```
# File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
```
Which yields:
```
$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
```
I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.
Is there a portable way to get an array filled with the directory listing?
(The array should only have the folder names.) | Try using [`ftp.nlst(dir)`](https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst).
However, note that if the folder is empty, it might throw an error:
```
files = []
try:
files = ftp.nlst()
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
``` |
112,036 | <p>I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.</p>
<pre><code><mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:RadioButtonGroup id="leftAxisGrp" />
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
trace (rightAxisGrp.selection);
trace (rightAxisGrp.selection.data.name);
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
height="150" width="400"
sortExpertMode="true"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn
headerText="L" width="25" paddingLeft="6"
dataField="left" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn
headerText="R" width="25" paddingLeft="6"
dataField="right" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:dataProvider>
<mx:Array>
<mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" />
<mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" />
<mx:Object left="false" right="false" name="Sambirano Mouse Lemur" />
<mx:Object left="false" right="false" name="Simmons' Mouse Lemur" />
<mx:Object left="false" right="false" name="Pygmy Mouse Lemur" />
<mx:Object left="false" right="false" name="Brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" />
<mx:Object left="false" right="false" name="Goodman's Mouse Lemur" />
<mx:Object left="false" right="false" name="Jolly's Mouse Lemur" />
<mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" />
<mx:Object left="false" right="false" name="Claire's Mouse Lemur" />
<mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" />
<mx:Object left="false" right="false" name="Lokobe Mouse Lemur" />
<mx:Object left="true" right="true" name="Bongolava Mouse Lemur" />
</mx:Array>
</mx:dataProvider>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
</code></pre>
<hr>
<p><em>UPDATED</em> (thanks bill!)</p>
<p>Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).</p>
<pre><code><mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.utils.ObjectProxy;
import mx.collections.ArrayCollection;
[Bindable]
private var myData:ArrayCollection = new ArrayCollection ();
private function selectItem (selObject:Object, property:String) : void
{
for each (var obj:ObjectProxy in myData) {
obj[property] = (obj.name === selObject.name);
}
readingsGrid.invalidateDisplayList ();
}
]]>
</mx:Script>
<mx:RadioButtonGroup id="leftAxisGrp">
<mx:change>
<![CDATA[
selectItem (leftAxisGrp.selectedValue, 'left');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
selectItem (rightAxisGrp.selectedValue, 'right');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
dataProvider="{myData}"
sortExpertMode="true"
height="150" width="400"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn id="leftCol"
headerText="L" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp"
buttonMode="true" value="{data}" selected="{data.left}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn id="rightCol"
headerText="R" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp"
buttonMode="true" value="{data}" selected="{data.right}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:creationComplete>
<![CDATA[
myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" }));
myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" }));
]]>
</mx:creationComplete>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
</code></pre>
| [
{
"answer_id": 112822,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 0,
"selected": false,
"text": "<p>Reproduced this. Likely to be a ADG bug, we've run into a few here. (Didn't find this one on bugs.adobe.com, but t... | 2008/09/21 | [
"https://Stackoverflow.com/questions/112036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7536/"
] | I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.
```
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:RadioButtonGroup id="leftAxisGrp" />
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
trace (rightAxisGrp.selection);
trace (rightAxisGrp.selection.data.name);
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
height="150" width="400"
sortExpertMode="true"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn
headerText="L" width="25" paddingLeft="6"
dataField="left" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn
headerText="R" width="25" paddingLeft="6"
dataField="right" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:dataProvider>
<mx:Array>
<mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" />
<mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" />
<mx:Object left="false" right="false" name="Sambirano Mouse Lemur" />
<mx:Object left="false" right="false" name="Simmons' Mouse Lemur" />
<mx:Object left="false" right="false" name="Pygmy Mouse Lemur" />
<mx:Object left="false" right="false" name="Brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" />
<mx:Object left="false" right="false" name="Goodman's Mouse Lemur" />
<mx:Object left="false" right="false" name="Jolly's Mouse Lemur" />
<mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" />
<mx:Object left="false" right="false" name="Claire's Mouse Lemur" />
<mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" />
<mx:Object left="false" right="false" name="Lokobe Mouse Lemur" />
<mx:Object left="true" right="true" name="Bongolava Mouse Lemur" />
</mx:Array>
</mx:dataProvider>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
```
---
*UPDATED* (thanks bill!)
Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).
```
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.utils.ObjectProxy;
import mx.collections.ArrayCollection;
[Bindable]
private var myData:ArrayCollection = new ArrayCollection ();
private function selectItem (selObject:Object, property:String) : void
{
for each (var obj:ObjectProxy in myData) {
obj[property] = (obj.name === selObject.name);
}
readingsGrid.invalidateDisplayList ();
}
]]>
</mx:Script>
<mx:RadioButtonGroup id="leftAxisGrp">
<mx:change>
<![CDATA[
selectItem (leftAxisGrp.selectedValue, 'left');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
selectItem (rightAxisGrp.selectedValue, 'right');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
dataProvider="{myData}"
sortExpertMode="true"
height="150" width="400"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn id="leftCol"
headerText="L" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp"
buttonMode="true" value="{data}" selected="{data.left}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn id="rightCol"
headerText="R" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp"
buttonMode="true" value="{data}" selected="{data.right}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:creationComplete>
<![CDATA[
myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" }));
myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" }));
]]>
</mx:creationComplete>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
``` | What's happening here is that Flex only creates itemRenderer instances for the *visible* columns. When you scroll around, those instances get recycled. So if you scroll down, the RadioButton object that was drawing the first column of the first row may now have changed to instead be drawing the first column of the seventh row. Flex resets the "data" property of the itemRenderer whenever this happens.
So while there are 15 rows of data, there are only ever 12 RadioButtons (6 for the "left", and 6 for the "right" for the 6 visible rows), not 30 RadioButtons, as you might expect. This isn't a big problem if you're only *displaying* the selection, but it becomes more of a problem when you allow updates.
To fix the display issue, instead of setting the "dataField" on the column, you can bind the RadioButton's "selected" property to the itemRenderer's data.left (or right) value. You'll then need to make the items in your dataProvider "Bindable".
To fix the update issue, since you'd be binding directly to the dataProvider item values, you need to be sure to update them. Since there's isn't one RadioButton per-item, you'll need another scheme for that. In this case I put in a handler that goes and sets the left/right property of each item to "false", except for the "selected" one, which gets set to "true".
I updated your example code based on these thoughts. Try something like this:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application layout="absolute"
xmlns:my="*"
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RadioButtonGroup id="leftAxisGrp"
change="selectItem(leftAxisGrp.selectedValue, 'left');"/>
<mx:RadioButtonGroup id="rightAxisGrp"
change="selectItem(rightAxisGrp.selectedValue, 'right');">
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
height="150" width="400"
sortExpertMode="true"
selectable="false"
dataProvider="{adgData.object}">
<mx:columns>
<mx:AdvancedDataGridColumn
headerText="L" width="25" paddingLeft="6"
sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp"
value="{data}" selected="{data.left}"/>
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn
headerText="R" width="25" paddingLeft="6"
sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp"
value="{data}" selected="{data.right}"/>
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
</mx:AdvancedDataGrid>
<mx:Model id="adgData">
<root>
<object left="false" right="false" name="Reddish-gray Mouse Lemur" />
<object left="false" right="false" name="Golden-brown Mouse Lemur" />
<object left="false" right="false" name="Northern Rufous Mouse Lemur" />
<object left="false" right="false" name="Sambirano Mouse Lemur" />
<object left="false" right="false" name="Simmons' Mouse Lemur" />
<object left="false" right="false" name="Pygmy Mouse Lemur" />
<object left="false" right="false" name="Brown Mouse Lemur" />
<object left="false" right="false" name="Madame Berthe's Mouse Lemur" />
<object left="false" right="false" name="Goodman's Mouse Lemur" />
<object left="false" right="false" name="Jolly's Mouse Lemur" />
<object left="false" right="false" name="Mittermeier's Mouse Lemur" />
<object left="false" right="false" name="Claire's Mouse Lemur" />
<object left="false" right="false" name="Danfoss' Mouse Lemur" />
<object left="false" right="false" name="Lokobe Mouse Lemur" />
<object left="true" right="true" name="Bongolava Mouse Lemur" />
</root>
</mx:Model>
<mx:Script>
<![CDATA[
private function selectItem(selObject:Object, property:String) : void {
for each(var obj:Object in adgData.object) {
obj[property] = (obj === selObject);
}
readingsGrid.invalidateDisplayList();
}
]]>
</mx:Script>
</mx:Application>
``` |
112,055 | <p>I'm looking at a batch file which defines the following variables:</p>
<pre><code>set _SCRIPT_DRIVE=%~d0
set _SCRIPT_PATH=%~p0
</code></pre>
<ul>
<li>What do <code>%~d0</code> or <code>%~p0</code> actually mean?</li>
<li>Is there a set of well-known values for things like current directory, drive, parameters to a script?</li>
<li>Are there any other similar shortcuts I could use?</li>
</ul>
| [
{
"answer_id": 112071,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 4,
"selected": false,
"text": "<p>From <em><a href=\"http://www.rgagnon.com/gp/gp-0008.html\" rel=\"noreferrer\" title=\"Filename parsing in batch... | 2008/09/21 | [
"https://Stackoverflow.com/questions/112055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
] | I'm looking at a batch file which defines the following variables:
```
set _SCRIPT_DRIVE=%~d0
set _SCRIPT_PATH=%~p0
```
* What do `%~d0` or `%~p0` actually mean?
* Is there a set of well-known values for things like current directory, drive, parameters to a script?
* Are there any other similar shortcuts I could use? | The magic variables `%`*n* contains the arguments used to invoke the file: `%0` is the path to the bat-file itself, `%1` is the first argument after, `%2` is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. `~d` is drive, `~p` is the path (without drive), `~n` is the file name. They can be combined so `~dp` is drive+path.
`%~dp0` is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: `~t` is the timestamp, `~z` is the size.
Look [here](http://technet.microsoft.com/en-us/library/bb490890.aspx) for a reference for all command line commands. The tilde-magic codes are described under [for](http://technet.microsoft.com/en-us/library/bb490909.aspx). |
112,085 | <p>Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:</p>
<pre><code>struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
memset(this, 0, sizeof(MY_STRUCT));
}
};
</code></pre>
<p>This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous <strong>cbSize</strong> member.</p>
<p>Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice?</p>
| [
{
"answer_id": 112099,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "<p>Precise layout of a class or structure is not guaranteed in C++, which is why you should not make assumptions abo... | 2008/09/21 | [
"https://Stackoverflow.com/questions/112085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] | Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:
```
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
memset(this, 0, sizeof(MY_STRUCT));
}
};
```
This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous **cbSize** member.
Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice? | PREAMBLE:
---------
While my answer is still Ok, I find [litb's answer](https://stackoverflow.com/questions/112085/is-this-c-structure-initialization-trick-safe/1315024#1315024) quite superior to mine because:
1. It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I write it down)
2. It answers exactly the question (that is, initializing the original struct's part to zero)
So please, consider litb's answer before mine. In fact, I suggest the question's author to consider litb's answer as the right one.
Original answer
---------------
Putting a true object (i.e. std::string) etc. inside will break, because the true object will be initialized before the memset, and then, overwritten by zeroes.
Using the initialization list doesn't work for g++ (I'm surprised...). Initialize it instead in the CMyStruct constructor body. It will be C++ friendly:
```
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct() { n1 = 0 ; n2 = 0 ; }
};
```
P.S.: I assumed you did have **no** control over MY\_STRUCT, of course. With control, you would have added the constructor directly inside MY\_STRUCT and forgotten about inheritance. Note that you can add non-virtual methods to a C-like struct, and still have it behave as a struct.
EDIT: Added missing parenthesis, after Lou Franco's comment. Thanks!
EDIT 2 : I tried the code on g++, and for some reason, using the initialization list does not work. I corrected the code using the body constructor. The solution is still valid, though.
Please reevaluate my post, as the original code was changed (see changelog for more info).
EDIT 3 : After reading Rob's comment, I guess he has a point worthy of discussion: "Agreed, but this could be an enormous Win32 structure which may change with a new SDK, so a memset is future proof."
I disagree: Knowing Microsoft, it won't change because of their need for perfect backward compatibility. They will create instead an extended MY\_STRUCT**Ex** struct with the same initial layout as MY\_STRUCT, with additionnal members at the end, and recognizable through a "size" member variable like the struct used for a RegisterWindow, IIRC.
So the only valid point remaining from Rob's comment is the "enormous" struct. In this case, perhaps a memset is more convenient, but you will have to make MY\_STRUCT a variable member of CMyStruct instead of inheriting from it.
I see another hack, but I guess this would break because of possible struct alignment problem.
EDIT 4: Please take a look at Frank Krueger's solution. I can't promise it's portable (I guess it is), but it is still interesting from a technical viewpoint because it shows one case where, in C++, the "this" pointer "address" moves from its base class to its inherited class. |
112,093 | <p>I have a simple list I am using for a horizontal menu:</p>
<pre><code><ul>
<h1>Menu</h1>
<li>
<a href="/" class="selected">Home</a>
</li>
<li>
<a href="/Home">Forum</a>
</li>
</ul>
</code></pre>
<p>When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.</p>
<p>Hope this makes sense.</p>
| [
{
"answer_id": 112106,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 5,
"selected": true,
"text": "<p>The a element is an inline element, meaning it only applies to the text it encloses. If you want the background colo... | 2008/09/21 | [
"https://Stackoverflow.com/questions/112093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] | I have a simple list I am using for a horizontal menu:
```
<ul>
<h1>Menu</h1>
<li>
<a href="/" class="selected">Home</a>
</li>
<li>
<a href="/Home">Forum</a>
</li>
</ul>
```
When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.
Hope this makes sense. | The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine.
Alternatively, you could add this to the selected class' CSS:
```
display: block;
```
Which will make the a element display like a block element. |