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
|
---|---|---|---|---|---|---|
148,951 | <p>I'm trying to use <code>mysqldump</code> to dump a schema, and it mostly works but I ran into one curiosity: the <code>-p</code> or <code>--password</code> option seems like it is doing something other than setting the password (as the <code>man</code> page and <code>--help</code> output say it should).</p>
<p>Specifically, it looks like it's doing what is indicated here: <a href="http://snippets.dzone.com/posts/show/360" rel="noreferrer">http://snippets.dzone.com/posts/show/360</a> - that is, setting the database to dump.</p>
<p>To support my somewhat outlandish claim, I can tell you that if I do not specify the <code>--password</code> (or <code>-p</code>) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the <code>--password</code> option is dumped (or an error is given in the usual case that a password not matching any database name was specified).</p>
<p>Here's a transcript:</p>
<pre>
$ mysqldump -u test -h myhost --no-data --tables --password lose
Enter password:
-- MySQL dump 10.10
mysqldump: Got error: 1044: Access denied for user 'test'@'%' to
database 'lose' when selecting the database
</pre>
<p>So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using <code>expect</code>???</p>
<p>I'm using <code>mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486)</code>.</p>
| [
{
"answer_id": 148969,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try --password=whatever-password-is ?</p>\n\n<p>Perhaps I'm missing the question, but that is what I do to run the tool.</p>\n"
},
{
"answer_id": 148975,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure if it works for the --password version, but if you use -p you can specify the password immediately afterwards (the key is not to include a space):</p>\n\n<p>mysqldump -pmypassword ...</p>\n"
},
{
"answer_id": 148978,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 0,
"selected": false,
"text": "<p>The -p option does not require an argument. You just put -p or --password to indicate that you're going to use a password to access the database. The reason it's dumping the database named whatever you put after -p is that the last argument for mysqldump should be the name of the database you want to dump (or --all-databases if you want them all).</p>\n\n<p>@Nathan's answer is also true. You can specify the password <em>immediately</em> following the -p switch (useful in scripts and such where you can't enter it by hand after executing the command).</p>\n"
},
{
"answer_id": 148984,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 7,
"selected": true,
"text": "<p>From man mysqldump:</p>\n\n<blockquote>\n <p>--password[=password], -p[password]</p>\n \n <p>The password to use when connecting to the server. If you use\n the short option form (-p), you cannot have a space between the option\n and the password. If you omit the password value following the\n --password or -p option on the command line, you are prompted for\n one.<br>\n Specifying a password on the command line should be considered\n insecure. See Section 6.6, \"Keeping Your Password Secure\".</p>\n</blockquote>\n\n<p>Syntactically, you are not using the --password switch correctly. As such, the command line parser is seeing your use of \"lose\" as a stand-alone argument which mysqldump interprets as the database name as it would if you were to attempt a simpler command like <code>mysqldump lose</code></p>\n\n<p>To correct this, try using <code>--password=lose</code> or <code>-plose</code> or simply use <code>-p</code> or <code>--password</code> and type the password when prompted.</p>\n"
},
{
"answer_id": 148989,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 2,
"selected": false,
"text": "<p>Try placing a '=' in between --password lose like:</p>\n\n<pre><code>--password=lose\n</code></pre>\n\n<p>If you use -p, then there can be no space between the -p and the password, i.e. '-plose'.</p>\n"
},
{
"answer_id": 148994,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>--password[=password]</p>\n\n<p>Here is the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html\" rel=\"nofollow noreferrer\">documentation</a></p>\n"
},
{
"answer_id": 149009,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "<p>Another option is to create the file <strong>~/.my.cnf</strong> (permissions need to be 600).</p>\n\n<p>Add this to the .my.cnf file</p>\n\n<pre><code>[client]\npassword=lose\n</code></pre>\n\n<p>This lets you connect as a MySQL user who requires a password without having to actually enter the password. You don't even need the -p or --password.</p>\n\n<p>Very handy for scripting mysql & mysqldump commands.</p>\n"
},
{
"answer_id": 149013,
"author": "Giuseppe Maxia",
"author_id": 18535,
"author_profile": "https://Stackoverflow.com/users/18535",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the -p or --password without an argument, you will get a prompt, asking to insert a password.</p>\n\n<p>If you want to indicate a password on the command line, you must use -pYOURPASSWORD or --password=YOURPASSWORD. Notice that there is no space after -p, and there is an \"=\" sign after --password.</p>\n\n<p>In your example, mysqldump asks for a password, and then treats \"lose\" as the database name. If that was your password, you should have included a \"=\"</p>\n"
},
{
"answer_id": 149093,
"author": "Giuda",
"author_id": 16180,
"author_profile": "https://Stackoverflow.com/users/16180",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe your user \"test\" doesn't have the permission to access your \"lose\" database?</p>\n"
},
{
"answer_id": 2601600,
"author": "Phil Gordemer",
"author_id": 312080,
"author_profile": "https://Stackoverflow.com/users/312080",
"pm_score": 4,
"selected": false,
"text": "<p>I found that this happens if your password has special characters in it. The mysql password here has a ! in it, so I have to do ==password='xxx!xxxx' for it to work corrrectly. Note the ' marks.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/148951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
]
| I'm trying to use `mysqldump` to dump a schema, and it mostly works but I ran into one curiosity: the `-p` or `--password` option seems like it is doing something other than setting the password (as the `man` page and `--help` output say it should).
Specifically, it looks like it's doing what is indicated here: <http://snippets.dzone.com/posts/show/360> - that is, setting the database to dump.
To support my somewhat outlandish claim, I can tell you that if I do not specify the `--password` (or `-p`) option, the command prints the usage statement and exits with an error. If I do specify it, I am immediately prompted to enter a password (!), and then the database specified in the `--password` option is dumped (or an error is given in the usual case that a password not matching any database name was specified).
Here's a transcript:
```
$ mysqldump -u test -h myhost --no-data --tables --password lose
Enter password:
-- MySQL dump 10.10
mysqldump: Got error: 1044: Access denied for user 'test'@'%' to
database 'lose' when selecting the database
```
So, what gives? Is this the way this is supposed to work? It surely does not appear to make sense nor does it match the official documentation. And finally, if this just the way it works, how am I meant to specify the password to be used in an automated job? Using `expect`???
I'm using `mysqldump Ver 10.10 Distrib 5.0.22, for pc-linux-gnu (i486)`. | From man mysqldump:
>
> --password[=password], -p[password]
>
>
> The password to use when connecting to the server. If you use
> the short option form (-p), you cannot have a space between the option
> and the password. If you omit the password value following the
> --password or -p option on the command line, you are prompted for
> one.
>
> Specifying a password on the command line should be considered
> insecure. See Section 6.6, "Keeping Your Password Secure".
>
>
>
Syntactically, you are not using the --password switch correctly. As such, the command line parser is seeing your use of "lose" as a stand-alone argument which mysqldump interprets as the database name as it would if you were to attempt a simpler command like `mysqldump lose`
To correct this, try using `--password=lose` or `-plose` or simply use `-p` or `--password` and type the password when prompted. |
148,955 | <p>I want the 2 columns to touch ie. remove the margins, how can I do this?</p>
<p>My code:</p>
<pre><code> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>testing</TITLE>
<!-- css -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css">
<!-- js -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/utilities/utilities.js"></script>
<style>
.yui-b {
background-color: #eeeeee;
}
</style>
</HEAD>
<BODY>
<div id="doc3" class="yui-t1"> <!-- change class to change preset -->
<div id="hd">header</div>
<div id="bd">
<div id="yui-main">
<div class="yui-b">
bd.main
</div>
</div>
<div class="yui-b">bd.other</div>
</div>
<div id="ft">footer</div>
</div>
</BODY>
</HTML>
</code></pre>
| [
{
"answer_id": 148973,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 1,
"selected": false,
"text": "<p>Add a class to the right column and set margin-left to 0. </p>\n\n<p>If that doesn't work you might have to increase the width by 1 or 2%. You can use firebug to check the applied styles and change them on the fly.</p>\n"
},
{
"answer_id": 634123,
"author": "Neil Fenwick",
"author_id": 76091,
"author_profile": "https://Stackoverflow.com/users/76091",
"pm_score": 1,
"selected": false,
"text": "<p>Notice that you're using YUI (Yahoo UI).</p>\n\n<p>Look for the YUI reset.css. Every browser has potentially different margin, padding, font-size defaults. You should really start every web app with a reset.css file like that to bring everything to a common denominator. Otherwise you might find you \"fix\" the issue, only for it to appear again when viewed from another machine / platform.</p>\n\n<p>Should hopefully start you off with all block elements having no margins or padding and then you can rather add margins and padding back in where you need it.</p>\n"
},
{
"answer_id": 901410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Notice that you're using YUI (Yahoo UI).</strong> </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/148955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want the 2 columns to touch ie. remove the margins, how can I do this?
My code:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>testing</TITLE>
<!-- css -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css">
<!-- js -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.5.2/build/utilities/utilities.js"></script>
<style>
.yui-b {
background-color: #eeeeee;
}
</style>
</HEAD>
<BODY>
<div id="doc3" class="yui-t1"> <!-- change class to change preset -->
<div id="hd">header</div>
<div id="bd">
<div id="yui-main">
<div class="yui-b">
bd.main
</div>
</div>
<div class="yui-b">bd.other</div>
</div>
<div id="ft">footer</div>
</div>
</BODY>
</HTML>
``` | Add a class to the right column and set margin-left to 0.
If that doesn't work you might have to increase the width by 1 or 2%. You can use firebug to check the applied styles and change them on the fly. |
148,982 | <p>I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.</p>
<p>ex.</p>
<p>function A:</p>
<pre><code>add(new Array("hello", some function));
</code></pre>
<p>function B:</p>
<pre><code>public function b(args:Array) {
var myString = args[0];
var myFunc = args[1];
}
</code></pre>
| [
{
"answer_id": 148990,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 3,
"selected": false,
"text": "<p>This is very easy in ActionScript:</p>\n\n<pre><code>function someFunction(foo, bar) {\n ...\n}\n\nfunction a() {\n b([\"hello\", someFunction]);\n}\n\nfunction b(args:Array) {\n var myFunc:Function = args[1];\n myFunc(123, \"helloworld\");\n}\n</code></pre>\n"
},
{
"answer_id": 164498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Simply pass the function name as an argument, no, just like in AS2 or JavaScript?</p>\n\n<pre><code>function functionToPass()\n{\n}\n\nfunction otherFunction( f:Function )\n{\n // passed-in function available here\n f();\n}\n\notherFunction( functionToPass );\n</code></pre>\n"
},
{
"answer_id": 4926184,
"author": "micsun",
"author_id": 607065,
"author_profile": "https://Stackoverflow.com/users/607065",
"pm_score": 2,
"selected": false,
"text": "<p>You can do the following:</p>\n\n<pre><code>add([\"string\", function():void\n{\ntrace('Code...');\n}]);\n</code></pre>\n\n<p>...or...</p>\n\n<pre><code>...\nadd([\"string\", someFunction]);\n...\n\nprivate function someFunction():void\n{\ntrace('Code...');\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/148982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.
ex.
function A:
```
add(new Array("hello", some function));
```
function B:
```
public function b(args:Array) {
var myString = args[0];
var myFunc = args[1];
}
``` | Simply pass the function name as an argument, no, just like in AS2 or JavaScript?
```
function functionToPass()
{
}
function otherFunction( f:Function )
{
// passed-in function available here
f();
}
otherFunction( functionToPass );
``` |
148,988 | <p>I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.</p>
<p>XML example:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<node>
<attribute/>
<node>
<attribute/>
<node/>
</node>
</node>
</code></pre>
<p>Which is the best way to validate it? Recursion?</p>
| [
{
"answer_id": 149003,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 5,
"selected": false,
"text": "<p>XSD does indeed allow for recursion of elements. Here <a href=\"https://web.archive.org/web/20140421153734/http://www.stylusstudio.com/xmldev/200501/post80430.html\" rel=\"nofollow noreferrer\">is a sample for you</a></p>\n\n<pre><code><xsd:element name=\"section\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element ref=\"title\"/>\n <xsd:element ref=\"para\" maxOccurs=\"unbounded\"/>\n <xsd:element ref=\"section\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xsd:sequence>\n </xsd:complexType>\n</xsd:element>\n</code></pre>\n\n<p>As you can see the section element contains a child element that is of type section.</p>\n"
},
{
"answer_id": 149010,
"author": "Dani Duran",
"author_id": 19010,
"author_profile": "https://Stackoverflow.com/users/19010",
"pm_score": 7,
"selected": true,
"text": "<p>if you need a recursive type declaration, here is an example that might help:</p>\n\n<pre><code><xs:schema id=\"XMLSchema1\"\n targetNamespace=\"http://tempuri.org/XMLSchema1.xsd\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://tempuri.org/XMLSchema1.xsd\"\n xmlns:mstns=\"http://tempuri.org/XMLSchema1.xsd\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n>\n <xs:element name=\"node\" type=\"nodeType\"></xs:element>\n\n <xs:complexType name=\"nodeType\"> \n <xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:element name=\"node\" type=\"nodeType\"></xs:element>\n </xs:sequence>\n </xs:complexType>\n\n</xs:schema>\n</code></pre>\n\n<p>As you can see, this defines a recursive schema with only one node named \"node\" which can be as deep as desired.</p>\n"
},
{
"answer_id": 63074091,
"author": "xperroni",
"author_id": 476920,
"author_profile": "https://Stackoverflow.com/users/476920",
"pm_score": 1,
"selected": false,
"text": "<p>The other solutions work great for making root elements recursive. However, in order to make a non-root element recursive without turning it into a valid root element in the process, a slightly different approach is needed.</p>\n<p>Let's say you want to define an XML message format for exchanging structured data between nodes in a distributed application. It contains the following elements:</p>\n<ul>\n<li><code><message></code> - the root element;</li>\n<li><code><from></code> - the message's origin;</li>\n<li><code><to></code> - the message's destination;</li>\n<li><code><type></code> - the data structure type encoded in the message;</li>\n<li><code><data></code> - the data contained in the message.</li>\n</ul>\n<p>In order to support complex data types, <code><data></code> is a recursive element. This makes possible to write messages as below, for sending e.g. a <a href=\"http://docs.ros.org/melodic/api/geometry_msgs/html/msg/TwistStamped.html\" rel=\"nofollow noreferrer\"><code>geometry_msgs/TwistStamped</code></a> message to a flying drone specifying its linear and angular (i.e. rotating) speeds:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="utf-8"?>\n\n<message xmlns="https://stackoverflow.com/message/1.0.0">\n <from>controller:8080</from>\n <to>drone:8080</to>\n <type>geometry_msgs/TwistStamped</type>\n <data name="header">\n <data name="seq">0</data>\n <data name="stamp">\n <data name="sec">1</data>\n <data name="nsec">0</data>\n </data>\n <data name="frame_id">base_link</data>\n </data>\n <data name="twist">\n <data name="linear">\n <data name="x">1.0</data>\n <data name="y">0</data>\n <data name="z">1.0</data>\n </data>\n <data name="angular">\n <data name="x">0.3</data>\n <data name="y">0</data>\n <data name="z">0</data>\n </data>\n </data>\n</message>\n</code></pre>\n<p>We can easily write an XML schema to validate this format:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="utf-8"?>\n\n<xs:schema\n xmlns:xs="http://www.w3.org/2001/XMLSchema"\n targetNamespace="https://stackoverflow.com/message/1.0.0"\n elementFormDefault="qualified"\n xmlns="https://stackoverflow.com/message/1.0.0"\n>\n <xs:element name="data">\n <xs:complexType mixed="true">\n <xs:sequence>\n <xs:element ref="data" minOccurs="0" maxOccurs="unbounded"/>\n </xs:sequence>\n <xs:attribute name="name" type="xs:string" use="required"/>\n </xs:complexType>\n </xs:element>\n\n <xs:element name="message">\n <xs:complexType>\n <xs:sequence>\n <xs:element name="from" type="xs:string"/>\n <xs:element name="to" type="xs:string"/>\n <xs:element name="type" type="xs:string"/>\n <xs:element ref="data" maxOccurs="unbounded"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n</code></pre>\n<p>The problem with the schema above is that it makes <code><data></code> a root element, which means it also validates the document below:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="utf-8"?>\n\n<data xmlns="https://stackoverflow.com/message/1.0.0" name="twist">\n <data name="header">\n <data name="seq">0</data>\n <data name="stamp">\n <data name="sec">1</data>\n <data name="nsec">0</data>\n </data>\n <data name="frame_id">base_link</data>\n </data>\n <data name="twist">\n <data name="linear">\n <data name="x">1.0</data>\n <data name="y">0</data>\n <data name="z">1.0</data>\n </data>\n <data name="angular">\n <data name="x">0.3</data>\n <data name="y">0</data>\n <data name="z">0</data>\n </data>\n </data>\n</data>\n</code></pre>\n<p>In order to avoid this side-effect, instead of defining the <code><data></code> element directly at the global level, we first define a <code>data</code> type, then define a <code>data</code> element of that type inside <code>message</code>:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="utf-8"?>\n\n<xs:schema\n xmlns:xs="http://www.w3.org/2001/XMLSchema"\n targetNamespace="https://stackoverflow.com/message/1.0.0"\n elementFormDefault="qualified"\n xmlns="https://stackoverflow.com/message/1.0.0"\n>\n <xs:complexType name="data" mixed="true">\n <xs:sequence>\n <xs:element name="data" type="data" minOccurs="0" maxOccurs="unbounded"/>\n </xs:sequence>\n <xs:attribute name="name" type="xs:string" use="required"/>\n </xs:complexType>\n\n <xs:element name="message">\n <xs:complexType>\n <xs:sequence>\n <xs:element name="from" type="xs:string"/>\n <xs:element name="to" type="xs:string"/>\n <xs:element name="type" type="xs:string"/>\n <xs:element name="data" type="data" maxOccurs="unbounded"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n</code></pre>\n<p>Notice that we end up having to define the <code><data></code> element twice — once inside the <code>data</code> type, and again inside <code><element></code> — but apart a little work duplication this is of no consequence.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/148988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19012/"
]
| I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.
XML example:
```
<?xml version="1.0" encoding="utf-8"?>
<node>
<attribute/>
<node>
<attribute/>
<node/>
</node>
</node>
```
Which is the best way to validate it? Recursion? | if you need a recursive type declaration, here is an example that might help:
```
<xs:schema id="XMLSchema1"
targetNamespace="http://tempuri.org/XMLSchema1.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/XMLSchema1.xsd"
xmlns:mstns="http://tempuri.org/XMLSchema1.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="node" type="nodeType"></xs:element>
<xs:complexType name="nodeType">
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="node" type="nodeType"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:schema>
```
As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired. |
149,008 | <p>I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised? </p>
<p>Best I could come up with (I am certain it gets better than this):</p>
<pre><code>public void MyCallback(object sender, EventArgs e) { _flag = true;}
[Test]
public void DoSomethingRaisesEvent() {
_flag = false;
using(_mocks.Record()) {
Expect.Call(delegeate { _obj.DoSomething();});
}
using(_mocks.Playback()) {
_obj = new SomethingDoer();
_obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
Assert.IsTrue(_flag);
}
}
</code></pre>
| [
{
"answer_id": 149077,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks</p>\n\n<p>In any case, here is another way I like to deal with events:</p>\n\n<pre><code>[Test]\npublic void MyEventTest()\n{\n\n IEventRaiser eventRaiser;\n\n mockView = _mocks.CreateMock<IView>();\n using (_mocks.Record())\n {\n mockView.DoSomethingEvent += null;\n eventRaiser = LastCall.IgnoreArguments();\n }\n using (_mocks.Playback())\n {\n new Controller(mockView, mockModel);\n eventRaiser.Raise(mockView, EventArgs.Empty);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 149914,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 3,
"selected": false,
"text": "<p>I found <a href=\"http://haacked.com/archive/2006/12/13/tip_jar_unit_test_events_with_anonymous_delegates.aspx\" rel=\"noreferrer\">this article by Phil Haack on how to test events using anonymous delegates</a></p>\n\n<p>Here is the code, ripped directly from his blog for those too lazy to click through:</p>\n\n<pre><code>[Test]\npublic void SettingValueRaisesEvent()\n{\n bool eventRaised = false;\n Parameter param = new Parameter(\"num\", \"int\", \"1\");\n param.ValueChanged += \n delegate(object sender, ValueChangedEventArgs e)\n {\n Assert.AreEqual(\"42\", e.NewValue);\n Assert.AreEqual(\"1\", e.OldValue);\n Assert.AreEqual(\"num\", e.ParameterName);\n eventRaised = true;\n };\n param.Value = \"42\"; //should fire event.\n\n Assert.IsTrue(eventRaised, \"Event was not raised\");\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I have an object that I'm testing that raises an event. What is the best way of using Rhino Mocks to check that it was raised?
Best I could come up with (I am certain it gets better than this):
```
public void MyCallback(object sender, EventArgs e) { _flag = true;}
[Test]
public void DoSomethingRaisesEvent() {
_flag = false;
using(_mocks.Record()) {
Expect.Call(delegeate { _obj.DoSomething();});
}
using(_mocks.Playback()) {
_obj = new SomethingDoer();
_obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
Assert.IsTrue(_flag);
}
}
``` | I found [this article by Phil Haack on how to test events using anonymous delegates](http://haacked.com/archive/2006/12/13/tip_jar_unit_test_events_with_anonymous_delegates.aspx)
Here is the code, ripped directly from his blog for those too lazy to click through:
```
[Test]
public void SettingValueRaisesEvent()
{
bool eventRaised = false;
Parameter param = new Parameter("num", "int", "1");
param.ValueChanged +=
delegate(object sender, ValueChangedEventArgs e)
{
Assert.AreEqual("42", e.NewValue);
Assert.AreEqual("1", e.OldValue);
Assert.AreEqual("num", e.ParameterName);
eventRaised = true;
};
param.Value = "42"; //should fire event.
Assert.IsTrue(eventRaised, "Event was not raised");
}
``` |
149,037 | <p><P>How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed.</P>
Here's the code that I'm currently using to put the message in the queue:</p>
<pre><code>/**
* publishResponseToQueue publishes Requests to the Queue.
*
* @param jmsQueueFactory -Name of the queue-connection-factory
* @param jmsQueue -The queue name for the request
* @param response -A response object that needs to be published
*
* @throws ServiceLocatorException -An exception if a request message
* could not be published to the Topic
*/
private void publishResponseToQueue( String jmsQueueFactory,
String jmsQueue,
Response response )
throws ServiceLocatorException {
if ( logger.isInfoEnabled() ) {
logger.info( "Begin publishRequestToQueue: " +
jmsQueueFactory + "," + jmsQueue + "," + response );
}
logger.assertLog( jmsQueue != null && !jmsQueue.equals(""),
"jmsQueue cannot be null" );
logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""),
"jmsQueueFactory cannot be null" );
logger.assertLog( response != null, "Request cannot be null" );
try {
Queue queue = (Queue)_context.lookup( jmsQueue );
QueueConnectionFactory factory = (QueueConnectionFactory)
_context.lookup( jmsQueueFactory );
QueueConnection connection = factory.createQueueConnection();
connection.start();
QueueSession session = connection.createQueueSession( false,
QueueSession.AUTO_ACKNOWLEDGE );
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setJMSCorrelationID(response.getID());
objectMessage.setObject( response );
session.createSender( queue ).send( objectMessage );
session.close();
connection.close();
} catch ( Exception e ) {
//XC3.2 Added/Modified BEGIN
logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " +
"Response to the Queue - " + e.getMessage() );
throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " +
"- Could not publish the " +
"Response to the Queue - " + e.getMessage() );
//XC3.2 Added/Modified END
}
if ( logger.isInfoEnabled() ) {
logger.info( "End publishResponseToQueue: " +
jmsQueueFactory + "," + jmsQueue + response );
}
} // end of publishResponseToQueue method
</code></pre>
| [
{
"answer_id": 149167,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 5,
"selected": true,
"text": "<p>The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver.</p>\n\n<pre><code> QueueReceiver receiver = session.createReceiver(myQueue, \"JMSCorrelationID='theid'\");\n</code></pre>\n\n<p>then</p>\n\n<pre><code>receiver.receive()\n</code></pre>\n\n<p>or </p>\n\n<pre><code>receiver.setListener(myListener);\n</code></pre>\n"
},
{
"answer_id": 149399,
"author": "James Strachan",
"author_id": 2068211,
"author_profile": "https://Stackoverflow.com/users/2068211",
"pm_score": 3,
"selected": false,
"text": "<p>BTW while its not the actual question you asked - if you are trying to implement request response over JMS I'd recommend <a href=\"http://activemq.apache.org/how-should-i-implement-request-response-with-jms.html\" rel=\"noreferrer\">reading this article</a> as the JMS API is quite a bit more complex than you might imagine and doing this efficiently is much harder than it looks. </p>\n\n<p>In particular <a href=\"http://activemq.apache.org/how-do-i-use-jms-efficiently.html\" rel=\"noreferrer\">to use JMS efficiently</a> you should try to avoid creating consumers for a single message etc.</p>\n\n<p>Also because the JMS API is so very complex to use correctly and efficiently - particularly with pooling, transactions and concurrent processing - I recommend folks <a href=\"http://activemq.apache.org/camel/hiding-middleware.html\" rel=\"noreferrer\">hide the middleware from their application code</a> such as via using <a href=\"http://activemq.apache.org/camel/spring-remoting.html\" rel=\"noreferrer\">Apache Camel's Spring Remoting implementation for JMS</a></p>\n"
},
{
"answer_id": 19505822,
"author": "Trying",
"author_id": 2109070,
"author_profile": "https://Stackoverflow.com/users/2109070",
"pm_score": 0,
"selected": false,
"text": "<pre><code>String filter = \"JMSCorrelationID = '\" + msg.getJMSMessageID() + \"'\";\nQueueReceiver receiver = session.createReceiver(queue, filter);\n</code></pre>\n\n<p>Here the receiver will get the messages for which <code>JMSCorrelationID</code> is equal to <code>MessageID</code>. this is very helpful in request/ response paradigm.</p>\n\n<p>or you can directly set this to any value:</p>\n\n<pre><code>QueueReceiver receiver = session.createReceiver(queue, \"JMSCorrelationID ='\"+id+\"'\";);\n</code></pre>\n\n<p>Than you can do either <code>receiver.receive(2000);</code> or <code>receiver.setMessageListener(this);</code></p>\n"
},
{
"answer_id": 27805185,
"author": "saptarshi",
"author_id": 1421710,
"author_profile": "https://Stackoverflow.com/users/1421710",
"pm_score": 2,
"selected": false,
"text": "<p>Hope this will help. I used Open MQ.</p>\n\n<pre><code>package com.MQueues;\n\nimport java.util.UUID;\n\nimport javax.jms.JMSException;\nimport javax.jms.MessageProducer;\nimport javax.jms.QueueConnection;\nimport javax.jms.QueueReceiver;\nimport javax.jms.QueueSession;\nimport javax.jms.Session;\nimport javax.jms.TextMessage;\n\nimport com.sun.messaging.BasicQueue;\nimport com.sun.messaging.QueueConnectionFactory;\n\npublic class HelloProducerConsumer {\n\npublic static String queueName = \"queue0\";\npublic static String correlationId;\n\npublic static String getCorrelationId() {\n return correlationId;\n}\n\npublic static void setCorrelationId(String correlationId) {\n HelloProducerConsumer.correlationId = correlationId;\n}\n\npublic static String getQueueName() {\n return queueName;\n}\n\npublic static void sendMessage(String threadName) {\n correlationId = UUID.randomUUID().toString();\n try {\n\n // Start connection\n QueueConnectionFactory cf = new QueueConnectionFactory();\n QueueConnection connection = cf.createQueueConnection();\n QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);\n BasicQueue destination = (BasicQueue) session.createQueue(threadName);\n MessageProducer producer = session.createProducer(destination);\n connection.start();\n\n // create message to send\n TextMessage message = session.createTextMessage();\n message.setJMSCorrelationID(correlationId);\n message.setText(threadName + \"(\" + System.currentTimeMillis() \n + \") \" + correlationId +\" from Producer\");\n\n System.out.println(correlationId +\" Send from Producer\");\n producer.send(message);\n\n // close everything\n producer.close();\n session.close();\n connection.close();\n\n } catch (JMSException ex) {\n System.out.println(\"Error = \" + ex.getMessage());\n }\n}\n\npublic static void receivemessage(final String correlationId) {\n try {\n\n QueueConnectionFactory cf = new QueueConnectionFactory();\n QueueConnection connection = cf.createQueueConnection();\n QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);\n\n BasicQueue destination = (BasicQueue) session.createQueue(getQueueName());\n\n connection.start();\n\n System.out.println(\"\\n\");\n System.out.println(\"Start listen \" + getQueueName() + \" \" + correlationId +\" Queue from receivemessage\");\n long now = System.currentTimeMillis();\n\n // receive our message\n String filter = \"JMSCorrelationID = '\" + correlationId + \"'\";\n QueueReceiver receiver = session.createReceiver(destination, filter);\n TextMessage m = (TextMessage) receiver.receive();\n System.out.println(\"Received message = \" + m.getText() + \" timestamp=\" + m.getJMSTimestamp());\n\n System.out.println(\"End listen \" + getQueueName() + \" \" + correlationId +\" Queue from receivemessage\");\n\n session.close();\n connection.close();\n\n } catch (JMSException ex) {\n System.out.println(\"Error = \" + ex.getMessage());\n }\n}\n\npublic static void main(String args[]) {\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId1 = getCorrelationId();\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId2 = getCorrelationId();\n HelloProducerConsumer.sendMessage(getQueueName());\n String correlationId3 = getCorrelationId();\n\n\n HelloProducerConsumer.receivemessage(correlationId2);\n\n HelloProducerConsumer.receivemessage(correlationId1);\n\n HelloProducerConsumer.receivemessage(correlationId3);\n}\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231627/"
]
| How can I instantiate a JMS queue listener in java (JRE /JDK / J2EE 1.4) that only receives messages that match a given JMSCorrelationID? The messages that I'm looking to pick up have been published to a queue and not a topic, although that can change if needed.
Here's the code that I'm currently using to put the message in the queue:
```
/**
* publishResponseToQueue publishes Requests to the Queue.
*
* @param jmsQueueFactory -Name of the queue-connection-factory
* @param jmsQueue -The queue name for the request
* @param response -A response object that needs to be published
*
* @throws ServiceLocatorException -An exception if a request message
* could not be published to the Topic
*/
private void publishResponseToQueue( String jmsQueueFactory,
String jmsQueue,
Response response )
throws ServiceLocatorException {
if ( logger.isInfoEnabled() ) {
logger.info( "Begin publishRequestToQueue: " +
jmsQueueFactory + "," + jmsQueue + "," + response );
}
logger.assertLog( jmsQueue != null && !jmsQueue.equals(""),
"jmsQueue cannot be null" );
logger.assertLog( jmsQueueFactory != null && !jmsQueueFactory.equals(""),
"jmsQueueFactory cannot be null" );
logger.assertLog( response != null, "Request cannot be null" );
try {
Queue queue = (Queue)_context.lookup( jmsQueue );
QueueConnectionFactory factory = (QueueConnectionFactory)
_context.lookup( jmsQueueFactory );
QueueConnection connection = factory.createQueueConnection();
connection.start();
QueueSession session = connection.createQueueSession( false,
QueueSession.AUTO_ACKNOWLEDGE );
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setJMSCorrelationID(response.getID());
objectMessage.setObject( response );
session.createSender( queue ).send( objectMessage );
session.close();
connection.close();
} catch ( Exception e ) {
//XC3.2 Added/Modified BEGIN
logger.error( "ServiceLocator.publishResponseToQueue - Could not publish the " +
"Response to the Queue - " + e.getMessage() );
throw new ServiceLocatorException( "ServiceLocator.publishResponseToQueue " +
"- Could not publish the " +
"Response to the Queue - " + e.getMessage() );
//XC3.2 Added/Modified END
}
if ( logger.isInfoEnabled() ) {
logger.info( "End publishResponseToQueue: " +
jmsQueueFactory + "," + jmsQueue + response );
}
} // end of publishResponseToQueue method
``` | The queue connection setup is the same, but once you have the QueueSession, you set the selector when creating a receiver.
```
QueueReceiver receiver = session.createReceiver(myQueue, "JMSCorrelationID='theid'");
```
then
```
receiver.receive()
```
or
```
receiver.setListener(myListener);
``` |
149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| [
{
"answer_id": 149067,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets, and than overriding the save method to copy the slug from the tile, and potentially slugifying it...</p>\n"
},
{
"answer_id": 149176,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 0,
"selected": false,
"text": "<p>This <a href=\"http://www.djangosnippets.org/snippets/937/\" rel=\"nofollow noreferrer\">Django Snippet</a> does what you want by defining a custom Read-Only Widget. So you define a custom editor for the field which in fact doesn't allow any editing.</p>\n"
},
{
"answer_id": 149295,
"author": "Dmitry Shevchenko",
"author_id": 7437,
"author_profile": "https://Stackoverflow.com/users/7437",
"pm_score": 3,
"selected": true,
"text": "<p>For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.</p>\n\n<p>Consider this example:</p>\n\n<pre><code>def save(self):\n from django.template.defaultfilters import slugify\n\n if not self.slug:\n self.slug = slugify(self.title)\n\n super(Your_Model_Name,self).save()\n</code></pre>\n"
},
{
"answer_id": 150229,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.djangosnippets.org/snippets/770/\" rel=\"nofollow noreferrer\">This snippet</a> gives you an AutoSlugField with exactly the behavior you are seeking, and adding it to your model is a one-liner.</p>\n"
},
{
"answer_id": 150296,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to overriding <code>save</code> to provide the generated value you want, you can also use the <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#exclude\" rel=\"nofollow noreferrer\">exclude</a> option in your <code>ModelAdmin</code> class to prevent the field from being displayed in the admin:</p>\n\n<pre><code>class EntryAdmin(admin.ModelAdmin):\n exclude = ('slug',)\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
]
| Assume the following:
*models.py*
```
class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
```
*admin.py*
```
class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
```
I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).
Thoughts? | For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.
Consider this example:
```
def save(self):
from django.template.defaultfilters import slugify
if not self.slug:
self.slug = slugify(self.title)
super(Your_Model_Name,self).save()
``` |
149,055 | <p>I would like to format a price in JavaScript. I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p>
<pre><code>"$ 2,500.00"
</code></pre>
<p>How can I do this?</p>
| [
{
"answer_id": 149080,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 5,
"selected": false,
"text": "<p>The main part is inserting the thousand-separators, and that could be done like this:</p>\n<pre><code><script type="text/javascript">\n function ins1000Sep(val) {\n val = val.split(".");\n val[0] = val[0].split("").reverse().join("");\n val[0] = val[0].replace(/(\\d{3})/g, "$1,");\n val[0] = val[0].split("").reverse().join("");\n val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];\n return val.join(".");\n }\n\n function rem1000Sep(val) {\n return val.replace(/,/g, "");\n }\n\n function formatNum(val) {\n val = Math.round(val*100)/100;\n val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";\n var dec = val.indexOf(".");\n return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);\n }\n</script>\n\n<button onclick="alert(ins1000Sep(formatNum(12313231)));">\n</code></pre>\n"
},
{
"answer_id": 149099,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 11,
"selected": false,
"text": "<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed\" rel=\"noreferrer\">Number.prototype.toFixed</a></h2>\n<p>This solution is compatible with every single major browser:</p>\n<pre><code> const profits = 2489.8237;\n\n profits.toFixed(3) // Returns 2489.824 (rounds up)\n profits.toFixed(2) // Returns 2489.82\n profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)\n</code></pre>\n<p>All you need is to add the currency symbol (e.g. <code>"$" + profits.toFixed(2)</code>) and you will have your amount in dollars.</p>\n<h2>Custom function</h2>\n<p>If you require the use of <code>,</code> between each digit, you can use this function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function formatMoney(number, decPlaces, decSep, thouSep) {\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,\n decSep = typeof decSep === \"undefined\" ? \".\" : decSep;\n thouSep = typeof thouSep === \"undefined\" ? \",\" : thouSep;\n var sign = number < 0 ? \"-\" : \"\";\n var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));\n var j = (j = i.length) > 3 ? j % 3 : 0;\n\n return sign +\n (j ? i.substr(0, j) + thouSep : \"\") +\n i.substr(j).replace(/(\\decSep{3})(?=\\decSep)/g, \"$1\" + thouSep) +\n (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : \"\");\n}\n\ndocument.getElementById(\"b\").addEventListener(\"click\", event => {\n document.getElementById(\"x\").innerText = \"Result was: \" + formatMoney(document.getElementById(\"d\").value);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><label>Insert your amount: <input id=\"d\" type=\"text\" placeholder=\"Cash amount\" /></label>\n<br />\n<button id=\"b\">Get Output</button>\n<p id=\"x\">(press button to get output)</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Use it like so:</p>\n<pre><code>(123456789.12345).formatMoney(2, ".", ",");\n</code></pre>\n<p>If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.</p>\n<pre><code>(123456789.12345).formatMoney(2);\n</code></pre>\n<p>If your culture has the two symbols flipped (i.e., Europeans) and you would like to use the defaults, just paste over the following two lines in the <code>formatMoney</code> method:</p>\n<pre><code> d = d == undefined ? "," : d,\n t = t == undefined ? "." : t,\n</code></pre>\n<h2>Custom function (ES6)</h2>\n<p>If you can use modern ECMAScript syntax (i.e., through Babel), you can use this simpler function instead:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function formatMoney(amount, decimalCount = 2, decimal = \".\", thousands = \",\") {\n try {\n decimalCount = Math.abs(decimalCount);\n decimalCount = isNaN(decimalCount) ? 2 : decimalCount;\n\n const negativeSign = amount < 0 ? \"-\" : \"\";\n\n let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();\n let j = (i.length > 3) ? i.length % 3 : 0;\n\n return\n negativeSign +\n (j ? i.substr(0, j) + thousands : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, \"$1\" + thousands) +\n (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : \"\");\n } catch (e) {\n console.log(e)\n }\n};\n\ndocument.getElementById(\"b\").addEventListener(\"click\", event => {\n document.getElementById(\"x\").innerText = \"Result was: \" + formatMoney(document.getElementById(\"d\").value);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><label>Insert your amount: <input id=\"d\" type=\"text\" placeholder=\"Cash amount\" /></label>\n<br />\n<button id=\"b\">Get Output</button>\n<p id=\"x\">(press button to get output)</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 149107,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 8,
"selected": false,
"text": "<p>Take a look at the JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"noreferrer\">Number</a> object and see if it can help you.</p>\n<ul>\n<li><code>toLocaleString()</code> will format a number using location specific thousands separator.</li>\n<li><code>toFixed()</code> will round the number to a specific number of decimal places.</li>\n</ul>\n<p>To use these at the same time the value must have its type changed back to a number because they both output a string.</p>\n<p>Example:</p>\n<pre><code>Number((someNumber).toFixed(1)).toLocaleString()\n</code></pre>\n<p><strong>EDIT</strong></p>\n<p>One can just use toLocaleString directly and its not necessary to recast to a number:</p>\n<pre><code>someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\n</code></pre>\n<h4>Multiple numbers</h4>\n<p>If you need to frequently format numbers similarly you can create a specific object for reuse. Like for German (Switzerland):</p>\n<pre><code>const money = new Intl.NumberFormat('de-CH',\n { style:'currency', currency: 'CHF' });\nconst percent = new Intl.NumberFormat('de-CH',\n { style:'percent', maximumFractionDigits: 1, signDisplay: "always"});\n</code></pre>\n<p>which than can be used as:</p>\n<pre><code>money.format(1234.50); // output CHF 1'234.50\npercent.format(0.083); // output +8.3%\n</code></pre>\n<p>Pretty nifty.</p>\n"
},
{
"answer_id": 149120,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function CurrencyFormatted(amount)\n{\n var i = parseFloat(amount);\n if(isNaN(i)) { i = 0.00; }\n var minus = '';\n if(i < 0) { minus = '-'; }\n i = Math.abs(i);\n i = parseInt((i + .005) * 100);\n i = i / 100;\n s = new String(i);\n if(s.indexOf('.') < 0) { s += '.00'; }\n if(s.indexOf('.') == (s.length - 2)) { s += '0'; }\n s = minus + s;\n return s;\n}\n</code></pre>\n\n<p>From <a href=\"http://www.willmaster.com/library/tutorials/currency-formatting-and-putting-commas-in-numbers-with-javascript-and-perl.php\" rel=\"noreferrer\">WillMaster</a>.</p>\n"
},
{
"answer_id": 149126,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"https://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"nofollow noreferrer\">YUI</a> codebase uses the following formatting:</p>\n<pre><code>format: function(nData, oConfig) {\n oConfig = oConfig || {};\n\n if(!YAHOO.lang.isNumber(nData)) {\n nData *= 1;\n }\n\n if(YAHOO.lang.isNumber(nData)) {\n var sOutput = nData + "";\n var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";\n var nDotIndex;\n\n // Manage decimals\n if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) {\n // Round to the correct decimal place\n var nDecimalPlaces = oConfig.decimalPlaces;\n var nDecimal = Math.pow(10, nDecimalPlaces);\n sOutput = Math.round(nData*nDecimal)/nDecimal + "";\n nDotIndex = sOutput.lastIndexOf(".");\n\n if(nDecimalPlaces > 0) {\n // Add the decimal separator\n if(nDotIndex < 0) {\n sOutput += sDecimalSeparator;\n nDotIndex = sOutput.length-1;\n }\n // Replace the "."\n else if(sDecimalSeparator !== "."){\n sOutput = sOutput.replace(".",sDecimalSeparator);\n }\n // Add missing zeros\n while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {\n sOutput += "0";\n }\n }\n }\n\n // Add the thousands separator\n if(oConfig.thousandsSeparator) {\n var sThousandsSeparator = oConfig.thousandsSeparator;\n nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);\n nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;\n var sNewOutput = sOutput.substring(nDotIndex);\n var nCount = -1;\n for (var i=nDotIndex; i>0; i--) {\n nCount++;\n if ((nCount%3 === 0) && (i !== nDotIndex)) {\n sNewOutput = sThousandsSeparator + sNewOutput;\n }\n sNewOutput = sOutput.charAt(i-1) + sNewOutput;\n }\n sOutput = sNewOutput;\n }\n\n // Prepend prefix\n sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;\n\n // Append suffix\n sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;\n\n return sOutput;\n }\n // Still not a number. Just return it unaltered\n else {\n return nData;\n }\n}\n</code></pre>\n<p>It would need editing as the YUI library is configurable, like replacing oConfig.decimalSeparator with ".".</p>\n"
},
{
"answer_id": 149150,
"author": "Daniel Magliola",
"author_id": 3314,
"author_profile": "https://Stackoverflow.com/users/3314",
"pm_score": 6,
"selected": true,
"text": "<p>Ok, based on what you said, I'm using this:</p>\n<pre><code>var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);\n\nvar AmountWithCommas = Amount.toLocaleString();\nvar arParts = String(AmountWithCommas).split(DecimalSeparator);\nvar intPart = arParts[0];\nvar decPart = (arParts.length > 1 ? arParts[1] : '');\ndecPart = (decPart + '00').substr(0,2);\n\nreturn '£ ' + intPart + DecimalSeparator + decPart;\n</code></pre>\n<p>I'm open to improvement suggestions (I'd prefer not to include <a href=\"https://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"nofollow noreferrer\">YUI</a> just to do this :-) )</p>\n<p>I already know I should be detecting the "." instead of just using it as the decimal separator...</p>\n"
},
{
"answer_id": 149371,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 3,
"selected": false,
"text": "<p>A minimalistic approach that just meets the original requirements:</p>\n<pre><code>function formatMoney(n) {\n return "$ " + (Math.round(n * 100) / 100).toLocaleString();\n}\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings#comment43766_149371\">@Daniel Magliola</a>: You're right. The above was a hasty, incomplete implementation. Here's the corrected implementation:</p>\n<pre><code>function formatMoney(n) {\n return "$ " + n.toLocaleString().split(".")[0] + "."\n + n.toFixed(2).split(".")[1];\n}\n</code></pre>\n"
},
{
"answer_id": 1323064,
"author": "DaMayan",
"author_id": 162092,
"author_profile": "https://Stackoverflow.com/users/162092",
"pm_score": 5,
"selected": false,
"text": "<p>There is a JavaScript port of the PHP function "number_format".</p>\n<p>I find it very useful as it is easy to use and recognisable for PHP developers.</p>\n<pre><code>function number_format (number, decimals, dec_point, thousands_sep) {\n var n = number, prec = decimals;\n\n var toFixedFix = function (n,prec) {\n var k = Math.pow(10,prec);\n return (Math.round(n*k)/k).toString();\n };\n\n n = !isFinite(+n) ? 0 : +n;\n prec = !isFinite(+prec) ? 0 : Math.abs(prec);\n var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;\n var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;\n\n var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);\n // Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0;\n\n var abs = toFixedFix(Math.abs(n), prec);\n var _, i;\n\n if (abs >= 1000) {\n _ = abs.split(/\\D/);\n i = _[0].length % 3 || 3;\n\n _[0] = s.slice(0,i + (n < 0)) +\n _[0].slice(i).replace(/(\\d{3})/g, sep+'$1');\n s = _.join(dec);\n } else {\n s = s.replace('.', dec);\n }\n\n var decPos = s.indexOf(dec);\n if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {\n s += new Array(prec-(s.length-decPos-1)).join(0)+'0';\n }\n else if (prec >= 1 && decPos === -1) {\n s += dec+new Array(prec).join(0)+'0';\n }\n return s;\n}\n</code></pre>\n<p>(Comment block from <a href=\"http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/\" rel=\"nofollow noreferrer\">the original</a>, included below for examples & credit where due)</p>\n<pre><code>// Formats a number with grouped thousands\n//\n// version: 906.1806\n// discuss at: http://phpjs.org/functions/number_format\n// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n// + bugfix by: Michael White (http://getsprink.com)\n// + bugfix by: Benjamin Lupton\n// + bugfix by: Allan Jensen (http://www.winternet.no)\n// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n// + bugfix by: Howard Yeend\n// + revised by: Luke Smith (http://lucassmith.name)\n// + bugfix by: Diogo Resende\n// + bugfix by: Rival\n// + input by: Kheang Hok Chin (http://www.distantia.ca/)\n// + improved by: davook\n// + improved by: Brett Zamir (http://brett-zamir.me)\n// + input by: Jay Klehr\n// + improved by: Brett Zamir (http://brett-zamir.me)\n// + input by: Amir Habibi (http://www.residence-mixte.com/)\n// + bugfix by: Brett Zamir (http://brett-zamir.me)\n// * example 1: number_format(1234.56);\n// * returns 1: '1,235'\n// * example 2: number_format(1234.56, 2, ',', ' ');\n// * returns 2: '1 234,56'\n// * example 3: number_format(1234.5678, 2, '.', '');\n// * returns 3: '1234.57'\n// * example 4: number_format(67, 2, ',', '.');\n// * returns 4: '67,00'\n// * example 5: number_format(1000);\n// * returns 5: '1,000'\n// * example 6: number_format(67.311, 2);\n// * returns 6: '67.31'\n// * example 7: number_format(1000.55, 1);\n// * returns 7: '1,000.6'\n// * example 8: number_format(67000, 5, ',', '.');\n// * returns 8: '67.000,00000'\n// * example 9: number_format(0.9, 0);\n// * returns 9: '1'\n// * example 10: number_format('1.20', 2);\n// * returns 10: '1.20'\n// * example 11: number_format('1.20', 4);\n// * returns 11: '1.2000'\n// * example 12: number_format('1.2000', 3);\n// * returns 12: '1.200'\n</code></pre>\n"
},
{
"answer_id": 2866613,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 7,
"selected": false,
"text": "<p>Below is the <a href=\"https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript/149099#149099\">Patrick Desjardins (alias Daok)</a> code with a bit of comments added and some minor changes:</p>\n<pre><code>/*\ndecimal_sep: character used as decimal separator, it defaults to '.' when omitted\nthousands_sep: char used as thousands separator, it defaults to ',' when omitted\n*/\nNumber.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)\n{\n var n = this,\n c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal\n d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)\n\n /*\n According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]\n the fastest way to check for not defined parameter is to use typeof value === 'undefined'\n rather than doing value === undefined.\n */\n t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value\n\n sign = (n < 0) ? '-' : '',\n\n // Extracting the absolute value of the integer part of the number and converting to string\n i = parseInt(n = Math.abs(n).toFixed(c)) + '',\n\n j = ((j = i.length) > 3) ? j % 3 : 0;\n return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\\d{3})(?=\\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n}\n</code></pre>\n<p>And here some tests:</p>\n<pre><code>// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)\nalert(123456789.67392.toMoney() + '\\n' + 123456789.67392.toMoney(3) + '\\n' + 123456789.67392.toMoney(0) + '\\n' + (123456).toMoney() + '\\n' + (123456).toMoney(0) + '\\n' + 89.67392.toMoney() + '\\n' + (89).toMoney());\n\n// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)\nalert((-123456789.67392).toMoney() + '\\n' + (-123456789.67392).toMoney(-3));\n</code></pre>\n<p>The minor changes are:</p>\n<ol>\n<li><p>moved a bit the <code>Math.abs(decimals)</code> to be done only when is not <code>NaN</code>.</p>\n</li>\n<li><p><code>decimal_sep</code> can not be empty string any more (a some sort of decimal separator is a <em>must</em>)</p>\n</li>\n<li><p>we use <code>typeof thousands_sep === 'undefined'</code> as suggested in <a href=\"https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function\">How best to determine if an argument is not sent to the JavaScript function</a></p>\n</li>\n<li><p><code>(+n || 0)</code> is not needed because <code>this</code> is a <code>Number</code> object</p>\n</li>\n</ol>\n<p><a href=\"https://jsfiddle.net/9kvrndfu/\" rel=\"nofollow noreferrer\">JSFiddle</a></p>\n"
},
{
"answer_id": 2919971,
"author": "Richard Parnaby-King",
"author_id": 351785,
"author_profile": "https://Stackoverflow.com/users/351785",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function getMoney(A){\n var a = new Number(A);\n var b = a.toFixed(2); // Get 12345678.90\n a = parseInt(a); // Get 12345678\n b = (b-a).toPrecision(2); // Get 0.90\n b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00\n a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00\n // If Internet Explorer (our number ends in .00)\n if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))\n {\n a = a.substr(0, a.length-3); // Delete the .00\n }\n return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90\n}\nalert(getMoney(12345678.9));\n</code></pre>\n<p>This works in Firefox and Internet Explorer.</p>\n"
},
{
"answer_id": 3284302,
"author": "Miller Medeiros",
"author_id": 278435,
"author_profile": "https://Stackoverflow.com/users/278435",
"pm_score": 4,
"selected": false,
"text": "<p>As usually, there are multiple ways of doing the same thing, but I would avoid using <code>Number.prototype.toLocaleString</code> since it can return different values based on the user settings.</p>\n<p>I also don't recommend extending the <code>Number.prototype</code> - extending native objects prototypes is a bad practice since it can cause conflicts with other people code (e.g. libraries/frameworks/plugins) and may not be compatible with future JavaScript implementations/versions.</p>\n<p>I believe that regular expressions are the best approach for the problem, here is my implementation:</p>\n<pre><code>/**\n * Converts number into currency format\n * @param {number} number Number that should be converted.\n * @param {string} [decimalSeparator] Decimal separator, defaults to '.'.\n * @param {string} [thousandsSeparator] Thousands separator, defaults to ','.\n * @param {int} [nDecimalDigits] Number of decimal digits, defaults to `2`.\n * @return {string} Formatted string (e.g. numberToCurrency(12345.67) returns '12,345.67')\n */\nfunction numberToCurrency(number, decimalSeparator, thousandsSeparator, nDecimalDigits){\n //default values\n decimalSeparator = decimalSeparator || '.';\n thousandsSeparator = thousandsSeparator || ',';\n nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits;\n\n var fixed = number.toFixed(nDecimalDigits), //limit/add decimal digits\n parts = new RegExp('^(-?\\\\d{1,3})((?:\\\\d{3})+)(\\\\.(\\\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); //separate begin [$1], middle [$2] and decimal digits [$4]\n\n if(parts){ //number >= 1000 || number <= -1000\n return parts[1] + parts[2].replace(/\\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');\n }else{\n return fixed.replace('.', decimalSeparator);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5342097,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 6,
"selected": false,
"text": "<p>Here's another attempt, just for fun:</p>\n<pre><code>function formatDollar(num) {\n var p = num.toFixed(2).split(".");\n return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {\n return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;\n }, "") + "." + p[1];\n}\n</code></pre>\n<p>And some tests:</p>\n<pre><code>formatDollar(45664544.23423) // "$45,664,544.23"\nformatDollar(45) // "$45.00"\nformatDollar(123) // "$123.00"\nformatDollar(7824) // "$7,824.00"\nformatDollar(1) // "$1.00"\nformatDollar(-1345) // "$-1,345.00\nformatDollar(-3) // "$-3.00"\n</code></pre>\n"
},
{
"answer_id": 5681208,
"author": "jc00ke",
"author_id": 710404,
"author_profile": "https://Stackoverflow.com/users/710404",
"pm_score": 3,
"selected": false,
"text": "<p>Patrick Desjardins (ex Daok)'s example worked well for me. I ported it over to CoffeeScript if anyone is interested.</p>\n<pre><code>Number.prototype.toMoney = (decimals = 2, decimal_separator = ".", thousands_separator = ",") ->\n n = this\n c = if isNaN(decimals) then 2 else Math.abs decimals\n sign = if n < 0 then "-" else ""\n i = parseInt(n = Math.abs(n).toFixed(c)) + ''\n j = if (j = i.length) > 3 then j % 3 else 0\n x = if j then i.substr(0, j) + thousands_separator else ''\n y = i.substr(j).replace(/(\\d{3})(?=\\d)/g, "$1" + thousands_separator)\n z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else ''\n sign + x + y + z\n</code></pre>\n"
},
{
"answer_id": 5969458,
"author": "Daniel Fernandez",
"author_id": 749340,
"author_profile": "https://Stackoverflow.com/users/749340",
"pm_score": 2,
"selected": false,
"text": "<p>This might work:</p>\n\n<pre><code>function format_currency(v, number_of_decimals, decimal_separator, currency_sign){\n return (isNaN(v)? v : currency_sign + parseInt(v||0).toLocaleString() + decimal_separator + (v*1).toFixed(number_of_decimals).slice(-number_of_decimals));\n}\n</code></pre>\n\n<p>No loops, no regexes, no arrays, no exotic conditionals.</p>\n"
},
{
"answer_id": 6715476,
"author": "Goodeq",
"author_id": 645710,
"author_profile": "https://Stackoverflow.com/users/645710",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://github.com/Mottie/javascript-number-formatter\" rel=\"nofollow noreferrer\">javascript-number-formatter</a> (formerly <a href=\"https://code.google.com/archive/p/javascript-number-formatter/\" rel=\"nofollow noreferrer\">at Google Code</a>)</p>\n<ul>\n<li>Short, fast, flexible yet stand-alone.</li>\n<li>Accept standard number formatting like <code>#,##0.00</code> or with negation <code>-000.####</code>.</li>\n<li>Accept any country format like <code># ##0,00</code>, <code>#,###.##</code>, <code>#'###.##</code> or any type of non-numbering symbol.</li>\n<li>Accept any numbers of digit grouping. <code>#,##,#0.000</code> or <code>#,###0.##</code> are all valid.</li>\n<li>Accept any redundant/foolproof formatting. <code>##,###,##.#</code> or <code>0#,#00#.###0#</code> are all OK.</li>\n<li>Auto number rounding.</li>\n<li>Simple interface, just supply mask & value like this: <code>format( "0.0000", 3.141592)</code>.</li>\n<li>Include a prefix & suffix with the mask</li>\n</ul>\n<p>(excerpt from its README)</p>\n"
},
{
"answer_id": 6787083,
"author": "daveoncode",
"author_id": 267719,
"author_profile": "https://Stackoverflow.com/users/267719",
"pm_score": 5,
"selected": false,
"text": "<p>I use the library <a href=\"https://github.com/jquery/globalize\" rel=\"nofollow noreferrer\">Globalize</a> (from Microsoft): </p>\n\n<p>It's a great project to localize numbers, currencies and dates and to have them automatically formatted the right way according to the user locale! ...and despite it should be a jQuery extension, it's currently a 100% independent library. I suggest you all to try it out! :)</p>\n"
},
{
"answer_id": 7266497,
"author": "GasheK",
"author_id": 362508,
"author_profile": "https://Stackoverflow.com/users/362508",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://openexchangerates.github.io/accounting.js/\" rel=\"noreferrer\">accounting.js</a> is a tiny JavaScript library for number, money and currency formatting.</p>\n"
},
{
"answer_id": 8313159,
"author": "Julien de Prabère",
"author_id": 1071570,
"author_profile": "https://Stackoverflow.com/users/1071570",
"pm_score": 2,
"selected": false,
"text": "<p>A quicker way with regexp:</p>\n<pre><code>Number.prototype.toMonetaryString = function() {\n var n = this.toFixed(2), m;\n //var = this.toFixed(2).replace(/\\./, ','); For comma separator\n // with a space for thousands separator\n while ((m = n.replace(/(\\d)(\\d\\d\\d)\\b/g, '$1 $2')) != n)\n n = m;\n return m;\n}\n\nString.prototype.fromMonetaryToNumber = function(s) {\n return this.replace(/[^\\d-]+/g, '')/100;\n}\n</code></pre>\n"
},
{
"answer_id": 8363954,
"author": "troy",
"author_id": 1078380,
"author_profile": "https://Stackoverflow.com/users/1078380",
"pm_score": 3,
"selected": false,
"text": "<p>A simple option for proper comma placement by reversing the string first and basic regexp.</p>\n\n<pre><code>String.prototype.reverse = function() {\n return this.split('').reverse().join('');\n};\n\nNumber.prototype.toCurrency = function( round_decimal /*boolean*/ ) { \n // format decimal or round to nearest integer\n var n = this.toFixed( round_decimal ? 0 : 2 );\n\n // convert to a string, add commas every 3 digits from left to right \n // by reversing string\n return (n + '').reverse().replace( /(\\d{3})(?=\\d)/g, '$1,' ).reverse();\n};\n</code></pre>\n"
},
{
"answer_id": 8726353,
"author": "Julien de Prabère",
"author_id": 1071607,
"author_profile": "https://Stackoverflow.com/users/1071607",
"pm_score": 5,
"selected": false,
"text": "<p>A shorter method (for inserting space, comma or point) with a regular expression:</p>\n<pre><code> Number.prototype.toCurrencyString = function(){\n return this.toFixed(2).replace(/(\\d)(?=(\\d{3})+\\b)/g, '$1 ');\n }\n\n n = 12345678.9;\n alert(n.toCurrencyString());\n</code></pre>\n"
},
{
"answer_id": 9318703,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<p>There is no equivalent of \"formatNumber\" in JavaScript. You can write it yourself or find a library that already does this.</p>\n"
},
{
"answer_id": 9318723,
"author": "crush",
"author_id": 1195273,
"author_profile": "https://Stackoverflow.com/users/1195273",
"pm_score": 6,
"selected": false,
"text": "<p>I think you want:</p>\n<pre><code>f.nettotal.value = "$" + showValue.toFixed(2);\n</code></pre>\n"
},
{
"answer_id": 9318724,
"author": "Jonathan M",
"author_id": 751484,
"author_profile": "https://Stackoverflow.com/users/751484",
"pm_score": 7,
"selected": false,
"text": "<p>Here's the best JavaScript money formatter I've seen:</p>\n<pre><code>Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {\n var n = this,\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,\n decSeparator = decSeparator == undefined ? "." : decSeparator,\n thouSeparator = thouSeparator == undefined ? "," : thouSeparator,\n sign = n < 0 ? "-" : "",\n i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",\n j = (j = i.length) > 3 ? j % 3 : 0;\n return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");\n};\n</code></pre>\n<p>It was reformatted and borrowed from here: <em><a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/149099#149099\">How to format numbers as currency strings</a></em></p>\n<p>You'll have to supply your own currency designator (you used <code>$</code> above).</p>\n<p>Call it like this (although note that the arguments default to 2, comma, and period, so you don't need to supply any arguments if that's your preference):</p>\n<pre><code>var myMoney = 3543.75873;\nvar formattedMoney = '$' + myMoney.formatMoney(2, ',', '.'); // "$3,543.76"\n</code></pre>\n"
},
{
"answer_id": 9327950,
"author": "Gate",
"author_id": 656293,
"author_profile": "https://Stackoverflow.com/users/656293",
"pm_score": 4,
"selected": false,
"text": "<p>There is a built-in function, <a href=\"http://www.w3schools.com/jsref/jsref_tofixed.asp\" rel=\"nofollow noreferrer\">toFixed</a>, in JavaScript:</p>\n<pre><code>var num = new Number(349);\ndocument.write("$" + num.toFixed(2));\n</code></pre>\n"
},
{
"answer_id": 10168573,
"author": "Tim Saylor",
"author_id": 155987,
"author_profile": "https://Stackoverflow.com/users/155987",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/149099/155987\">Patrick Desjardins</a>' answer looks good, but I prefer my JavaScript code simple. Here's a function I just wrote to take a number in and return it in currency format (minus the dollar sign):</p>\n<pre><code>// Format numbers to two decimals with commas\nfunction formatDollar(num) {\n var p = num.toFixed(2).split(".");\n var chars = p[0].split("").reverse();\n var newstr = '';\n var count = 0;\n for (x in chars) {\n count++;\n if(count%3 == 1 && count != 1) {\n newstr = chars[x] + ',' + newstr;\n } else {\n newstr = chars[x] + newstr;\n }\n }\n return newstr + "." + p[1];\n}\n</code></pre>\n"
},
{
"answer_id": 11264443,
"author": "Ebubekir Dirican",
"author_id": 869571,
"author_profile": "https://Stackoverflow.com/users/869571",
"pm_score": 2,
"selected": false,
"text": "<pre><code>String.prototype.toPrice = function () {\n var v;\n if (/^\\d+(,\\d+)$/.test(this))\n v = this.replace(/,/, '.');\n else if (/^\\d+((,\\d{3})*(\\.\\d+)?)?$/.test(this))\n v = this.replace(/,/g, \"\");\n else if (/^\\d+((.\\d{3})*(,\\d+)?)?$/.test(this))\n v = this.replace(/\\./g, \"\").replace(/,/, \".\");\n var x = parseFloat(v).toFixed(2).toString().split(\".\"),\n x1 = x[0],\n x2 = ((x.length == 2) ? \".\" + x[1] : \".00\"),\n exp = /^([0-9]+)(\\d{3})/;\n while (exp.test(x1))\n x1 = x1.replace(exp, \"$1\" + \",\" + \"$2\");\n return x1 + x2;\n}\n\nalert(\"123123\".toPrice()); //123,123.00\nalert(\"123123,316\".toPrice()); //123,123.32\nalert(\"12,312,313.33213\".toPrice()); //12,312,313.33\nalert(\"123.312.321,32132\".toPrice()); //123,312,321.32\n</code></pre>\n"
},
{
"answer_id": 11270819,
"author": "XML",
"author_id": 800457,
"author_profile": "https://Stackoverflow.com/users/800457",
"pm_score": 5,
"selected": false,
"text": "<p>+1 to <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/9318724#9318724\">Jonathan M for providing the original method</a>. Since this is explicitly a currency formatter, I went ahead and added the currency symbol (defaults to '$') to the output, and added a default comma as the thousands separator. If you don't actually want a currency symbol (or thousands separator), just use "" (empty string) as your argument for it.</p>\n<pre><code>Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {\n // check the args and supply defaults:\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\n decSeparator = decSeparator == undefined ? "." : decSeparator;\n thouSeparator = thouSeparator == undefined ? "," : thouSeparator;\n currencySymbol = currencySymbol == undefined ? "$" : currencySymbol;\n\n var n = this,\n sign = n < 0 ? "-" : "",\n i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",\n j = (j = i.length) > 3 ? j % 3 : 0;\n\n return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");\n};\n</code></pre>\n"
},
{
"answer_id": 11335085,
"author": "DanielEli",
"author_id": 273163,
"author_profile": "https://Stackoverflow.com/users/273163",
"pm_score": 2,
"selected": false,
"text": "<p>CoffeeScript for <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/149099#149099\">Patrick's popular answer</a>:</p>\n<pre><code>Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->\n n = this\n c = decimalPlaces\n d = decimalChar\n t = thousandsChar\n c = (if isNaN(c = Math.abs(c)) then 2 else c)\n d = (if d is undefined then "." else d)\n t = (if t is undefined then "," else t)\n s = (if n < 0 then "-" else "")\n i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + ""\n j = (if (j = i.length) > 3 then j % 3 else 0)\n s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\\d{3})(?=\\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "")\n</code></pre>\n"
},
{
"answer_id": 12698339,
"author": "adamwdraper",
"author_id": 875473,
"author_profile": "https://Stackoverflow.com/users/875473",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://numeraljs.com/\" rel=\"nofollow noreferrer\">Numeral.js</a> - a JavaScript library for easy number formatting by @adamwdraper</p>\n<pre><code>numeral(23456.789).format('$0,0.00'); // = "$23,456.79"\n</code></pre>\n"
},
{
"answer_id": 12698442,
"author": "juanOS",
"author_id": 1357423,
"author_profile": "https://Stackoverflow.com/users/1357423",
"pm_score": 4,
"selected": false,
"text": "<p>I suggest the NumberFormat class from <a href=\"https://developers.google.com/chart/interactive/docs/reference#numberformatter\" rel=\"nofollow noreferrer\">Google Visualization API</a>.</p>\n<p>You can do something like this:</p>\n<pre><code>var formatter = new google.visualization.NumberFormat({\n prefix: '$',\n pattern: '#,###,###.##'\n});\n\nformatter.formatValue(1000000); // $ 1,000,000\n</code></pre>\n"
},
{
"answer_id": 12967079,
"author": "mendezcode",
"author_id": 235571,
"author_profile": "https://Stackoverflow.com/users/235571",
"pm_score": 1,
"selected": false,
"text": "<p>Here's mine...</p>\n\n<pre><code>function thousandCommas(num) {\n num = num.toString().split('.');\n var ints = num[0].split('').reverse();\n for (var out=[],len=ints.length,i=0; i < len; i++) {\n if (i > 0 && (i % 3) === 0) out.push(',');\n out.push(ints[i]);\n }\n out = out.reverse() && out.join('');\n if (num.length === 2) out += '.' + num[1];\n return out;\n}\n</code></pre>\n"
},
{
"answer_id": 14339482,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/javascript-number-formatter/\" rel=\"nofollow noreferrer\">http://code.google.com/p/javascript-number-formatter/</a>:</p>\n<ul>\n<li>Short, fast, flexible yet stand-alone. Only 75 lines including MIT license info, blank lines & comments.</li>\n<li>Accept standard number formatting like #,##0.00 or with negation -000.####.</li>\n<li>Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.</li>\n<li>Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.</li>\n<li>Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.</li>\n<li>Auto number rounding.</li>\n<li>Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)</li>\n</ul>\n<p><strong>UPDATE</strong> This is my home-grown <code>pp</code> utilities for most common tasks:</p>\n<pre><code>var NumUtil = {};\n\n/**\n Petty print 'num' wth exactly 'signif' digits.\n pp(123.45, 2) == "120"\n pp(0.012343, 3) == "0.0123"\n pp(1.2, 3) == "1.20"\n*/\nNumUtil.pp = function(num, signif) {\n if (typeof(num) !== "number")\n throw 'NumUtil.pp: num is not a number!';\n if (isNaN(num))\n throw 'NumUtil.pp: num is NaN!';\n if (num < 1e-15 || num > 1e15)\n return num;\n var r = Math.log(num)/Math.LN10;\n var dot = Math.floor(r) - (signif-1);\n r = r - Math.floor(r) + (signif-1);\n r = Math.round(Math.exp(r * Math.LN10)).toString();\n if (dot >= 0) {\n for (; dot > 0; dot -= 1)\n r += "0";\n return r;\n } else if (-dot >= r.length) {\n var p = "0.";\n for (; -dot > r.length; dot += 1) {\n p += "0";\n }\n return p+r;\n } else {\n return r.substring(0, r.length + dot) + "." + r.substring(r.length + dot);\n }\n}\n\n/** Append leading zeros up to 2 digits. */\nNumUtil.align2 = function(v) {\n if (v < 10)\n return "0"+v;\n return ""+v;\n}\n/** Append leading zeros up to 3 digits. */\nNumUtil.align3 = function(v) {\n if (v < 10)\n return "00"+v;\n else if (v < 100)\n return "0"+v;\n return ""+v;\n}\n\nNumUtil.integer = {};\n\n/** Round to integer and group by 3 digits. */\nNumUtil.integer.pp = function(num) {\n if (typeof(num) !== "number") {\n console.log("%s", new Error().stack);\n throw 'NumUtil.integer.pp: num is not a number!';\n }\n if (isNaN(num))\n throw 'NumUtil.integer.pp: num is NaN!';\n if (num > 1e15)\n return num;\n if (num < 0)\n throw 'Negative num!';\n num = Math.round(num);\n var group = num % 1000;\n var integ = Math.floor(num / 1000);\n if (integ === 0) {\n return group;\n }\n num = NumUtil.align3(group);\n while (true) {\n group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0)\n return group + " " + num;\n num = NumUtil.align3(group) + " " + num;\n }\n return num;\n}\n\nNumUtil.currency = {};\n\n/** Round to coins and group by 3 digits. */\nNumUtil.currency.pp = function(amount) {\n if (typeof(amount) !== "number")\n throw 'NumUtil.currency.pp: amount is not a number!';\n if (isNaN(amount))\n throw 'NumUtil.currency.pp: amount is NaN!';\n if (amount > 1e15)\n return amount;\n if (amount < 0)\n throw 'Negative amount!';\n if (amount < 1e-2)\n return 0;\n var v = Math.round(amount*100);\n var integ = Math.floor(v / 100);\n var frac = NumUtil.align2(v % 100);\n var group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0) {\n return group + "." + frac;\n }\n amount = NumUtil.align3(group);\n while (true) {\n group = integ % 1000;\n integ = Math.floor(integ / 1000);\n if (integ === 0)\n return group + " " + amount + "." + frac;\n amount = NumUtil.align3(group) + " " + amount;\n }\n return amount;\n}\n</code></pre>\n"
},
{
"answer_id": 14428340,
"author": "VisioN",
"author_id": 1249581,
"author_profile": "https://Stackoverflow.com/users/1249581",
"pm_score": 11,
"selected": false,
"text": "<h2>Short and fast solution (works everywhere!)</h2>\n\n<pre><code>(12345.67).toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,'); // 12,345.67\n</code></pre>\n\n<p>The idea behind this solution is replacing matched sections with first match and comma, i.e. <code>'$&,'</code>. The matching is done using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-lookahead\" rel=\"noreferrer\">lookahead approach</a>. You may read the expression as <em>\"match a number if it is followed by a sequence of three number sets (one or more) and a dot\"</em>.</p>\n\n<p><strong>TESTS:</strong></p>\n\n<pre><code>1 --> \"1.00\"\n12 --> \"12.00\"\n123 --> \"123.00\"\n1234 --> \"1,234.00\"\n12345 --> \"12,345.00\"\n123456 --> \"123,456.00\"\n1234567 --> \"1,234,567.00\"\n12345.67 --> \"12,345.67\"\n</code></pre>\n\n<p><strong>DEMO:</strong> <a href=\"http://jsfiddle.net/hAfMM/9571/\" rel=\"noreferrer\">http://jsfiddle.net/hAfMM/9571/</a></p>\n\n<hr>\n\n<h2>Extended short solution</h2>\n\n<p>You can also extend the prototype of <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number\" rel=\"noreferrer\"><code>Number</code></a> object to add additional support of any number of decimals <code>[0 .. n]</code> and the size of number groups <code>[0 .. x]</code>:</p>\n\n<pre><code>/**\n * Number.prototype.format(n, x)\n * \n * @param integer n: length of decimal\n * @param integer x: length of sections\n */\nNumber.prototype.format = function(n, x) {\n var re = '\\\\d(?=(\\\\d{' + (x || 3) + '})+' + (n > 0 ? '\\\\.' : '$') + ')';\n return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');\n};\n\n1234..format(); // \"1,234\"\n12345..format(2); // \"12,345.00\"\n123456.7.format(3, 2); // \"12,34,56.700\"\n123456.789.format(2, 4); // \"12,3456.79\"\n</code></pre>\n\n<p><strong>DEMO / TESTS:</strong> <a href=\"http://jsfiddle.net/hAfMM/435/\" rel=\"noreferrer\">http://jsfiddle.net/hAfMM/435/</a></p>\n\n<hr>\n\n<h2>Super extended short solution</h2>\n\n<p>In this <a href=\"https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript/14428340#comment34151293_14428340\">super extended version</a> you may set different delimiter types:</p>\n\n<pre><code>/**\n * Number.prototype.format(n, x, s, c)\n * \n * @param integer n: length of decimal\n * @param integer x: length of whole part\n * @param mixed s: sections delimiter\n * @param mixed c: decimal delimiter\n */\nNumber.prototype.format = function(n, x, s, c) {\n var re = '\\\\d(?=(\\\\d{' + (x || 3) + '})+' + (n > 0 ? '\\\\D' : '$') + ')',\n num = this.toFixed(Math.max(0, ~~n));\n\n return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));\n};\n\n12345678.9.format(2, 3, '.', ','); // \"12.345.678,90\"\n123456.789.format(4, 4, ' ', ':'); // \"12 3456:7890\"\n12345678.9.format(0, 3, '-'); // \"12-345-679\"\n</code></pre>\n\n<p><strong>DEMO / TESTS:</strong> <a href=\"http://jsfiddle.net/hAfMM/612/\" rel=\"noreferrer\">http://jsfiddle.net/hAfMM/612/</a></p>\n"
},
{
"answer_id": 14576179,
"author": "Kirk Bentley",
"author_id": 295694,
"author_profile": "https://Stackoverflow.com/users/295694",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a mootools 1.2 implementation from the code provided by XMLilley...</p>\n\n<pre><code>Number.implement('format', function(decPlaces, thouSeparator, decSeparator){\ndecPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\ndecSeparator = decSeparator === undefined ? '.' : decSeparator;\nthouSeparator = thouSeparator === undefined ? ',' : thouSeparator;\n\nvar num = this,\n sign = num < 0 ? '-' : '',\n i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + '',\n j = (j = i.length) > 3 ? j % 3 : 0;\n\nreturn sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : '');\n});\n</code></pre>\n"
},
{
"answer_id": 14735423,
"author": "Jay Dansand",
"author_id": 198299,
"author_profile": "https://Stackoverflow.com/users/198299",
"pm_score": 4,
"selected": false,
"text": "<p>This might be a little late, but here's a method I just worked up for a coworker to add a locale-aware <code>.toCurrencyString()</code> function to all numbers. The internalization is for number grouping only, <em>not</em> the currency sign - if you're outputting dollars, use <code>"$"</code> as supplied, because <code>$123 4567</code> in Japan or China is the same number of USD as <code>$1,234,567</code> is in the US. If you're outputting euro, etc., then change the currency sign from <code>"$"</code>.</p>\n<p>Declare this anywhere in your HTML <head> section or wherever necessary, just before you need to use it:</p>\n<pre><code> Number.prototype.toCurrencyString = function(prefix, suffix) {\n if (typeof prefix === 'undefined') { prefix = '$'; }\n if (typeof suffix === 'undefined') { suffix = ''; }\n var _localeBug = new RegExp((1).toLocaleString().replace(/^1/, '').replace(/\\./, '\\\\.') + "$");\n return prefix + (~~this).toLocaleString().replace(_localeBug, '') + (this % 1).toFixed(2).toLocaleString().replace(/^[+-]?0+/,'') + suffix;\n }\n</code></pre>\n<p>Then you're done! Use <code>(number).toCurrencyString()</code> anywhere you need to output the number as currency.</p>\n<pre><code>var MyNumber = 123456789.125;\nalert(MyNumber.toCurrencyString()); // alerts "$123,456,789.13"\nMyNumber = -123.567;\nalert(MyNumber.toCurrencyString()); // alerts "$-123.57"\n</code></pre>\n"
},
{
"answer_id": 15538795,
"author": "kalisjoshua",
"author_id": 881558,
"author_profile": "https://Stackoverflow.com/users/881558",
"pm_score": 2,
"selected": false,
"text": "<p>I based this heavily on <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/14428340#14428340\">the answer from VisioN</a>:</p>\n<pre><code>function format (val) {\n val = (+val).toLocaleString();\n val = (+val).toFixed(2);\n val += "";\n return val.replace(/(\\d)(?=(\\d{3})+(?:\\.\\d+)?$)/g, "$1" + format.thousands);\n}\n\n(function (isUS) {\n format.decimal = isUS ? "." : ",";\n format.thousands = isUS ? "," : ".";\n}(("" + (+(0.00).toLocaleString()).toFixed(2)).indexOf(".") > 0));\n</code></pre>\n<p>I tested with inputs:</p>\n<pre><code>[ ""\n , "1"\n , "12"\n , "123"\n , "1234"\n , "12345"\n , "123456"\n , "1234567"\n , "12345678"\n , "123456789"\n , "1234567890"\n , ".12"\n , "1.12"\n , "12.12"\n , "123.12"\n , "1234.12"\n , "12345.12"\n , "123456.12"\n , "1234567.12"\n , "12345678.12"\n , "123456789.12"\n , "1234567890.12"\n , "1234567890.123"\n , "1234567890.125"\n].forEach(function (item) {\n console.log(format(item));\n});\n</code></pre>\n<p>And got these results:</p>\n<pre><code>0.00\n1.00\n12.00\n123.00\n1,234.00\n12,345.00\n123,456.00\n1,234,567.00\n12,345,678.00\n123,456,789.00\n1,234,567,890.00\n0.12\n1.12\n12.12\n123.12\n1,234.12\n12,345.12\n123,456.12\n1,234,567.12\n12,345,678.12\n123,456,789.12\n1,234,567,890.12\n1,234,567,890.12\n1,234,567,890.13\n</code></pre>\n<p>Just for fun.</p>\n"
},
{
"answer_id": 16233919,
"author": "aross",
"author_id": 1000608,
"author_profile": "https://Stackoverflow.com/users/1000608",
"pm_score": 11,
"selected": false,
"text": "<h1><a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/NumberFormat\" rel=\"noreferrer\">Intl.NumberFormat</a></h1>\n<p>JavaScript has a number formatter (part of the Internationalization API).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Create our number formatter.\nconst formatter = new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: 'USD',\n\n // These options are needed to round to whole numbers if that's what you want.\n //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)\n //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)\n});\n\nconsole.log(formatter.format(2500)); /* $2,500.00 */</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Use <code>undefined</code> in place of the first argument (<code>'en-US'</code> in the example) to use the system locale (the user locale in case the code is running in a browser). <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation\" rel=\"noreferrer\">Further explanation of the locale code</a>.</p>\n<p>Here's a <a href=\"https://www.iban.com/currency-codes\" rel=\"noreferrer\">list of the currency codes</a>.</p>\n<h2>Intl.NumberFormat vs Number.prototype.toLocaleString</h2>\n<p>A final note comparing this to the older .<code>toLocaleString</code>. They both offer essentially the same functionality. However, toLocaleString in its older incarnations (pre-Intl) <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3\" rel=\"noreferrer\">does not actually support locales</a>: it uses the system locale. So when debugging old browsers, be sure that you're using the correct version (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Checking_for_support_for_locales_and_options_arguments\" rel=\"noreferrer\">MDN suggests to check for the existence of <code>Intl</code></a>). There isn't any need to worry about this at all if you don't care about old browsers or just use the <a href=\"https://github.com/andyearnshaw/Intl.js\" rel=\"noreferrer\">shim</a>.</p>\n<p>Also, the performance of both is the same for a <em>single</em> item, but if you have a lot of numbers to format, using <code>Intl.NumberFormat</code> is ~70 times faster. Therefore, it's usually best to use <code>Intl.NumberFormat</code> and instantiate only once per page load. Anyway, here's the equivalent usage of <code>toLocaleString</code>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log((2500).toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n})); /* $2,500.00 */</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Some notes on browser support and Node.js</h3>\n<ul>\n<li>Browser support is no longer an issue nowadays with 98% support globally, 99% in the US and 99+% in the EU</li>\n<li>There is a <a href=\"https://github.com/andyearnshaw/Intl.js\" rel=\"noreferrer\">shim</a> to support it on fossilized browsers (like <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"noreferrer\">Internet Explorer 8</a>), should you really need to</li>\n<li>Node.js before v13 only supports <code>en-US</code> out of the box. One solution is to install <a href=\"https://github.com/icu-project/full-icu-npm\" rel=\"noreferrer\">full-icu</a>, see <a href=\"https://stackoverflow.com/a/39626602/1000608\">here</a> for more information</li>\n<li>Have a look at <a href=\"https://caniuse.com/#feat=internationalization\" rel=\"noreferrer\">CanIUse</a> for more information</li>\n</ul>\n"
},
{
"answer_id": 18245848,
"author": "Joseph Lennox",
"author_id": 1392539,
"author_profile": "https://Stackoverflow.com/users/1392539",
"pm_score": 2,
"selected": false,
"text": "<p>This answer meets the following criteria:</p>\n<ul>\n<li>Does not depend on an external dependency.</li>\n<li>Does support localization.</li>\n<li>Does have tests/proofs.</li>\n<li>Does use simple and best coding practices (no complicated regex's and uses standard coding patterns).</li>\n</ul>\n<p>This code is built on concepts from other answers. Its execution speed should be among the better posted here if that's a concern.</p>\n<pre><code>var decimalCharacter = Number("1.1").toLocaleString().substr(1,1);\nvar defaultCurrencyMarker = "$";\nfunction formatCurrency(number, currencyMarker) {\n if (typeof number != "number")\n number = parseFloat(number, 10);\n\n // if NaN is passed in or comes from the parseFloat, set it to 0.\n if (isNaN(number))\n number = 0;\n\n var sign = number < 0 ? "-" : "";\n number = Math.abs(number); // so our signage goes before the $ symbol.\n\n var integral = Math.floor(number);\n var formattedIntegral = integral.toLocaleString();\n\n // IE returns "##.00" while others return "##"\n formattedIntegral = formattedIntegral.split(decimalCharacter)[0];\n\n var decimal = Math.round((number - integral) * 100);\n return sign + (currencyMarker || defaultCurrencyMarker) +\n formattedIntegral +\n decimalCharacter +\n decimal.toString() + (decimal < 10 ? "0" : "");\n}\n</code></pre>\n<p>These tests only work on a US locale machine. This decision was made for simplicity and because this could cause of crappy input (bad auto-localization) allowing for crappy output issues.</p>\n<pre><code>var tests = [\n // [ input, expected result ]\n [123123, "$123,123.00"], // no decimal\n [123123.123, "$123,123.12"], // decimal rounded down\n [123123.126, "$123,123.13"], // decimal rounded up\n [123123.4, "$123,123.40"], // single decimal\n ["123123", "$123,123.00"], // repeat subset of the above using string input.\n ["123123.123", "$123,123.12"],\n ["123123.126", "$123,123.13"],\n [-123, "-$123.00"] // negatives\n];\n\nfor (var testIndex=0; testIndex < tests.length; testIndex++) {\n var test = tests[testIndex];\n var formatted = formatCurrency(test[0]);\n if (formatted == test[1]) {\n console.log("Test passed, \\"" + test[0] + "\\" resulted in \\"" + formatted + "\\"");\n } else {\n console.error("Test failed. Expected \\"" + test[1] + "\\", got \\"" + formatted + "\\"");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18994850,
"author": "Nick Grealy",
"author_id": 782034,
"author_profile": "https://Stackoverflow.com/users/782034",
"pm_score": 6,
"selected": false,
"text": "<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_Compatibility\" rel=\"nofollow noreferrer\">Works for all current browsers</a></strong></p>\n<p>Use <code>toLocaleString</code> to format a currency in its language-sensitive representation (using <a href=\"https://www.currency-iso.org/en/home/tables/table-a1.html\" rel=\"nofollow noreferrer\">ISO 4217</a> currency codes).</p>\n<pre><code>(2500).toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2})\n</code></pre>\n<p><em><strong>Example South African Rand code snippets <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/14735423#comment101585127_18994850\">for avenmore</a></strong></em>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log((2500).toLocaleString(\"en-ZA\", {style: \"currency\", currency: \"ZAR\", minimumFractionDigits: 2}))\n// -> R 2 500,00\nconsole.log((2500).toLocaleString(\"en-GB\", {style: \"currency\", currency: \"ZAR\", minimumFractionDigits: 2}))\n// -> ZAR 2,500.00</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 21255239,
"author": "Anunay",
"author_id": 674127,
"author_profile": "https://Stackoverflow.com/users/674127",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the short and best one to convert numbers into a currency format:</p>\n<pre><code>function toCurrency(amount){\n return amount.replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, "$1,");\n}\n\n// usage: toCurrency(3939920.3030);\n</code></pre>\n"
},
{
"answer_id": 23717185,
"author": "Steely Wing",
"author_id": 1877620,
"author_profile": "https://Stackoverflow.com/users/1877620",
"pm_score": 4,
"selected": false,
"text": "<p>Here are some solutions and all pass the test suite. The test suite and benchmark are included. If you want copy and paste to test, try <a href=\"https://gist.github.com/steelywing/85fdcbe084c332596179\" rel=\"nofollow noreferrer\">this gist</a>.</p>\n<h3>Method 0 (RegExp)</h3>\n<p>It is based on <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/14428340#14428340\">VisioN's answer</a>, but it fixes if there isn't a decimal point.</p>\n<pre><code>if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.');\n a[0] = a[0].replace(/\\d(?=(\\d{3})+$)/g, '$&,');\n return a.join('.');\n }\n}\n</code></pre>\n<h3>Method 1</h3>\n<pre><code>if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.'),\n // Skip the '-' sign\n head = Number(this < 0);\n\n // Skip the digits that's before the first thousands separator\n head += (a[0].length - head) % 3 || 3;\n\n a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\\d{3}/g, ',$&');\n return a.join('.');\n };\n}\n</code></pre>\n<h3>Method 2 (Split to Array)</h3>\n<pre><code>if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('.');\n\n a[0] = a[0]\n .split('').reverse().join('')\n .replace(/\\d{3}(?=\\d)/g, '$&,')\n .split('').reverse().join('');\n\n return a.join('.');\n };\n}\n</code></pre>\n<h3>Method 3 (Loop)</h3>\n<pre><code>if (typeof Number.prototype.format === 'undefined') {\n Number.prototype.format = function (precision) {\n if (!isFinite(this)) {\n return this.toString();\n }\n\n var a = this.toFixed(precision).split('');\n a.push('.');\n\n var i = a.indexOf('.') - 3;\n while (i > 0 && a[i-1] !== '-') {\n a.splice(i, 0, ',');\n i -= 3;\n }\n\n a.pop();\n return a.join('');\n };\n}\n</code></pre>\n<h3>Usage Example</h3>\n<pre><code>console.log('======== Demo ========')\nconsole.log(\n (1234567).format(0),\n (1234.56).format(2),\n (-1234.56).format(0)\n);\nvar n = 0;\nfor (var i=1; i<20; i++) {\n n = (n * 10) + (i % 10)/100;\n console.log(n.format(2), (-n).format(2));\n}\n</code></pre>\n<h3>Separator</h3>\n<p>If we want custom a thousands separator or decimal separator, use <code>replace()</code>:</p>\n<pre><code>123456.78.format(2).replace(',', ' ').replace('.', ' ');\n</code></pre>\n<h3>Test suite</h3>\n<pre><code>function assertEqual(a, b) {\n if (a !== b) {\n throw a + ' !== ' + b;\n }\n}\n\nfunction test(format_function) {\n console.log(format_function);\n assertEqual('NaN', format_function.call(NaN, 0))\n assertEqual('Infinity', format_function.call(Infinity, 0))\n assertEqual('-Infinity', format_function.call(-Infinity, 0))\n\n assertEqual('0', format_function.call(0, 0))\n assertEqual('0.00', format_function.call(0, 2))\n assertEqual('1', format_function.call(1, 0))\n assertEqual('-1', format_function.call(-1, 0))\n\n // Decimal padding\n assertEqual('1.00', format_function.call(1, 2))\n assertEqual('-1.00', format_function.call(-1, 2))\n\n // Decimal rounding\n assertEqual('0.12', format_function.call(0.123456, 2))\n assertEqual('0.1235', format_function.call(0.123456, 4))\n assertEqual('-0.12', format_function.call(-0.123456, 2))\n assertEqual('-0.1235', format_function.call(-0.123456, 4))\n\n // Thousands separator\n assertEqual('1,234', format_function.call(1234.123456, 0))\n assertEqual('12,345', format_function.call(12345.123456, 0))\n assertEqual('123,456', format_function.call(123456.123456, 0))\n assertEqual('1,234,567', format_function.call(1234567.123456, 0))\n assertEqual('12,345,678', format_function.call(12345678.123456, 0))\n assertEqual('123,456,789', format_function.call(123456789.123456, 0))\n assertEqual('-1,234', format_function.call(-1234.123456, 0))\n assertEqual('-12,345', format_function.call(-12345.123456, 0))\n assertEqual('-123,456', format_function.call(-123456.123456, 0))\n assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))\n assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))\n assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))\n\n // Thousands separator and decimal\n assertEqual('1,234.12', format_function.call(1234.123456, 2))\n assertEqual('12,345.12', format_function.call(12345.123456, 2))\n assertEqual('123,456.12', format_function.call(123456.123456, 2))\n assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))\n assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))\n assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))\n assertEqual('-1,234.12', format_function.call(-1234.123456, 2))\n assertEqual('-12,345.12', format_function.call(-12345.123456, 2))\n assertEqual('-123,456.12', format_function.call(-123456.123456, 2))\n assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))\n assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))\n assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))\n}\n\nconsole.log('======== Testing ========');\ntest(Number.prototype.format);\ntest(Number.prototype.format1);\ntest(Number.prototype.format2);\ntest(Number.prototype.format3);\n</code></pre>\n<h3>Benchmark</h3>\n<pre><code>function benchmark(f) {\n var start = new Date().getTime();\n f();\n return new Date().getTime() - start;\n}\n\nfunction benchmark_format(f) {\n console.log(f);\n time = benchmark(function () {\n for (var i = 0; i < 100000; i++) {\n f.call(123456789, 0);\n f.call(123456789, 2);\n }\n });\n console.log(time.format(0) + 'ms');\n}\n\n// If not using async, the browser will stop responding while running.\n// This will create a new thread to benchmark\nasync = [];\nfunction next() {\n setTimeout(function () {\n f = async.shift();\n f && f();\n next();\n }, 10);\n}\n\nconsole.log('======== Benchmark ========');\nasync.push(function () { benchmark_format(Number.prototype.format); });\nnext();\n</code></pre>\n"
},
{
"answer_id": 23747994,
"author": "Chad Kuehn",
"author_id": 1069995,
"author_profile": "https://Stackoverflow.com/users/1069995",
"pm_score": 3,
"selected": false,
"text": "<p>A function to handle currency output, including negatives.\n<br /><br />Sample Output:<br />\n$5.23<br />\n-$5.23</p>\n\n<pre><code>function formatCurrency(total) {\n var neg = false;\n if(total < 0) {\n neg = true;\n total = Math.abs(total);\n }\n return (neg ? \"-$\" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\\d)(?=(\\d{3})+\\.)/g, \"$1,\").toString();\n}\n</code></pre>\n"
},
{
"answer_id": 24428097,
"author": "Tom",
"author_id": 1937025,
"author_profile": "https://Stackoverflow.com/users/1937025",
"pm_score": 2,
"selected": false,
"text": "<p>The code <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/9318724#9318724\">from Jonathan M</a> looked too complicated for me, so I rewrote it and got about 30% on Firefox v30 and 60% on Chrome v35 speed boost (<a href=\"http://jsperf.com/number-formating2\" rel=\"nofollow noreferrer\">http://jsperf.com/number-formating2</a>):</p>\n<pre><code>Number.prototype.formatNumber = function(decPlaces, thouSeparator, decSeparator) {\n decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;\n decSeparator = decSeparator == undefined ? "." : decSeparator;\n thouSeparator = thouSeparator == undefined ? "," : thouSeparator;\n\n var n = this.toFixed(decPlaces);\n if (decPlaces) {\n var i = n.substr(0, n.length - (decPlaces + 1));\n var j = decSeparator + n.substr(-decPlaces);\n } else {\n i = n;\n j = '';\n }\n\n function reverse(str) {\n var sr = '';\n for (var l = str.length - 1; l >= 0; l--) {\n sr += str.charAt(l);\n }\n return sr;\n }\n\n if (parseInt(i)) {\n i = reverse(reverse(i).replace(/(\\d{3})(?=\\d)/g, "$1" + thouSeparator));\n }\n return i + j;\n};\n</code></pre>\n<p>Usage:</p>\n<pre><code>var sum = 123456789.5698;\nvar formatted = '$' + sum.formatNumber(2, ',', '.'); // "$123,456,789.57"\n</code></pre>\n"
},
{
"answer_id": 25753822,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 1,
"selected": false,
"text": "<p>I like it simple:</p>\n\n<pre><code>function formatPriceUSD(price) {\n var strPrice = price.toFixed(2).toString();\n var a = strPrice.split('');\n\n if (price > 1000000000)\n a.splice(a.length - 12, 0, ',');\n\n if (price > 1000000)\n a.splice(a.length - 9, 0, ',');\n\n if (price > 1000)\n a.splice(a.length - 6, 0, ',');\n\n return '$' + a.join(\"\");\n}\n</code></pre>\n"
},
{
"answer_id": 25755921,
"author": "iBet7o",
"author_id": 2109568,
"author_profile": "https://Stackoverflow.com/users/2109568",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat\" rel=\"nofollow noreferrer\">Intl.NumberFormat</a></p>\n<pre><code>var number = 3500;\nalert(new Intl.NumberFormat().format(number));\n// → "3,500" if in US English locale\n</code></pre>\n<p>Or <em><a href=\"http://phpjs.org/functions/number_format/\" rel=\"nofollow noreferrer\">PHP's number_format in JavaScript</a></em>.</p>\n"
},
{
"answer_id": 26506271,
"author": "Mohamed.Abdo",
"author_id": 1399223,
"author_profile": "https://Stackoverflow.com/users/1399223",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat</a>\nExample: Using locales</p>\n\n<p>This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:</p>\n\n<blockquote>\n <p>var number = 123456.789;</p>\n \n <p>// German uses comma as decimal separator and period for thousands\n console.log(new Intl.NumberFormat('de-DE').format(number)); // →\n 123.456,789</p>\n \n <p>// Arabic in most Arabic speaking countries uses real Arabic digits\n console.log(new Intl.NumberFormat('ar-EG').format(number)); // →\n ١٢٣٤٥٦٫٧٨٩</p>\n \n <p>// India uses thousands/lakh/crore separators console.log(new\n Intl.NumberFormat('en-IN').format(number));</p>\n</blockquote>\n"
},
{
"answer_id": 26745078,
"author": "Daniel Barbalace",
"author_id": 4076267,
"author_profile": "https://Stackoverflow.com/users/4076267",
"pm_score": 7,
"selected": false,
"text": "<p>If amount is a number, say <code>-123</code>, then</p>\n<pre><code>amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });\n</code></pre>\n<p>will produce the string <code>"-$123.00"</code>.</p>\n<p>Here's a complete working <a href=\"http://jsfiddle.net/1h29dguy/\" rel=\"noreferrer\">example</a>.</p>\n"
},
{
"answer_id": 28215542,
"author": "mp31415",
"author_id": 194715,
"author_profile": "https://Stackoverflow.com/users/194715",
"pm_score": 2,
"selected": false,
"text": "<p>I like the shortest <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/14428340#14428340\">answer by VisionN</a> except when I need to modify it for a number without a decimal point ($123 instead of $123.00). It does not work, so instead of quick copy/paste I need to decipher the arcane syntax of the JavaScript regular expression.</p>\n<p>Here is the original solution</p>\n<pre><code>n.toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,');\n</code></pre>\n<p>I'll make it a bit longer:</p>\n<pre><code>var re = /\\d(?=(\\d{3})+\\.)/g;\nvar subst = '$&,';\nn.toFixed(2).replace(re, subst);\n</code></pre>\n<p>The <code>re</code> part here (search part in string replace) means</p>\n<ol>\n<li>Find all digits (<code>\\d</code>)</li>\n<li>Followed by (<code>?=</code> ...) (lookahead)</li>\n<li>One or more groups <code>(</code>...<code>)+</code></li>\n<li>Of exactly three digits (<code>\\d{3}</code>)</li>\n<li>Ending with a dot (<code>\\.</code>)</li>\n<li>Do it for all occurrences (<code>g</code>)</li>\n</ol>\n<p>The <code>subst</code> part here means:</p>\n<ol>\n<li>Every time there is a match, replace it with itself (<code>$&</code>), followed by a comma.</li>\n</ol>\n<p>As we use <code>string.replace</code>, all other text in the string remains the same and only found digits (those that are followed by 3, 6, 9, etc. other digits) get an additional comma.</p>\n<p>So in a number, 1234567.89, digits <strong>1</strong> and <strong>4</strong> meet the condition (<strong>1</strong>23<strong>4</strong>567.89) and are replaced with "<strong>1,</strong>" and "<strong>4,</strong>" resulting in 1,234,567.89.</p>\n<p>If we don't need the decimal point in dollar amount at all (i.e., $123 instead of $123.00), we may change the regular expression like this:</p>\n<pre><code>var re2 = /\\d(?=(\\d{3})+$)/g;\n</code></pre>\n<p>It relies on the end of line (<code>$</code>) instead of a dot (<code>\\.</code>) and the final expression will be (notice also <code>toFixed(0)</code>):</p>\n<pre><code>n.toFixed(0).replace(/\\d(?=(\\d{3})+$)/g, '$&,');\n</code></pre>\n<p>This expression will give</p>\n<pre><code>1234567.89 -> 1,234,567\n</code></pre>\n<p>Also instead of end of line (<code>$</code>) in the regular expression above, you may opt for a word boundary as well (<code>\\b</code>).</p>\n<p><em>My apology in advance if I misinterpreted any part of the regular expression handling.</em></p>\n"
},
{
"answer_id": 28640113,
"author": "user2807653",
"author_id": 2807653,
"author_profile": "https://Stackoverflow.com/users/2807653",
"pm_score": 2,
"selected": false,
"text": "<p>Many of the answers had helpful ideas, but none of them could fit my needs. So I used all the ideas and build this example:</p>\n<pre><code>function Format_Numb(fmt){\n var decimals = isNaN(decimals) ? 2 : Math.abs(decimals);\n if(typeof decSgn === "undefined") decSgn = ".";\n if(typeof kommaSgn === "undefined") kommaSgn= ",";\n\n var s3digits = /(\\d{1,3}(?=(\\d{3})+(?=[.]|$))|(?:[.]\\d*))/g;\n var dflt_nk = "00000000".substring(0, decimals);\n\n //--------------------------------\n // handler for pattern: "%m"\n var _f_money = function(v_in){\n var v = v_in.toFixed(decimals);\n var add_nk = ",00";\n var arr = v.split(".");\n return arr[0].toString().replace(s3digits, function ($0) {\n return ($0.charAt(0) == ".")\n ? ((add_nk = ""), (kommaSgn + $0.substring(1)))\n : ($0 + decSgn);\n })\n + ((decimals > 0)\n ? (kommaSgn\n + (\n (arr.length > 1)\n ? arr[1]\n : dflt_nk\n )\n )\n : ""\n );\n }\n\n // handler for pattern: "%<len>[.<prec>]f"\n var _f_flt = function(v_in, l, prec){\n var v = (typeof prec !== "undefined") ? v_in.toFixed(prec) : v_in;\n return ((typeof l !== "undefined") && ((l=l-v.length) > 0))\n ? (Array(l+1).join(" ") + v)\n : v;\n }\n\n // handler for pattern: "%<len>x"\n var _f_hex = function(v_in, l, flUpper){\n var v = Math.round(v_in).toString(16);\n if(flUpper) v = v.toUpperCase();\n return ((typeof l !== "undefined") && ((l=l-v.length) > 0))\n ? (Array(l+1).join("0") + v)\n : v;\n }\n\n //...can be extended..., just add the function, for example: var _f_octal = function( v_in,...){\n //--------------------------------\n\n if(typeof(fmt) !== "undefined"){\n //...can be extended..., just add the char, for example "O": MFX -> MFXO\n var rpatt = /(?:%([^%"MFX]*)([MFX]))|(?:"([^"]*)")|("|%%)/gi;\n var _qu = "\\"";\n var _mask_qu = "\\\\\\"";\n var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){\n var f;\n if(typeof $1 !== "undefined"){\n switch($2.toUpperCase()){\n case "M": f = "_f_money(v)"; break;\n\n case "F": var n_dig0, n_dig1;\n var re_flt =/^(?:(\\d))*(?:[.](\\d))*$/;\n $1.replace(re_flt, function($0, $1, $2){\n n_dig0 = $1;\n n_dig1 = $2;\n });\n f = "_f_flt(v, " + n_dig0 + "," + n_dig1 + ")"; break;\n\n case "X": var n_dig = "undefined";\n var re_flt = /^(\\d*)$/;\n $1.replace(re_flt, function($0){\n if($0 != "") n_dig = $0;\n });\n f = "_f_hex(v, " + n_dig + "," + ($2=="X") + ")"; break;\n //...can be extended..., for example: case "O":\n }\n return "\\"+"+f+"+\\"";\n } else if(typeof $3 !== "undefined"){\n return _mask_qu + $3 + _mask_qu;\n } else {\n return ($4 == _qu) ? _mask_qu : $4.charAt(0);\n }\n });\n\n var cmd = "return function(v){"\n + "if(typeof v === \\"undefined\\")return \\"\\";" // null returned as empty string\n + "if(!v.toFixed) return v.toString();" // not numb returned as string\n + "return \\"" + str + "\\";"\n + "}";\n\n //...can be extended..., just add the function name in the 2 places:\n return new Function("_f_money,_f_flt,_f_hex", cmd)(_f_money,_f_flt,_f_hex);\n }\n}\n</code></pre>\n<p>First, I needed a <strong>C-style</strong> format-string-definition that should be <strong>flexible, but very easy to use</strong> and I defined it in following way; patterns:</p>\n<pre class=\"lang-none prettyprint-override\"><code>%[<len>][.<prec>]f float, example "%f", "%8.2d", "%.3f"\n%m money\n%[<len>]x hexadecimal lower case, example "%x", "%8x"\n%[<len>]X hexadecimal upper case, example "%X", "%8X"\n</code></pre>\n<p>Because there isn't any need to format others than to euro for me, I implemented only "%m".</p>\n<p>But it's easy to extend this... Like in C, the format string is a string containing the patterns. For example, <strong>for euro</strong>: <strong>"%m €"</strong> (returns strings like "8.129,33 €")</p>\n<p>Besides the flexibility, I needed a <strong>very fast solution for processing tables</strong>. That means that, when processing thousands of cells, the processing of format string <strong>must not be done more than once</strong>. A call like "format( value, fmt)" is not acceptable for me, but this must be split into two steps:</p>\n<pre><code>// var formatter = Format_Numb( "%m €");\n// simple example for Euro...\n\n// but we use a complex example:\n\nvar formatter = Format_Numb("a%%%3mxx \\"zz\\"%8.2f°\\" >0x%8X<");\n\n// formatter is now a function, which can be used more than once (this is an example, that can be tested:)\n\nvar v1 = formatter(1897654.8198344);\n\nvar v2 = formatter(4.2);\n\n... (and thousands of rows)\n</code></pre>\n<p>Also for performance, _f_money encloses the regular expression;</p>\n<p>Third, a call like "format( value, fmt)" is not acceptable because:</p>\n<p>Although it should be possible to format different collections of objects (for example, cells of a column) with different masks, I don't want to have something to handle format strings at the point of processing. At this point I only want <em>to use</em> formatting, like in</p>\n<blockquote>\n<p>for( var cell in cells){ do_something( cell.col.formatter(\ncell.value)); }</p>\n</blockquote>\n<p>What format - maybe it's defined in an .ini file, in an XML for each column or somewhere else ..., but <strong>analyzing and setting formats</strong> or dealing with internationalizaton <strong>is processed in totally another place</strong>, and there I want to assign the formatter to the collection without thinking about performance issues:</p>\n<blockquote>\n<p>col.formatter = Format_Numb( _getFormatForColumn(...) );</p>\n</blockquote>\n<p>Fourth, I wanted an <strong>"tolerant" solution</strong>, so passing, for example, a string instead of a number should return simply the string, but "null" should return en empty string.</p>\n<p>(Also formatting "%4.2f" must not cut something if the value is too big.)</p>\n<p>And last, but not least - it should be <strong>readable and easy extendable</strong>, <em>without</em> having any effects in performance...\nFor example, if somebody needs "octal values", please refer to lines with "...can be extended..." - I think that should be a very easy task.</p>\n<p>My overall focus lay on performance. Each "processing routine" (for example, <code>_f_money</code>) can be encapsulated optimized or exchanged with other ideas in this or other threads without change of the "prepare routines" (analyze format strings and creation of the functions), which must only be processed once and in that sense are not so performance critical like the conversion calls of thousands of numbers.</p>\n<p>For all, who prefer methods of numbers:</p>\n<pre><code>Number.prototype.format_euro = (function(formatter){\n return function(){ return formatter(this); }})\n(Format_Numb( "%m €"));\n\nvar v_euro = (8192.3282).format_euro(); // results: 8.192,33 €\n\nNumber.prototype.format_hex = (function(formatter){\n return function(){ return formatter(this); }})\n(Format_Numb( "%4x"));\n\nvar v_hex = (4.3282).format_hex();\n</code></pre>\n<p>Although I tested some, there may be a lot of bugs in the code. So it's not a ready module, but just an idea and a starting point for non-JavaScript experts like me.</p>\n<p>The code contains many and little modified ideas from a lot of Stack Overflow posts; sorry I can't reference all of them, but thanks to all the experts.</p>\n"
},
{
"answer_id": 29471888,
"author": "rab",
"author_id": 1722625,
"author_profile": "https://Stackoverflow.com/users/1722625",
"pm_score": 2,
"selected": false,
"text": "<p>There are already good answers. Here's a simple attempt for fun:</p>\n<pre><code>function currencyFormat(no) {\n var ar = (+no).toFixed(2).split('.');\n return [\n numberFormat(ar[0] | 0),\n '.',\n ar[1]\n ].join('');\n}\n\n\nfunction numberFormat(no) {\n var str = no + '';\n var ar = [];\n var i = str.length -1;\n\n while(i >= 0) {\n ar.push((str[i-2] || '') + (str[i-1] || '') + (str[i] || ''));\n i = i-3;\n }\n return ar.reverse().join(',');\n}\n</code></pre>\n<p>Then run some examples:</p>\n<pre><code>console.log(\n currencyFormat(1),\n currencyFormat(1200),\n currencyFormat(123),\n currencyFormat(9870000),\n currencyFormat(12345),\n currencyFormat(123456.232)\n)\n</code></pre>\n"
},
{
"answer_id": 30033551,
"author": "Ken Palmer",
"author_id": 993856,
"author_profile": "https://Stackoverflow.com/users/993856",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings?page=3&tab=oldest#comment52088405_30033551\">tggagne is correct</a>. My solution below is not good due to float rounding. And the toLocaleString function lacks some browser support. I'll leave the below comments for archival purposes of what <em>not</em> to do. :)</p>\n<p><em><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_Compatibility\" rel=\"nofollow noreferrer\">Date.prototype.toLocaleString()</a></em></p>\n<p><strong>(Old Solution) Use <a href=\"https://stackoverflow.com/questions/149055/how-to-format-numbers-as-currency-strings/149099#149099\">Patrick Desjardins' solution</a> instead.</strong></p>\n<p><em>This is a terse solution that uses toLocaleString(), which has been supported since JavaScript version 1.0. This example designates the currency to U.S. Dollars, but could be switched to pounds by using 'GBP' instead of 'USD'.</em></p>\n<pre><code>var formatMoney = function (value) {\n // Convert the value to a floating point number in case it arrives as a string.\n var numeric = parseFloat(value);\n // Specify the local currency.\n return numeric.toLocaleString('USD', { style: 'currency', currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });\n}\n</code></pre>\n<p><em>See</em> <em><strong><a href=\"https://marcoscaceres.github.io/jsi18n/#localize_currency\" rel=\"nofollow noreferrer\">Internationalization and localization, Currencies</a></strong></em> <em>for additional details.</em></p>\n"
},
{
"answer_id": 33286686,
"author": "jacob",
"author_id": 1784298,
"author_profile": "https://Stackoverflow.com/users/1784298",
"pm_score": 3,
"selected": false,
"text": "<p>Another way:</p>\n<pre><code>function centsToDollaString(x){\n var cents = x + ""\n while(cents.length < 4){\n cents = "0" + cents;\n }\n var dollars = cents.substr(0,cents.length - 2)\n var decimal = cents.substr(cents.length - 2, 2)\n while(dollars.length % 3 != 0){\n dollars = "0" + dollars;\n }\n str = dollars.replace(/(\\d{3})(?=\\d)/g, "$1" + ",").replace(/^0*(?=.)/, "");\n return "$" + str + "." + decimal;\n}\n</code></pre>\n"
},
{
"answer_id": 34686753,
"author": "Diego Fernando Villarroel Diaz",
"author_id": 5236798,
"author_profile": "https://Stackoverflow.com/users/5236798",
"pm_score": 2,
"selected": false,
"text": "<p>I want to contribute with this:</p>\n<pre><code>function toMoney(amount) {\n neg = amount.charAt(0);\n amount = amount.replace(/\\D/g, '');\n amount = amount.replace(/\\./g, '');\n amount = amount.replace(/\\-/g, '');\n\n var numAmount = new Number(amount);\n amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {\n return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;\n });\n\n if(neg == '-')\n return neg + amount;\n else\n return amount;\n}\n</code></pre>\n<p>This allows you to convert numbers in a text box where you are only supposed to put numbers (consider this scenario).</p>\n<p><strong>This is going to clean a textbox where there are only supposed to be numbers, even if you paste a string with numbers and letters or any character</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code><html>\n<head>\n <script language=="Javascript">\n function isNumber(evt) {\n var theEvent = evt || window.event;\n var key = theEvent.keyCode || theEvent.which;\n key = String.fromCharCode(key);\n if (key.length == 0)\n return;\n var regex = /^[0-9\\-\\b]+$/;\n if (!regex.test(key)) {\n theEvent.returnValue = false;\n if (theEvent.preventDefault)\n theEvent.preventDefault();\n }\n }\n\n function toMoney(amount) {\n neg = amount.charAt(0);\n amount = amount.replace(/\\D/g, '');\n amount = amount.replace(/\\./g, '');\n amount = amount.replace(/\\-/g, '');\n\n var numAmount = new Number(amount);\n amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {\n return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;\n });\n\n if(neg == '-')\n return neg + amount;\n else\n return amount;\n }\n\n function clearText(inTxt, newTxt, outTxt) {\n inTxt = inTxt.trim();\n newTxt = newTxt.trim();\n if(inTxt == '' || inTxt == newTxt)\n return outTxt;\n\n return inTxt;\n }\n\n function fillText(inTxt, outTxt) {\n inTxt = inTxt.trim();\n if(inTxt != '')\n outTxt = inTxt;\n\n return outTxt;\n }\n </script>\n</head>\n\n<body>\n $ <input name=reca2 id=reca2 type=text value="0" onFocus="this.value = clearText(this.value, '0', '');" onblur="this.value = fillText(this.value, '0'); this.value = toMoney(this.value);" onKeyPress="isNumber(event);" style="width:80px;" />\n</body>\n\n</html>\n</code></pre>\n"
},
{
"answer_id": 37626980,
"author": "Faysal Haque",
"author_id": 1993427,
"author_profile": "https://Stackoverflow.com/users/1993427",
"pm_score": 4,
"selected": false,
"text": "<p>I found this from: <a href=\"http://openexchangerates.github.io/accounting.js/\" rel=\"nofollow noreferrer\">accounting.js</a>. It's very easy and perfectly fits my need.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Default usage:\naccounting.formatMoney(12345678); // $12,345,678.00\n\n// European formatting (custom symbol and separators), can also use options object as second parameter:\naccounting.formatMoney(4999.99, \"€\", 2, \".\", \",\"); // €4.999,99\n\n// Negative values can be formatted nicely:\naccounting.formatMoney(-500000, \"£ \", 0); // £ -500,000\n\n// Simple `format` string allows control of symbol position (%v = value, %s = symbol):\naccounting.formatMoney(5318008, { symbol: \"GBP\", format: \"%v %s\" }); // 5,318,008.00 GBP\n\n// Euro currency symbol to the right\naccounting.formatMoney(5318008, {symbol: \"€\", precision: 2, thousand: \".\", decimal : \",\", format: \"%v%s\"}); // 1.008,00€ </code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 39782793,
"author": "James Eames",
"author_id": 6896525,
"author_profile": "https://Stackoverflow.com/users/6896525",
"pm_score": 2,
"selected": false,
"text": "<p>toLocaleString is good, but it doesn't work in all browsers. I usually use currencyFormatter.js (<a href=\"https://osrec.github.io/currencyFormatter.js/\" rel=\"nofollow noreferrer\">https://osrec.github.io/currencyFormatter.js/</a>). It's pretty lightweight and contains all the currency and locale definitions right out of the box. It's also good at formatting unusually formatted currencies, such as the <a href=\"https://en.wikipedia.org/wiki/Indian_rupee\" rel=\"nofollow noreferrer\">INR</a> (which groups numbers in <a href=\"https://en.wiktionary.org/wiki/lakh#Numeral\" rel=\"nofollow noreferrer\">lakhs</a>, <a href=\"https://en.wiktionary.org/wiki/crore#Noun\" rel=\"nofollow noreferrer\">crores</a>, etc.). Also, there aren't any dependencies!</p>\n<p><code>OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); // Returns ₹ 25,34,234.00</code></p>\n<p><code>OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); // Returns 2.534.234,00 €</code></p>\n<p><code>OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); // Returns 2 534 234,00 €</code></p>\n"
},
{
"answer_id": 40079019,
"author": "synthet1c",
"author_id": 1733478,
"author_profile": "https://Stackoverflow.com/users/1733478",
"pm_score": 5,
"selected": false,
"text": "<p>The following is concise, easy to understand, and doesn't rely on any overly complicated regular expressions.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function moneyFormat(price, sign = '$') {\n const pieces = parseFloat(price).toFixed(2).split('')\n let ii = pieces.length - 3\n while ((ii-=3) > 0) {\n pieces.splice(ii, 0, ',')\n }\n return sign + pieces.join('')\n}\n\nconsole.log(\n moneyFormat(100),\n moneyFormat(1000),\n moneyFormat(10000.00),\n moneyFormat(1000000000000000000)\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Here is a version with more options in the final output to allow formatting different currencies in different locality formats.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// higher order function that takes options then a price and will return the formatted price\nconst makeMoneyFormatter = ({\n sign = '$',\n delimiter = ',',\n decimal = '.',\n append = false,\n precision = 2,\n round = true,\n custom\n} = {}) => value => {\n\n const e = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000]\n\n value = round\n ? (Math.round(value * e[precision]) / e[precision])\n : parseFloat(value)\n\n const pieces = value\n .toFixed(precision)\n .replace('.', decimal)\n .split('')\n\n let ii = pieces.length - (precision ? precision + 1 : 0)\n\n while ((ii-=3) > 0) {\n pieces.splice(ii, 0, delimiter)\n }\n\n if (typeof custom === 'function') {\n return custom({\n sign,\n float: value,\n value: pieces.join('')\n })\n }\n\n return append\n ? pieces.join('') + sign\n : sign + pieces.join('')\n}\n\n// create currency converters with the correct formatting options\nconst formatDollar = makeMoneyFormatter()\nconst formatPound = makeMoneyFormatter({\n sign: '£',\n precision: 0\n})\nconst formatEuro = makeMoneyFormatter({\n sign: '€',\n delimiter: '.',\n decimal: ',',\n append: true\n})\n\nconst customFormat = makeMoneyFormatter({\n round: false,\n custom: ({ value, float, sign }) => `SALE:$${value}USD`\n})\n\nconsole.log(\n formatPound(1000),\n formatDollar(10000.0066),\n formatEuro(100000.001),\n customFormat(999999.555)\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 40534670,
"author": "Daniel Campos",
"author_id": 1790336,
"author_profile": "https://Stackoverflow.com/users/1790336",
"pm_score": 2,
"selected": false,
"text": "<p>I had a hard time finding a simple library to work with date and currency, so I created my own: <a href=\"https://github.com/dericeira/slimFormatter.js\" rel=\"nofollow noreferrer\">https://github.com/dericeira/slimFormatter.js</a></p>\n<p>Simple as that:</p>\n<pre><code>var number = slimFormatter.currency(2000.54);\n</code></pre>\n"
},
{
"answer_id": 40753048,
"author": "Choylton B. Higginbottom",
"author_id": 949598,
"author_profile": "https://Stackoverflow.com/users/949598",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a straightforward formatter in vanilla JavaScript:</p>\n<pre><code>function numberFormatter (num) {\n console.log(num)\n var wholeAndDecimal = String(num.toFixed(2)).split(".");\n console.log(wholeAndDecimal)\n var reversedWholeNumber = Array.from(wholeAndDecimal[0]).reverse();\n var formattedOutput = [];\n\n reversedWholeNumber.forEach( (digit, index) => {\n formattedOutput.push(digit);\n if ((index + 1) % 3 === 0 && index < reversedWholeNumber.length - 1) {\n formattedOutput.push(",");\n }\n })\n\n formattedOutput = formattedOutput.reverse().join('') + "." + wholeAndDecimal[1];\n\n return formattedOutput;\n}\n</code></pre>\n"
},
{
"answer_id": 49688690,
"author": "Nick",
"author_id": 9473764,
"author_profile": "https://Stackoverflow.com/users/9473764",
"pm_score": 2,
"selected": false,
"text": "<p>Because every problem deserves a one-line solution:</p>\n<pre><code>Number.prototype.formatCurrency = function() { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\\d)(?=(\\d{3})+$)/g, '$1,') : t + '.' + c; }, '$'); }\n</code></pre>\n<p>This is easy enough to change for different locales. Just change the '$1,' to '$1.' and '.' to ',' to swap <code>,</code> and <code>.</code> in numbers. The currency symbol can be changed by changing the '$' at the end.</p>\n<p>Or, if you have <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015\" rel=\"nofollow noreferrer\">ES6</a>, you can just declare the function with default values:</p>\n<pre><code>Number.prototype.formatCurrency = function(thou = ',', dec = '.', sym = '$') { return this.toFixed(2).toString().split(/[-.]/).reverse().reduceRight(function (t, c, i) { return (i == 2) ? '-' + t : (i == 1) ? t + c.replace(/(\\d)(?=(\\d{3})+$)/g, '$1' + thou) : t + dec + c; }, sym); }\n\nconsole.log((4215.57).formatCurrency())\n$4,215.57\nconsole.log((4216635.57).formatCurrency('.', ','))\n$4.216.635,57\nconsole.log((4216635.57).formatCurrency('.', ',', "\\u20AC"))\n€4.216.635,57\n</code></pre>\n<p>Oh and it works for negative numbers too:</p>\n<pre><code>console.log((-6635.574).formatCurrency('.', ',', "\\u20AC"))\n-€6.635,57\nconsole.log((-1066.507).formatCurrency())\n-$1,066.51\n</code></pre>\n<p>And of course you don't have to have a currency symbol:</p>\n<pre><code>console.log((1234.586).formatCurrency(',','.',''))\n1,234.59\nconsole.log((-7890123.456).formatCurrency(',','.',''))\n-7,890,123.46\nconsole.log((1237890.456).formatCurrency('.',',',''))\n1.237.890,46\n</code></pre>\n"
},
{
"answer_id": 51597446,
"author": "Nicolas Giszpenc",
"author_id": 3727524,
"author_profile": "https://Stackoverflow.com/users/3727524",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted a vanilla JavaScript solution that automatically returned the decimal portion.</p>\n<pre><code>function formatDollar(amount) {\n var dollar = Number(amount).toLocaleString("us", "currency");\n // Decimals\n var arrAmount = dollar.split(".");\n if (arrAmount.length==2) {\n var decimal = arrAmount[1];\n if (decimal.length==1) {\n arrAmount[1] += "0";\n }\n }\n if (arrAmount.length==1) {\n arrAmount.push("00");\n }\n\n return "$" + arrAmount.join(".");\n}\n\n\nconsole.log(formatDollar("1812.2");\n</code></pre>\n"
},
{
"answer_id": 54274936,
"author": "Adam Pery",
"author_id": 1500836,
"author_profile": "https://Stackoverflow.com/users/1500836",
"pm_score": 4,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Number(value)\r\n .toFixed(2)\r\n .replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, \"$1,\")</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 57726061,
"author": "Dinesh Lomte",
"author_id": 2436314,
"author_profile": "https://Stackoverflow.com/users/2436314",
"pm_score": 1,
"selected": false,
"text": "<p>Please find in the below code what I have developed to support internationalization.</p>\n<p>It formats the given numeric value to language specific format. In the given example I have used <strong>‘en’</strong> while have tested for <strong>‘es’</strong>, <strong>‘fr’</strong> and other countries where in the format varies. It not only stops the user from keying characters, but it formats the value on tab out.</p>\n<p>I have created components for <strong>Number</strong> as well as for <strong>Decimal</strong> format. Apart from this, I have created <strong>parseNumber(value, locale)</strong> and <strong>parseDecimal(value, locale)</strong> functions which will parse the formatted data for any other business purposes. The said function will accept the formatted data and will return the non-formatted value. I have used the jQuery validator plugin in the below shared code.</p>\n<p><strong>HTML:</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code><tr>\n <td>\n <label class="control-label">\n Number Field:\n </label>\n <div class="inner-addon right-addon">\n <input type="text" id="numberField"\n name="numberField"\n class="form-control"\n autocomplete="off"\n maxlength="17"\n data-rule-required="true"\n data-msg-required="Cannot be blank."\n data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"\n data-rule-numberExceedsMaxLimit="en"\n data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"\n onkeydown="return isNumber(event, 'en')"\n onkeyup="return updateField(this)"\n onblur="numberFormatter(this,\n 'en',\n 'Invalid character(s) found. Please enter valid characters.')">\n </div>\n </td>\n</tr>\n\n<tr>\n <td>\n <label class="control-label">\n Decimal Field:\n </label>\n <div class="inner-addon right-addon">\n <input type="text" id="decimalField"\n name="decimalField"\n class="form-control"\n autocomplete="off"\n maxlength="20"\n data-rule-required="true"\n data-msg-required="Cannot be blank."\n data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"\n data-rule-decimalExceedsMaxLimit="en"\n data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"\n onkeydown="return isDecimal(event, 'en')"\n onkeyup="return updateField(this)"\n onblur="decimalFormatter(this,\n 'en',\n 'Invalid character(s) found. Please enter valid characters.')">\n </div>\n </td>\n</tr>\n</code></pre>\n<p><strong>JavaScript:</strong></p>\n<pre><code>/*\n * @author: dinesh.lomte\n */\n/* Holds the maximum limit of digits to be entered in number field. */\nvar numericMaxLimit = 13;\n/* Holds the maximum limit of digits to be entered in decimal field. */\nvar decimalMaxLimit = 16;\n\n/**\n *\n * @param {type} value\n * @param {type} locale\n * @returns {Boolean}\n */\nparseDecimal = function(value, locale) {\n\n value = value.trim();\n if (isNull(value)) {\n return 0.00;\n }\n if (isNull(locale)) {\n return value;\n }\n if (getNumberFormat(locale)[0] === '.') {\n value = value.replace(/\\./g, '');\n } else {\n value = value.replace(\n new RegExp(getNumberFormat(locale)[0], 'g'), '');\n }\n if (getNumberFormat(locale)[1] === ',') {\n value = value.replace(\n new RegExp(getNumberFormat(locale)[1], 'g'), '.');\n }\n return value;\n};\n\n/**\n *\n * @param {type} element\n * @param {type} locale\n * @param {type} nanMessage\n * @returns {Boolean}\n */\ndecimalFormatter = function (element, locale, nanMessage) {\n\n showErrorMessage(element.id, false, null);\n if (isNull(element.id) || isNull(element.value) || isNull(locale)) {\n return true;\n }\n var value = element.value.trim();\n value = value.replace(/\\s/g, '');\n value = parseDecimal(value, locale);\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 2,\n maximumFractionDigits: 2\n }\n );\n if (numberFormatObj.format(value) === 'NaN') {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n element.value = numberFormatObj.format(value);\n return true;\n};\n\n/**\n *\n * @param {type} element\n * @param {type} locale\n * @param {type} nanMessage\n * @returns {Boolean}\n */\nnumberFormatter = function (element, locale, nanMessage) {\n\n showErrorMessage(element.id, false, null);\n if (isNull(element.id) || isNull(element.value) || isNull(locale)) {\n return true;\n }\n var value = element.value.trim();\n var format = getNumberFormat(locale);\n if (hasDecimal(value, format[1])) {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n value = value.replace(/\\s/g, '');\n value = parseNumber(value, locale);\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 0,\n maximumFractionDigits: 0\n }\n );\n if (numberFormatObj.format(value) === 'NaN') {\n showErrorMessage(element.id, true, nanMessage);\n setFocus(element.id);\n return false;\n }\n element.value =\n numberFormatObj.format(value);\n return true;\n};\n\n/**\n *\n * @param {type} id\n * @param {type} flag\n * @param {type} message\n * @returns {undefined}\n */\nshowErrorMessage = function(id, flag, message) {\n\n if (flag) {\n // only add if not added\n if ($('#'+id).parent().next('.app-error-message').length === 0) {\n var errorTag = '<div class=\\'app-error-message\\'>' + message + '</div>';\n $('#'+id).parent().after(errorTag);\n }\n } else {\n // remove it\n $('#'+id).parent().next(".app-error-message").remove();\n }\n};\n\n/**\n *\n * @param {type} id\n * @returns\n */\nsetFocus = function(id) {\n\n id = id.trim();\n if (isNull(id)) {\n return;\n }\n setTimeout(function() {\n document.getElementById(id).focus();\n }, 10);\n};\n\n/**\n *\n * @param {type} value\n * @param {type} locale\n * @returns {Array}\n */\nparseNumber = function(value, locale) {\n\n value = value.trim();\n if (isNull(value)) {\n return 0;\n }\n if (isNull(locale)) {\n return value;\n }\n if (getNumberFormat(locale)[0] === '.') {\n return value.replace(/\\./g, '');\n }\n return value.replace(\n new RegExp(getNumberFormat(locale)[0], 'g'), '');\n};\n\n/**\n *\n * @param {type} locale\n * @returns {Array}\n */\ngetNumberFormat = function(locale) {\n\n var format = [];\n var numberFormatObj = new Intl.NumberFormat(locale,\n { minimumFractionDigits: 2,\n maximumFractionDigits: 2\n }\n );\n var value = numberFormatObj.format('132617.07');\n format[0] = value.charAt(3);\n format[1] = value.charAt(7);\n return format;\n};\n\n/**\n *\n * @param {type} value\n * @param {type} fractionFormat\n * @returns {Boolean}\n */\nhasDecimal = function(value, fractionFormat) {\n\n value = value.trim();\n if (isNull(value) || isNull(fractionFormat)) {\n return false;\n }\n if (value.indexOf(fractionFormat) >= 1) {\n return true;\n }\n};\n\n/**\n *\n * @param {type} event\n * @param {type} locale\n * @returns {Boolean}\n */\nisNumber = function(event, locale) {\n\n var keyCode = event.which ? event.which : event.keyCode;\n // Validating if user has pressed shift character\n if (keyCode === 16) {\n return false;\n }\n if (isNumberKey(keyCode)) {\n return true;\n }\n var numberFormatter = [32, 110, 188, 190];\n if (keyCode === 32\n && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {\n return true;\n }\n if (numberFormatter.indexOf(keyCode) >= 0\n && getNumberFormat(locale)[0] === getFormat(keyCode)) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} event\n * @param {type} locale\n * @returns {Boolean}\n */\nisDecimal = function(event, locale) {\n\n var keyCode = event.which ? event.which : event.keyCode;\n // Validating if user has pressed shift character\n if (keyCode === 16) {\n return false;\n }\n if (isNumberKey(keyCode)) {\n return true;\n }\n var numberFormatter = [32, 110, 188, 190];\n if (keyCode === 32\n && isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {\n return true;\n }\n if (numberFormatter.indexOf(keyCode) >= 0\n && (getNumberFormat(locale)[0] === getFormat(keyCode)\n || getNumberFormat(locale)[1] === getFormat(keyCode))) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} keyCode\n * @returns {Boolean}\n */\nisNumberKey = function(keyCode) {\n\n if ((keyCode >= 48 && keyCode <= 57) ||\n (keyCode >= 96 && keyCode <= 105)) {\n return true;\n }\n var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];\n if (keys.indexOf(keyCode) !== -1) {\n return true;\n }\n return false;\n};\n\n/**\n *\n * @param {type} keyCode\n * @returns {JSON@call;parse.numberFormatter.value|String}\n */\ngetFormat = function(keyCode) {\n\n var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.numberFormatter) {\n if (jsonObject.numberFormatter.hasOwnProperty(key)\n && keyCode === parseInt(jsonObject.numberFormatter[key].key)) {\n return jsonObject.numberFormatter[key].value;\n }\n }\n return '';\n};\n\n/**\n *\n * @type String\n */\nvar jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';\n\n/**\n *\n * @param {type} value\n * @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}\n */\ngetShiftCharSpecificNumber = function(value) {\n\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.shiftCharacterNumberMap) {\n if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)\n && value === jsonObject.shiftCharacterNumberMap[key].char) {\n return jsonObject.shiftCharacterNumberMap[key].number;\n }\n }\n return '';\n};\n\n/**\n *\n * @param {type} value\n * @returns {Boolean}\n */\nisShiftSpecificChar = function(value) {\n\n var jsonObject = JSON.parse(jsonString);\n for (var key in jsonObject.shiftCharacterNumberMap) {\n if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)\n && value === jsonObject.shiftCharacterNumberMap[key].char) {\n return true;\n }\n }\n return false;\n};\n\n/**\n *\n * @param {type} element\n * @returns {undefined}\n */\nupdateField = function(element) {\n\n var value = element.value;\n\n for (var index = 0; index < value.length; index++) {\n if (!isShiftSpecificChar(value.charAt(index))) {\n continue;\n }\n element.value = value.replace(\n value.charAt(index),\n getShiftCharSpecificNumber(value.charAt(index)));\n }\n};\n\n/**\n *\n * @param {type} value\n * @param {type} element\n * @param {type} params\n */\njQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {\n\n value = parseInt(parseNumber(value, params));\n if (value.toString().length > numericMaxLimit) {\n showErrorMessage(element.id, false, null);\n setFocus(element.id);\n return false;\n }\n return true;\n}, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');\n\n/**\n *\n * @param {type} value\n * @param {type} element\n * @param {type} params\n */\njQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {\n\n value = parseFloat(parseDecimal(value, params)).toFixed(2);\n if (value.toString().substring(\n 0, value.toString().lastIndexOf('.')).length > numericMaxLimit\n || value.toString().length > decimalMaxLimit) {\n showErrorMessage(element.id, false, null);\n setFocus(element.id);\n return false;\n }\n return true;\n}, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');\n\n/**\n * @param {type} id\n * @param {type} locale\n * @returns {boolean}\n */\nisNumberExceedMaxLimit = function(id, locale) {\n\n var value = parseInt(parseNumber(\n document.getElementById(id).value, locale));\n if (value.toString().length > numericMaxLimit) {\n setFocus(id);\n return true;\n }\n return false;\n};\n\n/**\n * @param {type} id\n * @param {type} locale\n * @returns {boolean}\n */\nisDecimalExceedsMaxLimit = function(id, locale) {\n\n var value = parseFloat(parseDecimal(\n document.getElementById(id).value, locale)).toFixed(2);\n if (value.toString().substring(\n 0, value.toString().lastIndexOf('.')).length > numericMaxLimit\n || value.toString().length > decimalMaxLimit) {\n setFocus(id);\n return true;\n }\n return false;\n};\n</code></pre>\n"
},
{
"answer_id": 58007996,
"author": "Murtaza Hussain",
"author_id": 4527878,
"author_profile": "https://Stackoverflow.com/users/4527878",
"pm_score": 3,
"selected": false,
"text": "<p>We can also use <a href=\"http://numeraljs.com/\" rel=\"noreferrer\"><strong>numeraljs</strong></a></p>\n\n<blockquote>\n <p>Numbers can be formatted to look like currency, percentages, times, or even plain old numbers with decimal places, thousands, and abbreviations. And you can always create a custom format.</p>\n</blockquote>\n\n<pre><code>var string = numeral(1000).format('0,0');\n// '1,000'\n</code></pre>\n"
},
{
"answer_id": 60877747,
"author": "Vinod Kumar",
"author_id": 3771354,
"author_profile": "https://Stackoverflow.com/users/3771354",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Please try the below code</strong></p>\n<pre><code>"250000".replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,');\n</code></pre>\n<p><strong>Ans</strong>: 250,000</p>\n<p><a href=\"https://i.stack.imgur.com/nkmZ3.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nkmZ3.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 64200888,
"author": "pgee70",
"author_id": 1490306,
"author_profile": "https://Stackoverflow.com/users/1490306",
"pm_score": 1,
"selected": false,
"text": "<p>Taking a few of the best rated answers, I combined and made an <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript 2015</a> (ES6) function that passes <a href=\"https://en.wikipedia.org/wiki/ESLint\" rel=\"nofollow noreferrer\">ESLint</a>.</p>\n<pre><code>export const formatMoney = (\n amount,\n decimalCount = 2,\n decimal = '.',\n thousands = ',',\n currencySymbol = '$',\n) => {\n if (typeof Intl === 'object') {\n return new Intl.NumberFormat('en-AU', {\n style: 'currency',\n currency: 'AUD',\n }).format(amount);\n }\n // Fallback if Intl is not present.\n try {\n const negativeSign = amount < 0 ? '-' : '';\n const amountNumber = Math.abs(Number(amount) || 0).toFixed(decimalCount);\n const i = parseInt(amountNumber, 10).toString();\n const j = i.length > 3 ? i.length % 3 : 0;\n return (\n currencySymbol +\n negativeSign +\n (j ? i.substr(0, j) + thousands : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, `$1${thousands}`) +\n (decimalCount\n ? decimal +\n Math.abs(amountNumber - i)\n .toFixed(decimalCount)\n .slice(2)\n : '')\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error(e);\n }\n return amount;\n};\n</code></pre>\n"
},
{
"answer_id": 68536579,
"author": "gadielkalleb",
"author_id": 11336223,
"author_profile": "https://Stackoverflow.com/users/11336223",
"pm_score": 5,
"selected": false,
"text": "<h3>just use the native javascript Intl</h3>\n<p>you just use the options to format its value</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const number = 1233445.5678\nconsole.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat\" rel=\"noreferrer\">mozilla documentation link</a></p>\n"
},
{
"answer_id": 74385955,
"author": "odionk",
"author_id": 13534081,
"author_profile": "https://Stackoverflow.com/users/13534081",
"pm_score": 0,
"selected": false,
"text": "<p>after converting PHP number_format() to javascript this work for me</p>\n<pre><code>function number_format(number, decimals = 0, dec_point = ".",thousands_sep = ",") {\n number = (number + '').replace(/[^0-9+\\-Ee.]/g, '');\n var n = !isFinite(+number) ? 0 : +number,\n prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),\n s = '',\n toFixedFix = function(n, prec)\n {\n var k = Math.pow(10, prec);\n return '' + (Math.round(n * k) / k).toFixed(prec);\n };\n // Fix for IE parseFloat(0.55).toFixed(0) = 0;\n s = (prec ? toFixedFix(n, prec) : '' + \n Math.round(n)).split('.');\n if (s[0].length > 3)\n {\n s[0] = s[0].replace(/\\B(?=(?:\\d{3})+(?!\\d))/g, \n thousands_sep);\n }\n if ((s[1] || '').length < prec)\n {\n s[1] = s[1] || '';\n s[1] += new Array(prec - s[1].length + 1).join('0');\n }\n return s.join(dec_point);\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
| I would like to format a price in JavaScript. I'd like a function which takes a `float` as an argument and returns a `string` formatted like this:
```
"$ 2,500.00"
```
How can I do this? | Ok, based on what you said, I'm using this:
```
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
```
I'm open to improvement suggestions (I'd prefer not to include [YUI](https://en.wikipedia.org/wiki/Yahoo!_UI_Library) just to do this :-) )
I already know I should be detecting the "." instead of just using it as the decimal separator... |
149,057 | <p>How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders.</p>
<p>Also, I want to to be able to modify the file directly, and not just print everything to stdout.</p>
| [
{
"answer_id": 149070,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "<p>In Bash:</p>\n\n<p><code>find dir -type f -exec sed -i 's/ *$//' '{}' ';'</code></p>\n\n<p>Note: If you're using <code>.git</code> repository, try adding: <code>-not -iwholename '.git'</code>.</p>\n"
},
{
"answer_id": 149081,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 5,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>find . -type f -print0 | xargs -0 perl -pi.bak -e 's/ +$//'\n</code></pre>\n\n<p>if you don't want the \".bak\" files generated:</p>\n\n<pre><code>find . -type f -print0 | xargs -0 perl -pi -e 's/ +$//'\n</code></pre>\n\n<p>as a zsh user, you can omit the call to find, and instead use:</p>\n\n<pre><code>perl -pi -e 's/ +$//' **/*\n</code></pre>\n\n<p>Note: To prevent destroying <code>.git</code> directory, try adding: <code>-not -iwholename '*.git*'</code>.</p>\n"
},
{
"answer_id": 639043,
"author": "pojo",
"author_id": 70350,
"author_profile": "https://Stackoverflow.com/users/70350",
"pm_score": 4,
"selected": false,
"text": "<p>This worked for me in OSX 10.5 Leopard, which does not use GNU sed or xargs.</p>\n\n<pre><code>find dir -type f -print0 | xargs -0 sed -i.bak -E \"s/[[:space:]]*$//\"\n</code></pre>\n\n<p>Just be careful with this if you have files that need to be excluded (I did)!</p>\n\n<p>You can use -prune to ignore certain directories or files. For Python files in a git repository, you could use something like:</p>\n\n<pre><code>find dir -not -path '.git' -iname '*.py'\n</code></pre>\n"
},
{
"answer_id": 1803902,
"author": "Jesper Rønn-Jensen",
"author_id": 109305,
"author_profile": "https://Stackoverflow.com/users/109305",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up not using find and not creating backup files.</p>\n\n<pre><code>sed -i '' 's/[[:space:]]*$//g' **/*.*\n</code></pre>\n\n<p>Depending on the depth of the file tree, this (shorter version) may be sufficient for your needs. </p>\n\n<p>NOTE this also takes binary files, for instance.</p>\n"
},
{
"answer_id": 4198102,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up running this, which is a mix between pojo and adams version.</p>\n\n<p>It will clean both trailing whitespace, and also another form of trailing whitespace, the carriage return:</p>\n\n<pre><code>find . -not \\( -name .svn -prune -o -name .git -prune \\) -type f \\\n -exec sed -i 's/[:space:]+$//' \\{} \\; \\\n -exec sed -i 's/\\r\\n$/\\n/' \\{} \\;\n</code></pre>\n\n<p>It won't touch the .git folder if there is one.</p>\n\n<p><strong>Edit</strong>: Made it a bit safer after the comment, not allowing to take files with \".git\" or \".svn\" in it. But beware, it <em>will</em> touch binary files if you've got some. Use <code>-iname \"*.py\" -or -iname \"*.php\"</code> after <code>-type f</code> if you only want it to touch e.g. .py and .php-files.</p>\n\n<p><strong>Update 2</strong>: It now replaces all kinds of spaces at end of line (which means tabs as well)</p>\n"
},
{
"answer_id": 5130044,
"author": "deepwell",
"author_id": 21473,
"author_profile": "https://Stackoverflow.com/users/21473",
"pm_score": 6,
"selected": false,
"text": "<p>Here is an OS X >= 10.6 Snow Leopard solution.</p>\n<p><strong>It Ignores .git and .svn folders</strong> and their contents. Also it won't leave a backup file.</p>\n<pre><code>(export LANG=C LC_CTYPE=C\nfind . -not \\( -name .svn -prune -o -name .git -prune \\) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//'\n)\n</code></pre>\n<p>The enclosing parenthesis preserves the <code>L*</code> variables of current shell – executing in subshell.</p>\n"
},
{
"answer_id": 9639285,
"author": "ChicagoBob",
"author_id": 61614,
"author_profile": "https://Stackoverflow.com/users/61614",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of excluding files, here is a variation of the above the explicitly white lists the files, based on file extension, that you want to strip, feel free to season to taste:</p>\n\n<pre><code>find . \\( -name *.rb -or -name *.html -or -name *.js -or -name *.coffee -or \\\n-name *.css -or -name *.scss -or -name *.erb -or -name *.yml -or -name *.ru \\) \\\n-print0 | xargs -0 sed -i '' -E \"s/[[:space:]]*$//\"\n</code></pre>\n"
},
{
"answer_id": 10120431,
"author": "l0b0",
"author_id": 96588,
"author_profile": "https://Stackoverflow.com/users/96588",
"pm_score": 5,
"selected": false,
"text": "<p>Two alternative approaches which also work with <strong>DOS newlines</strong> (CR/LF) and do a pretty good job at <strong>avoiding binary files</strong>:</p>\n\n<p><a href=\"https://unix.stackexchange.com/questions/36233/how-to-skip-file-in-sed-if-it-contains-regex\">Generic solution</a> which checks that the MIME type starts with <code>text/</code>:</p>\n\n<pre><code>while IFS= read -r -d '' -u 9\ndo\n if [[ \"$(file -bs --mime-type -- \"$REPLY\")\" = text/* ]]\n then\n sed -i 's/[ \\t]\\+\\(\\r\\?\\)$/\\1/' -- \"$REPLY\"\n else\n echo \"Skipping $REPLY\" >&2\n fi\ndone 9< <(find . -type f -print0)\n</code></pre>\n\n<p><a href=\"https://unix.stackexchange.com/a/36240/3645\"><strong>Git repository-specific</strong> solution</a> by Mat which uses the <code>-I</code> option of <code>git grep</code> to skip files which Git considers to be binary:</p>\n\n<pre><code>git grep -I --name-only -z -e '' | xargs -0 sed -i 's/[ \\t]\\+\\(\\r\\?\\)$/\\1/'\n</code></pre>\n"
},
{
"answer_id": 11861798,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 1,
"selected": false,
"text": "<p>This is what works for me (Mac OS X 10.8, GNU sed installed by Homebrew):</p>\n\n<pre><code>find . -path ./vendor -prune -o \\\n \\( -name '*.java' -o -name '*.xml' -o -name '*.css' \\) \\\n -exec gsed -i -E 's/\\t/ /' \\{} \\; \\\n -exec gsed -i -E 's/[[:space:]]*$//' \\{} \\; \\\n -exec gsed -i -E 's/\\r\\n/\\n/' \\{} \\;\n</code></pre>\n\n<p>Removed trailing spaces, replaces tabs with spaces, replaces Windows CRLF with Unix <code>\\n</code>.</p>\n\n<p>What's interesting is that I have to run this 3-4 times before all files get fixed, by all cleaning <code>gsed</code> instructions.</p>\n"
},
{
"answer_id": 12508409,
"author": "Grant Murphy",
"author_id": 1312070,
"author_profile": "https://Stackoverflow.com/users/1312070",
"pm_score": 2,
"selected": false,
"text": "<p>This works well.. add/remove --include for specific file types : </p>\n\n<pre><code>egrep -rl ' $' --include *.c * | xargs sed -i 's/\\s\\+$//g'\n</code></pre>\n"
},
{
"answer_id": 16246948,
"author": "jbbuckley",
"author_id": 884900,
"author_profile": "https://Stackoverflow.com/users/884900",
"pm_score": 4,
"selected": false,
"text": "<p>Ack was made for this kind of task.</p>\n\n<p>It works just like grep, but knows not to descend into places like .svn, .git, .cvs, etc.</p>\n\n<pre><code>ack --print0 -l '[ \\t]+$' | xargs -0 -n1 perl -pi -e 's/[ \\t]+$//'\n</code></pre>\n\n<p>Much easier than jumping through hoops with find/grep.</p>\n\n<p>Ack is available via most package managers (as either <em>ack</em> or <em>ack-grep</em>).</p>\n\n<p>It's just a Perl program, so it's also available in a single-file version that you can just download and run. See: <a href=\"http://beyondgrep.com/install/\" rel=\"noreferrer\">Ack Install</a></p>\n"
},
{
"answer_id": 23657918,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "<h3><code>ex</code></h3>\n\n<p>Try using <a href=\"https://en.wikipedia.org/wiki/Ex_%28text_editor%29\" rel=\"noreferrer\">Ex editor</a> (part of Vim):</p>\n\n<pre><code>$ ex +'bufdo!%s/\\s\\+$//e' -cxa **/*.*\n</code></pre>\n\n<p><sup>Note: For recursion (bash4 & zsh), we use <a href=\"https://stackoverflow.com/q/4438306/55075\">a new globbing option</a> (<code>**/*.*</code>). Enable by <code>shopt -s globstar</code>.</sup></p>\n\n<p>You may add the following function into your <code>.bash_profile</code>:</p>\n\n<pre><code># Strip trailing whitespaces.\n# Usage: trim *.*\n# See: https://stackoverflow.com/q/10711051/55075\ntrim() {\n ex +'bufdo!%s/\\s\\+$//e' -cxa $*\n}\n</code></pre>\n\n<h3><code>sed</code></h3>\n\n<p>For using <code>sed</code>, check: <a href=\"https://stackoverflow.com/q/4438306/55075\">How to remove trailing whitespaces with sed?</a></p>\n\n<h3><code>find</code></h3>\n\n<p>Find the following script (e.g. <code>remove_trail_spaces.sh</code>) for removing trailing whitespaces from the files:</p>\n\n<pre><code>#!/bin/sh\n# Script to remove trailing whitespace of all files recursively\n# See: https://stackoverflow.com/questions/149057/how-to-remove-trailing-whitespace-of-all-files-recursively\n\ncase \"$OSTYPE\" in\n darwin*) # OSX 10.5 Leopard, which does not use GNU sed or xargs.\n find . -type f -not -iwholename '*.git*' -print0 | xargs -0 sed -i .bak -E \"s/[[:space:]]*$//\"\n find . -type f -name \\*.bak -print0 | xargs -0 rm -v\n ;;\n *)\n find . -type f -not -iwholename '*.git*' -print0 | xargs -0 perl -pi -e 's/ +$//'\nesac\n</code></pre>\n\n<p>Run this script from the directory which you want to scan. On OSX at the end, it will remove all the files ending with <code>.bak</code>.</p>\n\n<p>Or just:</p>\n\n<pre><code>find . -type f -name \"*.java\" -exec perl -p -i -e \"s/[ \\t]$//g\" {} \\;\n</code></pre>\n\n<p>which is recommended way by <a href=\"https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-Code-Style\" rel=\"noreferrer\">Spring Framework Code Style</a>.</p>\n"
},
{
"answer_id": 25131751,
"author": "grosser",
"author_id": 110333,
"author_profile": "https://Stackoverflow.com/users/110333",
"pm_score": 2,
"selected": false,
"text": "<p>Ruby:</p>\n\n<pre><code>irb\nDir['lib/**/*.rb'].each{|f| x = File.read(f); File.write(f, x.gsub(/[ \\t]+$/,\"\")) }\n</code></pre>\n"
},
{
"answer_id": 40371757,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 2,
"selected": false,
"text": "<p>1) Many other answers use <code>-E</code>. I am not sure why, as that's <a href=\"https://stackoverflow.com/questions/3139126/whats-the-difference-between-sed-e-and-sed-e\">undocumented BSD compatibility</a> option. <code>-r</code> should be used instead.</p>\n\n<p>2) Other answers use <code>-i ''</code>. That should be just <code>-i</code> (or <code>-i''</code> if preffered), because <code>-i</code> has the suffix right after. </p>\n\n<p>3) Git specific solution:</p>\n\n<pre><code>git config --global alias.check-whitespace \\\n'git diff-tree --check $(git hash-object -t tree /dev/null) HEAD'\n\ngit check-whitespace | grep trailing | cut -d: -f1 | uniq -u -z | xargs -0 sed --in-place -e 's/[ \\t]+$//'\n</code></pre>\n\n<p>The first one registers a git alias <code>check-whitespace</code> which lists the files with trailing whitespaces.\nThe second one runs <code>sed</code> on them.</p>\n\n<p>I only use <code>\\t</code> rather than <code>[:space:]</code> as I don't typically see vertical tabs, form feeds and non-breakable spaces. Your measurement may vary.</p>\n"
},
{
"answer_id": 57334826,
"author": "roedeercuco",
"author_id": 10175885,
"author_profile": "https://Stackoverflow.com/users/10175885",
"pm_score": 2,
"selected": false,
"text": "<p>I use regular expressions. 4 steps:</p>\n\n<ol>\n<li>Open the root folder in your editor (I use Visual Studio Code).</li>\n<li>Tap the Search icon on the left, and enable the regular expression mode.</li>\n<li>Enter \" +\\n\" in the Search bar and \"\\n\" in the Replace bar.</li>\n<li>Click \"Replace All\".</li>\n</ol>\n\n<p>This removes all trailing spaces at the end of each line in all files. And you can exclude some files that don't fit with this need.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19718/"
]
| How can you remove all of the trailing whitespace of an entire project? Starting at a root directory, and removing the trailing whitespace from all files in all folders.
Also, I want to to be able to modify the file directly, and not just print everything to stdout. | Here is an OS X >= 10.6 Snow Leopard solution.
**It Ignores .git and .svn folders** and their contents. Also it won't leave a backup file.
```
(export LANG=C LC_CTYPE=C
find . -not \( -name .svn -prune -o -name .git -prune \) -type f -print0 | perl -0ne 'print if -T' | xargs -0 sed -Ei 's/[[:blank:]]+$//'
)
```
The enclosing parenthesis preserves the `L*` variables of current shell – executing in subshell. |
149,073 | <p>I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:</p>
<pre><code>public function PrintStackTrace() {
try {
throw new Error('StackTrace');
} catch (e:Error) {
trace(e.getStackTrace());
}
}
</code></pre>
<p>I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.</p>
<p>Thanks!</p>
| [
{
"answer_id": 149188,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 7,
"selected": true,
"text": "<p>As far as I know, the only way to make the stack trace available to your own code is via the <a href=\"http://livedocs.adobe.com/flex/3/langref/Error.html#getStackTrace()\" rel=\"noreferrer\">getStackTrace()</a> method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it:</p>\n\n<pre><code>var tempError:Error = new Error();\nvar stackTrace:String = tempError.getStackTrace();\n</code></pre>\n\n<p>Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/system/Capabilities.html#isDebugger\" rel=\"noreferrer\">Capabilities.isDebugger</a> if you want.</p>\n"
},
{
"answer_id": 3925218,
"author": "Joony",
"author_id": 448287,
"author_profile": "https://Stackoverflow.com/users/448287",
"pm_score": 3,
"selected": false,
"text": "<p>Use the Flex DeBugger (FDB) that comes with the Flex SDK. It's a command-line debugger that allows you to debug .swf, even ones online (if it's a debug version). It allows you to set break-points, print/change variables, and dump the stack, and <b>does not require you to add any extra code</b>. A very useful tool that you shouldn't be without!</p>\n\n<p>The fdb options you will need are 'break' and to specify the class and line where you want execution to halt, and 'bt' or 'info stack' to give you a backtrace of the stack. You can also display almost everything about the application while it runs.</p>\n"
},
{
"answer_id": 9157603,
"author": "plam4u",
"author_id": 774798,
"author_profile": "https://Stackoverflow.com/users/774798",
"pm_score": 2,
"selected": false,
"text": "<p>@hasseg is right. You can also preserve the stacktrace information in release version (not debug) by providing the -compiler.verbose-stacktraces=true when compiling your SWF.</p>\n"
},
{
"answer_id": 14804061,
"author": "Glen Blanchard",
"author_id": 652588,
"author_profile": "https://Stackoverflow.com/users/652588",
"pm_score": 3,
"selected": false,
"text": "<p>From Flash Player 11.5 the stack traces are also available in the non-debugger versions of the players as well.</p>\n"
},
{
"answer_id": 20659235,
"author": "gaurav_gupta",
"author_id": 1157936,
"author_profile": "https://Stackoverflow.com/users/1157936",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var tempError:Error = new Error();\nvar stackTrace:String = tempError.getStackTrace();\n</code></pre>\n\n<p>write this <code>stackTrace</code> string into any file so that you can see the logs of your program at run mode also. So you need not to run it in debugger mode only. Write it into <code>uncaughtexception</code> event of application, so it will execute lastly. </p>\n"
},
{
"answer_id": 25493160,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 1,
"selected": false,
"text": "<p>As of Flash 11.5, stack traces work in the release version of Flash.</p>\n\n<p>However, that doesn't mean this is no longer an issue. If your application is set to use a compiler older than 11.5 in <code>Flash Builder --> Project properties --> ActionScript Compiler</code>, you won't have stack traces.</p>\n\n<p>Additionally, on that same page you can see your AIR SDK version. If you're using v3.4 or older, you won't see stack traces. If this is your issue, all your developers should update their AIR SDK by following the instructions <a href=\"http://helpx.adobe.com/flash-builder/kb/overlay-air-sdk-flash-builder.html\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 36290419,
"author": "OMA",
"author_id": 732669,
"author_profile": "https://Stackoverflow.com/users/732669",
"pm_score": 2,
"selected": false,
"text": "<p>I've put together this little function:</p>\n\n<pre><code>public static function getStackTrace() : String\n{\n var aStackTrace : Array = new Error().getStackTrace().split(\"\\n\");\n aStackTrace.shift();\n aStackTrace.shift();\n return \"Stack trace: \\n\" + aStackTrace.join(\"\\n\");\n}\n</code></pre>\n\n<p>I have this function in a custom \"Debug\" class I use with my apps when developing. The two shift() calls remove the first two lines: The first one is just the string \"Error\" and the second line refers to this function itself, so it's not useful. You can even remove the third line if you wish (it refers to the line where you place the call to the getStackTrace() function) by adding another shift() call, but I left it to serve as a starting point of the \"stack trace\".</p>\n"
},
{
"answer_id": 38303128,
"author": "Andrei Tofan",
"author_id": 2464151,
"author_profile": "https://Stackoverflow.com/users/2464151",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>getStackTrace</code> method returns the stack trace only on the debug flash player (<a href=\"https://www.adobe.com/support/flashplayer/debug_downloads.html\" rel=\"nofollow\">https://www.adobe.com/support/flashplayer/debug_downloads.html</a>), on the release player returns <code>null</code>. Make sure you have the debug player installed and running.</p>\n\n<p>The <code>-compiler.verbose-stacktraces=true</code> only adds the line number to the debug stack trace.</p>\n\n<p>Sample test:\n<a href=\"https://gist.github.com/pipeno/03310d3d3cae61460ac6c590c4f355ed\" rel=\"nofollow\">https://gist.github.com/pipeno/03310d3d3cae61460ac6c590c4f355ed</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
]
| I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:
```
public function PrintStackTrace() {
try {
throw new Error('StackTrace');
} catch (e:Error) {
trace(e.getStackTrace());
}
}
```
I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.
Thanks! | As far as I know, the only way to make the stack trace available to your own code is via the [getStackTrace()](http://livedocs.adobe.com/flex/3/langref/Error.html#getStackTrace()) method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it:
```
var tempError:Error = new Error();
var stackTrace:String = tempError.getStackTrace();
```
Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of [Capabilities.isDebugger](http://livedocs.adobe.com/flex/3/langref/flash/system/Capabilities.html#isDebugger) if you want. |
149,078 | <p>Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index.</p>
<p>Now suppose I perform a query such as <code>SELECT * FROM sometable WHERE foo='hello' AND bar='world';</code> My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'.</p>
<p>So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is <code>O(n)</code> where n is the number of rows where bar is 'world'.</p>
<p>However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be <code>O(m)</code> where m is the number of rows where foo is 'hello'.</p>
<p>So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting <code>bar='world'</code> first in the <code>WHERE</code> clause?</p>
| [
{
"answer_id": 149104,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can give \"hints\" with the query to Oracle. These hints are disguised as comments (\"/* HINT */\") to the database and are mainly vendor specific. So one hint for one database will not work on an other database.</p>\n\n<p>I would use index hints here, the first hint for the small table. See <a href=\"http://www.dbasupport.com/oracle/ora9i/index_hints.shtml\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>On the other hand, if you often search over these two fields, why not create an index on these two? I do not have the right syntax, but it would be something like</p>\n\n<pre><code>CREATE INDEX IX_BAR_AND_FOO on sometable(bar,foo);\n</code></pre>\n\n<p>This way data retrieval should be pretty fast. And in case the concatenation is unique hten you simply create a unique index which should be lightning fast.</p>\n"
},
{
"answer_id": 149111,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>So is Oracle smart enough to search\n efficiently here?</p>\n</blockquote>\n\n<p>The simple answer is \"probably\". There are lots'o' very bright people at each of the database vendors working on optimizing the query optimizer, so it's probably doing things that you haven't even thought of. And if you update the statistics, it'll probably do even more.</p>\n"
},
{
"answer_id": 149115,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm sure you can also have Oracle display a query plan so you can see exactly which index is used first.</p>\n"
},
{
"answer_id": 149122,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 0,
"selected": false,
"text": "<p>You can provide hints as to which index to use. I'm not familiar with Oracle, but in Mysql you can use USE|IGNORE|FORCE_INDEX (see <a href=\"http://dev.mysql.com/doc/refman/5.1/en/index-hints.html\" rel=\"nofollow noreferrer\">here</a> for more details). For best performance though you should use a combined index.</p>\n"
},
{
"answer_id": 149140,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "<p>The best approach would be to add foo to bar's index, or add bar to foo's index (or both). If foo's index also contains an index on bar, that additional indexing level will not affect the utility of the foo index in any current uses of that index, nor will it appreciably affect the performance of maintaining that index, but it will give the database additional information to work with in optimizing queries such as in the example.</p>\n"
},
{
"answer_id": 149161,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 1,
"selected": false,
"text": "<p>It's better than that.</p>\n\n<p>Index Seeks are always quicker than full table scans. So behind the scenes Oracle (and SQL server for that matter) will first locate the range of rows on both indices. It will then look at which range is shorter (seeing that it's an inner join), and it will iterate the shorter range to find the matches with the larger of the two.</p>\n"
},
{
"answer_id": 149168,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 5,
"selected": true,
"text": "<p>Oracle will almost certainly use the most selective index to drive the query, and you can check that with the explain plan.</p>\n\n<p>Furthermore, Oracle can combine the use of both indexes in a couple of ways -- it can convert btree indexes to bitmaps and perform a bitmap ANd operation on them, or it can perform a hash join on the rowid's returned by the two indexes.</p>\n\n<p>One important consideration here might be any correlation between the values being queried. If foo='hello' accounts for 80% of values in the table and bar='world' accounts for 10%, then Oracle is going to estimate that the query will return 0.8*0.1= 8% of the table rows. However this may not be correct - the query may actually return 10% of the rwos or even 0% of the rows depending on how correlated the values are. Now, depending on the distribution of those rows throughout the table it may not be efficient to use an index to find them. You may still need to access (say) 70% or the table blocks to retrieve the required rows (google for \"clustering factor\"), in which case Oracle is going to perform a ful table scan if it gets the estimation correct.</p>\n\n<p>In 11g you can collect multicolumn statistics to help with this situation I believe. In 9i and 10g you can use dynamic sampling to get a very good estimation of the number of rows to be retrieved.</p>\n\n<p>To get the execution plan do this:</p>\n\n<pre><code>explain plan for\nSELECT *\nFROM sometable\nWHERE foo='hello' AND bar='world'\n/\nselect * from table(dbms_xplan.display)\n/\n</code></pre>\n\n<p>Contrast that with:</p>\n\n<pre><code>explain plan for\nSELECT /*+ dynamic_sampling(4) */\n *\nFROM sometable\nWHERE foo='hello' AND bar='world'\n/\nselect * from table(dbms_xplan.display)\n/\n</code></pre>\n"
},
{
"answer_id": 149185,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 2,
"selected": false,
"text": "<p>First off, I'll assume that you are talking about nice, normal, standard b*-tree indexes. The answer for bitmap indexes is radically different. And there are lots of options for various types of indexes in Oracle that may or may not change the answer.</p>\n\n<p>At a minimum, if the optimizer is able to determine the selectivity of a particular condition, it will use the more selective index (i.e. the index on bar). But if you have skewed data (there are N values in the column bar but the selectivity of any particular value is substantially more or less than 1/N of the data), you would need to have a histogram on the column in order to tell the optimizer which values are more or less likely. And if you are using bind variables (as all good OLTP developers should), depending on the Oracle version, you may have issues with bind variable peeking.</p>\n\n<p>Potentially, Oracle could even do an on the fly conversion of the two b*-tree indexes to bitmaps and combine the bitmaps in order to use both indexes to find the rows it needs to retrieve. But this is a rather unusual query plan, particularly if there are only two columns where one column is highly selective.</p>\n"
},
{
"answer_id": 179822,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Eli,</p>\n\n<p>In a comment you wrote:</p>\n\n<blockquote>\n <p>Unfortunately, I have a table with lots of columns each with their own index. Users can query any combination of fields, so I can't efficiently create indexes on each field combination. But if I did only have two fields needing indexes, I'd completely agree with your suggestion to use two indexes. – Eli Courtwright (Sep 29 at 15:51)</p>\n</blockquote>\n\n<p>This is actually rather crucial information. Sometimes programmers outsmart themselves when asking questions. They try to distill the question down to the seminal points but quite often over simplify and miss getting the best answer.</p>\n\n<p>This scenario is precisely why bitmap indexes were invented -- to handle the times when unknown groups of columns would be used in a where clause. </p>\n\n<p>Just in case someone says that BMIs are for low cardinality columns only and may not apply to your case. Low is probably not as small as you think. The only real issue is concurrency of DML to the table. Must be single threaded or rare for this to work. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
]
| Suppose I have a database table with two fields, "foo" and "bar". Neither of them are unique, but each of them are indexed. However, rather than being indexed together, they each have a separate index.
Now suppose I perform a query such as `SELECT * FROM sometable WHERE foo='hello' AND bar='world';` My table a huge number of rows for which foo is 'hello' and a small number of rows for which bar is 'world'.
So the most efficient thing for the database server to do under the hood is use the bar index to find all fields where bar is 'world', then return only those rows for which foo is 'hello'. This is `O(n)` where n is the number of rows where bar is 'world'.
However, I imagine it's possible that the process would happen in reverse, where the fo index was used and the results searched. This would be `O(m)` where m is the number of rows where foo is 'hello'.
So is Oracle smart enough to search efficiently here? What about other databases? Or is there some way I can tell it in my query to search in the proper order? Perhaps by putting `bar='world'` first in the `WHERE` clause? | Oracle will almost certainly use the most selective index to drive the query, and you can check that with the explain plan.
Furthermore, Oracle can combine the use of both indexes in a couple of ways -- it can convert btree indexes to bitmaps and perform a bitmap ANd operation on them, or it can perform a hash join on the rowid's returned by the two indexes.
One important consideration here might be any correlation between the values being queried. If foo='hello' accounts for 80% of values in the table and bar='world' accounts for 10%, then Oracle is going to estimate that the query will return 0.8\*0.1= 8% of the table rows. However this may not be correct - the query may actually return 10% of the rwos or even 0% of the rows depending on how correlated the values are. Now, depending on the distribution of those rows throughout the table it may not be efficient to use an index to find them. You may still need to access (say) 70% or the table blocks to retrieve the required rows (google for "clustering factor"), in which case Oracle is going to perform a ful table scan if it gets the estimation correct.
In 11g you can collect multicolumn statistics to help with this situation I believe. In 9i and 10g you can use dynamic sampling to get a very good estimation of the number of rows to be retrieved.
To get the execution plan do this:
```
explain plan for
SELECT *
FROM sometable
WHERE foo='hello' AND bar='world'
/
select * from table(dbms_xplan.display)
/
```
Contrast that with:
```
explain plan for
SELECT /*+ dynamic_sampling(4) */
*
FROM sometable
WHERE foo='hello' AND bar='world'
/
select * from table(dbms_xplan.display)
/
``` |
149,092 | <p>I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive.</p>
<p>The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times.</p>
<p>The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer?</p>
<p>The question is mainly about Linux, but any Win32 pointers will be more than welcome too.</p>
| [
{
"answer_id": 149840,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": -1,
"selected": false,
"text": "<p>dd(1) is your friend.</p>\n\n<p>dd if=/dev/cdrom of=image bs=2352 conv=noerror,notrunc</p>\n\n<p>The drive may still retry a bit, but I don't think you'll get any better without modifying firmware.</p>\n"
},
{
"answer_id": 150102,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 1,
"selected": false,
"text": "<p>While checking whether <code>hdparm</code> could modify the number of retries (doesn't seem so), I thought that, depending on the type of error, lowering the CD-ROM speed could potentially reduce the number of read errors, which could actually increase the average read speed. However, if some sectors are completely unreadable, then even lowering the CD-ROM speed won't help.</p>\n"
},
{
"answer_id": 150252,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>Since dd was suggested, I should note that I know of the existence and have used sg_dd, but my question was not about commands (1) or (1m), but about system calls (2) or libraries (3).</p>\n<h3>EDIT</h3>\n<p>Another linux command-line utility that is of help, is <code>sdparm</code>. The following flag seems to disable hardware retries:</p>\n<pre><code>sudo sdparm --set=RRC=0 /dev/sr0\n</code></pre>\n<p>where <code>/dev/sr0</code> is the device for the optical drive in my case.</p>\n"
},
{
"answer_id": 542057,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<p>Since you are asking about driver level access, you should look into SCSI commands, or perhaps an ASPI like API. On windows VSO software (developers of blindread/blindwrite below) have developed a much better API, Patin-Couffin, that provides locked low level access:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Patin-Couffin\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Patin-Couffin</a></p>\n\n<p>That might get you started. However, at the end of the day, the drive is interfaced with SCSI commands, even if it's actually USB, SATA, ATA, IDE, or otherwise. You might also look up terms related to ATAPI, which was one of the first specifications for this CD-ROM SCSI layer interface.</p>\n\n<p>I'd be surprised if you couldn't find a suitable linux library or example of dealing with the lower level commands using the above search terms and concepts.</p>\n\n<hr>\n\n<p>Older answer: </p>\n\n<p><a href=\"http://www.blindwrite.com/\" rel=\"nofollow noreferrer\">Blindread/blindwrite</a> was developed in the heyday of cd-rom protection schemes often using intentionally bad sectors or error information to verify the original CD.</p>\n\n<p>It will allow you to set a whole slew of parameters, including retries. Keep in mind that the CD-ROM drive itself determines how many times to retry, and I'm not sure that this is settable via software for many (most?) CD-ROM drives.</p>\n\n<p>You can copy the disk to ISO format, ignoring the errors, and then use ISO utilities to read the data.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 552596,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 4,
"selected": true,
"text": "<p><code>man readom</code>, a program that comes with cdrecord:</p>\n\n<pre><code> -noerror\n Do not abort if the high level error checking in readom found an\n uncorrectable error in the data stream.\n\n -nocorr\n Switch the drive into a mode where it ignores read errors in\n data sectors that are a result of uncorrectable ECC/EDC errors\n before reading. If readom completes, the error recovery mode of\n the drive is switched back to the remembered old mode.\n ...\n\n retries=#\n Set the retry count for high level retries in readom to #. The\n default is to do 128 retries which may be too much if you like\n to read a CD with many unreadable sectors.\n</code></pre>\n"
},
{
"answer_id": 552630,
"author": "bang",
"author_id": 611084,
"author_profile": "https://Stackoverflow.com/users/611084",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://en.wikipedia.org/wiki/ASPI\" rel=\"nofollow noreferrer\">ASPI</a> interface. Available on both windows and linux.</p>\n"
},
{
"answer_id": 556871,
"author": "motobói",
"author_id": 25612,
"author_profile": "https://Stackoverflow.com/users/25612",
"pm_score": 3,
"selected": false,
"text": "<p>The best tool avaliable is dd_rhelp. Just</p>\n\n<pre><code>dd_rhelp /dev/cdrecorder /home/myself/DVD.img\n</code></pre>\n\n<p>,take a cup of tea and watch the nice graphics.</p>\n\n<p>The dd_rhelp rpm package info:</p>\n\n<blockquote>\n <p>dd_rhelp uses ddrescue on your entire disc, and attempts to gather the maximum\n valid data before trying for ages on badsectors. If you leave dd_rhelp work\n for infinite time, it has a similar effect as a simple dd_rescue. But because\n you may not have this infinite time, dd_rhelp jumps over bad sectors and rescue\n valid data. In the long run, it parses all your device with dd_rescue.</p>\n \n <p>You can Ctrl-C it whenever you want, and rerun-it at will, dd_rhelp resumes the\n job as it depends on the log files dd_rescue creates. In addition, progress\n is shown in an ASCII picture of your device being rescued.</p>\n</blockquote>\n\n<p>I've used it a lot myself and Is very, very realiable.</p>\n\n<p>You can install it from DAG to Red Hat like distributions.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6899/"
]
| I have backups of files archived in optical media (CDs and DVDs). These all have par2 recovery files, stored on separate media. Even in cases where there are no par2 files, minor errors when reading on one optical drive can be read fine on another drive.
The thing is, when reading faulty media, the read time is very, very long, because devices tend to retry multiple times.
The question is: how can I control the number of retries (ie set to no retries or only one try)? Some system call? A library I can download? Do I have to work on the SCSI layer?
The question is mainly about Linux, but any Win32 pointers will be more than welcome too. | `man readom`, a program that comes with cdrecord:
```
-noerror
Do not abort if the high level error checking in readom found an
uncorrectable error in the data stream.
-nocorr
Switch the drive into a mode where it ignores read errors in
data sectors that are a result of uncorrectable ECC/EDC errors
before reading. If readom completes, the error recovery mode of
the drive is switched back to the remembered old mode.
...
retries=#
Set the retry count for high level retries in readom to #. The
default is to do 128 retries which may be too much if you like
to read a CD with many unreadable sectors.
``` |
149,102 | <p>How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column.</p>
| [
{
"answer_id": 149109,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.worksheet.selectionchange(VS.80).aspx\" rel=\"nofollow noreferrer\">Worksheet.SelectionChange</a> event to trap this.</p>\n"
},
{
"answer_id": 149121,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 3,
"selected": true,
"text": "<p>Check out the Worksheet_SelectionChange event. In that event you could use Intersect() with named ranges to figure out if a specific range were clicked.</p>\n\n<p>Here's some code that might help you get started.</p>\n\n<pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)\n If Not Intersect(Target, Range(\"SomeNamedRange\")) Is Nothing Then\n 'Your counting code \n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 149129,
"author": "Andrew Cowenhoven",
"author_id": 12281,
"author_profile": "https://Stackoverflow.com/users/12281",
"pm_score": 0,
"selected": false,
"text": "<p>Worksheet SelectionChange event would do it. Note that this fires <strong>every</strong> time user clicks a new cell. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22376/"
]
| How can I capture the event in Excel when a user clicks on a cell. I want to be able to use this event to trigger some code to count how many times the user clicks on several different cells in a column. | Check out the Worksheet\_SelectionChange event. In that event you could use Intersect() with named ranges to figure out if a specific range were clicked.
Here's some code that might help you get started.
```
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If Not Intersect(Target, Range("SomeNamedRange")) Is Nothing Then
'Your counting code
End If
End Sub
``` |
149,132 | <p>I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:</p>
<p>I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.</p>
<p>How do I do this without the use of cursors? Should be an easy one for you sql gurus!</p>
| [
{
"answer_id": 149152,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": true,
"text": "<p>This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example:</p>\n\n<pre><code>CREATE TABLE #t (uniqueid int)\nINSERT INTO #t EXEC p_YourStoredProc\n\nUPDATE TargetTable \nSET a.FlagColumn = 1\nFROM TargetTable a JOIN #t b \n ON a.uniqueid = b.uniqueid\n\nDROP TABLE #t\n</code></pre>\n"
},
{
"answer_id": 149154,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": -1,
"selected": false,
"text": "<p>An ugly solution would be to have your procedure return the \"next\" id each time it is called by using the other table (or some flag on the existing table) to filter out the rows that it has already returned</p>\n"
},
{
"answer_id": 149160,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Insert the results of the stored proc into a temporary table and join this to the table you want to update:</p>\n\n<pre><code>INSERT INTO #WorkTable\nEXEC usp_WorkResults\n\nUPDATE DataTable\n SET Flag = Whatever\nFROM DataTable\nINNER JOIN #WorkTable\n ON DataTable.Ket = #WorkTable.Key\n</code></pre>\n"
},
{
"answer_id": 149177,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 0,
"selected": false,
"text": "<p>Use temporary tables or a table variable (you are using SS2005). </p>\n\n<p>Although, that's not nest-able - if a stored proc uses that method then you can't dumpt that output into a temp table. </p>\n"
},
{
"answer_id": 149179,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": -1,
"selected": false,
"text": "<p>You can use a temp table or table variable with an additional column:</p>\n\n<pre><code>DECLARE @MyTable TABLE (\n Column1 uniqueidentifer,\n ...,\n Checked bit\n)\n\nINSERT INTO @MyTable\nSELECT [...], 0 FROM MyTable WHERE [...]\n\nDECLARE @Continue bit\nSET @Continue = 1\nWHILE (@Continue)\nBEGIN\n SELECT @var1 = Column1,\n @var2 = Column2,\n ...\n FROM @MyTable\n WHERE Checked = 1\n\n IF @var1 IS NULL\n SET @Continue = 0\n ELSE\n BEGIN\n\n ...\n\n UPDATE @MyTable SET Checked = 1 WHERE Column1 = @var1\n END\nEND\n</code></pre>\n\n<p>Edit: Actually, in your situation a join will be better; the code above is a cursorless iteration, which is overkill for your situation.</p>\n"
},
{
"answer_id": 149192,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>If you upgrade to SQL 2008 then you can pass table parameters I believe. Otherwise, you're stuck with a global temporary table or creating a permanent table that includes a column for some sort of process ID to identify which call to the stored procedure is relevant.</p>\n\n<p>How much room do you have in changing the stored procedure that generates the IDs? You could add code in there to handle it or have a parameter that lets you optionally flag the rows when it is called.</p>\n"
},
{
"answer_id": 151567,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 2,
"selected": false,
"text": "<p>You could also change your stored proc to a user-defined function that returns a table with your uniqueidentifiers. You can joing directly to the UDF and treat it like a table which avoids having to create the extra temp table explicitly. Also, you can pass parameters into the function as you're calling it, making this a very flexible solution.</p>\n\n<pre><code>CREATE FUNCTION dbo.udfGetUniqueIDs\n()\nRETURNS TABLE \nAS\nRETURN \n(\n SELECT uniqueid FROM dbo.SomeWhere\n)\n\nGO\n\nUPDATE dbo.TargetTable \nSET a.FlagColumn = 1\nFROM dbo.TargetTable a INNER JOIN dbo.udfGetUniqueIDs() b \n ON a.uniqueid = b.uniqueid\n</code></pre>\n\n<p><b>Edit:</b>\nThis will work on SQL Server 2000 and up...</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
| I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:
I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.
How do I do this without the use of cursors? Should be an easy one for you sql gurus! | This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example:
```
CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc
UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
ON a.uniqueid = b.uniqueid
DROP TABLE #t
``` |
149,153 | <p>I'm trying to create a ImageIcon from a animated gif stored in a jar file.</p>
<pre><code>ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
</code></pre>
<p>The image loads, but only the first frame of the animated gif. The animation does not play. </p>
<p>If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:</p>
<pre><code>ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
</code></pre>
<p>How can I load an animated gif into an ImageIcon from a jar file?</p>
<p>EDIT: Here is a complete test case, why doesn't this display the animation?</p>
<pre><code>import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
| [
{
"answer_id": 149182,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>You have to use getClass().getResource(imgName); to get a URL to the image file. Check out <a href=\"http://www.rgagnon.com/javadetails/java-0240.html\" rel=\"noreferrer\">this tutorial</a> from Real's HowTo.</p>\n\n<p>EDIT: Once the image is loaded you have to <a href=\"http://java.sun.com/javase/6/docs/api/javax/swing/ImageIcon.html#setImageObserver(java.awt.image.ImageObserver)\" rel=\"noreferrer\">set the ImageObserver property</a> to get the animation to run.</p>\n"
},
{
"answer_id": 5444422,
"author": "Andrew Thompson",
"author_id": 418556,
"author_profile": "https://Stackoverflow.com/users/418556",
"pm_score": 2,
"selected": false,
"text": "<p>Since this thread was just linked from a more current thread that had little to do with animated GIFs but got dragged OT, I thought I'd add this trivial source that 'works for me'.</p>\n\n<pre><code>import javax.swing.*;\nimport java.net.URL;\n\nclass AnimatedGifInLabel {\n\n public static void main(String[] args) throws Exception {\n final URL url = new URL(\"http://i.stack.imgur.com/OtTIY.gif\");\n Runnable r = new Runnable() {\n public void run() {\n ImageIcon ii = new ImageIcon(url);\n JLabel label = new JLabel(ii);\n JOptionPane.showMessageDialog(null, label);\n }\n };\n SwingUtilities.invokeLater(r);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6504520,
"author": "Penkov Vladimir",
"author_id": 555830,
"author_profile": "https://Stackoverflow.com/users/555830",
"pm_score": 4,
"selected": true,
"text": "<p>This reads gif animation from inputStream</p>\n\n<pre><code>InputStream in = ...;\nImage image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));\n</code></pre>\n"
},
{
"answer_id": 15166546,
"author": "Paulo Pedroso",
"author_id": 1474815,
"author_profile": "https://Stackoverflow.com/users/1474815",
"pm_score": 1,
"selected": false,
"text": "<p>Hopefully it's not too late for this.</p>\n\n<p>I managed to get the animated gif inside my JPanel this way:</p>\n\n<pre><code>private JPanel loadingPanel() {\n JPanel panel = new JPanel();\n BoxLayout layoutMgr = new BoxLayout(panel, BoxLayout.PAGE_AXIS);\n panel.setLayout(layoutMgr);\n\n ClassLoader cldr = this.getClass().getClassLoader();\n java.net.URL imageURL = cldr.getResource(\"img/spinner.gif\");\n ImageIcon imageIcon = new ImageIcon(imageURL);\n JLabel iconLabel = new JLabel();\n iconLabel.setIcon(imageIcon);\n imageIcon.setImageObserver(iconLabel);\n\n JLabel label = new JLabel(\"Loading...\");\n panel.add(iconLabel);\n panel.add(label);\n return panel;\n}\n</code></pre>\n\n<p>Some points of this approach:<br>\n1. The image file is within the jar;<br>\n2. ImageIO.read() returns a BufferedImage, which doesn't update the ImageObserver;<br>\n3. Another alternative to find images that are bundled in the jar file is to ask the Java class loader, the code that loaded your program, to get the files. It knows where things are.<br><br></p>\n\n<p>So by doing this I was able to get my animated gif inside my JPanel and it worked like a charm.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739/"
]
| I'm trying to create a ImageIcon from a animated gif stored in a jar file.
```
ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));
```
The image loads, but only the first frame of the animated gif. The animation does not play.
If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:
```
ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");
```
How can I load an animated gif into an ImageIcon from a jar file?
EDIT: Here is a complete test case, why doesn't this display the animation?
```
import javax.imageio.ImageIO;
import javax.swing.*;
public class AnimationTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AnimationTest test = new AnimationTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setVisible(true);
}
});
}
public AnimationTest() {
super();
try {
JLabel label = new JLabel();
ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
label.setIcon(imageIcon);
imageIcon.setImageObserver(label);
add(label);
pack();
} catch (Exception e) {
e.printStackTrace();
}
}
}
``` | This reads gif animation from inputStream
```
InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
``` |
149,191 | <p>I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function:</p>
<pre><code>function Return-True { return $true }
</code></pre>
<p>and then some sample code to invoke it:</p>
<pre><code>PS C:\> Return-True
True
PS C:\> Return-True -eq $false
True
PS C:\> (Return-True) -eq $false
False
</code></pre>
<p>Ideas? Comments? </p>
| [
{
"answer_id": 149373,
"author": "hurcane",
"author_id": 21363,
"author_profile": "https://Stackoverflow.com/users/21363",
"pm_score": 3,
"selected": false,
"text": "<p>The second line is not doing a boolean evaluation. Look at what happens if you do the same thing with strings.</p>\n\n<pre><code>PS C:\\> function Return-True { return \"True string\" }\nPS C:\\> Return-True\nTrue string\nPS C:\\> Return-True -eq \"False string\"\nTrue string\nPS C:\\> (Return-True) -eq \"False string\"\nFalse\n</code></pre>\n\n<p>The second line is simply returning the value of the function, and not doing a comparison. I'm not sure exactly why this behavior is happening, but it makes the behavior easier to see than when using boolean values that are being converted to the strings \"True\" and \"False\".</p>\n"
},
{
"answer_id": 149376,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 6,
"selected": true,
"text": "<p>When PowerShell sees the token <code>Return-True</code> it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function <code>Return-True</code>.</p>\n\n<p>You can see this in action if you do:</p>\n\n<pre><code>PS > function Return-True { \"The arguments are: $args\"; return $true }\nPS > Return-True -eq $false\nThe arguments are: -eq False\nTrue\n</code></pre>\n\n<p>That's why all of the following return 'True', because all you are seeing is the result of calling <code>Return-True</code> with various arguments:</p>\n\n<pre><code>PS > Return-True -eq $false\nTrue\nPS > Return-True -ne $false\nTrue\nPS > Return-True -eq $true\nTrue\nPS > Return-True -ne $true\nTrue\n</code></pre>\n\n<p>Using <code>(Return-True)</code> forces PowerShell to evaluate the function (with no arguments).</p>\n"
},
{
"answer_id": 957587,
"author": "mrwaim",
"author_id": 97909,
"author_profile": "https://Stackoverflow.com/users/97909",
"pm_score": 3,
"selected": false,
"text": "<p>If you use PowerShell V2's editor, you would see that \n-eq in the first example is blue, because it is an argument\nand -eq in the second example is gray because it is an operator</p>\n\n<p>Also in V2, you can be strict about arguments, with CmdletBinding and param</p>\n\n<pre><code>function Return-True\n{\n [CmdletBinding()]\n param()\n return $true\n}\nReturn-True -eq $false\n\nReturn-True -eq $false\nReturn-True : A parameter cannot be found that matches parameter name 'eq'.\nAt line:7 char:16\n+ Return-True -eq <<<< $false\n + CategoryInfo : InvalidArgument: (:) [Return-True], ParameterBindingException\n + FullyQualifiedErrorId : NamedParameterNotFound,Return-True\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243/"
]
| I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function:
```
function Return-True { return $true }
```
and then some sample code to invoke it:
```
PS C:\> Return-True
True
PS C:\> Return-True -eq $false
True
PS C:\> (Return-True) -eq $false
False
```
Ideas? Comments? | When PowerShell sees the token `Return-True` it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function `Return-True`.
You can see this in action if you do:
```
PS > function Return-True { "The arguments are: $args"; return $true }
PS > Return-True -eq $false
The arguments are: -eq False
True
```
That's why all of the following return 'True', because all you are seeing is the result of calling `Return-True` with various arguments:
```
PS > Return-True -eq $false
True
PS > Return-True -ne $false
True
PS > Return-True -eq $true
True
PS > Return-True -ne $true
True
```
Using `(Return-True)` forces PowerShell to evaluate the function (with no arguments). |
149,198 | <p>I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system. </p>
<p>What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.</p>
<p>I heard Git supports this, please let me know if this is correct.</p>
| [
{
"answer_id": 149270,
"author": "Nicholas Riley",
"author_id": 6372,
"author_profile": "https://Stackoverflow.com/users/6372",
"pm_score": 6,
"selected": true,
"text": "<p>Mercurial can do this with the <a href=\"https://www.mercurial-scm.org/wiki/RecordExtension\" rel=\"nofollow noreferrer\">record</a> extension.</p>\n\n<p>It'll prompt you for each file and each diff hunk. For example:</p>\n\n<pre><code>% hg record\ndiff --git a/prelim.tex b/prelim.tex\n2 hunks, 4 lines changed\nexamine changes to 'prelim.tex'? [Ynsfdaq?] \n@@ -12,7 +12,7 @@\n \\setmonofont[Scale=0.88]{Consolas}\n % missing from xunicode.sty\n \\DeclareUTFcomposite[\\UTFencname]{x00ED}{\\'}{\\i}\n-\\else\n+\\else foo\n \\usepackage[pdftex]{graphicx}\n \\fi\n\nrecord this change to 'prelim.tex'? [Ynsfdaq?] \n@@ -1281,3 +1281,5 @@\n %% Local variables:\n %% mode: latex\n %% End:\n+\n+foo\n\\ No newline at end of file\nrecord this change to 'prelim.tex'? [Ynsfdaq?] n\nWaiting for Emacs...\n</code></pre>\n\n<p>After the commit, the remaining diff will be left behind:</p>\n\n<pre><code>% hg di\ndiff --git a/prelim.tex b/prelim.tex\n--- a/prelim.tex\n+++ b/prelim.tex\n@@ -1281,3 +1281,5 @@\n %% Local variables:\n %% mode: latex\n %% End:\n+\n+foo\n\\ No newline at end of file\n</code></pre>\n\n<p>Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too.</p>\n\n<p><strong>Update:</strong> Also try the <a href=\"http://bitbucket.org/edgimar/crecord/wiki/Home\" rel=\"nofollow noreferrer\">crecord</a> extension, which provides a curses interface to hunk/line selection.</p>\n\n<p><img src=\"https://i.stack.imgur.com/wRcie.png\" alt=\"crecord screenshot\"></p>\n"
},
{
"answer_id": 149283,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend not working like this. </p>\n\n<p>If you have to sets of changes, set A which is ready to check in and set B which is not ready yet, how can you be sure that only checking in set A will not break your build/tests? You may miss some lines, forget about lines in a different file, or not realize a dependency that A has on B breaking the build for others.</p>\n\n<p>Your commits should be discreet atomic changes that don't break the build for you <em>or others</em> on you team. If you are partially committing a file you are greatly increasing the chances you will break the build for others without knowing about it until you've got some unhappy coworker knocking on your door.</p>\n\n<p>The big question is, why do you feel the need to work this way?</p>\n"
},
{
"answer_id": 151052,
"author": "Ted Naleid",
"author_id": 8912,
"author_profile": "https://Stackoverflow.com/users/8912",
"pm_score": 3,
"selected": false,
"text": "<p>I asked a <a href=\"https://stackoverflow.com/questions/125272/using-mercurial-whats-the-easiest-way-to-commit-and-push-a-single-file-while-le\">similar question</a> just a little while ago, and the resulting answer of using the <a href=\"https://www.mercurial-scm.org/wiki/ShelveExtension\" rel=\"nofollow noreferrer\">hgshelve extension</a> was exactly what I was looking for.</p>\n\n<p>Before you do a commit, you can put changes from different files (or hunks of changes within a file) on the \"shelf\" and then commit the things you want. Then you can unshelve the changes you didn't commit and continue working.</p>\n\n<p>I've been using it the past few days and like it a lot. Very easy to visualize and use.</p>\n"
},
{
"answer_id": 151784,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, git allows you to do this. The <code>git add</code> command has a <code>-p</code> (or <code>--patch</code>) option that allows you to review your changes hunk-by-hunk, select which to stage (you can also refine the hunks or, edit the patches in place). You can also use the interactive mode to git-add (<code>git add -i</code>) and use the \"p\" option.</p>\n\n<p>Here's a <a href=\"http://gitcasts.com/posts/interactive-adding\" rel=\"noreferrer\">screencast on interactive adding</a> which also demonstrates the patch feature of <code>git add</code>.</p>\n"
},
{
"answer_id": 2357486,
"author": "Hauge",
"author_id": 17368,
"author_profile": "https://Stackoverflow.com/users/17368",
"pm_score": 3,
"selected": false,
"text": "<p>Check out TortoiseHG, which will do hunk selection and let you commit different changes to one file as to different commits. </p>\n\n<p>It will even let you commit all changes to some files together with partial changes to other files in one commit.</p>\n\n<p><a href=\"http://tortoisehg.bitbucket.io/\" rel=\"nofollow noreferrer\">http://tortoisehg.bitbucket.io/</a></p>\n"
},
{
"answer_id": 46101985,
"author": "Oly",
"author_id": 5181199,
"author_profile": "https://Stackoverflow.com/users/5181199",
"pm_score": 2,
"selected": false,
"text": "<p>Mercurial now provides an option <code>--interactive</code> (or <code>-i</code>) to the <code>commit</code> command, which enables this functionality right out of the box.</p>\n\n<p>This works directly from the command-line so it's perfect if you are a command-line enthusiast!</p>\n\n<p>Running</p>\n\n<pre><code>> hg commit -i\n</code></pre>\n\n<p>begins an interactive session which allows examination, editing and recording of individual changes to create a commit.</p>\n\n<p>This behaves very similarly to the <code>--patch</code> and <code>--interactive</code> options for the <code>git add</code> and <code>git commit</code> commands.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752/"
]
| I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system.
What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.
I heard Git supports this, please let me know if this is correct. | Mercurial can do this with the [record](https://www.mercurial-scm.org/wiki/RecordExtension) extension.
It'll prompt you for each file and each diff hunk. For example:
```
% hg record
diff --git a/prelim.tex b/prelim.tex
2 hunks, 4 lines changed
examine changes to 'prelim.tex'? [Ynsfdaq?]
@@ -12,7 +12,7 @@
\setmonofont[Scale=0.88]{Consolas}
% missing from xunicode.sty
\DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i}
-\else
+\else foo
\usepackage[pdftex]{graphicx}
\fi
record this change to 'prelim.tex'? [Ynsfdaq?]
@@ -1281,3 +1281,5 @@
%% Local variables:
%% mode: latex
%% End:
+
+foo
\ No newline at end of file
record this change to 'prelim.tex'? [Ynsfdaq?] n
Waiting for Emacs...
```
After the commit, the remaining diff will be left behind:
```
% hg di
diff --git a/prelim.tex b/prelim.tex
--- a/prelim.tex
+++ b/prelim.tex
@@ -1281,3 +1281,5 @@
%% Local variables:
%% mode: latex
%% End:
+
+foo
\ No newline at end of file
```
Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too.
**Update:** Also try the [crecord](http://bitbucket.org/edgimar/crecord/wiki/Home) extension, which provides a curses interface to hunk/line selection.
 |
149,206 | <p>I have a XML response from an HTTPService call with the e4x result format.</p>
<pre>
<code>
<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />
</code>
</pre>
<p>I have tried:</p>
<pre>
<code>
private function callback(event:ResultEvent):void {
if(event.result..@Error) {
// error attr present
}
else {
// error attr not present
}
}
</code>
</pre>
<p>This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.</p>
<p><b>EDIT:</b> I have also tried to compare the attribute to null and an empty string without such success...</p>
| [
{
"answer_id": 149291,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "<p>I have figured out a solution, I'm still interested if there is a better way to do this...</p>\n\n<p>This will work:</p>\n\n<pre>\n<code>\nprivate function callback(event:ResultEvent):void {\n if(event.result.attribute(\"Error\").length()) {\n // error attr present\n }\n else {\n // error attr not present\n }\n}\n</code>\n</pre>\n"
},
{
"answer_id": 149316,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming that in your example <code>event.result</code> is an <code>XML</code> object the contents of which are exactly as you posted, this should work (due to the fact that the Validation tag is the root tag of the XML):</p>\n\n<pre><code>var error:String = event.result.@Error;\nif (error != \"\")\n // error\nelse\n // no error\n</code></pre>\n\n<p>The above example will assume that an existing <code>Error</code> attribute with an empty value should be treated as a \"no-error\" case, though, so if you want to know if the attribute <em>actually</em> exists or not, you should do this:</p>\n\n<pre><code>if (event.result.hasOwnProperty(\"@Error\"))\n // error\nelse\n // no error\n</code></pre>\n"
},
{
"answer_id": 149794,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": false,
"text": "<p>You have found the best way to do it:</p>\n\n<pre><code>event.result.attribute(\"Error\").length() > 0\n</code></pre>\n\n<p>The <code>attribute</code> method is the preferred way to retrieve attributes if you don't know if they are there or not.</p>\n"
},
{
"answer_id": 150179,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 2,
"selected": false,
"text": "<p>You can check this in the following way:</p>\n\n<pre><code>if (undefined == event.result.@Error)\n</code></pre>\n\n<p>or dynamically</p>\n\n<pre><code>if (undefined == event.result.@[attributeName])\n</code></pre>\n\n<p>Note that in your example, the two dots will retrieve all descendants on all levels so you'll get a list as a result. If there are no Error attributes, you'll get an empty list. That's why it will never equal null.</p>\n"
},
{
"answer_id": 627164,
"author": "Paul Mignard",
"author_id": 3435,
"author_profile": "https://Stackoverflow.com/users/3435",
"pm_score": 3,
"selected": false,
"text": "<p>I like this method because a.) it's painfully simple and b.) Ely Greenfield uses it. ;)</p>\n\n<pre><code>if(\"@property\" in node){//do something}\n</code></pre>\n"
},
{
"answer_id": 4019282,
"author": "Rihards",
"author_id": 374476,
"author_profile": "https://Stackoverflow.com/users/374476",
"pm_score": 0,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>if(event.result.@error[0]){\n //exists \n}\n</code></pre>\n\n<p>Easy, eh? :)</p>\n"
},
{
"answer_id": 17086830,
"author": "1.21 gigawatts",
"author_id": 441016,
"author_profile": "https://Stackoverflow.com/users/441016",
"pm_score": 2,
"selected": false,
"text": "<p>I like to use the following syntax to check because it's easy to read, less typing and it nearly tied as the fastest method: </p>\n\n<pre><code>if (\"@style\" in item) // do something\n</code></pre>\n\n<p>To assign a value back to that attribute when you don't know the name of it before hand use the <code>attribute</code> method:</p>\n\n<pre><code>var attributeName:String = \"style\";\nvar attributeWithAtSign:String = \"@\" + attributeName;\nvar item:XML = <item style=\"value\"/>;\nvar itemNoAttribute:XML = <item />;\n\nif (attributeWithAtSign in itemNoAttribute) {\n trace(\"should not be here if attribute is not on the xml\");\n}\nelse {\n trace(attributeName + \" not found in \" + itemNoAttribute);\n}\n\nif (attributeWithAtSign in item) {\n item.attribute(attributeName)[0] = \"a new value\";\n}\n</code></pre>\n\n<hr>\n\n<p>All of the following are ways to test if an attribute exists gathered from the answers listed on this question. Since there were so many I ran each in the 11.7.0.225 debug player. The value on the right is the method used. The value on the left is the lowest time in milliseconds it takes when running the code one million times. Here are the results: </p>\n\n<pre><code>807 item.hasOwnProperty(\"@style\")\n824 \"@style\" in item\n1756 item.@style[0]\n2166 (undefined != item.@[\"style\"])\n2431 (undefined != item[\"@style\"])\n3050 XML(item).attribute(\"style\").length()>0\n</code></pre>\n\n<p>Performance Test code: </p>\n\n<pre><code>var item:XML = <item value=\"value\"/>;\nvar attExists:Boolean;\nvar million:int = 1000000;\nvar time:int = getTimer();\n\nfor (var j:int;j<million;j++) {\n attExists = XML(item).attribute(\"style\").length()>0;\n attExists = XML(item).attribute(\"value\").length()>0;\n}\n\nvar test1:int = getTimer() - time; // 3242 3050 3759 3075\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = \"@style\" in item;\n attExists = \"@value\" in item;\n}\n\nvar test2:int = getTimer() - time; // 1089 852 991 824\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = (undefined != item.@[\"style\"]);\n attExists = (undefined != item.@[\"value\"]);\n}\n\nvar test3:int = getTimer() - time; // 2371 2413 2790 2166\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = (undefined != item[\"@style\"]);\n attExists = (undefined != item[\"@value\"]);\n}\n\nvar test3_1:int = getTimer() - time; // 2662 3287 2941 2431\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = item.hasOwnProperty(\"@style\");\n attExists = item.hasOwnProperty(\"@value\");\n}\n\nvar test4:int = getTimer() - time; // 900 946 960 807\n\ntime = getTimer();\n\nfor (var j:int=0;j<million;j++) {\n attExists = item.@style[0];\n attExists = item.@value[0];\n}\n\nvar test5:int = getTimer() - time; // 1838 1756 1756 1775\n</code></pre>\n"
},
{
"answer_id": 71918664,
"author": "lojolis",
"author_id": 17728701,
"author_profile": "https://Stackoverflow.com/users/17728701",
"pm_score": 0,
"selected": false,
"text": "<p>May be you can try this way</p>\n<pre><code>if (undefined == event.result.@[attributeName]);\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
]
| I have a XML response from an HTTPService call with the e4x result format.
```
<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />
```
I have tried:
```
private function callback(event:ResultEvent):void {
if(event.result..@Error) {
// error attr present
}
else {
// error attr not present
}
}
```
This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.
**EDIT:** I have also tried to compare the attribute to null and an empty string without such success... | You have found the best way to do it:
```
event.result.attribute("Error").length() > 0
```
The `attribute` method is the preferred way to retrieve attributes if you don't know if they are there or not. |
149,268 | <p>Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?</p>
| [
{
"answer_id": 149277,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "<p>Boost is a collection of C++ libraries. 10 of which are being included in tr1 of C++0x.</p>\n\n<p>You can <a href=\"http://www.boost.org/users/index.html\" rel=\"noreferrer\">get started with boost here</a>.</p>\n"
},
{
"answer_id": 149285,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": false,
"text": "<p>You get a lot of the things that are coming in C++0x. But aside from that generality, some of the better specifics are a simple <a href=\"https://stackoverflow.com/questions/130186/ie-textrange-select-method-not-working-properly\">regex library</a>, a casting library for <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm\" rel=\"nofollow noreferrer\">casting from strings to ints</a> (Lexical cast):</p>\n\n<pre><code>int iResult = 0;\ntry\n{\n iResult = lexical_cast<int>(\"4\");\n}\ncatch(bad_lexical_cast &)\n{\n cout << \"Unable to cast string to int\";\n}\n</code></pre>\n\n<p>A <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/date_time.html\" rel=\"nofollow noreferrer\">date/time library</a>, among others...</p>\n\n<pre><code>using namespace boost::gregorian;\ndate weekstart(2002,Feb,1);\ndate thursday_next = next_weekday(weekstart, Thursday); // following Thursday\n</code></pre>\n\n<p>There's also a <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/python/doc/index.html\" rel=\"nofollow noreferrer\">Python interface</a> (Boost Python), a <a href=\"http://spirit.sourceforge.net/\" rel=\"nofollow noreferrer\">lexer/parser DSL</a> (Boost Spirit):</p>\n\n<pre><code>// A grammar in C++ for equations\ngroup = '(' >> expression >> ')';\nfactor = integer | group;\nterm = factor >> *(('*' >> factor) | ('/' >> factor));\nexpression = term >> *(('+' >> term) | ('-' >> term));\n</code></pre>\n\n<p>and that's just scratching the surface...</p>\n"
},
{
"answer_id": 149290,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>Boost is a very extensive library of (usually) generic constructs that can help in almost any application. This can be shown by the fact that a lot of boost components have been included in the C++ 0x specifications. </p>\n\n<p>It is also portable across at least the major platforms, and should be portable to almost anything with a mostly standards compliant C++ compiler.</p>\n\n<p>The only warning is that there can be a lot of mingled dependencies between boost libraries, making it harder to pick out just a specific component to distribute (other than the entire boost library).</p>\n"
},
{
"answer_id": 149302,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 4,
"selected": false,
"text": "<p>You can simply read the <a href=\"http://www.boost.org/users/\" rel=\"noreferrer\">Boost Background Information</a> page to get a quick overview of why you should use Boost and what you can use it for. Worth the few minutes it takes.</p>\n"
},
{
"answer_id": 149305,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 7,
"selected": true,
"text": "<p>Boost is organized by several members of the standard committee.<br />\nSo it is a breeding ground for libraries that will be in the next standard.</p>\n<ol>\n<li>It is an extension to the STL (it fills in the bits left out)</li>\n<li>It is well documented.</li>\n<li>It is well peer-reviewed.</li>\n<li>It has high activity so bugs are found and fixed quickly.</li>\n<li>It is platform neutral and works everywhere.</li>\n<li>It is free to use.</li>\n</ol>\n<p>With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost).</p>\n<p>All that you need to do is add the following to your compilers default <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/boost_tr1/usage.html\" rel=\"noreferrer\">include search path</a>:</p>\n<pre><code><boost-install-path>/boost/tr1/tr1\n</code></pre>\n<p>Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1</p>\n<h3>For Example:</h3>\n<p>To use std::tr1::share_ptr you just need to include <memory>. This will give you all the smart pointers with one file.</p>\n"
},
{
"answer_id": 149309,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> is a collection of high quality peer reviewed C++ libraries that place emphasis on portability and correctness. It acts as the defacto proving grounds for new additions to the language and the standard library. Check out their website for more details.</p>\n"
},
{
"answer_id": 149313,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 3,
"selected": false,
"text": "<p>Boost's advantages:\nIt's widely available, will port to any modern C++ compiler or about any platform.<br>\nThe functions are platform independant, you don't have to learn a new thread design for each new framework.<br>\nIt encapsulates a lot of platfom specific functions, like filesystems in a standard way.</p>\n\n<p>It's what C++ should have shipped with! A lot of Java's popularity was that is shipped with a standard library to do prety much everything you wanted. C++ unfortunately only inherited the limited C/Unix standard functions.</p>\n"
},
{
"answer_id": 149328,
"author": "argatxa",
"author_id": 23460,
"author_profile": "https://Stackoverflow.com/users/23460",
"pm_score": 4,
"selected": false,
"text": "<p>99% portable. </p>\n\n<p>I would say that it has quite a few libraries that are really useful once you discover a need that is solved by boost. Either you code it yourself or you use a very solid library. \nHaving off the shelve source for stuff like Multi-Index, Lambda, Program Options, RegEx, SmartPtr and Tuple is amazing... </p>\n\n<p>The best thing is to spend some time going through the documentation for the different libraries and evaluating whether it could be of any use to you. </p>\n\n<p>Worthy!! </p>\n"
},
{
"answer_id": 149401,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>All of the above, plus it encourages a lot of modern, best-practice C++ techniques. It tends to improve the quality of your code.</p>\n"
},
{
"answer_id": 150599,
"author": "Jeroen Dirks",
"author_id": 7743,
"author_profile": "https://Stackoverflow.com/users/7743",
"pm_score": 4,
"selected": false,
"text": "<p>Boost is great, but just playing Devil's Advocate here are some reasons why you may not want to use Boost:</p>\n\n<ul>\n<li>Does sometimes fails to compile/work properly on old compilers.</li>\n<li>It often increases compile times more than less template-heavy approaches.</li>\n<li>Some Boost code may not do what you think that it does. Read the documentation!</li>\n<li>Template abuse can lead to unreadable error messages.</li>\n<li>Template abuse can lead to code hard to step through in the debugger.</li>\n<li>It is bleeding edge C++. The next version of Boost may no longer compile on your current (older) compiler.</li>\n</ul>\n\n<p>All of this does not mean that you should not have a look at the Boost code and get some ideas yourself even if you do not use Boost as it is.</p>\n"
},
{
"answer_id": 275293,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 2,
"selected": false,
"text": "<p><code>shared_ptr</code> and <code>weak_ptr</code>, especially in multithreaded code, are alone worth installing boost. <code>BOOST_STATIC_ASSERT</code> is also pretty cool for doing compile-time logic checking.</p>\n\n<p>The fact that a lot of the classes and utilities in boost are in headers, meaning you can get a lot of functionality without having to compile anything at all, is also a plus. Portability usually isn't a problem, unless you use an extremely old compiler. I once tried to get MPL to work with VC6 and it printed out 40,000 warnings/internal errors before exploding completely. But in general most of the library should work regardless of your platform or compiler vendor.</p>\n\n<p>Take into consideration the fact that quite a few things from Boost are already in TR1, and will most likely be in the next revision of the C++ standard library. That's a pretty big endorsement.</p>\n"
},
{
"answer_id": 457100,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Also note most of boost is templates so does not require building<br>\n(just include the correct header files). </p>\n\n<p>The few parts that do require building are optional:<br>\nThese can each be built independently thus preventing unnecessary bloat for unneeded code.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
]
| Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library? | Boost is organized by several members of the standard committee.
So it is a breeding ground for libraries that will be in the next standard.
1. It is an extension to the STL (it fills in the bits left out)
2. It is well documented.
3. It is well peer-reviewed.
4. It has high activity so bugs are found and fixed quickly.
5. It is platform neutral and works everywhere.
6. It is free to use.
With tr1 coming up soon it is nice to know that boost already has a lot of the ground covered. A lot of the libraries in tr1 are basically adapted directly from boost originals and thus have been tried and tested. The difference is that they have been moved into the std::tr1 namespace (rather than boost).
All that you need to do is add the following to your compilers default [include search path](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_tr1/usage.html):
```
<boost-install-path>/boost/tr1/tr1
```
Then when you include the standard headers boost will automatically import all the required stuff into the namespace std::tr1
### For Example:
To use std::tr1::share\_ptr you just need to include <memory>. This will give you all the smart pointers with one file. |
149,311 | <p>When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.</p>
<p><strong>Edit</strong>
When I access the value like so</p>
<pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;
</code></pre>
<p>the text box is found, but the .Text is not the user input.</p>
| [
{
"answer_id": 149392,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example: </p>\n\n<pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl(\"txtValue\") as TextBox;\n</code></pre>\n\n<p>I have used that syntax before and it works like a charm.</p>\n"
},
{
"answer_id": 149398,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": true,
"text": "<p>Did you turn off ViewState?\nDid you add control programmatically in the template? If so, did you create them at the correct stage?</p>\n"
},
{
"answer_id": 149460,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 0,
"selected": false,
"text": "<p>Moved post-back data-bind to Page_Init</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
]
| When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.
**Edit**
When I access the value like so
```
TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;
```
the text box is found, but the .Text is not the user input. | Did you turn off ViewState?
Did you add control programmatically in the template? If so, did you create them at the correct stage? |
149,324 | <p>Is there a way set flags on a per-file basis with automake?<br>
In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?</p>
<p>I tried something like:</p>
<pre><code>CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
</code></pre>
<p>but it didn't work.</p>
<p>EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).</p>
| [
{
"answer_id": 149642,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>You've got confused - that section is referring to options to automake itself.</p>\n\n<p>It's a way of setting the automake command-line options:</p>\n\n<blockquote>\n <p>-W CATEGORY\n --warnings=category\n Output warnings falling in category. category can be one of:</p>\n\n<pre><code>gnu\n warnings related to the GNU Coding Standards (see Top).\nobsolete\n obsolete features or constructions\noverride\n user redefinitions of Automake rules or variables\nportability\n portability issues (e.g., use of make features that are known to be not portable)\nsyntax\n weird syntax, unused variables, typos\nunsupported\n unsupported or incomplete features\nall\n all the warnings\nnone\n turn off all the warnings\nerror\n treat warnings as errors \n</code></pre>\n \n <p>A category can be turned off by prefixing its name with ‘no-’.\n For instance, -Wno-syntax will hide the\n warnings about unused variables.</p>\n \n <p>The categories output by default are ‘syntax’ and ‘unsupported’.\n Additionally, ‘gnu’ and ‘portability’\n are enabled in --gnu and --gnits\n strictness.</p>\n \n <p>The environment variable WARNINGS can contain a comma separated list of\n categories to enable. It will be taken\n into account before the command-line\n switches, this way -Wnone will also\n ignore any warning category enabled by\n WARNINGS. This variable is also used\n by other tools like autoconf; unknown\n categories are ignored for this\n reason.</p>\n</blockquote>\n\n<p>The per-file listed in section 17 refers to per-Makefile not source file.</p>\n\n<p>I'm not aware of any per-source file flag setting, but you can set the option for each result binary with:</p>\n\n<pre><code>binaryname_CXXFLAGS\n</code></pre>\n"
},
{
"answer_id": 201418,
"author": "adl",
"author_id": 27835,
"author_profile": "https://Stackoverflow.com/users/27835",
"pm_score": 4,
"selected": true,
"text": "<p>Automake only supports per-target flags, while you want per-object flags. One way around is to create a small library that contains your object: </p>\n\n<pre><code>CXXFLAGS = -Wall ...\nbin_PROGRAMS = test\ntest_SOURCES = main.cpp\ntest_LDADD = libutility.a\nnoinst_LIBRARIES = libutility.a\nlibutility_a_SOURCES = utility.cpp\nlibutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value\n</code></pre>\n"
},
{
"answer_id": 12371346,
"author": "Andrey Starodubtsev",
"author_id": 814297,
"author_profile": "https://Stackoverflow.com/users/814297",
"pm_score": 4,
"selected": false,
"text": "<p>You can't do this with <code>automake</code>... but <em>can do</em> with <code>make</code> =) Add following line to your <code>Makefile.am</code>:</p>\n\n<pre><code>utility.$(OBJEXT) : CXXFLAGS += -Wno-unused-value\n</code></pre>\n\n<p>See <a href=\"http://www.gnu.org/software/make/manual/html_node/Target_002dspecific.html#Target_002dspecific\" rel=\"nofollow noreferrer\">GNU Make documentation : Target-specific Variable Values</a> for details.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
]
| Is there a way set flags on a per-file basis with automake?
In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?
I tried something like:
```
CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
```
but it didn't work.
EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder). | Automake only supports per-target flags, while you want per-object flags. One way around is to create a small library that contains your object:
```
CXXFLAGS = -Wall ...
bin_PROGRAMS = test
test_SOURCES = main.cpp
test_LDADD = libutility.a
noinst_LIBRARIES = libutility.a
libutility_a_SOURCES = utility.cpp
libutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
``` |
149,337 | <p>Is it possible to create a .NET equivalent to the following code?</p>
<pre><code><?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
</code></pre>
<p>I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.</p>
<hr>
<p>All I want is this:</p>
<p><img src="https://i.stack.imgur.com/IJE1b.png" alt="https://i.stack.imgur.com/IJE1b.png"></p>
| [
{
"answer_id": 149353,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can add to web.config and use forms authentication. I dont know php, so i cant help witjh the rest of your question</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx</a>\\</p>\n"
},
{
"answer_id": 149383,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, you can specify credentials in the web.config. ASP.NET also has a built-in membership system and has controls like Login to work with it - although this is different from setting static credentials in the web.config.</p>\n\n<p>I think the easiest way to do what you're talking about is to protect the directory in IIS.</p>\n"
},
{
"answer_id": 149390,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>I typically do my own authentication is asp.net against my own username and passwords in a database. For the way I do it, I create a username and password dialog on a page, and have a login button. During postback i do something like:</p>\n\n<pre><code>if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))\n{\n FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);\n}\n</code></pre>\n\n<p>Do with that in mind all you need to do is the same, check the username and password against whatveer you want, you can even hardcode if you want buy i wouldnt recommend it. \\if its valid use the formsauthentication class's static methods.</p>\n"
},
{
"answer_id": 149440,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>I am afraid I cant help you. I dont know how to get a dialog like that besides using a different security setup in IIS, such as integrated security (windows security). If that is all you want then you need to go into IIS and disable anonymous access, enable another auth type, such as integrated, basic,, and in your code you can verify they are logged in by checking:</p>\n\n<pre><code>System.Security.Principal.WindowsIdentity.GetCurrent().IsAuthenticated\n</code></pre>\n\n<p>Although IIS takes care of verification in this case. Other than that i cant help you out.</p>\n\n<p>In case you need it, a link to windows auth in asp.net: <a href=\"http://msdn.microsoft.com/en-us/library/ms998358.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms998358.aspx</a></p>\n"
},
{
"answer_id": 149476,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way to achieve the same as with the PHP code would be to directly send the same headers via <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendheader(VS.80).aspx\" rel=\"nofollow noreferrer\">Reponse.AppendHeader()</a>.</p>\n\n<p>Still I would suggest you to read an <a href=\"http://www.asp.net/Learn/Security/\" rel=\"nofollow noreferrer\">ASP.NET Forms Authentication Tutorial</a>.</p>\n"
},
{
"answer_id": 150244,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 2,
"selected": false,
"text": "<p>You need to implement basic authentication in ASP.NET not forms authentication as the above responders said. A good example <a href=\"http://www.codeproject.com/KB/aspnet/mybasicauthentication.aspx\" rel=\"nofollow noreferrer\">can be found here </a>.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795/"
]
| Is it possible to create a .NET equivalent to the following code?
```
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
```
I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.
---
All I want is this:
 | The easiest way to achieve the same as with the PHP code would be to directly send the same headers via [Reponse.AppendHeader()](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendheader(VS.80).aspx).
Still I would suggest you to read an [ASP.NET Forms Authentication Tutorial](http://www.asp.net/Learn/Security/). |
149,379 | <p>I want to create Code39 encoded barcodes from my application. </p>
<p>I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that.</p>
<p><em>An example of what I've produced after asking this question is in the answers</em></p>
| [
{
"answer_id": 149412,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>If you choose Code39, you could probably code up from this code I wrote</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode-generation.aspx\" rel=\"noreferrer\">http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode-generation.aspx</a></p>\n\n<p>I wrote it to use our toolkit for image generation, but you could rewrite it to use .NET Image/Graphics pretty easily.</p>\n"
},
{
"answer_id": 149415,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>At my last job I worked with a couple different libraries in vb.net for this. We had one, and moved to a different one. I can't remember their names (I'd recognize them again if I saw them), but I do know that <em>both</em> were for-pay, we evaluated several different components at the time of the switch, and I think that included a free one. We were a <em>very</em> small shop and <em>very</em> cost sensitive, so if the free component were any good at all you can bet we would have used it (I think we needed 128b support, and it only handled code39).</p>\n\n<p>I also remember that reason we switched was that it was at the same time we moved from .Net 1.1 to .Net 2.0, and the first component was too slow making the transition.</p>\n\n<p>So, in summary, there is something out there, but it wasn't any good 3 years ago. Hopefully someone else can come along and fill in some actual names.</p>\n"
},
{
"answer_id": 149505,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an open source barcode rendering library for .NET languages: <a href=\"http://www.codeplex.com/BarcodeRender\" rel=\"nofollow noreferrer\">http://www.codeplex.com/BarcodeRender</a></p>\n\n<p>It can render some usual encodings.</p>\n\n<p>The license looks benign, and it seems to be usable in both open source and commercial apps (however, IANAL, you might want to check its <a href=\"http://www.codeplex.com/BarcodeRender/license\" rel=\"nofollow noreferrer\">license</a> yourself.)</p>\n\n<p>Here's another one, also open source, using the Apache 2.0 license: <a href=\"http://sourceforge.net/projects/onecode/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/onecode/</a></p>\n\n<p>Generally, when you know from the start you're looking for open source components, it's better to bypass Google and directly start searching on <a href=\"http://sourceforge.net\" rel=\"nofollow noreferrer\">SourceForge</a> (it's got a wonderful filtering system for search results, you can filter by language, which is probably of interest to you) or on Microsoft's <a href=\"http://www.codeplex.com/\" rel=\"nofollow noreferrer\">CodePlex</a> (where choice is usually more limited, but there you go.)</p>\n"
},
{
"answer_id": 149591,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know about libraries -- all of the barcode work I've done has been with barcode fonts. Check out <a href=\"http://www.squaregear.net/fonts/free3of9.shtml\" rel=\"noreferrer\">free 3-of-9</a> if you're using the \"3 of 9\" format.</p>\n\n<p>Caveats of 3-of-9:</p>\n\n<p>make sure all text is in upper case\nstart and end each barcode with an asterisk</p>\n"
},
{
"answer_id": 149624,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 0,
"selected": false,
"text": "<p>If you render client side then the font can reside on a workstation. This way you can use 3-of-9. I've used 3-of-9 in several projects and the simplest solution for you. </p>\n"
},
{
"answer_id": 156784,
"author": "sebastiaan",
"author_id": 5018,
"author_profile": "https://Stackoverflow.com/users/5018",
"pm_score": 5,
"selected": true,
"text": "<p>This is my current codebehind, with lots of comments:</p>\n\n<pre><code>Option Explicit On\nOption Strict On\n\nImports System.Drawing\nImports System.Drawing.Imaging\nImports System.Drawing.Bitmap\nImports System.Drawing.Graphics\nImports System.IO\n\nPartial Public Class Barcode\n Inherits System.Web.UI.Page\n 'Sebastiaan Janssen - 20081001 - TINT-30584\n 'Most of the code is based on this example: \n 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx\n 'With a bit of this thrown in:\n 'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode\n\n Private _encoding As Hashtable = New Hashtable\n Private Const _wideBarWidth As Short = 8\n Private Const _narrowBarWidth As Short = 2\n Private Const _barHeight As Short = 100\n\n Sub BarcodeCode39()\n _encoding.Add(\"*\", \"bWbwBwBwb\")\n _encoding.Add(\"-\", \"bWbwbwBwB\")\n _encoding.Add(\"$\", \"bWbWbWbwb\")\n _encoding.Add(\"%\", \"bwbWbWbWb\")\n _encoding.Add(\" \", \"bWBwbwBwb\")\n _encoding.Add(\".\", \"BWbwbwBwb\")\n _encoding.Add(\"/\", \"bWbWbwbWb\")\n _encoding.Add(\"+\", \"bWbwbWbWb\")\n _encoding.Add(\"0\", \"bwbWBwBwb\")\n _encoding.Add(\"1\", \"BwbWbwbwB\")\n _encoding.Add(\"2\", \"bwBWbwbwB\")\n _encoding.Add(\"3\", \"BwBWbwbwb\")\n _encoding.Add(\"4\", \"bwbWBwbwB\")\n _encoding.Add(\"5\", \"BwbWBwbwb\")\n _encoding.Add(\"6\", \"bwBWBwbwb\")\n _encoding.Add(\"7\", \"bwbWbwBwB\")\n _encoding.Add(\"8\", \"BwbWbwBwb\")\n _encoding.Add(\"9\", \"bwBWbwBwb\")\n _encoding.Add(\"A\", \"BwbwbWbwB\")\n _encoding.Add(\"B\", \"bwBwbWbwB\")\n _encoding.Add(\"C\", \"BwBwbWbwb\")\n _encoding.Add(\"D\", \"bwbwBWbwB\")\n _encoding.Add(\"E\", \"BwbwBWbwb\")\n _encoding.Add(\"F\", \"bwBwBWbwb\")\n _encoding.Add(\"G\", \"bwbwbWBwB\")\n _encoding.Add(\"H\", \"BwbwbWBwb\")\n _encoding.Add(\"I\", \"bwBwbWBwb\")\n _encoding.Add(\"J\", \"bwbwBWBwb\")\n _encoding.Add(\"K\", \"BwbwbwbWB\")\n _encoding.Add(\"L\", \"bwBwbwbWB\")\n _encoding.Add(\"M\", \"BwBwbwbWb\")\n _encoding.Add(\"N\", \"bwbwBwbWB\")\n _encoding.Add(\"O\", \"BwbwBwbWb\")\n _encoding.Add(\"P\", \"bwBwBwbWb\")\n _encoding.Add(\"Q\", \"bwbwbwBWB\")\n _encoding.Add(\"R\", \"BwbwbwBWb\")\n _encoding.Add(\"S\", \"bwBwbwBWb\")\n _encoding.Add(\"T\", \"bwbwBwBWb\")\n _encoding.Add(\"U\", \"BWbwbwbwB\")\n _encoding.Add(\"V\", \"bWBwbwbwB\")\n _encoding.Add(\"W\", \"BWBwbwbwb\")\n _encoding.Add(\"X\", \"bWbwBwbwB\")\n _encoding.Add(\"Y\", \"BWbwBwbwb\")\n _encoding.Add(\"Z\", \"bWBwBwbwb\")\n End Sub\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n BarcodeCode39()\n Dim barcode As String = String.Empty\n If Not IsNothing(Request(\"barcode\")) AndAlso Not (Request(\"barcode\").Length = 0) Then\n barcode = Request(\"barcode\")\n Response.ContentType = \"image/png\"\n Response.AddHeader(\"Content-Disposition\", String.Format(\"attachment; filename=barcode_{0}.png\", barcode))\n\n 'TODO: Depending on the length of the string, determine how wide the image will be\n GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream)\n End If\n End Sub\n\n Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush\n getBCSymbolColor = Brushes.Black\n If symbol = \"W\" Or symbol = \"w\" Then\n getBCSymbolColor = Brushes.White\n End If\n End Function\n\n Protected Function getBCSymbolWidth(ByVal symbol As String) As Short\n getBCSymbolWidth = _narrowBarWidth\n If symbol = \"B\" Or symbol = \"W\" Then\n getBCSymbolWidth = _wideBarWidth\n End If\n End Function\n\n Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream\n 'create a new bitmap\n Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb)\n\n 'create a canvas to paint on\n Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight)\n\n 'draw a white background\n Dim g As Graphics = Graphics.FromImage(b)\n g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)\n\n 'write the unaltered code at the bottom\n 'TODO: truely center this text\n Dim textBrush As New SolidBrush(Color.Black)\n g.DrawString(Code, New Font(\"Courier New\", 12), textBrush, 100, 110)\n\n 'Code has to be surrounded by asterisks to make it a valid Code39 barcode\n Dim UseCode As String = String.Format(\"{0}{1}{0}\", \"*\", Code)\n\n 'Start drawing at 10, 10\n Dim XPosition As Short = 10\n Dim YPosition As Short = 10\n\n Dim invalidCharacter As Boolean = False\n Dim CurrentSymbol As String = String.Empty\n\n For j As Short = 0 To CShort(UseCode.Length - 1)\n CurrentSymbol = UseCode.Substring(j, 1)\n 'check if symbol can be used\n If Not IsNothing(_encoding(CurrentSymbol)) Then\n Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString\n\n For i As Short = 0 To CShort(EncodedSymbol.Length - 1)\n Dim CurrentCode As String = EncodedSymbol.Substring(i, 1)\n g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight)\n XPosition = XPosition + getBCSymbolWidth(CurrentCode)\n Next\n\n 'After each written full symbol we need a whitespace (narrow width)\n g.FillRectangle(getBCSymbolColor(\"w\"), XPosition, YPosition, getBCSymbolWidth(\"w\"), _barHeight)\n XPosition = XPosition + getBCSymbolWidth(\"w\")\n Else\n invalidCharacter = True\n End If\n Next\n\n 'errorhandling when an invalidcharacter is found\n If invalidCharacter Then\n g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)\n g.DrawString(\"Invalid characters found,\", New Font(\"Courier New\", 8), textBrush, 0, 0)\n g.DrawString(\"no barcode generated\", New Font(\"Courier New\", 8), textBrush, 0, 10)\n g.DrawString(\"Input was: \", New Font(\"Courier New\", 8), textBrush, 0, 30)\n g.DrawString(Code, New Font(\"Courier New\", 8), textBrush, 0, 40)\n End If\n\n 'write the image into a memorystream\n Dim ms As New MemoryStream\n\n Dim encodingParams As New EncoderParameters\n encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100)\n\n Dim encodingInfo As ImageCodecInfo = FindCodecInfo(\"PNG\")\n\n b.Save(ms, encodingInfo, encodingParams)\n\n 'dispose of the object we won't need any more\n g.Dispose()\n b.Dispose()\n\n Return ms\n End Function\n\n Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo\n Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders\n For Each e As ImageCodecInfo In encoders\n If e.FormatDescription.Equals(codec) Then Return e\n Next\n Return Nothing\n End Function\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 172856,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>are you printing to a standard printer or an actual barcode printer (zebra or datamax)?\nboth zebra and datamax have their own scripting languages - actually more like markup languages. ZPL and DPL respectively. I like zebra's more and their documentation is much cleaner.</p>\n\n<p>If you don't have a legitimate barcode printer, I suggest purchasing one and do the following.... (it'll be much cleaner than trying to work out building little image blocks and painting them to simulate a barcode font)</p>\n\n<p>both allow you great flexibility and you can let the printer handle creating the actual barcode image.</p>\n\n<p>have your program send a customized ZPL/DPL script that includes the values that you want to have printed as barcodes to the printer via ftp. basically, you just \"put\" a text file that contains the script to the IP of the printer and the printer takes care of the font.</p>\n"
},
{
"answer_id": 294975,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"http://itextsharp.sourceforge.net/\" rel=\"nofollow noreferrer\">iTextSharp</a> library, while ostensibly for creating creating PDFs, also has a barcode generation library that includes Code39.</p>\n\n<p>Once you add a reference to the DLL, it's as simple as:</p>\n\n<pre><code>Barcode39 code39 = new Barcode39();\ncode39.Code = \"Whatever You're Encoding\";\n</code></pre>\n\n<p>Oops, that's C#, but you get the idea. Once created, you can render an image in just about any image format and use it as you wish.</p>\n"
},
{
"answer_id": 26901212,
"author": "civ",
"author_id": 4246566,
"author_profile": "https://Stackoverflow.com/users/4246566",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an example of <a href=\"http://www.barcodelib.com/vb_net/\" rel=\"nofollow\">how to generate Code39 barcodes in vb.net</a>. I tested It now and it works.</p>\n\n<pre><code> Public Class code39\n Private bitsCode As ArrayList\n\n Public Sub New()\n bitsCode = New ArrayList\n bitsCode.Add(New String(3) {\"0001101\", \"0100111\", \"1110010\", \"000000\"})\n bitsCode.Add(New String(3) {\"0011001\", \"0110011\", \"1100110\", \"001011\"})\n bitsCode.Add(New String(3) {\"0010011\", \"0011011\", \"1101100\", \"001101\"})\n bitsCode.Add(New String(3) {\"0111101\", \"0100001\", \"1000010\", \"001110\"})\n bitsCode.Add(New String(3) {\"0100011\", \"0011101\", \"1011100\", \"010011\"})\n bitsCode.Add(New String(3) {\"0110001\", \"0111001\", \"1001110\", \"011001\"})\n bitsCode.Add(New String(3) {\"0101111\", \"0000101\", \"1010000\", \"011100\"})\n bitsCode.Add(New String(3) {\"0111011\", \"0010001\", \"1000100\", \"010101\"})\n bitsCode.Add(New String(3) {\"0110111\", \"0001001\", \"1001000\", \"010110\"})\n bitsCode.Add(New String(3) {\"0001011\", \"0010111\", \"1110100\", \"011010\"})\n End Sub\n\n Public Function Generate(ByVal Code As String) As Image\n Dim a As Integer = 0\n Dim b As Integer = 0\n Dim imgCode As Image\n Dim g As Graphics\n Dim i As Integer\n Dim bCode As Byte()\n Dim bitCode As Byte()\n Dim tmpFont As Font\n\n If Code.Length <> 12 Or Not IsNumeric(Code.Replace(\".\", \"_\").Replace(\",\", \"_\")) Then Throw New Exception(\"Le code doit être composé de 12 chiffres\")\n\n ReDim bCode(12)\n For i = 0 To 11\n bCode(i) = CInt(Code.Substring(i, 1))\n If (i Mod 2) = 1 Then\n b += bCode(i)\n Else\n a += bCode(i)\n End If\n Next\n\n i = (a + (b * 3)) Mod 10\n If i = 0 Then\n bCode(12) = 0\n Else\n bCode(12) = 10 - i\n End If\n bitCode = getBits(bCode)\n\n tmpFont = New Font(\"times new roman\", 14, FontStyle.Regular, GraphicsUnit.Pixel)\n imgCode = New Bitmap(110, 50)\n g = Graphics.FromImage(imgCode)\n g.Clear(Color.White)\n\n g.DrawString(Code.Substring(0, 1), tmpFont, Brushes.Black, 2, 30)\n a = g.MeasureString(Code.Substring(0, 1), tmpFont).Width\n\n For i = 0 To bitCode.Length - 1\n If i = 2 Then\n g.DrawString(Code.Substring(1, 6), tmpFont, Brushes.Black, a, 30)\n ElseIf i = 48 Then\n g.DrawString(Code.Substring(7, 5) & bCode(12).ToString, tmpFont, Brushes.Black, a, 30)\n End If\n\n If i = 0 Or i = 2 Or i = 46 Or i = 48 Or i = 92 Or i = 94 Then\n If bitCode(i) = 1 Then 'noir\n g.DrawLine(Pens.Black, a, 0, a, 40)\n a += 1\n End If\n Else\n If bitCode(i) = 1 Then 'noir\n g.DrawLine(Pens.Black, a, 0, a, 30)\n a += 1\n Else 'blanc\n a += 1\n End If\n End If\n Next\n g.Flush()\n Return imgCode\n End Function\n\n Private Function getBits(ByVal bCode As Byte()) As Byte()\n Dim i As Integer\n Dim res As Byte()\n Dim bits As String = \"101\"\n Dim cle As String = bitsCode(bCode(0))(3)\n For i = 1 To 6\n bits &= bitsCode(bCode(i))(CInt(cle.Substring(i - 1, 1)))\n Next\n bits &= \"01010\"\n For i = 7 To 12\n bits &= bitsCode(bCode(i))(2)\n Next\n bits += \"101\"\n ReDim res(bits.Length - 1)\n For i = 0 To bits.Length - 1\n res(i) = Asc(bits.Chars(i)) - 48\n Next\n Return res\n End Function\n\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 27896165,
"author": "Belinda Raman",
"author_id": 4444045,
"author_profile": "https://Stackoverflow.com/users/4444045",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using barcode font, i would prefer a <a href=\"http://www.pqscan.com/barcode-creator/\" rel=\"nofollow\">.net barcode generator component</a>. Below is a <a href=\"http://www.pqscan.com/generate-barcode/csharp-vb.html\" rel=\"nofollow\">vb.net sample for creating Code 39 barcode</a>.</p>\n\n<pre><code>Imports System.IO\nImports PQScan.BarcodeCreator\n\nNamespace BarcodeGeneratorVB\nClass Program\n Private Shared Sub Main(args As String())\n Dim barcode As New Barcode()\n\n barcode.Data = \"www.pqscan.com\"\n barcode.BarType = BarCodeType.Code39\n barcode.Width = 300\n barcode.Height = 100\n\n barcode.CreateBarcode(\"code39-vb.jpeg\")\n End Sub\nEnd Class\nEnd Namespace\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
]
| I want to create Code39 encoded barcodes from my application.
I know I can use a font for this, but I'd prefer not to as I'd have to register the font on the server and I've had some pretty bad experiences with that.
*An example of what I've produced after asking this question is in the answers* | This is my current codebehind, with lots of comments:
```
Option Explicit On
Option Strict On
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Bitmap
Imports System.Drawing.Graphics
Imports System.IO
Partial Public Class Barcode
Inherits System.Web.UI.Page
'Sebastiaan Janssen - 20081001 - TINT-30584
'Most of the code is based on this example:
'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/25/writing-code-39-barcodes-with-javascript.aspx-generation.aspx
'With a bit of this thrown in:
'http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/03/24/code-39-barcode
Private _encoding As Hashtable = New Hashtable
Private Const _wideBarWidth As Short = 8
Private Const _narrowBarWidth As Short = 2
Private Const _barHeight As Short = 100
Sub BarcodeCode39()
_encoding.Add("*", "bWbwBwBwb")
_encoding.Add("-", "bWbwbwBwB")
_encoding.Add("$", "bWbWbWbwb")
_encoding.Add("%", "bwbWbWbWb")
_encoding.Add(" ", "bWBwbwBwb")
_encoding.Add(".", "BWbwbwBwb")
_encoding.Add("/", "bWbWbwbWb")
_encoding.Add("+", "bWbwbWbWb")
_encoding.Add("0", "bwbWBwBwb")
_encoding.Add("1", "BwbWbwbwB")
_encoding.Add("2", "bwBWbwbwB")
_encoding.Add("3", "BwBWbwbwb")
_encoding.Add("4", "bwbWBwbwB")
_encoding.Add("5", "BwbWBwbwb")
_encoding.Add("6", "bwBWBwbwb")
_encoding.Add("7", "bwbWbwBwB")
_encoding.Add("8", "BwbWbwBwb")
_encoding.Add("9", "bwBWbwBwb")
_encoding.Add("A", "BwbwbWbwB")
_encoding.Add("B", "bwBwbWbwB")
_encoding.Add("C", "BwBwbWbwb")
_encoding.Add("D", "bwbwBWbwB")
_encoding.Add("E", "BwbwBWbwb")
_encoding.Add("F", "bwBwBWbwb")
_encoding.Add("G", "bwbwbWBwB")
_encoding.Add("H", "BwbwbWBwb")
_encoding.Add("I", "bwBwbWBwb")
_encoding.Add("J", "bwbwBWBwb")
_encoding.Add("K", "BwbwbwbWB")
_encoding.Add("L", "bwBwbwbWB")
_encoding.Add("M", "BwBwbwbWb")
_encoding.Add("N", "bwbwBwbWB")
_encoding.Add("O", "BwbwBwbWb")
_encoding.Add("P", "bwBwBwbWb")
_encoding.Add("Q", "bwbwbwBWB")
_encoding.Add("R", "BwbwbwBWb")
_encoding.Add("S", "bwBwbwBWb")
_encoding.Add("T", "bwbwBwBWb")
_encoding.Add("U", "BWbwbwbwB")
_encoding.Add("V", "bWBwbwbwB")
_encoding.Add("W", "BWBwbwbwb")
_encoding.Add("X", "bWbwBwbwB")
_encoding.Add("Y", "BWbwBwbwb")
_encoding.Add("Z", "bWBwBwbwb")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
BarcodeCode39()
Dim barcode As String = String.Empty
If Not IsNothing(Request("barcode")) AndAlso Not (Request("barcode").Length = 0) Then
barcode = Request("barcode")
Response.ContentType = "image/png"
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=barcode_{0}.png", barcode))
'TODO: Depending on the length of the string, determine how wide the image will be
GenerateBarcodeImage(250, 140, barcode).WriteTo(Response.OutputStream)
End If
End Sub
Protected Function getBCSymbolColor(ByVal symbol As String) As System.Drawing.Brush
getBCSymbolColor = Brushes.Black
If symbol = "W" Or symbol = "w" Then
getBCSymbolColor = Brushes.White
End If
End Function
Protected Function getBCSymbolWidth(ByVal symbol As String) As Short
getBCSymbolWidth = _narrowBarWidth
If symbol = "B" Or symbol = "W" Then
getBCSymbolWidth = _wideBarWidth
End If
End Function
Protected Overridable Function GenerateBarcodeImage(ByVal imageWidth As Short, ByVal imageHeight As Short, ByVal Code As String) As MemoryStream
'create a new bitmap
Dim b As New Bitmap(imageWidth, imageHeight, Imaging.PixelFormat.Format32bppArgb)
'create a canvas to paint on
Dim canvas As New Rectangle(0, 0, imageWidth, imageHeight)
'draw a white background
Dim g As Graphics = Graphics.FromImage(b)
g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)
'write the unaltered code at the bottom
'TODO: truely center this text
Dim textBrush As New SolidBrush(Color.Black)
g.DrawString(Code, New Font("Courier New", 12), textBrush, 100, 110)
'Code has to be surrounded by asterisks to make it a valid Code39 barcode
Dim UseCode As String = String.Format("{0}{1}{0}", "*", Code)
'Start drawing at 10, 10
Dim XPosition As Short = 10
Dim YPosition As Short = 10
Dim invalidCharacter As Boolean = False
Dim CurrentSymbol As String = String.Empty
For j As Short = 0 To CShort(UseCode.Length - 1)
CurrentSymbol = UseCode.Substring(j, 1)
'check if symbol can be used
If Not IsNothing(_encoding(CurrentSymbol)) Then
Dim EncodedSymbol As String = _encoding(CurrentSymbol).ToString
For i As Short = 0 To CShort(EncodedSymbol.Length - 1)
Dim CurrentCode As String = EncodedSymbol.Substring(i, 1)
g.FillRectangle(getBCSymbolColor(CurrentCode), XPosition, YPosition, getBCSymbolWidth(CurrentCode), _barHeight)
XPosition = XPosition + getBCSymbolWidth(CurrentCode)
Next
'After each written full symbol we need a whitespace (narrow width)
g.FillRectangle(getBCSymbolColor("w"), XPosition, YPosition, getBCSymbolWidth("w"), _barHeight)
XPosition = XPosition + getBCSymbolWidth("w")
Else
invalidCharacter = True
End If
Next
'errorhandling when an invalidcharacter is found
If invalidCharacter Then
g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight)
g.DrawString("Invalid characters found,", New Font("Courier New", 8), textBrush, 0, 0)
g.DrawString("no barcode generated", New Font("Courier New", 8), textBrush, 0, 10)
g.DrawString("Input was: ", New Font("Courier New", 8), textBrush, 0, 30)
g.DrawString(Code, New Font("Courier New", 8), textBrush, 0, 40)
End If
'write the image into a memorystream
Dim ms As New MemoryStream
Dim encodingParams As New EncoderParameters
encodingParams.Param(0) = New EncoderParameter(Encoder.Quality, 100)
Dim encodingInfo As ImageCodecInfo = FindCodecInfo("PNG")
b.Save(ms, encodingInfo, encodingParams)
'dispose of the object we won't need any more
g.Dispose()
b.Dispose()
Return ms
End Function
Protected Overridable Function FindCodecInfo(ByVal codec As String) As ImageCodecInfo
Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders
For Each e As ImageCodecInfo In encoders
If e.FormatDescription.Equals(codec) Then Return e
Next
Return Nothing
End Function
End Class
``` |
149,380 | <p>This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern <a href="http://en.wikipedia.org/wiki/Relational_database_management_system" rel="noreferrer">RDBMS</a> solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.</p>
<p>I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:</p>
<pre><code>ORDER BY @sortCol1, @sortCol2
</code></pre>
<p>This is the canonical example given by newbie SQL and <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="noreferrer">Stored Procedure</a> developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an <code>ORDER BY</code> clause.</p>
<hr>
<p>I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are <em>very</em> good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.</p>
<p>Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really <em>really</em> easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.</p>
<p>But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."</p>
<hr>
<p>The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.</p>
<p>We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):</p>
<pre><code>DECLARE @sortCol1 AS varchar(20)
DECLARE @sortCol2 AS varchar(20)
DECLARE @dir1 AS varchar(20)
DECLARE @dir2 AS varchar(20)
DECLARE @col1 AS varchar(20)
DECLARE @col2 AS varchar(20)
SET @col1 = 'storagedatetime';
SET @col2 = 'vehicleid';
IF @sort = 1 -- Default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'asc';
SET @sortCol2 = @col2;
SET @dir2 = 'asc';
END
ELSE IF @sort = 2 -- Reversed order default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'desc';
SET @sortCol2 = @col2;
SET @dir2 = 'desc';
END
</code></pre>
<p>You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:</p>
<pre><code>ORDER BY
CASE @dir1
WHEN 'desc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir1
WHEN 'asc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END,
CASE @dir2
WHEN 'desc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir2
WHEN 'asc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END
</code></pre>
<p>Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.</p>
<p>The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:</p>
<pre><code>ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah
</code></pre>
<p>You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."</p>
<p>Yet it <em>did</em> work.</p>
<hr>
<p>My question is then: <strong>is there a better way?</strong></p>
<p>I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?</p>
<p>And thank you for reading (or at least skimming) such a long question!</p>
<p>PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, <em>AND</em> try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.</p>
<hr>
<p><strong>Update:</strong></p>
<ul>
<li>I would like to <strong>avoid dynamic SQL</strong>. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world.</li>
<li>A lot of the reason we want stored procedures in the first place is for <strong>security</strong>. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)</li>
</ul>
| [
{
"answer_id": 149391,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 1,
"selected": false,
"text": "<p>How about handling sorting on the stuff displaying the results -- grids, reports, etc. rather than on SQL?</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>To clarify things since this answer got down-voted earlier, I'll elaborate a bit...</p>\n\n<p>You stated you knew about client-side sorting but wanted to steer clear of it. That's your call, of course.</p>\n\n<p>What I want to point out, though, is that by doing it on the client-side, you're able to pull data ONCE and then work with it however you want -- versus doing multiple trips back and forth to the server each time the sort gets changed.</p>\n\n<p>Your SQL Server isn't getting taxed right now and that's awesome. It shouldn't be. But just because it isn't overloaded yet doesn't mean that it'll stay like that forever.</p>\n\n<p>If you're using any of the newer ASP.NET stuff for displaying on the web, a lot of that stuff is already baked right in.</p>\n\n<p>Is it worth adding so much code to each stored procedure just to handle sorting? Again, your call. </p>\n\n<p>I'm not the one who will ultimately be in charge of supporting it. But give some thought to what will be involved as columns are added/removed within the various datasets used by the stored procedures (requiring modifications to the CASE statements) or when suddenly instead of sorting by two columns, the user decides they need three -- requiring you to now update every one of your stored procedures that uses this method.</p>\n\n<p>For me, it's worth it to get a working client-side solution and apply it to the handful of user-facing displays of data and be done with it. If a new column is added, it's already handled. If the user wants to sort by multiple columns, they can sort by two or twenty of them.</p>\n"
},
{
"answer_id": 149470,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>At some point, doesn't it become worth it to move away from stored procedures and just use parameterized queries to avoid this sort of hackery?</p>\n"
},
{
"answer_id": 149481,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "<p>Dynamic SQL is still an option. You just have to decide whether that option is more palatable than what you currently have.</p>\n\n<p>Here is an article that shows that: <a href=\"https://web.archive.org/web/20211029044050/https://www.4guysfromrolla.com/webtech/010704-1.shtml\" rel=\"noreferrer\">https://web.archive.org/web/20211029044050/https://www.4guysfromrolla.com/webtech/010704-1.shtml</a>. </p>\n"
},
{
"answer_id": 149549,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 7,
"selected": false,
"text": "<p>Yeah, it's a pain, and the way you're doing it looks similar to what I do:</p>\n\n<pre><code>order by\ncase when @SortExpr = 'CustomerName' and @SortDir = 'ASC' \n then CustomerName end asc, \ncase when @SortExpr = 'CustomerName' and @SortDir = 'DESC' \n then CustomerName end desc,\n...\n</code></pre>\n\n<p>This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs.</p>\n\n<p>What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for <code>@SortExpr</code> and <code>@SortDir</code>.</p>\n\n<p>As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes.</p>\n"
},
{
"answer_id": 149586,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>There may be a third option, since your server has lots of spare cycles - use a helper procedure to do the sorting via a temporary table. Something like</p>\n\n<pre><code>create procedure uspCallAndSort\n(\n @sql varchar(2048), --exec dbo.uspSomeProcedure arg1,'arg2',etc.\n @sortClause varchar(512) --comma-delimited field list\n)\nAS\ninsert into #tmp EXEC(@sql)\ndeclare @msql varchar(3000)\nset @msql = 'select * from #tmp order by ' + @sortClause\nEXEC(@msql)\ndrop table #tmp\nGO\n</code></pre>\n\n<p>Caveat: I haven't tested this, but it \"should\" work in SQL Server 2005 (which will create a temporary table from a result set without specifying the columns in advance.)</p>\n"
},
{
"answer_id": 149906,
"author": "D.S.",
"author_id": 343291,
"author_profile": "https://Stackoverflow.com/users/343291",
"pm_score": 2,
"selected": false,
"text": "<p>I agree, use client side. But it appears that is not the answer you want to hear.</p>\n\n<p>So, it is perfect the way it is. I don't know why you would want to change it, or even ask \"Is there a better way.\" Really, it should be called \"The Way\". Besides, it seems to work and suit the needs of the project just fine and will probably be extensible enough for years to come. Since your databases aren't taxed and sorting is <em>really really easy</em> it should stay that way for years to come.</p>\n\n<p>I wouldn't sweat it.</p>\n"
},
{
"answer_id": 150173,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 3,
"selected": false,
"text": "<p>My applications do this a lot but they are all dynamically building the SQL. However, when I deal with stored procedures I do this:</p>\n\n<ol>\n<li>Make the stored procedure a function that returns a table of your values - no sort.</li>\n<li>Then in your application code do a <code>select * from dbo.fn_myData() where ... order by ...</code> so you can dynamically specify the sort order there.</li>\n</ol>\n\n<p>Then at least the dynamic part is in your application, but the database is still doing the heavy lifting.</p>\n"
},
{
"answer_id": 150979,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": false,
"text": "<p>There's a couple of different ways you can hack this in. </p>\n\n<p>Prerequisites:</p>\n\n<ol>\n<li>Only one SELECT statement in the\nsp </li>\n<li>Leave out any sorting (or have\na default)</li>\n</ol>\n\n<p>Then insert into a temp table:</p>\n\n<pre><code>create table #temp ( your columns )\n\ninsert #temp\nexec foobar\n\nselect * from #temp order by whatever\n</code></pre>\n\n<p>Method #2: set up a linked server back to itself, then select from this using openquery:\n<a href=\"http://www.sommarskog.se/share_data.html#OPENQUERY\" rel=\"nofollow noreferrer\">http://www.sommarskog.se/share_data.html#OPENQUERY</a></p>\n"
},
{
"answer_id": 151718,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": -1,
"selected": false,
"text": "<p>This solution might only work in .NET, I don't know. </p>\n\n<p>I fetch the data into the C# with the initial sort order in the SQL order by clause, put that data in a DataView, cache it in a Session variable, and use it to build a page.</p>\n\n<p>When the user clicks on a column heading to sort (or page, or filter), I don't go back to the database. Instead, I go back to my cached DataView and set its \"Sort\" property to an expression I build dynamically, just like I would dynamic SQL. ( I do the filtering the same way, using the \"RowFilter\" property).</p>\n\n<p>You can see/feel it working in a demo of my app, BugTracker.NET, at <a href=\"http://ifdefined.com/btnet/bugs.aspx\" rel=\"nofollow noreferrer\">http://ifdefined.com/btnet/bugs.aspx</a></p>\n"
},
{
"answer_id": 151729,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": -1,
"selected": false,
"text": "<p>You should avoid the SQL Server sorting, unless if necessary. Why not sort on app server or client side? Also .NET Generics does exceptional sortin</p>\n"
},
{
"answer_id": 151764,
"author": "Jason DeFontes",
"author_id": 6159,
"author_profile": "https://Stackoverflow.com/users/6159",
"pm_score": 5,
"selected": false,
"text": "<p>This approach keeps the sortable columns from being duplicated twice in the order by, and is a little more readable IMO:</p>\n\n<pre><code>SELECT\n s.*\nFROM\n (SELECT\n CASE @SortCol1\n WHEN 'Foo' THEN t.Foo\n WHEN 'Bar' THEN t.Bar\n ELSE null\n END as SortCol1,\n CASE @SortCol2\n WHEN 'Foo' THEN t.Foo\n WHEN 'Bar' THEN t.Bar\n ELSE null\n END as SortCol2,\n t.*\n FROM\n MyTable t) as s\nORDER BY\n CASE WHEN @dir1 = 'ASC' THEN SortCol1 END ASC,\n CASE WHEN @dir1 = 'DESC' THEN SortCol1 END DESC,\n CASE WHEN @dir2 = 'ASC' THEN SortCol2 END ASC,\n CASE WHEN @dir2 = 'DESC' THEN SortCol2 END DESC\n</code></pre>\n"
},
{
"answer_id": 836798,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 2,
"selected": false,
"text": "<p>When you are paging sorted results, dynamic SQL is a good option. If you're paranoid about SQL injection you can use the column numbers instead of the column name. I've done this before using negative values for descending. Something like this...</p>\n\n<pre><code>declare @o int;\nset @o = -1;\n\ndeclare @sql nvarchar(2000);\nset @sql = N'select * from table order by ' + \n cast(abs(@o) as varchar) + case when @o < 0 then ' desc' else ' asc' end + ';'\n\nexec sp_executesql @sql\n</code></pre>\n\n<p>Then you just need to make sure the number is inside 1 to # of columns. You could even expand this to a list of column numbers and parse that into a table of ints using a function like <a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html#iterative\" rel=\"nofollow noreferrer\">this</a>. Then you would build the order by clause like so...</p>\n\n<pre><code>declare @cols varchar(100);\nset @cols = '1 -2 3 6';\n\ndeclare @order_by varchar(200)\n\nselect @order_by = isnull(@order_by + ', ', '') + \n cast(abs(number) as varchar) + \n case when number < 0 then ' desc' else '' end\nfrom dbo.iter_intlist_to_tbl(@cols) order by listpos\n\nprint @order_by\n</code></pre>\n\n<p>One drawback is you have to remember the order of each column on the client side. Especially, when you don't display all the columns or you display them in a different order. When the client wants to sort, you map the column names to the column order and generate the list of ints. </p>\n"
},
{
"answer_id": 3390130,
"author": "dave",
"author_id": 391047,
"author_profile": "https://Stackoverflow.com/users/391047",
"pm_score": 3,
"selected": false,
"text": "<p>A stored procedure technique (hack?) I've used to avoid dynamic SQL for certain jobs is to have a unique sort column. I.e.,</p>\n\n<pre><code>SELECT\n name_last,\n name_first,\n CASE @sortCol WHEN 'name_last' THEN [name_last] ELSE 0 END as mySort\nFROM\n table\nORDER BY \n mySort\n</code></pre>\n\n<p>This one is easy to beat into submission -- you can concat fields in your mySort column, reverse the order with math or date functions, etc.</p>\n\n<p>Preferably though, I use my asp.net gridviews or other objects with build-in sorting to do the sorting for me AFTER retrieving the data fro Sql-Server. Or even if it's not built-in -- e.g., datatables, etc. in asp.net.</p>\n"
},
{
"answer_id": 20979546,
"author": "Paul Schirf",
"author_id": 3170431,
"author_profile": "https://Stackoverflow.com/users/3170431",
"pm_score": 2,
"selected": false,
"text": "<p>An argument against doing the sorting on the client side is large volume data and pagination. Once your row count gets beyond what you can easily display you're often sorting as part of a skip/take, which you probably want to run in SQL.</p>\n\n<p>For Entity Framework, you could use a stored procedure to handle your text search. If you encounter the same sort issue, the solution I've seen is to use a stored proc for the search, returning only an id key set for the match. Next, re-query (with the sort) against the db using the ids in a list (contains). EF handles this pretty well, even when the ID set is pretty large. Yes, this is two round trips, but it allows you to always keep your sorting in the DB, which can be important in some situations, and prevents you from writing a boatload of logic in the stored procedure.</p>\n"
},
{
"answer_id": 53860218,
"author": "BVernon",
"author_id": 2449861,
"author_profile": "https://Stackoverflow.com/users/2449861",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry I'm late to the party, but here's another option for those who really want to avoid dynamic SQL, but want the flexibility it offers:</p>\n\n<p>Instead of dynamically generating the SQL on the fly, write code to generate a unique proc for every possible variation. Then you can write a method in the code to look at the search options and have it choose the appropriate proc to call.</p>\n\n<p>If you only have a few variations then you can just create the procs by hand. But if you have a lot of variations then instead of having to maintain them all, you would just maintain your proc generator instead to have it recreate them.</p>\n\n<p>As an added benefit, you'll get better SQL plans for better performance doing it this way too.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290/"
]
| This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern [RDBMS](http://en.wikipedia.org/wiki/Relational_database_management_system) solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.
I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:
```
ORDER BY @sortCol1, @sortCol2
```
This is the canonical example given by newbie SQL and [Stored Procedure](http://en.wikipedia.org/wiki/Stored_procedure) developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an `ORDER BY` clause.
---
I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are *very* good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.
Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really *really* easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.
But this brings back the point that it isn't possible — or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."
---
The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.
We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):
```
DECLARE @sortCol1 AS varchar(20)
DECLARE @sortCol2 AS varchar(20)
DECLARE @dir1 AS varchar(20)
DECLARE @dir2 AS varchar(20)
DECLARE @col1 AS varchar(20)
DECLARE @col2 AS varchar(20)
SET @col1 = 'storagedatetime';
SET @col2 = 'vehicleid';
IF @sort = 1 -- Default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'asc';
SET @sortCol2 = @col2;
SET @dir2 = 'asc';
END
ELSE IF @sort = 2 -- Reversed order default sort.
BEGIN
SET @sortCol1 = @col1;
SET @dir1 = 'desc';
SET @sortCol2 = @col2;
SET @dir2 = 'desc';
END
```
You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:
```
ORDER BY
CASE @dir1
WHEN 'desc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir1
WHEN 'asc' THEN
CASE @sortCol1
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END,
CASE @dir2
WHEN 'desc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END DESC,
CASE @dir2
WHEN 'asc' THEN
CASE @sortCol2
WHEN @col1 THEN [storagedatetime]
WHEN @col2 THEN [vehicleid]
END
END
```
Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.
The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:
```
ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah
```
You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."
Yet it *did* work.
---
My question is then: **is there a better way?**
I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?
And thank you for reading (or at least skimming) such a long question!
PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, *AND* try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.
---
**Update:**
* I would like to **avoid dynamic SQL**. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that — like I'm still living in the Classic ASP world.
* A lot of the reason we want stored procedures in the first place is for **security**. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :) | Yeah, it's a pain, and the way you're doing it looks similar to what I do:
```
order by
case when @SortExpr = 'CustomerName' and @SortDir = 'ASC'
then CustomerName end asc,
case when @SortExpr = 'CustomerName' and @SortDir = 'DESC'
then CustomerName end desc,
...
```
This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs.
What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for `@SortExpr` and `@SortDir`.
As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes. |
149,388 | <p>Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method.</p>
<p>My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message.</p>
<p>Right? Wrong? Thanks!</p>
<p><strong>Update 09:39AMPST</strong></p>
<p>Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "<em>where</em> is the method getting queued? <em>how</em> is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em</p>
<p><strong>Update 14:21PST</strong></p>
<p>Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for <strong>concrete</strong> information on what is happening, so I can be sure I'm understanding things <em>correctly</em>. Thanks! </p>
<p><strong>Update 03/06/09</strong></p>
<p>I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read <strong>everything</strong>, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the <strong>lowest-level detail</strong> of the mechanism used by <code>performSelectorOnMainThread:</code> and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can <strong>confirm</strong> the answer given is correct. Thanks everyone!</p>
| [
{
"answer_id": 149448,
"author": "Evan DiBiase",
"author_id": 2399475,
"author_profile": "https://Stackoverflow.com/users/2399475",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:\" rel=\"nofollow noreferrer\">documentation for NSObject's <code>performSelectorOnMainThread:withObject:waitUntilDone:</code> method</a> says:</p>\n\n<blockquote>\n <p>This method queues the message on the run loop of the main thread using the default run loop modes—that is, the modes associated with the <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/c/data/NSRunLoopCommonModes\" rel=\"nofollow noreferrer\">NSRunLoopCommonModes</a> constant. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.</p>\n</blockquote>\n"
},
{
"answer_id": 149471,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<p>One More Edit:</p>\n\n<p>To answer the question of the comment:</p>\n\n<blockquote>\n <p>what IPC mechanism is being used to\n pass info between threads? Shared\n memory? Sockets? Mach messaging?</p>\n</blockquote>\n\n<p>NSThread stores internally a reference to the main thread and via that reference you can get a reference to the NSRunloop of that thread. A NSRunloop internally is a linked list and by adding a NSTimer object to the runloop, a new linked list element is created and added to the list. So you could say it's shared memory, the linked list, that actually belongs to the main thread, is simply modified from within a different thread. There are mutexes/locks (possibly even NSLock objects) that will make sure editing the linked list is thread-safe.</p>\n\n<p>Pseudo code:</p>\n\n<pre><code>// Main Thread\n\nfor (;;) {\n lock(runloop->runloopLock);\n task = NULL;\n do {\n task = getNextTask(runloop);\n if (!task) {\n // function below unlocks the lock and\n // atomically sends thread to sleep.\n // If thread is woken up again, it will\n // get the lock again before continuing\n // running. See \"man pthread_cond_wait\"\n // as an example function that works\n // this way\n wait_for_notification(runloop->newTasks, runloop->runloopLock);\n }\n } while (!task);\n unlock(runloop->runloopLock);\n processTask(task);\n}\n\n\n// Other thread, perform selector on main thread\n// selector is char *, containing the selector\n// object is void *, reference to object\n\ntimer = createTimerInPast(selector, object);\nrunloop = getRunloopOfMainThread();\nlock(runloop->runloopLock);\naddTask(runloop, timer);\nwake_all_sleeping(runloop->newTasks);\nunlock(runloop->runloopLock);\n</code></pre>\n\n<p>Of course this is oversimplified, most details are hidden between functions here. E.g. getNextTask will only return a timer, if the timer should have fired already. If the fire date for every timer is still in the future and there is no other event to process (like a keyboard, mouse event from UI or a sent notification), it would return NULL.</p>\n\n<hr>\n\n<p>I'm still not sure what the question is. A <strong>selector</strong> is nothing more than a C string containing the name of a method being called. Every method is a normal C function and there exists a string table, containing the method names as strings and function pointers. That are the very basics how Objective-C actually works.</p>\n\n<p>As I wrote below, a NSTimer object is created that gets a pointer to the target object and a pointer to a C string containing the method name and when the timer fires, it finds the right C method to call by using the string table (hence it needs the string name of the method) of the target object (hence it needs a reference to it).</p>\n\n<p>Not exactly the implementation, but pretty close to it:</p>\n\n<p>Every thread in Cocoa has a NSRunLoop (it's always there, you never need to create on for a thread). PerformSelectorOnMainThread creates a NSTimer object like <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html#//apple_ref/occ/instm/NSTimer/initWithFireDate:interval:target:selector:userInfo:repeats:\" rel=\"nofollow noreferrer\">this</a>, one that fires only once and where the time to fire is already located in the past (so it needs firing immediately), then gets the NSRunLoop of the main thread and adds the timer object there. As soon as the main thread goes <em>idle</em>, it searches for the next event in its Runloop to process (or goes to sleep if there is nothing to process and being woken up again as soon as an event is added) and performs it. Either the main thread is busy when you schedule the call, in which case it will process the timer event as soon as it has finished its current task or it is sleeping at the moment, in which case it will be woken up by adding the event and processes it immediately.</p>\n\n<p>A good source to look up how Apple is <em>most likely doing it</em> (nobody can say for sure, as after all its closed source) is GNUStep. Since the GCC can handle Objective-C (it's not just an extension only Apple ships, even the standard GCC can handle it), however, having Obj-C without all the basic classes Apple ships is rather useless, the GNU community tried to re-implement the most common Obj-C classes you use on Mac and their implementation is OpenSource.</p>\n\n<p><a href=\"ftp://ftp.gnustep.org/pub/daily-snapshots/core.20080925.tar.bz2\" rel=\"nofollow noreferrer\">Here</a> you can download a recent source package.</p>\n\n<p>Unpack that and have a look at the implementation of NSThread, NSObject and NSTimer for details. I guess Apple is not doing it much different, I could probably prove it using gdb, but why would they do it much different than that approach? It's a clever approach that works very well :)</p>\n"
},
{
"answer_id": 151166,
"author": "Jens Ayton",
"author_id": 6443,
"author_profile": "https://Stackoverflow.com/users/6443",
"pm_score": 0,
"selected": false,
"text": "<p>As Mecki said, a more general mechanism that could be used to implement <code>-performSelectorOn…</code> is <code>NSTimer</code>.</p>\n\n<p><code>NSTimer</code> is toll-free bridged to <code>CFRunLoopTimer</code>. An implementation of <code>CFRunLoopTimer</code> – although not necessarily the one actually used for normal processes in OS X – can be found in CFLite (open-source subset of CoreFoundation; package CF-476.14 in the <a href=\"http://www.opensource.apple.com/darwinsource/10.5.4/\" rel=\"nofollow noreferrer\">Darwin 9.4 source code</a>. (CF-476.15, corresponding to OS X 10.5.5, is not yet available.)</p>\n"
},
{
"answer_id": 620284,
"author": "Tony",
"author_id": 34101,
"author_profile": "https://Stackoverflow.com/users/34101",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, it does use Mach ports. What happens is this:</p>\n\n<ol>\n<li>A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using <code>@synchronized</code>, which ultimately uses <code>pthread_mutex_lock</code>.</li>\n<li>CFRunLoopSourceSignal is called to signal that the source is ready to fire.</li>\n<li>CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach_msg.</li>\n</ol>\n\n<p>From the Apple docs:</p>\n\n<blockquote>\n <p>Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources.</p>\n</blockquote>\n\n<p>I'm looking at a stack trace right now, and this is what it shows:</p>\n\n<pre><code>0 mach_msg\n1 CFRunLoopWakeUp\n2 -[NSThread _nq:]\n3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:]\n4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:]\n</code></pre>\n\n<p>Set a breakpoint on mach_msg and you'll be able to confirm it.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23498/"
]
| Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method.
My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message.
Right? Wrong? Thanks!
**Update 09:39AMPST**
Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "*where* is the method getting queued? *how* is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em
**Update 14:21PST**
Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for **concrete** information on what is happening, so I can be sure I'm understanding things *correctly*. Thanks!
**Update 03/06/09**
I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read **everything**, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the **lowest-level detail** of the mechanism used by `performSelectorOnMainThread:` and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can **confirm** the answer given is correct. Thanks everyone! | Yes, it does use Mach ports. What happens is this:
1. A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using `@synchronized`, which ultimately uses `pthread_mutex_lock`.
2. CFRunLoopSourceSignal is called to signal that the source is ready to fire.
3. CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach\_msg.
From the Apple docs:
>
> Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources.
>
>
>
I'm looking at a stack trace right now, and this is what it shows:
```
0 mach_msg
1 CFRunLoopWakeUp
2 -[NSThread _nq:]
3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:]
4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:]
```
Set a breakpoint on mach\_msg and you'll be able to confirm it. |
149,394 | <p>I have a winforms application, the issue has to do with threading.
Since I am calling 'MyCustomCode() which creates a new thread, and calls the method
'SomeMethod()' which then accesses MessageBox.Show(...).</p>
<p>The problem has to do with threading, since the newly created thread is trying to access
a control that was created on another thread.</p>
<p>I am getting the error:</p>
<p>Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on.</p>
<pre><code>public TestForm()
{
InitializeComponent();
// custom code
//
MyCustomCode();
}
public void SomeMethod()
{
// ***** This causes an error ****
MessageBox.Show(this,
ex.Message,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
private void InitializeAutoUpdater()
{
// Seperate thread is spun to keep polling for updates
ThreadStart ts = new ThreadStart(SomeMethod);
pollThread = new Thread(ts);
pollThread.Start();
}
</code></pre>
<p><b>Update</b></p>
<p>If you look at this example <a href="http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx</a>, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go!</p>
<p><b>Funny thing</b> is that this code was working just fine on Friday???</p>
| [
{
"answer_id": 149404,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 3,
"selected": false,
"text": "<p>You cannot acces UI elements from multiple threads.</p>\n\n<p>One way to solve this is to call the Invoke method of a control with a delegate to the function wich use the UI elements (like the message box). Somethin like:</p>\n\n<pre><code>public delegate void InvokeDelegate();\n\npublic void SomeMethod()\n{\n\n button1.Invoke((InvokeDelegate)doUIStuff);\n\n\n}\n\n\nvoid doUIStuff()\n{\n MessageBox.Show(this, \n ex.Message, \n \"Error\", \n MessageBoxButtons.OK, \n MessageBoxIcon.Error\n );\n}\n</code></pre>\n"
},
{
"answer_id": 149423,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 0,
"selected": false,
"text": "<p>You should <strong>NOT</strong> use BeginInvoke, you should use Invoke, then once you grasp that, you can look into using BeginInvoke if really needed.</p>\n"
},
{
"answer_id": 149424,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx\" rel=\"nofollow noreferrer\">Control.BeginInvoke</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx\" rel=\"nofollow noreferrer\">Control.Invoke</a> methods</li>\n</ul>\n\n<p>OR</p>\n\n<ul>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx\" rel=\"nofollow noreferrer\">SynchronizationContext</a></li>\n</ul>\n"
},
{
"answer_id": 149436,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-vb prettyprint-override\"><code>'*******************************************************************\n' Get a new processor and fire it off on a new thread.\n'*******************************************************************\nfpProc = New Processor(confTable, paramFile, keyCount)\nAddHandler fpProc.LogEntry, AddressOf LogEntry_Handler\nDim myThread As System.Threading.Thread = New System.Threading.Thread(AddressOf fpProc.ProcessEntry)\nmyThread.Start()\n</code></pre>\n\n<p>Then in the parent app you have:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>'*************************************************************************\n' Sub: LogEntry_Handler()\n' Author: Ron Savage\n' Date: 08/29/2007\n'\n' This routine handles the LogEntry events raised by the Processor class\n' running in a thread.\n'*************************************************************************\nPrivate Sub LogEntry_Handler(ByVal logLevel As Integer, ByVal logMsg As String) Handles fProc.LogEntry\n writeLogMessage(logMsg);\nEnd Sub\n</code></pre>\n\n<p>That's what I do.</p>\n"
},
{
"answer_id": 149444,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "<p>to avoid cross-thread exceptions (InvalidOperationException), here is the code pattern:</p>\n\n<pre><code>protected delegate void someGuiFunctionDelegate(int iParam);\n\nprotected void someGuiFunction(int iParam)\n{\n if (this.InvokeRequired)\n {\n someGuiFunctionDelegate dlg = new \n someGuiFunctionDelegate(this.someGuiFunction);\n this.Invoke(dlg, new object[] { iParam });\n return;\n }\n\n //do something with the GUI control here\n}\n</code></pre>\n\n<p>i agree that this is annoying, but it is an artifact of the fact that windows GUI controls are not thread-safe. The exception can be turned off with a flag somewhere or other, but don't do that as it can lead to extremely hard to find bugs.</p>\n"
},
{
"answer_id": 149499,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 2,
"selected": false,
"text": "<p>To keep things simple you can look into using the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">BackGroundWorker</a> class. This class will provide a framework for to handle your threading and progress notification events. Your ui thread will handle the progress event and display the error message you pass back.</p>\n"
},
{
"answer_id": 149550,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Check for InvokeRequired</p>\n"
},
{
"answer_id": 2016581,
"author": "Joel Barsotti",
"author_id": 37154,
"author_profile": "https://Stackoverflow.com/users/37154",
"pm_score": 0,
"selected": false,
"text": "<p>I praticularly like a recursive call.</p>\n\n<pre><code>public delegate void InvokeDelegate(string errMessage); \n\n public void SomeMethod() \n { \n doUIStuff(\"my error message\");\n } \n\n\n void doUIStuff(string errMessage) \n { \n if (button1.InvokeRequired)\n button1.Invoke((InvokeDelegate)doUIStuff(errMessage)); \n else\n {\n MessageBox.Show(this, \n ex.Message, \n errMessage, \n MessageBoxButtons.OK, \n MessageBoxIcon.Error \n ); \n }\n } \n</code></pre>\n"
},
{
"answer_id": 3903823,
"author": "Arical",
"author_id": 471982,
"author_profile": "https://Stackoverflow.com/users/471982",
"pm_score": 1,
"selected": false,
"text": "<p>I know this is an older post, but I recently found an elegant solution to this problem using generics and extension methods. This is a combination of the authors works and some comments. </p>\n\n<p><strong>A Generic Method for Cross-thread Winforms Access</strong></p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/GenericCrossThread.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/cs/GenericCrossThread.aspx</a></p>\n\n<pre><code>public static void Manipulate<T>(this T control, Action<T> action) where T : Control\n{\n if (control.InvokeRequired)\n {\n control.Invoke(new Action<T, Action<T>>(Manipulate),\n new object[] { control, action });\n }\n else\n { action(control); }\n}\n</code></pre>\n\n<p>This can be called in the following manner, for simplicity I used a label.</p>\n\n<pre><code>someLabel.Manipulate(lbl => lbl.Text = \"Something\");\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a winforms application, the issue has to do with threading.
Since I am calling 'MyCustomCode() which creates a new thread, and calls the method
'SomeMethod()' which then accesses MessageBox.Show(...).
The problem has to do with threading, since the newly created thread is trying to access
a control that was created on another thread.
I am getting the error:
Cross-thread operation not valid: Control 'TestForm' accessed from a thread other than the thread it was created on.
```
public TestForm()
{
InitializeComponent();
// custom code
//
MyCustomCode();
}
public void SomeMethod()
{
// ***** This causes an error ****
MessageBox.Show(this,
ex.Message,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
private void InitializeAutoUpdater()
{
// Seperate thread is spun to keep polling for updates
ThreadStart ts = new ThreadStart(SomeMethod);
pollThread = new Thread(ts);
pollThread.Start();
}
```
**Update**
If you look at this example <http://www.codeproject.com/KB/cs/vanillaupdaterblock.aspx>, the method CheckAndUpdate is calling MessageBox.Show(..) that is what my problem is. I would have thought that code was good to go!
**Funny thing** is that this code was working just fine on Friday??? | You cannot acces UI elements from multiple threads.
One way to solve this is to call the Invoke method of a control with a delegate to the function wich use the UI elements (like the message box). Somethin like:
```
public delegate void InvokeDelegate();
public void SomeMethod()
{
button1.Invoke((InvokeDelegate)doUIStuff);
}
void doUIStuff()
{
MessageBox.Show(this,
ex.Message,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
``` |
149,395 | <p>We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows.</p>
| [
{
"answer_id": 149418,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.freetds.org\" rel=\"noreferrer\">FreeTDS</a> + <a href=\"http://www.unixodbc.org\" rel=\"noreferrer\">unixODBC</a> or <a href=\"http://www.iodbc.org\" rel=\"noreferrer\">iODBC</a></p>\n\n<p>Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.</p>\n\n<p>unixODBC has isql, iODBC has iodbctest</p>\n\n<p>You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)</p>\n\n<p>I'm personally using FreeTDS + iODBC:</p>\n\n<pre><code>$more /etc/freetds/freetds.conf\n[10.0.1.251]\n host = 10.0.1.251\n port = 1433\n tds version = 8.0\n\n$ more /etc/odbc.ini\n[ACCT]\nDriver = /usr/local/freetds/lib/libtdsodbc.so\nDescription = ODBC to SQLServer via FreeTDS\nTrace = No\nServername = 10.0.1.251\nDatabase = accounts_ver8\n</code></pre>\n"
},
{
"answer_id": 149429,
"author": "SteinNorheim",
"author_id": 19220,
"author_profile": "https://Stackoverflow.com/users/19220",
"pm_score": 3,
"selected": false,
"text": "<p>Mono contains an ADO.NET provider that should do this for you. I don't know if there is a command line utility for it, but you could definitely wrap up some C# to do the queries if there isn't. </p>\n\n<p>Have a look at <a href=\"http://www.mono-project.com/TDS_Providers\" rel=\"nofollow noreferrer\">http://www.mono-project.com/TDS_Providers</a> and <a href=\"http://www.mono-project.com/SQLClient\" rel=\"nofollow noreferrer\">http://www.mono-project.com/SQLClient</a></p>\n"
},
{
"answer_id": 149449,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 2,
"selected": false,
"text": "<p>You don't say what you want to do with the resulting data, but if it's general queries for development/maintenance then I'd have thought Remote Desktop to the windows server and then using the actual SQL Server tools on their would always have been a more productive option over any hacked together solution on Linux itself.</p>\n"
},
{
"answer_id": 149496,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://pymssql.sourceforge.net/\" rel=\"noreferrer\">pymssql</a> is a DB-API Python module, based on FreeTDS. It worked for me. Create some helper functions, if you need, and use it from Python shell.</p>\n"
},
{
"answer_id": 149519,
"author": "Taptronic",
"author_id": 14728,
"author_profile": "https://Stackoverflow.com/users/14728",
"pm_score": 2,
"selected": false,
"text": "<p>There is an abstraction lib available for PHP. Not sure what your client's box will support but if its Linux then certainly should support building a PHP query interface with this:\n<a href=\"http://adodb.sourceforge.net/\" rel=\"nofollow noreferrer\">http://adodb.sourceforge.net/</a> Hope that helps you.</p>\n"
},
{
"answer_id": 150895,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.sqsh.org/\" rel=\"nofollow noreferrer\">sqsh</a> + <a href=\"https://www.freetds.org\" rel=\"nofollow noreferrer\">freetds</a>.</p>\n<p>sqsh was primarily an isql replacement for Sybase SQL Server (now ASE) but it works just fine for connecting to SQL Server (provided you use freetds).</p>\n<p>To compile, simply point $SYBASE to freetds install and it should work from there. I use it on my Mac all day.</p>\n<p>The best part of sqsh are the advanced features, such as dead simple server linking (no need to set up linked servers in SQL Server), flow control and looping (no more concatenating strings and executing dynamic SQL), and invisible bulk copy/load.</p>\n<p>Anyone who uses any other command line tool is simply crazy! :)</p>\n"
},
{
"answer_id": 150918,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using Java, have a look at JDBC.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms378672(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms378672(SQL.90).aspx</a></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Jdbc\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Jdbc</a></p>\n"
},
{
"answer_id": 19522787,
"author": "François Neumann-rystow",
"author_id": 2907900,
"author_profile": "https://Stackoverflow.com/users/2907900",
"pm_score": 0,
"selected": false,
"text": "<p>I was not confortable with the freetds solution,\nit's why i coded a class (command history, autocompletion on tables and fields, etc.)</p>\n\n<p><a href=\"http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html\" rel=\"nofollow\">http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html</a></p>\n"
},
{
"answer_id": 23601136,
"author": "Muhammad Hasan Khan",
"author_id": 36464,
"author_profile": "https://Stackoverflow.com/users/36464",
"pm_score": 4,
"selected": false,
"text": "<p>sql-cli is a nodejs based cross platform command line interface for sql server. You can install it via npm <a href=\"https://www.npmjs.org/package/sql-cli\" rel=\"noreferrer\">https://www.npmjs.org/package/sql-cli</a> </p>\n\n<p>It can connect to both on-premise and sql azure instance.</p>\n"
},
{
"answer_id": 25948864,
"author": "mleu",
"author_id": 2809693,
"author_profile": "https://Stackoverflow.com/users/2809693",
"pm_score": 3,
"selected": false,
"text": "<p>Since <a href=\"http://blogs.technet.com/b/dataplatforminsider/archive/2011/11/28/available-today-preview-release-of-the-sql-server-odbc-driver-for-linux.aspx\" rel=\"noreferrer\">November 2011</a> Microsoft provides their own <a href=\"http://msdn.microsoft.com/en-us/sqlserver/connectivity#SNAC\" rel=\"noreferrer\">SQL Server ODBC Driver for Linux</a> for Red Hat Enterprise Linux (RHEL) and SUSE Linux Enterprise Server (SLES).</p>\n\n<ul>\n<li><a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=36437\" rel=\"noreferrer\">Download Microsoft ODBC Driver 11 for SQL Server on Red Hat Linux</a></li>\n<li><a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=34687\" rel=\"noreferrer\">Download Microsoft ODBC Driver 11 for SQL Server on SUSE - CTP</a></li>\n<li><a href=\"http://go.microsoft.com/fwlink/?LinkID=125813\" rel=\"noreferrer\">ODBC Driver on Linux Documentation</a></li>\n</ul>\n\n<p>It also includes <a href=\"http://msdn.microsoft.com/en-us/library/hh568447%28v=sql.110%29.aspx\" rel=\"noreferrer\"><code>sqlcmd</code></a> for Linux.</p>\n"
},
{
"answer_id": 50422823,
"author": "mohsen.nour",
"author_id": 3434956,
"author_profile": "https://Stackoverflow.com/users/3434956",
"pm_score": 0,
"selected": false,
"text": "<p><strong>valentina-db</strong> it has free version for sql server<br>\n.rpm and .deb<br>\n serial id will be sent by email after registration </p>\n\n<p><a href=\"https://www.valentina-db.com/en/\" rel=\"nofollow noreferrer\">https://www.valentina-db.com/en/</a> </p>\n\n<p><a href=\"https://valentina-db.com/en/store/category/14-free-products\" rel=\"nofollow noreferrer\">https://valentina-db.com/en/store/category/14-free-products</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/1vERC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1vERC.png\" alt=\"valentina-db\"></a></p>\n"
},
{
"answer_id": 51277532,
"author": "Mehdi",
"author_id": 1010619,
"author_profile": "https://Stackoverflow.com/users/1010619",
"pm_score": 0,
"selected": false,
"text": "<p>If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine.</p>\n"
},
{
"answer_id": 54808074,
"author": "helvete",
"author_id": 2915423,
"author_profile": "https://Stackoverflow.com/users/2915423",
"pm_score": 0,
"selected": false,
"text": "<p>There is a nice CLI based tool for accessing MSSQL databases <em>now</em>.</p>\n\n<p>It's called <code>mssql-cli</code> and it's a bit similar to postgres' <code>psql</code>.</p>\n\n<p><a href=\"https://github.com/dbcli/mssql-cli\" rel=\"nofollow noreferrer\">Gihub repository page</a></p>\n\n<p>Install for example via <code>pip</code> (global installation, for a local one omit the <code>sudo</code> part):</p>\n\n<pre><code>sudo pip install mssql-cli\n</code></pre>\n"
},
{
"answer_id": 60994296,
"author": "Moacir Rosa",
"author_id": 363072,
"author_profile": "https://Stackoverflow.com/users/363072",
"pm_score": 1,
"selected": false,
"text": "<p>I'd like to recommend <a href=\"https://www.electronjs.org/apps/sqlectron\" rel=\"nofollow noreferrer\">Sqlectron</a>. Besides being open source under MIT license it's multiplatform boosted by Electron. Its own definition is:</p>\n\n<blockquote>\n <p>A simple and lightweight SQL client desktop with cross database and platform support</p>\n</blockquote>\n\n<p>It <a href=\"https://github.com/sqlectron/sqlectron-core#current-supported-databases\" rel=\"nofollow noreferrer\">currently supports</a> PostgreSQL, MySQL, MS SQL Server, Cassandra and SQLite. </p>\n"
},
{
"answer_id": 68340084,
"author": "mwag",
"author_id": 3160967,
"author_profile": "https://Stackoverflow.com/users/3160967",
"pm_score": 1,
"selected": false,
"text": "<p>Surprised no one has mentioned that, contrary to what other answers seem to suggest, FreeTDS is all you need. No need for unixODBC, iODBC or anything else on top of it.</p>\n<blockquote>\n<p>run some database queries [...] command-line utility similar to sqlcmd on Windows</p>\n</blockquote>\n<p><code>tsql</code> does this and is part of the FreeTDS package (as are <code>freebcp</code> and other utilities). <code>tsql</code> does not have fancy UI, but if you want a command-line utility that is light, functional and performant, it'll do just fine.</p>\n<p>See e.g. <a href=\"https://stackoverflow.com/questions/17078869/how-to-run-a-sql-script-in-tsql\">How to run a SQL script in tsql</a></p>\n<p>And by light, I mean under 500kb in size (maybe under 60k depending on how it's compiled) and, as far as I have seen, extremely efficient with memory and CPU.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
]
| We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on Windows. | [FreeTDS](http://www.freetds.org) + [unixODBC](http://www.unixodbc.org) or [iODBC](http://www.iodbc.org)
Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.
unixODBC has isql, iODBC has iodbctest
You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)
I'm personally using FreeTDS + iODBC:
```
$more /etc/freetds/freetds.conf
[10.0.1.251]
host = 10.0.1.251
port = 1433
tds version = 8.0
$ more /etc/odbc.ini
[ACCT]
Driver = /usr/local/freetds/lib/libtdsodbc.so
Description = ODBC to SQLServer via FreeTDS
Trace = No
Servername = 10.0.1.251
Database = accounts_ver8
``` |
149,416 | <p>I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days.</p>
<p>Would it be better (more efficient) to code a SELECT statement like this...</p>
<pre><code>SELECT
CASE TermId
WHEN 1 THEN '30 days'
WHEN 2 THEN '60 days'
END AS Term
FROM MyTable
</code></pre>
<p>...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly?</p>
<p>Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server.</p>
| [
{
"answer_id": 149469,
"author": "hurcane",
"author_id": 21363,
"author_profile": "https://Stackoverflow.com/users/21363",
"pm_score": 0,
"selected": false,
"text": "<p>For a number of reasons, I would process the translation in the grid view.</p>\n\n<p>Reason #1: SQL resource is shared. Grid is distributed. Better scalability.</p>\n\n<p>Reason #2: Lower bandwidth to transmit a couple integers vs. strings.</p>\n\n<p>Reason #3: Code can be localized for other languages without affecting the SQL Server code.</p>\n"
},
{
"answer_id": 149483,
"author": "Kolten",
"author_id": 13959,
"author_profile": "https://Stackoverflow.com/users/13959",
"pm_score": 2,
"selected": true,
"text": "<p>Efficiency probably wouldn't matter here - code maintainability does though.\nAsk yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change?\nIf it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in a stored Procedure. If it's easier to change them in code later, then do that.\nThe benefits from doing either are quite low, as the code doesn't look complex at all.</p>\n"
},
{
"answer_id": 149761,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 0,
"selected": false,
"text": "<p>A field in a database table called TermID would imply itself to represent a foreign key to another table (perhaps called \"Term\"). </p>\n\n<p>If this is the case, then perhaps that table has (or should have), a Description field which could hold the \"30 days\" text. You could/should join to this table to retrieve the descriptive text.</p>\n\n<p>While this join might not improve efficiency, it it a light weight enough join to not get in the way.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54420/"
]
| I have a curious question about efficiency. Say I have a field on a database that is just a numeric digit that represents something else. Like, a value of 1 means the term is 30 days.
Would it be better (more efficient) to code a SELECT statement like this...
```
SELECT
CASE TermId
WHEN 1 THEN '30 days'
WHEN 2 THEN '60 days'
END AS Term
FROM MyTable
```
...and bind the results directly to the GridView, or would it be better to evaluate the TermId field in RowDataBound event of the GridView and change the cell text accordingly?
Don't worry about extensibility or anything like that, I am only concerned about the differences in overall efficiency. For what it's worth, the database resides on the web server. | Efficiency probably wouldn't matter here - code maintainability does though.
Ask yourself - will these values change? What if they do? What would I need to do after 2 years of use if these values change?
If it becomes evident that scripting them in SQL would mean better maintainability (easier to change), then do it in a stored Procedure. If it's easier to change them in code later, then do that.
The benefits from doing either are quite low, as the code doesn't look complex at all. |
149,439 | <p>How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.</p>
<pre><code>public interface Listener {
void callBack(Object arg);
}
public class ListenerImpl implements Listener {
public ListenerImpl(Broadcaster b) { b.register(this); }
public void callBack(Object arg) { ... }
public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
private final List listeners = new ArrayList();
public void register(Listener lis) { listeners.add(lis); }
public void unregister(Listener lis) {listeners.remove(lis); }
public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}
</code></pre>
| [
{
"answer_id": 149457,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 4,
"selected": true,
"text": "<p>I don't see that being a circular dependency.</p>\n\n<p>Listener depends on nothing.</p>\n\n<p>ListenerImpl depends on Listener and Broadcaster</p>\n\n<p>Broadcaster depends on Listener.</p>\n\n<pre><code> Listener\n ^ ^\n / \\\n / \\\nBroadcaster <-- ListenerImpl\n</code></pre>\n\n<p>All arrows end at Listener. There's no cycle. So, I think you're OK.</p>\n"
},
{
"answer_id": 149478,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a java dev, but something like this:</p>\n\n<pre><code>public class ListenerImpl implements Listener {\n public Foo() {}\n public void registerWithBroadcaster(Broadcaster b){ b.register(this); isRegistered = true;}\n public void callBack(Object arg) { if (!isRegistered) throw ... else ... }\n public void shutDown() { isRegistered = false; }\n}\n\npublic class Broadcaster {\n private final List listeners = new ArrayList();\n public void register(Listener lis) { listeners.add(lis); }\n public void unregister(Listener lis) {listeners.remove(lis); }\n public void broadcast(Object arg) { for (Listener lis : listeners) { if (lis.isRegistered) lis.callBack(arg) else unregister(lis); } }\n}\n</code></pre>\n"
},
{
"answer_id": 149693,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 3,
"selected": false,
"text": "<p>Any OOP language? OK. Here's a ten-minute version in CLOS.</p>\n\n<h1>Broadcasting framework</h1>\n\n<pre><code>(defclass broadcaster ()\n ((listeners :accessor listeners\n :initform '())))\n\n(defgeneric add-listener (broadcaster listener)\n (:documentation \"Add a listener (a function taking one argument)\n to a broadcast's list of interested parties\"))\n\n(defgeneric remove-listener (broadcaster listener)\n (:documentation \"Reverse of add-listener\"))\n\n(defgeneric broadcast (broadcaster object)\n (:documentation \"Broadcast an object to all registered listeners\"))\n\n(defmethod add-listener (broadcaster listener)\n (pushnew listener (listeners broadcaster)))\n\n(defmethod remove-listener (broadcaster listener)\n (let ((listeners (listeners broadcaster)))\n (setf listeners (remove listener listeners))))\n\n(defmethod broadcast (broadcaster object)\n (dolist (listener (listeners broadcaster))\n (funcall listener object)))\n</code></pre>\n\n<h1>Example subclass</h1>\n\n<pre><code>(defclass direct-broadcaster (broadcaster)\n ((latest-broadcast :accessor latest-broadcast)\n (latest-broadcast-p :initform nil))\n (:documentation \"I broadcast the latest broadcasted object when a new listener is added\"))\n\n(defmethod add-listener :after ((broadcaster direct-broadcaster) listener)\n (when (slot-value broadcaster 'latest-broadcast-p)\n (funcall listener (latest-broadcast broadcaster))))\n\n(defmethod broadcast :after ((broadcaster direct-broadcaster) object)\n (setf (slot-value broadcaster 'latest-broadcast-p) t)\n (setf (latest-broadcast broadcaster) object))\n</code></pre>\n\n<h1>Example code</h1>\n\n<pre><code>Lisp> (let ((broadcaster (make-instance 'broadcaster)))\n (add-listener broadcaster \n #'(lambda (obj) (format t \"I got myself a ~A object!~%\" obj)))\n (add-listener broadcaster \n #'(lambda (obj) (format t \"I has object: ~A~%\" obj)))\n (broadcast broadcaster 'cheezburger))\n\nI has object: CHEEZBURGER\nI got myself a CHEEZBURGER object!\n\nLisp> (defparameter *direct-broadcaster* (make-instance 'direct-broadcaster))\n (add-listener *direct-broadcaster*\n #'(lambda (obj) (format t \"I got myself a ~A object!~%\" obj)))\n (broadcast *direct-broadcaster* 'kitty)\n\nI got myself a KITTY object!\n\nLisp> (add-listener *direct-broadcaster*\n #'(lambda (obj) (format t \"I has object: ~A~%\" obj)))\n\nI has object: KITTY\n</code></pre>\n\n<p>Unfortunately, Lisp solves most of the design pattern problems (such as yours) by eliminating the need for them.</p>\n"
},
{
"answer_id": 149884,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 3,
"selected": false,
"text": "<p>In contrast to Herms' answer, I <b>do</b> see a loop. It's not a dependency loop, it's a a reference loop: LI holds the B object, the B object holds (an Array of) LI object(s). They don't free easily, and care needs to be taken to ensure that they free when possible.</p>\n\n<p>One workaround is simply to have the LI object hold a WeakReference to the broadcaster. Theoretically, if the broadcaster has gone away, there's nothing to deregister with anyway, so then your deregistration will simply check if there is a broadcaster to deregister from, and do so if there is.</p>\n"
},
{
"answer_id": 161516,
"author": "janm",
"author_id": 7256,
"author_profile": "https://Stackoverflow.com/users/7256",
"pm_score": 0,
"selected": false,
"text": "<p>Use weak references to break the cycle. </p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/157856/do-java-listeners-need-to-be-removed-in-the-finalize-method#157903\">this answer</a>.</p>\n"
},
{
"answer_id": 325391,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an example in Lua (I use my own <a href=\"http://luaforge.net/projects/objectlua/\" rel=\"nofollow noreferrer\">Oop lib</a> here, see references to 'Object' in the code).</p>\n\n<p>Like in Mikael Jansson's CLOS example, your can use functions directly, removing the need of defining listeners (note the use of '...', it's Lua's varargs):</p>\n\n<pre><code>Broadcaster = Object:subclass()\n\nfunction Broadcaster:initialize()\n self._listeners = {}\nend\n\nfunction Broadcaster:register(listener)\n self._listeners[listener] = true\nend\n\nfunction Broadcaster:unregister(listener)\n self._listeners[listener] = nil\nend\nfunction Broadcaster:broadcast(...)\n for listener in pairs(self._listeners) do\n listener(...)\n end\nend\n</code></pre>\n\n<p>Sticking to your implementation, here's an example that could be written in any dynamic language I guess:</p>\n\n<pre><code>--# Listener\nListener = Object:subclass()\nfunction Listener:callback(arg)\n self:subclassResponsibility()\nend\n\n--# ListenerImpl\nfunction ListenerImpl:initialize(broadcaster)\n self._broadcaster = broadcaster\n broadcaster:register(this)\nend\nfunction ListenerImpl:callback(arg)\n --# ...\nend\nfunction ListenerImpl:shutdown()\n self._broadcaster:unregister(self)\nend\n\n--# Broadcaster\nfunction Broadcaster:initialize()\n self._listeners = {}\nend\nfunction Broadcaster:register(listener)\n self._listeners[listener] = true\nend\nfunction Broadcaster:unregister(listener)\n self._listeners[listener] = nil\nend\nfunction Broadcaster:broadcast(arg)\n for listener in pairs(self._listeners) do\n listener:callback(arg)\n end\nend\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16399/"
]
| How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.
```
public interface Listener {
void callBack(Object arg);
}
public class ListenerImpl implements Listener {
public ListenerImpl(Broadcaster b) { b.register(this); }
public void callBack(Object arg) { ... }
public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
private final List listeners = new ArrayList();
public void register(Listener lis) { listeners.add(lis); }
public void unregister(Listener lis) {listeners.remove(lis); }
public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}
``` | I don't see that being a circular dependency.
Listener depends on nothing.
ListenerImpl depends on Listener and Broadcaster
Broadcaster depends on Listener.
```
Listener
^ ^
/ \
/ \
Broadcaster <-- ListenerImpl
```
All arrows end at Listener. There's no cycle. So, I think you're OK. |
149,463 | <p>I have this code inside a class:</p>
<pre><code>void SendStones()
{
int currenthole = hole;
int lastplace = 0;
for(int i=0;i<stns.size();i++)
{
while(1)
{//Calculate new currenthole
if(currenthole == 13) { currenthole = 7; break;}
if(currenthole == 14) { currenthole = 6; break;}
if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;}
}
lastplace = stns.size()-1;
hole[currenthole]->ReciveStone(stns[lastplace]);//PROBLEM
stns.pop_back();
}
}
vector<Stones*> stns;
</code></pre>
<p>so it makes this error:
invalid types `int[int]' for array subscript </p>
<p>what's the problem?i don't understand.
Thanks.</p>
| [
{
"answer_id": 149482,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like hole is a simple int, and you're trying to subscript it. Is that what you mean to do? Where is hole declared?</p>\n"
},
{
"answer_id": 149502,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Hole is a really big class,<br>\nSendStones is a function member in the class.<br>\nI won't send the whole file but i can say that <br>\nhole[currenthole] is a Hole *hole[14];<br>\nIt's a big program and project so i sent the related code needed.<br></p>\n\n<p>Here's the code of the ReciveStones function:</p>\n\n<p><br><br>\nvoid ReciveStone(Stone *rcvstone)\n {\n stns.push_back(rcvstone);\n }<br></p>\n"
},
{
"answer_id": 149562,
"author": "moswald",
"author_id": 8368,
"author_profile": "https://Stackoverflow.com/users/8368",
"pm_score": 0,
"selected": false,
"text": "<p>Based on what you said in your answer, hole is a pointer to <em>n</em> Hole objects. That means your code isn't doing what you think it's doing.</p>\n\n<pre><code>int currenthole = hole;\n</code></pre>\n\n<p>This is storing an address value pointing to the first object in your array collection, which means that this code</p>\n\n<pre><code>if(currenthole == 13) { currenthole = 7; break;}\n if(currenthole == 14) { currenthole = 6; break;}\n if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;}\n</code></pre>\n\n<p>is probably nonsense.</p>\n\n<p>It doesn't explain why you're getting the <em>\"invalid types `int[int]' for array subscript\"</em> error. Are you sure that there's not a second declaration of type <em>int</em> named <em>hole</em>?</p>\n\n<p>--Actually, re-reading what you wrote, I'm even more certain you're not doing what you think you're doing. SendStones is a member of the class Hole, correct? Check that your Hole class doesn't have a hole member variable inside it. That is probably the problem, since it will be found before any global variable called hole (if I remember my scoping rules correctly).</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have this code inside a class:
```
void SendStones()
{
int currenthole = hole;
int lastplace = 0;
for(int i=0;i<stns.size();i++)
{
while(1)
{//Calculate new currenthole
if(currenthole == 13) { currenthole = 7; break;}
if(currenthole == 14) { currenthole = 6; break;}
if((currenthole<=12 && currenthole > 7) || (currenthole<=6 && currenthole > 1)) { currenthole--; break;}
}
lastplace = stns.size()-1;
hole[currenthole]->ReciveStone(stns[lastplace]);//PROBLEM
stns.pop_back();
}
}
vector<Stones*> stns;
```
so it makes this error:
invalid types `int[int]' for array subscript
what's the problem?i don't understand.
Thanks. | It looks like hole is a simple int, and you're trying to subscript it. Is that what you mean to do? Where is hole declared? |
149,474 | <p>This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.</p>
<pre><code>big_story_export.xml
</code></pre>
<p>turns into</p>
<pre><code>lifestyles.xml
food.xml
nascar.xml
</code></pre>
<p>...and so on.</p>
<p>I got the job done using a one-off python script, <em>however</em>, <strong>I originally attempted this using XSLT</strong>. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...<em>nothing</em>.</p>
<p>What strategies do you recommend for ensuring that files like this will run through XSLT? <em>This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file.</em></p>
<p>If you guys want code samples, I'll put some together. </p>
<p>If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly.</p>
<hr>
<p>@Sklivvz</p>
<p>I was using python's libxml2 & libxslt to process this. I'm looking into xsltproc now. </p>
<p>It seems like a good tool for these one-off situations. Thanks!</p>
<hr>
<p>@diomidis-spinellis</p>
<p>It's well-formed, though (as mentioned) I don't have faculties to discover it's validity.</p>
<p>As for writing a Schema, I like the idea. </p>
<p>The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor.</p>
<p>Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks!</p>
| [
{
"answer_id": 149495,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "<p>What language/parser were you using?<br>\nFor large files I try to use Unix command line tools.<br>\nThey are usually much, much more efficient than other solutions and don't \"crap out\" on large files.</p>\n\n<p>Try using <code>xsltproc</code></p>\n"
},
{
"answer_id": 149524,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 3,
"selected": true,
"text": "<p>This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file.</p>\n\n<ol>\n<li>Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like <a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">xmlstarlet</a>, can tell you that.</li>\n<li>Does the file contain valid XML? For this you need a schema and an XML validator (<a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">xmlstarlet</a> can do this trick as well). I suggest you invest some effort to write the schema definition of your file. It will simplify a lot your debugging, because you can then easily pinpoint the exact source of problems you may be having.</li>\n</ol>\n\n<p>If the file is well-formed and valid, but the XSLT processor still refuses to give you the results you would expect, you can be sure that the problem lies in the processor, and you should try a different one.</p>\n"
},
{
"answer_id": 149857,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>Can I recommend Saxon XSLT processor - I know for a fact it can handle large files, provided you give the Java JVM enough memory.</p>\n\n<p>Another thing is that there may be optimisations n your XSLT that could help, but its hard to make blanket statements about things like that.</p>\n"
},
{
"answer_id": 150755,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with using XSLT to process arbitrarily large XML documents is that XSLT processing begins by parsing the input document into a source tree. This tree gets parsed into memory. This means that eventually you'll encounter an input document large enough to cause problems even if you're using a robust XSLT processor like Saxon and you have plenty of virtual memory. (It may still work, but it'll be slow.)</p>\n\n<p>Another reason not to use XSLT for this is that you're producing multiple output documents, which (based on what you've said so far) means you're making multiple passes over your input document.</p>\n\n<p>It may (depending on a lot of factors about your situation that I don't know about) be better to take a SAX-based approach instead of using XSLT. Using a SAX processor, you may be able to write a method that makes a single, forward-only pass through the source document, parsing it as it goes, and writes all of the output documents as it encounters the elements that contain them.</p>\n"
},
{
"answer_id": 231351,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 0,
"selected": false,
"text": "<p>Check out Apache's <a href=\"http://xml.apache.org/xalan-c/index.html\" rel=\"nofollow noreferrer\">Xalan C++</a>. In my experience, where others (including Saxon) have failed on \"large\" XML files (>600 MB), this was able to run with memory to spare. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22491/"
]
| This XML file contained archived news stories for all of last year. I was asked to sort these stories by story categor[y|ies] into new XML files.
```
big_story_export.xml
```
turns into
```
lifestyles.xml
food.xml
nascar.xml
```
...and so on.
I got the job done using a one-off python script, *however*, **I originally attempted this using XSLT**. This resulted in frustration as my XPATH selections were crapping the bed. Test files were transformed perfectly, but putting the big file up against my style sheet resulted in ...*nothing*.
What strategies do you recommend for ensuring that files like this will run through XSLT? *This was handed to me by a vendor, so imagine that I don't have a lot of leverage when it comes to defining the structure of this file.*
If you guys want code samples, I'll put some together.
If anything, I'd be satisfied with some tips for making XML+XSLT work together smoothly.
---
@Sklivvz
I was using python's libxml2 & libxslt to process this. I'm looking into xsltproc now.
It seems like a good tool for these one-off situations. Thanks!
---
@diomidis-spinellis
It's well-formed, though (as mentioned) I don't have faculties to discover it's validity.
As for writing a Schema, I like the idea.
The amount of time I invest in getting this one file validated would be impractical if it were a one-time thing, though I foresee having to handle more files like this from our vendor.
Writing a schema (and submitting it to the vendor) would be an excellent long-term strategy for managing XML funk like this. Thanks! | This sounds like a bug in the large XML file or the XSLT processor. There are two things you should check on your file.
1. Is the file well-formed XML? That is, are all tags and attributes properly terminated and matched? An XML processor, like [xmlstarlet](http://xmlstar.sourceforge.net/), can tell you that.
2. Does the file contain valid XML? For this you need a schema and an XML validator ([xmlstarlet](http://xmlstar.sourceforge.net/) can do this trick as well). I suggest you invest some effort to write the schema definition of your file. It will simplify a lot your debugging, because you can then easily pinpoint the exact source of problems you may be having.
If the file is well-formed and valid, but the XSLT processor still refuses to give you the results you would expect, you can be sure that the problem lies in the processor, and you should try a different one. |
149,479 | <p>Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.</p>
| [
{
"answer_id": 149494,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 4,
"selected": false,
"text": "<p>You may want to look at <a href=\"http://tug.ctan.org/tex-archive/macros/latex/contrib/float/\" rel=\"nofollow noreferrer\"><a href=\"http://tug.ctan.org/tex-archive/macros/latex/contrib/float/\" rel=\"nofollow noreferrer\">http://tug.ctan.org/tex-archive/macros/latex/contrib/float/</a></a> which allows you to define new floats using <code>\\newfloat</code></p>\n\n<p>I say this because captions are usually applied to floats.</p>\n\n<p>Straight ahead equations (those written with <code>$ ... $</code>, <code>$$ ... $$</code>, <code>begin{equation}...</code>) are in-line objects that do not support <code>\\caption</code>.</p>\n\n<p>This can be done using the following <a href=\"https://tex.stackexchange.com/a/97034/149720\">snippet</a> just before <code>\\begin{document}</code></p>\n\n<pre><code>\\usepackage{float}\n\\usepackage{aliascnt}\n\\newaliascnt{eqfloat}{equation}\n\\newfloat{eqfloat}{h}{eqflts}\n\\floatname{eqfloat}{Equation}\n\n\\newcommand*{\\ORGeqfloat}{}\n\\let\\ORGeqfloat\\eqfloat\n\\def\\eqfloat{%\n \\let\\ORIGINALcaption\\caption\n \\def\\caption{%\n \\addtocounter{equation}{-1}%\n \\ORIGINALcaption\n }%\n \\ORGeqfloat\n}\n</code></pre>\n\n<p>and when adding an equation use something like</p>\n\n<pre><code>\\begin{eqfloat}\n\\begin{equation}\nf( x ) = ax + b\n\\label{eq:linear}\n\\end{equation}\n\\caption{Caption goes here}\n\\end{eqfloat}\n</code></pre>\n"
},
{
"answer_id": 149677,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 7,
"selected": true,
"text": "<p>The <code>\\caption</code> command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:</p>\n\n<pre><code>\\begin{figure}\n\\[ E = m c^2 \\]\n\\caption{A famous equation}\n\\end{figure}\n</code></pre>\n\n<p>The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The <code>\\captionof</code> command of the <a href=\"http://www.tex.ac.uk/tex-archive/macros/latex/contrib/caption/caption-eng.pdf\" rel=\"noreferrer\">caption package</a> can be used to place a caption outside of a floating environment. It is used like this:</p>\n\n<pre><code>\\[ E = m c^2 \\]\n\\captionof{figure}{A famous equation}\n</code></pre>\n\n<p>This will also produce an entry for the <code>\\listoffigures</code>, if your document has one.</p>\n\n<p>To align parts of an equation, take a look at the <a href=\"http://www.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-223.html\" rel=\"noreferrer\"><code>eqnarray</code> environment</a>, or some of the environments of the <a href=\"http://www.ams.org/tex/amslatex.html\" rel=\"noreferrer\">amsmath</a> package: align, gather, multiline,...</p>\n"
},
{
"answer_id": 47840493,
"author": "MattAllegro",
"author_id": 3543233,
"author_profile": "https://Stackoverflow.com/users/3543233",
"pm_score": 4,
"selected": false,
"text": "<p>As in this <a href=\"http://latex.org/forum/viewtopic.php?t=6343\" rel=\"noreferrer\">forum post by Gonzalo Medina</a>, a third way may be:</p>\n<pre class=\"lang-latex prettyprint-override\"><code>\\documentclass{article}\n\\usepackage{caption}\n\n\\DeclareCaptionType{equ}[][]\n%\\captionsetup[equ]{labelformat=empty}\n\n\\begin{document}\n\nSome text\n\n\\begin{equ}[!ht]\n \\begin{equation}\n a=b+c\n \\end{equation}\n\\caption{Caption of the equation}\n\\end{equ}\n\nSome other text\n \n\\end{document}\n</code></pre>\n<p>More details of the commands used from package <a href=\"https://ctan.org/pkg/caption\" rel=\"noreferrer\"><code>caption</code></a>: <a href=\"https://ctan.mirror.garr.it/mirrors/ctan/macros/latex/contrib/caption/caption-eng.pdf\" rel=\"noreferrer\">here</a>.</p>\n<p>A screenshot of the output of the above code:</p>\n<p><a href=\"https://i.stack.imgur.com/YQHsQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YQHsQ.png\" alt=\"screenshot of output\" /></a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
]
| Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great. | The `\caption` command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:
```
\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}
```
The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The `\captionof` command of the [caption package](http://www.tex.ac.uk/tex-archive/macros/latex/contrib/caption/caption-eng.pdf) can be used to place a caption outside of a floating environment. It is used like this:
```
\[ E = m c^2 \]
\captionof{figure}{A famous equation}
```
This will also produce an entry for the `\listoffigures`, if your document has one.
To align parts of an equation, take a look at the [`eqnarray` environment](http://www.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-223.html), or some of the environments of the [amsmath](http://www.ams.org/tex/amslatex.html) package: align, gather, multiline,... |
149,484 | <p>I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like:</p>
<pre><code>Public Function Build(Of T) as T
If T Is IDoSomething then
Return New DoSomething()
ElseIf T Is IAndSoOn Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub
</code></pre>
<p>But this code does not compile.</p>
| [
{
"answer_id": 149536,
"author": "codeConcussion",
"author_id": 1321,
"author_profile": "https://Stackoverflow.com/users/1321",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Public Function Build(Of T) As T\n Dim foo As Type = GetType(T)\n\n If foo Is GetType(IDoSomething) Then\n Return New DoSomething()\n ...\n End If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 149603,
"author": "Drak",
"author_id": 22939,
"author_profile": "https://Stackoverflow.com/users/22939",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Public Function Build(Of T) as T \n If T.gettype Is gettype(IDoSomething) then \n Return New DoSomething() \n ElseIf T.gettype Is gettype(IAndSoOn) Then \n Return New AndSoOn() \n Else \n Throw New WhatWereYouThinkingException(\"Bad\") \n End If \nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like:
```
Public Function Build(Of T) as T
If T Is IDoSomething then
Return New DoSomething()
ElseIf T Is IAndSoOn Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub
```
But this code does not compile. | ```
Public Function Build(Of T) As T
Dim foo As Type = GetType(T)
If foo Is GetType(IDoSomething) Then
Return New DoSomething()
...
End If
End Function
``` |
149,485 | <p>Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc..</p>
<p>What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server?</p>
<p>Mainly, we do not want to expose production credentials to every developer.</p>
| [
{
"answer_id": 149497,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>I would not store configuration information in the repository at all. That way you don't have to worry about SVN trying to update the config when you update your source. </p>\n"
},
{
"answer_id": 149542,
"author": "Jurassic_C",
"author_id": 20572,
"author_profile": "https://Stackoverflow.com/users/20572",
"pm_score": 0,
"selected": false,
"text": "<p>I would agree with adam. If its not something that benefits everybody who works on the project, it shouldn't be under version control. If somebody checks out a copy of your code, will your personal project files help them? Probably not. It would most likely just clutter things up.</p>\n"
},
{
"answer_id": 149590,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 3,
"selected": false,
"text": "<p>I'd rather provide configuration examples than real config files. In my project there is <code>setup.default.php</code> file in root directory that every user need to copy as <code>setup.php</code> and amend to match local environment. Additionally, to prevent checking in back customised setup files there is a rule for it in <code>.svnignore</code>.</p>\n\n<pre><code>$ echo 'setup.php' > .svnignore\n$ svn propset svn:ignore -F .svnignore .\n</code></pre>\n"
},
{
"answer_id": 150475,
"author": "jW.",
"author_id": 8880,
"author_profile": "https://Stackoverflow.com/users/8880",
"pm_score": 2,
"selected": false,
"text": "<p>This is a problem I have run into as well. I think the answer is to check in a Template (such as you have with setup.php.default) and then use an automated tool such as <a href=\"http://phing.info/trac/\" rel=\"nofollow noreferrer\">Phing</a> to make the push to development. If you use recognizable tokens in the setup.php file then Phing will be able to replace these tokens with individual server values. Also, an easy one step push live will be a helpful process to have.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc..
What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server?
Mainly, we do not want to expose production credentials to every developer. | I'd rather provide configuration examples than real config files. In my project there is `setup.default.php` file in root directory that every user need to copy as `setup.php` and amend to match local environment. Additionally, to prevent checking in back customised setup files there is a rule for it in `.svnignore`.
```
$ echo 'setup.php' > .svnignore
$ svn propset svn:ignore -F .svnignore .
``` |
149,491 | <p>I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower <a href="http://en.wikipedia.org/wiki/CamelCase" rel="noreferrer">CamelCasing</a>. They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:</p>
<pre><code>string firstName;
public string FirstName {
...
}
</code></pre>
<p>But they are used to this:</p>
<pre><code>string _firstname;
public string firstName {
...
}
</code></pre>
<p>I try to keep up with their "standard" so the code looks the same but I just don't like it.</p>
<p>I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:</p>
<pre><code>System.Console.WriteLine("string")
</code></pre>
<p>What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.</p>
<p><strong>Update:</strong>
I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.)</p>
| [
{
"answer_id": 149507,
"author": "Dennis S.",
"author_id": 22250,
"author_profile": "https://Stackoverflow.com/users/22250",
"pm_score": 2,
"selected": false,
"text": "<p>I (and my team) prefer to reserve initial capitals for class names. </p>\n\n<p>Why? Java standards propagating, I think.</p>\n"
},
{
"answer_id": 149508,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>Pascal casing should be used for Properties. As far as varible names go, some people use _ and some poeple use m_ and some people just use plain old camel casing. I think that as long as you ae consistant here, it shouldn't matter.</p>\n"
},
{
"answer_id": 149511,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "<p>That example of .NET you posted was a function. The adopted \"standard\" for methods/functions is A capped camel-case (or Pascal, if you want to call it that).</p>\n\n<p>I stick to camel case where I can. It lets you easily know the difference between a variable and a method.</p>\n\n<p>Additionally, I'm a fan of sticking an underscore in front of local class variables. E.g.: <code>_localVar</code>.</p>\n"
},
{
"answer_id": 149516,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 6,
"selected": true,
"text": "<p>I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is <strong>consistently</strong> using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all.</p>\n"
},
{
"answer_id": 149520,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 3,
"selected": false,
"text": "<p>For public interfaces you should stick with the MS .NET framework design \nguidelines: \"<a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"nofollow noreferrer\">Capitalization Conventions</a>\".</p>\n\n<p>For non-exposed members then whatever you and your colleagues can agree on.</p>\n"
},
{
"answer_id": 149526,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>I guess you have to put up with what the coding standard says for your place of work, however much you personally dislike it. Maybe one day in the future you will be able to dictate your own coding standards.</p>\n\n<p>Personally I like databases to use names of the form \"fish_name\", \"tank_id\", etc for tables and fields, whereas the code equivalent of the database model would be \"fishName\" and \"tankID\". I also dislike \"_fooname\" naming when \"fooName\" is available. But I must repeat that this is subjective, and different people will have different ideas about what is good and bad due to their prior experience and education.</p>\n"
},
{
"answer_id": 149527,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>A link to the official <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/\" rel=\"nofollow noreferrer\">design guidelines</a> might help. Specifically, read the section on <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions#capitalizing-compound-words-and-common-terms\" rel=\"nofollow noreferrer\">Capitalization styles</a>.</p>\n\n<p>In the grand scheme of things, Pascal vs Camel doesn't matter that much and you're not likely to convince anyone to go back over an existing code base just to change the case of names. What's really important is that you want to be consistent within a given code base.</p>\n\n<p>I'm just happy as long as you're not using Hungarian.</p>\n"
},
{
"answer_id": 149539,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, there's no \"standard\" convention on this. There's a Microsoft edited guideline somewhere, and as with with any other naming convention guideline, surely there's another one refuting it, but here's what I've come to understand as \"standard C# casing convention\".</p>\n\n<ol>\n<li>PerWordCaps in type names (classes, enums), constants and properties.</li>\n<li>camelCase for really long local variables and protected/private variables</li>\n<li>No ALL_CAPS <strong>ever</strong> (well, only in compiler defines, but not in your code)</li>\n<li>It seems some of the system classes use underscored names (_name) for private variables, but I guess that comes from the original writer's background as most of them came straight from C++. Also, notice that VB.NET isn't case sensitive, so you wouldn't be able to access the protected variables if you extended the class.</li>\n</ol>\n\n<p>Actually, <a href=\"http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx\" rel=\"nofollow noreferrer\">FxCop</a> will enforce a few of those rules, but (AFAIK) it ignores whatever spelling you use for local variables.</p>\n"
},
{
"answer_id": 149568,
"author": "Tanj",
"author_id": 4275,
"author_profile": "https://Stackoverflow.com/users/4275",
"pm_score": 0,
"selected": false,
"text": "<p>I like the coding conventions laid out in the <a href=\"http://www.joelonsoftware.com/articles/AardvarkSpec.html\" rel=\"nofollow noreferrer\">Aardvark'd</a> project spec</p>\n"
},
{
"answer_id": 149619,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 4,
"selected": false,
"text": "<p>You should have a look at Microsoft's new tool, <a href=\"http://code.msdn.microsoft.com/sourceanalysis\" rel=\"noreferrer\">StyleCop</a> for checking C# source code.\nAlso keep an eye on <a href=\"http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx\" rel=\"noreferrer\">FxCop</a> for checking compiled .Net assemblies. FxCop focuses more on the details of what the code does, not the layout, but it does have some naming rules related to publicly visible names.</p>\n\n<p>StyleCop defines a coding standard, which is now being promoted by Microsoft as an industry standard. It checks C# source code against the standard.\nStyleCop adheres to your PascalCase style.</p>\n\n<p>Getting people onto StyleCop (or any other standard for that matter) can be hard, it's quite a hurdle, and StyleCop is quite exhaustive. But code should be to a uniform standard - and a personal standard is better than none, company standard is better than a personal one, and an industry standard is best of all.</p>\n\n<p>It's a lot easier to convince people when a a project starts - team is being formed and there is no existing code to convert. And you can put tools (FxCop, StyleCop) in place to break the build if the code does not meet standards.</p>\n\n<p>You should use the standard for the language and framework - SQL code should use SQL standards, and C# code should use C# standards.</p>\n"
},
{
"answer_id": 549526,
"author": "Tom A",
"author_id": 10226,
"author_profile": "https://Stackoverflow.com/users/10226",
"pm_score": 1,
"selected": false,
"text": "<p>From\n.NET Framework Developer's Guide\n<a href=\"https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"nofollow noreferrer\">Capitalization Conventions</a>, Case-Sensitivity: </p>\n\n<blockquote>\n <p>The capitalization guidelines exist\n solely to make identifiers easier to\n read and recognize. Casing cannot be\n used as a means of avoiding name\n collisions between library elements. </p>\n \n <p>Do not assume that all programming\n languages are case-sensitive. They are\n not. Names cannot differ by case\n alone.</p>\n</blockquote>\n"
},
{
"answer_id": 6840874,
"author": "Naveen Vijay",
"author_id": 649408,
"author_profile": "https://Stackoverflow.com/users/649408",
"pm_score": 1,
"selected": false,
"text": "<p>I just found <a href=\"http://se.inf.ethz.ch/old/teaching/ss2007/251-0290-00/project/CSharpCodingStandards.pdf\" rel=\"nofollow\">Coding Standards for .Net</a>.</p>\n"
},
{
"answer_id": 15917051,
"author": "newbprofi",
"author_id": 2227633,
"author_profile": "https://Stackoverflow.com/users/2227633",
"pm_score": -1,
"selected": false,
"text": "<p>The day when i quit programming - its when Microsoft will make CamelCase in C# as standard. Because my grown logic has many reasons for PascalCase, unlike kid's logic, who cares only shorter names or easier to write.</p>\n\n<p>And BTW: CamelCasing comes primarily from C++ STD library style, the native old language inherited from C. So Java inherited from C++. But C# - is entirely new language - clean and beauty, with new rules. Oldfags must programm on Java or C++, new generation people must programm on C# - and they should never interact.</p>\n\n<p>Consider this example:\n1) PascalCase: list.Capacity.ToString();\n2) CamelCase: list.capacity.toString();</p>\n\n<p>In (1) we have CAMEL CASE in long TERM!!! means listCapacityToString.\nIn (2) we have bullshit: listcapacitytoString.</p>\n\n<p>Thats how i read. And why CamelCase is illogical for itselt. I could kill for PascalCase, never touch it, kids of any age.</p>\n\n<p>Microsoft - forever or until they use PascalCase.</p>\n"
},
{
"answer_id": 43342665,
"author": "Daniel",
"author_id": 7849938,
"author_profile": "https://Stackoverflow.com/users/7849938",
"pm_score": -1,
"selected": false,
"text": "<p>Whichever you prefer is what matters, obviously adhering to the team's standard primarily.\nIn private you code however you want, it doesn't affect the finished product whether you named your variable someVariable or SomeVariable.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14533/"
]
| I've been arguing with my coworkers about Pascal casing (upper camel case) vs. lower [CamelCasing](http://en.wikipedia.org/wiki/CamelCase). They are used to lower camel casing for everything from table names in SQL databases to property naming in C# code but I like Pascal casing better, lower camel casing for variables and Pascal casing for properties:
```
string firstName;
public string FirstName {
...
}
```
But they are used to this:
```
string _firstname;
public string firstName {
...
}
```
I try to keep up with their "standard" so the code looks the same but I just don't like it.
I've seen that at least the .NET framework uses this convention and that is how I try to keep my code, e.g.:
```
System.Console.WriteLine("string")
```
What do you use/prefer and why? I'm sorry if somebody else asked this question but I searched and did not find anything.
**Update:**
I've given a method example and not a property but it's the same. As I stated in the first paragraph my colleagues use the Pascal convention for everything (variables, methods, table names, etc.) | I use what the Framework uses, as it's the de-facto best practice. However, so long as the code in your company is **consistently** using their style, then you're much better off getting used to it. If every developer has their own standard, then there's no standard at all. |
149,500 | <p>What does the following code do in C/C++?</p>
<pre><code>if (blah(), 5) {
//do something
}
</code></pre>
| [
{
"answer_id": 149514,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 7,
"selected": true,
"text": "<p>Comma operator is applied and the value 5 is used to determine the conditional's true/false.</p>\n\n<p>It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.</p>\n\n<hr>\n\n<p>Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.</p>\n"
},
{
"answer_id": 149517,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that depends on blah().</p>\n"
},
{
"answer_id": 149518,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 6,
"selected": false,
"text": "<p>If the comma operator is not overloaded, the code is similar to this:</p>\n\n<pre><code>blah();\nif (5) {\n // do something\n}\n</code></pre>\n\n<p>If the comma operator is overloaded, the result will be based on that function.</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nusing namespace std;\n\nstring blah()\n{\n return \"blah\";\n}\n\nbool operator,(const string& key, const int& val) {\n return false;\n}\n\nint main (int argc, char * const argv[]) {\n\n if (blah(), 5) {\n cout << \"if block\";\n } else {\n cout << \"else block\";\n }\n\n return 0;\n}\n</code></pre>\n\n<p><em>(edited to show comma operator overloading scenario. thanks to David Pierre for commenting on this)</em></p>\n"
},
{
"answer_id": 149533,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<p>The following was written assuming it is C code, either in a C file or within a C block of a C++ file:</p>\n\n<p>It is a pointless <em>if</em>. It will call blah(), however the result of blah() is not considered by <em>if</em> at all. The only thing being considered is 5, thus the if will always evaluate to true. IOW you could write this code as</p>\n\n<pre><code>blah();\n// do something\n</code></pre>\n\n<p>without any <em>if</em> at all.</p>\n"
},
{
"answer_id": 149594,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "<p>In the pathological case, it depends on what the comma operator does...</p>\n\n<pre><code>class PlaceHolder\n{\n};\n\nPlaceHolder Blah() { return PlaceHolder(); }\n\nbool operator,(PlaceHolder, int) { return false; }\n\nif (Blah(), 5)\n{\n cout << \"This will never run.\";\n}\n</code></pre>\n"
},
{
"answer_id": 149727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I know one thing that this kind of code should do: it should get the coder fired. I would be quite a bit afraid to work next to someone who writes like this.</p>\n"
},
{
"answer_id": 152684,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 1,
"selected": false,
"text": "<p>On a more broad answer. The comma operator (non overloaded) resolves as in, execute the first part and return the second part.</p>\n\n<p>So if you have (foo(),bar()) Both functions will be executed, but the value of the expression evaluates to bar() (and the type of the expression as well).</p>\n\n<p>While I won't say there are fair usages for that, is usually considered a bit hard to read code. Mainly because not many languages shares such constructs. So As a personal rule of thumb I avoid it unless I am adding code to a preexistent expression and don't want to change completely its format.</p>\n\n<p>Example: I have a Macro (not discussing if you should use macros or not, sometimes its not even you that wrote it) </p>\n\n<p>FIND_SOMETHING(X) (x>2) ? find_fruits(x) : find_houses(x)</p>\n\n<p>And I usually use it in assignments like my_possession = FIND_SOMETHING(34);</p>\n\n<p>Now I want to add log to it for debuggin purposes but I cannot change the find functions,. I could do :</p>\n\n<p>FIND_SOMETHING(X) (x>2)? (LOG(\"looking for fruits\"),find_fruits(x)):(LOG(\"looking for houses\"),find_houses(x))</p>\n"
},
{
"answer_id": 157652,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I use sometimes constructs like this for debugging purposes. When I force the if close to be true regardless of the return value of blah. \nIt's obvious that it should never appear in production code.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630/"
]
| What does the following code do in C/C++?
```
if (blah(), 5) {
//do something
}
``` | Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
---
Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious. |
149,506 | <p>I'm investigating an annotation-based approach to validating Spring beans using <a href="https://springmodules.dev.java.net/" rel="nofollow noreferrer">spring modules</a>. In <a href="http://wheelersoftware.com/articles/spring-bean-validation-framework.html" rel="nofollow noreferrer">this tutorial</a>, the following bean (getters and setters omitted) is used as an example:</p>
<pre><code>public final class User {
@NotBlank
@Length(max = 80)
private String name;
@NotBlank
@Email
@Length(max = 80)
private String email;
@NotBlank
@Length(max = 4000)
private String text;
}
</code></pre>
<p>The error message that is used if a particular validation rule is disobeyed should follow this format:</p>
<pre><code>bean-class.bean-propery[validation-rule]=Validation Error message
</code></pre>
<p>Examples for the class shown above include:</p>
<pre><code>User.email[not.blank]=Please enter your e-mail address.
User.email[email]=Please enter a valid e-mail address.
User.email[length]=Please enter no more than {2} characters.
</code></pre>
<p>The fact that the message keys contain the class name presents a couple of problems:</p>
<ol>
<li>If the class is renamed, the message keys also need to be changed</li>
<li><p>If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.</p>
<p>Person.email[not.blank]=Please enter your e-mail address.<br>
Person.email[email]=Please enter a valid e-mail address.<br>
Person.email[length]=Please enter no more than {2} characters.</p></li>
</ol>
<p>In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:</p>
<pre><code>email=email address is invalid
</code></pre>
<p>This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work. </p>
<p>An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule</p>
<pre><code>badEmail=Email address is invalid
</code></pre>
<p>This message should be used if I annotate the relevant property like this:</p>
<pre><code>@Email(errorCode="badEmail")
private String email;
</code></pre>
<p>However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?</p>
| [
{
"answer_id": 176039,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": true,
"text": "<p>I took a quick look at the <a href=\"https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/BeanValidator.html\" rel=\"nofollow noreferrer\">BeanValidator API</a>, and it looks like you might want to try the <em>errorCodeConverter</em> property.</p>\n\n<p>You would need to implement your own <a href=\"https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/converter/ErrorCodeConverter.html\" rel=\"nofollow noreferrer\">ErrorCodeConverter</a>, or use one of the provided implementations?</p>\n\n<pre><code>....\n<bean id=\"validator\" class=\"org.springmodules.validation.bean.BeanValidator\"\n p:configurationLoader-ref=\"configurationLoader\"\n p:errorCodeConverter-ref=\"errorCodeConverter\" />\n\n<bean id=\"errorCodeConverter\" class=\"contact.MyErrorCodeConverter\" />\n....\n</code></pre>\n\n<p><em>Note: configurationLoader is another bean defined in the config XML used in the tutorial</em></p>\n\n<p>Example converter:</p>\n\n<pre><code>package contact;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.springmodules.validation.bean.converter.ErrorCodeConverter;\n\npublic class MyErrorCodeConverter implements ErrorCodeConverter {\n\n private Log log = LogFactory.getLog(MyErrorCodeConverter.class);\n\n @Override\n public String convertPropertyErrorCode(String errorCode, Class clazz, String property) {\n log.error(String.format(\"Property %s %s %s\", errorCode, clazz.getClass().getName(), property));\n return errorCode; // <------ use the errorCode only\n }\n\n @Override\n public String convertGlobalErrorCode(String errorCode, Class clazz) {\n log.error(String.format(\"Global %s %s\", errorCode, clazz.getClass().getName()));\n return errorCode;\n }\n}\n</code></pre>\n\n<p>Now the properties should work:</p>\n\n<pre><code>MyEmailErrorCode=Bad email\n\nclass Foo {\n @Email(errorCode=\"MyEmailErrorCode\")\n String email\n}\n</code></pre>\n"
},
{
"answer_id": 11158437,
"author": "Rian",
"author_id": 1128112,
"author_profile": "https://Stackoverflow.com/users/1128112",
"pm_score": 2,
"selected": false,
"text": "<p>Spring validation does have an ErrorCodeConverter that does this:</p>\n\n<p>org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter</p>\n\n<p>When this is used, the resource bundle will be checked for the following codes:</p>\n\n<p>[errorCode.commandBeanName.fieldName, errorCode.fieldName, errorCode.fieldClassName, errorCode]</p>\n\n<ul>\n<li>errorCode is the actual validation errorCode eg. not.blank, email.</li>\n<li>commandBeanName is the same as the model key name that references the\nform backing bean. </li>\n<li>fieldName is the name of the field. </li>\n<li>fieldClassName is the field class name eg. java.lang.String, java.lang.Integer</li>\n</ul>\n\n<p>So for instance if I have a bean that is referenced in the model by the key \"formBean\" and the field emailAddress of type java.lang.String does not contain an email address, which causes the errorCode email. The validation framework will attempt to resolve the following message codes:</p>\n\n<p>[email.formBean.emailAddress, email.emailAddress, email.java.lang.String, email]</p>\n\n<p>If the errorCode is replaced by the errorCode \"badEmail\" like this:</p>\n\n<p>@Email(errorCode=\"badEmail\")</p>\n\n<p>The messages codes that the framework will try resolve will be:</p>\n\n<p>[badEmail.formBean.emailAddress, badEmail.emailAddress, badEmail.java.lang.String, badEmail]</p>\n\n<p>I would suggest keeping the errodCode the same. Thus one message can be used for all fields that have that errorCode associated with them. If you need to be more specific with the message for a certain field you can add a message to the resource bundles with the code errorCode.commandBeanName.field.</p>\n"
},
{
"answer_id": 39374697,
"author": "VHS",
"author_id": 5749570,
"author_profile": "https://Stackoverflow.com/users/5749570",
"pm_score": 0,
"selected": false,
"text": "<p>Add the following beans in your <code>applicationContext.xml</code> file.</p>\n\n<pre><code><bean id=\"configurationLoader\"\n class=\"org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader\" />\n\n<!-- Use the error codes as is. Don't convert them to <Bean class name>.<bean field being validated>[errorCode]. --> \n<bean id=\"errorCodeConverter\"\n class=\"org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter\"/>\n\n <!-- shortCircuitFieldValidation = true ==> If the first rule fails on a field, no need to check \n other rules for that field --> \n<bean id=\"validator\" class=\"org.springmodules.validation.bean.BeanValidator\"\n p:configurationLoader-ref=\"configurationLoader\"\n p:shortCircuitFieldValidation=\"true\" \n p:errorCodeConverter-ref=\"errorCodeConverter\"/>\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| I'm investigating an annotation-based approach to validating Spring beans using [spring modules](https://springmodules.dev.java.net/). In [this tutorial](http://wheelersoftware.com/articles/spring-bean-validation-framework.html), the following bean (getters and setters omitted) is used as an example:
```
public final class User {
@NotBlank
@Length(max = 80)
private String name;
@NotBlank
@Email
@Length(max = 80)
private String email;
@NotBlank
@Length(max = 4000)
private String text;
}
```
The error message that is used if a particular validation rule is disobeyed should follow this format:
```
bean-class.bean-propery[validation-rule]=Validation Error message
```
Examples for the class shown above include:
```
User.email[not.blank]=Please enter your e-mail address.
User.email[email]=Please enter a valid e-mail address.
User.email[length]=Please enter no more than {2} characters.
```
The fact that the message keys contain the class name presents a couple of problems:
1. If the class is renamed, the message keys also need to be changed
2. If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.
Person.email[not.blank]=Please enter your e-mail address.
Person.email[email]=Please enter a valid e-mail address.
Person.email[length]=Please enter no more than {2} characters.
In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:
```
email=email address is invalid
```
This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work.
An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule
```
badEmail=Email address is invalid
```
This message should be used if I annotate the relevant property like this:
```
@Email(errorCode="badEmail")
private String email;
```
However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework? | I took a quick look at the [BeanValidator API](https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/BeanValidator.html), and it looks like you might want to try the *errorCodeConverter* property.
You would need to implement your own [ErrorCodeConverter](https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/converter/ErrorCodeConverter.html), or use one of the provided implementations?
```
....
<bean id="validator" class="org.springmodules.validation.bean.BeanValidator"
p:configurationLoader-ref="configurationLoader"
p:errorCodeConverter-ref="errorCodeConverter" />
<bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" />
....
```
*Note: configurationLoader is another bean defined in the config XML used in the tutorial*
Example converter:
```
package contact;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springmodules.validation.bean.converter.ErrorCodeConverter;
public class MyErrorCodeConverter implements ErrorCodeConverter {
private Log log = LogFactory.getLog(MyErrorCodeConverter.class);
@Override
public String convertPropertyErrorCode(String errorCode, Class clazz, String property) {
log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property));
return errorCode; // <------ use the errorCode only
}
@Override
public String convertGlobalErrorCode(String errorCode, Class clazz) {
log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName()));
return errorCode;
}
}
```
Now the properties should work:
```
MyEmailErrorCode=Bad email
class Foo {
@Email(errorCode="MyEmailErrorCode")
String email
}
``` |
149,573 | <p>Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.</p>
<p>(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)</p>
| [
{
"answer_id": 149592,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>Look at the <a href=\"http://www.w3schools.com/htmldom/prop_select_selectedindex.asp\" rel=\"nofollow noreferrer\">selectedIndex</a> of the <code>select</code> element. BTW, that's a plain ol' DOM thing, not JQuery-specific.</p>\n"
},
{
"answer_id": 149620,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>No need to use jQuery for this:</p>\n\n<pre><code>var foo = document.getElementById('yourSelect');\nif (foo)\n{\n if (foo.selectedIndex != null)\n {\n foo.selectedIndex = 0;\n } \n}\n</code></pre>\n"
},
{
"answer_id": 149820,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 9,
"selected": true,
"text": "<p>While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.</p>\n\n<pre><code><select id=\"mySelect\" multiple=\"multiple\">\n <option value=\"1\">First</option>\n <option value=\"2\">Second</option>\n <option value=\"3\">Third</option>\n <option value=\"4\">Fourth</option>\n</select>\n\n<script type=\"text/javascript\"> \n$(document).ready(function() {\n if (!$(\"#mySelect option:selected\").length) {\n $(\"#mySelect option[value='3']\").attr('selected', 'selected');\n }\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 149861,
"author": "Alexander Pendleton",
"author_id": 21201,
"author_profile": "https://Stackoverflow.com/users/21201",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/149573/check-if-option-is-selected-with-jquery-if-not-select-a-default/149820#149820\">lencioni's answer</a> is what I'd recommend. You can change the selector for the option <code>('#mySelect option:last')</code> to select the option with a specific value using \"<code>#mySelect option[value='yourDefaultValue']</code>\". <a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\" title=\"More selectors\">More on selectors</a>.</p>\n\n<p>If you're working extensively with select lists on the client check out this plugin:\n<a href=\"http://www.texotela.co.uk/code/jquery/select/\" rel=\"nofollow noreferrer\">http://www.texotela.co.uk/code/jquery/select/</a>. Take a look the source if you want to see some more examples of working with select lists.</p>\n"
},
{
"answer_id": 149934,
"author": "meleyal",
"author_id": 4196,
"author_profile": "https://Stackoverflow.com/users/4196",
"pm_score": 2,
"selected": false,
"text": "<p>I already came across the <a href=\"http://www.texotela.co.uk/code/jquery/select/\" rel=\"nofollow noreferrer\">texotela plugin</a> mentioned, which let me solve it like this:</p>\n\n<pre><code>$(document).ready(function(){\n if ( $(\"#context\").selectedValues() == false) {\n $(\"#context\").selectOptions(\"71\");\n }\n});\n</code></pre>\n"
},
{
"answer_id": 1649507,
"author": "sata",
"author_id": 199630,
"author_profile": "https://Stackoverflow.com/users/199630",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my function changing the selected option. It works for jQuery 1.3.2</p>\n\n<pre><code>function selectOption(select_id, option_val) {\n $('#'+select_id+' option:selected').removeAttr('selected');\n $('#'+select_id+' option[value='+option_val+']').attr('selected','selected'); \n}\n</code></pre>\n"
},
{
"answer_id": 1652471,
"author": "Joel",
"author_id": 199941,
"author_profile": "https://Stackoverflow.com/users/199941",
"pm_score": 2,
"selected": false,
"text": "<p>This was a quick script I found that worked...\n.Result is assigned to a label.</p>\n\n<pre><code>$(\".Result\").html($(\"option:selected\").text());\n</code></pre>\n"
},
{
"answer_id": 1847923,
"author": "giagejoe",
"author_id": 214993,
"author_profile": "https://Stackoverflow.com/users/214993",
"pm_score": 1,
"selected": false,
"text": "<p>You guys are doing way too much for selecting. Just select by value:</p>\n\n<pre><code>$(\"#mySelect\").val( 3 );\n</code></pre>\n"
},
{
"answer_id": 1848078,
"author": "Martin Labuschin",
"author_id": 221368,
"author_profile": "https://Stackoverflow.com/users/221368",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Easy!</strong> The default should be the first option. <strong>Done!</strong> That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Unobtrusive_JavaScript\" rel=\"nofollow noreferrer\">Unobtrusive JavaScript</a></p>\n"
},
{
"answer_id": 1873462,
"author": "Ram Prasad",
"author_id": 186923,
"author_profile": "https://Stackoverflow.com/users/186923",
"pm_score": 3,
"selected": false,
"text": "<pre><code><script type=\"text/javascript\"> \n$(document).ready(function() {\n if (!$(\"#mySelect option:selected\").length)\n $(\"#mySelect\").val( 3 );\n\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 3487319,
"author": "user420944",
"author_id": 420944,
"author_profile": "https://Stackoverflow.com/users/420944",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$(\"option[value*='2']\").attr('selected', 'selected');\n// 2 for example, add * for every option\n</code></pre>\n"
},
{
"answer_id": 9972446,
"author": "Taimoor Changaiz",
"author_id": 1222852,
"author_profile": "https://Stackoverflow.com/users/1222852",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$(\"#select_box_id\").children()[1].selected\n</code></pre>\n\n<p>This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).</p>\n\n<p>[1] is index of select box option </p>\n"
},
{
"answer_id": 18354158,
"author": "Avinash Saini",
"author_id": 2226601,
"author_profile": "https://Stackoverflow.com/users/2226601",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (!$(\"#select\").find(\"option:selected\").length){\n //\n}\n</code></pre>\n"
},
{
"answer_id": 18793799,
"author": "Gavin",
"author_id": 2211053,
"author_profile": "https://Stackoverflow.com/users/2211053",
"pm_score": 4,
"selected": false,
"text": "<p>This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.</p>\n\n<p>To check if a select element has any selected items:</p>\n\n<pre><code>if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }\n</code></pre>\n\n<p>or to check if a select has nothing selected:</p>\n\n<pre><code>if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }\n</code></pre>\n\n<p>or if you're in a loop of some sort and want to check if the current element is selected:</p>\n\n<pre><code>$('#mySelect option').each(function() {\n if ($(this).is(':selected')) { .. }\n});\n</code></pre>\n\n<p>to check if an element is not selected while in a loop:</p>\n\n<pre><code>$('#mySelect option').each(function() {\n if ($(this).not(':selected')) { .. }\n});\n</code></pre>\n\n<p>These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.</p>\n"
},
{
"answer_id": 21787851,
"author": "Akash Deep Singhal",
"author_id": 2791794,
"author_profile": "https://Stackoverflow.com/users/2791794",
"pm_score": 0,
"selected": false,
"text": "<p>Change event on the select box to fire and once it does then just pull the id attribute of the selected option :-</p>\n\n<pre><code>$(\"#type\").change(function(){\n var id = $(this).find(\"option:selected\").attr(\"id\");\n\n switch (id){\n case \"trade_buy_max\":\n // do something here\n break;\n }\n});\n</code></pre>\n"
},
{
"answer_id": 23229044,
"author": "Steven Schoch",
"author_id": 2548668,
"author_profile": "https://Stackoverflow.com/users/2548668",
"pm_score": 0,
"selected": false,
"text": "<p>I was just looking for something similar and found this:</p>\n\n<pre><code>$('.mySelect:not(:has(option[selected])) option[value=\"2\"]').attr('selected', true);\n</code></pre>\n\n<p>This finds all select menus in the class that don't already have an option selected, and selects the default option (\"2\" in this case).</p>\n\n<p>I tried using <code>:selected</code> instead of <code>[selected]</code>, but that didn't work because something is always selected, even if nothing has the attribute</p>\n"
},
{
"answer_id": 29184991,
"author": "Marcin Bąk",
"author_id": 4697638,
"author_profile": "https://Stackoverflow.com/users/4697638",
"pm_score": 1,
"selected": false,
"text": "<p>I found a good way to check, if option is selected and select a default when it isn't.</p>\n\n<pre><code> if(!$('#some_select option[selected=\"selected\"]').val()) {\n //here code if it HAS NOT selected value\n //for exaple adding the first value as \"placeholder\"\n $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');\n }\n</code></pre>\n\n<p>If <strong>#some_select</strong> has't default selected option then <strong>.val()</strong> is <em>undefined</em></p>\n"
},
{
"answer_id": 34836842,
"author": "zeman",
"author_id": 1994491,
"author_profile": "https://Stackoverflow.com/users/1994491",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to explicitly check each option to see if any have the \"selected\" attribute you can do this. Otherwise using <code>option:selected</code> you'll get the value for the first default option.</p>\n\n<pre><code>var viewport_selected = false; \n$('#viewport option').each(function() {\n if ($(this).attr(\"selected\") == \"selected\") {\n viewport_selected = true;\n }\n});\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
]
| Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.
(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :) | While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.
```
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length) {
$("#mySelect option[value='3']").attr('selected', 'selected');
}
});
</script>
``` |
149,600 | <p>Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.</p>
| [
{
"answer_id": 149612,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 3,
"selected": false,
"text": "<p>If you use Zend Development Environment, you can use the Indent Code feature (Ctrl+Shift+F).</p>\n"
},
{
"answer_id": 149648,
"author": "Adam",
"author_id": 13320,
"author_profile": "https://Stackoverflow.com/users/13320",
"pm_score": 2,
"selected": false,
"text": "<p>The Zend Development Environment is now an Eclipse plugin, you may be able to run it alongside Aptana and just use it's Indent Code feature. </p>\n\n<p><a href=\"http://www.zend.com/en/products/studio/downloads\" rel=\"nofollow noreferrer\">Zend Studio</a></p>\n\n<p>I haven't upgraded to the Eclipse plugin yet myself, I love the previous ZDE so much. Though now that I've started actually using Eclipse for other languages, I'm almost ready to make the leap.</p>\n"
},
{
"answer_id": 149863,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a php code beautifier (PHP of course) class:<br>\n<a href=\"http://www.codeassembly.com/A-php-code-beautifier-that-works/\" rel=\"nofollow noreferrer\">http://www.codeassembly.com/A-php-code-beautifier-that-works/</a></p>\n\n<p>and</p>\n\n<p>online demo:</p>\n\n<p><a href=\"http://www.codeassembly.com/examples/beautifier.php\" rel=\"nofollow noreferrer\">http://www.codeassembly.com/examples/beautifier.php</a></p>\n"
},
{
"answer_id": 150028,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.waterproof.fr/products/phpCodeBeautifier/\" rel=\"noreferrer\">PHP Code Beautifier</a> is a useful free tool that should do what you're after, although their <a href=\"http://www.waterproof.fr/products/phpCodeBeautifier/download.php\" rel=\"noreferrer\">download page</a> does require an account to be created.</p>\n\n<blockquote>\n <p>The tool has been declined into 3 versions:</p>\n \n <ul>\n <li>A GUI version which allow to process file visually.</li>\n <li>A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...).</li>\n <li>As an integrated tool of PHPEdit.</li>\n </ul>\n</blockquote>\n\n<p>Basically, it'll turn:</p>\n\n<pre><code>if($code == BAD){$action = REWRITE;}else{$action = KEEP;}\nfor($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}}\n</code></pre>\n\n<p>into</p>\n\n<pre><code>if ($code == BAD) {\n $action = REWRITE;\n} else {\n $action = KEEP;\n}\nfor($i = 0; $i < 10;$i++) {\n while ($j > 0) {\n $j++;\n doCall($i + $j);\n if ($k) {\n $k /= 10;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 494295,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 5,
"selected": false,
"text": "<p>Well here is my very basic and rough script:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\nclass Token {\n public $type;\n public $contents;\n\n public function __construct($rawToken) {\n if (is_array($rawToken)) {\n $this->type = $rawToken[0];\n $this->contents = $rawToken[1];\n } else {\n $this->type = -1;\n $this->contents = $rawToken;\n }\n }\n}\n\n$file = $argv[1];\n$code = file_get_contents($file);\n\n$rawTokens = token_get_all($code);\n$tokens = array();\nforeach ($rawTokens as $rawToken) {\n $tokens[] = new Token($rawToken);\n}\n\nfunction skipWhitespace(&$tokens, &$i) {\n global $lineNo;\n $i++;\n $token = $tokens[$i];\n while ($token->type == T_WHITESPACE) {\n $lineNo += substr($token->contents, \"\\n\");\n $i++;\n $token = $tokens[$i];\n }\n}\n\nfunction nextToken(&$j) {\n global $tokens, $i;\n $j = $i;\n do {\n $j++;\n $token = $tokens[$j];\n } while ($token->type == T_WHITESPACE);\n return $token;\n}\n\n$OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&&', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '<=', '>=', '<', '>', '===', '!==');\n\n$IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE);\n\n$CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE);\n$WHITESPACE_BEFORE = array('?', '{', '=>');\n$WHITESPACE_AFTER = array(',', '?', '=>');\n\nforeach ($OPERATORS as $op) {\n $WHITESPACE_BEFORE[] = $op;\n $WHITESPACE_AFTER[] = $op;\n}\n\n$matchingTernary = false;\n\n// First pass - filter out unwanted tokens\n$filteredTokens = array();\nfor ($i = 0, $n = count($tokens); $i < $n; $i++) {\n $token = $tokens[$i];\n if ($token->contents == '?') {\n $matchingTernary = true;\n }\n if (in_array($token->type, $IMPORT_STATEMENTS) && nextToken($j)->contents == '(') {\n $filteredTokens[] = $token;\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n $filteredTokens[] = new Token(array(T_WHITESPACE, ' '));\n }\n $i = $j;\n do {\n $i++;\n $token = $tokens[$i];\n if ($token->contents != ')') {\n $filteredTokens[] = $token;\n }\n } while ($token->contents != ')');\n } elseif ($token->type == T_ELSE && nextToken($j)->type == T_IF) {\n $i = $j;\n $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif'));\n } elseif ($token->contents == ':') {\n if ($matchingTernary) {\n $matchingTernary = false;\n } elseif ($tokens[$i - 1]->type == T_WHITESPACE) {\n array_pop($filteredTokens); // Remove whitespace before\n }\n $filteredTokens[] = $token;\n } else {\n $filteredTokens[] = $token;\n }\n}\n$tokens = $filteredTokens;\n\nfunction isAssocArrayVariable($offset = 0) {\n global $tokens, $i;\n $j = $i + $offset;\n return $tokens[$j]->type == T_VARIABLE &&\n $tokens[$j + 1]->contents == '[' &&\n $tokens[$j + 2]->type == T_STRING &&\n preg_match('/[a-z_]+/', $tokens[$j + 2]->contents) &&\n $tokens[$j + 3]->contents == ']';\n}\n\n// Second pass - add whitespace\n$matchingTernary = false;\n$doubleQuote = false;\nfor ($i = 0, $n = count($tokens); $i < $n; $i++) {\n $token = $tokens[$i];\n if ($token->contents == '?') {\n $matchingTernary = true;\n }\n if ($token->contents == '\"' && isAssocArrayVariable(1) && $tokens[$i + 5]->contents == '\"') {\n /*\n * Handle case where the only thing quoted is the assoc array variable.\n * Eg. \"$value[key]\"\n */\n $quote = $tokens[$i++]->contents;\n $var = $tokens[$i++]->contents;\n $openSquareBracket = $tokens[$i++]->contents;\n $str = $tokens[$i++]->contents;\n $closeSquareBracket = $tokens[$i++]->contents;\n $quote = $tokens[$i]->contents; \n echo $var . \"['\" . $str . \"']\";\n $doubleQuote = false;\n continue;\n }\n if ($token->contents == '\"') {\n $doubleQuote = !$doubleQuote;\n }\n if ($doubleQuote && $token->contents == '\"' && isAssocArrayVariable(1)) {\n // don't echo \"\n } elseif ($doubleQuote && isAssocArrayVariable()) {\n if ($tokens[$i - 1]->contents != '\"') {\n echo '\" . ';\n }\n $var = $token->contents;\n $openSquareBracket = $tokens[++$i]->contents;\n $str = $tokens[++$i]->contents;\n $closeSquareBracket = $tokens[++$i]->contents;\n echo $var . \"['\" . $str . \"']\";\n if ($tokens[$i + 1]->contents != '\"') {\n echo ' . \"';\n } else {\n $i++; // process \"\n $doubleQuote = false;\n }\n } elseif ($token->type == T_STRING && $tokens[$i - 1]->contents == '[' && $tokens[$i + 1]->contents == ']') {\n if (preg_match('/[a-z_]+/', $token->contents)) {\n echo \"'\" . $token->contents . \"'\";\n } else {\n echo $token->contents;\n }\n } elseif ($token->type == T_ENCAPSED_AND_WHITESPACE || $token->type == T_STRING) {\n echo $token->contents;\n } elseif ($token->contents == '-' && in_array($tokens[$i + 1]->type, array(T_LNUMBER, T_DNUMBER))) {\n echo '-';\n } elseif (in_array($token->type, $CONTROL_STRUCTURES)) {\n echo $token->contents;\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n } elseif ($token->contents == '}' && in_array($tokens[$i + 1]->type, $CONTROL_STRUCTURES)) {\n echo '} ';\n } elseif ($token->contents == '=' && $tokens[$i + 1]->contents == '&') {\n if ($tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n $i++; // match &\n echo '=&';\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' '; \n }\n } elseif ($token->contents == ':' && $matchingTernary) {\n $matchingTernary = false;\n if ($tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n echo ':';\n if ($tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ';\n }\n } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE &&\n in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {\n echo ' ' . $token->contents . ' ';\n } elseif (in_array($token->contents, $WHITESPACE_BEFORE) && $tokens[$i - 1]->type != T_WHITESPACE) {\n echo ' ' . $token->contents;\n } elseif (in_array($token->contents, $WHITESPACE_AFTER) && $tokens[$i + 1]->type != T_WHITESPACE) {\n echo $token->contents . ' ';\n } else {\n echo $token->contents;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 805338,
"author": "SeanJA",
"author_id": 75924,
"author_profile": "https://Stackoverflow.com/users/75924",
"pm_score": 2,
"selected": false,
"text": "<p>What about this one:</p>\n\n<p><a href=\"http://universalindent.sourceforge.net/\" rel=\"nofollow noreferrer\">http://universalindent.sourceforge.net/</a></p>\n\n<p>It combines a bunch of formatters out there, and will generate the scripts you need so you can pass them out and get your team members to use them before committing next time... Though... formatters might mess up your code and render it unusable... </p>\n"
},
{
"answer_id": 2854605,
"author": "Ira Baxter",
"author_id": 120163,
"author_profile": "https://Stackoverflow.com/users/120163",
"pm_score": 1,
"selected": false,
"text": "<p>Our <a href=\"http://www.semanticdesigns.com/Products/Formatters/PHPFormatter.html\" rel=\"nofollow noreferrer\"> PHP Formatter</a> will reliably format your code. It uses a compiler-based front end to parse the code, so it doesn't misinterpret the code and damage it. Consequently its formatted output <em>always</em> works.</p>\n"
},
{
"answer_id": 3427820,
"author": "projecktzero",
"author_id": 13380,
"author_profile": "https://Stackoverflow.com/users/13380",
"pm_score": 3,
"selected": false,
"text": "<p>There's a pear module that formats your code. <a href=\"http://pear.php.net/package/PHP_Beautifier\" rel=\"noreferrer\">PHP Beautifier</a></p>\n"
},
{
"answer_id": 3517764,
"author": "Chris",
"author_id": 227260,
"author_profile": "https://Stackoverflow.com/users/227260",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://en.sourceforge.jp/projects/pdt-tools/\" rel=\"noreferrer\">http://en.sourceforge.jp/projects/pdt-tools/</a></p>\n\n<p>^^^ will give you a proper CTRL+SHIFT+F Eclipse/Aptana PHP formatter like Java.</p>\n\n<p>See <a href=\"http://www.free-source.net/blog/Aptana%20and%20Eclispe%20-%20Code%20Formatter%20for%20PHP%20Development%20Tools%20for%20Eclipse\" rel=\"noreferrer\">here</a> for installation help.</p>\n\n<p><img src=\"https://i.stack.imgur.com/xDegS.png\" alt=\"eclipse php code formatter\"></p>\n"
},
{
"answer_id": 10198736,
"author": "Aaron",
"author_id": 1339743,
"author_profile": "https://Stackoverflow.com/users/1339743",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest solution is to just use an IDE that has this built in. If you're going to be writing code in PHP on a regular a regular basis, just drop the $60 for PHPStorm. You won't regret it.</p>\n\n<p><a href=\"http://www.jetbrains.com/phpstorm/\" rel=\"nofollow\">http://www.jetbrains.com/phpstorm/</a></p>\n\n<p>It lets you format your code however you like using a simple keyboard shortcut at the file or directory level, and has a zillion other great features.</p>\n"
},
{
"answer_id": 10560525,
"author": "vaichidrewar",
"author_id": 553223,
"author_profile": "https://Stackoverflow.com/users/553223",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://phpformatter.com/\" rel=\"nofollow\">phpformatter.com</a> works best</p>\n\n<p>\"This free online PHP Formatter is designed so that you can beautify all your PHP script with the style that you prefer\"</p>\n"
},
{
"answer_id": 11597951,
"author": "user1501974",
"author_id": 1501974,
"author_profile": "https://Stackoverflow.com/users/1501974",
"pm_score": 1,
"selected": false,
"text": "<p>This is an excellent question. I have an application that reads json and outputs php and html and css. I run a program and generate dozens (hundreds?) of files. I hope the answer here is useful.</p>\n\n<p>I started my project using heredocs, special include files, meta chars, etc but that quickly became a mess. I wanted a stand-alone solution that didn't require framework or ide. So I removed all the heredoc and other junk and created a generic text buffering class with no concern for formatting. It can all be one line for all I care. For html, I do tidy() built-in. For php, I use <a href=\"http://sourceforge.net/projects/phpstylist/\" rel=\"nofollow\">phpstylist</a>. phpstylist is older but still works well for php format.</p>\n\n<p>To set up the phpstylist options I used <a href=\"http://universalindent.sourceforge.net/\" rel=\"nofollow\">UniversalIndent</a> (updated Jan 2012) in windows gui. </p>\n\n<p>UniversalStylist lists 24 (!) formatter programs (c, php, ruby, html,...). It specifically knows the options for phpstylist and gives you a live refresh on a file as you turn options on and off. Very great. Then, when you have your style, it has an option to save the command line options and generates a script. For some formatting options you'll have to add paths to perl, python, etc.</p>\n\n<p>If you are using windows and want to try phpstylist with UniversalIndent, just add directory for php.exe to your env path. I use <a href=\"http://www.ampps.com/\" rel=\"nofollow\">ampps</a> so mine is set to c:\\ampps\\php.</p>\n\n<p>It was not very easy to find a good solid solution. I'm also interested in hearing what other people do for simple as possible batch formatting of auto-generated php/html files for code review and archiving purposes.</p>\n"
},
{
"answer_id": 15954536,
"author": "Stefan Brinkmann",
"author_id": 1378586,
"author_profile": "https://Stackoverflow.com/users/1378586",
"pm_score": 3,
"selected": false,
"text": "<p>Use NetBeans PHP and press alt+shift+F.</p>\n"
},
{
"answer_id": 30383232,
"author": "Aran",
"author_id": 4806775,
"author_profile": "https://Stackoverflow.com/users/4806775",
"pm_score": -1,
"selected": false,
"text": "<p>I've been having a lot of trouble finding a decent free formatter for PHP as well, there are many online and command-line tools but they just don't seem to work for some reason, the results are all still full of bad indenting with combinations of tabs and spaces, and they never get the braces the way you want them!</p>\n\n<p>I tried the snippet above and that didn't work for me either, indenting still full of spaces and tabs all mixed up.</p>\n\n<p>So I've had a go at writing a simple one too, this one just uses all regex, no fancy compiler magic, so it's possible that it could break things, and is still very beta and being tested on various messy code. The interface is very basic at the moment too, but should improve over the next few days.</p>\n\n<p>It's hardwired for MediaWiki's conventions, but you can modify it pretty easily (I may add options later).</p>\n\n<p><a href=\"https://www.organicdesign.co.nz/Special:CodeTidy\" rel=\"nofollow\">https://www.organicdesign.co.nz/Special:CodeTidy</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
]
| Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too. | [PHP Code Beautifier](http://www.waterproof.fr/products/phpCodeBeautifier/) is a useful free tool that should do what you're after, although their [download page](http://www.waterproof.fr/products/phpCodeBeautifier/download.php) does require an account to be created.
>
> The tool has been declined into 3 versions:
>
>
> * A GUI version which allow to process file visually.
> * A command line version which allow to be batched or integrated with other tools (CVS, SubVersion, IDE ...).
> * As an integrated tool of PHPEdit.
>
>
>
Basically, it'll turn:
```
if($code == BAD){$action = REWRITE;}else{$action = KEEP;}
for($i=0; $i<10;$i++){while($j>0){$j++;doCall($i+$j);if($k){$k/=10;}}}
```
into
```
if ($code == BAD) {
$action = REWRITE;
} else {
$action = KEEP;
}
for($i = 0; $i < 10;$i++) {
while ($j > 0) {
$j++;
doCall($i + $j);
if ($k) {
$k /= 10;
}
}
}
``` |
149,609 | <p>Does the using catch the exception or throw it? i.e. </p>
<pre><code>using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
</code></pre>
<p>If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?</p>
| [
{
"answer_id": 149623,
"author": "hometoast",
"author_id": 2009,
"author_profile": "https://Stackoverflow.com/users/2009",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't specifically catch an exception it's thrown up the stack until something does</p>\n"
},
{
"answer_id": 149625,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx\" rel=\"noreferrer\"><code>using</code></a> allows the exception to boil through. It acts like a try/finally, where the finally disposes the used object. Thus, it is only appropriate/useful for objects that implement <code>IDisposable</code>.</p>\n"
},
{
"answer_id": 149629,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "<p>using statements do not eat exceptions.</p>\n\n<p>All \"Using\" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block.</p>\n\n<p>There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called.</p>\n"
},
{
"answer_id": 149630,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 2,
"selected": false,
"text": "<p>The using does not interfere with exception handling apart from cleaning up stuff in its scope.</p>\n\n<p>It doesn't handle exceptions but lets exceptions pass through.</p>\n"
},
{
"answer_id": 149637,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 0,
"selected": false,
"text": "<p>\"using\" does not catch exceptions, it just disposes of resources in the event of unhandled exceptions.</p>\n\n<p>Perhaps the question is, would it dispose of resources allocated in the parentheses if an error also occured in the declaration? It's hard to imagine both happening, though.</p>\n"
},
{
"answer_id": 149643,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 6,
"selected": false,
"text": "<p>When you see a using statement, think of this code:</p>\n\n<pre><code>StreadReader rdr = null;\ntry\n{\n rdr = File.OpenText(\"file.txt\");\n //do stuff\n}\nfinally\n{\n if (rdr != null)\n rdr.Dispose();\n}\n</code></pre>\n\n<p>So the real answer is that it doesn't do anything with the exception thrown in the body of the using block. It doesn't handle it or rethrow it.</p>\n"
},
{
"answer_id": 149649,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": false,
"text": "<p>It throws the exception, so either your containing method needs to handle it, or pass it up the stack.</p>\n\n<pre><code>try\n{\n using (\n StreamReader rdr = File.OpenText(\"file.txt\"))\n { //do stuff \n }\n}\ncatch (FileNotFoundException Ex)\n{\n // The file didn't exist\n}\ncatch (AccessViolationException Ex)\n{\n // You don't have the permission to open this\n}\ncatch (Exception Ex)\n{\n // Something happened! \n}\n</code></pre>\n"
},
{
"answer_id": 149657,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p><code>using</code> guarantees* the object created will be disposed at the end of the block, even if an exception is thrown. The exception is <em>not</em> caught. However, you need to be careful about what you do if you try to catch it yourself. Since any code that catches the exception is outside the scope block defined by the <code>using</code> statement, your object won't be available to that code.</p>\n\n<p>*barring the usual suspects like power failure, nuclear holocaust, etc</p>\n"
},
{
"answer_id": 149671,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>You can imagine <strong>using</strong> as a <strong>try...finally</strong> block without the catch block. In the finally block, IDisposable.Dispose is called, and since there is no catch block, any exceptions are thrown up the stack.</p>\n"
},
{
"answer_id": 149676,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "<p>Any exceptions that are thrown in the initialization expression of the using statement will propagate up the method scope and call stack as expected.</p>\n\n<p>One thing to watch out for, though, is that if an exception occures in the initialization expression, then the Dispose() method will not be called on the expression variable. This is almost always the behavior that you would want, since you don't want to bother disposing an object that was not actually created. However, there could be an issue in complex circumstances. That is, if multiple initializations are buried inside the constructor and some succeed prior to the exception being thrown, then the Dispose call may not occur at that point. This is usually not a problem, though, since constructors are usually kept simple.</p>\n"
},
{
"answer_id": 5878360,
"author": "Branko Dimitrijevic",
"author_id": 533120,
"author_profile": "https://Stackoverflow.com/users/533120",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, if <code>File.OpenText</code> throws, the <code>Dispose</code> will <strong>not</strong> be called.</p>\n\n<p>If the exception happens in <code>//do stuff</code>, the <code>Dispose</code> <strong>will</strong> be called.</p>\n\n<p>In both cases, the exception is normally propagated out of the scope, as it would be without the <em>using</em> statement.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
]
| Does the using catch the exception or throw it? i.e.
```
using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
```
If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it? | using statements do not eat exceptions.
All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block.
There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called. |
149,617 | <p>Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used.</p>
<p>For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum.</p>
<p>Then I tried <a href="http://svn.rot13.org/index.cgi/RFID/view/guess-crc.pl" rel="noreferrer">several variations of CRC16</a>, but without much luck.</p>
<p>This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to <a href="http://lcamtuf.coredump.cx/newtcp/" rel="noreferrer">drawing different CRC algorithms</a> if everything else fails.</p>
<p>Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor. </p>
<p>Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem.</p>
<p><a href="http://www.bljak.org/~dpavlin/rfid-serial-dump.tar.gz" rel="noreferrer">dump files with data</a> are available if question itself isn't enough :-)</p>
<p><strong>Need reference documentation?</strong> <a href="http://www.geocities.com/SiliconValley/Pines/8659/crc.htm" rel="noreferrer">A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS</a> is great reference which I found after asking question here.</p>
<p>In the end, after very helpful hint in accepted answer than it's CCITT, I
<a href="http://www.zorc.breitbandkatze.de/crc.html" rel="noreferrer">used this CRC calculator</a>, and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000.</p>
| [
{
"answer_id": 149663,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 0,
"selected": false,
"text": "<p>You would have to try every possible checksum algorithm and see which one generates the same result. However, there is no guarantee to what content was included in the checksum. For example, some algorithms skip white spaces, which lead to different results.</p>\n\n<p>I really don't see why would somebody want to know that though.</p>\n"
},
{
"answer_id": 149715,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>It might not be a CRC, it might be an error correcting code like Reed-Solomon.</p>\n\n<p>ECC codes are often a substantial fraction of the size of the original data they protect, depending on the error rate they want to handle. If the size of the messages is more than about 16 bytes, 2 bytes of ECC wouldn't be enough to be useful. So if the message is large, you're most likely correct that its some sort of CRC.</p>\n"
},
{
"answer_id": 158693,
"author": "selwyn",
"author_id": 16314,
"author_profile": "https://Stackoverflow.com/users/16314",
"pm_score": 5,
"selected": true,
"text": "<p>There are a number of variables to consider for a CRC:</p>\n\n<pre><code>Polynomial\nNo of bits (16 or 32)\nNormal (LSB first) or Reverse (MSB first)\nInitial value\nHow the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value\n</code></pre>\n\n<p>Typical CRCs:</p>\n\n<pre><code>LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculated\nCRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculated\nCCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0f\nXmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0f\nCRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted value\nZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated\n</code></pre>\n\n<p>The first thing to do is to get some samples by changing say the last byte. This will assist you to figure out the number of bytes in the CRC. </p>\n\n<p>Is this a \"homemade\" algorithm. In this case it may take some time. Otherwise try the standard algorithms.</p>\n\n<p>Try changing either the msb or the lsb of the last byte, and see how this changes the CRC. This will give an indication of the direction.</p>\n\n<p>To make it more difficult, there are implementations that manipulate the CRC so that it will not affect the communications medium (protocol).</p>\n\n<p>From your comment about RFID, it implies that the CRC is communications related. Usually CRC16 is used for communications, though CCITT is also used on some systems.</p>\n\n<p>On the other hand, if this is UHF RFID tagging, then there are a few CRC schemes - a 5 bit one and some 16 bit ones. These are documented in the ISO standards and the IPX data sheets.</p>\n\n<pre><code>IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculated\nISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated\nISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated\n Data must be padded with zeroes to make a multiple of 8 bits\nISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits\n Data must be padded with zeroes to make a multiple of 8 bits\nEPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits\n</code></pre>\n\n<p><strong>Here is your answer!!!!</strong></p>\n\n<p><strong>Having worked through your logs, the CRC is the CCITT one. The first byte 0xd6 is excluded from the CRC.</strong></p>\n"
},
{
"answer_id": 30734555,
"author": "Brian",
"author_id": 2146208,
"author_profile": "https://Stackoverflow.com/users/2146208",
"pm_score": 2,
"selected": false,
"text": "<p>I'm trying to crack a similar problem here and I found a pretty neat website that will take your file and run checksums on it with 47 different algorithms and show the results. If the algorithm used to calculate your checksum is any of these algorithms, you would simply find it among the list of checksums produced with a simple text search.</p>\n\n<p>The website is <a href=\"https://defuse.ca/checksums.htm\" rel=\"nofollow\">https://defuse.ca/checksums.htm</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1081/"
]
| Let's assume that I have some packets with a 16-bit checksum at the end. I would like to guess which checksum algorithm is used.
For a start, from dump data I can see that one byte change in the packet's payload totally changes the checksum, so I can assume that it isn't some kind of simple XOR or sum.
Then I tried [several variations of CRC16](http://svn.rot13.org/index.cgi/RFID/view/guess-crc.pl), but without much luck.
This question might be more biased towards cryptography, but I'm really interested in any easy to understand statistical tools to find out which CRC this might be. I might even turn to [drawing different CRC algorithms](http://lcamtuf.coredump.cx/newtcp/) if everything else fails.
Backgroud story: I have serial RFID protocol with some kind of checksum. I can replay messages without problem, and interpret results (without checksum check), but I can't send modified packets because device drops them on the floor.
Using existing software, I can change payload of RFID chip. However, unique serial number is immutable, so I don't have ability to check every possible combination. Allthough I could generate dumps of values incrementing by one, but not enough to make exhaustive search applicable to this problem.
[dump files with data](http://www.bljak.org/~dpavlin/rfid-serial-dump.tar.gz) are available if question itself isn't enough :-)
**Need reference documentation?** [A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS](http://www.geocities.com/SiliconValley/Pines/8659/crc.htm) is great reference which I found after asking question here.
In the end, after very helpful hint in accepted answer than it's CCITT, I
[used this CRC calculator](http://www.zorc.breitbandkatze.de/crc.html), and xored generated checksum with known checksum to get 0xffff which led me to conclusion that final xor is 0xffff instread of CCITT's 0x0000. | There are a number of variables to consider for a CRC:
```
Polynomial
No of bits (16 or 32)
Normal (LSB first) or Reverse (MSB first)
Initial value
How the final value is manipulated (e.g. subtracted from 0xffff), or is a constant value
```
Typical CRCs:
```
LRC: Polynomial=0x81; 8 bits; Normal; Initial=0; Final=as calculated
CRC16: Polynomial=0xa001; 16 bits; Normal; Initial=0; Final=as calculated
CCITT: Polynomial=0x1021; 16 bits; reverse; Initial=0xffff; Final=0x1d0f
Xmodem: Polynomial=0x1021; 16 bits; reverse; Initial=0; Final=0x1d0f
CRC32: Polynomial=0xebd88320; 32 bits; Normal; Initial=0xffffffff; Final=inverted value
ZIP32: Polynomial=0x04c11db7; 32 bits; Normal; Initial=0xffffffff; Final=as calculated
```
The first thing to do is to get some samples by changing say the last byte. This will assist you to figure out the number of bytes in the CRC.
Is this a "homemade" algorithm. In this case it may take some time. Otherwise try the standard algorithms.
Try changing either the msb or the lsb of the last byte, and see how this changes the CRC. This will give an indication of the direction.
To make it more difficult, there are implementations that manipulate the CRC so that it will not affect the communications medium (protocol).
From your comment about RFID, it implies that the CRC is communications related. Usually CRC16 is used for communications, though CCITT is also used on some systems.
On the other hand, if this is UHF RFID tagging, then there are a few CRC schemes - a 5 bit one and some 16 bit ones. These are documented in the ISO standards and the IPX data sheets.
```
IPX: Polynomial=0x8005; 16 bits; Reverse; Initial=0xffff; Final=as calculated
ISO 18000-6B: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated
ISO 18000-6C: Polynomial=0x1021; 16 bits; Reverse; Initial=0xffff; Final=as calculated
Data must be padded with zeroes to make a multiple of 8 bits
ISO CRC5: Polynomial=custom; 5 bits; Reverse; Initial=0x9; Final=shifted left by 3 bits
Data must be padded with zeroes to make a multiple of 8 bits
EPC class 1: Polynomial=custom 0x1021; 16 bits; Reverse; Initial=0xffff; Final=post processing of 16 zero bits
```
**Here is your answer!!!!**
**Having worked through your logs, the CRC is the CCITT one. The first byte 0xd6 is excluded from the CRC.** |
149,627 | <p>Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.</p>
| [
{
"answer_id": 149650,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 2,
"selected": true,
"text": "<p>Not unless you want to get into dynamic SQL. Since you wrote \"clean\", I'll assume not.</p>\n\n<p><strong>Edit:</strong> Since he asked for a dynamic SQL example, I'll take a stab at it. I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision. But hopefully it captures the spirit of things:</p>\n\n<pre><code>-- Get list of columns in table\nSELECT INTO #t\nEXEC sp_columns @table_name = N'TargetTable'\n\n-- Create a comma-delimited string excluding the identity column\nDECLARE @cols varchar(MAX)\nSELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'\n\n-- Construct dynamic SQL statement\nDECLARE @sql varchar(MAX)\nSET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +\n 'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'\n\nPRINT @sql -- for debugging\nEXEC(@sql)\n</code></pre>\n"
},
{
"answer_id": 149675,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 0,
"selected": false,
"text": "<p>You could create an insert trigger to do this, however, you would lose the ability to do an insert with an explicit ID. It would, instead, always use the value from the sequence.</p>\n"
},
{
"answer_id": 149700,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "<p>There's no easy and clean way that I can think of off the top of my head, but from a few items in your question I'd be concerned about your underlying architecture. Maybe you have an absolutely legitimate reason for wanting to do this, but usually you want to try to avoid duplicates in a database, not make them easier to cause. Also, explicitly naming columns is usually a good idea. If you're linking to outside code, it makes sure that you don't break that link when you add a new column. If you're not (and it sounds like you probably aren't in this scenario) I still prefer to have the columns listed out because it forces me to review the effects of the change/new column - even if it's just to look at the code and decide that adding the new column is not a problem.</p>\n"
},
{
"answer_id": 149785,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a trigger to do it for you. To make sure that trigger only works for cloning, you could create a separate username CLONE and log in with it. Or, even better, if your DBMS supports it, create a role named CLONE and any user can log in using that role and do the cloning. The trigger code would be something like:</p>\n\n<pre><code>if (CURRENT_ROLE = 'CLONE') then\n new.ID = assign new id from generator/sequence\n</code></pre>\n\n<p>Of course, you would grant that role only to the users who are allowed to clone records.</p>\n"
},
{
"answer_id": 2437212,
"author": "Danny",
"author_id": 292794,
"author_profile": "https://Stackoverflow.com/users/292794",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DROP TABLE #tmp_MyTable\n\nSELECT * INTO #tmp_MyTable\nFROM MyTable\nWHERE MyIndentID = 165\n\nALTER TABLE #tmp_MyTable\nDROP Column MyIndentID\n\nINSERT INTO MyTable\nSELECT * \nFROM #tmp_MyTable\n</code></pre>\n"
},
{
"answer_id": 9830110,
"author": "Marie",
"author_id": 1286924,
"author_profile": "https://Stackoverflow.com/users/1286924",
"pm_score": 1,
"selected": false,
"text": "<p>This also deals with a unique key projectnum as well as the primary key.</p>\n\n<pre><code>CREATE TEMPORARY TABLE projecttemp SELECT * FROM project WHERE projectid='6';\nALTER TABLE projecttemp DROP COLUMN projectid;\nUPDATE projecttemp SET projectnum = CONCAT(projectnum, ' CLONED');\nINSERT INTO project SELECT NULL,projecttemp.* FROM projecttemp;\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
]
| Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time. | Not unless you want to get into dynamic SQL. Since you wrote "clean", I'll assume not.
**Edit:** Since he asked for a dynamic SQL example, I'll take a stab at it. I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision. But hopefully it captures the spirit of things:
```
-- Get list of columns in table
SELECT INTO #t
EXEC sp_columns @table_name = N'TargetTable'
-- Create a comma-delimited string excluding the identity column
DECLARE @cols varchar(MAX)
SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'
-- Construct dynamic SQL statement
DECLARE @sql varchar(MAX)
SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +
'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'
PRINT @sql -- for debugging
EXEC(@sql)
``` |
149,639 | <p>I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview.</p>
<p>Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted?</p>
<pre>
Task Table
----------
TaskId
ParentTaskId
TaskOrder
TaskName
--etc--
</pre>
<p>Any ideas? Thanks.</p>
| [
{
"answer_id": 149695,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>If you're only using TaskOrder for sorting, it would certainly be simpler to simply leave the holes in TaskOrder, because simply deleting items won't make the sorting incorrect. But then I'm not sure about your application's needs.</p>\n"
},
{
"answer_id": 149709,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>Not directly. This is a <a href=\"http://en.wikipedia.org/wiki/Topological_sorting\" rel=\"nofollow noreferrer\">Topological Sort</a> where you are 'hanging' the child nodes off a parent. If there is no dependency within the children the order that they are executed does not matter. If the children must be executed in a certain order then you do not have enough information to infer this - they would have to have additional levels of hierarchy.</p>\n\n<p>Assuming that the order of children within a parent is irrelevant then a topoligical sort will get you what you want. You won't get this into a single query in most SQL dialects - you will have to write a sproc to do it.</p>\n\n<p>If the order of the children within the node is relevant then you need to maintain the task order within the parent. A query using ParentNodeID, TaskOrder and count (*) will pick out duplicates but unless the system has additional information to order the tasks you will still need manual intervention to select the correct order.</p>\n\n<p>Please add comments if you want me to clarify something.</p>\n"
},
{
"answer_id": 149711,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>This looks like a job for ROW_Number.</p>\n\n<pre><code>DECLARE @Tasks TABLE\n(\n TaskId int PRIMARY KEY,\n ParentTaskId int,\n TaskOrder int,\n TaskName varchar(30)\n)\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 1, null, 1, 'ParentTask'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 2, 1, 2, 'B'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 3, 1, 1, 'A'\n\nINSERT INTO @Tasks(TaskId, ParentTaskId, TaskOrder, TaskName)\nSELECT 4, 1, 3, 'C'\n--Initial\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n\nDELETE FROM @Tasks WHERE TaskId = 2\n--After Delete\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n\n\nUPDATE t\nSET TaskOrder = NewTaskOrder\nFROM @Tasks t\n JOIN\n(\nSELECT TaskId, ROW_Number() OVER(ORDER BY TaskOrder) as NewTaskOrder\nFROM @Tasks\nWHERE ParentTaskId = 1\n) sub ON t.TaskId = sub.TaskId\n\n--After Update\nSELECT * FROM @Tasks WHERE ParentTaskId = 1 ORDER BY TaskOrder\n</code></pre>\n"
},
{
"answer_id": 149713,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<p>Delete task 88:</p>\n\n<pre><code>UPDATE TaskTable\nSET ParentTaskID = (SELECT ParentTaskID AS temp FROM Task_Table t1 WHERE TaskID = 88)\nWHERE\nTaskID IN (SELECT TaskID task2 FROM TaskTable t2 WHERE ParentTaskID = 88);\nDelete FROM TaskTable WHERE TaskID = 88;\n</code></pre>\n\n<p>Of course, you could eliminate the delete, and just leave the record lying around for future reporting purposes.</p>\n\n<p>CAVEAT: NOT TESTED!!!</p>\n"
},
{
"answer_id": 150920,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 2,
"selected": true,
"text": "<p>Couple of different ways... Since the TaskOrder is scoped by parent id, it's not terribly difficult to gather it. In SQL Server, I'd put a trigger on delete that decrements all the ones 'higher' than the one you deleted, thereby closing the gap (pseudocode follows):</p>\n\n<pre><code>CREATE TRIGGER ON yourtable FOR DELETE\nAS\n UPDATE Task\n SET TaskOrder = TaskOrder - 1\n WHERE ParentTaskId = deleted.ParentTaskId\n AND TaskOrder > deleted.TaskOrder\n</code></pre>\n\n<p>If you don't want a trigger, you can capture the parentID and TaskOrder in a query first, delete the row, then execute that same update statement but with literals rather than the trigger.</p>\n\n<p>Or if you want to minimize server round-trips, you could move the to-be-deleted task all the way to the bottom, then move the others up, then do the delete, but that seems overly complicated.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
]
| I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview.
Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent and update the TaskOder column when a sibling is deleted?
```
Task Table
----------
TaskId
ParentTaskId
TaskOrder
TaskName
--etc--
```
Any ideas? Thanks. | Couple of different ways... Since the TaskOrder is scoped by parent id, it's not terribly difficult to gather it. In SQL Server, I'd put a trigger on delete that decrements all the ones 'higher' than the one you deleted, thereby closing the gap (pseudocode follows):
```
CREATE TRIGGER ON yourtable FOR DELETE
AS
UPDATE Task
SET TaskOrder = TaskOrder - 1
WHERE ParentTaskId = deleted.ParentTaskId
AND TaskOrder > deleted.TaskOrder
```
If you don't want a trigger, you can capture the parentID and TaskOrder in a query first, delete the row, then execute that same update statement but with literals rather than the trigger.
Or if you want to minimize server round-trips, you could move the to-be-deleted task all the way to the bottom, then move the others up, then do the delete, but that seems overly complicated. |
149,646 | <p>In the Apple documentation for <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run" rel="noreferrer">NSRunLoop</a> there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.</p>
<pre><code>BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
</code></pre>
<p>I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a <code>NSLog</code> on the line after the flag is being set (in another method) and then a line after the <code>while()</code> there is a seemingly random wait between the two log statements of several seconds.</p>
<p>The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.</p>
<p>I have worked around this issue with the following code but it does not seem right that the original code doesn't work.</p>
<pre><code>NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil])
loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
</code></pre>
<p>using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.</p>
<p>Anyone any ideas why the original code exhibits this behaviour?</p>
| [
{
"answer_id": 150302,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 6,
"selected": true,
"text": "<p>Runloops can be a bit of a magic box where stuff just happens.</p>\n\n<p>Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit.</p>\n\n<p>With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event.</p>\n\n<p>With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind.</p>\n\n<p>A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP. </p>\n\n<p>You might want to play around with runloop observers so you can see exactly what the runloop is doing.</p>\n\n<p>See <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW22\" rel=\"noreferrer\">this Apple doc</a> for more information.</p>\n"
},
{
"answer_id": 150417,
"author": "Jon Shea",
"author_id": 3770,
"author_profile": "https://Stackoverflow.com/users/3770",
"pm_score": 2,
"selected": false,
"text": "<p>I’ve had similar issues while trying to manage <code>NSRunLoops</code>. The <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/doc/uid/20000321-CHDDBFEA\" rel=\"nofollow noreferrer\">discussion</a> for <code>runMode:beforeDate:</code> on the class references page says:</p>\n\n<blockquote>\n <p>If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it returns after either the first input source is processed or limitDate is reached. Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. Mac OS X may install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.</p>\n</blockquote>\n\n<p>My best guess is that an input source is attached to your <code>NSRunLoop</code>, perhaps by OS X itself, and that <code>runMode:beforeDate:</code> is blocking until that input source either has some input processed, or is removed. In your case it was taking \"<em>couple of seconds and up to 10 seconds</em>\" for this to happen, at which point <code>runMode:beforeDate:</code> would return with a boolean, the <code>while()</code> would run again, it would detect that <code>shouldKeepRunning</code> has been set to <code>NO</code>, and the loop would terminate.</p>\n\n<p>With your refinement the <code>runMode:beforeDate:</code> will return within 0.1 seconds, regardless of whether or not it has attached input sources or has processed any input. It's an educated guess (I'm not an expert on the run loop internals), but think your refinement is the right way to handle the situation.</p>\n"
},
{
"answer_id": 151500,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to be able to set your flag variable and have the run loop immediately notice, just use <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/doc/uid/20000321-performSelector_target_argument_order_modes_\" rel=\"noreferrer\" title=\"-[NSRunLoop performSelector:target:argument:order:modes:]\"><code>-[NSRunLoop performSelector:target:argument:order:modes:</code></a> to ask the run loop to invoke the method that sets the flag to false. This will cause your run loop to spin immediately, the method to be invoked, and then the flag will be checked.</p>\n"
},
{
"answer_id": 173948,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 3,
"selected": false,
"text": "<p>At your code the current thread will check for the variable to have changed every 0.1 seconds. In the Apple code example, changing the variable will not have any effect. The runloop will run till it processes some event. If the value of webViewIsLoading has changed, no event is generated automatically, thus it will stay in the loop, why would it break out of it? It will stay there, till it gets some other event to process, then it will break out of it. This may happen in 1, 3, 5, 10 or even 20 seconds. And until that happens, it will not break out of the runloop and thus it won't notice that this variable has changed. IOW the Apple code you quoted is indeterministic. This example will only work if the value change of webViewIsLoading also creates an event that causes the runloop to wake up and this seems not to be the case (or at least not always).</p>\n\n<p>I think you should re-think the problem. Since your variable is named webViewIsLoading, do you wait for a webpage to be loaded? Are you using Webkit for that? I doubt you need such a variable at all, nor any of the code you have posted. Instead you should code your app asynchronously. You should start the \"web page load process\" and then go back to the main loop and as soon as the page finished loading, you should asynchronously post a notification that is processed within the main thread and runs the code that should run as soon as loading has finished.</p>\n"
},
{
"answer_id": 178083,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "<p>Okay, I explained you the problem, here's a possible solution:</p>\n\n<pre><code>@implementation MyWindowController\n\nvolatile BOOL pageStillLoading;\n\n- (void) runInBackground:(id)arg\n{\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n // Simmulate web page loading\n sleep(5);\n\n // This will not wake up the runloop on main thread!\n pageStillLoading = NO;\n\n // Wake up the main thread from the runloop\n [self performSelectorOnMainThread:@selector(wakeUpMainThreadRunloop:) withObject:nil waitUntilDone:NO];\n\n [pool release];\n}\n\n\n- (void) wakeUpMainThreadRunloop:(id)arg\n{\n // This method is executed on main thread!\n // It doesn't need to do anything actually, just having it run will\n // make sure the main thread stops running the runloop\n}\n\n\n- (IBAction)start:(id)sender\n{\n pageStillLoading = YES;\n [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil];\n [progress setHidden:NO];\n while (pageStillLoading) {\n [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];\n }\n [progress setHidden:YES];\n}\n\n@end\n</code></pre>\n\n<p><em>start</em> displays a progress indicator and captures the main thread in an internal runloop. It will stay there till the other thread announces that it is done. To wake up the main thread, it will make it process a function with no purpose other than waking the main thread up.</p>\n\n<p>This is just one way how you can do it. A notification being posted and processed on main thread might be preferable (also other threads could register for it), but the solution above is the simplest I can think of. BTW it is not really thread-safe. To really be thread-safe, every access to the boolean needs to be locked by a NSLock object from either thread (using such a lock also makes \"volatile\" obsolete, as variables protected by a lock are implicit volatile according to POSIX standard; the C standard however doesn't know about locks, so here only volatile can guarantee this code to work; GCC doesn't need volatile to be set for a variable protected by locks).</p>\n"
},
{
"answer_id": 237152,
"author": "Wil Shipley",
"author_id": 30602,
"author_profile": "https://Stackoverflow.com/users/30602",
"pm_score": 4,
"selected": false,
"text": "<p>In general, if you are processing events yourself in a loop, you're Doing It Wrong. It can cause a ton of messy problems, in my experience.</p>\n\n<p>If you want to run modally -- for example, showing a progress panel -- run modally! Go ahead and use the NSApplication methods, run modally for the progress sheet, then stop the modal when the load is done. See the Apple documentation, for example <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/WinPanel/Concepts/UsingModalWindows.html\" rel=\"noreferrer\">http://developer.apple.com/documentation/Cocoa/Conceptual/WinPanel/Concepts/UsingModalWindows.html</a> .</p>\n\n<p>If you just want a view to be up for the duration of your load, but you don't want it to be modal (eg, you want other views to be able to respond to events), then you should do something much simpler. For instance, you could do this:</p>\n\n<pre><code>- (IBAction)start:(id)sender\n{\n pageStillLoading = YES;\n [NSThread detachNewThreadSelector:@selector(runInBackground:) toTarget:self withObject:nil];\n [progress setHidden:NO];\n}\n\n- (void)wakeUpMainThreadRunloop:(id)arg\n{\n [progress setHidden:YES];\n}\n</code></pre>\n\n<p>And you're done. No need to keep control of the run loop!</p>\n\n<p>-Wil</p>\n"
},
{
"answer_id": 18221959,
"author": "Richard",
"author_id": 1640726,
"author_profile": "https://Stackoverflow.com/users/1640726",
"pm_score": 1,
"selected": false,
"text": "<p>Your second example just work around as you poll to check input of the run loop within time interval 0.1.</p>\n\n<p>Occasionally I find a solution for your first example:</p>\n\n<pre><code>BOOL shouldKeepRunning = YES; // global\nNSRunLoop *theRL = [NSRunLoop currentRunLoop];\nwhile (shouldKeepRunning && [theRL runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]]);\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4496/"
]
| In the Apple documentation for [NSRunLoop](http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/occ/instm/NSRunLoop/run) there is sample code demonstrating suspending execution while waiting for a flag to be set by something else.
```
BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
```
I have been using this and it works but in investigating a performance issue I tracked it down to this piece of code. I use almost exactly the same piece of code (just the name of the flag is different :) and if I put a `NSLog` on the line after the flag is being set (in another method) and then a line after the `while()` there is a seemingly random wait between the two log statements of several seconds.
The delay does not seem to be different on slower or faster machines but does vary from run to run being at least a couple of seconds and up to 10 seconds.
I have worked around this issue with the following code but it does not seem right that the original code doesn't work.
```
NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
while (webViewIsLoading && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil])
loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
```
using this code, the log statements when setting the flag and after the while loop are now consistently less than 0.1 seconds apart.
Anyone any ideas why the original code exhibits this behaviour? | Runloops can be a bit of a magic box where stuff just happens.
Basically you're telling the runloop to go process some events and then return. OR return if it doesn't process any events before the timeout is hit.
With 0.1 second timeout, you're htting the timeout more often than not. The runloop fires, doesn't process any events and returns in 0.1 of second. Occasionally it'll get a chance to process an event.
With your distantFuture timeout, the runloop will wait foreever until it processes an event. So when it returns to you, it has just processed an event of some kind.
A short timeout value will consume considerably more CPU than the infinite timeout but there are good reasons for using a short timeout, for example if you want to terminate the process/thread the runloop is running in. You'll probably want the runloop to notice that a flag has changed and that it needs to bail out ASAP.
You might want to play around with runloop observers so you can see exactly what the runloop is doing.
See [this Apple doc](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW22) for more information. |
149,690 | <p>I am trying to extract a certain part of a column that is between delimiters.</p>
<p>e.g. find foo in the following</p>
<p>test 'esf :foo: bar</p>
<p>So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL</p>
| [
{
"answer_id": 149703,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<p>A combination of <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_locate\" rel=\"nofollow noreferrer\">LOCATE</a> and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_mid\" rel=\"nofollow noreferrer\">MID</a> would probably do the trick.</p>\n\n<p>If the value <em>\"test 'esf :foo: bar\"</em> was in the field <strong>fooField</strong>:</p>\n\n<pre><code>MID( fooField, LOCATE('foo', fooField), 3);\n</code></pre>\n"
},
{
"answer_id": 149743,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if you have this kind of authority, but if you have to do queries like this it might be time to renormalize your tables, and have these values in a lookup table. </p>\n"
},
{
"answer_id": 149756,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select mid(col from locate(':',col) + 1 for \nlocate(':',col,locate(':',col)+1)-locate(':',col) - 1 ) \nfrom table where col rlike ':.*:';\n</code></pre>\n"
},
{
"answer_id": 149770,
"author": "Pete Karl II",
"author_id": 22491,
"author_profile": "https://Stackoverflow.com/users/22491",
"pm_score": 6,
"selected": true,
"text": "<p>Here ya go, bud:</p>\n\n<pre><code>SELECT \n SUBSTR(column, \n LOCATE(':',column)+1, \n (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) \nFROM table\n</code></pre>\n\n<p>Yea, no clue why you're doing this, but this will do the trick.</p>\n\n<p>By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).</p>\n\n<p>With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (<em>don't use LENGTH() for this</em>), we can use a little math to discover the length of the string between the two instances of ':'.</p>\n\n<p>This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.</p>\n\n<p>Again, it's gross, but to each his own.</p>\n"
},
{
"answer_id": 149791,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "<p>With only one set of delimeters, the following should work:</p>\n\n<pre><code>SUBSTR(\n SUBSTR(fooField,LOCATE(':',fooField)+1),\n 1,\n LOCATE(':',SUBSTR(fooField,LOCATE(':',fooField)+1))-1\n )\n</code></pre>\n"
},
{
"answer_id": 149816,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>If you know the position you want to extract from as opposed to what the data itself is:</p>\n\n<pre><code>$colNumber = 2; //2nd position\n$sql = \"REPLACE(SUBSTRING(SUBSTRING_INDEX(fooField, ':', $colNumber),\n LENGTH(SUBSTRING_INDEX(fooField, \n ':', \n $colNumber - 1)) + 1)\";\n</code></pre>\n"
},
{
"answer_id": 23839571,
"author": "chris2k",
"author_id": 2854900,
"author_profile": "https://Stackoverflow.com/users/2854900",
"pm_score": -1,
"selected": false,
"text": "<p>you can use the substring / locate function in 1 command </p>\n\n<p>here is a mice tutorial:</p>\n\n<p><a href=\"http://infofreund.de/mysql-select-substring-2-different-delimiters/\" rel=\"nofollow\">http://infofreund.de/mysql-select-substring-2-different-delimiters/</a></p>\n\n<p>The command as describes their should look for u:</p>\n\n<p>**SELECT substr(text,Locate(' :', text )+2,Locate(': ', text )-(Locate(' :', text )+2)) FROM <code>testtable**</code></p>\n\n<p>where text is the textfield which contains \"test 'esf :foo: bar\"</p>\n\n<p>So foo can be fooooo or fo - the length doesnt matter :).</p>\n"
},
{
"answer_id": 26789184,
"author": "Danny Z",
"author_id": 4224550,
"author_profile": "https://Stackoverflow.com/users/4224550",
"pm_score": 3,
"selected": false,
"text": "<p>This should work if the two delimiters only appear twice in your column. I am doing something similar...</p>\n\n<pre><code>substring_index(substring_index(column,':',-2),':',1)\n</code></pre>\n"
},
{
"answer_id": 28712538,
"author": "hrushikesh",
"author_id": 1492552,
"author_profile": "https://Stackoverflow.com/users/1492552",
"pm_score": 1,
"selected": false,
"text": "<pre><code>mid(col, \n locate('?m=',col) + char_length('?m='), \n locate('&o=',col) - locate('?m=',col) - char_length('?m=') \n)\n</code></pre>\n\n<p>A bit compact form by replacing <code>char_length(.)</code> with the number <code>3</code> </p>\n\n<pre><code>mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3)\n</code></pre>\n\n<p>the patterns I have used are <code>'?m='</code> and <code>'&o'</code>.</p>\n"
},
{
"answer_id": 39865512,
"author": "brewmanz",
"author_id": 2821586,
"author_profile": "https://Stackoverflow.com/users/2821586",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I am extracting from (mainly colon ':' as delimiter but some exceptions), as column theline255 in table loaddata255:</p>\n\n<pre><code>23856.409:0023:trace:message:SPY_EnterMessage (0x2003a) L\"{#32769}\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0\n</code></pre>\n\n<p>This is the MySql code (It quickly did what I want, and is straight forward):</p>\n\n<pre><code>select \ntime('2000-01-01 00:00:00' + interval substring_index(theline255, '.', 1) second) as hhmmss\n, substring_index(substring_index(theline255, ':', 1), '.', -1) as logMilli\n, substring_index(substring_index(theline255, ':', 2), ':', -1) as logTid\n, substring_index(substring_index(theline255, ':', 3), ':', -1) as logType\n, substring_index(substring_index(theline255, ':', 4), ':', -1) as logArea\n, substring_index(substring_index(theline255, ' ', 1), ':', -1) as logFunction\n, substring(theline255, length(substring_index(theline255, ' ', 1)) + 2) as logText\nfrom loaddata255\n</code></pre>\n\n<p>and this is the result:</p>\n\n<pre><code># LogTime, LogTimeMilli, LogTid, LogType, LogArea, LogFunction, LogText\n'06:37:36', '409', '0023', 'trace', 'message', 'SPY_EnterMessage', '(0x2003a) L\\\"{#32769}\\\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0'\n</code></pre>\n"
},
{
"answer_id": 44822505,
"author": "mprot",
"author_id": 7974700,
"author_profile": "https://Stackoverflow.com/users/7974700",
"pm_score": 0,
"selected": false,
"text": "<p>This one looks elegant to me. Strip all after n-th separator, rotate string, strip everything after 1. separator, rotate back. </p>\n\n<pre><code>select\n reverse(\n substring_index(\n reverse(substring_index(str,separator,substrindex)),\n separator,\n 1)\n );\n</code></pre>\n\n<p>For example: </p>\n\n<pre><code>select\n reverse(\n substring_index(\n reverse(substring_index('www.mysql.com','.',2)),\n '.',\n 1\n )\n );\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to extract a certain part of a column that is between delimiters.
e.g. find foo in the following
test 'esf :foo: bar
So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL | Here ya go, bud:
```
SELECT
SUBSTR(column,
LOCATE(':',column)+1,
(CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column)))
FROM table
```
Yea, no clue why you're doing this, but this will do the trick.
By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).
With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR\_LENGTH (*don't use LENGTH() for this*), we can use a little math to discover the length of the string between the two instances of ':'.
This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.
Again, it's gross, but to each his own. |
149,772 | <p>Basically the question is how to get from this:</p>
<pre>
foo_id foo_name
1 A
1 B
2 C
</pre>
<p>to this:</p>
<pre>
foo_id foo_name
1 A B
2 C
</pre>
| [
{
"answer_id": 149799,
"author": "Scott Noyes",
"author_id": 23539,
"author_profile": "https://Stackoverflow.com/users/23539",
"pm_score": 10,
"selected": true,
"text": "<pre><code>SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;\n</code></pre>\n<p><a href=\"https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat</a></p>\n<p>From the link above, <code>GROUP_CONCAT</code>: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.</p>\n"
},
{
"answer_id": 149805,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 7,
"selected": false,
"text": "<pre><code>SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id\n</code></pre>\n\n<p>More details <a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"noreferrer\">here</a>.</p>\n\n<p>From the link above, <code>GROUP_CONCAT</code>: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.</p>\n"
},
{
"answer_id": 149817,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id\n</code></pre>\n\n<p>Will give you a comma-delimited string</p>\n"
},
{
"answer_id": 3785928,
"author": "Waqar Alamgir",
"author_id": 457124,
"author_profile": "https://Stackoverflow.com/users/457124",
"pm_score": 4,
"selected": false,
"text": "<p>The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024 characters, so we first do:</p>\n\n<pre><code>SET group_concat_max_len=100000000;\n</code></pre>\n\n<p>and then, for example:</p>\n\n<pre><code>SELECT pub_id,GROUP_CONCAT(cate_id SEPARATOR ' ') FROM book_mast GROUP BY pub_id\n</code></pre>\n"
},
{
"answer_id": 18118387,
"author": "Exundoz",
"author_id": 2663165,
"author_profile": "https://Stackoverflow.com/users/2663165",
"pm_score": 5,
"selected": false,
"text": "<pre><code>SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;\n</code></pre>\n\n<p>:-\nIn MySQL, you can get the concatenated values of expression combinations\n. To eliminate duplicate values, use the <strong>DISTINCT</strong> clause. To sort values in the result, use the ORDER BY clause. To sort in <em>reverse order</em>, add the <strong><em>DESC</em></strong> (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify <strong>SEPARATOR ''</strong>.</p>\n\n<pre><code>GROUP_CONCAT([DISTINCT] expr [,expr ...]\n [ORDER BY {unsigned_integer | col_name | expr}\n [ASC | DESC] [,col_name ...]]\n [SEPARATOR str_val])\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>mysql> SELECT student_name,\n -> GROUP_CONCAT(DISTINCT test_score\n -> ORDER BY test_score DESC SEPARATOR ' ')\n -> FROM student\n -> GROUP BY student_name;\n</code></pre>\n"
},
{
"answer_id": 44271351,
"author": "Mauricio Alo",
"author_id": 1902560,
"author_profile": "https://Stackoverflow.com/users/1902560",
"pm_score": 4,
"selected": false,
"text": "<p>Great answers.\nI also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows: </p>\n\n<pre><code>SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ') \nFROM table \nGROUP BY id;\n</code></pre>\n\n<p>Hope this helps someone else</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
| Basically the question is how to get from this:
```
foo_id foo_name
1 A
1 B
2 C
```
to this:
```
foo_id foo_name
1 A B
2 C
``` | ```
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
```
<https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat>
From the link above, `GROUP_CONCAT`: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. |
149,784 | <p><a href="https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another">This question</a> comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:</p>
<pre><code>insert into MyTable
select * from MyTable where uniqueId = @Id;
</code></pre>
<p>I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).</p>
<p>I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.</p>
| [
{
"answer_id": 149792,
"author": "AaronSieb",
"author_id": 16911,
"author_profile": "https://Stackoverflow.com/users/16911",
"pm_score": 9,
"selected": true,
"text": "<p>Try this:\n<pre><code>\ninsert into MyTable(field1, field2, id_backup)\n select field1, field2, uniqueId from MyTable where uniqueId = @Id;\n</pre></code></p>\n\n<p>Any fields not specified should receive their default value (which is usually NULL when not defined).</p>\n"
},
{
"answer_id": 149793,
"author": "Scott Bevington",
"author_id": 9544,
"author_profile": "https://Stackoverflow.com/users/9544",
"pm_score": 4,
"selected": false,
"text": "<p>Specify all fields but your ID field.</p>\n\n<pre><code>INSERT INTO MyTable (FIELD2, FIELD3, ..., FIELD529, PreviousId)\nSELECT FIELD2, NULL, ..., FIELD529, FIELD1\nFROM MyTable\nWHERE FIELD1 = @Id;\n</code></pre>\n"
},
{
"answer_id": 149804,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "<pre><code>insert into MyTable (uniqueId, column1, column2, referencedUniqueId)\nselect NewGuid(), // don't know this syntax, sorry\n column1,\n column2,\n uniqueId,\nfrom MyTable where uniqueId = @Id\n</code></pre>\n"
},
{
"answer_id": 149822,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 1,
"selected": false,
"text": "<p>If \"key\" is your PK field and it's autonumeric.</p>\n\n<pre><code>insert into MyTable (field1, field2, field3, parentkey)\nselect field1, field2, null, key from MyTable where uniqueId = @Id\n</code></pre>\n\n<p>it will generate a new record, copying field1 and field2 from the original record</p>\n"
},
{
"answer_id": 894772,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": false,
"text": "<p>I'm guessing you're trying to avoid writing out all the column names. If you're using SQL Management Studio you can easily right click on the table and Script As Insert.. then you can mess around with that output to create your query.</p>\n"
},
{
"answer_id": 2461030,
"author": "Denis Kutlubaev",
"author_id": 295517,
"author_profile": "https://Stackoverflow.com/users/295517",
"pm_score": 0,
"selected": false,
"text": "<p>You can do like this: </p>\n\n<pre><code>INSERT INTO DENI/FRIEN01P \nSELECT \n RCRDID+112,\n PROFESION,\n NAME,\n SURNAME,\n AGE, \n RCRDTYP, \n RCRDLCU, \n RCRDLCT, \n RCRDLCD \nFROM \n FRIEN01P \n</code></pre>\n\n<p>There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P.</p>\n"
},
{
"answer_id": 14427540,
"author": "Rit Man",
"author_id": 1510859,
"author_profile": "https://Stackoverflow.com/users/1510859",
"pm_score": 1,
"selected": false,
"text": "<p>My table has 100 fields, and I needed a query to just work. Now I can switch out any number of fields with some basic conditional logic and not worry about its ordinal position. </p>\n\n<ol>\n<li><p>Replace the below table name with your table name</p>\n\n<pre><code>SQLcolums = \"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')\"\n\nSet GetColumns = Conn.Execute(SQLcolums)\nDo WHILE not GetColumns.eof\n\ncolName = GetColumns(\"COLUMN_NAME\")\n</code></pre></li>\n<li><p>Replace the original identity field name with your PK field name</p>\n\n<pre><code>IF colName = \"ORIGINAL-IDENTITY-FIELD-NAME\" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES\n columnListSOURCE = colName \n columnListTARGET = \"[PreviousId field name]\"\nELSE\n columnListSOURCE = columnListSOURCE & colName\n columnListTARGET = columnListTARGET & colName\nEND IF\n\nGetColumns.movenext\n\nloop\n\nGetColumns.close \n</code></pre></li>\n<li><p>Replace the table names again (both target table name and source table name); edit your <code>where</code> conditions</p>\n\n<pre><code>SQL = \"INSERT INTO TARGET-TABLE-NAME (\" & columnListTARGET & \") SELECT \" & columnListSOURCE & \" FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)\" \nConn.Execute(SQL)\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 15025236,
"author": "Jonas",
"author_id": 1651165,
"author_profile": "https://Stackoverflow.com/users/1651165",
"pm_score": 7,
"selected": false,
"text": "<p>Ok, I know that it's an old issue but I post my answer anyway.</p>\n\n<p>I like this solution. I only have to specify the identity column(s).</p>\n\n<pre><code>SELECT * INTO TempTable FROM MyTable_T WHERE id = 1;\nALTER TABLE TempTable DROP COLUMN id;\nINSERT INTO MyTable_T SELECT * FROM TempTable;\nDROP TABLE TempTable;\n</code></pre>\n\n<p>The \"id\"-column is the identity column and that's the only column I have to specify. It's better than the other way around anyway. :-)</p>\n\n<p>I use SQL Server. You may want to use \"<code>CREATE TABLE</code>\" and \"<code>UPDATE TABLE</code>\" at row 1 and 2.\nHmm, I saw that I did not really give the answer that he wanted. He wanted to copy the id to another column also. But this solution is nice for making a copy with a new auto-id.</p>\n\n<p>I edit my solution with the idéas from Michael Dibbets.</p>\n\n<pre><code>use MyDatabase; \nSELECT * INTO #TempTable FROM [MyTable] WHERE [IndexField] = :id;\nALTER TABLE #TempTable DROP COLUMN [IndexField]; \nINSERT INTO [MyTable] SELECT * FROM #TempTable; \nDROP TABLE #TempTable;\n</code></pre>\n\n<p>You can drop more than one column by separating them with a \",\".\nThe :id should be replaced with the id of the row you want to copy.\nMyDatabase, MyTable and IndexField should be replaced with your names (of course). </p>\n"
},
{
"answer_id": 46045294,
"author": "TonyT",
"author_id": 1621506,
"author_profile": "https://Stackoverflow.com/users/1621506",
"pm_score": 3,
"selected": false,
"text": "<p>I have the same issue where I want a single script to work with a table that has columns added periodically by other developers. Not only that, but I am supporting many different versions of our database as customers may not all be up-to-date with the current version.</p>\n\n<p>I took the solution by Jonas and modified it slightly. This allows me to make a copy of the row and then change the primary key before adding it back into the original source table. This is also really handy for working with tables that do not allow NULL values in columns and you don't want to have to specify each column name in the INSERT.</p>\n\n<p>This code copies the row for 'ABC' to 'XYZ'</p>\n\n<pre><code>SELECT * INTO #TempRow FROM SourceTable WHERE KeyColumn = 'ABC';\nUPDATE #TempRow SET KeyColumn = 'XYZ';\nINSERT INTO SourceTable SELECT * FROM #TempRow;\nDELETE #TempRow;\n</code></pre>\n\n<p>Once you have finished the drop the temp table.</p>\n\n<pre><code>DROP TABLE #TempRow;\n</code></pre>\n"
},
{
"answer_id": 50902859,
"author": "Jeyara",
"author_id": 712826,
"author_profile": "https://Stackoverflow.com/users/712826",
"pm_score": 3,
"selected": false,
"text": "<p>I know my answer is late to the party. But the way i solved is bit different than all the answers.</p>\n\n<p>I had a situation, i need to clone a row in a table except few columns. Those few will have new values. This process should support automatically for future changes to the table. This implies, clone the record without specifying any column names. </p>\n\n<p>My approach is to,</p>\n\n<ol>\n<li>Query Sys.Columns to get the full list of columns for the table and include the names \nof columns to skip in where clause.</li>\n<li>Convert that in to CSV as column names. </li>\n<li>Build Select ... Insert into script based on this.</li>\n</ol>\n\n<p><pre><code>\ndeclare @columnsToCopyValues varchar(max), @query varchar(max)\nSET @columnsToCopyValues = ''</p>\n\n<p>--Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2\nSelect @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2')\nSelect @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues))\nprint @columnsToCopyValues</p>\n\n<p>Select @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''')</p>\n\n<p>print @query\nexec (@query)\n</pre></code></p>\n"
},
{
"answer_id": 54237321,
"author": "Daniel Nordh",
"author_id": 9450614,
"author_profile": "https://Stackoverflow.com/users/9450614",
"pm_score": 0,
"selected": false,
"text": "<p>Here is how I did it using ASP classic and couldn't quite get it to work with the answers above and I wanted to be able to copy a product in our system to a new product_id and needed it to be able to work even when we add in more columns to the table.</p>\n\n<pre><code>Cn.Execute(\"CREATE TEMPORARY TABLE temprow AS SELECT * FROM product WHERE product_id = '12345'\")\nCn.Execute(\"UPDATE temprow SET product_id = '34567'\")\nCn.Execute(\"INSERT INTO product SELECT * FROM temprow\")\nCn.Execute(\"DELETE temprow\")\nCn.Execute(\"DROP TABLE temprow\")\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
| [This question](https://stackoverflow.com/questions/57168/how-to-copy-a-row-from-one-sql-server-table-to-another) comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:
```
insert into MyTable
select * from MyTable where uniqueId = @Id;
```
I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).
I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is. | Try this:
```
insert into MyTable(field1, field2, id_backup)
select field1, field2, uniqueId from MyTable where uniqueId = @Id;
```
Any fields not specified should receive their default value (which is usually NULL when not defined). |
149,796 | <p>Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user_id' and 'pref_key' columns in the example:</p>
<p><strong>1. Blind insert, update if receiving a duplicate key error:</strong></p>
<pre><code>// Try to insert as a new value
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If a duplicate-key error occurs run an update query
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p><strong>2. Check for existence, then select or update:</strong></p>
<pre><code>// Check for existence
SELECT COUNT(*)
FROM my_prefs
WHERE user_id=1234 AND pref_key='show_help';
// If count is zero, insert
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If count is one, update
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
</code></pre>
<p>The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert?</p>
| [
{
"answer_id": 149812,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 0,
"selected": false,
"text": "<p>The first way is the preferred way as far as I know.</p>\n"
},
{
"answer_id": 149819,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I am never a fan of exception based programming (expecting an exception in the normal operation of an application) and to me the second example is much more readable/maintainable.</p>\n\n<p>There are situations where this would make a difference (very tight loops for example) but I think there should be a good reason to write code like this rather than it being the default.</p>\n"
},
{
"answer_id": 149826,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>In your DAO model you could have an id field.</p>\n\n<ul>\n<li><p>If set to null / -1 / whatever, the data hasn't been persisted.</p></li>\n<li><p>When you persist it (or retrieve from database), set it to the id value in the database.</p></li>\n<li><p>Your persist method can check the ID and pass it onto the update() or add() implementation.</p></li>\n<li><p>Flaws: Getting out of sync with the database, etc. I'm sure there are more, but I really should get some work done...</p></li>\n</ul>\n"
},
{
"answer_id": 149834,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>There is the third MySQL way, which would be the preferred one in that RDBMS</p>\n\n<pre><code>INSERT INTO my_prefs \n(user_id, pref_key, pref_value) \nVALUES (1234, 'show_help', 'true')\nON DUPLICATE KEY \nUPDATE pref_value = 'true'\n</code></pre>\n"
},
{
"answer_id": 149836,
"author": "Paul Kroll",
"author_id": 6280,
"author_profile": "https://Stackoverflow.com/users/6280",
"pm_score": 2,
"selected": false,
"text": "<p>You may be able to use REPLACE instead, or if using a more current MySQL you get the option of using \"<a href=\"http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html\" rel=\"nofollow noreferrer\">INSERT ... ON DUPLICATE KEY UPDATE</a>\"</p>\n\n<p>The fact that several people brought this up in quick succession says \"always check the MySQL docs\" when you have an issue, as they're decent and in many cases, leads directly to the solution.</p>\n"
},
{
"answer_id": 149837,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 4,
"selected": false,
"text": "<p>have a look at the ON DUPLICATE KEY syntax in <a href=\"http://dev.mysql.com/doc/refman/5.0/en/insert-select.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/insert-select.html</a></p>\n\n<pre><code>INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n[INTO] tbl_name [(col_name,...)]\nSELECT ...\n[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]\n</code></pre>\n"
},
{
"answer_id": 149841,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 0,
"selected": false,
"text": "<p>So long as you're using <code>MySQL</code>, you can use the <code>ON DUPLICATE</code> keyword. For example:</p>\n\n<pre><code>INSERT INTO my_prefs (user_id, pref_key, pref_value) VALUES (1234, 'show_help', 'true') \nON DUPLICATE KEY UPDATE (pref_key, pref_value) VALUES ('show_help', 'true');\n</code></pre>\n"
},
{
"answer_id": 149849,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to avoid \"the exception\" by perhaps inserting a doublette and you want to use standard SQL (and your programming language / database returns the count of the updated rows) then use the following \"SQL\" - commands (pseudo-code):</p>\n\n<pre><code>int i = SQL(\"UPDATE my_prefs ...\");\nif(i==0) {\n SQL(\"INSERT INTO my_prefs ...\");\n}\n</code></pre>\n\n<p>This also takes in account that - for the most use cases - updates do occur more often than inserts.</p>\n"
},
{
"answer_id": 150305,
"author": "Scott Lamb",
"author_id": 23584,
"author_profile": "https://Stackoverflow.com/users/23584",
"pm_score": 3,
"selected": true,
"text": "<p>Will there be concurrent INSERTs to these rows? DELETEs?</p>\n\n<p>\"ON DUPLICATE\" sounds great (the behavior is just what you want) provided that you're not concerned about portability to non-MySQL databases.</p>\n\n<p>The \"blind insert\" seems reasonable and robust provided that rows are never deleted. (If the INSERT case fails because the row exists, the UPDATE afterward should succeed because the row still exists. But this assumption is false if rows are deleted - you'd need retry logic then.) On other databases without \"ON DUPLICATE\", you might consider an optimization if you find latency to be bad: you could avoid a database round trip in the already-exists case by putting this logic in a stored procedure.</p>\n\n<p>The \"check for existence\" is tricky to get right if there are concurrent INSERTs. Rows could be added between your SELECT and your UPDATE. Transactions won't even really help - I think even at isolation level \"serializable\", you'll see \"could not serialize access due to concurrent update\" errors occasionally (or whatever the MySQL equivalent error message is). You'll need retry logic, so I'd say the person above who suggests using this method to avoid \"exception-based programming\" is wrong, as is the person who suggests doing the UPDATE first for the same reason.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15872/"
]
| Often I want to add a value to a table or update the value if its key already exists. This can be accomplished in several ways, assuming a primary or unique key is set on the 'user\_id' and 'pref\_key' columns in the example:
**1. Blind insert, update if receiving a duplicate key error:**
```
// Try to insert as a new value
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If a duplicate-key error occurs run an update query
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
```
**2. Check for existence, then select or update:**
```
// Check for existence
SELECT COUNT(*)
FROM my_prefs
WHERE user_id=1234 AND pref_key='show_help';
// If count is zero, insert
INSERT INTO my_prefs
(user_id, pref_key, pref_value)
VALUES (1234, 'show_help', 'true');
// If count is one, update
UPDATE my_prefs
SET pref_value = 'true'
WHERE user_id=1234 AND pref_key='show_help';
```
The first way seems to be preferable as it will require only one query for new inserts and two for an update, where as the second way will always require two queries. Is there anything I'm missing though that would make it a bad idea to blindly insert? | Will there be concurrent INSERTs to these rows? DELETEs?
"ON DUPLICATE" sounds great (the behavior is just what you want) provided that you're not concerned about portability to non-MySQL databases.
The "blind insert" seems reasonable and robust provided that rows are never deleted. (If the INSERT case fails because the row exists, the UPDATE afterward should succeed because the row still exists. But this assumption is false if rows are deleted - you'd need retry logic then.) On other databases without "ON DUPLICATE", you might consider an optimization if you find latency to be bad: you could avoid a database round trip in the already-exists case by putting this logic in a stored procedure.
The "check for existence" is tricky to get right if there are concurrent INSERTs. Rows could be added between your SELECT and your UPDATE. Transactions won't even really help - I think even at isolation level "serializable", you'll see "could not serialize access due to concurrent update" errors occasionally (or whatever the MySQL equivalent error message is). You'll need retry logic, so I'd say the person above who suggests using this method to avoid "exception-based programming" is wrong, as is the person who suggests doing the UPDATE first for the same reason. |
149,800 | <p>I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work.</p>
<p>The code for creating the button can be found below.</p>
<pre><code>_button = new RadioButton();
_button.setStyle("textFormat", _format);
_button.label = _config.toString();
_button.width = Number(_defaults.@alen);
_button.textField.width = Number(_defaults.@alen);
_button.textField.multiline = true;
_button.textField.wordWrap = true;
_button.value = _config.@value;
_button.group = _group;
_button.x = _config.@x;
_button.y = _config.@y;
</code></pre>
<p>_config is a piece of XML, and _defaults is a piece of XML containing size-information and font-setup</p>
<p>When I set _button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at _defaults.@alen, which I want, but looks like it happens pretty much after each word.</p>
<p>Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it.</p>
| [
{
"answer_id": 149926,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 3,
"selected": true,
"text": "<p>Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up some of the width.</p>\n\n<p>If you can't get it to work, instead of banging your head on it, might want to just create the label separately, either a simple TextField, or using a Label component. Slightly more code, but might be worth it to spend an extra 10 minutes writing code versus two hours getting the component to work how you want.</p>\n"
},
{
"answer_id": 149955,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The passed width is in pixels. </p>\n\n<p>I previously had some problems with not being able to style the label with CSS (at least I couldn't figure out how), so went with a regular textfield. Was a bit of a hassle to get the aligning just right, so I was hoping it was possible to move back to just the component.</p>\n\n<p>I've been banging my head for two-three hours now, so I think it's back to a regular textfield again for me...</p>\n"
},
{
"answer_id": 5940594,
"author": "Rose",
"author_id": 466884,
"author_profile": "https://Stackoverflow.com/users/466884",
"pm_score": 0,
"selected": false,
"text": "<p>I think a better solution is <a href=\"http://blogs.adobe.com/aharui/2007/04/multiline_buttons.html\" rel=\"nofollow\">here</a> . Check that out.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work.
The code for creating the button can be found below.
```
_button = new RadioButton();
_button.setStyle("textFormat", _format);
_button.label = _config.toString();
_button.width = Number(_defaults.@alen);
_button.textField.width = Number(_defaults.@alen);
_button.textField.multiline = true;
_button.textField.wordWrap = true;
_button.value = _config.@value;
_button.group = _group;
_button.x = _config.@x;
_button.y = _config.@y;
```
\_config is a piece of XML, and \_defaults is a piece of XML containing size-information and font-setup
When I set \_button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at \_defaults.@alen, which I want, but looks like it happens pretty much after each word.
Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it. | Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up some of the width.
If you can't get it to work, instead of banging your head on it, might want to just create the label separately, either a simple TextField, or using a Label component. Slightly more code, but might be worth it to spend an extra 10 minutes writing code versus two hours getting the component to work how you want. |
149,808 | <p>I have several stored procedures in my database that are used to load data from a datamart that is housed in a separate database. These procedures are, generally, in the form:</p>
<pre><code>
CREATE PROCEDURE load_stuff
WITH EXECUTE AS OWNER AS
INSERT INTO my_db.dbo.report_table
(
column_a
)
SELECT
column_b
FROM data_mart.dbo.source_table
WHERE
foo = 'bar';
</code></pre>
<p>These run fine when I execute the query in SQL Server Management Studio. When I try to execute them using EXEC load_stuff, the procedure fails with a security warning:</p>
<p><em>The server principal "the_user" is not able to access the database "data_mart" under the current security context.</em></p>
<p>The OWNER of the sproc is dbo, which is the_user (for the sake of our example). The OWNER of both databases is also the_user and the_user is mapped to dbo (which is what SQL Server should do).</p>
<p>Why would I be seeing this error in SQL Server? Is this because the user in question is being aliased as dbo and I should use a different user account for my cross-database data access?</p>
<p><strong>Edit</strong>
I understand that this is because SQL Server disables cross database ownership chaining by default, which is good. However, I'm not sure of the best practice in this situation. If anyone has any input on the best practice for this scenario, it would be greatly appreciated.</p>
<p><strong>Edit 2</strong>
The eventual solution was to set TRUSTWORTHY ON on both of the databases. This allows for limited ownership chaining between the two databases without resorting to full database ownership chaining.</p>
| [
{
"answer_id": 149984,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>Why not remove EXECUTE AS OWNER?</p>\n\n<p>Usually, my user executing the SP would have appropriate rights in both databases, and I don't have to do that at all.</p>\n"
},
{
"answer_id": 158015,
"author": "matdumsa",
"author_id": 1775,
"author_profile": "https://Stackoverflow.com/users/1775",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, DBO is a role (you can consider it as a group of users), not a user in himself. (Unless you can connect to SQL SERVER using dbo:passwordfordbo it's not a user).</p>\n\n<p>Usually, in the wonderful world of SQL Server, if you grant userX right to execute storedprocY then X gets the right to perform all the task Y contains even if he doesn't have all the permission on all the objects used in Y. </p>\n\n<p>That's an extremely useful feature to encapsulate business logic in a stored procedure. (Your user have NO access on the table but they do can EXECUTE one stored proc).</p>\n\n<p>When we talk about \"ownership chaining\" it means the following (please correct me if I am wrong though)\n - If ownership chaining is disabled: the right to execute procedureX will work as long as all the required objects are in the same database\n - Of chaining is enabled: That \"privilege\" will expands towards all databases.</p>\n\n<p>Hope that helps,</p>\n"
},
{
"answer_id": 5043170,
"author": "Shamik",
"author_id": 623378,
"author_profile": "https://Stackoverflow.com/users/623378",
"pm_score": 1,
"selected": false,
"text": "<p>There is no need to create login, you can just enable guest user in target DB.</p>\n\n<p><strong>grant connect to guest</strong></p>\n\n<p>This allows executing user to enter DB under guest context, and when \"db chaining is ON access will not be checked in target DB.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11780/"
]
| I have several stored procedures in my database that are used to load data from a datamart that is housed in a separate database. These procedures are, generally, in the form:
```
CREATE PROCEDURE load_stuff
WITH EXECUTE AS OWNER AS
INSERT INTO my_db.dbo.report_table
(
column_a
)
SELECT
column_b
FROM data_mart.dbo.source_table
WHERE
foo = 'bar';
```
These run fine when I execute the query in SQL Server Management Studio. When I try to execute them using EXEC load\_stuff, the procedure fails with a security warning:
*The server principal "the\_user" is not able to access the database "data\_mart" under the current security context.*
The OWNER of the sproc is dbo, which is the\_user (for the sake of our example). The OWNER of both databases is also the\_user and the\_user is mapped to dbo (which is what SQL Server should do).
Why would I be seeing this error in SQL Server? Is this because the user in question is being aliased as dbo and I should use a different user account for my cross-database data access?
**Edit**
I understand that this is because SQL Server disables cross database ownership chaining by default, which is good. However, I'm not sure of the best practice in this situation. If anyone has any input on the best practice for this scenario, it would be greatly appreciated.
**Edit 2**
The eventual solution was to set TRUSTWORTHY ON on both of the databases. This allows for limited ownership chaining between the two databases without resorting to full database ownership chaining. | Why not remove EXECUTE AS OWNER?
Usually, my user executing the SP would have appropriate rights in both databases, and I don't have to do that at all. |
149,821 | <p>I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data.</p>
<pre><code> function SendToExcel() {
$.ajax({
type: "GET",
url: "/Search.aspx",
contentType: "application/vnd.ms-excel",
dataType: "text",
data: "{id: '" + "asdf" + "'}",
success: function(data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}});
}
</code></pre>
<p>I don't want to display the data in the browser--I want to send it to Excel.</p>
<p><strong>EDIT:</strong> I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had.</p>
<p>Here's the function I'm calling on the button click:</p>
<pre><code> function SendToExcel() {
var dataString = 'type=excel' +
'&Number=' + $('#txtNumber').val() +
'&Reference=' + $('#txtReference').val()
$("#sltCTPick option").each(function (i) {
dataString = dataString + '&Columns=' + this.value;
});
top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;;
}
</code></pre>
| [
{
"answer_id": 149859,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, and let the browser figure out what to do with it.</p>\n"
},
{
"answer_id": 149890,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 2,
"selected": false,
"text": "<p>Since it uses JavaScript, AJAX is bound by JavaScript's designed limitations, which includes interacting with other processes on the client's machine. In this case, it's a good thing; you wouldn't want a site to be able to automatically load an Excel document with a malicious macro in it.</p>\n\n<p>If you want to display the data in the browser, you can use AJAX; otherwise, you'll want to just give a link to an Excel document and let the browser's regular download handling capabilities figure out what to do.</p>\n"
},
{
"answer_id": 151184,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 0,
"selected": false,
"text": "<p>It's possible that you don't want to do this with javascript.</p>\n\n<p>What I think you want to do is create a response page with the mine type <strong>application/csv</strong> then redirect the user to that page. I would probably do a window.open() since the user doesn't lose the page they're currently on.</p>\n"
},
{
"answer_id": 4455600,
"author": "fernando",
"author_id": 544005,
"author_profile": "https://Stackoverflow.com/users/544005",
"pm_score": 3,
"selected": false,
"text": "<p>in HTML I have a Form with serial inputs elements and a button that calls a JavaScript function <code>onclick=\"exportExcel();</code></p>\n\n<p><hr>\nthen in JavaScript file:</p>\n\n<pre><code>function exportExcel(){\n var inputs = $(\"#myForm\").serialize();\n var url = '/ajaxresponse.php?select=exportExcel&'+inputs;\n location.href = url;\n}\n</code></pre>\n\n<p>and finally a pivot file who response to something</p>\n\n<p>PHP code:</p>\n\n<pre><code>case 'exportExcel':{\n ob_end_clean();\n header(\"Content-type: application/vnd.ms-excel\");\n header(\"Content-Disposition: attachment;\n filename=exportFile.xls\");\n echo $html->List($bd->ResultSet($_GET));\n }\n</code></pre>\n\n<p>$html is an object who handle html, and $bd is an object that returns data from Database\nsend your own html table or whatever you want.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
]
| I have the following function that is pulling data from a database. The ajax call is working correctly. How can I send the tab delimited data in my success function to the user? Setting the contect type to "application/vnd.ms-excel" didn't work. The alert on success shows the correctly formatted data.
```
function SendToExcel() {
$.ajax({
type: "GET",
url: "/Search.aspx",
contentType: "application/vnd.ms-excel",
dataType: "text",
data: "{id: '" + "asdf" + "'}",
success: function(data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}});
}
```
I don't want to display the data in the browser--I want to send it to Excel.
**EDIT:** I found a way to do what I wanted. Instead of redirecting the users to a new page that would prompt them to save/open an Excel file, I opened the page inside a hidden iframe. That way, the users click a button, and they are prompted to save/open an Excel file. No page redirection. Is it Ajax? No, but it solves the real problem I had.
Here's the function I'm calling on the button click:
```
function SendToExcel() {
var dataString = 'type=excel' +
'&Number=' + $('#txtNumber').val() +
'&Reference=' + $('#txtReference').val()
$("#sltCTPick option").each(function (i) {
dataString = dataString + '&Columns=' + this.value;
});
top.iExcelHelper.location.href = "/Reports/JobSearchResults.aspx?" + dataString;;
}
``` | AJAX is... the wrong choice. Redirect the user to a server resource that will send the data down with the proper MIME type, and let the browser figure out what to do with it. |
149,823 | <p>When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event? </p>
<p>Thanks.</p>
| [
{
"answer_id": 150068,
"author": "Brendan Enrick",
"author_id": 22381,
"author_profile": "https://Stackoverflow.com/users/22381",
"pm_score": 0,
"selected": false,
"text": "<p>This article on the MSDN site clearly explains how to go about <a href=\"http://msdn.microsoft.com/en-us/library/aa984252(VS.71).aspx\" rel=\"nofollow noreferrer\">adding a button into a datagrid</a>. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set.</p>\n\n<p>This article shows <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.command.aspx\" rel=\"nofollow noreferrer\">how to use the command event with buttons</a>. In it you use CommandArguments and CommandNames.</p>\n"
},
{
"answer_id": 150165,
"author": "Collin Estes",
"author_id": 20748,
"author_profile": "https://Stackoverflow.com/users/20748",
"pm_score": 0,
"selected": false,
"text": "<p>Here is where I create the datagrid:</p>\n\n<p>System.Web.UI.WebControls.DataGrid Datagridtest = new System.Web.UI.WebControls.DataGrid();</p>\n\n<pre><code> Datagridtest.Width = 600;\n Datagridtest.GridLines = GridLines.Both;\n Datagridtest.CellPadding = 1;\n\n ButtonColumn bc = new ButtonColumn();\n bc.CommandName = \"add\";\n bc.HeaderText = \"Event Details\";\n bc.Text = \"Details\";\n bc.ButtonType = System.Web.UI.WebControls.ButtonColumnType.PushButton;\n Datagridtest.Columns.Add(bc);\n PlaceHolder1.Controls.Add(Datagridtest);\n\n Datagridtest.DataSource = dt;\n Datagridtest.DataBind();\n</code></pre>\n\n<p>And here is the event I am trying to use:</p>\n\n<p>protected void Datagridtest_ItemCommand(object source, DataGridCommandEventArgs e)\n {\n ....\n }</p>\n\n<p>Thought that might help because I can't seem to capture the event at all.</p>\n"
},
{
"answer_id": 150288,
"author": "taco",
"author_id": 5203,
"author_profile": "https://Stackoverflow.com/users/5203",
"pm_score": 3,
"selected": true,
"text": "<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n DataGrid dg = new DataGrid();\n\n dg.GridLines = GridLines.Both;\n\n dg.Columns.Add(new ButtonColumn {\n CommandName = \"add\",\n HeaderText = \"Event Details\",\n Text = \"Details\",\n ButtonType = ButtonColumnType.PushButton\n });\n\n dg.DataSource = getDataTable();\n dg.DataBind();\n\n dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);\n\n pnlMain.Controls.Add(dg);\n}\n\nprotected void dg_ItemCommand(object source, DataGridCommandEventArgs e)\n{\n if (e.CommandName == \"add\")\n {\n throw new Exception(\"add it!\");\n }\n}\n\nprotected DataTable getDataTable()\n{\n // returns your data table\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20748/"
]
| When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn\_click event?
Thanks. | ```
protected void Page_Load(object sender, EventArgs e)
{
DataGrid dg = new DataGrid();
dg.GridLines = GridLines.Both;
dg.Columns.Add(new ButtonColumn {
CommandName = "add",
HeaderText = "Event Details",
Text = "Details",
ButtonType = ButtonColumnType.PushButton
});
dg.DataSource = getDataTable();
dg.DataBind();
dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);
pnlMain.Controls.Add(dg);
}
protected void dg_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "add")
{
throw new Exception("add it!");
}
}
protected DataTable getDataTable()
{
// returns your data table
}
``` |
149,825 | <p>I ran across the following code in <a href="http://www.quietlyscheming.com/blog/" rel="nofollow noreferrer">Ely Greenfield's</a> SuperImage from his Book component - I understand loader.load() but what does the rest of do?</p>
<pre><code>loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));
</code></pre>
<p>It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement?</p>
| [
{
"answer_id": 149847,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 0,
"selected": false,
"text": "<p>this is using the <a href=\"http://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary ?: operator</a>. the first part is the condition, between the ? and : is what to return if the condition is true. after the : is what to return if the condition is false.</p>\n\n<p>a simpler example</p>\n\n<pre><code>String str = null;\nint x = (str != null) ? str.length() : 0;\n</code></pre>\n\n<p>would be the same as </p>\n\n<pre><code>String str = null;\nint x;\nif (str != null)\n x = str.length()\nelse\n x = 0;\n</code></pre>\n"
},
{
"answer_id": 149853,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 1,
"selected": false,
"text": "<p>Basically what it says is: if newsource is a type of URLRequest, then pass the newSource variable into the load method, if its not a type of URLReuqest, create a new URLRequest and pass that into the load method.</p>\n\n<p>The basic syntax is: (condition) ? (code to execute if true) : (code to execute if false)</p>\n"
},
{
"answer_id": 149867,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 5,
"selected": true,
"text": "<p>? is called the 'ternary operator' and it's basic use is:</p>\n\n<pre><code>(expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise);\n</code></pre>\n\n<p>In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource.</p>\n\n<p>The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be:</p>\n\n<pre><code>if (newSource is URLRequest)\n loader.load(newSource);\nelse\n loader.load(new URLRequest(newSource));\n</code></pre>\n"
},
{
"answer_id": 687923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Basically what this means, as far as im aware of, is its asking wheter that variable newSource's class is String or URLRequest like workmad and jason explained. If its an URLRequest it will <strong><em>run loader.load(newSource:URLRequest)</em></strong>. If its not an URLRequest it means automatically that it is a String (in other words the url). And in that case it will run <strong><em>loader.load(new URLrequest(newSource:String)</em></strong>.</p>\n\n<p>The complete code could look something like this:</p>\n\n<pre><code>function myFunction(newSource:Object):SomeClass {\nvar loader:URLLoader = new URLLoader();\nloader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));\n}\n</code></pre>\n\n<p>Regards,</p>\n\n<p>Filipe A.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
]
| I ran across the following code in [Ely Greenfield's](http://www.quietlyscheming.com/blog/) SuperImage from his Book component - I understand loader.load() but what does the rest of do?
```
loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));
```
It looks like some kind of crazy inline if statement but still, I'm a little preplexed. And if it is an if statement - is this way better than a regular if statement? | ? is called the 'ternary operator' and it's basic use is:
```
(expression) ? (evaluate to this if expression is true) : (evaluate to this otherwise);
```
In this case, if newSource is a URLRequest, loader.load will be passed newSource directly, otherwise it will be passed a new URLRequest built from newSource.
The ternary operator is frequently used as a more concise form of if statement as it allows ifs to be inlined. The corresponding code in this case would be:
```
if (newSource is URLRequest)
loader.load(newSource);
else
loader.load(new URLRequest(newSource));
``` |
149,827 | <p>I want to be able to run a text editor from my app, as given by the user in the TEXT_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program?</p>
<p>Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file.</p>
<p>Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason.</p>
| [
{
"answer_id": 149846,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that Mac OS X provides a default application mechanism, so that .txt will open in TextEdit.app or Emacs or GVim or whatever the user has specified. I couldn't find anything online however.</p>\n"
},
{
"answer_id": 149866,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": -1,
"selected": false,
"text": "<p>You could run following command from your application:</p>\n\n<pre><code>open <full path to text file>\n</code></pre>\n\n<p>This will open the text file in the default text editor. You can open any file type using <code>open</code> command.</p>\n"
},
{
"answer_id": 149870,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>I believe hardcoding \"Applications\" will not work if the user's language setting is not English. For example in Norsk the \"Applications\" folder is named \"Programmer\".</p>\n\n<p>The Apple document on internationalization is <A HREF=\"http://developer.apple.com/documentation/MacOSX/Conceptual/BPInternational/BPInternational.pdf\" rel=\"nofollow noreferrer\">here</A>. Starting on page 45 is a section on handling localized path names. </p>\n"
},
{
"answer_id": 149915,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>Mac OS X has a mechanism called \"uniform type identifiers\" that it uses to track associations between data types and applications that can handle them. The subsystem that manages this is Launch Services. You can do one of two things:</p>\n\n<ul>\n<li><p>If you have a file with a reasonably well-known path extension, e.g. <code>.txt</code>, you can just ask <code>NSWorkspace</code> to open the file in the appropriate application.</p></li>\n<li><p>If you don't have a well-known path extension, but you know the type of data, you can ask Launch Services to look up the default application for that type, and then ask <code>NSWorkspace</code> to open the file in that specific application.</p></li>\n</ul>\n\n<p>If you do it this way you'll get the same behavior as the Finder, and you won't have to fork()/exec() or use system() just to open a file.</p>\n"
},
{
"answer_id": 151007,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 3,
"selected": true,
"text": "<p>In your second edit it makes it sound like you just want to get the path to TextEdit, this can be done easily by using NSWorkspace method absolutePathForAppBundleWithIdentifier:</p>\n\n<pre><code>NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@\"com.apple.TextEdit\"];\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
]
| I want to be able to run a text editor from my app, as given by the user in the TEXT\_EDITOR environment variable. Now, assuming there is nothing in that variable, I want to default to the TextEdit program that ships with OSX. Is it kosher to hardcode /Applications/TextEdit.app/Contents/MacOS/TextEdit into my app, or is there a better way to call the program?
Edit: For the record, I am limited to running a specific application path, in C. I'm not opening a path to a text file.
Edit 2: Seriously people, I'm not opening a file here. I'm asking about an application path for a reason. | In your second edit it makes it sound like you just want to get the path to TextEdit, this can be done easily by using NSWorkspace method absolutePathForAppBundleWithIdentifier:
```
NSString *path = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.TextEdit"];
``` |
149,844 | <p>I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.</p>
<p>As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.</p>
<p>An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an <em>undesirable</em> solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.</p>
<p>As an example: </p>
<pre><code><div id="twitter_div">
<h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=1"></script>
</ul>
</div>
</code></pre>
<p>Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 150071,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right?</p>\n\n<p>You'd just need to make sure your document writing happens before the javascript for your various badges.</p>\n\n<p>Could you give a specific example of the HTML / link to a page with the invalid code?</p>\n"
},
{
"answer_id": 150099,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>At some point the page becomes valid, right? That's the only time it can really be validated.</p>\n\n<p>I'm not sure a non-trivial page will remain valid at every point during its construction if it's constructed with a lot of DOM scripting.</p>\n"
},
{
"answer_id": 150128,
"author": "rfunduk",
"author_id": 210,
"author_profile": "https://Stackoverflow.com/users/210",
"pm_score": 0,
"selected": false,
"text": "<p>This might not be the most popular opinion on this topic, but...</p>\n\n<p>Don't worry about 100% validation. It's just not that big of a deal.</p>\n\n<p>The point of validation is to make your markup as standard as possible. Why? Because browsers that are given markup that doesn't conform to the spec (eg, markup that does not validate) do their own error checking to correct it and display the page the way you intended it to look to the user. The quality of the browsers error checking varies, yadda-yadda-yadda, it's better to have valid markup... But it's not even your code that's causing the validation to fail! The people who wrote those badges probably tested them in multiple browsers (and you should do the same, of course), if they work as expected then just leave it at that.</p>\n\n<p>In short, there's no prize for validating :)</p>\n"
},
{
"answer_id": 150230,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 4,
"selected": true,
"text": "<p>The following fragment is valid XHTML and does the job:</p>\n\n<pre><code><div id=\"twitter_div\">\n <h2 class=\"twitter-title\"><a href=\"http://twitter.com/stopsineman\" title=\"Tim's Twitter Page.\">Twitter Updates</a></h2>\n <div id=\"myDiv\" />\n</div> \n\n<script type=\"text/javascript\">\n var placeHolderNode = document.getElementById(\"myDiv\");\n var parentNode = placeHolderNode.parentNode;\n var insertedNode = document.createElement(\"ul\");\n insertedNode .setAttribute(\"id\", \"twitter_update_list\");\n parentNode.insertBefore( insertedNode, placeHolderNode);\n parentNode.remove(placeHolderNode);\n</script>\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&amp;count=5\"></script>\n</code></pre>\n"
},
{
"answer_id": 150262,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 2,
"selected": false,
"text": "<p>The solutions might be different for each badge. In Twitter's case, you can just write your own callback function. Here's an example based on their badge code:</p>\n\n<pre><code><div id=\"twitter_div\">\n <h2><a href=\"http://twitter.com/stopsineman\">@Twitter</a></h2>\n <div id=\"twitter_update_list\"></div>\n</div>\n\n<script type=\"text/javascript\">\nfunction updateTwitterCallback(obj)\n{\n var twitters = obj;\n var statusHTML = \"\";\n var username = \"\";\n for (var i = 0; i < twitters.length; i++)\n {\n username = twitters[i].user.screen_name;\n statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style=\"font-size:85%\" href=\"http://twitter.com/' + username + '/statuses/' + twitters[i].id + '\">' + relative_time(twitters[i].created_at) + '</a></li>');\n }\n document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>';\n}\n</script>\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&amp;count=1\"></script>\n</code></pre>\n"
},
{
"answer_id": 3030592,
"author": "Markus",
"author_id": 365455,
"author_profile": "https://Stackoverflow.com/users/365455",
"pm_score": 1,
"selected": false,
"text": "<p>I put a <li> with \"display:none\" in the <ul> Tag:</p>\n\n<pre><code><ul id=\"twitter_update_list\"><li style=\"display:none;\">A</li></ul>\n\n<script type=\"text/javascript\" src=\"http://twitter.com/javascripts/blogger.js\"></script>\n<script type=\"text/javascript\" src=\"http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&amp;count=1\"></script>\n</code></pre>\n\n<p>This does not disturb the script and in this case it works,\nand I think its not a \"<em>undesirable</em> solution\" :)</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16562/"
]
| I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.
As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.
An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an *undesirable* solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.
As an example:
```
<div id="twitter_div">
<h2><a href="http://twitter.com/stopsineman">@Twitter</a></h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=1"></script>
</ul>
</div>
```
Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.
Thanks in advance! | The following fragment is valid XHTML and does the job:
```
<div id="twitter_div">
<h2 class="twitter-title"><a href="http://twitter.com/stopsineman" title="Tim's Twitter Page.">Twitter Updates</a></h2>
<div id="myDiv" />
</div>
<script type="text/javascript">
var placeHolderNode = document.getElementById("myDiv");
var parentNode = placeHolderNode.parentNode;
var insertedNode = document.createElement("ul");
insertedNode .setAttribute("id", "twitter_update_list");
parentNode.insertBefore( insertedNode, placeHolderNode);
parentNode.remove(placeHolderNode);
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=5"></script>
``` |
149,848 | <p>What is a strong way to protect against sql injection for a classic asp app?</p>
<p>FYI I am using it with an access DB. (I didnt write the app)</p>
| [
{
"answer_id": 149854,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 6,
"selected": true,
"text": "<p>Stored Procedures and/or prepared statements:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks\">https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/139199/can-i-protect-against-sql-injection-by-escaping-single-quote-and-surrounding-us\">Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1284/catching-sql-injection-and-other-malicious-web-requests\">Catching SQL Injection and other Malicious Web Requests</a></p>\n\n<p>With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.</p>\n\n<p>Here's a link to the technique in Access:</p>\n\n<p><a href=\"http://www.asp101.com/samples/storedqueries.asp\" rel=\"nofollow noreferrer\">http://www.asp101.com/samples/storedqueries.asp</a></p>\n\n<p>Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.</p>\n\n<p>In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:</p>\n\n<pre><code>Conn.Execute(\"EXEC usp_ImOnlySafeIfYouCallMeRight '\" + param1 + \"', '\" + param2 + \"'\") ;\n</code></pre>\n\n<p>Remember that your database needs to defend its own perimeter, and if various logins have rights to <code>INSERT/UPDATE/DELETE</code> in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)</p>\n"
},
{
"answer_id": 149856,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "<p>Using parametrized querys, you need to create a command object, assign it parameters with a name and a value, if you do so you wouldn't need to worry about anything else (refering to sql injection of course ;))</p>\n\n<p><a href=\"http://prepared-statement.blogspot.com/2006/02/asp-prepared-statements.html\" rel=\"nofollow noreferrer\">http://prepared-statement.blogspot.com/2006/02/asp-prepared-statements.html</a></p>\n\n<p>And don't trust stored procedures, they can became a attack vector too if you don't use prepared statements.</p>\n"
},
{
"answer_id": 150323,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>if stored procedures are not an option - and even if they are - <strong>validate all inputs thoroughly</strong></p>\n"
},
{
"answer_id": 150338,
"author": "Brendan Enrick",
"author_id": 22381,
"author_profile": "https://Stackoverflow.com/users/22381",
"pm_score": -1,
"selected": false,
"text": "<p>Switching to SQL Express at the very least is a great option. It will make things much more secure. Even though using parameters and Stored Procedures can help greatly. I also recommend that you validate the inputs carefully to be sure they match what you're expecting.</p>\n\n<p>For values like numbers it is fairly easy to extract the number to verify that it is indeed just a number. Escape all special characters for SQL. Doing this will prevent the attempted attack from working. </p>\n"
},
{
"answer_id": 170901,
"author": "AnonJr",
"author_id": 25163,
"author_profile": "https://Stackoverflow.com/users/25163",
"pm_score": 2,
"selected": false,
"text": "<p>\"A strong way to protect against sql injection for a classic asp app\" is to ruthlessly validate all input. Period.</p>\n\n<p>Stored procedures alone and/or a different database system do not necessarily equal good security. </p>\n\n<p>MS recently put out a SQL Injection Inspection tool that looks for unvalidated input that is used in a query. THAT is what you should be looking for.</p>\n\n<p>Here's the link:\n<a href=\"http://support.microsoft.com/kb/954476\" rel=\"nofollow noreferrer\">The Microsoft Source Code Analyzer for SQL Injection tool is available to find SQL injection vulnerabilities in ASP code</a></p>\n"
},
{
"answer_id": 1158295,
"author": "BigJump",
"author_id": 8542,
"author_profile": "https://Stackoverflow.com/users/8542",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://support.microsoft.com/kb/954476\" rel=\"nofollow noreferrer\">Microsoft Source Code Analyzer for SQL Injection tool</a> is available to find SQL injection vulnerabilities in ASP code</p>\n"
},
{
"answer_id": 5071692,
"author": "alexsts",
"author_id": 552446,
"author_profile": "https://Stackoverflow.com/users/552446",
"pm_score": 1,
"selected": false,
"text": "<p>Hey, any database as good as developer who uses it. </p>\n\n<p>Nothing more but nothing less.</p>\n\n<p>If you are good developer you can build e-commerce site using text files as a database. \nYes it will not be as good as Oracle driven website but it will do just fine for small business like home based, custom jewelry manufacturing.</p>\n\n<p>And if you are good developer you will not use inline SQL statements on your ASP pages.\nEven in Access you have option to build and use queries..</p>\n\n<p>Store procs with data verification, along with html encode -- is the best way to prevent any SQL Injection attacks.</p>\n"
},
{
"answer_id": 6995837,
"author": "Plippie",
"author_id": 344117,
"author_profile": "https://Stackoverflow.com/users/344117",
"pm_score": 4,
"selected": false,
"text": "<p>Here are a couple of sqlinject scripts I made a long time ago a simple version and a extended version:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>function SQLInject(strWords) \ndim badChars, newChars, i\nbadChars = array(\"select\", \"drop\", \";\", \"--\", \"insert\", \"delete\", \"xp_\") \nnewChars = strWords \nfor i = 0 to uBound(badChars) \nnewChars = replace(newChars, badChars(i), \"\") \nnext \nnewChars = newChars \nnewChars= replace(newChars, \"'\", \"''\")\nnewChars= replace(newChars, \" \", \"\")\nnewChars= replace(newChars, \"'\", \"|\")\nnewChars= replace(newChars, \"|\", \"''\")\nnewChars= replace(newChars, \"\\\"\"\", \"|\")\nnewChars= replace(newChars, \"|\", \"''\")\nSQLInject=newChars\nend function \n\n\nfunction SQLInject2(strWords)\ndim badChars, newChars, tmpChars, regEx, i\nbadChars = array( _\n\"select(.*)(from|with|by){1}\", \"insert(.*)(into|values){1}\", \"update(.*)set\", \"delete(.*)(from|with){1}\", _\n\"drop(.*)(from|aggre|role|assem|key|cert|cont|credential|data|endpoint|event|f ulltext|function|index|login|type|schema|procedure|que|remote|role|route|sign| stat|syno|table|trigger|user|view|xml){1}\", _\n\"alter(.*)(application|assem|key|author|cert|credential|data|endpoint|fulltext |function|index|login|type|schema|procedure|que|remote|role|route|serv|table|u ser|view|xml){1}\", _\n\"xp_\", \"sp_\", \"restore\\s\", \"grant\\s\", \"revoke\\s\", _\n\"dbcc\", \"dump\", \"use\\s\", \"set\\s\", \"truncate\\s\", \"backup\\s\", _\n\"load\\s\", \"save\\s\", \"shutdown\", \"cast(.*)\\(\", \"convert(.*)\\(\", \"execute\\s\", _\n\"updatetext\", \"writetext\", \"reconfigure\", _\n\"/\\*\", \"\\*/\", \";\", \"\\-\\-\", \"\\[\", \"\\]\", \"char(.*)\\(\", \"nchar(.*)\\(\") \nnewChars = strWords\nfor i = 0 to uBound(badChars)\nSet regEx = New RegExp\nregEx.Pattern = badChars(i)\nregEx.IgnoreCase = True\nregEx.Global = True\nnewChars = regEx.Replace(newChars, \"\")\nSet regEx = nothing\nnext\nnewChars = replace(newChars, \"'\", \"''\")\nSqlInject2 = newChars\nend function\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23528/"
]
| What is a strong way to protect against sql injection for a classic asp app?
FYI I am using it with an access DB. (I didnt write the app) | Stored Procedures and/or prepared statements:
<https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks>
[Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?](https://stackoverflow.com/questions/139199/can-i-protect-against-sql-injection-by-escaping-single-quote-and-surrounding-us)
[Catching SQL Injection and other Malicious Web Requests](https://stackoverflow.com/questions/1284/catching-sql-injection-and-other-malicious-web-requests)
With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.
Here's a link to the technique in Access:
<http://www.asp101.com/samples/storedqueries.asp>
Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic. Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code. Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.
In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:
```
Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ;
```
Remember that your database needs to defend its own perimeter, and if various logins have rights to `INSERT/UPDATE/DELETE` in tables, any code in those applications (or compromised applications) can be a potential problem. If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior. (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.) |
149,860 | <p>I have a <code>popen()</code> function which executes <code>tail -f sometextfile</code>. Aslong as there is data in the filestream obviously I can get the data through <code>fgets()</code>. Now, if no new data comes from tail, <code>fgets()</code> hangs. I tried <code>ferror()</code> and <code>feof()</code> to no avail. How can I make sure <code>fgets()</code> doesn't try to read data when nothing new is in the file stream? </p>
<p>One of the suggestion was <code>select()</code>. Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see <a href="https://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example" title="this post">this post</a>).</p>
| [
{
"answer_id": 149875,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 0,
"selected": false,
"text": "<p>I you would use POSIX functions for IO instead of those of C library, you could use <a href=\"http://linux.die.net/man/2/select\" rel=\"nofollow noreferrer\">select</a> or <a href=\"http://linux.die.net/man/2/poll\" rel=\"nofollow noreferrer\">poll</a>.</p>\n"
},
{
"answer_id": 149878,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>You can instead try reading sometextfile using low-level IO functions (open(), read(), etc.), like tail itself does. When there's nothing more to read, read() returns zero, but will still try to read more the next time, unlike FILE* functions.</p>\n"
},
{
"answer_id": 149885,
"author": "Sufian",
"author_id": 9241,
"author_profile": "https://Stackoverflow.com/users/9241",
"pm_score": 4,
"selected": false,
"text": "<p><code>fgets()</code> is a blocking read, it is supposed to wait until data is available if there is no data.</p>\n\n<p>You'll want to perform asynchronous I/O using <code>select()</code>, <code>poll()</code>, or <code>epoll()</code>. And then perform a read from the file descriptor when there is data available.</p>\n\n<p>These functions use the file descriptor of the <code>FILE*</code> handle, retrieved by: <code>int fd = fileno(f);</code></p>\n"
},
{
"answer_id": 149988,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 5,
"selected": false,
"text": "<p>In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. </p>\n\n<pre><code>#include <fcntl.h>\n\nFILE *proc = popen(\"tail -f /tmp/test.txt\", \"r\");\nint fd = fileno(proc);\n\nint flags;\nflags = fcntl(fd, F_GETFL, 0);\nflags |= O_NONBLOCK;\nfcntl(fd, F_SETFL, flags);\n</code></pre>\n\n<p>If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK.</p>\n"
},
{
"answer_id": 157981,
"author": "SinisterDex",
"author_id": 10010,
"author_profile": "https://Stackoverflow.com/users/10010",
"pm_score": 1,
"selected": false,
"text": "<p>i solved my problems by using threads , specifically <a href=\"https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/beginthread-beginthreadex\" rel=\"nofollow noreferrer\"><code>_beginthread</code> , <code>_beginthreadex</code></a>.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010/"
]
| I have a `popen()` function which executes `tail -f sometextfile`. Aslong as there is data in the filestream obviously I can get the data through `fgets()`. Now, if no new data comes from tail, `fgets()` hangs. I tried `ferror()` and `feof()` to no avail. How can I make sure `fgets()` doesn't try to read data when nothing new is in the file stream?
One of the suggestion was `select()`. Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see [this post](https://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example "this post")). | In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking.
```
#include <fcntl.h>
FILE *proc = popen("tail -f /tmp/test.txt", "r");
int fd = fileno(proc);
int flags;
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
```
If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK. |
149,871 | <p>I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube.</p>
<p>The Deliveries information consists of the following tables:</p>
<p><strong>FactDeliveres</strong></p>
<ul>
<li>BranchKey</li>
<li>DeliveryDateKey</li>
<li>ProductKey</li>
<li>InvoiceNumber (DD: degenerate dimension)</li>
<li>Quantity</li>
<li>UnitCosT</li>
<li>Linecost</li>
</ul>
<p><strong>Note:</strong> </p>
<ul>
<li>The granularity of FactDeliveres is each line on the invoice</li>
<li>The Product dimension include supplier information</li>
</ul>
<p><strong>And the problem:</strong> there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery.</p>
<p>In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates.</p>
<p>In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber.</p>
<p>I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. </p>
<p><strong>So, do I:</strong> </p>
<ol>
<li>Use that as the underlying key for the InvoiceNumber dimension?</li>
<li>Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber.</li>
</ol>
<p>After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database</p>
<p><strong>DeliveryHeaders</strong></p>
<ul>
<li>DeliveryID (PK)</li>
<li>DeliveryDate</li>
<li>SupplierID (FK)</li>
<li>InvoiceNumber (typed in manually)</li>
</ul>
<p><strong>DeliveryDetails</strong></p>
<ul>
<li>DeliveryID (PK)</li>
<li>ProductID (PK)</li>
<li>Quantity</li>
<li>UnitCosT</li>
</ul>
| [
{
"answer_id": 149951,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID are degenerate dimensions, because they will change with every fact (or very few facts). It is possible that you could put them in their own dimension if you have a large number of items on each order. The model below may not be 100% correct if you have multiple deliveries on an invoice, but it will be close. Check out Kimball, he might have an example of a star schema for this business scenario.</p>\n\n<pre><code>Fact table:\nOrderDateID (not in your model, but probably should be, date dimension in a role)\nDeliveryDateID (date dimension in a role)\nSupplierID (supplier dimension surrogate key)\nInvoiceID (invoice dimension surrogate key)\nProductID (product dimension surrogate key)\nQuantity (fact)\nUnitCost (fact)\nInvoiceNumber (optional)\nDeliveryID (optional)\n</code></pre>\n\n<p>with the usual date dimension table and the following dimensions:</p>\n\n<pre><code>Supplier Dim:\nSupplierID (surrogate)\nSupplierCode and data\n\nInvoice Dim:\nInvoiceID (surrogate)\nInvoiceNumber (optional)\nDeliveryID (optional)\n\nProduct Dim:\nProductID (surrogate)\nProductCode and Data\n</code></pre>\n\n<p>Always remember, your (star schema) data warehouse is not going to be structured at all like your OLTP data - it's all about the facts and what dimensions describe them.</p>\n"
},
{
"answer_id": 150312,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>Fact table PK's are almost always surrogate keys. Each fact is part of several dimensions, so the fact has FK's to the dimensions, but no real keys of it's own.</p>\n\n<p>A Delivery Fact (a Line Item) belongs to a Branch, it has a Product, it is part of a larger Delivery, it occurs on a particular Date. Sounds like 4 independent dimensions.</p>\n\n<p>The Delivery dimension has it's own PK and it has a dimension attribute of invoice number. Plus, perhaps, other attributes of the delivery as a whole. </p>\n\n<p>Each Delivery Line Item Fact is associated with one Delivery and the invoice number for that Delivery. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279/"
]
| I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube.
The Deliveries information consists of the following tables:
**FactDeliveres**
* BranchKey
* DeliveryDateKey
* ProductKey
* InvoiceNumber (DD: degenerate dimension)
* Quantity
* UnitCosT
* Linecost
**Note:**
* The granularity of FactDeliveres is each line on the invoice
* The Product dimension include supplier information
**And the problem:** there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery.
In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates.
In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber.
I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how.
**So, do I:**
1. Use that as the underlying key for the InvoiceNumber dimension?
2. Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber.
After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database
**DeliveryHeaders**
* DeliveryID (PK)
* DeliveryDate
* SupplierID (FK)
* InvoiceNumber (typed in manually)
**DeliveryDetails**
* DeliveryID (PK)
* ProductID (PK)
* Quantity
* UnitCosT | I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID are degenerate dimensions, because they will change with every fact (or very few facts). It is possible that you could put them in their own dimension if you have a large number of items on each order. The model below may not be 100% correct if you have multiple deliveries on an invoice, but it will be close. Check out Kimball, he might have an example of a star schema for this business scenario.
```
Fact table:
OrderDateID (not in your model, but probably should be, date dimension in a role)
DeliveryDateID (date dimension in a role)
SupplierID (supplier dimension surrogate key)
InvoiceID (invoice dimension surrogate key)
ProductID (product dimension surrogate key)
Quantity (fact)
UnitCost (fact)
InvoiceNumber (optional)
DeliveryID (optional)
```
with the usual date dimension table and the following dimensions:
```
Supplier Dim:
SupplierID (surrogate)
SupplierCode and data
Invoice Dim:
InvoiceID (surrogate)
InvoiceNumber (optional)
DeliveryID (optional)
Product Dim:
ProductID (surrogate)
ProductCode and Data
```
Always remember, your (star schema) data warehouse is not going to be structured at all like your OLTP data - it's all about the facts and what dimensions describe them. |
149,909 | <p>I would like to specify a constraint which is another type with a generic argument.</p>
<pre><code>class KeyFrame<T>
{
public float Time;
public T Value;
}
// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}
</code></pre>
<p>But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:</p>
<pre><code>class Timeline<TKeyframe, TKeyframeValue>
where TKeyframe : Keyframe<TKeyframeValue>,
{
}
</code></pre>
| [
{
"answer_id": 149954,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:</p>\n\n<pre><code>class TimeLine<T>\n{\nprivate IList<KeyFrame<T>> keyFrameList;\n...\n}\n</code></pre>\n\n<p>fulfill your requirements nicely?</p>\n"
},
{
"answer_id": 149997,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 0,
"selected": false,
"text": "<p>If the type T that <code>Timeline<T></code> represents is the same as the type <code>KeyFrame<T></code> represents you can just go with:</p>\n\n<pre><code>class Timeline<T>\n{\n List<KeyFrame<T>> _frames = new List<KeyFrame<T>>(); //Or whatever...\n\n ...\n}\n</code></pre>\n\n<p>If type T represents something different between the classes that implies that <code>Timeline<T></code> can contain multiple types of <code>KeyFrame</code>'s in which case you should create a more abstract implementation of <code>KeyFrame</code> and use that in <code>Timeline<T></code>.</p>\n"
},
{
"answer_id": 150132,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 3,
"selected": true,
"text": "<p>Read about this from <a href=\"http://blogs.msdn.com/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx\" rel=\"nofollow noreferrer\">Eric Lippert's blog</a>\nBasically, you have to find a way to refer to the type you want without specifying the secondary type parameter. </p>\n\n<p>In his post, he shows this example as a possible solution:</p>\n\n<pre><code>public abstract class FooBase\n{\n private FooBase() {} // Not inheritable by anyone else\n public class Foo<U> : FooBase {...generic stuff ...}\n\n ... nongeneric stuff ...\n}\n\npublic class Bar<T> where T: FooBase { ... }\n...\nnew Bar<FooBase.Foo<string>>()\n</code></pre>\n\n<p>Hope that helps, \nTroy</p>\n"
},
{
"answer_id": 3152920,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe nesting <code>Timeline</code> inside <code>KeyFrame</code> would make sense in your design:</p>\n\n<pre><code>class KeyFrame<T> { \n public float Time; \n public T Value; \n\n class Timeline<U> where U : Keyframe<T> { \n } \n} \n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
]
| I would like to specify a constraint which is another type with a generic argument.
```
class KeyFrame<T>
{
public float Time;
public T Value;
}
// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}
```
But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:
```
class Timeline<TKeyframe, TKeyframeValue>
where TKeyframe : Keyframe<TKeyframeValue>,
{
}
``` | Read about this from [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx)
Basically, you have to find a way to refer to the type you want without specifying the secondary type parameter.
In his post, he shows this example as a possible solution:
```
public abstract class FooBase
{
private FooBase() {} // Not inheritable by anyone else
public class Foo<U> : FooBase {...generic stuff ...}
... nongeneric stuff ...
}
public class Bar<T> where T: FooBase { ... }
...
new Bar<FooBase.Foo<string>>()
```
Hope that helps,
Troy |
149,939 | <p>I would like to do something like
<code><test:di id="someService"</code>/`><br>
<%
someService.methodCall();
%></p>
<p>where <code><test:di</code><br>
gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example
<code><jsp:useBean id="someDate" class="java.util.Date"</code>/><br>
<%<br>
someDate.getYear();</p>
<pre><code>%>
</code></pre>
<p>how do i make my own objects available as a scritping variable?</p>
| [
{
"answer_id": 149989,
"author": "zmf",
"author_id": 13285,
"author_profile": "https://Stackoverflow.com/users/13285",
"pm_score": 1,
"selected": false,
"text": "<p>I think you're trying to write your own tag library.</p>\n\n<p>Check out the tutorial at:\n<a href=\"http://www.ironflare.com/docs/tutorials/taglibs/\" rel=\"nofollow noreferrer\">http://www.ironflare.com/docs/tutorials/taglibs/</a></p>\n\n<p>Edit:\nAs Garth pointed out, you want to use the TagExtraInfo class after you've defined your tag lib. \n<a href=\"http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2\" rel=\"nofollow noreferrer\">http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2</a></p>\n"
},
{
"answer_id": 150013,
"author": "Garth Gilmour",
"author_id": 2635682,
"author_profile": "https://Stackoverflow.com/users/2635682",
"pm_score": 3,
"selected": true,
"text": "<p>The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class.</p>\n\n<p>You can find an <a href=\"http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2\" rel=\"nofollow noreferrer\">example here</a>.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
]
| I would like to do something like
`<test:di id="someService"`/`>
<%
someService.methodCall();
%>
where `<test:di`
gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example
`<jsp:useBean id="someDate" class="java.util.Date"`/>
<%
someDate.getYear();
```
%>
```
how do i make my own objects available as a scritping variable? | The way this is done in a Tag Library is by using a Tag Extra Info (TEI) class.
You can find an [example here](http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2). |
149,956 | <p>Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy:</p>
<pre><code>set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)
</code></pre>
| [
{
"answer_id": 149979,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>You may have better luck using the Copy method on a <a href=\"http://msdn.microsoft.com/en-us/library/6973t06a(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>FileSystemObject</code></a>. I've used it for copying, and it's a blocking call.</p>\n"
},
{
"answer_id": 149996,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 4,
"selected": true,
"text": "<pre><code>Do Until zip.Items.Count = Fol.Items.Count\n WScript.Sleep 300\nLoop\n</code></pre>\n\n<p>When the loop finishes your copy is finished.</p>\n\n<p>But if you only want to copy and not zip, FSO or WMI is better.</p>\n\n<p>If you are zipping and want them in a file you have to create the zip-file yourself, with the right header first. Else you only get compressed files/folders IIRC. Something like this:</p>\n\n<pre><code>Set FSO = CreateObject( \"Scripting.FileSystemObject\" )\nSet File = FSO.OpenTextFile( saveFile, 2, True )\nFile.Write \"PK\" & Chr(5) & Chr(6) & String( 18, Chr(0) )\nFile.Close\nSet File = Nothing\nSet FSO = Nothing\n</code></pre>\n\n<p>The 2 in OpenTextFile is ForWriting.</p>\n"
},
{
"answer_id": 28565054,
"author": "user3013626",
"author_id": 3013626,
"author_profile": "https://Stackoverflow.com/users/3013626",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Const FOF_CREATEPROGRESSDLG = &H0&\nConst ForReading = 1, ForWriting = 2, ForAppending = 8\n\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\nstrSource = \" \" ' Source folder path of log files\nstrTarget = \" .zip\" ' backup path where file will be created\n\nAddFilesToZip strSource,strTarget\n\nFunction AddFilesToZip (strSource,strTarget)\nSet r=fso.GetFolder(strSource)\n set file = fso.opentextfile(strTarget,ForWriting,true) \n file.write \"PK\" & chr(5) & chr(6) & string(18,chr(0)) \n file.Close\n Set shl = CreateObject(\"Shell.Application\")\n i = 0\n\n For each f in r.Files\n If fso.GetExtensionName(f) = \"log\" Or fso.GetExtensionName(f) = \"Log\" Or fso.GetExtensionName(f) = \"LOG\" Then\n shl.namespace(strTarget).copyhere(f.Path)', FOF_CREATEPROGRESSDLG \n Do until shl.namespace(strTarget).items.count = i\n wscript.sleep 300\n Loop\n End If\n i = i + 1\n Next\n\n set shl = Nothing\nEnd Function\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14092/"
]
| Does anyone know of a method to determine when a file copy completes in VBScript? I'm using the following to copy:
```
set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)
``` | ```
Do Until zip.Items.Count = Fol.Items.Count
WScript.Sleep 300
Loop
```
When the loop finishes your copy is finished.
But if you only want to copy and not zip, FSO or WMI is better.
If you are zipping and want them in a file you have to create the zip-file yourself, with the right header first. Else you only get compressed files/folders IIRC. Something like this:
```
Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set File = FSO.OpenTextFile( saveFile, 2, True )
File.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) )
File.Close
Set File = Nothing
Set FSO = Nothing
```
The 2 in OpenTextFile is ForWriting. |
149,995 | <p>I have a C++ program representing a TCP header as a struct:</p>
<pre><code>#include "stdafx.h"
/* TCP HEADER
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
typedef struct { // RFC793
WORD wSourcePort;
WORD wDestPort;
DWORD dwSequence;
DWORD dwAcknowledgment;
unsigned int byReserved1:4;
unsigned int byDataOffset:4;
unsigned int fFIN:1;
unsigned int fSYN:1;
unsigned int fRST:1;
unsigned int fPSH:1;
unsigned int fACK:1;
unsigned int fURG:1;
unsigned int byReserved2:2;
unsigned short wWindow;
WORD wChecksum;
WORD wUrgentPointer;
} TCP_HEADER, *PTCP_HEADER;
int _tmain(int argc, _TCHAR* argv[])
{
printf("TCP header length: %d\n", sizeof(TCP_HEADER));
return 0;
}
</code></pre>
<p>If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this?</p>
<p>I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine.</p>
| [
{
"answer_id": 150001,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>Because the compiler is packing your bitfield into a 32-bit int, not a 16-bit entity.</p>\n\n<p>In general you should avoid bitfields and use other manifest constants (enums or whatever) with explicit bit masking and shifting to access the 'sub-fields' in a field.</p>\n\n<p>Here's one reason why bitfields should be avoided - they aren't very portable between compilers even for the same platform. from the C99 standard (there's similar wording in the C90 standard):</p>\n\n<blockquote>\n <p>An implementation may allocate any\n addressable storage unit large enough\n to hold a bitfield. If enough space\n remains, a bit-field that immediately\n follows another bit-field in a\n structure shall be packed into\n adjacent bits of the same unit. If\n insufficient space remains, whether a\n bit-field that does not fit is put\n into the next unit or overlaps\n adjacent units is\n implementation-defined. The order of\n allocation of bit-fields within a unit\n (high-order to low-order or low-order\n to high-order) is\n implementation-defined. The alignment\n of the addressable storage unit is\n unspecified.</p>\n</blockquote>\n\n<p>You cannot guarantee whether a bit field will 'span' an int boundary or not and you can't specify whether a bitfield starts at the low-end of the int or the high end of the int (this is independant of whether the processor is big-endian or little-endian).</p>\n"
},
{
"answer_id": 150002,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>The compiler is padding the non-bitfield struct member to 32-bit -- native word alignment. To fix this, do #pragma pack(0) before the struct and #pragma pack() after.</p>\n"
},
{
"answer_id": 150004,
"author": "Scottie T",
"author_id": 6688,
"author_profile": "https://Stackoverflow.com/users/6688",
"pm_score": 0,
"selected": false,
"text": "<p>Struct boundaries in memory can be padded by the compiler depending on the size and order of fields.</p>\n"
},
{
"answer_id": 150008,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "<p>Not a C/C++ expert when it comes to packing. But I imagine there is a rule in the spec which says that when a non-bitfield follows a bitfield it must be aligned on the word boundary regardless of whether or not it fits in the remaining space. By making it an explicit bitvector you are avoiding this problem.</p>\n\n<p>Again this is speculation with a touch of experience. </p>\n"
},
{
"answer_id": 150009,
"author": "andy",
"author_id": 21482,
"author_profile": "https://Stackoverflow.com/users/21482",
"pm_score": 3,
"selected": true,
"text": "<p>See this question: <a href=\"https://stackoverflow.com/questions/119123/why-does-the-sizeof-operator-return-a-size-larger-for-a-structure-than-the-tota\">Why isn't sizeof for a struct equal to the sum of sizeof of each member?</a> .</p>\n\n<p>I believe that compiler takes a hint to disable padding when you use the \"unsigned int wWindow:16\" syntax.</p>\n\n<p>Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int.</p>\n"
},
{
"answer_id": 150012,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting - I would think that \"WORD\" would evaluate to \"unsigned short\", so you'd have that problem in more than one place.</p>\n\n<p>Also be aware that you'll need to deal with endian issues in any value over 8 bits.</p>\n"
},
{
"answer_id": 150030,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 0,
"selected": false,
"text": "<p>You are seeing different values because of compiler packing rules. You can see rules specific to visual studio <a href=\"http://msdn.microsoft.com/en-us/library/1d48zaa8.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>When you have a structure that must be packed (or adhere to some specific alignment requirements), you should use the #pragma pack() option. For your code, you can use #pragma pack(0) which will align all structure members on byte boundaries. You can then use #pragma pack() to reset structure packing to it's default state. You can see more information on the pack pragma <a href=\"http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 150224,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Your series of \"unsigned int:xx\" bitfields use up only 16 of the 32 bits in an int. The other 16 bits (2 bytes) are there, but unused. This is followed by the unsigned short, which is on an int boundary, and then a WORD, which is along aligned on an int boundary which means that there 2 bytes of padding between them.</p>\n\n<p>When you switch to \"unsigned int wWindow:16\", instead of being a separate short, the compiler uses the unused parts of the previous bitfield, so no waste, no short, and no padding after the short, hence you save four bytes.</p>\n"
},
{
"answer_id": 150621,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think Mike B got it right, but but not perfectly clear. When you ask for \"short\", it's aligned on 32bit boundary. When you ask for int:16, it's not. So int:16 fits right after th ebit fields, while short skips 2 bytes and starts at the next 32-bit block.</p>\n\n<p>The rest of what he is saying is perfectly applicable - the bit field must never be used to code an externally-visible structure, because there are no guarantee as to how they are allocated. At best, they belong in embedded programs where saving a byte is important. And even there, you can't use them to actually controly bits in memory-mapped ports.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/149995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a C++ program representing a TCP header as a struct:
```
#include "stdafx.h"
/* TCP HEADER
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Source Port | Destination Port |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Sequence Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Acknowledgment Number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Data | |U|A|P|R|S|F| |
| Offset| Reserved |R|C|S|S|Y|I| Window |
| | |G|K|H|T|N|N| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | Urgent Pointer |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Options | Padding |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
typedef struct { // RFC793
WORD wSourcePort;
WORD wDestPort;
DWORD dwSequence;
DWORD dwAcknowledgment;
unsigned int byReserved1:4;
unsigned int byDataOffset:4;
unsigned int fFIN:1;
unsigned int fSYN:1;
unsigned int fRST:1;
unsigned int fPSH:1;
unsigned int fACK:1;
unsigned int fURG:1;
unsigned int byReserved2:2;
unsigned short wWindow;
WORD wChecksum;
WORD wUrgentPointer;
} TCP_HEADER, *PTCP_HEADER;
int _tmain(int argc, _TCHAR* argv[])
{
printf("TCP header length: %d\n", sizeof(TCP_HEADER));
return 0;
}
```
If I run this program I get the size of this header as 24 bytes, which is not the size I was expecting. If I change the type of the field "wWindow" to "unsigned int wWindow:16", which has the same number of bits as an unsigned short, the program tells me the size of the struct is now 20 bytes, the correct size. Why is this?
I am using Microsoft Visual Studio 2005 with SP1 on a 32-bit x86 machine. | See this question: [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-does-the-sizeof-operator-return-a-size-larger-for-a-structure-than-the-tota) .
I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" syntax.
Also, note that a short is not guaranteed to be 16 bits. The guarantee is that: 16 bits <= size of a short <= size of an int. |
150,010 | <p>I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with.</p>
<p>I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form.</p>
<p>I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form:
</p>
<pre><code>Public Class DeptPicker
Private m_TargetResult As String
Public Sub New(ByRef TargetResult As String)
InitializeComponent()
' This works just fine, my "parent" form has the reference value properly updated.
TargetResult = "Booyah!"
' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent
m_TargetResult = TargetResult
End Sub
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
DialogResult = Windows.Forms.DialogResult.OK
' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want.
m_TargetResult = "That department I selected."
Me.Close()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
End Class
</code></pre>
<p>Can somebody tell me what I'm missing here or a different approach to make this happen?</p>
<p><em>Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D</em></p>
| [
{
"answer_id": 150021,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 3,
"selected": true,
"text": "<p>In such cases, I usually either</p>\n\n<ul>\n<li>Write a ShowDialog function that does what I want (e.g. return the value) or</li>\n<li>Just let the result be a property in the dialog. This is how the common file dialogs do it in the BCL. The caller must then read the property to get the result. That's fine in my opinion.</li>\n</ul>\n\n<p>You can also combine these methods, by making the result value a property in the dialog and creating a ShowDialog method that returns that property value, either as ByRef as you want or as a return value, depending on your needs.</p>\n\n<p>I'll add this as a usage instruction, for example (sorry, no VB over here, and you said C# is welcome):</p>\n\n<pre><code>using (var dlg = new DeptPicker()) {\n if (dlg.ShowDialog() == DialogResult.OK) {\n myTextBoxOrWhatEver.Text = dlg.TargetResult;\n }\n}\n</code></pre>\n\n<p>In the dialog itself, just do this:</p>\n\n<pre><code>void okButton_Click(object sender, EventArgs e)\n{\n TargetResult = whatever; // can also do this when the selection changes\n DialogResult = DialogResult.OK;\n Close();\n}\n</code></pre>\n\n<p>I didn't use the new ShowDialog implementation in this sample though.</p>\n"
},
{
"answer_id": 150024,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that assigning TargetResult in the constructor is using the string as a reference. The m_TargetResult string is just a copy of the ref string, not a reference to the original string.</p>\n\n<p>As for how to make a \"pointer\" to the original, I don't know.</p>\n\n<p>This is made even harder by the fact that VB.NET doesn't support unsafe code blocks, so you can't make a pointer reference to the string.</p>\n"
},
{
"answer_id": 150199,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>You could pass the textbox reference to the modal form.</p>\n\n<p>Let the user choose any department. When user clicks OK, set the referred textbox's text property to chosen department's text or id (depends on what you need)</p>\n\n<p>I am using the code provided by you.</p>\n\n<pre>\n<code>\nPublic Class DeptPicker\n\n Private m_TargetTextBox As TextBox\n\n Public Sub New(ByRef TargetTextBox As TextBox)\n InitializeComponent()\n\n m_TargetTextBox = TargetTextBox\n\n End Sub\n\n Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click\n\n DialogResult = Windows.Forms.DialogResult.OK\n\n ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want.\n m_TargetTextBox.Text = \"That department I selected.\"\n Me.Close()\n\n End Sub\n\n Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click\n\n DialogResult = Windows.Forms.DialogResult.Cancel\n Me.Close()\n\n End Sub\n\nEnd Class\n</code>\n</pre>\n"
},
{
"answer_id": 150693,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<pre>\n<code>\nPublic Class DeptPicker\n\n dim dlgResult as DialogResult\n\n Public Function GetSelectedDepartment() As String\n Me.Show vbModal\n If (dlgResult = Windows.Forms.DialogResult.OK) Then\n return \"selected department string here\"\n Else\n return \"sorry, you didnt canceled on the form\"\n End If\n End Function\n\n Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click\n dlgResult = Windows.Forms.DialogResult.OK\n Me.Close()\n End Sub\n\n Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click\n dlgResult = Windows.Forms.DialogResult.Cancel\n Me.Close()\n End Sub\nEnd Class\n</code>\n</pre>\n\n<p>Note: I haven't tested this. I hope you get idea of what I mean.</p>\n\n<p>OregonGhost: Does this look better?</p>\n\n<p>The user can call new DeptPicker().GetSelectedDepartment().\nI didnt know that I need not post the answer again & could use the same post.</p>\n\n<p>Thanks OregonGhost. Now, does it look ok?</p>\n"
},
{
"answer_id": 154398,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This may work:</p>\n\n<pre><code> // This code in your dialog form. Hide the base showdialog method \n // and implement your own versions\n public new string ShowDialog() {\n return this.ShowDialog(null);\n }\n\n public new string ShowDialog(IWin32Window owner) {\n // Call the base implementation of show dialog\n base.ShowDialog(owner);\n\n // You get here after the close button is clicked and the form is hidden. Capture the data you want.\n string s = this.someControl.Text;\n\n // Now really close the form and return the value\n this.Close();\n return s;\n }\n\n // On close, just hide. Close in the show dialog method\n private void closeButton_Click(object sender, EventArgs e) {\n this.Hide();\n }\n\n // This code in your calling form\n MyCustomForm f = new MyCustomForm();\n string myAnswer = f.ShowDialog();\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
]
| I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with.
I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form.
I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form:
```
Public Class DeptPicker
Private m_TargetResult As String
Public Sub New(ByRef TargetResult As String)
InitializeComponent()
' This works just fine, my "parent" form has the reference value properly updated.
TargetResult = "Booyah!"
' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent
m_TargetResult = TargetResult
End Sub
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
DialogResult = Windows.Forms.DialogResult.OK
' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want.
m_TargetResult = "That department I selected."
Me.Close()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
DialogResult = Windows.Forms.DialogResult.Cancel
Me.Close()
End Sub
End Class
```
Can somebody tell me what I'm missing here or a different approach to make this happen?
*Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D* | In such cases, I usually either
* Write a ShowDialog function that does what I want (e.g. return the value) or
* Just let the result be a property in the dialog. This is how the common file dialogs do it in the BCL. The caller must then read the property to get the result. That's fine in my opinion.
You can also combine these methods, by making the result value a property in the dialog and creating a ShowDialog method that returns that property value, either as ByRef as you want or as a return value, depending on your needs.
I'll add this as a usage instruction, for example (sorry, no VB over here, and you said C# is welcome):
```
using (var dlg = new DeptPicker()) {
if (dlg.ShowDialog() == DialogResult.OK) {
myTextBoxOrWhatEver.Text = dlg.TargetResult;
}
}
```
In the dialog itself, just do this:
```
void okButton_Click(object sender, EventArgs e)
{
TargetResult = whatever; // can also do this when the selection changes
DialogResult = DialogResult.OK;
Close();
}
```
I didn't use the new ShowDialog implementation in this sample though. |
150,011 | <p>My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like: </p>
<pre><code>writeln(file, exportRealvalue:30); //using excess width of field
....
readln(file, importRealvalue);
</code></pre>
<p>When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it): </p>
<pre><code>-1.23456789012E-0002
-1.23456789034E-0002
</code></pre>
<p>This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this?</p>
<p>This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on.</p>
| [
{
"answer_id": 150180,
"author": "Jon Trauntvein",
"author_id": 19674,
"author_profile": "https://Stackoverflow.com/users/19674",
"pm_score": 0,
"selected": false,
"text": "<p>When using floating point types, you should be aware of the precision limitations on the specified types. A 4 byte IEEE-754 type, for instance, has only about 7.5 significant digits of precision. An eight byte IEEE-754 type has roughly double the number of significant digits. Apparently, the delphi real type has a precision that lies around 11 significant digits. The result of this is that any extra digits of formatting that you specify are likely to be noise that can result in conversions between base 10 formatted values and base 2 floating point values. </p>\n"
},
{
"answer_id": 150265,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 3,
"selected": false,
"text": "<p>You might try switching to <strong>extended</strong> for greater precision. As was pointed out though, floating point numbers only have so many significant digits of precision, so it is still possible to display more digits then are accurately stored, which could result in the behavior you specified.</p>\n<p>From the Delphi help:</p>\n<p>Fundamental Win32 real types</p>\n<pre>\n | Significant | Size in \nType | Range | digits | bytes\n---------+----------------------------------+-------------+----------\nReal | -5.0 x 10^–324 .. 1.7 x 10^308 | 15–16 | 8 \nReal48 | -2.9 x 10^–39 .. 1.7 x 10^38 | 11-12 | 6 \nSingle | -1.5 x 10^–45 .. 3.4 x 10^38 | 7-8 | 4 \nDouble | -5.0 x 10^–324 .. 1.7 x 10^308 | 15-16 | 8 \nExtended | -3.6 x 10^–4951 .. 1.1 x 10^4932 | 10-20 | 10 \nComp | -2^63+1 .. 2^63–1 | 10-20 | 8 \nCurrency | -922337203685477.5808.. | | \n 922337203685477.5807 | 10-20 | 8 \n</pre>\n<blockquote>\n<p><strong>Note</strong>: The six-byte <strong>Real48</strong> type was called <strong>Real</strong> in earlier versions of Object Pascal. If you are recompiling code that uses the older, six-byte Real type in Delphi, you may want to change it to <strong>Real48</strong>. You can also use the {$REALCOMPATIBILITY ON} compiler directive to turn <strong>Real</strong> back into the six-byte type. The following remarks apply to fundamental real types.</p>\n<ul>\n<li><strong>Real48</strong> is maintained for backward compatibility. Since its storage format is not native to the Intel processor architecture, it results in slower performance than other floating-point types.</li>\n<li><strong>Extended</strong> offers greater precision than other real types but is less portable. Be careful using Extended if you are creating data files to share across platforms.</li>\n</ul>\n</blockquote>\n<p>Notice that the range is greater then the significant digits. So you can have a number larger then can be accurately stored. I would recommend rounding to the significant digits to prevent that from happening.</p>\n"
},
{
"answer_id": 150290,
"author": "SteinNorheim",
"author_id": 19220,
"author_profile": "https://Stackoverflow.com/users/19220",
"pm_score": 0,
"selected": false,
"text": "<p>First of all I would try to see if I could get any help from using Str with different arguments or increasing the precision of the types in your app. (Have you tried using Extended?)</p>\n\n<p>As a last resort, (<strong>Warning! Workaround!!</strong>) I'd try saving the customer's string representation along with the binary representation in a sorted list. Before writing back a floating point value I'd see if there already is a matching value in the table, whose string representation is already known and can be used instead. In order to make get this lookup quick, you can sort it on the numeric value and use binary search for finding the best match.</p>\n"
},
{
"answer_id": 150644,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to specify the precision of a real with a WriteLn, use the following:</p>\n\n<pre><code>WriteLn(RealVar:12:3);\n</code></pre>\n\n<p>It outputs the value Realvar with at least 12 positions and a precision of 3.</p>\n"
},
{
"answer_id": 156699,
"author": "Lars Fosdal",
"author_id": 10002,
"author_profile": "https://Stackoverflow.com/users/10002",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on how much processing you need to do, an alternative could be to keep the numbers in BCD format to retain original accuracy.</p>\n"
},
{
"answer_id": 207463,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 0,
"selected": false,
"text": "<p>It's hard to answer this without knowing what type your ExportRealValue and ImportRealValue are. As others have mentioned, the real types all have different precisions. </p>\n\n<p>It's worth noting, contrary to some thought, extended is not always higher precision. Extended is 10-20 significant figures where double is 15-16. As you are having trouble around the tenth sig fig perhaps you are using extended already.</p>\n\n<p>To get more control over the reading and writing you can convert the numbers to and from strings yourself and write them to a file stream. At least that way you don't have to worry if readln and writeln are up to no good behind your back.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
]
| My clients application exports and imports quite a few variables of type real through a text file using writeln and readln. I've tried to increase the width of the fields written so the code looks like:
```
writeln(file, exportRealvalue:30); //using excess width of field
....
readln(file, importRealvalue);
```
When I export and then import and export again and compare the files I get a difference in the last two digits, e.g (might be off on the actual number of digits here but you get it):
```
-1.23456789012E-0002
-1.23456789034E-0002
```
This actually makes a difference in the app so the client wants to know what I can do about it. Now I'm not sure it's only the write/read that does it but I thought I'd throw a quick question out there before I dive into the hey stack again. Do I need to go binary on this?
This is not an app dealing with currency or something, I just write and read the values to/from file. I know floating points are a bit strange sometimes and I thought one of the routines (writeln/readln) may have some funny business going on. | If you want to specify the precision of a real with a WriteLn, use the following:
```
WriteLn(RealVar:12:3);
```
It outputs the value Realvar with at least 12 positions and a precision of 3. |
150,017 | <p>I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly). </p>
<p>As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds.</p>
<p>Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers.</p>
<p>Thanks in advance for any help with this.</p>
<p>Code Sample Below (The Difference in in the first line of the query at the end (fk_source vs. fk _Source):</p>
<pre><code>//Original
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn);
//Rebuilt
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn);
</code></pre>
| [
{
"answer_id": 150029,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 1,
"selected": false,
"text": "<p>Since you are using SQL Server 2005, have you tried with a SqlCommand object instead of the OleDbCommand object?</p>\n"
},
{
"answer_id": 150039,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not seeing a difference in your queries which would affect performance - what about caching or index/statistics changes between runs? The execution plan may have changed due to statistics or index changes.</p>\n\n<p>Regarding the case: Case can matter if the database is set to be case-sensistive, but for both queries to run in a case-sensitive database, there would have to be columns named in both formats - the query parser will obey the case - it won't cause a performance difference.</p>\n"
},
{
"answer_id": 150041,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 0,
"selected": false,
"text": "<p>firstly, are you 100% sure its the query that is going wrong? Check the trace profile in sql server to see how long its taking in the DB.</p>\n\n<p>Secondly, are you getting the same number of results back. The capitalisation should not matter by default in sql server, but it could have been set up differently.</p>\n"
},
{
"answer_id": 150050,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>If I had a query that took \"5+ minutes\", I wouldn't be worried about the 100 milliseconds it takes to match up the case of the string.</p>\n"
},
{
"answer_id": 150154,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 0,
"selected": false,
"text": "<p>thanks for all your answers, I'll respond to each in turn:</p>\n\n<p>1) Russ, I agree that SQLConnection would be better, but unfortunately I do not get to set the type of connection. I just created a small app to test this query, but the query is dynamically created in a much larger application.</p>\n\n<p>2) gbjbaanb, It's not a server issue I think, because I can run both queries from the management studio in about the same time, it only seems to be a problem when run through oledb in .net (1.1 and 2.0). We've run a profiler on it and the trace file confirmed that it took over 5 minutes to complete the query when called this way.</p>\n\n<p>3)Joel Coehoorn, Agreed, but really what I'm trying to get at here is \"why\" because right now we don't know how big this problem is and where it lies.</p>\n\n<p>4)Cade Roux, The difference is very reproduceable, so I don't think it's an issue with index changes or caching since I have run the tests back to back with the same results and that they take about the same time in SQL Server to run.</p>\n"
},
{
"answer_id": 150408,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": true,
"text": "<p>I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries).</p>\n\n<p>Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then I ran the same query with different capitlization and I was surprised to see the procedure count higher.</p>\n\n<p>Try this....</p>\n\n<p>Connect to SQL Server Management Studio.</p>\n\n<pre><code>DBCC MemoryStatus\n\nSelect Columns... From TABLES.... Where....\n\ndbcc MemoryStatus\n\nSelect Columns... From tables.... Where....\n\ndbcc MemoryStatus\n</code></pre>\n\n<p>I think you'll find that the TotalProcs changes when the statement changes (even when the only change is case sensitive). </p>\n\n<p>Updating your statistics may help. That is a rather slow running process, so you may want to run that during a slow period.</p>\n"
},
{
"answer_id": 150966,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to G Mastros for the most complete answer, although in retrospect the update in statistics was suggested by Cade. G Mastos' solution was better suited to my level of SQL Server experience, however.</p>\n\n<p>Thanks for helping everybody! </p>\n\n<p>I'm going to look into why this seemingly innocent difference has such large consequences </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23553/"
]
| I have a query that I'm executing from a .NET application to a SQL Server database and it seems to take quite a while to complete (5+ Minutes). I created a test app in c# to try to see what was talking so long (the query should return quickly).
As I was reconstructing the query by adding in elements to see which portion was taking so long, I ended up reconstructing the query practically verbatim where the only difference was the spaces in the original query and a capitalization difference. This difference returned a result in about 100 milliseconds.
Has anybody seen this before? I'm wondering if there are services turned off in our server (since a coworker has the same problem) or on our computers.
Thanks in advance for any help with this.
Code Sample Below (The Difference in in the first line of the query at the end (fk\_source vs. fk \_Source):
```
//Original
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id = '27038dbb19ed93db011a315297df3b7a'", dbConn);
//Rebuilt
OleDbCommand comm = new OleDbCommand("select min(ctc.serial_no) as MIN_INTERVAL from countstypecode ctc, source s, countstype ct, counts c where ct.value_id=c.value_id and s.c_id=ct.fk_Source and " +
"ct.timeinterval=ctc.typename and ct.timeinterval in ('15min','1h','1day') and c.time_stamp >= CONVERT(datetime,'01-01-2008',105) and c.time_stamp < " +
"CONVERT(datetime,'01-01-2009',105) and s.c_id='27038dbb19ed93db011a315297df3b7a'", dbConn);
``` | I suspect that this is a procedure cache issue. One benefit of stored procedures is that the plan is stored for you, which speeds things up. Unfortunately, it's possible to get a bad plan in the cache (even when using dynamic queries).
Just for fun, I checked my procedure cache, ran an adhoc query, checked again, then I ran the same query with different capitlization and I was surprised to see the procedure count higher.
Try this....
Connect to SQL Server Management Studio.
```
DBCC MemoryStatus
Select Columns... From TABLES.... Where....
dbcc MemoryStatus
Select Columns... From tables.... Where....
dbcc MemoryStatus
```
I think you'll find that the TotalProcs changes when the statement changes (even when the only change is case sensitive).
Updating your statistics may help. That is a rather slow running process, so you may want to run that during a slow period. |
150,032 | <p>We have a Cash flow report which is basically in this structure:</p>
<pre><code>Date |Credit|Debit|balance|
09/29| 20 | 10 | 10 |
09/30| 0 | 10 | 0 |
</code></pre>
<p>The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day.</p>
<p>Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently.</p>
<p>Anyone could give me some possible different solutions? for the problem?</p>
<p>This report is being displayed on a DataGrid.</p>
| [
{
"answer_id": 150064,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>On the code side of things, you've got two relatively easy options, but they both involve iterating through the dataset.</p>\n\n<p>option 1: For loop prior to databinding.\nFor each row in the datatable, add/subtract the credit/debits to the previous row's balance and assign it to the appropriate cell of your datatable.</p>\n\n<p>Option 2: calculate during databinding.\nFirst you'd have a global variable that you could hold your value in. Set it to zero right before the databind. For each item or altitem, add/subtract the credit/debits to the global variable and assign it to the appropriate cell of your datagrid.</p>\n"
},
{
"answer_id": 150574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>This may be too big a change or off the mark for you, but a cash flow report indicates to me that you are probably maintaining, either formally or informally, a general ledger arrangement of some sort. If you are, then maybe I am naive about this but I think you should maintain your general ledger detail as a single table that has a bare minimum number of columns like ID, date, account, source and amount. </p>\n\n<p>All of the data that comes from different tables suggests that there several different kinds of events that are affecting your cash. To me, representing these different kinds of events in their own tables (like accounts receivable or accounts payable or inventory or whatever) makes sense, but the trick is to not have any monetary columns in those other tables. Instead, have them refer to the row in the general ledger detail where that data is recorded. If you enforce this, then the cash flow would always work the same regardless of changes to the other tables.</p>\n\n<p>The balance forward issue still has to be addressed and you have to take into account the number of transactions involved and the responsiveness required of the system but at least you could make a decision about how to handle it one time and not have to make changes as the other parts of your system evolve.</p>\n"
},
{
"answer_id": 153162,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 0,
"selected": false,
"text": "<p>Be aware that this normally means great raise of network traffic, which can reduce the performance of the application as a whole (since you'd have to fetch all this data to process on the client).</p>\n\n<p>An alternative approach is creating a <em>( in what implementation you like)</em> middle layer application which you can send a request and do this processing on the database server or in a separate network segment. </p>\n\n<p>If there is a SP to do this calculation, normally is because it touch <strong>a lot of data</strong> and the objective is to avoid this circulating in the network.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
]
| We have a Cash flow report which is basically in this structure:
```
Date |Credit|Debit|balance|
09/29| 20 | 10 | 10 |
09/30| 0 | 10 | 0 |
```
The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day.
Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently.
Anyone could give me some possible different solutions? for the problem?
This report is being displayed on a DataGrid. | This may be too big a change or off the mark for you, but a cash flow report indicates to me that you are probably maintaining, either formally or informally, a general ledger arrangement of some sort. If you are, then maybe I am naive about this but I think you should maintain your general ledger detail as a single table that has a bare minimum number of columns like ID, date, account, source and amount.
All of the data that comes from different tables suggests that there several different kinds of events that are affecting your cash. To me, representing these different kinds of events in their own tables (like accounts receivable or accounts payable or inventory or whatever) makes sense, but the trick is to not have any monetary columns in those other tables. Instead, have them refer to the row in the general ledger detail where that data is recorded. If you enforce this, then the cash flow would always work the same regardless of changes to the other tables.
The balance forward issue still has to be addressed and you have to take into account the number of transactions involved and the responsiveness required of the system but at least you could make a decision about how to handle it one time and not have to make changes as the other parts of your system evolve. |
150,033 | <p>What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. </p>
| [
{
"answer_id": 150062,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 2,
"selected": false,
"text": "<p>All Unicode-enabled Regex flavours should have a special character class like \\w that match any Unicode letter. Take a look at <a href=\"http://www.regular-expressions.info\" rel=\"nofollow noreferrer\">your specific flavour here</a>.</p>\n"
},
{
"answer_id": 150069,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 3,
"selected": false,
"text": "<p>You do the same way as any other character matching, but you use \\uXXXX where XXXX is the unicode number of the character.</p>\n\n<p>Look at:\n<a href=\"http://unicode.org/charts/charindex.html\" rel=\"noreferrer\">http://unicode.org/charts/charindex.html</a></p>\n\n<p><a href=\"http://unicode.org/charts/\" rel=\"noreferrer\">http://unicode.org/charts/</a></p>\n\n<p><a href=\"http://www.decodeunicode.org/\" rel=\"noreferrer\">http://www.decodeunicode.org/</a></p>\n"
},
{
"answer_id": 150078,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 9,
"selected": true,
"text": "<p>This should do it:</p>\n\n<pre><code>[^\\x00-\\x7F]+\n</code></pre>\n\n<p>It matches any character which is not contained in the <a href=\"http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange\" rel=\"noreferrer\">ASCII character set</a> (0-127, i.e. 0x0 to 0x7F). </p>\n\n<p>You can do the same thing with Unicode:</p>\n\n<pre><code>[^\\u0000-\\u007F]+\n</code></pre>\n\n<p>For unicode you can look at this 2 resources:</p>\n\n<ul>\n<li><a href=\"http://www.unicode.org/charts/\" rel=\"noreferrer\">Code charts</a> list of Unicode ranges </li>\n<li><a href=\"http://kourge.net/projects/regexp-unicode-block\" rel=\"noreferrer\">This tool</a> to create a regex filtered by Unicode block.</li>\n</ul>\n"
},
{
"answer_id": 873600,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>The situation with regexes, Unicode, and Javascript sucks. It's ridiculous that programmers should have to rely on external libraries to recognize that \"Αλφα\" is a word, or even that \"é\" is a letter.</p>\n\n<p>But so it goes. </p>\n\n<p>This guy has written a good library for handling Unicode in Javascript Regexes:</p>\n\n<p><a href=\"http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode\" rel=\"noreferrer\">http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode</a></p>\n\n<p>The Unicode stuff is a plugin to this regex library:</p>\n\n<p><a href=\"http://xregexp.com/\" rel=\"noreferrer\">http://xregexp.com/</a></p>\n\n<p>Here's a post about the Unicode extension:</p>\n\n<p><a href=\"http://blog.stevenlevithan.com/archives/xregexp-unicode-plugin\" rel=\"noreferrer\">http://blog.stevenlevithan.com/archives/xregexp-unicode-plugin</a></p>\n\n<p>And the extension page itself:</p>\n\n<p><a href=\"http://xregexp.com/plugins/\" rel=\"noreferrer\">http://xregexp.com/plugins/</a></p>\n\n<p>Great work but it still bums me out that Javascript is so backwards in this regard.</p>\n\n<p>(He wrote a book for O'Reilly about the topic so it's quite possible that he knows what he's talking about.)</p>\n\n<p>The way he implemented it is by adding tables of characters with certain properties. Then, when you contruct a regex with his library, <code>\\p{charclass}</code> gets replaced with <code>[allthecharactersintheclass]</code>.</p>\n"
},
{
"answer_id": 22075070,
"author": "rjanjic",
"author_id": 1934618,
"author_profile": "https://Stackoverflow.com/users/1934618",
"pm_score": 8,
"selected": false,
"text": "<pre><code>var words_in_text = function (text) {\n var regex = /([\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]+)/g;\n return text.match(regex);\n};\n\nwords_in_text('Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$');\n\n// returns array [\"Düsseldorf\", \"Köln\", \"Москва\", \"北京市\", \"إسرائيل\"]\n</code></pre>\n\n<p>This regex will match all words in the text of any language...</p>\n"
},
{
"answer_id": 35743562,
"author": "Arkadiusz Kałkus",
"author_id": 3775079,
"author_profile": "https://Stackoverflow.com/users/3775079",
"pm_score": 5,
"selected": false,
"text": "<p>The answer given by Jeremy Ruten is great, but I think it's not exactly what Paul Wicks was searching for. If I understand correctly Paul asked about expression to match non-english words like <code>können</code> or <code>móc</code>. Jeremy's regex matches only non-english letters, so there's need for small improvement:</p>\n\n<pre><code>([^\\x00-\\x7F]|\\w)+\n</code></pre>\n\n<p>or</p>\n\n<pre><code>([^\\u0000-\\u007F]|\\w)+\n</code></pre>\n\n<p>This <code>[^\\x00-\\x7F]</code> and this <code>[^\\u0000-\\u007F]</code> parts allow regullar expression to match non-english letters.</p>\n\n<p>This <code>(|)</code> is logical or and <code>\\w</code> is english letter, so <code>([^\\u0000-\\u007F]|\\w)</code> will match single english or non-english letter.</p>\n\n<p><code>+</code> at the end of the expression means it could be repeated, so the whole expression allows all english or non-english letters to match.</p>\n\n<p><a href=\"https://regex101.com/r/iS5jK8/1\" rel=\"noreferrer\">Here</a> you can test the first expression with various strings and <a href=\"https://regex101.com/r/sV8uK9/1\" rel=\"noreferrer\">here</a> is the second.</p>\n"
},
{
"answer_id": 48902765,
"author": "Loilo",
"author_id": 2048874,
"author_profile": "https://Stackoverflow.com/users/2048874",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"https://github.com/tc39/proposal-regexp-unicode-property-escapes\" rel=\"noreferrer\">Unicode Property Escapes</a> are among the features of ES2018.</p>\n<h3>Basic Usage</h3>\n<p>With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression:</p>\n<pre><code>/\\p{Letter}/u\n</code></pre>\n<p>Or with the shorthand, even terser:</p>\n<pre><code>/\\p{L}/u\n</code></pre>\n<h3>Matching Words</h3>\n<p>Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters <em>together</em> with other word-characters like hyphens:</p>\n<pre><code>/[\\p{L}-]/u\n</code></pre>\n<p>Stitching it all together, you could match words of all<sup>[1]</sup> languages with this beautifully short RegEx:</p>\n<pre><code>/[\\p{L}-]+/ug\n</code></pre>\n<p>Example (shamelessly plugged from <a href=\"https://stackoverflow.com/a/22075070/2048874\">the answer above</a>):</p>\n<pre><code>'Düsseldorf, Köln, Москва, 北京市, إسرائيل !@#$'.match(/[\\p{L}-]+/ug)\n\n// ["Düsseldorf", "Köln", "Москва", "北京市", "إسرائيل"]\n</code></pre>\n<blockquote>\n<p><sup><strong>[1]</strong></sup> Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words <em>besides</em> letters and hyphens.</p>\n</blockquote>\n<h3>Browser Support</h3>\n<p>This feature is available <a href=\"https://caniuse.com/#feat=mdn-javascript_builtins_regexp_property_escapes\" rel=\"noreferrer\">in all major evergreen browsers</a>.</p>\n<h3>Transpiling</h3>\n<p>If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called <a href=\"https://github.com/mathiasbynens/regexpu\" rel=\"noreferrer\">regexpu</a>. There's an online demo available <a href=\"https://mothereff.in/regexpu#input=var+regex+%3D+/%5Cp%7BL%7D/u%3B&unicodePropertyEscape=1\" rel=\"noreferrer\">here</a>. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression:</p>\n<pre><code>/(?:[A-Za-z\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDE80-\\uDE9C\\uDEA0-\\uDED0\\uDF00-\\uDF1F\\uDF2D-\\uDF40\\uDF42-\\uDF49\\uDF50-\\uDF75\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF]|\\uD801[\\uDC00-\\uDC9D\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-\\uDD63\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67]|\\uD802[\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC60-\\uDC76\\uDC80-\\uDC9E\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDD00-\\uDD15\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBE\\uDDBF\\uDE00\\uDE10-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE33\\uDE60-\\uDE7C\\uDE80-\\uDE9C\\uDEC0-\\uDEC7\\uDEC9-\\uDEE4\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF60-\\uDF72\\uDF80-\\uDF91]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2]|\\uD804[\\uDC03-\\uDC37\\uDC83-\\uDCAF\\uDCD0-\\uDCE8\\uDD03-\\uDD26\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D])/\n</code></pre>\n<p>If you're using Babel, there's also a regexpu-powered plugin for that (<a href=\"https://github.com/mathiasbynens/babel-plugin-transform-unicode-property-regex\" rel=\"noreferrer\">Babel v6 plugin</a>, <a href=\"https://github.com/babel/babel/tree/master/packages/babel-plugin-proposal-unicode-property-regex\" rel=\"noreferrer\">Babel v7 plugin</a>).</p>\n"
},
{
"answer_id": 62125247,
"author": "Jonathan",
"author_id": 271450,
"author_profile": "https://Stackoverflow.com/users/271450",
"pm_score": 0,
"selected": false,
"text": "<p>I had a problem with <strong>\\p</strong> working as expected, so I just used a different strategy like:</p>\n\n<pre><code>([^\\t]+)\\t\n</code></pre>\n\n<p>Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
]
| What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. | This should do it:
```
[^\x00-\x7F]+
```
It matches any character which is not contained in the [ASCII character set](http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange) (0-127, i.e. 0x0 to 0x7F).
You can do the same thing with Unicode:
```
[^\u0000-\u007F]+
```
For unicode you can look at this 2 resources:
* [Code charts](http://www.unicode.org/charts/) list of Unicode ranges
* [This tool](http://kourge.net/projects/regexp-unicode-block) to create a regex filtered by Unicode block. |
150,038 | <p>I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships.</p>
<p>I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted.</p>
<p>How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset?</p>
<p>Also, how do I wire the relationships together for 2 tables?</p>
<p>The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail)</p>
<p>I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method.</p>
<p>Thank you,
Keith</p>
| [
{
"answer_id": 151255,
"author": "Keith Sirmons",
"author_id": 1048,
"author_profile": "https://Stackoverflow.com/users/1048",
"pm_score": 0,
"selected": false,
"text": "<p>So, What I am doing right now is passing a reference to the DataSet and a reference to the DataRow of the parent into the Save method of the Child Object.</p>\n\n<p>Here is a little code showing the concept of what I am doing.</p>\n\n<pre><code>// some random save event in a gui.cs//\npublic void HandleSaveButtonClick()\n{ parentObject.Save(); }\n\n\n// Save inside the parentObject.cs //\npublic void Save()\n{ \n CustomDataSet dataSet = new CustomDataSet();\n\n ParentObjectTableAdapter parentTableAdapter = new ParentObjectTableAdapter();\n\n DataTable dt = dataSet.ParentTable;\n DataRow newParentDataRow = dt.NewRow();\n newParentDataRow[\"Property1\"] = \"Hello\";\n newParentDataRow[\"Property2\"] = \"World\";\n dt.Rows.Add(newParentDataRow);\n\n parentTableAdapter.Update(dataSet.ParentTable);\n\n //save children\n _child1.Save(dataSet, newParentDataRow)\n\n\n dataSet.AcceptChanges();\n}\n\n//Save inside child1.cs //\npublic void Save(CustomDataSet dataSet, DataRow parentRow)\n{\n\n Child1TableAdapter childTableAdapter= new Child1TableAdapter();\n\n DataTable dt = dataSet.ChildTable;\n\n DataRow dr = dt.NewRow();\n dr.SetParentRow(parentRow);\n dr[\"CProp1\"] = \"Child Property 1\"; \n dt.Rows.Add(dr);\n\n childTableAdapter.Update(dataSet.ChildTable);\n\n}\n</code></pre>\n\n<p>Let me know how this looks. Is this a usable pattern or am I missing something critical? </p>\n\n<p>Thank you,<br>\nKeith</p>\n"
},
{
"answer_id": 237114,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 2,
"selected": false,
"text": "<p>I will not start another debate whether datasets are good or evil. If you continue to use them, here are something to consider:</p>\n\n<ul>\n<li>You need to keep the original dataset and update that, in order to get correct inserts and updates.</li>\n<li>You want your parents to know their children, but not the other way. Banish the ParentTable.</li>\n<li>An Order and its OrderDetails is an aggregate (from Domain Driven Design) and should be considered as a whole. A call to order.Save() should save everything.</li>\n</ul>\n\n<p>Well, that's the theory. How can we do that? One way is to create the following artifacts:</p>\n\n<ul>\n<li>Order</li>\n<li>OrderDetail</li>\n<li>OrderRepository</li>\n<li>OrderMap</li>\n</ul>\n\n<p>The OrderMap is where you manage the Order to Dataset relationships. Internally, it could use a Hashtable or a Dictionary.</p>\n\n<p>The OrderRepository is where you get your Orders from. The repository will get the dataset with all relations from somewhere, build the Order with all its OrderDetails, and store the Order/Dataset relationship in the OrderMap.</p>\n\n<p>The OrderMap must be kept alive as long as the Order is alive.\nThe Order contains all OrderDetails.</p>\n\n<p>Pass the order to the repository and let it save it. The repository will get the dataset from the map, update the Order-table from the order and iterate all order-details to update the OrderDetail-table.</p>\n\n<p>Retrieve and save:</p>\n\n<pre><code>var order = repository.GetOrder(id);\nrepository.Save(order);\n</code></pre>\n\n<p>Inside OrderRepository.GetOrder():</p>\n\n<pre><code>var ds = db.GetOrderAndDetailsBy(id);\nvar order = new Order();\nUpdateOrder(ds, order);\nUpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order.\nmap.Register(ds, order);\n</code></pre>\n\n<p>Inside OrderRepository.Save():</p>\n\n<pre><code>var ds = map.GetDataSetFor(order);\nUpdateFromOrder(ds, order);\nforeach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail);\n</code></pre>\n\n<p>Some final notes:</p>\n\n<ul>\n<li>You can implement the map as a singelton. </li>\n<li>Let the map use weak references. Then any order should be\ngarbage-collected when it should,\nand memory will be freed. </li>\n<li>You need some way to associate an OrderDetail with its table-row</li>\n<li>If you have the slightest possibility to upgrade to .NET 3.5, do it. Linq to Sql or Linq to Entity will remove some of your pain.</li>\n<li>All of this is created out of thin air. I hope it's not too inaccurate.</li>\n</ul>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
]
| I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships.
I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted.
How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset?
Also, how do I wire the relationships together for 2 tables?
The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail)
I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method.
Thank you,
Keith | I will not start another debate whether datasets are good or evil. If you continue to use them, here are something to consider:
* You need to keep the original dataset and update that, in order to get correct inserts and updates.
* You want your parents to know their children, but not the other way. Banish the ParentTable.
* An Order and its OrderDetails is an aggregate (from Domain Driven Design) and should be considered as a whole. A call to order.Save() should save everything.
Well, that's the theory. How can we do that? One way is to create the following artifacts:
* Order
* OrderDetail
* OrderRepository
* OrderMap
The OrderMap is where you manage the Order to Dataset relationships. Internally, it could use a Hashtable or a Dictionary.
The OrderRepository is where you get your Orders from. The repository will get the dataset with all relations from somewhere, build the Order with all its OrderDetails, and store the Order/Dataset relationship in the OrderMap.
The OrderMap must be kept alive as long as the Order is alive.
The Order contains all OrderDetails.
Pass the order to the repository and let it save it. The repository will get the dataset from the map, update the Order-table from the order and iterate all order-details to update the OrderDetail-table.
Retrieve and save:
```
var order = repository.GetOrder(id);
repository.Save(order);
```
Inside OrderRepository.GetOrder():
```
var ds = db.GetOrderAndDetailsBy(id);
var order = new Order();
UpdateOrder(ds, order);
UpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order.
map.Register(ds, order);
```
Inside OrderRepository.Save():
```
var ds = map.GetDataSetFor(order);
UpdateFromOrder(ds, order);
foreach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail);
```
Some final notes:
* You can implement the map as a singelton.
* Let the map use weak references. Then any order should be
garbage-collected when it should,
and memory will be freed.
* You need some way to associate an OrderDetail with its table-row
* If you have the slightest possibility to upgrade to .NET 3.5, do it. Linq to Sql or Linq to Entity will remove some of your pain.
* All of this is created out of thin air. I hope it's not too inaccurate. |
150,042 | <p>I have tried this...</p>
<pre><code>Dim myMatches As String() =
System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b")
</code></pre>
<p>But it is splitting all words, I want an array of words that start with#</p>
<p>Thanks!</p>
| [
{
"answer_id": 150086,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 1,
"selected": false,
"text": "<p>Since you want to include the words in the split you should use something like</p>\n\n<pre><code>\"\\b#\\w+\\b\"\n</code></pre>\n\n<p>This includes the actual word there in the expression. However I'm not sure that's what you want. Could you provide an example of input and the desired output?</p>\n"
},
{
"answer_id": 150087,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 3,
"selected": true,
"text": "<p>This seems to work...</p>\n\n<p>c#</p>\n\n<pre><code>Regex MyRegex = new Regex(\"\\\\#\\\\w+\");\nMatchCollection ms = MyRegex.Matches(InputText);\n</code></pre>\n\n<p>or vb.net</p>\n\n<pre><code>Dim MyRegex as Regex = new Regex(\"\\#\\w+\")\nDim ms as MatchCollection = MyRegex.Matches(InputText)\n</code></pre>\n\n<p>Given input text of...</p>\n\n<p>\"asdfas asdf #asdf asd fas df asd fas #df asd f asdf\"</p>\n\n<p>...this will yield....</p>\n\n<p>\"#asdf\" and \"#df\"</p>\n\n<p>I'll grant you that this does not get you a string Array but the MatchCollection is enumerable and so might be good enough.</p>\n\n<hr>\n\n<p>Additionally, I'll add that I got this through the use of <a href=\"http://www.ultrapico.com/Expresso.htm\" rel=\"nofollow noreferrer\">Expresso</a>. which appears to be free. It was very helpful in producing the c# which I am very poor at. (Ie it did the escaping for me.)\n(If anyone thinks I should remove this pseudo-advert then please comment, but I thought it might be helpful :) Good times )</p>\n"
},
{
"answer_id": 150088,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 1,
"selected": false,
"text": "<p>Using PHP's <a href=\"http://us2.php.net/manual/en/function.preg-match-all.php\" rel=\"nofollow noreferrer\"><code>preg_match_all()</code></a>:</p>\n\n<pre><code>$text = 'Test #string testing #my test #text.';\npreg_match_all('/#[\\S]+/', $text, $matches);\n\necho '<pre>';\nprint_r($matches[0]);\necho '</pre>';\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre>\nArray\n(\n [0] => #string\n [1] => #my\n [2] => #text.\n)\n</pre>\n"
},
{
"answer_id": 150100,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a code in Javascript:</p>\n\n<pre><code>text = \"what #regEx can I use to #split a #string into whole words but only\" \n// what #regEx can I use to #split a #string into whole words but only\"\ntext.match(/#\\w+/g);\n// [#regEx,#split,#string]\n</code></pre>\n"
},
{
"answer_id": 150107,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<p>In Microsoft RegEx flavours, try: <code>\\#:w</code></p>\n\n<p>That worked for me using Find in Visual Studio. I don't know how it will translate into the RegEx class.</p>\n\n<p><strong><em>EDIT</em></strong>: Backslash was swallowed. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6514/"
]
| I have tried this...
```
Dim myMatches As String() =
System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b")
```
But it is splitting all words, I want an array of words that start with#
Thanks! | This seems to work...
c#
```
Regex MyRegex = new Regex("\\#\\w+");
MatchCollection ms = MyRegex.Matches(InputText);
```
or vb.net
```
Dim MyRegex as Regex = new Regex("\#\w+")
Dim ms as MatchCollection = MyRegex.Matches(InputText)
```
Given input text of...
"asdfas asdf #asdf asd fas df asd fas #df asd f asdf"
...this will yield....
"#asdf" and "#df"
I'll grant you that this does not get you a string Array but the MatchCollection is enumerable and so might be good enough.
---
Additionally, I'll add that I got this through the use of [Expresso](http://www.ultrapico.com/Expresso.htm). which appears to be free. It was very helpful in producing the c# which I am very poor at. (Ie it did the escaping for me.)
(If anyone thinks I should remove this pseudo-advert then please comment, but I thought it might be helpful :) Good times ) |
150,044 | <p>I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?</p>
| [
{
"answer_id": 150072,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "<p>Title is actually an attribute on content pages, so you do something like:</p>\n\n<pre><code><%@ Page Language=\"C#\" MasterPageFile=\"~/default.master\" Title=\"My Content Title\" %>\n</code></pre>\n\n<p>on the content page. To get that into a header, on the master page just render the page title:</p>\n\n<pre><code><h1><%= this.Page.Title %></h3>\n</code></pre>\n"
},
{
"answer_id": 150172,
"author": "Ronald Wildenberg",
"author_id": 23562,
"author_profile": "https://Stackoverflow.com/users/23562",
"pm_score": 0,
"selected": false,
"text": "<p>I see that someone has just provided a (far) better answer to this specific problem. You could use the solution below if you have a master page that has the same content in multiple places (excluding the title).</p>\n\n<p>The best solution I can come up with is the following:</p>\n\n<p>Add an <code>asp:Label</code> for the page title and another one for the second position you want the text to appear (use two different id's, for example: <code>pageTitle</code> and <code>sameTitle</code>)</p>\n\n<p>Add a method to your master page:</p>\n\n<pre><code>public void SetPageTitle(string title)\n{\n pageTitle.Text = title;\n sameTitle.Text = title;\n}\n</code></pre>\n\n<p>On your content page, call the master page method. If your content page has a master page, it has a property called <code>Master</code>. You can now call the <code>SetPageTitle</code> method from your content page <code>PageLoad</code> method:</p>\n\n<pre><code>((MyMasterPage) Master).SetPageTitle(\"My content page\");\n</code></pre>\n\n<p>You can also use the <code>MasterType</code> directive in your master page, check <a href=\"http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx\" rel=\"nofollow noreferrer\">here</a> for more info. This way you get a strongly-typed <code>Master</code> property that you do not have to cast:</p>\n\n<pre><code>Master.SetPageTitle(\"My content page\");\n</code></pre>\n\n<p>Regards,<br>\nRonald</p>\n"
},
{
"answer_id": 156073,
"author": "flukus",
"author_id": 407256,
"author_profile": "https://Stackoverflow.com/users/407256",
"pm_score": 0,
"selected": false,
"text": "<p>Also, master pages can have different content tags (with different Id's) which is good if you want pages to potentially alter various parts of the page.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6222/"
]
| I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page? | Title is actually an attribute on content pages, so you do something like:
```
<%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %>
```
on the content page. To get that into a header, on the master page just render the page title:
```
<h1><%= this.Page.Title %></h3>
``` |
150,047 | <p>Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.</p>
<p>Example:</p>
<pre><code>msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV
</code></pre>
<p>I want access to the target words <code>ApplicationDeployment</code> in my .Proj file. </p>
<p>Is there a property I can access? Any clue how to do this?</p>
<p><strong>EDIT:</strong> I do not want to have to also pass in a property to get this.</p>
<p><strong>UPDATE:</strong> This is based on <strong>deployment scripts</strong> using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.</p>
| [
{
"answer_id": 150271,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not sure how to do exactly what you ask, but could you pass that string using the /p option?</p>\n\n<pre><code>msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV;MyValue=ApplicationDeployment\n</code></pre>\n\n<hr>\n\n<p>The only other way I can see to do it is to use a conditional property in each target, and thus establish the first target to be invoked.</p>\n\n<pre><code><Target Name=\"ApplicationDeployment\">\n<PropertyGroup>\n <InvokedTarget Condition=\"'${InvokedTarget}'==''\">ApplicationDeployment</InvokedTarget>\n</PropertyGroup>\n\n...\n</Target>\n</code></pre>\n"
},
{
"answer_id": 150351,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "<p>There's no way to do this (that I am aware of). MSBuild doesn't have a property for the list of targets requested to build.</p>\n\n<p>However, if you find a way, keep in mind that it might not be a single target, but instead a list of targets to build.</p>\n"
},
{
"answer_id": 150738,
"author": "kodefuguru",
"author_id": 18065,
"author_profile": "https://Stackoverflow.com/users/18065",
"pm_score": -1,
"selected": false,
"text": "<p>I'd recommend using a server like CCNET to handle build executions and notification. Sure, you can do things to your MSBuild script to send out notificatioms, but that domain belongs to the build server.</p>\n"
},
{
"answer_id": 153741,
"author": "ferventcoder",
"author_id": 18475,
"author_profile": "https://Stackoverflow.com/users/18475",
"pm_score": 4,
"selected": true,
"text": "<p>I found the answer!</p>\n\n<pre><code><Target Name=\"ApplicationDeployment\" >\n <CreateProperty Value=\"$(MSBuildProjectName) - $(Environment) - Application Deployment Complete\">\n <Output TaskParameter=\"Value\" PropertyName=\"DeploymentCompleteNotifySubject\" />\n </CreateProperty>\n</code></pre>\n\n<p>I would like to give partial credit to apathetic. Not sure how to do that.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18475/"
]
| Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.
Example:
```
msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV
```
I want access to the target words `ApplicationDeployment` in my .Proj file.
Is there a property I can access? Any clue how to do this?
**EDIT:** I do not want to have to also pass in a property to get this.
**UPDATE:** This is based on **deployment scripts** using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into. | I found the answer!
```
<Target Name="ApplicationDeployment" >
<CreateProperty Value="$(MSBuildProjectName) - $(Environment) - Application Deployment Complete">
<Output TaskParameter="Value" PropertyName="DeploymentCompleteNotifySubject" />
</CreateProperty>
```
I would like to give partial credit to apathetic. Not sure how to do that. |
150,053 | <p>How can I limit my post-build events to running only for one type of build?</p>
<p>I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.</p>
| [
{
"answer_id": 150070,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "<p>You can pass the configuration name to the post-build script and check it in there to see if it should run.</p>\n\n<p>Pass the configuration name with <code>$(ConfigurationName)</code>.</p>\n\n<p>Checking it is based on how you are implementing the post-build step -- it will be a command-line argument.</p>\n"
},
{
"answer_id": 150089,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 7,
"selected": false,
"text": "<p>Add your post build event like normal. Then save your project, open it in <a href=\"https://en.wikipedia.org/wiki/Notepad_%28software%29\" rel=\"noreferrer\">Notepad</a> (or your favorite editor), and add condition to the PostBuildEvent property group. Here's an example:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><PropertyGroup Condition=\" '$(Configuration)' == 'Debug' \">\n <PostBuildEvent>start gpedit</PostBuildEvent>\n</PropertyGroup>\n</code></pre>\n"
},
{
"answer_id": 150092,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 11,
"selected": true,
"text": "<p>Pre- and Post-Build Events run as a batch script. You can do a conditional statement on <code>$(ConfigurationName)</code>.</p>\n\n<p>For instance</p>\n\n<pre><code>if $(ConfigurationName) == Debug xcopy something somewhere\n</code></pre>\n"
},
{
"answer_id": 150097,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": -1,
"selected": false,
"text": "<p>Like any project setting, the buildevents can be configured per Configuration. Just select the configuration you want to change in the dropdown of the Property Pages dialog and edit the post build step.</p>\n"
},
{
"answer_id": 1176725,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 7,
"selected": false,
"text": "<p>Alternatively (since the events are put into a batch file and then called), use the following (in the Build event box, not in a batch file):</p>\n\n<pre><code>if $(ConfigurationName) == Debug goto :debug\n\n:release\nsigntool.exe ....\nxcopy ...\n\ngoto :exit\n\n:debug\n' Debug items in here\n\n:exit\n</code></pre>\n\n<p>This way you can have events for any configuration, and still manage it with the macros rather than having to pass them into a batch file, remember that <code>%1</code> is <code>$(OutputPath)</code>, etc.</p>\n"
},
{
"answer_id": 3547790,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 9,
"selected": false,
"text": "<p>FYI, you do not need to use goto. The shell <a href=\"https://ss64.com/nt/if.html\" rel=\"noreferrer\">IF</a> command can be used with round brackets:</p>\n\n<pre><code>if $(ConfigurationName) == Debug (\n copy \"$(TargetDir)myapp.dll\" \"c:\\delivery\\bin\" /y\n copy \"$(TargetDir)myapp.dll.config\" \"c:\\delivery\\bin\" /y\n) ELSE (\n echo \"why, Microsoft, why\".\n)\n</code></pre>\n"
},
{
"answer_id": 13874593,
"author": "mawl",
"author_id": 260865,
"author_profile": "https://Stackoverflow.com/users/260865",
"pm_score": -1,
"selected": false,
"text": "<p>In Visual Studio 2012 you have to use (I think in Visual Studio 2010, too)</p>\n\n<pre><code>if $(Configuration) == Debug xcopy\n</code></pre>\n\n<p><code>$(ConfigurationName)</code> was listed as a macro, but it wasn't assigned.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CWF67.png\" alt=\"Enter image description here\"></p>\n\n<p>Compare: <em><a href=\"https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/c02as0cs(v=vs.110)\" rel=\"nofollow noreferrer\">Macros for Build Commands and Properties</a></em></p>\n"
},
{
"answer_id": 35554802,
"author": "Eric Bole-Feysot",
"author_id": 616274,
"author_profile": "https://Stackoverflow.com/users/616274",
"pm_score": 4,
"selected": false,
"text": "<p>Visual Studio 2015: The correct syntax is (keep it on one line):</p>\n\n<pre><code>if \"$(ConfigurationName)\"==\"My Debug CFG\" ( xcopy \"$(TargetDir)test1.tmp\" \"$(TargetDir)test.xml\" /y) else ( xcopy \"$(TargetDir)test2.tmp\" \"$(TargetDir)test.xml\" /y)\n</code></pre>\n\n<p>No error 255 here.</p>\n"
},
{
"answer_id": 44828684,
"author": "Jaan Marks",
"author_id": 6415166,
"author_profile": "https://Stackoverflow.com/users/6415166",
"pm_score": -1,
"selected": false,
"text": "<p>This works for me in Visual Studio 2015.</p>\n\n<p>I copy all DLL files from a folder located in a library folder on the same level as my solution folder into the targetdirectory of the project being built.</p>\n\n<p>Using a relative path from my project directory and going up the folder structure two steps with..\\..\\lib</p>\n\n<p>MySolutionFolder <br/>\n....MyProject <br/>\nLib</p>\n\n<pre><code>if $(ConfigurationName) == Debug (\nxcopy /Y \"$(ProjectDir)..\\..\\lib\\*.dll\" \"$(TargetDir)\"\n) ELSE (echo \"Not Debug mode, no file copy from lib\")\n</code></pre>\n"
},
{
"answer_id": 59650562,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 5,
"selected": false,
"text": "<p>As of Visual Studio 2019, the modern <code>.csproj</code> format supports adding a condition directly on the <code>Target</code> element:</p>\n\n<pre><code><Target Name=\"PostBuild\" AfterTargets=\"PostBuildEvent\" Condition=\"'$(Configuration)' == 'Debug'\">\n <Exec Command=\"nswag run nswag.json\" />\n</Target>\n</code></pre>\n\n<p>The UI doesn't provide a way to set this up, but it does appear to safely leave the <code>Configuration</code> attribute in place if you make changes via the UI.</p>\n"
},
{
"answer_id": 70988151,
"author": "plcnut",
"author_id": 4770398,
"author_profile": "https://Stackoverflow.com/users/4770398",
"pm_score": 1,
"selected": false,
"text": "<p>I found that I was able to put multiple Conditions in the project file just like this:</p>\n<pre><code> <Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' != 'Debug' AND '$(Configuration)' != 'Release' ">\n <Exec Command="powershell.exe -ExecutionPolicy Unrestricted -NoProfile -NonInteractive -File $(ProjectDir)postBuild.ps1 -ProjectPath $(ProjectPath) -Build $(Configuration)" />\n </Target>\n</code></pre>\n"
},
{
"answer_id": 73445133,
"author": "IAbstract",
"author_id": 210709,
"author_profile": "https://Stackoverflow.com/users/210709",
"pm_score": 2,
"selected": false,
"text": "<p>As of VS 2022, I have found 2 solutions. In my particular case, I want to pack to a different directory depending on <code>Configuration</code>.</p>\n<p><strong>Option 1</strong></p>\n<pre><code><Target Name="PostBuild" AfterTargets="PostBuildEvent">\n <Exec Command="if $(Configuration) == Debug (dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)) else (dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo))" />\n</Target>\n</code></pre>\n<p><strong>Option 2</strong></p>\n<pre><code><Target Name="PostBuild" AfterTargets="PostBuildEvent">\n <Exec Condition="'$(Configuration)' == 'Debug'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo/debug -p:PackageVersion=$(VersionInfo)" />\n <Exec Condition="'$(Configuration)' == 'Release'" Command="dotnet pack --no-build -o ~/../../../../../nuget-repo -p:PackageVersion=$(VersionInfo)" />\n</Target>\n</code></pre>\n<p>I prefer <em>option <strong>2</strong></em>.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3615/"
]
| How can I limit my post-build events to running only for one type of build?
I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode. | Pre- and Post-Build Events run as a batch script. You can do a conditional statement on `$(ConfigurationName)`.
For instance
```
if $(ConfigurationName) == Debug xcopy something somewhere
``` |
150,076 | <p>I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?</p>
<pre><code>require 'rubygems'
require 'activeresource'
class Event < ActiveResource::Base
self.site = "http://localhost:3000"
end
e = Event.create(
:name => "Shortest Event Ever!",
:starts_at => 1.second.ago,
:capacity => 25,
:price => 10.00)
e.destroy
</code></pre>
| [
{
"answer_id": 150109,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 3,
"selected": false,
"text": "<p>By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so conceivably \"drop database A\" could affect database B. Since \"drop database\" is likely to involve heavy reorgainsing of the innodb data files, it's conceivable that it's a blocking operation, either because of the intensity of the operation, or by design.</p>\n\n<p>However, I think you can make each database use different physical files, although I haven't tried that myself, so you'll have to figure out the specifics for yourself. Failing that, then you may need to use two different mysql installs side-by-side on the same machine, which is perfectly doable.</p>\n"
},
{
"answer_id": 150763,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "<p>Following off of skaffman:</p>\n\n<p>Change your my.cnf (and restart MySQL) to include:</p>\n\n<pre><code>innodb_file_per_table = 1\n</code></pre>\n\n<p>(<a href=\"http://mysqldba.blogspot.com/2006/12/innodbfilepertable.html\" rel=\"noreferrer\">http://mysqldba.blogspot.com/2006/12/innodbfilepertable.html</a>)</p>\n\n<p>This will give your databases dedicated file storage and take it out of the shared pool. It will then let you do fun things like place the tables/indexes on different physical disks to even further split up I/O and improve performance.</p>\n\n<p>Note this doesn't change existing tables; you'll have to do work to get 'em in their own file (<a href=\"http://capttofu.livejournal.com/11791.html\" rel=\"noreferrer\">http://capttofu.livejournal.com/11791.html</a>).</p>\n"
},
{
"answer_id": 1350520,
"author": "Morgan Tocker",
"author_id": 165234,
"author_profile": "https://Stackoverflow.com/users/165234",
"pm_score": 5,
"selected": true,
"text": "<p>So I'm not sure <a href=\"https://stackoverflow.com/a/150763\">Matt Rogish's answer</a> is going to help 100%.</p>\n\n<p>The problem is that MySQL* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, <em>no</em> other tables can be opened.</p>\n\n<p>This is described by a colleague of mine here:\n<a href=\"http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/\" rel=\"nofollow noreferrer\">http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/</a></p>\n\n<p>One excellent impact reduction strategy is to use a filesystem like XFS.</p>\n\n<p>The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above).</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219658/"
]
| I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?
```
require 'rubygems'
require 'activeresource'
class Event < ActiveResource::Base
self.site = "http://localhost:3000"
end
e = Event.create(
:name => "Shortest Event Ever!",
:starts_at => 1.second.ago,
:capacity => 25,
:price => 10.00)
e.destroy
``` | So I'm not sure [Matt Rogish's answer](https://stackoverflow.com/a/150763) is going to help 100%.
The problem is that MySQL\* has a mutex (mutually exclusive lock) around opening and closing tables, so that basically means that if a table is in the process of being closed/deleted, *no* other tables can be opened.
This is described by a colleague of mine here:
<http://www.mysqlperformanceblog.com/2009/06/16/slow-drop-table/>
One excellent impact reduction strategy is to use a filesystem like XFS.
The workaround is ugly. You essentially have to nibble away at all the data in the tables before dropping them (see comment #11 on the link above). |
150,084 | <p>I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". </p>
<p>Is there a way to do this without copying all of the records in the DataTable into the XDocument?</p>
<p>I'm using .Net 3.5</p>
| [
{
"answer_id": 150117,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking for something similar to what I asked regarding <a href=\"https://stackoverflow.com/questions/142010/can-xpath-do-a-foreign-key-lookup-across-two-subtrees-of-an-xml\">XPath foreign keys</a>?</p>\n"
},
{
"answer_id": 150689,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "<p>As the XPath recommendation says, \"The primary purpose of XPath is to address parts of an XML document.\" It doesn't have any facility for addressing parts of more than one XML document. You'll have to build a single XML document if you want to do what you're trying to do.</p>\n"
},
{
"answer_id": 150757,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": -1,
"selected": false,
"text": "<p>You would have to merge your documents, or at lest perform the same transformations on all of your documents. You may consider moving your documents to a single DataTable, then filtering the DataTable if the XPath / XSLT is not do-able.</p>\n"
},
{
"answer_id": 172752,
"author": "Oliver Hallam",
"author_id": 19995,
"author_profile": "https://Stackoverflow.com/users/19995",
"pm_score": 1,
"selected": false,
"text": "<p>.NETs XPath stuff operates on the IXPathNavigable interface. Every IXPathNavigable has a CreateNavigator() method that returns an IXPathNavigator. </p>\n\n<p>In order to expose all of your data sources as one large document you would need to create a class implementing IXPathNavigable, containing all the xpath data sources. The CreateNavigator method should return a custom XPathNavigator that exposes the contents as one large data source.</p>\n\n<p>Unfortunately, implementing this navigator is somewhat fiddly, and care must be taken especially when jumping between documents,</p>\n"
},
{
"answer_id": 226818,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 2,
"selected": true,
"text": "<p>I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space.</p>\n\n<pre><code>Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>();\n// ... populate dictionary of tables ...\nXElement TableRoot = new XStreamingElement(\"Tables\",\n from t in Tables\n select new XStreamingElement(t.Key,\n from DataRow r in t.Value.Rows\n select new XStreamingElement(\"row\",\n from DataColumn c in t.Value.Columns\n select new XElement(c.ColumnName, r[c])))))\n</code></pre>\n\n<p>The result is an XElement (TableRoot) with a structure similar to the following, assuming the dictionary contains one table called \"Orders\" with two rows.</p>\n\n<pre><code><Tables>\n <Orders>\n <row>\n <sku>12345</sku>\n <quantity>2</quantity>\n <price>5.95</price>\n </row>\n <row>\n <sku>54321</sku>\n <quantity>3</quantity>\n <price>2.95</price>\n </row>\n </Orders>\n</Tables>\n</code></pre>\n\n<p>That can be merged with a larger XElement/XDocument based hierarchy and queried with XPath.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
]
| I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders".
Is there a way to do this without copying all of the records in the DataTable into the XDocument?
I'm using .Net 3.5 | I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space.
```
Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>();
// ... populate dictionary of tables ...
XElement TableRoot = new XStreamingElement("Tables",
from t in Tables
select new XStreamingElement(t.Key,
from DataRow r in t.Value.Rows
select new XStreamingElement("row",
from DataColumn c in t.Value.Columns
select new XElement(c.ColumnName, r[c])))))
```
The result is an XElement (TableRoot) with a structure similar to the following, assuming the dictionary contains one table called "Orders" with two rows.
```
<Tables>
<Orders>
<row>
<sku>12345</sku>
<quantity>2</quantity>
<price>5.95</price>
</row>
<row>
<sku>54321</sku>
<quantity>3</quantity>
<price>2.95</price>
</row>
</Orders>
</Tables>
```
That can be merged with a larger XElement/XDocument based hierarchy and queried with XPath. |
150,095 | <p>I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:</p>
<pre><code>foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
puts "success!"
end
</code></pre>
| [
{
"answer_id": 150108,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>Use Regexp.new:</p>\n\n<pre><code>if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n</code></pre>\n"
},
{
"answer_id": 150110,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": false,
"text": "<p>Probably <code>Regexp.escape(foo)</code> would be a starting point, but is there a good reason you can't use the more conventional expression-interpolation: <code>\"my stuff #{mysubstitutionvariable}\"</code>?</p>\n\n<p>Also, you can just use <code>!goo.match(foo).nil?</code> with a literal string.</p>\n"
},
{
"answer_id": 150111,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Regexp.compile(Regexp.escape(foo))\n</code></pre>\n"
},
{
"answer_id": 150115,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 9,
"selected": true,
"text": "<p>Same as string insertion.</p>\n\n<pre><code>if goo =~ /#{Regexp.quote(foo)}/\n#...\n</code></pre>\n"
},
{
"answer_id": 150116,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": -1,
"selected": false,
"text": "<pre><code>foo = \"0.0.0.0\"\ngoo = \"here is some other stuff 0.0.0.0\" \n\nputs \"success!\" if goo =~ /#{foo}/\n</code></pre>\n"
},
{
"answer_id": 150598,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 7,
"selected": false,
"text": "<p>Note that the <a href=\"http://ruby-doc.org/core/Regexp.html#method-c-quote\" rel=\"noreferrer\"><code>Regexp.quote</code></a> in <a href=\"https://stackoverflow.com/a/150115/211563\">Jon L.'s answer</a> is important!</p>\n\n<pre><code>if goo =~ /#{Regexp.quote(foo)}/\n</code></pre>\n\n<p>If you just do the \"obvious\" version:</p>\n\n<pre><code>if goo =~ /#{foo}/\n</code></pre>\n\n<p>then the periods in your match text are treated as regexp wildcards, and <code>\"0.0.0.0\"</code> will match <code>\"0a0b0c0\"</code>.</p>\n\n<p>Note also that if you really just want to check for a substring match, you can simply do</p>\n\n<pre><code>if goo.include?(foo)\n</code></pre>\n\n<p>which doesn't require an additional quoting or worrying about special characters.</p>\n"
},
{
"answer_id": 19717549,
"author": "Plasmarob",
"author_id": 2225842,
"author_profile": "https://Stackoverflow.com/users/2225842",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a limited but useful other answer:</p>\n\n<p>I discovered I that I can easily insert into a regex without using Regexp.quote or Regexp.escape if I just used single quotes on my input string: (an IP address match)</p>\n\n<pre><code>IP_REGEX = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n\nmy_str = \"192.0.89.234 blahblah text 1.2, 1.4\" # get the first ssh key \n# replace the ip, for demonstration\nmy_str.gsub!(/#{IP_REGEX}/,\"192.0.2.0\") \nputs my_str # \"192.0.2.0 blahblah text 1.2, 1.4\"\n</code></pre>\n\n<p>single quotes only interpret \\\\ and \\'.</p>\n\n<p><a href=\"http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes\" rel=\"nofollow\">http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes</a></p>\n\n<p>This helped me when i needed to use the same long portion of a regex several times. \nNot universal, but fits the question example, I believe.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
| I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:
```
foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
puts "success!"
end
``` | Same as string insertion.
```
if goo =~ /#{Regexp.quote(foo)}/
#...
``` |
150,113 | <p>An older application using System.Web.Mail is throwing an exception on emails coming from <em>[email protected]</em>. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening?</p>
<p>Here is the exception and stack trace:</p>
<blockquote>
<p>System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server.<br/>
<br/>
--- End of inner exception stack trace ---<br/>
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)<br/>
at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)<br/>
at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/>
--- End of inner exception stack trace ---<br/>
at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)<br/>
at System.Web.Mail.CdoSysHelper.Send(MailMessage message)<br/>
at System.Web.Mail.SmtpMail.Send(MailMessage message)<br/>
at ProcessEmail.Main()<br/></p>
</blockquote>
| [
{
"answer_id": 150108,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>Use Regexp.new:</p>\n\n<pre><code>if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/\n</code></pre>\n"
},
{
"answer_id": 150110,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 3,
"selected": false,
"text": "<p>Probably <code>Regexp.escape(foo)</code> would be a starting point, but is there a good reason you can't use the more conventional expression-interpolation: <code>\"my stuff #{mysubstitutionvariable}\"</code>?</p>\n\n<p>Also, you can just use <code>!goo.match(foo).nil?</code> with a literal string.</p>\n"
},
{
"answer_id": 150111,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Regexp.compile(Regexp.escape(foo))\n</code></pre>\n"
},
{
"answer_id": 150115,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 9,
"selected": true,
"text": "<p>Same as string insertion.</p>\n\n<pre><code>if goo =~ /#{Regexp.quote(foo)}/\n#...\n</code></pre>\n"
},
{
"answer_id": 150116,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": -1,
"selected": false,
"text": "<pre><code>foo = \"0.0.0.0\"\ngoo = \"here is some other stuff 0.0.0.0\" \n\nputs \"success!\" if goo =~ /#{foo}/\n</code></pre>\n"
},
{
"answer_id": 150598,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 7,
"selected": false,
"text": "<p>Note that the <a href=\"http://ruby-doc.org/core/Regexp.html#method-c-quote\" rel=\"noreferrer\"><code>Regexp.quote</code></a> in <a href=\"https://stackoverflow.com/a/150115/211563\">Jon L.'s answer</a> is important!</p>\n\n<pre><code>if goo =~ /#{Regexp.quote(foo)}/\n</code></pre>\n\n<p>If you just do the \"obvious\" version:</p>\n\n<pre><code>if goo =~ /#{foo}/\n</code></pre>\n\n<p>then the periods in your match text are treated as regexp wildcards, and <code>\"0.0.0.0\"</code> will match <code>\"0a0b0c0\"</code>.</p>\n\n<p>Note also that if you really just want to check for a substring match, you can simply do</p>\n\n<pre><code>if goo.include?(foo)\n</code></pre>\n\n<p>which doesn't require an additional quoting or worrying about special characters.</p>\n"
},
{
"answer_id": 19717549,
"author": "Plasmarob",
"author_id": 2225842,
"author_profile": "https://Stackoverflow.com/users/2225842",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a limited but useful other answer:</p>\n\n<p>I discovered I that I can easily insert into a regex without using Regexp.quote or Regexp.escape if I just used single quotes on my input string: (an IP address match)</p>\n\n<pre><code>IP_REGEX = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'\n\nmy_str = \"192.0.89.234 blahblah text 1.2, 1.4\" # get the first ssh key \n# replace the ip, for demonstration\nmy_str.gsub!(/#{IP_REGEX}/,\"192.0.2.0\") \nputs my_str # \"192.0.2.0 blahblah text 1.2, 1.4\"\n</code></pre>\n\n<p>single quotes only interpret \\\\ and \\'.</p>\n\n<p><a href=\"http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes\" rel=\"nofollow\">http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes</a></p>\n\n<p>This helped me when i needed to use the same long portion of a regex several times. \nNot universal, but fits the question example, I believe.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17287/"
]
| An older application using System.Web.Mail is throwing an exception on emails coming from *[email protected]*. Other addresses appear to be working correctly. We changed our mail server to Exchange 2007 when the errors started, so I assume that is where the problem is. Does anyone know what is happening?
Here is the exception and stack trace:
>
> System.Web.HttpException: Could not access 'CDO.Message' object. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80040212): The transport lost its connection to the server.
>
>
>
> --- End of inner exception stack trace ---
>
> at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
>
> at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
>
> at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
>
> --- End of inner exception stack trace ---
>
> at System.Web.Mail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
>
> at System.Web.Mail.CdoSysHelper.Send(MailMessage message)
>
> at System.Web.Mail.SmtpMail.Send(MailMessage message)
>
> at ProcessEmail.Main()
>
>
>
> | Same as string insertion.
```
if goo =~ /#{Regexp.quote(foo)}/
#...
``` |
150,114 | <p>I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.</p>
<p>Which of these offers the best performance in which situations?</p>
<pre><code>Parse(...) // Crash if the case is extremely rare .0001%
If (SomethingIsValid) // Check the value before parsing
Parse(...)
TryParse(...) // Using TryParse
try
{
Parse(...)
}
catch
{
// Catch any thrown exceptions
}
</code></pre>
| [
{
"answer_id": 150123,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 7,
"selected": true,
"text": "<p>Always use <strong>T.TryParse(string str, out T value)</strong>. Throwing exceptions is expensive and should be avoided if you can handle the situation <em>a priori</em>. Using a try-catch block to \"save\" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize.</p>\n\n<blockquote>\n <p>\"We should forget about small efficiencies, say about 97% of the time: <strong>premature optimization is the root of all evil</strong>. Yet we should not pass up our opportunities in that critical 3%\" -Donald Knuth</p>\n</blockquote>\n\n<p>Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is <em>worse</em> and that the performance of TryParse is <em>better</em>. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse.</p>\n\n<p><em>(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)</em></p>\n\n<p>Times for various failure rates on 10,000 inputs from the user (for the unbelievers):</p>\n\n<pre><code>Failure Rate Try-Catch TryParse Slowdown\n 0% 00:00:00.0131758 00:00:00.0120421 0.1\n 10% 00:00:00.1540251 00:00:00.0087699 16.6\n 20% 00:00:00.2833266 00:00:00.0105229 25.9\n 30% 00:00:00.4462866 00:00:00.0091487 47.8\n 40% 00:00:00.6951060 00:00:00.0108980 62.8\n 50% 00:00:00.7567745 00:00:00.0087065 85.9\n 60% 00:00:00.7090449 00:00:00.0083365 84.1\n 70% 00:00:00.8179365 00:00:00.0088809 91.1\n 80% 00:00:00.9468898 00:00:00.0088562 105.9\n 90% 00:00:01.0411393 00:00:00.0081040 127.5\n100% 00:00:01.1488157 00:00:00.0078877 144.6\n\n\n/// <param name=\"errorRate\">Rate of errors in user input</param>\n/// <returns>Total time taken</returns>\npublic static TimeSpan TimeTryCatch(double errorRate, int seed, int count)\n{\n Stopwatch stopwatch = new Stopwatch();\n Random random = new Random(seed);\n string bad_prefix = @\"X\";\n\n stopwatch.Start();\n for(int ii = 0; ii < count; ++ii)\n {\n string input = random.Next().ToString();\n if (random.NextDouble() < errorRate)\n {\n input = bad_prefix + input;\n }\n\n int value = 0;\n try\n {\n value = Int32.Parse(input);\n }\n catch(FormatException)\n {\n value = -1; // we would do something here with a logger perhaps\n }\n }\n stopwatch.Stop();\n\n return stopwatch.Elapsed;\n}\n\n/// <param name=\"errorRate\">Rate of errors in user input</param>\n/// <returns>Total time taken</returns>\npublic static TimeSpan TimeTryParse(double errorRate, int seed, int count)\n{\n Stopwatch stopwatch = new Stopwatch();\n Random random = new Random(seed);\n string bad_prefix = @\"X\";\n\n stopwatch.Start();\n for(int ii = 0; ii < count; ++ii)\n {\n string input = random.Next().ToString();\n if (random.NextDouble() < errorRate)\n {\n input = bad_prefix + input;\n }\n\n int value = 0;\n if (!Int32.TryParse(input, out value))\n {\n value = -1; // we would do something here with a logger perhaps\n }\n }\n stopwatch.Stop();\n\n return stopwatch.Elapsed;\n}\n\npublic static void TimeStringParse()\n{\n double errorRate = 0.1; // 10% of the time our users mess up\n int count = 10000; // 10000 entries by a user\n\n TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);\n TimeSpan tryparse = TimeTryParse(errorRate, 1, count);\n\n Console.WriteLine(\"trycatch: {0}\", trycatch);\n Console.WriteLine(\"tryparse: {0}\", tryparse);\n}\n</code></pre>\n"
},
{
"answer_id": 150127,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 3,
"selected": false,
"text": "<p>Try-Catch will always be the slower. TryParse will be faster.</p>\n\n<p>The IF and TryParse are the same.</p>\n"
},
{
"answer_id": 150139,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Option 1: Will throw an exception on bad data.\nOption 2: SomethingIsValid() could be quite expensive - particularly if you are pre-checking a string for Integer parsability.\nOption 3: I like this. You need a null check afterwards, but it's pretty cheap.\nOption 4 is definitely the worst.\n</code></pre>\n\n<p>Exception handling is comparatively expensive, so avoid it if you can.</p>\n\n<p>In particular, bad inputs are to be expected, not exceptional, so you shouldn't use them for this situation. </p>\n\n<p>(Although, before TryParse, It may have been the best option.) </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22381/"
]
| I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.
Which of these offers the best performance in which situations?
```
Parse(...) // Crash if the case is extremely rare .0001%
If (SomethingIsValid) // Check the value before parsing
Parse(...)
TryParse(...) // Using TryParse
try
{
Parse(...)
}
catch
{
// Catch any thrown exceptions
}
``` | Always use **T.TryParse(string str, out T value)**. Throwing exceptions is expensive and should be avoided if you can handle the situation *a priori*. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize.
>
> "We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil**. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth
>
>
>
Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is *worse* and that the performance of TryParse is *better*. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse.
*(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)*
Times for various failure rates on 10,000 inputs from the user (for the unbelievers):
```
Failure Rate Try-Catch TryParse Slowdown
0% 00:00:00.0131758 00:00:00.0120421 0.1
10% 00:00:00.1540251 00:00:00.0087699 16.6
20% 00:00:00.2833266 00:00:00.0105229 25.9
30% 00:00:00.4462866 00:00:00.0091487 47.8
40% 00:00:00.6951060 00:00:00.0108980 62.8
50% 00:00:00.7567745 00:00:00.0087065 85.9
60% 00:00:00.7090449 00:00:00.0083365 84.1
70% 00:00:00.8179365 00:00:00.0088809 91.1
80% 00:00:00.9468898 00:00:00.0088562 105.9
90% 00:00:01.0411393 00:00:00.0081040 127.5
100% 00:00:01.1488157 00:00:00.0078877 144.6
/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryCatch(double errorRate, int seed, int count)
{
Stopwatch stopwatch = new Stopwatch();
Random random = new Random(seed);
string bad_prefix = @"X";
stopwatch.Start();
for(int ii = 0; ii < count; ++ii)
{
string input = random.Next().ToString();
if (random.NextDouble() < errorRate)
{
input = bad_prefix + input;
}
int value = 0;
try
{
value = Int32.Parse(input);
}
catch(FormatException)
{
value = -1; // we would do something here with a logger perhaps
}
}
stopwatch.Stop();
return stopwatch.Elapsed;
}
/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryParse(double errorRate, int seed, int count)
{
Stopwatch stopwatch = new Stopwatch();
Random random = new Random(seed);
string bad_prefix = @"X";
stopwatch.Start();
for(int ii = 0; ii < count; ++ii)
{
string input = random.Next().ToString();
if (random.NextDouble() < errorRate)
{
input = bad_prefix + input;
}
int value = 0;
if (!Int32.TryParse(input, out value))
{
value = -1; // we would do something here with a logger perhaps
}
}
stopwatch.Stop();
return stopwatch.Elapsed;
}
public static void TimeStringParse()
{
double errorRate = 0.1; // 10% of the time our users mess up
int count = 10000; // 10000 entries by a user
TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);
TimeSpan tryparse = TimeTryParse(errorRate, 1, count);
Console.WriteLine("trycatch: {0}", trycatch);
Console.WriteLine("tryparse: {0}", tryparse);
}
``` |
150,146 | <p>In my just-completed project, I was working getting distributed transactions working.</p>
<p>We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries.</p>
<p>Our request sequence looked like:</p>
<pre><code>browser -> secured servlet -> 'wafer-thin' SLSB -> spring TX-aware proxy -> request-handler POJO
</code></pre>
<p>What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB.</p>
<p>Our SLSB had a static initialiser block to bootstrap our Spring application context.</p>
<p>I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations.</p>
<p>I would be interested to know what others propose to separate tiers when using Spring?</p>
| [
{
"answer_id": 150526,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 1,
"selected": false,
"text": "<p>Jeremiah Morrill has recently released a <a href=\"http://www.codeplex.com/WPFMediaKit\" rel=\"nofollow noreferrer\">specialized WPF library</a> that supports displaying HD Media (among other features)</p>\n"
},
{
"answer_id": 150613,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": 0,
"selected": false,
"text": "<p>It sure doesn't seem to work correctly. It may be that testing for the opacity of other layers slows it down too much. Have you tried running the test with Aero turned off?</p>\n\n<p>It has been suggested that hosting Windows Media Player may be the way to go.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms748870.aspx\" rel=\"nofollow noreferrer\">Walkthrough: Hosting an ActiveX Control in Windows Presentation Foundation by Using XAML</a></p>\n"
},
{
"answer_id": 158678,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>What is the resolution/format of your HD video?</p>\n\n<p>I have done a 720p WMV on a dual core 2.6ghz fullscreen without issues, but it has a NVidia 9800GXT in it. What is the CPU usage of the HD video in just WMP? Remember that there is some overhead with rendering anything within WPF. So if you are running near 100% CPU, rendering to WPF may be just enough to set it over. Also if your GPU is too slow, you may also suffer choppy video.</p>\n\n<p>-Jeremiah</p>\n"
},
{
"answer_id": 438755,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is only a problem in Windows XP. It seems that the video playback is not updating with the vsynch. So it updates the screen whenever it feels like it. In Vista, the video rendering of WPF is smarter some how.</p>\n"
},
{
"answer_id": 1711377,
"author": "komplikator",
"author_id": 208192,
"author_profile": "https://Stackoverflow.com/users/208192",
"pm_score": 0,
"selected": false,
"text": "<p>Using correct vsync should solve the problem, and it is not necessarily related to the wpf and vista. Some ATI cards come with graphic drivers that have the vsync option turned off by default. Hope this helps.</p>\n"
},
{
"answer_id": 3924312,
"author": "bart s",
"author_id": 474535,
"author_profile": "https://Stackoverflow.com/users/474535",
"pm_score": 0,
"selected": false,
"text": "<p>Old thread, but just like to share my own experience. My guess is that your distribution machines are single monitor. I ever had a second monitor on my laptop and found that the first seconds of a video where not visible, and schocking video afterwards. Removing and disable the additional monitor solved the problems. I have seen more reports that the media element has problems in a dual monitor environment.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295/"
]
| In my just-completed project, I was working getting distributed transactions working.
We implemented this using JBoss's Arjuna Transaction Manager, and Spring's declarative transaction boundaries.
Our request sequence looked like:
```
browser -> secured servlet -> 'wafer-thin' SLSB -> spring TX-aware proxy -> request-handler POJO
```
What this meant is that we had a WAR to serve our secured servlet and an EAR to serve our SLSB.
Our SLSB had a static initialiser block to bootstrap our Spring application context.
I don't like the mix of technologies, but I do like the separation of presentation and business tiers, which could reside on different physical locations.
I would be interested to know what others propose to separate tiers when using Spring? | Jeremiah Morrill has recently released a [specialized WPF library](http://www.codeplex.com/WPFMediaKit) that supports displaying HD Media (among other features) |
150,150 | <p>I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below?</p>
<pre><code><Page.Resources>
<MenuItem x:Key="123"/>
</Page.Resources>
<ContextMenu>
<MenuItem>Something hardcoded</MenuItem>
<!-- include shared menu here -->
</ContextMenu>
</code></pre>
| [
{
"answer_id": 150203,
"author": "Phobis",
"author_id": 19854,
"author_profile": "https://Stackoverflow.com/users/19854",
"pm_score": 1,
"selected": false,
"text": "<p>Because you want to mix-and-match... I would make a custom control that inherits from ContextMenu that has a \"SharedMenuItems\" Dependancy Property and a MenuItems Dependancy Property. This way your control can decide how to merge these two sets together. If you would like an example of this, please let me know.</p>\n"
},
{
"answer_id": 150706,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "<p>I've done this by setting x:Shared=\"False\" on the menu item itself. Resources are shared between each place that uses them by default (meaning one instance across all uses), so turning that off means that a new \"copy\" of the resource is made each time.</p>\n\n<p>So:</p>\n\n<pre><code><MenuItem x:Key=\"myMenuItem\" x:Shared=\"False\" />\n</code></pre>\n\n<p>You'll still get a \"copy\" of it, but you only need to define it in one place. See if that helps. You use it like this within your menu definition:</p>\n\n<pre><code><StaticResource ResourceKey=\"myMenuItem\" />\n</code></pre>\n"
},
{
"answer_id": 151780,
"author": "Dominic Hopton",
"author_id": 9475,
"author_profile": "https://Stackoverflow.com/users/9475",
"pm_score": 0,
"selected": false,
"text": "<p>A number of options:\na) Databind the ContextMenu or the Menu to the same underlying collection and use item templates et al to the work\nb) Use commands, and databind to a set of command bindings</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1514/"
]
| I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below?
```
<Page.Resources>
<MenuItem x:Key="123"/>
</Page.Resources>
<ContextMenu>
<MenuItem>Something hardcoded</MenuItem>
<!-- include shared menu here -->
</ContextMenu>
``` | I've done this by setting x:Shared="False" on the menu item itself. Resources are shared between each place that uses them by default (meaning one instance across all uses), so turning that off means that a new "copy" of the resource is made each time.
So:
```
<MenuItem x:Key="myMenuItem" x:Shared="False" />
```
You'll still get a "copy" of it, but you only need to define it in one place. See if that helps. You use it like this within your menu definition:
```
<StaticResource ResourceKey="myMenuItem" />
``` |
150,161 | <p>I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.</p>
<p>EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.</p>
<pre><code>function Pause-Host
{
param(
$Delay = 1
)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
{
[Threading.Thread]::Sleep(1000)
}
}
</code></pre>
| [
{
"answer_id": 150326,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 5,
"selected": true,
"text": "<p>Found something <a href=\"http://huddledmasses.org/powershell-xmpp-jabber-snapin/\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>$counter = 0\nwhile(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))\n{\n [Threading.Thread]::Sleep( 1000 )\n}\n</code></pre>\n"
},
{
"answer_id": 29343310,
"author": "nathanchere",
"author_id": 243557,
"author_profile": "https://Stackoverflow.com/users/243557",
"pm_score": 3,
"selected": false,
"text": "<p>It's quite old now but how I solved it based on the same KeyAvailable method is here:</p>\n\n<p><a href=\"https://gist.github.com/nathanchere/704920a4a43f06f4f0d2\" rel=\"noreferrer\">https://gist.github.com/nathanchere/704920a4a43f06f4f0d2</a></p>\n\n<p>It waits for x seconds, displaying a <code>.</code> for each second that elapses up to the maximum wait time. If a key is pressed it returns <code>$true</code>, otherwise <code>$false</code>.</p>\n\n<pre><code>Function TimedPrompt($prompt,$secondsToWait){ \n Write-Host -NoNewline $prompt\n $secondsCounter = 0\n $subCounter = 0\n While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $secondsToWait) ){\n start-sleep -m 10\n $subCounter = $subCounter + 10\n if($subCounter -eq 1000)\n {\n $secondsCounter++\n $subCounter = 0\n Write-Host -NoNewline \".\"\n } \n If ($secondsCounter -eq $secondsToWait) { \n Write-Host \"`r`n\"\n return $false;\n }\n }\n Write-Host \"`r`n\"\n return $true;\n}\n</code></pre>\n\n<p>And to use:</p>\n\n<pre><code>$val = TimedPrompt \"Press key to cancel restore; will begin in 3 seconds\" 3\nWrite-Host $val\n</code></pre>\n"
},
{
"answer_id": 50274450,
"author": "Elavarasan Muthuvalavan - Lee",
"author_id": 1621781,
"author_profile": "https://Stackoverflow.com/users/1621781",
"pm_score": 2,
"selected": false,
"text": "<p>For people who are looking for a modern age solution with an additional constraint for exiting a PowerShell script on a pre-defined key press, the following solution might help you:</p>\n\n<pre><code>Write-Host (\"PowerShell Script to run a loop and exit on pressing 'q'!\")\n$count=0\n$sleepTimer=500 #in milliseconds\n$QuitKey=81 #Character code for 'q' key.\nwhile($count -le 100)\n{\n if($host.UI.RawUI.KeyAvailable) {\n $key = $host.ui.RawUI.ReadKey(\"NoEcho,IncludeKeyUp\")\n if($key.VirtualKeyCode -eq $QuitKey) {\n #For Key Combination: eg., press 'LeftCtrl + q' to quit.\n #Use condition: (($key.VirtualKeyCode -eq $Qkey) -and ($key.ControlKeyState -match \"LeftCtrlPressed\"))\n Write-Host -ForegroundColor Yellow (\"'q' is pressed! Stopping the script now.\")\n break\n }\n }\n #Do your operations\n $count++\n Write-Host (\"Count Incremented to - {0}\" -f $count)\n Write-Host (\"Press 'q' to stop the script!\")\n Start-Sleep -m $sleepTimer\n}\nWrite-Host -ForegroundColor Green (\"The script has stopped.\")\n</code></pre>\n\n<p>Sample script output:\n<a href=\"https://i.stack.imgur.com/IBb2o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IBb2o.png\" alt=\"enter image description here\"></a></p>\n\n<p>Refer <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.host.controlkeystates?view=powershellsdk-1.1.0\" rel=\"nofollow noreferrer\">Microsoft document</a> on key states for handling more combinations.</p>\n\n<p>Credits: <a href=\"https://social.technet.microsoft.com/Forums/windowsserver/en-US/29dc9692-e1b0-4aae-90aa-73a763758534/quit-powershell-script-by-pressing-a-defined-key?forum=winserverpowershell\" rel=\"nofollow noreferrer\">Technet Link</a></p>\n"
},
{
"answer_id": 52546471,
"author": "crokusek",
"author_id": 538763,
"author_profile": "https://Stackoverflow.com/users/538763",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a keystroke utility function that accepts: </p>\n\n<ul>\n<li>Validation character set (as a 1-character regex).</li>\n<li>Optional message </li>\n<li>Optional timeout in seconds</li>\n</ul>\n\n<p>Only matching keystrokes are reflected to the screen. </p>\n\n<p>Usage:</p>\n\n<pre><code>$key = GetKeyPress '[ynq]' \"Run step X ([y]/n/q)?\" 5\n\nif ($key -eq $null)\n{\n Write-Host \"No key was pressed.\";\n}\nelse\n{\n Write-Host \"The key was '$($key)'.\"\n}\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>Function GetKeyPress([string]$regexPattern='[ynq]', [string]$message=$null, [int]$timeOutSeconds=0)\n{\n $key = $null\n\n $Host.UI.RawUI.FlushInputBuffer() \n\n if (![string]::IsNullOrEmpty($message))\n {\n Write-Host -NoNewLine $message\n }\n\n $counter = $timeOutSeconds * 1000 / 250\n while($key -eq $null -and ($timeOutSeconds -eq 0 -or $counter-- -gt 0))\n {\n if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable)\n { \n $key_ = $host.UI.RawUI.ReadKey(\"NoEcho,IncludeKeyDown,IncludeKeyUp\")\n if ($key_.KeyDown -and $key_.Character -match $regexPattern)\n {\n $key = $key_ \n }\n }\n else\n {\n Start-Sleep -m 250 # Milliseconds\n }\n } \n\n if (-not ($key -eq $null))\n {\n Write-Host -NoNewLine \"$($key.Character)\" \n }\n\n if (![string]::IsNullOrEmpty($message))\n {\n Write-Host \"\" # newline\n } \n\n return $(if ($key -eq $null) {$null} else {$key.Character})\n}\n</code></pre>\n"
},
{
"answer_id": 66668858,
"author": "user15413294",
"author_id": 15413294,
"author_profile": "https://Stackoverflow.com/users/15413294",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function ReadKeyWithDefault($prompt, $defaultKey, [int]$timeoutInSecond = 5 ) {\n $counter = $timeoutInSecond * 10\n do{\n $remainingSeconds = [math]::floor($counter / 10)\n Write-Host "`r$prompt (default $defaultKey in $remainingSeconds seconds): " -NoNewline\n if($Host.UI.RawUI.KeyAvailable){\n $key = $host.UI.RawUI.ReadKey("IncludeKeyUp")\n Write-Host \n return $key\n }\n Start-Sleep -Milliseconds 100\n }while($counter-- -gt 0)\n\n Write-Host $defaultKey\n return $defaultKey\n}\n\n$readKey = ReadKeyWithDefault "If error auto exit( y/n )" 'y' 5\n</code></pre>\n"
},
{
"answer_id": 68421194,
"author": "john v kumpf",
"author_id": 4582204,
"author_profile": "https://Stackoverflow.com/users/4582204",
"pm_score": 1,
"selected": false,
"text": "<pre><code>timeout.exe 5\n</code></pre>\n<p>still works from powershell. Waits 5 seconds or until key press.</p>\n<p>Inelegant perhaps. But easy.</p>\n<p>However,</p>\n<p>From the Powershell_ISE it pops up a new command prompt window, and returns immediately, so it doesnt wait (From the powershell console it uses that console and does wait). You can make it wait from the ISE with a little more work (still pops up its own window tho):</p>\n<pre><code>if ($psISE) {\n start -Wait timeout.exe 5\n} else {\n timeout.exe 5\n}\n</code></pre>\n"
},
{
"answer_id": 69072089,
"author": "Alex from Jitbit",
"author_id": 56621,
"author_profile": "https://Stackoverflow.com/users/56621",
"pm_score": 1,
"selected": false,
"text": "<p>Another option: you can use <code>choice</code> shell command which comes with every Windows version since Windows 2000</p>\n<pre><code>Choice /C yn /D n /t 5 /m "Are you sure? You have 5 seconds to decide"\nif ($LASTEXITCODE -eq "1") # 1 for "yes" 2 for "no"\n{\n # do stuff\n}\nelse\n{\n # don't do stuff\n}\n</code></pre>\n<p>Stackoverflow syntax higlighting doesn't work for powershell, <code>#</code> means "comment" here</p>\n"
},
{
"answer_id": 72987575,
"author": "Pavman",
"author_id": 5633445,
"author_profile": "https://Stackoverflow.com/users/5633445",
"pm_score": 0,
"selected": false,
"text": "<p>To optionally pause the script before it exits (useful for running headless scripts and pausing on error output), I appended <a href=\"https://stackoverflow.com/users/243557/nathanchere\">nathanchere's answer</a> with:</p>\n<pre><code>if ([Console]::KeyAvailable) { $pressedKey = [Console]::ReadKey($true); read-host; break; }\n elseif ($secondsCounter -gt $secondsToWait) { \n Write-Host "`r`n"\n return $false;\n }\n</code></pre>\n"
},
{
"answer_id": 73733859,
"author": "Araminty Whitesell",
"author_id": 12313985,
"author_profile": "https://Stackoverflow.com/users/12313985",
"pm_score": 0,
"selected": false,
"text": "<p>The $Host.UI.RawUI.KeyAvailable seems to be buggy so I had more luck using [Console]::KeyAvailable:</p>\n<pre><code>function keypress_wait {\n param (\n [int]$seconds = 10\n )\n $loops = $seconds*10\n Write-Host "Press any key within $seconds seconds to continue"\n for ($i = 0; $i -le $loops; $i++){\n if ([Console]::KeyAvailable) { break; }\n Start-Sleep -Milliseconds 100\n }\nif ([Console]::KeyAvailable) { return [Console]::ReadKey($true); }\nelse { return $null ;}\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
]
| I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.
EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.
```
function Pause-Host
{
param(
$Delay = 1
)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
{
[Threading.Thread]::Sleep(1000)
}
}
``` | Found something [here](http://huddledmasses.org/powershell-xmpp-jabber-snapin/):
```
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
[Threading.Thread]::Sleep( 1000 )
}
``` |
150,167 | <p>How do I list and export a private key from a keystore?</p>
| [
{
"answer_id": 150181,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": true,
"text": "<p>A portion of code originally from Example Depot for listing all of the aliases in a key store:</p>\n\n<pre><code> // Load input stream into keystore\n keystore.load(is, password.toCharArray());\n\n // List the aliases\n Enumeration aliases = keystore.aliases();\n for (; aliases.hasMoreElements(); ) {\n String alias = (String)aliases.nextElement();\n\n // Does alias refer to a private key?\n boolean b = keystore.isKeyEntry(alias);\n\n // Does alias refer to a trusted certificate?\n b = keystore.isCertificateEntry(alias);\n }\n</code></pre>\n\n<p>The exporting of private keys came up on the <a href=\"http://forums.sun.com/thread.jspa?threadID=154587&start=15&tstart=0\" rel=\"noreferrer\">Sun forums</a> a couple of months ago, and <a href=\"http://forums.sun.com/profile.jspa?userID=505275\" rel=\"noreferrer\">u:turingcompleter</a> came up with a DumpPrivateKey class to stitch into your app.</p>\n\n<pre><code>import java.io.FileInputStream;\nimport java.security.Key;\nimport java.security.KeyStore;\nimport sun.misc.BASE64Encoder;\n\npublic class DumpPrivateKey {\n /**\n * Provides the missing functionality of keytool\n * that Apache needs for SSLCertificateKeyFile.\n *\n * @param args <ul>\n * <li> [0] Keystore filename.\n * <li> [1] Keystore password.\n * <li> [2] alias\n * </ul>\n */\n static public void main(String[] args)\n throws Exception {\n if(args.length < 3) {\n throw new IllegalArgumentException(\"expected args: Keystore filename, Keystore password, alias, <key password: default same tha\nn keystore\");\n }\n final String keystoreName = args[0];\n final String keystorePassword = args[1];\n final String alias = args[2];\n final String keyPassword = getKeyPassword(args,keystorePassword);\n KeyStore ks = KeyStore.getInstance(\"jks\");\n ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());\n Key key = ks.getKey(alias, keyPassword.toCharArray());\n String b64 = new BASE64Encoder().encode(key.getEncoded());\n System.out.println(\"-----BEGIN PRIVATE KEY-----\");\n System.out.println(b64);\n System.out.println(\"-----END PRIVATE KEY-----\");\n }\n private static String getKeyPassword(final String[] args, final String keystorePassword)\n {\n String keyPassword = keystorePassword; // default case\n if(args.length == 4) {\n keyPassword = args[3];\n }\n return keyPassword;\n }\n}\n</code></pre>\n\n<p>Note: this use Sun package, <a href=\"http://java.sun.com/products/jdk/faq/faq-sun-packages.html\" rel=\"noreferrer\">which is a \"bad thing\"</a>.<br>\nIf you can download <a href=\"http://commons.apache.org/codec/index.html\" rel=\"noreferrer\">apache commons code</a>, here is a version which will compile without warning:</p>\n\n<pre><code>javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java\n</code></pre>\n\n<p>and will give the same result:</p>\n\n<pre><code>import java.io.FileInputStream;\nimport java.security.Key;\nimport java.security.KeyStore;\n//import sun.misc.BASE64Encoder;\nimport org.apache.commons.codec.binary.Base64;\n\npublic class DumpPrivateKey {\n /**\n * Provides the missing functionality of keytool\n * that Apache needs for SSLCertificateKeyFile.\n *\n * @param args <ul>\n * <li> [0] Keystore filename.\n * <li> [1] Keystore password.\n * <li> [2] alias\n * </ul>\n */\n static public void main(String[] args)\n throws Exception {\n if(args.length < 3) {\n throw new IllegalArgumentException(\"expected args: Keystore filename, Keystore password, alias, <key password: default same tha\nn keystore\");\n }\n final String keystoreName = args[0];\n final String keystorePassword = args[1];\n final String alias = args[2];\n final String keyPassword = getKeyPassword(args,keystorePassword);\n KeyStore ks = KeyStore.getInstance(\"jks\");\n ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());\n Key key = ks.getKey(alias, keyPassword.toCharArray());\n //String b64 = new BASE64Encoder().encode(key.getEncoded());\n String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));\n System.out.println(\"-----BEGIN PRIVATE KEY-----\");\n System.out.println(b64);\n System.out.println(\"-----END PRIVATE KEY-----\");\n }\n private static String getKeyPassword(final String[] args, final String keystorePassword)\n {\n String keyPassword = keystorePassword; // default case\n if(args.length == 4) {\n keyPassword = args[3];\n }\n return keyPassword;\n }\n}\n</code></pre>\n\n<p>You can use it like so:</p>\n\n<pre><code>java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat\n</code></pre>\n"
},
{
"answer_id": 150195,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, be careful! All of your security depends on the… er… <strong>privacy</strong> of your <em>private keys.</em> Keytool doesn't have key export built in to avoid accidental disclosure of this sensitive material, so you might want to consider some extra safeguards that could be put in place to protect your exported keys.</p>\n\n<p>Here is some simple code that gives you unencrypted PKCS #8 PrivateKeyInfo that can be used by OpenSSL (see the <code>-nocrypt</code> option of its <a href=\"http://www.openssl.org/docs/apps/pkcs8.html\" rel=\"nofollow noreferrer\">pkcs8 utility</a>):</p>\n\n<pre><code>KeyStore keys = ...\nchar[] password = ...\nEnumeration<String> aliases = keys.aliases();\nwhile (aliases.hasMoreElements()) {\n String alias = aliases.nextElement();\n if (!keys.isKeyEntry(alias))\n continue;\n Key key = keys.getKey(alias, password);\n if ((key instanceof PrivateKey) && \"PKCS#8\".equals(key.getFormat())) {\n /* Most PrivateKeys use this format, but check for safety. */\n try (FileOutputStream os = new FileOutputStream(alias + \".key\")) {\n os.write(key.getEncoded());\n os.flush();\n }\n }\n}\n</code></pre>\n\n<p>If you need other formats, you can use a KeyFactory to get a transparent key specification for different types of keys. Then you can get, for example, the private exponent of an RSA private key and output it in your desired format. That would make a good topic for a follow-up question.</p>\n"
},
{
"answer_id": 150321,
"author": "DustinB",
"author_id": 7888,
"author_profile": "https://Stackoverflow.com/users/7888",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't need to do it programatically, but just want to manage your keys, then I've used IBM's free KeyMan tool for a long time now. Very nice for exporting a private key to a PFX file (then you can easily use OpenSSL to manipulate it, extract it, change pwds, etc).</p>\n\n<p><a href=\"https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc\" rel=\"nofollow noreferrer\">https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc</a></p>\n\n<p>Select your keystore, select the private key entry, then File->Save to a pkcs12 file (*.pfx, typically). You can then view the contents with:</p>\n\n<p>$ openssl pkcs12 -in mykeyfile.pfx -info</p>\n"
},
{
"answer_id": 5596842,
"author": "Donal Fellows",
"author_id": 301832,
"author_profile": "https://Stackoverflow.com/users/301832",
"pm_score": 7,
"selected": false,
"text": "<p>You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use <code>keytool</code> to convert to the standard format. Make sure you <strong><em>use the same password for both files (private key password, not the keystore password)</em></strong> or you will get odd failures later on in the second step.</p>\n\n<pre><code>keytool -importkeystore -srckeystore keystore.jks \\\n -destkeystore intermediate.p12 -deststoretype PKCS12\n</code></pre>\n\n<p>Next, use OpenSSL to do the extraction to PEM:</p>\n\n<pre><code>openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes\n</code></pre>\n\n<p>You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format).</p>\n\n<p><em>When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly.</em> The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab.</p>\n"
},
{
"answer_id": 8308842,
"author": "diyism",
"author_id": 264181,
"author_profile": "https://Stackoverflow.com/users/264181",
"pm_score": 2,
"selected": false,
"text": "<p>For android development,\nto convert keystore created in eclipse ADT into public key and private key used in SignApk.jar:</p>\n\n<p>export private key:</p>\n\n<pre><code>keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der\nopenssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem\n</code></pre>\n\n<p>edit private.rsa.pem and leave \"-----BEGIN PRIVATE KEY-----\" to \"-----END PRIVATE KEY-----\" paragraph, then:</p>\n\n<pre><code>openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der\n</code></pre>\n\n<p>export public key:</p>\n\n<pre><code>keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der\n</code></pre>\n\n<p>sign apk:</p>\n\n<pre><code>java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk\n</code></pre>\n"
},
{
"answer_id": 9105021,
"author": "jrk",
"author_id": 543416,
"author_profile": "https://Stackoverflow.com/users/543416",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a shorter version of the above code, in Groovy. Also has built-in base64 encoding:</p>\n\n<pre><code>import java.security.Key\nimport java.security.KeyStore\n\nif (args.length < 3)\n throw new IllegalArgumentException('Expected args: <Keystore file> <Keystore format> <Keystore password> <alias> <key password>')\n\ndef keystoreName = args[0]\ndef keystoreFormat = args[1]\ndef keystorePassword = args[2]\ndef alias = args[3]\ndef keyPassword = args[4]\n\ndef keystore = KeyStore.getInstance(keystoreFormat)\nkeystore.load(new FileInputStream(keystoreName), keystorePassword.toCharArray())\ndef key = keystore.getKey(alias, keyPassword.toCharArray())\n\nprintln \"-----BEGIN PRIVATE KEY-----\"\nprintln key.getEncoded().encodeBase64()\nprintln \"-----END PRIVATE KEY-----\"\n</code></pre>\n"
},
{
"answer_id": 11467779,
"author": "Kkkev",
"author_id": 442255,
"author_profile": "https://Stackoverflow.com/users/442255",
"pm_score": 1,
"selected": false,
"text": "<p>Another less-conventional but arguably easier way of doing this is with <a href=\"http://jxplorer.org/\" rel=\"nofollow\">JXplorer</a>. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.</p>\n"
},
{
"answer_id": 24287452,
"author": "PhilDin",
"author_id": 387675,
"author_profile": "https://Stackoverflow.com/users/387675",
"pm_score": 2,
"selected": false,
"text": "<p>This question came up on stackexchange security, one of the suggestions was to use <a href=\"http://keystore-explorer.sourceforge.net/\" rel=\"nofollow noreferrer\">Keystore explorer</a> </p>\n\n<p><a href=\"https://security.stackexchange.com/questions/3779/how-can-i-export-my-private-key-from-a-java-keytool-keystore\">https://security.stackexchange.com/questions/3779/how-can-i-export-my-private-key-from-a-java-keytool-keystore</a></p>\n\n<p>Having just tried it, it works really well and I strongly recommend it. </p>\n"
},
{
"answer_id": 28274993,
"author": "Davio",
"author_id": 1283166,
"author_profile": "https://Stackoverflow.com/users/1283166",
"pm_score": 2,
"selected": false,
"text": "<p>Another great tool is KeyStore Explorer: <a href=\"http://keystore-explorer.sourceforge.net/\" rel=\"nofollow\">http://keystore-explorer.sourceforge.net/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
| How do I list and export a private key from a keystore? | A portion of code originally from Example Depot for listing all of the aliases in a key store:
```
// Load input stream into keystore
keystore.load(is, password.toCharArray());
// List the aliases
Enumeration aliases = keystore.aliases();
for (; aliases.hasMoreElements(); ) {
String alias = (String)aliases.nextElement();
// Does alias refer to a private key?
boolean b = keystore.isKeyEntry(alias);
// Does alias refer to a trusted certificate?
b = keystore.isCertificateEntry(alias);
}
```
The exporting of private keys came up on the [Sun forums](http://forums.sun.com/thread.jspa?threadID=154587&start=15&tstart=0) a couple of months ago, and [u:turingcompleter](http://forums.sun.com/profile.jspa?userID=505275) came up with a DumpPrivateKey class to stitch into your app.
```
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;
public class DumpPrivateKey {
/**
* Provides the missing functionality of keytool
* that Apache needs for SSLCertificateKeyFile.
*
* @param args <ul>
* <li> [0] Keystore filename.
* <li> [1] Keystore password.
* <li> [2] alias
* </ul>
*/
static public void main(String[] args)
throws Exception {
if(args.length < 3) {
throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
}
final String keystoreName = args[0];
final String keystorePassword = args[1];
final String alias = args[2];
final String keyPassword = getKeyPassword(args,keystorePassword);
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
Key key = ks.getKey(alias, keyPassword.toCharArray());
String b64 = new BASE64Encoder().encode(key.getEncoded());
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(b64);
System.out.println("-----END PRIVATE KEY-----");
}
private static String getKeyPassword(final String[] args, final String keystorePassword)
{
String keyPassword = keystorePassword; // default case
if(args.length == 4) {
keyPassword = args[3];
}
return keyPassword;
}
}
```
Note: this use Sun package, [which is a "bad thing"](http://java.sun.com/products/jdk/faq/faq-sun-packages.html).
If you can download [apache commons code](http://commons.apache.org/codec/index.html), here is a version which will compile without warning:
```
javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java
```
and will give the same result:
```
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;
public class DumpPrivateKey {
/**
* Provides the missing functionality of keytool
* that Apache needs for SSLCertificateKeyFile.
*
* @param args <ul>
* <li> [0] Keystore filename.
* <li> [1] Keystore password.
* <li> [2] alias
* </ul>
*/
static public void main(String[] args)
throws Exception {
if(args.length < 3) {
throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
}
final String keystoreName = args[0];
final String keystorePassword = args[1];
final String alias = args[2];
final String keyPassword = getKeyPassword(args,keystorePassword);
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
Key key = ks.getKey(alias, keyPassword.toCharArray());
//String b64 = new BASE64Encoder().encode(key.getEncoded());
String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(b64);
System.out.println("-----END PRIVATE KEY-----");
}
private static String getKeyPassword(final String[] args, final String keystorePassword)
{
String keyPassword = keystorePassword; // default case
if(args.length == 4) {
keyPassword = args[3];
}
return keyPassword;
}
}
```
You can use it like so:
```
java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat
``` |
150,177 | <p>I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters.</p>
<p>Their initial naive implementation was something like </p>
<pre><code>BEGIN
INSERT INTO B SELECT * FROM A
DELETE FROM A
COMMIT;
END
</code></pre>
<p>Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted).</p>
<p>Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table.</p>
<p>However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows <em>DURING THE WAIT</em>.</p>
<p>We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach.</p>
<p>However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command.</p>
<p>In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why?</p>
| [
{
"answer_id": 150187,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>i don't know if this is relevant, but in SQL Server the syntax is</p>\n\n<pre><code>begin tran\n....\ncommit\n</code></pre>\n\n<p>not just 'begin'</p>\n"
},
{
"answer_id": 150189,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "<p>You need to set your transaction isolation level so that the inserts from another transaction don't affect your transaction. I don't know how to do that in Oracle.</p>\n"
},
{
"answer_id": 150207,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>I can't speak to the transaction stability, but an alternate approach would be to have the second step delete from the source table where exists (select ids from target table).</p>\n\n<p>Forgive the syntax, I have not tested this code, but you should be able to get the idea:</p>\n\n<pre><code>INSERT INTO B SELECT * FROM A;\n\nDELETE FROM A WHERE EXISTS (SELECT B.<primarykey> FROM B WHERE B.<primarykey> = A.<primarykey>);\n</code></pre>\n\n<p>That way you are using the relational engine to enforce that no newer data will be deleted, and you don't need to do the two steps in a transaction.</p>\n\n<p>Update: corrected syntax in subquery</p>\n"
},
{
"answer_id": 150218,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "<p>This can be achieved in Oracle using:</p>\n\n<pre><code>Alter session set isolation_level=serializable;\n</code></pre>\n\n<p>This can be set in PL/SQL using EXECUTE IMMEDIATE:</p>\n\n<pre><code>BEGIN\n EXECUTE IMMEDIATE 'Alter session set isolation_level=serializable';\n ...\nEND;\n</code></pre>\n\n<p>See <a href=\"http://www.oracle.com/technology/oramag/oracle/05-nov/o65asktom.html\" rel=\"nofollow noreferrer\">Ask Tom: On Transaction Isolation Levels</a></p>\n"
},
{
"answer_id": 150222,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>It's just the way transactions work. You have to pick the correct isolation level for the task at hand.</p>\n\n<p>You're doing INSERT and DELETE in the same transaction. You don't mention the isolation mode transaction is using, but it's probably 'read committed'. This means that the DELETE command will see the records that were committed in the meantime. For this kind of job, it's much better to use 'snapshot' type of transaction, because then both INSERT and DELETE would know about the same set of records - only those and nothing else.</p>\n"
},
{
"answer_id": 150257,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 0,
"selected": false,
"text": "<p>Yes Milan, I haven't specified the transaction isolation level. I suppose it's the default isolation level which I don't know which it is. Neither in Oracle 11g nor in SQL Server 2005.</p>\n\n<p>Furthermore the INSERT that was made during the WAIT command (on the 2nd connection) was <em>NOT</em> inside a transaction. Should have it been to prevent this data loss?</p>\n"
},
{
"answer_id": 150259,
"author": "jwanagel",
"author_id": 15118,
"author_profile": "https://Stackoverflow.com/users/15118",
"pm_score": 4,
"selected": true,
"text": "<p>Depending on your isolation level, selecting all the rows from a table does not prevent new inserts, it will just lock the rows you read. In SQL Server, if you use the Serializable isolation level then it will prevent new rows if they would have been including in your select query.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms173763.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms173763.aspx</a> - </p>\n\n<p>SERIALIZABLE\nSpecifies the following:</p>\n\n<ul>\n<li><p>Statements cannot read data that has been modified but not yet committed by other transactions.</p></li>\n<li><p>No other transactions can modify data that has been read by the current transaction until the current transaction completes.</p></li>\n<li><p><strong>Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.</strong></p></li>\n</ul>\n"
},
{
"answer_id": 150497,
"author": "Justin Cave",
"author_id": 10397,
"author_profile": "https://Stackoverflow.com/users/10397",
"pm_score": 1,
"selected": false,
"text": "<p>In Oracle, the default transaction isolation level is read committed. That basically means that Oracle returns the results as they existed at the SCN (system change number) when your query started. Setting the transaction isolation level to serializable means that the SCN is captured at the start of the transaction so all the queries in your transaction return data as of that SCN. That ensures consistent results regardless of what other sessions and transactions are doing. On the other hand, there may be a cost in that Oracle may determine that it cannot serialize your transaction because of activity that other transactions are performing, so you would have to handle that sort of error.</p>\n\n<p>Tony's link to the AskTom discussion goes in to substantially more detail about all this-- I highly recommend it.</p>\n"
},
{
"answer_id": 152076,
"author": "Andrew not the Saint",
"author_id": 23670,
"author_profile": "https://Stackoverflow.com/users/23670",
"pm_score": 0,
"selected": false,
"text": "<p>This is the standard behaviour of the default read-committed mode, as mentioned above. The WAIT command just causes a delay in processing, there's no link to any DB transaction handling.</p>\n\n<p>To fix the problem you can either:</p>\n\n<ol>\n<li>set the isolation level to serializable, but then you can get ORA- errors, which you need to handle with retries! Also, you may get a serious performance hit.</li>\n<li>use a temp table to store the values first</li>\n<li>if the data is not too large to fit into the memory, you can use a RETURNING clause to BULK COLLECT INTO a nested table and delete only if the row is present in the nested table.</li>\n</ol>\n"
},
{
"answer_id": 1119702,
"author": "A-K",
"author_id": 108977,
"author_profile": "https://Stackoverflow.com/users/108977",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively, you can use snapshot isolation to detect lost updates:</p>\n\n<p><a href=\"http://www.devx.com/dbzone/Article/32957\" rel=\"nofollow noreferrer\">When Snapshot Isolation Helps and When It Hurts</a></p>\n"
},
{
"answer_id": 31817642,
"author": "Goyal Vicky",
"author_id": 5166587,
"author_profile": "https://Stackoverflow.com/users/5166587",
"pm_score": 0,
"selected": false,
"text": "<pre><code> I have written a sample code:-\n\n First run this on Oracle DB:-\n\n\n Create table AccountBalance\n (\n id integer Primary Key,\n acctName varchar2(255) not null,\n acctBalance integer not null,\n bankName varchar2(255) not null\n );\n\n insert into AccountBalance values (1,'Test',50000,'Bank-a');\n\n Now run the below code \n\n\n\n\n\n package com.java.transaction.dirtyread;\n import java.sql.Connection;\n import java.sql.DriverManager;\n import java.sql.SQLException;\n\n public class DirtyReadExample {\n\n /**\n * @param args\n * @throws ClassNotFoundException \n * @throws SQLException \n * @throws InterruptedException \n */\n public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {\n\n Class.forName(\"oracle.jdbc.driver.OracleDriver\");\n Connection connectionPayment = DriverManager.getConnection(\n \"jdbc:oracle:thin:@localhost:1521:xe\", \"hr\",\n \"hr\");\n Connection connectionReader = DriverManager.getConnection(\n \"jdbc:oracle:thin:@localhost:1521:xe\", \"hr\",\n \"hr\");\n\n try {\n connectionPayment.setAutoCommit(false);\n connectionPayment.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);\n\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n\n Thread pymtThread=new Thread(new PaymentRunImpl(connectionPayment));\n Thread readerThread=new Thread(new ReaderRunImpl(connectionReader));\n\n pymtThread.start();\n Thread.sleep(2000);\n readerThread.start();\n\n }\n\n }\n\n\n\n package com.java.transaction.dirtyread;\n\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.ResultSet;\n import java.sql.SQLException;\n\n public class ReaderRunImpl implements Runnable{\n\n private Connection conn;\n\n private static final String QUERY=\"Select acctBalance from AccountBalance where id=1\";\n\n public ReaderRunImpl(Connection conn){\n this.conn=conn;\n }\n\n @Override\n public void run() {\n PreparedStatement stmt =null; \n ResultSet rs =null;\n\n try {\n stmt = conn.prepareStatement(QUERY);\n System.out.println(\"In Reader thread --->Statement Prepared\");\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n System.out.println(\"In Reader thread --->Statement Prepared\");\n Thread.sleep(5000);\n stmt.close();\n rs.close();\n stmt = conn.prepareStatement(QUERY);\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n stmt.close();\n rs.close();\n stmt = conn.prepareStatement(QUERY);\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n } catch (SQLException | InterruptedException e) {\n e.printStackTrace();\n }finally{\n try {\n stmt.close();\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n }\n\n }\n\n package com.java.transaction.dirtyread;\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.SQLException;\n\n public class PaymentRunImpl implements Runnable{\n\n private Connection conn;\n\n private static final String QUERY1=\"Update AccountBalance set acctBalance=40000 where id=1\";\n private static final String QUERY2=\"Update AccountBalance set acctBalance=30000 where id=1\";\n private static final String QUERY3=\"Update AccountBalance set acctBalance=20000 where id=1\";\n private static final String QUERY4=\"Update AccountBalance set acctBalance=10000 where id=1\";\n\n public PaymentRunImpl(Connection conn){\n this.conn=conn;\n }\n\n @Override\n public void run() {\n PreparedStatement stmt = null;\n\n try { \n stmt = conn.prepareStatement(QUERY1);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n Thread.sleep(3000);\n stmt = conn.prepareStatement(QUERY2);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n Thread.sleep(3000);\n stmt = conn.prepareStatement(QUERY3);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n stmt = conn.prepareStatement(QUERY4);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n\n Thread.sleep(5000);\n //case 1\n conn.rollback();\n System.out.println(\"In Payment thread --> rollback\");\n //case 2\n //conn.commit();\n // System.out.println(\"In Payment thread --> commit\");\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (InterruptedException e) { \n e.printStackTrace();\n }finally{\n try {\n stmt.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n }\n\n }\n\n Output:-\n In Payment thread --> executed\n In Reader thread --->Statement Prepared\n In Reader thread --->executing\n Balance is:50000.0\n In Reader thread --->Statement Prepared\n In Payment thread --> executed\n In Payment thread --> executed\n In Payment thread --> executed\n In Reader thread --->executing\n Balance is:50000.0\n In Reader thread --->executing\n Balance is:50000.0\n In Payment thread --> rollback\n</code></pre>\n\n<p>U can test it by inserting new rows as defined by oracle:-\n A phantom read occurs when transaction A retrieves a set of rows satisfying a given condition, transaction B subsequently inserts or updates a row such that the row now meets the condition in transaction A, and transaction A later repeats the conditional retrieval. Transaction A now sees an additional row. This row is referred to as a phantom. It will avoid the above scenario as well as I have used TRANSACTION_SERIALIZABLE. It will set the most strict lock on the Oracle. Oracle only supports 2 type of transaction isolation levels:- TRANSACTION_READ_COMMITTED and TRANSACTION_SERIALIZABLE. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796/"
]
| I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters.
Their initial naive implementation was something like
```
BEGIN
INSERT INTO B SELECT * FROM A
DELETE FROM A
COMMIT;
END
```
Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted).
Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table.
However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows *DURING THE WAIT*.
We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach.
However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command.
In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why? | Depending on your isolation level, selecting all the rows from a table does not prevent new inserts, it will just lock the rows you read. In SQL Server, if you use the Serializable isolation level then it will prevent new rows if they would have been including in your select query.
<http://msdn.microsoft.com/en-us/library/ms173763.aspx> -
SERIALIZABLE
Specifies the following:
* Statements cannot read data that has been modified but not yet committed by other transactions.
* No other transactions can modify data that has been read by the current transaction until the current transaction completes.
* **Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.** |
150,186 | <p>I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.</p>
<p>this forum thread
<a href="http://www.daniweb.com/forums/thread29742.html" rel="nofollow noreferrer">IDataObject : ambiguous symbol error</a> answers a problem I've seen multiple times.</p>
<p>Post #4 states
"Move all 'using namespace XXXX' from .h to .cpp"</p>
<p>this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like</p>
<pre><code>void loadConfigurations(String^ pPathname);
</code></pre>
<p>How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?</p>
| [
{
"answer_id": 150236,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know much about .NET, so my answer only applies to the unmanaged c++ part of your question. Personally, this is one of the main reasons I avoid like the plague \"using namespace XXXX;\" statements.</p>\n\n<p>I prefer to just be explicit with namespaces like \"std::cout << \"hello world\" << std::endl;\"</p>\n\n<p>This avoid namespace collisions and there is never any ambiguity as to where something came from. Also, when you do something like \"using namespace std;\" you are kinda undoing what namespaces give you. They were designed to avoid collisions and by importing everything into the global, you just invite collisions back in.</p>\n\n<p>This is stricly a matter of opinion and taste.</p>\n\n<p>As for what to do in headers, I just write stuff like this: \"void f(const std::string &s);\"</p>\n"
},
{
"answer_id": 150245,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>To solve this I've done this in the .h file:</p>\n\n<pre><code>namespace TestClassNS\n{\n class TestClass;\n}\n</code></pre>\n\n<p>and then in the .cpp file I would #include the .h that TestClass was in and do the using namespaceTestClassNS there.</p>\n\n<p>My C++ is rusty, so there may be a better way.</p>\n"
},
{
"answer_id": 150249,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": true,
"text": "<p>It's a good idea to always use fully qualified names in header files. Because the <code>using</code> statement affects all following code regardless of <code>#include</code>, putting a <code>using</code> statement in a header file affects everybody that might include that header.</p>\n\n<p>So you would change your function declaration in your header file to:</p>\n\n<pre><code>void loadConfigurations(SomeNamespace::String^ pPathname);\n</code></pre>\n\n<p>where SomeNamespace is the name of the namespace you were <code>using</code> previously.</p>\n"
},
{
"answer_id": 151644,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 0,
"selected": false,
"text": "<p>In my experience the only namespace you have to be careful about is System itself. It's somewhat annoying that the most common, most important one is where you find problems, but that's life.</p>\n\n<p>At least you can take comfort that if you're creating managed classes, you're issues with includes will get relief at the assembly barrier, unlike issues with header files for unmanaged classes.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
]
| I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.
this forum thread
[IDataObject : ambiguous symbol error](http://www.daniweb.com/forums/thread29742.html) answers a problem I've seen multiple times.
Post #4 states
"Move all 'using namespace XXXX' from .h to .cpp"
this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like
```
void loadConfigurations(String^ pPathname);
```
How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file? | It's a good idea to always use fully qualified names in header files. Because the `using` statement affects all following code regardless of `#include`, putting a `using` statement in a header file affects everybody that might include that header.
So you would change your function declaration in your header file to:
```
void loadConfigurations(SomeNamespace::String^ pPathname);
```
where SomeNamespace is the name of the namespace you were `using` previously. |
150,208 | <p>Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)?</p>
<p>The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish.</p>
<p>I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly.</p>
| [
{
"answer_id": 152182,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe what you need is <a href=\"http://www.codeplex.com/WinformHtmlTextbox\" rel=\"nofollow noreferrer\">a control to edit the HTML</a>? </p>\n"
},
{
"answer_id": 155112,
"author": "Andrew",
"author_id": 20118,
"author_profile": "https://Stackoverflow.com/users/20118",
"pm_score": 2,
"selected": false,
"text": "<p>It is not perfect of course, but here is the code I use to convert HTML to plain text.</p>\n\n<p>(I was not the original author, I adapted it from code found on the web)</p>\n\n<pre><code>public static string ConvertHtmlToText(string source) {\n\n string result;\n\n // Remove HTML Development formatting\n // Replace line breaks with space\n // because browsers inserts space\n result = source.Replace(\"\\r\", \" \");\n // Replace line breaks with space\n // because browsers inserts space\n result = result.Replace(\"\\n\", \" \");\n // Remove step-formatting\n result = result.Replace(\"\\t\", string.Empty);\n // Remove repeating speces becuase browsers ignore them\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"( )+\", \" \");\n\n // Remove the header (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*head([^>])*>\", \"<head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*head( )*>)\", \"</head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<head>).*(</head>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all scripts (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*script([^>])*>\", \"<script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*script( )*>)\", \"</script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n //result = System.Text.RegularExpressions.Regex.Replace(result, \n // @\"(<script>)([^(<script>\\.</script>)])*(</script>)\",\n // string.Empty, \n // System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<script>).*(</script>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all styles (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*style([^>])*>\", \"<style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*style( )*>)\", \"</style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<style>).*(</style>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert tabs in spaces of <td> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*td([^>])*>\", \"\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line breaks in places of <BR> and <LI> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*br( )*>\", \"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*li( )*>\", \"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line paragraphs (double line breaks) in place\n // if <P>, <DIV> and <TR> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*div([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*tr([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*p([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // Remove remaining tags like <a>, links, images,\n // comments etc - anything thats enclosed inside < >\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<[^>]*>\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // replace special characters:\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&nbsp;\", \" \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&bull;\", \" * \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&lsaquo;\", \"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&rsaquo;\", \">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&trade;\", \"(tm)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&frasl;\", \"/\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<\", \"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\">\", \">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&copy;\", \"(c)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&reg;\", \"(r)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove all others. More can be added, see\n // http://hotwired.lycos.com/webmonkey/reference/special_characters/\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&(.{2,6});\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n\n // make line breaking consistent\n result = result.Replace(\"\\n\", \"\\r\");\n\n // Remove extra line breaks and tabs:\n // replace over 2 breaks with 2 and over 4 tabs with 4. \n // Prepare first to remove any whitespaces inbetween\n // the escaped characters and remove redundant tabs inbetween linebreaks\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\r)\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\t)\", \"\\t\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\r)\", \"\\t\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\t)\", \"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove redundant tabs\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+(\\r)\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove multible tabs followind a linebreak with just one tab\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+\", \"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Initial replacement target string for linebreaks\n string breaks = \"\\r\\r\\r\";\n // Initial replacement target string for tabs\n string tabs = \"\\t\\t\\t\\t\\t\";\n for (int index = 0; index < result.Length; index++) {\n result = result.Replace(breaks, \"\\r\\r\");\n result = result.Replace(tabs, \"\\t\\t\\t\\t\");\n breaks = breaks + \"\\r\";\n tabs = tabs + \"\\t\";\n }\n\n // Thats it.\n return result;\n\n }\n</code></pre>\n"
},
{
"answer_id": 754598,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 3,
"selected": false,
"text": "<p>Check out this CodeProject article on <a href=\"http://www.codeproject.com/KB/HTML/XHTML2RTF.aspx\" rel=\"noreferrer\">XHTML2RTF</a>.</p>\n"
},
{
"answer_id": 4854628,
"author": "Spartaco",
"author_id": 565927,
"author_profile": "https://Stackoverflow.com/users/565927",
"pm_score": 6,
"selected": true,
"text": "<p>Actually there is a simple and <strong>free</strong> solution: use your browser, ok this is the trick I used:</p>\n\n<pre><code>var webBrowser = new WebBrowser();\nwebBrowser.CreateControl(); // only if needed\nwebBrowser.DocumentText = *yourhtmlstring*;\nwhile (_webBrowser.DocumentText != *yourhtmlstring*)\n Application.DoEvents();\nwebBrowser.Document.ExecCommand(\"SelectAll\", false, null);\nwebBrowser.Document.ExecCommand(\"Copy\", false, null);\n*yourRichTextControl*.Paste(); \n</code></pre>\n\n<p>This could be slower than other methods but at least it's free and works!</p>\n"
},
{
"answer_id": 5034601,
"author": "cjbarth",
"author_id": 271351,
"author_profile": "https://Stackoverflow.com/users/271351",
"pm_score": 3,
"selected": false,
"text": "<p>Expanding on Spartaco's answer I implimented the following which works GREAT!</p>\n\n<pre><code> Using reportWebBrowser As New WebBrowser\n reportWebBrowser.CreateControl()\n reportWebBrowser.DocumentText = sbHTMLDoc.ToString\n While reportWebBrowser.DocumentText <> sbHTMLDoc.ToString\n Application.DoEvents()\n End While\n reportWebBrowser.Document.ExecCommand(\"SelectAll\", False, Nothing)\n reportWebBrowser.Document.ExecCommand(\"Copy\", False, Nothing)\n\n Using reportRichTextBox As New RichTextBox\n reportRichTextBox.Paste()\n reportRichTextBox.SaveFile(DocumentFileName)\n End Using\n End Using\n</code></pre>\n"
},
{
"answer_id": 56733740,
"author": "Jacek Krawczyk",
"author_id": 1960514,
"author_profile": "https://Stackoverflow.com/users/1960514",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend a console tool named <a href=\"https://pandoc.org/\" rel=\"nofollow noreferrer\">Pandoc</a>. It is not a component, it is rather huge conversion pack. I am using it to convert between HTML and LaTeX. It is just awesome.</p>\n\n<p>The full list of supported formats you can find <a href=\"https://pandoc.org/index.html\" rel=\"nofollow noreferrer\">on the program page</a>.</p>\n\n<p>In order to convert an HTML document to RTF format you write on the console:</p>\n\n<pre><code>pandoc filename.html -f html -t rtf -s -o filename.rtf\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
]
| Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)?
The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish.
I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly. | Actually there is a simple and **free** solution: use your browser, ok this is the trick I used:
```
var webBrowser = new WebBrowser();
webBrowser.CreateControl(); // only if needed
webBrowser.DocumentText = *yourhtmlstring*;
while (_webBrowser.DocumentText != *yourhtmlstring*)
Application.DoEvents();
webBrowser.Document.ExecCommand("SelectAll", false, null);
webBrowser.Document.ExecCommand("Copy", false, null);
*yourRichTextControl*.Paste();
```
This could be slower than other methods but at least it's free and works! |
150,213 | <p>I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered.</p>
<p>I started with this:</p>
<pre><code>var dailyCountList =
(from a in showDC.Attendee
let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day)
group a by justDate into DateGroup
orderby DateGroup.Key
select new RegistrationCount
{
EventDateTime = DateGroup.Key,
Count = DateGroup.Count()
}).ToList();
</code></pre>
<p>That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.</p>
<p>So this is my current working solution, but I KNOW THAT IT IS TERRIBLE.
I added the following to the code above:</p>
<pre><code>// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations)
var allDates = new List<RegistrationCount>();
for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date <= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1))
{
DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx
allDates.Add(new RegistrationCount
{
EventDateTime = date,
Count = (from dclInner in dailyCountList
where dclInner.EventDateTime == thisDate
select dclInner).DefaultIfEmpty(new RegistrationCount
{
EventDateTime = date,
Count = 0
}).Single().Count
});
}
</code></pre>
<p>So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.</p>
<p>Can anyone thing of an elegant solution? Or at least one that is less embarrassing?</p>
| [
{
"answer_id": 150334,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": true,
"text": "<p>O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff.</p>\n\n<pre><code> if (!dailyCountList.Any())\n return;\n\n //make a dictionary to provide O(1) lookups for later\n\n Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime);\n\n DateTime minDate = dailyCountList[0].EventDateTime;\n DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime;\n\n int DayCount = 1 + (int) (maxDate - minDate).TotalDays;\n\n // I have the days now.\n IEnumerable<DateTime> allDates = Enumerable\n .Range(0, DayCount)\n .Select(x => minDate.AddDays(x));\n\n //project the days into RegistrationCounts, making up the missing ones.\n List<RegistrationCount> result = allDates\n .Select(d => lookup.ContainsKey(d) ? lookup[d] :\n new RegistrationCount(){EventDateTime = d, Count = 0})\n .ToList();\n</code></pre>\n"
},
{
"answer_id": 150438,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 0,
"selected": false,
"text": "<p>Does this syntax for left outer joins no longer work as well after SP1, then?</p>\n\n<p>Usually, you should able to do the following, but you'd need a calendar table of sorts in your SQL database joined to your date key in the registrations table (w/a foreign key on the date id field), and then try:</p>\n\n<pre><code>var query =\n from cal in dataContext.Calendar\n from reg in cal.Registrations.DefaultIfEmpty()\n select new\n {\n cal.DateID,\n reg.Something\n };\n</code></pre>\n"
},
{
"answer_id": 150964,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that you have no range of dates without executing your query. So, you can either pick a date range, run a SELECT MAX and SELECT MIN against your DB, or execute your query and then add the missing dates.</p>\n\n<pre><code>var allDailyCountList =\n from d in Range(dc[0].EventDateTime, dc[dc.Count - 1].EventDateTime) \n // since you already ordered by DateTime, we don't have to search the entire List\n join dc in dailyCountList on\n d equals dc.EventDateTime\n into rcGroup\n from rc in rcGroup.DefaultIfEmpty(\n new RegistrationCount()\n {\n EventDateTime = d,\n Count = 0\n }\n ) // gives us a left join\n select rc;\n\npublic static IEnumerable<DateTime> Range(DateTime start, DateTime end) {\n for (DateTime date = start, date <= end; date = date.AddDays(1)) {\n yield return date;\n }\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13700/"
]
| I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A\_DT, which is the date and time the person registered.
I started with this:
```
var dailyCountList =
(from a in showDC.Attendee
let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day)
group a by justDate into DateGroup
orderby DateGroup.Key
select new RegistrationCount
{
EventDateTime = DateGroup.Key,
Count = DateGroup.Count()
}).ToList();
```
That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.
So this is my current working solution, but I KNOW THAT IT IS TERRIBLE.
I added the following to the code above:
```
// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations)
var allDates = new List<RegistrationCount>();
for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date <= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1))
{
DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx
allDates.Add(new RegistrationCount
{
EventDateTime = date,
Count = (from dclInner in dailyCountList
where dclInner.EventDateTime == thisDate
select dclInner).DefaultIfEmpty(new RegistrationCount
{
EventDateTime = date,
Count = 0
}).Single().Count
});
}
```
So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.
Can anyone thing of an elegant solution? Or at least one that is less embarrassing? | O(n) with 2 enumerations. It's very good to pull the items into memory before trying this. Database has enough to do without thinking about this stuff.
```
if (!dailyCountList.Any())
return;
//make a dictionary to provide O(1) lookups for later
Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime);
DateTime minDate = dailyCountList[0].EventDateTime;
DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime;
int DayCount = 1 + (int) (maxDate - minDate).TotalDays;
// I have the days now.
IEnumerable<DateTime> allDates = Enumerable
.Range(0, DayCount)
.Select(x => minDate.AddDays(x));
//project the days into RegistrationCounts, making up the missing ones.
List<RegistrationCount> result = allDates
.Select(d => lookup.ContainsKey(d) ? lookup[d] :
new RegistrationCount(){EventDateTime = d, Count = 0})
.ToList();
``` |
150,223 | <p>Looking for a way to programatically, or otherwise, add a new instance of SQL 2005 Express Edition to a system that already has an instance installed. Traditionally, you run Micrsoft's installer like I am in the command line below and it does the trick. Executing the command in my installer is not the issue, it's more a matter of dragging around the 40 MBs of MS-SQL installer that I don't need if they have SQL Express already installed. This is what my installer currently executes:</p>
<pre><code>SQLEXPR32.EXE /qb ADDLOCAL=ALL INSTANCENAME=<instancename> SECURITYMODE=SQL SAPWD=<password> SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0
</code></pre>
<p>I don't need assistance with launching this command, rather the appropriate way to add a new instance of SQL 2005 Express without actually running the full installer again. </p>
<p>I'd go into great detail about why I want to do this but I'd simply bore everyone. Suffice to say, having this ability to create a new instance without the time it takes to reinstall SQL Express etc. would greatly assist me for the deployment of my application and it's installer. If makes any difference to anyone, I'm using a combination of NSIS and Advanced Installer for this installation project.</p>
| [
{
"answer_id": 150247,
"author": "Scott Isaacs",
"author_id": 1664,
"author_profile": "https://Stackoverflow.com/users/1664",
"pm_score": 0,
"selected": false,
"text": "<p>I do not know how to do it with an API, but if no one gives a better solution, you can always use Process.Start() to execute your command line as-is.</p>\n"
},
{
"answer_id": 345061,
"author": "Bernhard Hofmann",
"author_id": 39722,
"author_profile": "https://Stackoverflow.com/users/39722",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like a user instance might help you. If you have the MDF and LDF files, you can connect to the files by instructing SQL Server Express to launch a user instance and attach the specified file to that instance.</p>\n\n<p>This artile <a href=\"http://msdn.microsoft.com/en-us/library/bb264564.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb264564.aspx</a> has a good description of how you can lean on the existing SQL Server Express installation to instantiate a user-specific instance for the duration of your connection.</p>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 2443798,
"author": "Douglas Anderson",
"author_id": 5678,
"author_profile": "https://Stackoverflow.com/users/5678",
"pm_score": 1,
"selected": true,
"text": "<p>After months/years of looking into this it appears it can't be done. Oh well, I guess I just reinstall each time I want a new instance. I guess it's because each instance is it's own service.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678/"
]
| Looking for a way to programatically, or otherwise, add a new instance of SQL 2005 Express Edition to a system that already has an instance installed. Traditionally, you run Micrsoft's installer like I am in the command line below and it does the trick. Executing the command in my installer is not the issue, it's more a matter of dragging around the 40 MBs of MS-SQL installer that I don't need if they have SQL Express already installed. This is what my installer currently executes:
```
SQLEXPR32.EXE /qb ADDLOCAL=ALL INSTANCENAME=<instancename> SECURITYMODE=SQL SAPWD=<password> SQLAUTOSTART=1 DISABLENETWORKPROTOCOLS=0
```
I don't need assistance with launching this command, rather the appropriate way to add a new instance of SQL 2005 Express without actually running the full installer again.
I'd go into great detail about why I want to do this but I'd simply bore everyone. Suffice to say, having this ability to create a new instance without the time it takes to reinstall SQL Express etc. would greatly assist me for the deployment of my application and it's installer. If makes any difference to anyone, I'm using a combination of NSIS and Advanced Installer for this installation project. | After months/years of looking into this it appears it can't be done. Oh well, I guess I just reinstall each time I want a new instance. I guess it's because each instance is it's own service. |
150,250 | <p>I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it</p>
<pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)
BEGIN
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,
FROM
ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID
WHERE ShoppingCartItem.PurchID = @PurchID
EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity
IF @ErrorCode <> 0
BEGIN
Goto Cleanup
END
DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID
-- @@ROWCOUNT is 1 after this
END
</code></pre>
<p>Facts:</p>
<ol>
<li>There's only one or two records matching the first select-clause</li>
<li>RowCount from the DELETE statement indicates that it has been removed</li>
<li>The WHILE-clause will loop forever</li>
</ol>
<p>The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.</p>
<p>Why does it loop forever?</p>
<p><strong>Clarification</strong>: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged)
<strong>Clarification 2</strong>: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.</p>
<p><strong>Update</strong>: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.</p>
<p><strong>Update clarification</strong>: <a href="https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400">brien</a> pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand</p>
| [
{
"answer_id": 150267,
"author": "Alex Fort",
"author_id": 12624,
"author_profile": "https://Stackoverflow.com/users/12624",
"pm_score": 0,
"selected": false,
"text": "<p>Obviously, something is not being deleted or modified where it should. If the condition is still the same on the next iteration, it's going to keep going.</p>\n\n<p>Also, you're comparing @TmpShoppingCartItemID, and not @PurchID. I can see how these could be different, and you could delete a different row than the one that's being checked for in the while statement.</p>\n"
},
{
"answer_id": 150289,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": -1,
"selected": false,
"text": "<p>I not sure if I understand the problem, but in the select clause it's making an inner join with another table. That join can cause to get no records and then the delete fails. Try using a left join.</p>\n"
},
{
"answer_id": 150295,
"author": "Adam Hughes",
"author_id": 3863,
"author_profile": "https://Stackoverflow.com/users/3863",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a record in ShoppingCartItem with that @PurchID where the GFSID is not in the GoodsForSale table? That would explain why the EXISTS returns true, but there are no more records to delete.</p>\n"
},
{
"answer_id": 150297,
"author": "brien",
"author_id": 4219,
"author_profile": "https://Stackoverflow.com/users/4219",
"pm_score": 3,
"selected": true,
"text": "<p>Are you operating in explicit or implicit <a href=\"http://doc.ddart.net/mssql/sql70/ta-tz_8.htm\" rel=\"nofollow noreferrer\">transaction mode</a>?</p>\n\n<p>Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements.</p>\n\n<pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)\nBEGIN\n SELECT TOP 1 \n @TmpGFSID = ShoppingCartItem.GFSID, \n @TmpQuantity = ShoppingCartItem.Quantity,\n @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,\n FROM\n ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID\n WHERE ShoppingCartItem.PurchID = @PurchID\n\n EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity\n IF @ErrorCode <> 0\n BEGIN\n Goto Cleanup \n END\n\n BEGIN TRANSACTION delete\n\n DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID\n -- @@ROWCOUNT is 1 after this\n\n COMMIT TRANSACTION delete\nEND\n</code></pre>\n\n<p><strong>Clarification:</strong> The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful.</p>\n\n<p>In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to <strong>really</strong> make the changes.</p>\n"
},
{
"answer_id": 150534,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "<p>If the above comments did not help you so far, I propose adding / replacing:</p>\n\n<pre><code>DECLARE Old@ShoppingCartItemID INT\n\nSET @OldShoppingCartItemID = 0\n\nWHILE EXISTS (SELECT ... WHERE ShoppingCartItemID > @ShoppingCartItemID)\n\nSELECT TOP 1 WHERE ShoppingCartItemID > @OldShoppingCartItemID ORDER BY ShoppingCartItemID \n\nSET @OldShoppingCartItemID = @TmpShoppingCartItemID\n</code></pre>\n"
},
{
"answer_id": 150883,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<pre><code>FROM\n ShoppingCartItem\n INNER JOIN\n GoodsForSale\n on ShoppingCartItem.GFSID = GoodsForSale.GFSID\n</code></pre>\n\n<p>Oops, your join brings the result set down to zero rows.</p>\n\n<pre><code> SELECT TOP 1\n @TmpGFSID = ShoppingCartItem.GFSID,\n @TmpQuantity = ShoppingCartItem.Quantity,\n @TmpShoppingCartItemID =\n ShoppingCartItem.ShoppingCartItemID\n</code></pre>\n\n<p>Oops, you used multi-assignment against a set with no rows. This causes the variables to remain unchanged (they will have the same value that they had last time through the loop). The variables do NOT get assigned to null in this case.</p>\n\n<p>If you put this code at the start of the loop, it will (correctly) fail faster:</p>\n\n<pre><code> SELECT\n @TmpGFSID = null,\n @TmpQuantity = null,\n @TmpShoppingCartItemID = null\n</code></pre>\n\n<p>If you change your code to fetch a key (without joining) and then fetching the related data by key in a second query, you'll win.</p>\n"
},
{
"answer_id": 193889,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 0,
"selected": false,
"text": "<p>If there are any shopping cart items that do not exist in the GoodsForSale table then this will spin into an infinite loop. </p>\n\n<p>Try changing your exists statement to take account of that </p>\n\n<pre><code>(SELECT * FROM ShoppingCartItem WHERE JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID where ShoppingCartItem.PurchID = @PurchID)\n</code></pre>\n\n<p>Or better still, rewriting this so it does not require a loop. Looping like this is an infinite loop waiting to happen. You should replace with set based operations and a transaction. </p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2114/"
]
| I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it
```
WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)
BEGIN
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,
FROM
ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID
WHERE ShoppingCartItem.PurchID = @PurchID
EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity
IF @ErrorCode <> 0
BEGIN
Goto Cleanup
END
DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID
-- @@ROWCOUNT is 1 after this
END
```
Facts:
1. There's only one or two records matching the first select-clause
2. RowCount from the DELETE statement indicates that it has been removed
3. The WHILE-clause will loop forever
The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.
Why does it loop forever?
**Clarification**: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged)
**Clarification 2**: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.
**Update**: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.
**Update clarification**: [brien](https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400) pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand | Are you operating in explicit or implicit [transaction mode](http://doc.ddart.net/mssql/sql70/ta-tz_8.htm)?
Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements.
```
WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)
BEGIN
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,
FROM
ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID
WHERE ShoppingCartItem.PurchID = @PurchID
EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity
IF @ErrorCode <> 0
BEGIN
Goto Cleanup
END
BEGIN TRANSACTION delete
DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID
-- @@ROWCOUNT is 1 after this
COMMIT TRANSACTION delete
END
```
**Clarification:** The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful.
In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to **really** make the changes. |
150,329 | <p>I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem. </p>
<p>How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:</p>
<pre><code>request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.
</code></pre>
<p>But that didn't work.</p>
<p>Any Ideas?</p>
<p>The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.</p>
| [
{
"answer_id": 150336,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>Update, you actually want to pick up:</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Request.QueryString(\"aspxerrorpath\")\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>Request.QueryString[\"aspxerrorpath\"];\n</code></pre>\n"
},
{
"answer_id": 150337,
"author": "LordHits",
"author_id": 8088,
"author_profile": "https://Stackoverflow.com/users/8088",
"pm_score": 2,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>Request.ServerVariables(\"HTTP_REFERER\");\n</code></pre>\n"
},
{
"answer_id": 150350,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>A lot of the links have changed, but they can be easily corrected by searching for patters in the url</p>\n</blockquote>\n\n<p>Rather than send your users to a 404, have you considered using url re-writes? This way your users (and search engines, if that's important to you in this case) will get a <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_status_codes\" rel=\"nofollow noreferrer\">301 or 302</a> rather than having to go through your 404 handler. It's usually quicker and less stressful on your servers to handle the rewrite at the url level than firing up your code and processing it there.</p>\n\n<p>Microsoft have released a <a href=\"http://iis.net/downloads/default.aspx?tabid=34&g=6&i=1691\" rel=\"nofollow noreferrer\">URL Rewrite Module for IIS 7</a>, and there's a decent introduction to it <a href=\"http://www.qwerksoft.com/products/iisrewrite/IISRewriteDocumentation.htm\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.sitepoint.com/article/guide-url-rewriting/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>For IIS 6, there's a <a href=\"http://www.sitepoint.com/blogs/2007/08/22/making-iis-60-play-with-urlrewriting/\" rel=\"nofollow noreferrer\">good intro here</a> to getting URL rewriting working with it, slightly different than IIS7.</p>\n\n<p>An example rewrite rule would be</p>\n\n<pre><code># $1 will contain the contents of (.*) - everything after new-dir/\nRewriteRule /new-dir/(.*) /find_old_page.asp?code=$1 \n</code></pre>\n\n<blockquote>\n <p>there are a few hundred pages, so no one is keen on spending the time to create the 301's</p>\n</blockquote>\n\n<p>The beauty of rewrite rules is that you don't need to list to explicitly list all of your pages, but can write rules which follow the same pattern. We had to do something similar to this recently, and it's surprising how many of the moved urls could be handled by a couple of simple rules.</p>\n"
},
{
"answer_id": 150363,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of using a 404 page, I think the proper thing to do would be to redirect with a <a href=\"http://en.wikipedia.org/wiki/HTTP_301\" rel=\"nofollow noreferrer\">301 - Moved Permanently</a> code.</p>\n"
},
{
"answer_id": 150460,
"author": "DougN",
"author_id": 7442,
"author_profile": "https://Stackoverflow.com/users/7442",
"pm_score": 3,
"selected": true,
"text": "<p>I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward.</p>\n\n<pre><code>//did the error go to a .ASP page? If so, append x (for .aspx) and \n//issue a 301 permanently moved\n//when we get an error, the querystring will be \"404;<complete original URL>\"\nstring targetPage = Request.RawUrl.Substring(Request.FilePath.Length);\n\nif((null == targetPage) || (targetPage.Length == 0))\n targetPage = \"[home page]\";\nelse\n{\n //find the original URL\n if(targetPage[0] == '?')\n {\n if(-1 != targetPage.IndexOf(\"?aspxerrorpath=\"))\n targetPage = targetPage.Substring(15); // ?aspxerrorpath=\n else\n targetPage = targetPage.Substring(5); // ?404;\n }\n else\n {\n if(-1 != targetPage.IndexOf(\"errorpath=\"))\n targetPage = targetPage.Substring(14); // aspxerrorpath=\n else\n targetPage = targetPage.Substring(4); // 404;\n }\n } \n\n string upperTarget = targetPage.ToUpper();\n if((-1 == upperTarget.IndexOf(\".ASPX\")) && (-1 != upperTarget.IndexOf(\".ASP\")))\n {\n //this is a request for an .ASP page - permanently redirect to .aspx\n targetPage = upperTarget.Replace(\".ASP\", \".ASPX\");\n //issue 301 redirect\n Response.Status = \"301 Moved Permanently\"; \n Response.AddHeader(\"Location\",targetPage);\n Response.End();\n }\n\n if(-1 != upperTarget.IndexOf(\"ORDER\"))\n {\n //going to old order page -- forward to new page\n Response.Redirect(WebRoot + \"/order.aspx\");\n Response.End();\n }\n</code></pre>\n"
},
{
"answer_id": 150525,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": "<p>Here's what we do on init on our 404 pages:</p>\n\n<pre><code>Dim AttemptedUrl As String = Request.QueryString(\"aspxerrorpath\")\nIf Len(AttemptedUrl) = 0 Then AttemptedUrl = Request.Url.Query\nAttemptedUrl = LCase(AttemptedUrl)\nCheckForRedirects(AttemptedUrl)\n</code></pre>\n\n<p>CheckforRedirects then has custom logic to match up old URLs with new URLs. </p>\n\n<p>I'd argue that this is the preferred approach (as opposed to 301s or URL rewriting) if you have enough information internally to match up a large number of URLs from the old system with the new system - e.g. if you have a table that matches up old IDs with new IDs or something similar. </p>\n\n<p>If there's a consistent pattern that you can use to map old URLs to new URLs with a regex, though, then URL rewriting would be the way to go.</p>\n"
},
{
"answer_id": 239867,
"author": "James Green",
"author_id": 31736,
"author_profile": "https://Stackoverflow.com/users/31736",
"pm_score": 1,
"selected": false,
"text": "<p>To build on the Rewrites suggestion, Umbraco already uses UrlRewriting.NET and new rewrites can be added to</p>\n\n<pre><code>\\config\\UrlRewriting.config\n</code></pre>\n\n<p>Hope this helps</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20483/"
]
| I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.
How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:
```
request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.
```
But that didn't work.
Any Ideas?
The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's. | I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward.
```
//did the error go to a .ASP page? If so, append x (for .aspx) and
//issue a 301 permanently moved
//when we get an error, the querystring will be "404;<complete original URL>"
string targetPage = Request.RawUrl.Substring(Request.FilePath.Length);
if((null == targetPage) || (targetPage.Length == 0))
targetPage = "[home page]";
else
{
//find the original URL
if(targetPage[0] == '?')
{
if(-1 != targetPage.IndexOf("?aspxerrorpath="))
targetPage = targetPage.Substring(15); // ?aspxerrorpath=
else
targetPage = targetPage.Substring(5); // ?404;
}
else
{
if(-1 != targetPage.IndexOf("errorpath="))
targetPage = targetPage.Substring(14); // aspxerrorpath=
else
targetPage = targetPage.Substring(4); // 404;
}
}
string upperTarget = targetPage.ToUpper();
if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP")))
{
//this is a request for an .ASP page - permanently redirect to .aspx
targetPage = upperTarget.Replace(".ASP", ".ASPX");
//issue 301 redirect
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",targetPage);
Response.End();
}
if(-1 != upperTarget.IndexOf("ORDER"))
{
//going to old order page -- forward to new page
Response.Redirect(WebRoot + "/order.aspx");
Response.End();
}
``` |
150,332 | <p>If I have variable of type <code>IEnumerable<List<string>></code> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an <code>IEnumerable<string></code>? </p>
| [
{
"answer_id": 150343,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "<p>SelectMany - i.e.</p>\n\n<pre><code> IEnumerable<List<string>> someList = ...;\n IEnumerable<string> all = someList.SelectMany(x => x);\n</code></pre>\n\n<p>For each item in someList, this then uses the lambda \"x => x\" to get an IEnumerable<T> for the inner items. In this case, each \"x\" is a List<T>, which is already IEnumerable<T>.</p>\n\n<p>These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):</p>\n\n<pre><code>static IEnumerable<TResult> SelectMany<TSource, TResult>(\n this IEnumerable<TSource> source,\n Func<TSource, IEnumerable<TResult>> selector) {\n\n foreach(TSource item in source) {\n foreach(TResult result in selector(item)) {\n yield return result;\n }\n }\n}\n</code></pre>\n\n<p>Although that is simplified somewhat.</p>\n"
},
{
"answer_id": 150348,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>Not exactly a single method call, but you should be able to write</p>\n\n<pre><code>var concatenated = from list in lists from item in list select item;\n</code></pre>\n\n<p>Where 'lists' is your <code>IEnumerable<List<string>></code> and concatenated is of type <code>IEnumerable<string></code>.</p>\n\n<p>(Technically this <em>is</em> a single method call to <code>SelectMany</code> - it just doesn't look like it was all I meant by the opening statement. Just wanted to clear that up in case anyone got confused or commented - I realised after I'd posted how it could have read).</p>\n"
},
{
"answer_id": 150388,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 0,
"selected": false,
"text": "<p>Make a simple method. No need for LINQ:</p>\n\n<pre><code>IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)\n{\n foreach (List<string> list in lists)\n foreach (string item in list)\n {\n yield return item;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 150402,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 0,
"selected": false,
"text": "<p>Using LINQ expression...</p>\n\n<pre><code>IEnumerable<string> myList = from a in (from b in myBigList\n select b)\n select a;\n</code></pre>\n\n<p>... works just fine. :-)</p>\n\n<p><code>b</code> will be an <code>IEnumerable<string></code> and <code>a</code> will be a <code>string</code>.</p>\n"
},
{
"answer_id": 150427,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another LINQ query comprehension.</p>\n\n<pre><code>IEnumerable<string> myStrings =\n from a in mySource\n from b in a\n select b;\n</code></pre>\n"
},
{
"answer_id": 150456,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code>myStrings.SelectMany(x => x)\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| If I have variable of type `IEnumerable<List<string>>` is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an `IEnumerable<string>`? | SelectMany - i.e.
```
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
```
For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.
These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):
```
static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector) {
foreach(TSource item in source) {
foreach(TResult result in selector(item)) {
yield return result;
}
}
}
```
Although that is simplified somewhat. |
150,333 | <p>We need to remotely create an Exchange 2007 distribution list from Asp.Net.</p>
<p>Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company.</p>
<p>Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API.</p>
<p>It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. </p>
<p>Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. </p>
<p>Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? </p>
| [
{
"answer_id": 150343,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "<p>SelectMany - i.e.</p>\n\n<pre><code> IEnumerable<List<string>> someList = ...;\n IEnumerable<string> all = someList.SelectMany(x => x);\n</code></pre>\n\n<p>For each item in someList, this then uses the lambda \"x => x\" to get an IEnumerable<T> for the inner items. In this case, each \"x\" is a List<T>, which is already IEnumerable<T>.</p>\n\n<p>These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):</p>\n\n<pre><code>static IEnumerable<TResult> SelectMany<TSource, TResult>(\n this IEnumerable<TSource> source,\n Func<TSource, IEnumerable<TResult>> selector) {\n\n foreach(TSource item in source) {\n foreach(TResult result in selector(item)) {\n yield return result;\n }\n }\n}\n</code></pre>\n\n<p>Although that is simplified somewhat.</p>\n"
},
{
"answer_id": 150348,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>Not exactly a single method call, but you should be able to write</p>\n\n<pre><code>var concatenated = from list in lists from item in list select item;\n</code></pre>\n\n<p>Where 'lists' is your <code>IEnumerable<List<string>></code> and concatenated is of type <code>IEnumerable<string></code>.</p>\n\n<p>(Technically this <em>is</em> a single method call to <code>SelectMany</code> - it just doesn't look like it was all I meant by the opening statement. Just wanted to clear that up in case anyone got confused or commented - I realised after I'd posted how it could have read).</p>\n"
},
{
"answer_id": 150388,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 0,
"selected": false,
"text": "<p>Make a simple method. No need for LINQ:</p>\n\n<pre><code>IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)\n{\n foreach (List<string> list in lists)\n foreach (string item in list)\n {\n yield return item;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 150402,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 0,
"selected": false,
"text": "<p>Using LINQ expression...</p>\n\n<pre><code>IEnumerable<string> myList = from a in (from b in myBigList\n select b)\n select a;\n</code></pre>\n\n<p>... works just fine. :-)</p>\n\n<p><code>b</code> will be an <code>IEnumerable<string></code> and <code>a</code> will be a <code>string</code>.</p>\n"
},
{
"answer_id": 150427,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another LINQ query comprehension.</p>\n\n<pre><code>IEnumerable<string> myStrings =\n from a in mySource\n from b in a\n select b;\n</code></pre>\n"
},
{
"answer_id": 150456,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code>myStrings.SelectMany(x => x)\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23583/"
]
| We need to remotely create an Exchange 2007 distribution list from Asp.Net.
Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company.
Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API.
It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work.
Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break.
Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? | SelectMany - i.e.
```
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
```
For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.
These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):
```
static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector) {
foreach(TSource item in source) {
foreach(TResult result in selector(item)) {
yield return result;
}
}
}
```
Although that is simplified somewhat. |
150,341 | <p>How do people approach mocking out TcpClient (or things like TcpClient)?</p>
<p>I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?</p>
| [
{
"answer_id": 150480,
"author": "Doron Yaacoby",
"author_id": 3389,
"author_profile": "https://Stackoverflow.com/users/3389",
"pm_score": 6,
"selected": true,
"text": "<p>When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the <a href=\"http://en.wikipedia.org/wiki/Adapter_pattern\" rel=\"noreferrer\">Adapter</a> design pattern.</p>\n\n<p>In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:</p>\n\n<pre><code>public interface ITcpClient\n{\n Stream GetStream(); \n // Anything you need here \n}\npublic class TcpClientAdapter: ITcpClient\n{\n private TcpClient wrappedClient;\n public TcpClientAdapter(TcpClient client)\n {\n wrappedClient = client;\n }\n\n public Stream GetStream()\n {\n return wrappedClient.GetStream();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 150561,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 2,
"selected": false,
"text": "<p>Using the Adapter pattern is most definitely the standard TDD approach to the problem. You could, however, also just create the other end of the TCP connection and have your test harness drive that.</p>\n\n<p>IMO the widespread use of adapter class obfuscates the most important parts of a design, and also tends to remove a lot of stuff from being tested that really ought to be tested in context. So the alternative is to build up your testing scaffolding to include more of the system under test. If you are building your tests from the ground up, you'll still achieve the ability to isolate the cause of a failure to a given class or function, it just won't be in isolation...</p>\n"
},
{
"answer_id": 150592,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 3,
"selected": false,
"text": "<p>I think @Hitchhiker is on the right track, but I also like to think about abstracting out things like that just a step further. </p>\n\n<p>I wouldn't mock out the TcpClient directly, because that would still tie you too closely to the underlying implementation even though you've written tests. That is, your implementation is tied to a TcpClient method specifically. Personally, I would try something like this:</p>\n\n<pre><code> [Test]\n public void TestInput(){\n\n NetworkInputSource mockInput = mocks.CreateMock<NetworkInputSource>();\n Consumer c = new Consumer(mockInput);\n\n c.ReadAll();\n // c.Read();\n // c.ReadLine();\n\n }\n\n public class TcpClientAdapter : NetworkInputSource\n {\n private TcpClient _client;\n public string ReadAll()\n { \n return new StreamReader(_tcpClient.GetStream()).ReadToEnd();\n }\n\n public string Read() { ... }\n public string ReadLine() { ... }\n }\n\n public interface NetworkInputSource\n {\n public string ReadAll(); \n public string Read();\n public string ReadLine();\n }\n</code></pre>\n\n<p>This implementation will decouple you from Tcp related details altogether (if that is a design goal), and you can even pipe in test input from a hard coded set of values, or a test input file. Very hand if you are on the road to testing your code for the long haul.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285/"
]
| How do people approach mocking out TcpClient (or things like TcpClient)?
I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this? | When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the [Adapter](http://en.wikipedia.org/wiki/Adapter_pattern) design pattern.
In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:
```
public interface ITcpClient
{
Stream GetStream();
// Anything you need here
}
public class TcpClientAdapter: ITcpClient
{
private TcpClient wrappedClient;
public TcpClientAdapter(TcpClient client)
{
wrappedClient = client;
}
public Stream GetStream()
{
return wrappedClient.GetStream();
}
}
``` |
150,355 | <p>Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?</p>
| [
{
"answer_id": 150369,
"author": "Chris Ballance",
"author_id": 1551,
"author_profile": "https://Stackoverflow.com/users/1551",
"pm_score": 2,
"selected": false,
"text": "<p>Windows Server 2003 and later lets you leverage the GetLogicalProcessorInformation function</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms683194.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms683194.aspx</a></p>\n"
},
{
"answer_id": 150379,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 4,
"selected": false,
"text": "<p>On Linux, you can read the /proc/cpuinfo file and count the cores.</p>\n"
},
{
"answer_id": 150380,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 3,
"selected": false,
"text": "<p>You probably won't be able to get it in a platform independent way. Windows you get number of processors.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms724381(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32 System Information</a></p>\n"
},
{
"answer_id": 150393,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 8,
"selected": false,
"text": "<p>This functionality is part of the C++11 standard.</p>\n\n<pre><code>#include <thread>\n\nunsigned int nthreads = std::thread::hardware_concurrency();\n</code></pre>\n\n<p>For older compilers, you can use the <a href=\"http://www.boost.org/doc/libs/1_46_0/doc/html/thread.html\" rel=\"noreferrer\">Boost.Thread</a> library.</p>\n\n<pre><code>#include <boost/thread.hpp>\n\nunsigned int nthreads = boost::thread::hardware_concurrency();\n</code></pre>\n\n<p>In either case, <code>hardware_concurrency()</code> returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.</p>\n"
},
{
"answer_id": 150394,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "<p>On linux the best programmatic way as far as I know is to use</p>\n\n<pre><code>sysconf(_SC_NPROCESSORS_CONF)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sysconf(_SC_NPROCESSORS_ONLN)\n</code></pre>\n\n<p>These aren't standard, but are in my man page for Linux.</p>\n"
},
{
"answer_id": 150580,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 5,
"selected": false,
"text": "<p>If you have assembly-language access, you can use the CPUID instruction to get all sorts of information about the CPU. It's portable between operating systems, though you'll need to use manufacturer-specific information to determine how to find the number of cores. Here's <a href=\"http://www.intel.com/content/www/us/en/processors/processor-identification-cpuid-instruction-note.html\" rel=\"noreferrer\">a document that describes how to do it on Intel chips</a>, and page 11 of <a href=\"http://support.amd.com/us/Embedded_TechDocs/25481.pdf\" rel=\"noreferrer\">this one</a> describes the AMD specification.</p>\n"
},
{
"answer_id": 150971,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 11,
"selected": true,
"text": "<h1>C++11</h1>\n\n<pre><code>#include <thread>\n\n//may return 0 when not able to detect\nconst auto processor_count = std::thread::hardware_concurrency();\n</code></pre>\n\n<p>Reference: <a href=\"http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency\" rel=\"noreferrer\">std::thread::hardware_concurrency</a></p>\n\n<hr>\n\n<p>In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate <code>#ifdef</code> lines):</p>\n\n<ul>\n<li><h3>Win32</h3>\n\n<pre><code>SYSTEM_INFO sysinfo;\nGetSystemInfo(&sysinfo);\nint numCPU = sysinfo.dwNumberOfProcessors;\n</code></pre></li>\n<li><h3>Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)</h3>\n\n<pre><code>int numCPU = sysconf(_SC_NPROCESSORS_ONLN);\n</code></pre></li>\n<li><h3>FreeBSD, MacOS X, NetBSD, OpenBSD, etc.</h3>\n\n<pre><code>int mib[4];\nint numCPU;\nstd::size_t len = sizeof(numCPU); \n\n/* set the mib for hw.ncpu */\nmib[0] = CTL_HW;\nmib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;\n\n/* get the number of CPUs from the system */\nsysctl(mib, 2, &numCPU, &len, NULL, 0);\n\nif (numCPU < 1) \n{\n mib[1] = HW_NCPU;\n sysctl(mib, 2, &numCPU, &len, NULL, 0);\n if (numCPU < 1)\n numCPU = 1;\n}\n</code></pre></li>\n<li><h3>HPUX</h3>\n\n<pre><code>int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);\n</code></pre></li>\n<li><h3>IRIX</h3>\n\n<pre><code>int numCPU = sysconf(_SC_NPROC_ONLN);\n</code></pre></li>\n<li><h3>Objective-C (Mac OS X >=10.5 or iOS)</h3>\n\n<pre><code>NSUInteger a = [[NSProcessInfo processInfo] processorCount];\nNSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 195869,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 4,
"selected": false,
"text": "<p>Note that \"number of cores\" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.</p>\n\n<p>The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...</p>\n"
},
{
"answer_id": 197200,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://openmp.org/\" rel=\"noreferrer\">OpenMP</a> is supported on many platforms (including Visual Studio 2005) and it offers a </p>\n\n<pre><code>int omp_get_num_procs();\n</code></pre>\n\n<p>function that returns the number of processors/cores available at the time of call.</p>\n"
},
{
"answer_id": 197917,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 3,
"selected": false,
"text": "<p>One more Windows recipe: use system-wide environment variable <code>NUMBER_OF_PROCESSORS</code>:</p>\n\n<pre><code>printf(\"%d\\n\", atoi(getenv(\"NUMBER_OF_PROCESSORS\")));\n</code></pre>\n"
},
{
"answer_id": 384806,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>you can use WMI in .net too but you're then dependent on the wmi service running\netc. Sometimes it works locally, but then fail when the same code is run on servers.\nI believe that's a namespace issue, related to the \"names\" whose values you're reading.</p>\n"
},
{
"answer_id": 1116776,
"author": "gauss256",
"author_id": 80309,
"author_profile": "https://Stackoverflow.com/users/80309",
"pm_score": 2,
"selected": false,
"text": "<p>OS X alternative: The solution described earlier based on [[NSProcessInfo processInfo] processorCount] is only available on OS X 10.5.0, according to the docs. For earlier versions of OS X, use the Carbon function MPProcessors().</p>\n\n<p>If you're a Cocoa programmer, don't be freaked out by the fact that this is Carbon. You just need to need to add the Carbon framework to your Xcode project and MPProcessors() will be available.</p>\n"
},
{
"answer_id": 3006416,
"author": "Dirk-Jan Kroon",
"author_id": 362493,
"author_profile": "https://Stackoverflow.com/users/362493",
"pm_score": 5,
"selected": false,
"text": "<p>(Almost) Platform Independent function in c-code</p>\n\n<pre><code>#ifdef _WIN32\n#include <windows.h>\n#elif MACOS\n#include <sys/param.h>\n#include <sys/sysctl.h>\n#else\n#include <unistd.h>\n#endif\n\nint getNumCores() {\n#ifdef WIN32\n SYSTEM_INFO sysinfo;\n GetSystemInfo(&sysinfo);\n return sysinfo.dwNumberOfProcessors;\n#elif MACOS\n int nm[2];\n size_t len = 4;\n uint32_t count;\n\n nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;\n sysctl(nm, 2, &count, &len, NULL, 0);\n\n if(count < 1) {\n nm[1] = HW_NCPU;\n sysctl(nm, 2, &count, &len, NULL, 0);\n if(count < 1) { count = 1; }\n }\n return count;\n#else\n return sysconf(_SC_NPROCESSORS_ONLN);\n#endif\n}\n</code></pre>\n"
},
{
"answer_id": 5382362,
"author": "Chris",
"author_id": 385711,
"author_profile": "https://Stackoverflow.com/users/385711",
"pm_score": 3,
"selected": false,
"text": "<p>Unrelated to C++, but on Linux I usually do:</p>\n\n<pre><code>grep processor /proc/cpuinfo | wc -l\n</code></pre>\n\n<p>Handy for scripting languages like bash/perl/python/ruby.</p>\n"
},
{
"answer_id": 6752739,
"author": "Akhil",
"author_id": 249560,
"author_profile": "https://Stackoverflow.com/users/249560",
"pm_score": 2,
"selected": false,
"text": "<p>hwloc (http://www.open-mpi.org/projects/hwloc/) is worth looking at. Though requires another library integration into your code but it can provide all the information about your processor (number of cores, the topology, etc.)</p>\n"
},
{
"answer_id": 12239411,
"author": "sezero",
"author_id": 1642354,
"author_profile": "https://Stackoverflow.com/users/1642354",
"pm_score": 3,
"selected": false,
"text": "<p>More on OS X: <code>sysconf(_SC_NPROCESSORS_ONLN)</code> is available only versions >= 10.5, not 10.4.</p>\n\n<p>An alternative is the <code>HW_AVAILCPU/sysctl()</code> BSD code which is available on versions >= 10.2.</p>\n"
},
{
"answer_id": 24127920,
"author": "P.P",
"author_id": 1275169,
"author_profile": "https://Stackoverflow.com/users/1275169",
"pm_score": 2,
"selected": false,
"text": "<p>On Linux, it's may not be safe to to use <code>_SC_NPROCESSORS_ONLN</code> as it's not part of POSIX standard and the <a href=\"http://man7.org/linux/man-pages/man3/sysconf.3.html\" rel=\"nofollow\">sysconf</a> manual states as much. So there's a possibility that <code>_SC_NPROCESSORS_ONLN</code> may not be present:</p>\n\n<pre><code> These values also exist, but may not be standard.\n\n [...] \n\n - _SC_NPROCESSORS_CONF\n The number of processors configured. \n - _SC_NPROCESSORS_ONLN\n The number of processors currently online (available).\n</code></pre>\n\n<p>A simple approach would be to read <code>/proc/stat</code> or <code>/proc/cpuinfo</code> and count them:</p>\n\n<pre><code>#include<unistd.h>\n#include<stdio.h>\n\nint main(void)\n{\nchar str[256];\nint procCount = -1; // to offset for the first entry\nFILE *fp;\n\nif( (fp = fopen(\"/proc/stat\", \"r\")) )\n{\n while(fgets(str, sizeof str, fp))\n if( !memcmp(str, \"cpu\", 3) ) procCount++;\n}\n\nif ( procCount == -1) \n{ \nprintf(\"Unable to get proc count. Defaulting to 2\");\nprocCount=2;\n}\n\nprintf(\"Proc Count:%d\\n\", procCount);\nreturn 0;\n}\n</code></pre>\n\n<p>Using <code>/proc/cpuinfo</code>:</p>\n\n<pre><code>#include<unistd.h>\n#include<stdio.h>\n\nint main(void)\n{\nchar str[256];\nint procCount = 0;\nFILE *fp;\n\nif( (fp = fopen(\"/proc/cpuinfo\", \"r\")) )\n{\n while(fgets(str, sizeof str, fp))\n if( !memcmp(str, \"processor\", 9) ) procCount++;\n}\n\nif ( !procCount ) \n{ \nprintf(\"Unable to get proc count. Defaulting to 2\");\nprocCount=2;\n}\n\nprintf(\"Proc Count:%d\\n\", procCount);\nreturn 0;\n}\n</code></pre>\n\n<hr>\n\n<p>The same approach in shell using grep:</p>\n\n<pre><code>grep -c ^processor /proc/cpuinfo\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>grep -c ^cpu /proc/stat # subtract 1 from the result\n</code></pre>\n"
},
{
"answer_id": 38049568,
"author": "irrlicht_ist_toll",
"author_id": 6059395,
"author_profile": "https://Stackoverflow.com/users/6059395",
"pm_score": 2,
"selected": false,
"text": "<p>For Win32:</p>\n\n<p>While GetSystemInfo() gets you the number of <em>logical</em> processors, use\n<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/dd405488(v=vs.85).aspx\" rel=\"nofollow\">GetLogicalProcessorInformationEx()</a>\n to get the number of <em>physical</em> processors.</p>\n"
},
{
"answer_id": 44247223,
"author": "Matthias",
"author_id": 1731200,
"author_profile": "https://Stackoverflow.com/users/1731200",
"pm_score": 3,
"selected": false,
"text": "<h2>Windows (x64 and Win32) and C++11</h2>\n<p><strong>The number of groups of logical processors sharing a single processor core.</strong> (Using <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/dd405488(v=vs.85).aspx\" rel=\"noreferrer\">GetLogicalProcessorInformationEx</a>, see <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms683194(v=vs.85).aspx\" rel=\"noreferrer\">GetLogicalProcessorInformation</a> as well)</p>\n<pre><code>size_t NumberOfPhysicalCores() noexcept {\n\n DWORD length = 0;\n const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);\n assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);\n\n std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);\n const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = \n reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());\n\n const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);\n assert(result_second != FALSE);\n\n size_t nb_physical_cores = 0;\n size_t offset = 0;\n do {\n const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =\n reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);\n offset += current_info->Size;\n ++nb_physical_cores;\n } while (offset < length);\n \n return nb_physical_cores;\n}\n</code></pre>\n<p><em>Note that the implementation of <code>NumberOfPhysicalCores</code> is IMHO far from trivial (i.e. "use <code>GetLogicalProcessorInformation</code> or <code>GetLogicalProcessorInformationEx</code>"). Instead it is rather subtle if one reads the documentation (explicitly present for <code>GetLogicalProcessorInformation</code> and implicitly present for <code>GetLogicalProcessorInformationEx</code>) at MSDN.</em></p>\n<p><strong>The number of logical processors.</strong> (Using <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724381(v=vs.85).aspx\" rel=\"noreferrer\">GetSystemInfo</a>)</p>\n<pre><code>size_t NumberOfSystemCores() noexcept {\n SYSTEM_INFO system_info;\n ZeroMemory(&system_info, sizeof(system_info));\n \n GetSystemInfo(&system_info);\n \n return static_cast< size_t >(system_info.dwNumberOfProcessors);\n}\n</code></pre>\n<p><em>Note that both methods can easily be converted to C/C++98/C++03.</em></p>\n"
},
{
"answer_id": 69214269,
"author": "Arran Cudbard-Bell",
"author_id": 2117998,
"author_profile": "https://Stackoverflow.com/users/2117998",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-c prettyprint-override\"><code>#include <stdint.h>\n\n#if defined(__APPLE__) || defined(__FreeBSD__)\n#include <sys/sysctl.h>\n\nuint32_t num_physical_cores(void)\n{\n uint32_t num_cores = 0;\n size_t num_cores_len = sizeof(num_cores);\n\n sysctlbyname("hw.physicalcpu", &num_cores, &num_cores_len, 0, 0);\n\n return num_cores;\n}\n#elif defined(__linux__)\n#include <unistd.h>\n#include <stdio.h>\nuint32_t num_physical_cores(void)\n{\n uint32_t lcores = 0, tsibs = 0;\n\n char buff[32];\n char path[64];\n\n for (lcores = 0;;lcores++) {\n FILE *cpu;\n\n snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u/topology/thread_siblings_list", lcores);\n\n cpu = fopen(path, "r");\n if (!cpu) break;\n\n while (fscanf(cpu, "%[0-9]", buff)) {\n tsibs++;\n if (fgetc(cpu) != ',') break;\n }\n\n fclose(cpu);\n }\n\n return lcores / (tsibs / lcores);\n}\n#else\n#error Unrecognized operating system\n#endif\n</code></pre>\n<p>This should return the number of physical cores on the system. This is different than the number of logical cores which most of these answers provide. If you're looking to size a thread pool which performs no blocking I/O, and doesn't sleep, then you want to use the number of physical cores, not the number of logical (hyper threading) cores.</p>\n<p>This answer only provides implementations for Linux and the BSDs.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5066/"
]
| Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/\*nix/Mac)? | C++11
=====
```
#include <thread>
//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();
```
Reference: [std::thread::hardware\_concurrency](http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency)
---
In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate `#ifdef` lines):
* ### Win32
```
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
int numCPU = sysinfo.dwNumberOfProcessors;
```
* ### Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)
```
int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
```
* ### FreeBSD, MacOS X, NetBSD, OpenBSD, etc.
```
int mib[4];
int numCPU;
std::size_t len = sizeof(numCPU);
/* set the mib for hw.ncpu */
mib[0] = CTL_HW;
mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;
/* get the number of CPUs from the system */
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
{
mib[1] = HW_NCPU;
sysctl(mib, 2, &numCPU, &len, NULL, 0);
if (numCPU < 1)
numCPU = 1;
}
```
* ### HPUX
```
int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
```
* ### IRIX
```
int numCPU = sysconf(_SC_NPROC_ONLN);
```
* ### Objective-C (Mac OS X >=10.5 or iOS)
```
NSUInteger a = [[NSProcessInfo processInfo] processorCount];
NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];
``` |
150,375 | <p>What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? </p>
| [
{
"answer_id": 150376,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 6,
"selected": true,
"text": "<pre><code>import pdb; pdb.set_trace()\n</code></pre>\n\n<p>See <a href=\"http://jjinux.blogspot.com/2007/08/python-coding-in-debugger-for-beginners.html\" rel=\"noreferrer\">Python: Coding in the Debugger for Beginners</a> for this and more helpful hints.</p>\n"
},
{
"answer_id": 59365802,
"author": "Adam Baxter",
"author_id": 229631,
"author_profile": "https://Stackoverflow.com/users/229631",
"pm_score": 4,
"selected": false,
"text": "<p>As of Python 3.7, you can use <code>breakpoint()</code> - <a href=\"https://docs.python.org/3/library/functions.html#breakpoint\" rel=\"noreferrer\">https://docs.python.org/3/library/functions.html#breakpoint</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
| What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? | ```
import pdb; pdb.set_trace()
```
See [Python: Coding in the Debugger for Beginners](http://jjinux.blogspot.com/2007/08/python-coding-in-debugger-for-beginners.html) for this and more helpful hints. |
150,446 | <p>I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?</p>
| [
{
"answer_id": 150449,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the GLPaint example.</p>\n\n<p><a href=\"http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html</a></p>\n"
},
{
"answer_id": 150721,
"author": "Dave Verwer",
"author_id": 4496,
"author_profile": "https://Stackoverflow.com/users/4496",
"pm_score": 4,
"selected": false,
"text": "<p>You need to check the accelerometer via accelerometer:didAccelerate: method which is part of the UIAccelerometerDelegate protocol and check whether the values go over a threshold for the amount of movement needed for a shake.</p>\n\n<p>There is decent sample code in the accelerometer:didAccelerate: method right at the bottom of AppController.m in the GLPaint example which is available on the iPhone developer site.</p>\n"
},
{
"answer_id": 159610,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 7,
"selected": false,
"text": "<p>From my <a href=\"http://infinite-labs.net/diceshaker/\" rel=\"noreferrer\">Diceshaker</a> application:</p>\n\n<pre><code>// Ensures the shake is strong enough on at least two axes before declaring it a shake.\n// \"Strong enough\" means \"greater than a client-supplied threshold\" in G's.\nstatic BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {\n double\n deltaX = fabs(last.x - current.x),\n deltaY = fabs(last.y - current.y),\n deltaZ = fabs(last.z - current.z);\n\n return\n (deltaX > threshold && deltaY > threshold) ||\n (deltaX > threshold && deltaZ > threshold) ||\n (deltaY > threshold && deltaZ > threshold);\n}\n\n@interface L0AppDelegate : NSObject <UIApplicationDelegate> {\n BOOL histeresisExcited;\n UIAcceleration* lastAcceleration;\n}\n\n@property(retain) UIAcceleration* lastAcceleration;\n\n@end\n\n@implementation L0AppDelegate\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application {\n [UIAccelerometer sharedAccelerometer].delegate = self;\n}\n\n- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n\n if (self.lastAcceleration) {\n if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {\n histeresisExcited = YES;\n\n /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */\n\n } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {\n histeresisExcited = NO;\n }\n }\n\n self.lastAcceleration = acceleration;\n}\n\n// and proper @synthesize and -dealloc boilerplate code\n\n@end\n</code></pre>\n\n<p>The histeresis prevents the shake event from triggering multiple times until the user stops the shake.</p>\n"
},
{
"answer_id": 278523,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I came across this post looking for a \"shaking\" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more \"shaking action\" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:</p>\n\n<pre><code>- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n if (self.lastAcceleration) {\n if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {\n //Shaking here, DO stuff.\n shakeCount = 0;\n } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {\n shakeCount = shakeCount + 5;\n }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {\n if (shakeCount > 0) {\n shakeCount--;\n }\n }\n }\n self.lastAcceleration = acceleration;\n}\n\n- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {\n double\n deltaX = fabs(last.x - current.x),\n deltaY = fabs(last.y - current.y),\n deltaZ = fabs(last.z - current.z);\n\n return\n (deltaX > threshold && deltaY > threshold) ||\n (deltaX > threshold && deltaZ > threshold) ||\n (deltaY > threshold && deltaZ > threshold);\n}\n</code></pre>\n\n<p>PS:\nI've set the update interval to 1/15th of a second.</p>\n\n<pre><code>[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];\n</code></pre>\n"
},
{
"answer_id": 671623,
"author": "Benjamin Ortuzar",
"author_id": 71560,
"author_profile": "https://Stackoverflow.com/users/71560",
"pm_score": 3,
"selected": false,
"text": "<p>This is the basic delegate code you need:</p>\n\n<pre><code>#define kAccelerationThreshold 2.2\n\n#pragma mark -\n#pragma mark UIAccelerometerDelegate Methods\n - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration \n { \n if (fabsf(acceleration.x) > kAccelerationThreshold || fabsf(acceleration.y) > kAccelerationThreshold || fabsf(acceleration.z) > kAccelerationThreshold) \n [self myShakeMethodGoesHere]; \n }\n</code></pre>\n\n<p>Also set the in the appropriate code in the Interface. i.e:</p>\n\n<p>@interface MyViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, UIAccelerometerDelegate> </p>\n"
},
{
"answer_id": 1111983,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 9,
"selected": true,
"text": "<p>In 3.0, there's now an easier way - hook into the new motion events.</p>\n\n<p>The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:</p>\n\n<pre><code>@implementation ShakingView\n\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if ( event.subtype == UIEventSubtypeMotionShake )\n {\n // Put in code here to handle shake\n }\n\n if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )\n [super motionEnded:motion withEvent:event];\n}\n\n- (BOOL)canBecomeFirstResponder\n{ return YES; }\n\n@end\n</code></pre>\n\n<p>You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).</p>\n\n<p>In the view controller, you want to set this view to become first responder:</p>\n\n<pre><code>- (void) viewWillAppear:(BOOL)animated\n{\n [shakeView becomeFirstResponder];\n [super viewWillAppear:animated];\n}\n- (void) viewWillDisappear:(BOOL)animated\n{\n [shakeView resignFirstResponder];\n [super viewWillDisappear:animated];\n}\n</code></pre>\n\n<p>Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns! </p>\n\n<p>This method works even if you set applicationSupportsShakeToEdit to NO.</p>\n"
},
{
"answer_id": 1294476,
"author": "Newtz",
"author_id": 158522,
"author_profile": "https://Stackoverflow.com/users/158522",
"pm_score": 3,
"selected": false,
"text": "<p>Sorry to post this as an answer rather than a comment but as you can see I'm new to Stack Overflow and so I'm not yet reputable enough to post comments!</p>\n\n<p>Anyway I second @cire about making sure to set the first responder status once the view is part of the view hierarchy. So setting first responder status in your view controllers <code>viewDidLoad</code> method won't work for example. And if you're unsure as to whether it is working <code>[view becomeFirstResponder]</code> returns you a boolean that you can test.</p>\n\n<p>Another point: you <strong>can</strong> use a view controller to capture the shake event if you don't want to create a UIView subclass unnecessarily. I know it's not that much hassle but still the option is there. Just move the code snippets that Kendall put into the UIView subclass into your controller and send the <code>becomeFirstResponder</code> and <code>resignFirstResponder</code> messages to <code>self</code> instead of the UIView subclass.</p>\n"
},
{
"answer_id": 1351486,
"author": "Joe D'Andrea",
"author_id": 126660,
"author_profile": "https://Stackoverflow.com/users/126660",
"pm_score": 7,
"selected": false,
"text": "<p>First, Kendall's July 10th answer is spot-on.</p>\n\n<p>Now ... I wanted to do something similar (in iPhone OS 3.0+), only in my case I wanted it app-wide so I could alert <em>various</em> parts of the app when a shake occurred. Here's what I ended up doing.</p>\n\n<p>First, I subclassed <strong>UIWindow</strong>. This is easy peasy. Create a new class file with an interface such as <code>MotionWindow : UIWindow</code> (feel free to pick your own, natch). Add a method like so:</p>\n\n<pre><code>- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {\n if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {\n [[NSNotificationCenter defaultCenter] postNotificationName:@\"DeviceShaken\" object:self];\n }\n}\n</code></pre>\n\n<p>Change <code>@\"DeviceShaken\"</code> to the notification name of your choice. Save the file.</p>\n\n<p>Now, if you use a MainWindow.xib (stock Xcode template stuff), go in there and change the class of your Window object from <strong>UIWindow</strong> to <strong>MotionWindow</strong> or whatever you called it. Save the xib. If you set up <strong>UIWindow</strong> programmatically, use your new Window class there instead.</p>\n\n<p>Now your app is using the specialized <strong>UIWindow</strong> class. Wherever you want to be told about a shake, sign up for them notifications! Like this:</p>\n\n<pre><code>[[NSNotificationCenter defaultCenter] addObserver:self\nselector:@selector(deviceShaken) name:@\"DeviceShaken\" object:nil];\n</code></pre>\n\n<p>To remove yourself as an observer:</p>\n\n<pre><code>[[NSNotificationCenter defaultCenter] removeObserver:self];\n</code></pre>\n\n<p>I put mine in <strong>viewWillAppear:</strong> and <strong>viewWillDisappear:</strong> where View Controllers are concerned. Be sure your response to the shake event knows if it is \"already in progress\" or not. Otherwise, if the device is shaken twice in succession, you'll have a li'l traffic jam. This way you can ignore other notifications until you're truly done responding to the original notification.</p>\n\n<p>Also: You may choose to cue off of <strong>motionBegan</strong> vs. <strong>motionEnded</strong>. It's up to you. In my case, the effect always needs to take place <em>after</em> the device is at rest (vs. when it starts shaking), so I use <strong>motionEnded</strong>. Try both and see which one makes more sense ... or detect/notify for both!</p>\n\n<p>One more (curious?) observation here: Notice there's no sign of first responder management in this code. I've only tried this with Table View Controllers so far and everything seems to work quite nicely together! I can't vouch for other scenarios though.</p>\n\n<p>Kendall, et. al - can anyone speak to why this might be so for <strong>UIWindow</strong> subclasses? Is it because the window is at the top of the food chain?</p>\n"
},
{
"answer_id": 2405692,
"author": "Eran Talmor",
"author_id": 2944908,
"author_profile": "https://Stackoverflow.com/users/2944908",
"pm_score": 7,
"selected": false,
"text": "<p>I finally made it work using code examples from this <a href=\"http://www.mobileorchard.com/new-in-iphone-30-tutorial-series-part-1-shake-to-undoredo-nsundomanager/\" rel=\"noreferrer\">Undo/Redo Manager Tutorial</a>.<br/>\nThis is exactly what you need to do:</p>\n\n<p></p>\n\n<p><li>Set the <b><i>applicationSupportsShakeToEdit</i></b> property in the App's Delegate:</li></p>\n\n<pre><code>\n - (void)applicationDidFinishLaunching:(UIApplication *)application {\n\n application.applicationSupportsShakeToEdit = YES;\n\n [window addSubview:viewController.view];\n [window makeKeyAndVisible];\n}\n</code></pre>\n\n<p><li>Add/Override <b><i>canBecomeFirstResponder</i></b>, <b><i>viewDidAppear:</i></b> and <b><i>viewWillDisappear:</i></b> methods in your View Controller:</li></p>\n\n<pre><code>\n-(BOOL)canBecomeFirstResponder {\n return YES;\n}\n\n-(void)viewDidAppear:(BOOL)animated {\n [super viewDidAppear:animated];\n [self becomeFirstResponder];\n}\n\n- (void)viewWillDisappear:(BOOL)animated {\n [self resignFirstResponder];\n [super viewWillDisappear:animated];\n}\n</code></pre>\n\n<p><li>Add the <b><i>motionEnded</i></b> method to your View Controller:</li></p>\n\n<pre><code>\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake)\n {\n // your code\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12895399,
"author": "Himanshu Mahajan",
"author_id": 1624283,
"author_profile": "https://Stackoverflow.com/users/1624283",
"pm_score": 3,
"selected": false,
"text": "<p>Add Following methods in ViewController.m file, its working properly</p>\n\n<pre><code> -(BOOL) canBecomeFirstResponder\n {\n /* Here, We want our view (not viewcontroller) as first responder \n to receive shake event message */\n\n return YES;\n }\n\n -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n {\n if(event.subtype==UIEventSubtypeMotionShake)\n {\n // Code at shake event\n\n UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@\"Motion\" message:@\"Phone Vibrate\"delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles: nil];\n [alert show];\n [alert release];\n\n [self.view setBackgroundColor:[UIColor redColor]];\n }\n }\n - (void)viewDidAppear:(BOOL)animated\n {\n [super viewDidAppear:animated];\n [self becomeFirstResponder]; // View as first responder \n }\n</code></pre>\n"
},
{
"answer_id": 14998702,
"author": "Mashhadi",
"author_id": 339171,
"author_profile": "https://Stackoverflow.com/users/339171",
"pm_score": 1,
"selected": false,
"text": "<p>Just use these three methods to do it </p>\n\n<pre><code>- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n</code></pre>\n\n<p>for details you may check a complete example code over <a href=\"http://www.mindyourcode.com/ios/how-to-detect-shake-motion-gesture-on-you-iphone-or-ipad/\" rel=\"nofollow\">there</a> </p>\n"
},
{
"answer_id": 24713067,
"author": "mxcl",
"author_id": 6444,
"author_profile": "https://Stackoverflow.com/users/6444",
"pm_score": 2,
"selected": false,
"text": "<p>Easiest solution is to derive a new root window for your application:</p>\n\n<pre><code>@implementation OMGWindow : UIWindow\n\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {\n if (event.type == UIEventTypeMotion && motion == UIEventSubtypeMotionShake) {\n // via notification or something \n }\n}\n@end\n</code></pre>\n\n<p>Then in your application delegate:</p>\n\n<pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {\n self.window = [[OMGWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];\n //…\n}\n</code></pre>\n\n<p>If you are using a Storyboard, this may be trickier, I don’t know the code you will need in the application delegate precisely.</p>\n"
},
{
"answer_id": 29035489,
"author": "Dennis",
"author_id": 1770453,
"author_profile": "https://Stackoverflow.com/users/1770453",
"pm_score": 3,
"selected": false,
"text": "<p>First off, I know this is an old post, but it is still relevant, and I found that the two highest voted answers did not <strong>detect the shake as early as possible</strong>. This is how to do it:</p>\n\n<ol>\n<li>Link CoreMotion to your project in the target's build phases:\n<img src=\"https://i.stack.imgur.com/MuLgk.png\" alt=\"CoreMotion\"></li>\n<li><p>In your ViewController:</p>\n\n<pre><code>- (BOOL)canBecomeFirstResponder {\n return YES;\n}\n\n- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake) {\n // Shake detected.\n }\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 29759696,
"author": "nhgrif",
"author_id": 2792531,
"author_profile": "https://Stackoverflow.com/users/2792531",
"pm_score": 4,
"selected": false,
"text": "<p>In iOS 8.3 (perhaps earlier) with Swift, it's as simple as overriding the <code>motionBegan</code> or <code>motionEnded</code> methods in your view controller:</p>\n\n<pre><code>class ViewController: UIViewController {\n override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {\n println(\"started shaking!\")\n }\n\n override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {\n println(\"ended shaking!\")\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46138429,
"author": "user3069232",
"author_id": 3069232,
"author_profile": "https://Stackoverflow.com/users/3069232",
"pm_score": 1,
"selected": false,
"text": "<p>A swiftease version based on the very first answer! </p>\n\n<pre><code>override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {\n if ( event?.subtype == .motionShake )\n {\n print(\"stop shaking me!\")\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46246551,
"author": "Mike",
"author_id": 3132984,
"author_profile": "https://Stackoverflow.com/users/3132984",
"pm_score": -1,
"selected": false,
"text": "<p>To enable this app-wide, I created a category on UIWindow:</p>\n\n<pre><code>@implementation UIWindow (Utils)\n\n- (BOOL)canBecomeFirstResponder\n{\n return YES;\n}\n\n- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake) {\n // Do whatever you want here...\n }\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 65879592,
"author": "Amit Baderia",
"author_id": 1737989,
"author_profile": "https://Stackoverflow.com/users/1737989",
"pm_score": 0,
"selected": false,
"text": "<p>In swift 5, this is how you can capture motion and check</p>\n<pre><code>override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {\n if motion == .motionShake \n {\n print("shaking")\n }\n}\n</code></pre>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944/"
]
| I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this? | In 3.0, there's now an easier way - hook into the new motion events.
The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:
```
@implementation ShakingView
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if ( event.subtype == UIEventSubtypeMotionShake )
{
// Put in code here to handle shake
}
if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
[super motionEnded:motion withEvent:event];
}
- (BOOL)canBecomeFirstResponder
{ return YES; }
@end
```
You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).
In the view controller, you want to set this view to become first responder:
```
- (void) viewWillAppear:(BOOL)animated
{
[shakeView becomeFirstResponder];
[super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
[shakeView resignFirstResponder];
[super viewWillDisappear:animated];
}
```
Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!
This method works even if you set applicationSupportsShakeToEdit to NO. |
150,454 | <p>In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking.
<hr/>
<em>Question:</em> What is the standard--or <em>cleanest</em> way--to fake the special status that <code>$a</code> and <code>$b</code> have in regard to strict by simply importing a module? </p>
<p>First of all some setup. The following works: </p>
<pre><code>#!/bin/perl
use strict;
print "\$a=$a\n";
print "\$b=$b\n";
</code></pre>
<p>If I add one more line: </p>
<pre><code>print "\$c=$c\n";
</code></pre>
<p>I get an error at compile time, which means that none of my <em>dazzling</em> print code gets to run. </p>
<p>If I comment out <code>use strict;</code> it runs fine. Outside of strictures, <code>$a</code> and <code>$b</code> are mainly special in that <code>sort</code> passes the two values to be compared with those names. </p>
<pre><code>my @reverse_order = sort { $b <=> $a } @unsorted;
</code></pre>
<p>Thus the main <em>functional</em> difference about <code>$a</code> and <code>$b</code>--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in <a href="http://search.cpan.org/module?List::Util" rel="nofollow noreferrer">List::Util</a>. </p>
<p>It's only when you use strict, that <code>$a</code> and <code>$b</code> become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared.</p>
<p><em>:</em> Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that <code>$a</code> and <code>$b</code> are special and that's it. If you want to use variables you don't have to declare <code>$a</code> and <code>$b</code> are your guys. If you want to have three variables by adding <code>$c</code>, suddenly there's a whole other way to do it.</p>
<p>Nevermind that in manipulating hashes <code>$k</code> and <code>$v</code> might make more sense:</p>
<pre><code>my %starts_upper_1_to_25
= skim { $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash
;`
</code></pre>
<p>Now, I use and I like strict. But I just want <code>$k</code> and <code>$v</code> to be visible to <code>skim</code> for the most compact syntax. And I'd like it to be visible simply by </p>
<pre><code>use Hash::Helper qw<skim>;
</code></pre>
<p>I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the <em>cleanest</em> solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI. </p>
| [
{
"answer_id": 150483,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 1,
"selected": false,
"text": "<p><code>$a</code> and <code>$b</code> are just global variables. You can achieve similar effects by simply declaring <code>$k</code> and <code>$v</code>:</p>\n\n<pre><code>use strict;\nour ($k, $v);\n</code></pre>\n\n<p>(In this case <code>$k</code> and <code>$v</code> are not global variables, but lexically scoped aliases for package variables. But if you don't cross the boundaries it's similarly enough.)</p>\n"
},
{
"answer_id": 150485,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand correctly, what you want is:</p>\n\n<pre><code>use vars qw($a $b); # Pre-5.6\n</code></pre>\n\n<p>or</p>\n\n<pre><code>our ($a, $b); # 5.6 +\n</code></pre>\n\n<p>You can read about it <a href=\"http://perldoc.perl.org/vars.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 150523,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 3,
"selected": false,
"text": "<p>Others mentioned how to 'use vars' and 'our' - I just wanted to add that $a and $b are special cases, since they're used internally by the sort routines. Here's the note from the strict.pm docs:</p>\n\n<pre><code>Because of their special use by sort(), the variables $a and $b are \nexempted from this check.\n</code></pre>\n"
},
{
"answer_id": 150527,
"author": "runrig",
"author_id": 10415,
"author_profile": "https://Stackoverflow.com/users/10415",
"pm_score": 2,
"selected": false,
"text": "<p>In Perl 5.6 and later, you can use our:</p>\n\n<pre><code>our ($k, $v);\n</code></pre>\n\n<p>Or you can stick with the older \"use vars\":</p>\n\n<pre><code>use vars qw($k $v);\n</code></pre>\n\n<p>Or you might just stick with \"my\", e.g.:</p>\n\n<pre><code>my %hash;\nmy ($k,$v);\nwhile (<>) {\n /^KEY=(.*)/ and $k = $1 and next;\n /^VALUE=(.*)/ and $v = $1;\n $hash{$k} = $v;\n print \"$k $v\\n\";\n}\n\n__END__\nKEY=a\nVALUE=1\nKEY=b\nVALUE=2\n</code></pre>\n\n<p>Making a global $v is not really necessary in the example above, but hopefully you get the idea ($k on the other hand needs to be scoped outside the while block).</p>\n\n<p>Alternatively, you can use fully qualified variable names:</p>\n\n<pre><code>$main::k=\"foo\";\n$main::v=\"bar\";\n%main::hash{$k}=$v;\n</code></pre>\n"
},
{
"answer_id": 150612,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": -1,
"selected": false,
"text": "<p><strong>EDIT</strong> - this is actually <strong>incorrect</strong>, see the comments. Leaving it here to give other people a chance to learn from my mistake :)</p>\n\n<hr>\n\n<p>Oh, you're asking if there's a way for a module to declare $k and $v in the CALLER's namespace? You can use Exporter to push up your variables to the caller:</p>\n\n<pre><code>use strict;\n\npackage Test; \nuse Exporter;\n\nmy @ISA = qw/Exporter/; \nmy $c = 3; \nmy @EXPORT = qw/$c/; \n\npackage main; \nprint $c;\n</code></pre>\n"
},
{
"answer_id": 150997,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 2,
"selected": false,
"text": "<p>$a and $b are special because they're a part of the core language. While I can see why you might say that the inability to create similarly-special variables of your own is anti-TIMTOWTDI, I would say that it's no more so than the inability to create new basic commands on the order of 'print' or 'sort'. (You can define subs in modules, but that doesn't make them true keywords. It's the equivalent of using 'our $k', which you seem to be saying doesn't make $k enough like $a for you.)</p>\n\n<p>For pushing names into someone else's namespace, this should be a working example of Exporter:</p>\n\n<pre><code>package SpecialK;\n\nuse strict;\n\nuse base 'Exporter';\nBEGIN {\n our @EXPORT = qw( $k );\n}\n\nour $k;\n\n1;\n</code></pre>\n\n<p>Save this to SpecialK.pm and 'use SpecialK' should then make $k available to you. Note that only 'our' variables can be exported, not 'my'.</p>\n"
},
{
"answer_id": 151042,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you want to do the sort of magic that <a href=\"http://search.cpan.org/~vparseval/List-MoreUtils-0.22/lib/List/MoreUtils.pm\" rel=\"nofollow noreferrer\"><code>List::MoreUtils</code></a> does:</p>\n\n<pre><code>use strict;\nmy @a = (1, 2);\nmy @b = (3, 4);\nmy @x = pairwise { $a + $b } @a, @b;\n</code></pre>\n\n<p>I'd suggest just looking at the <code>pairwise</code> sub <a href=\"http://search.cpan.org/src/VPARSEVAL/List-MoreUtils-0.22/lib/List/MoreUtils.pm\" rel=\"nofollow noreferrer\">in the <code>List::MoreUtils</code> source</a>. It uses some clever symbol table fiddling to inject <code>$a</code> and <code>$b</code> into the caller's namespace and then localize them to just within the sub body. I think.</p>\n"
},
{
"answer_id": 151045,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for me: </p>\n\n<pre><code>package Special;\nuse base qw<Exporter>;\n# use staging; -> commented out, my module for development\nour $c;\n\nour @EXPORT = qw<manip_c>;\n\nsub import { \n *{caller().'::c'} = *c;\n my $import_sub = Exporter->can( 'import' );\n goto &$import_sub;\n } \n</code></pre>\n\n<p>And it passes $c through strict, too. </p>\n\n<pre><code>package main;\nuse feature 'say';\nuse strict;\nuse Special;\nuse strict;\nsay \"In main: \\$c=$c\";\n\nmanip_c( 'f', sub {\n say \"In anon sub: \\$c=$c\\n\"; # In anon sub: $c=f\n});\n\nsay \"In main: \\$c=$c\";\n</code></pre>\n\n<p>Yeah, it's kind of dumb that I bracketed my modules with \"use strict\", but I don't know the internals, and that takes care of potential sequencing issues. </p>\n"
},
{
"answer_id": 151200,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 1,
"selected": false,
"text": "<p>Is this what your after?.....</p>\n\n<pre><code>use strict;\nuse warnings;\nuse feature qw/say/;\n\nsub hash_baz (&@) {\n my $code = shift; \n my $caller = caller;\n my %hash = (); \n use vars qw($k $v);\n\n no strict 'refs';\n local *{ $caller . '::k' } = \\my $k;\n local *{ $caller . '::v' } = \\my $v;\n\n while ( @_ ) {\n $k = shift;\n $v = shift;\n $hash{ $k } = $code->() || $v;\n }\n\n return %hash;\n}\n\nmy %hash = ( \n blue_cat => 'blue', \n purple_dog => 'purple', \n ginger_cat => 'ginger', \n purple_cat => 'purple' );\n\nmy %new_hash = hash_baz { uc $v if $k =~ m/purple/ } %hash;\n\nsay \"@{[ %new_hash ]}\";\n\n# => purple_dog PURPLE ginger_cat ginger purple_cat PURPLE blue_cat blue\n</code></pre>\n"
},
{
"answer_id": 152942,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure if anyone's clarified this, but strict does not whitelist $a and $b just because they are really convenient variable names for you to use in your own routines. $a and $b have special meaning for the sort operator. This is good from the point of view within such a sort routine, but kind of bad design from outside. :) You shouldn't be using $a and $b in other contexts, if you are.</p>\n"
},
{
"answer_id": 153717,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": true,
"text": "<p>If I'm understanding your question you want to write a module that declares variables in the user's namespace (so they don't have to) and which get localized automatically in callbacks. Is that right?</p>\n\n<p>You can do this by declaring globals and exporting them. (Though do note that it's generally considered bad form to export things without being asked to.)</p>\n\n<pre><code>package Foo;\nuse strict;\nuse warnings;\n\nrequire Exporter;\nour @ISA = qw(Exporter);\nour @EXPORT = qw(*k *v hashmap);\nour ($k, $v);\n\nsub hashmap(&\\%) {\n my $code = shift;\n my $hash = shift;\n\n while (local ($k, $v) = each %$hash) {\n $code->();\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> The export is of <code>*k</code> and <code>*v</code>, not <code>$k</code> and <code>$v</code>. If you don't export the entire typeglob the <code>local</code> in <code>hashmap</code> won't work correctly from the user's package. A side effect of this is that <em>all</em> of the various forms of <code>k</code> and <code>v</code> (<code>%k</code>, <code>@v</code>, etc.) get declared and aliased. For a full explanation of this, see <a href=\"http://perldoc.perl.org/perlmod.html#Symbol-Tables\" rel=\"nofollow noreferrer\">Symbol Tables in perlmod</a>.</p>\n\n<p>Then in your script:</p>\n\n<pre><code>use Foo; # exports $k and $v\n\nmy %h = (a => 1, b => 2, c => 3);\n\nhashmap { print \"$k => $v\\n\" } %h;\n\n__END__\nc => 3\na => 1\nb => 2\n</code></pre>\n"
},
{
"answer_id": 155708,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 1,
"selected": false,
"text": "<p>$a and $b aren't normal variables, though, and can't be easily replicated by either lexical declarations or explicit exports or messing about with the symbol table. For instance, using the debugger as a shell:</p>\n\n<pre><code> DB<1> @foo = sort { $b cmp $a } qw(foo bar baz wibble);\n\n DB<2> x @foo\n0 'wibble'\n1 'foo'\n2 'baz'\n3 'bar'\n DB<3> x $a\n0 undef\n DB<4> x $b\n0 undef\n</code></pre>\n\n<p>$a and $b only exist within the block passed to sort(), don't exist afterwards, and have scope in such a way that any further calls to sort don't tread on them.</p>\n\n<p>To replicate that, you probably need to start messing about with source filters, to turn your preferred notation</p>\n\n<pre><code>my %starts_upper_1_to_25 \n = skim { $k =~ m/^\\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash\n;\n</code></pre>\n\n<p>into effectively</p>\n\n<pre><code>my %starts_upper_1_to_25\n = map { my $k = $_; my $v = $my_hash{$v};\n $k =~ m/^\\p{IsUpper}/ && ( 1 <= $v && $v <=> 25 ) } keys %my_hash\n;\n</code></pre>\n\n<p>$a and $b are as special as $_ and @_, and while there's no easy way to change those names in Perl 5, Perl 6 does indeed fix this, with the given keyword. \"given\" is a rubbish term to search on, but <a href=\"http://dev.perl.org/perl6/doc/design/syn/S03.html\" rel=\"nofollow noreferrer\">http://dev.perl.org/perl6/doc/design/syn/S03.html</a> may be a good place to start.</p>\n"
},
{
"answer_id": 161129,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>The modules suggested that use export are really no different from <code>use vars</code>.\nBut the <code>use vars</code> would need to be done in each package that used the $a-like variable.\nAnd <code>our()</code> would need to be done in each outer scope.</p>\n\n<p>Note that you can avoid using $a and $b even for sort by using a $$-prototyped sub:</p>\n\n<pre><code>sub lccmp($$) { lc($_[0]) cmp lc($_[1]) }\nprint join ' ', sort lccmp\n qw/I met this guy and he looked like he might have been a hat-check clerk/;\n</code></pre>\n\n<p>This is essential when using a compare routine in a different package than the sort call.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
]
| In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking.
---
*Question:* What is the standard--or *cleanest* way--to fake the special status that `$a` and `$b` have in regard to strict by simply importing a module?
First of all some setup. The following works:
```
#!/bin/perl
use strict;
print "\$a=$a\n";
print "\$b=$b\n";
```
If I add one more line:
```
print "\$c=$c\n";
```
I get an error at compile time, which means that none of my *dazzling* print code gets to run.
If I comment out `use strict;` it runs fine. Outside of strictures, `$a` and `$b` are mainly special in that `sort` passes the two values to be compared with those names.
```
my @reverse_order = sort { $b <=> $a } @unsorted;
```
Thus the main *functional* difference about `$a` and `$b`--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in [List::Util](http://search.cpan.org/module?List::Util).
It's only when you use strict, that `$a` and `$b` become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared.
*:* Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that `$a` and `$b` are special and that's it. If you want to use variables you don't have to declare `$a` and `$b` are your guys. If you want to have three variables by adding `$c`, suddenly there's a whole other way to do it.
Nevermind that in manipulating hashes `$k` and `$v` might make more sense:
```
my %starts_upper_1_to_25
= skim { $k =~ m/^\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash
;`
```
Now, I use and I like strict. But I just want `$k` and `$v` to be visible to `skim` for the most compact syntax. And I'd like it to be visible simply by
```
use Hash::Helper qw<skim>;
```
I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the *cleanest* solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI. | If I'm understanding your question you want to write a module that declares variables in the user's namespace (so they don't have to) and which get localized automatically in callbacks. Is that right?
You can do this by declaring globals and exporting them. (Though do note that it's generally considered bad form to export things without being asked to.)
```
package Foo;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(*k *v hashmap);
our ($k, $v);
sub hashmap(&\%) {
my $code = shift;
my $hash = shift;
while (local ($k, $v) = each %$hash) {
$code->();
}
}
```
**Note:** The export is of `*k` and `*v`, not `$k` and `$v`. If you don't export the entire typeglob the `local` in `hashmap` won't work correctly from the user's package. A side effect of this is that *all* of the various forms of `k` and `v` (`%k`, `@v`, etc.) get declared and aliased. For a full explanation of this, see [Symbol Tables in perlmod](http://perldoc.perl.org/perlmod.html#Symbol-Tables).
Then in your script:
```
use Foo; # exports $k and $v
my %h = (a => 1, b => 2, c => 3);
hashmap { print "$k => $v\n" } %h;
__END__
c => 3
a => 1
b => 2
``` |
150,471 | <p>I have a DataGridView whose DataSource is a DataTable.
This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView.</p>
<pre><code>employeeSelectionTable.Columns.Add("IsSelected", typeof(bool));
...
employeeSelectionTable.RowChanged += selectionTableRowChanged;
dataGridViewSelectedEmployees.DataSource = employeeSelectionTable;
...
private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e)
{
if ((bool)e.Row["IsSelected"])
{
Console.Writeline("Is Selected");
}
else
{
Console.Writeline("Is Not Selected");
}
break;
}
</code></pre>
<p>When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected."</p>
<p>Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected."</p>
<p>Here's where I have the problem:</p>
<p>When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync.</p>
<p>My solution right now is to subclass DataGridView and override WndProc to eat WM_LBUTTONDBLCLICK, so any double-clicking on the control is ignored.
Is there a better solution?</p>
| [
{
"answer_id": 150482,
"author": "Ian Jacobs",
"author_id": 22818,
"author_profile": "https://Stackoverflow.com/users/22818",
"pm_score": 1,
"selected": false,
"text": "<p>Is there some reason it needs to be done that low level? Can the DoubleClick Method just be an empty method that eats it?</p>\n"
},
{
"answer_id": 150531,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I already tried overriding the OnDoubleClick method in the DataGridView subclass to do nothing, but it still allowed the checkbox to be changed a second time.</p>\n\n<p>Ideally I was looking to have the DataTable's RowChanged event get called twice.\nIs there a way to affect the underlying DataTable via the overridden OnDoubleClick method?</p>\n"
},
{
"answer_id": 150549,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just leave IsSelected column unbounded? Use CellContentClick event to push the data to underlying datatable and leave CellDoubleClick or RowChange event alone.</p>\n\n<pre><code>private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n if(e.ColumnIndex == <columnIndex of IsSelected>)\n {\n string value = dgv[e.ColumnIndex, e.RowIndex].EditedFormattedValue;\n if( value == null || Convert.ToBoolean(value) == false)\n {\n //push false to employeeSelectionTable\n }\n else\n {\n //push true to employeeSelectionTable\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 150889,
"author": "ManiacZX",
"author_id": 18148,
"author_profile": "https://Stackoverflow.com/users/18148",
"pm_score": 2,
"selected": false,
"text": "<p>The reason that making an empty DoubleClick event method would not help would be that is executed in addition to the other operations that happen when a double click occurs.</p>\n\n<p>If you look at the windows generated code or examples of programatically adding event handlers, you use += to assign the event handler. This means you are adding that event handler in addition to the others that already exist, you could have multiple event handlers being triggered on the save event.</p>\n\n<p>My instinct would have been to override the DataGridView class, then override the OnDoubleClick method and not call the base OnDoubleClick method.</p>\n\n<p>However, I have tested this real quick and am seeing some interesting results.</p>\n\n<p>I put together the following test class:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\nnamespace TestApp\n{\n class DGV : DataGridView\n {\n private string test = \"\";\n\n protected override void OnDoubleClick(EventArgs e)\n {\n MessageBox.Show(test + \"OnDoubleClick\");\n }\n\n protected override void OnCellMouseDoubleClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)\n {\n MessageBox.Show(test + \"OnCellMouseDoubleClick\");\n }\n\n protected override void OnCellMouseClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)\n {\n if (e.Clicks == 1)\n {\n // Had to do this with a variable as using a MessageBox\n // here would block us from pulling off a double click\n test = \"1 click \";\n base.OnCellMouseClick(e);\n }\n else\n {\n MessageBox.Show(\"OnCellMouseClick\");\n }\n }\n }\n}\n</code></pre>\n\n<p>Then inserted this into a windows form, adding a checkbox column and ran the program.</p>\n\n<p>On a fresh run, double clicking on the checkbox causes the messagebox display to say \"1 click OnDoubleClick\".</p>\n\n<p>This means that OnCellMouseClick executed on the first part of the double click and then OnDoubleClick executed on the second click.</p>\n\n<p>Also, unfortunately, the removal of the call to the base methods doesn't seem to be preventing the checkbox from getting the click passed to it.</p>\n\n<p>I suspect that for this approach to work it may have to be taken further and override the DataGridViewCheckBoxColumn and DataGridViewCheckBoxCell that ignores the double click. Assuming this works, you would be able to stop double click on the checkbox but allow it still on your other column controls.</p>\n\n<p>I have posted an answer on another question that talks about creating custom DataGridView columns and cells at <a href=\"https://stackoverflow.com/questions/121274/is-it-possible-to-bind-complex-type-properties-to-a-datagrid#128909\">here</a>.</p>\n"
},
{
"answer_id": 263102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Don't know why i had to, but i was able to put in a timer tick event attached to a datagridview refresh that just refreshed the dgv after the second click.</p>\n\n<p>In cell click event</p>\n\n<pre><code>** _RefreshTimer = new Timer();\n _RefreshTimer.Tick += new EventHandler(RefreshTimer_Tick);\n _RefreshTimer.Interval = 100;\n _RefreshTimer.Start();\n\n }\n }\n\n }\n\n void RefreshTimer_Tick(object sender, EventArgs e)\n {\n dgv.Refresh();\n _RefreshTimer.Stop();\n _RefreshTimer = null;\n }**\n</code></pre>\n"
},
{
"answer_id": 377544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In case you want a checkbox column inside a DataGridView, create something like this:</p>\n\n<pre><code>DataGridViewCheckBoxCell checkBoxCell = new MyDataGridViewCheckBoxCell();\n...\nDataGridViewColumn col = new DataGridViewColumn(checkBoxCell);\n...\ncol.Name = \"colCheckBox\";\n...\nthis.dgItems.Columns.Add(col);\n</code></pre>\n\n<p>where dgItems is DataGridView instance.</p>\n\n<p>As you can see I have a MyDataGridViewCheckBoxCell class which is a subclass of the DataGridViewCheckBoxCell class. In this subclass I define:</p>\n\n<pre><code>protected override void OnContentDoubleClick(DataGridViewCellEventArgs e)\n{\n //This the trick to keep the checkbox in sync with other actions.\n //base.OnContentDoubleClick(e);\n}\n</code></pre>\n\n<p>When the user now double clicks a checkbox in the checkbox column the checkbox will behave as if it was single clicked. This should solve your sync problem.</p>\n"
},
{
"answer_id": 1363636,
"author": "Rob Smith",
"author_id": 896691,
"author_profile": "https://Stackoverflow.com/users/896691",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't exactly an elegant solution, but why not simply do the following?</p>\n\n<pre><code>private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n{\n dgv_CellClick(sender, e);\n}\n</code></pre>\n\n<p>This would explicitly force the second CellClick event and avoid out of sync.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a DataGridView whose DataSource is a DataTable.
This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView.
```
employeeSelectionTable.Columns.Add("IsSelected", typeof(bool));
...
employeeSelectionTable.RowChanged += selectionTableRowChanged;
dataGridViewSelectedEmployees.DataSource = employeeSelectionTable;
...
private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e)
{
if ((bool)e.Row["IsSelected"])
{
Console.Writeline("Is Selected");
}
else
{
Console.Writeline("Is Not Selected");
}
break;
}
```
When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected."
Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected."
Here's where I have the problem:
When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync.
My solution right now is to subclass DataGridView and override WndProc to eat WM\_LBUTTONDBLCLICK, so any double-clicking on the control is ignored.
Is there a better solution? | The reason that making an empty DoubleClick event method would not help would be that is executed in addition to the other operations that happen when a double click occurs.
If you look at the windows generated code or examples of programatically adding event handlers, you use += to assign the event handler. This means you are adding that event handler in addition to the others that already exist, you could have multiple event handlers being triggered on the save event.
My instinct would have been to override the DataGridView class, then override the OnDoubleClick method and not call the base OnDoubleClick method.
However, I have tested this real quick and am seeing some interesting results.
I put together the following test class:
```
using System;
using System.Windows.Forms;
namespace TestApp
{
class DGV : DataGridView
{
private string test = "";
protected override void OnDoubleClick(EventArgs e)
{
MessageBox.Show(test + "OnDoubleClick");
}
protected override void OnCellMouseDoubleClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)
{
MessageBox.Show(test + "OnCellMouseDoubleClick");
}
protected override void OnCellMouseClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)
{
if (e.Clicks == 1)
{
// Had to do this with a variable as using a MessageBox
// here would block us from pulling off a double click
test = "1 click ";
base.OnCellMouseClick(e);
}
else
{
MessageBox.Show("OnCellMouseClick");
}
}
}
}
```
Then inserted this into a windows form, adding a checkbox column and ran the program.
On a fresh run, double clicking on the checkbox causes the messagebox display to say "1 click OnDoubleClick".
This means that OnCellMouseClick executed on the first part of the double click and then OnDoubleClick executed on the second click.
Also, unfortunately, the removal of the call to the base methods doesn't seem to be preventing the checkbox from getting the click passed to it.
I suspect that for this approach to work it may have to be taken further and override the DataGridViewCheckBoxColumn and DataGridViewCheckBoxCell that ignores the double click. Assuming this works, you would be able to stop double click on the checkbox but allow it still on your other column controls.
I have posted an answer on another question that talks about creating custom DataGridView columns and cells at [here](https://stackoverflow.com/questions/121274/is-it-possible-to-bind-complex-type-properties-to-a-datagrid#128909). |
150,505 | <p>I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the <code>HttpRequest</code> object?</p>
<p>My <code>HttpRequest.GET</code> currently returns an empty <code>QueryDict</code> object.</p>
<p>I'd like to learn how to do this without a library, so I can get to know Django better.</p>
| [
{
"answer_id": 150518,
"author": "camflan",
"author_id": 22445,
"author_profile": "https://Stackoverflow.com/users/22445",
"pm_score": 11,
"selected": true,
"text": "<p>When a URL is like <code>domain/search/?q=haha</code>, you would use <code>request.GET.get('q', '')</code>.</p>\n<p><code>q</code> is the parameter you want, and <code>''</code> is the default value if <code>q</code> isn't found.</p>\n<p>However, if you are instead just configuring your <code>URLconf</code>**, then your captures from the <code>regex</code> are passed to the function as arguments (or named arguments).</p>\n<p>Such as:</p>\n<pre><code>(r'^user/(?P<username>\\w{0,50})/$', views.profile_page,),\n</code></pre>\n<p>Then in your <code>views.py</code> you would have</p>\n<pre><code>def profile_page(request, username):\n # Rest of the method\n</code></pre>\n"
},
{
"answer_id": 152349,
"author": "jamting",
"author_id": 2639,
"author_profile": "https://Stackoverflow.com/users/2639",
"pm_score": 3,
"selected": false,
"text": "<p>This is not exactly what you asked for, but <a href=\"http://www.djangosnippets.org/snippets/826/\" rel=\"noreferrer\">this snippet</a> is helpful for managing <code>query_strings</code> in <code>templates</code>.</p>\n"
},
{
"answer_id": 157295,
"author": "akaihola",
"author_id": 15770,
"author_profile": "https://Stackoverflow.com/users/15770",
"pm_score": 9,
"selected": false,
"text": "<p>To clarify <a href=\"https://stackoverflow.com/users/22445/camflan\">camflan</a>'s <a href=\"https://stackoverflow.com/a/150518/11573842\">explanation</a>, let's suppose you have</p>\n<ul>\n<li>the rule <code>url(regex=r'^user/(?P<username>\\w{1,50})/$', view='views.profile_page')</code></li>\n<li>an incoming request for <code>http://domain/user/thaiyoshi/?message=Hi</code></li>\n</ul>\n<p>The URL dispatcher rule will catch parts of the URL <em>path</em> (here <code>"user/thaiyoshi/"</code>) and pass them to the view function along with the request object.</p>\n<p>The query string (here <code>message=Hi</code>) is parsed and parameters are stored as a <code>QueryDict</code> in <code>request.GET</code>. No further matching or processing for HTTP GET parameters is done.</p>\n<p>This view function would use both parts extracted from the URL path and a query parameter:</p>\n<pre><code>def profile_page(request, username=None):\n user = User.objects.get(username=username)\n message = request.GET.get('message')\n</code></pre>\n<p>As a side note, you'll find the request method (in this case <code>"GET"</code>, and for submitted forms usually <code>"POST"</code>) in <code>request.method</code>. In some cases, it's useful to check that it matches what you're expecting.</p>\n<p><strong>Update:</strong> When deciding whether to use the URL path or the query parameters for passing information, the following may help:</p>\n<ul>\n<li>use the URL path for uniquely identifying resources, e.g. <code>/blog/post/15/</code> (not <code>/blog/posts/?id=15</code>)</li>\n<li>use query parameters for changing the way the resource is displayed, e.g. <code>/blog/post/15/?show_comments=1</code> or <code>/blog/posts/2008/?sort_by=date&direction=desc</code></li>\n<li>to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories, and/or slugs: <code>/blog/post/2008/09/30/django-urls/</code></li>\n</ul>\n"
},
{
"answer_id": 4218313,
"author": "Kevin",
"author_id": 512577,
"author_profile": "https://Stackoverflow.com/users/512577",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def some_view(request, *args, **kwargs):\n if kwargs.get('q', None):\n # Do something here ..\n</code></pre>\n"
},
{
"answer_id": 14699001,
"author": "DrKaoliN",
"author_id": 1410452,
"author_profile": "https://Stackoverflow.com/users/1410452",
"pm_score": 4,
"selected": false,
"text": "<p>I would like to share a tip that may save you some time.<br/>\nIf you plan to use something like this in your <code>urls.py</code> file:</p>\n\n<pre><code>url(r'^(?P<username>\\w+)/$', views.profile_page,),\n</code></pre>\n\n<p>Which basically means <code>www.example.com/<username></code>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them <strong>will</strong> give you the nice error: <code>User matching query does not exist.</code><br> <br>\nI've just experienced it myself; hope it helps!</p>\n"
},
{
"answer_id": 28062342,
"author": "Dadaso Zanzane",
"author_id": 3056905,
"author_profile": "https://Stackoverflow.com/users/3056905",
"pm_score": 6,
"selected": false,
"text": "<p>Using GET</p>\n\n<pre><code>request.GET[\"id\"]\n</code></pre>\n\n<p>Using POST</p>\n\n<pre><code>request.POST[\"id\"]\n</code></pre>\n"
},
{
"answer_id": 43806831,
"author": "Ole Henrik Skogstrøm",
"author_id": 900271,
"author_profile": "https://Stackoverflow.com/users/900271",
"pm_score": 5,
"selected": false,
"text": "<p>For situations where you only have the <code>request</code> object you can use <code>request.parser_context['kwargs']['your_param']</code></p>\n"
},
{
"answer_id": 46564448,
"author": "Bartłomiej",
"author_id": 7665326,
"author_profile": "https://Stackoverflow.com/users/7665326",
"pm_score": 5,
"selected": false,
"text": "<p>You have two common ways to do that in case your URL looks like that:</p>\n<pre><code>https://domain/method/?a=x&b=y\n</code></pre>\n<p>Version 1:</p>\n<p>If a specific key is mandatory you can use:</p>\n<pre><code>key_a = request.GET['a']\n</code></pre>\n<p>This will return a value of <code>a</code> if the key exists and an <em>exception</em> if not.</p>\n<p>Version 2:</p>\n<p>If your keys are optional:</p>\n<pre><code>request.GET.get('a')\n</code></pre>\n<p>You can try that without any argument and this will not crash.\nSo you can wrap it with <code>try: except:</code> and return <code>HttpResponseBadRequest()</code> in example.\nThis is a simple way to make your code less complex, without using special exceptions handling.</p>\n"
},
{
"answer_id": 50714430,
"author": "Eric Andrews",
"author_id": 8350321,
"author_profile": "https://Stackoverflow.com/users/8350321",
"pm_score": 6,
"selected": false,
"text": "<p>Someone would wonder how to set path in file <em>urls.py</em>, such as</p>\n<pre><code>domain/search/?q=CA\n</code></pre>\n<p>so that we could invoke query.</p>\n<p>The fact is that it is <em>not</em> necessary to set such a route in file <em>urls.py</em>. You need to set just the route in <em>urls.py</em>:</p>\n<pre><code>urlpatterns = [\n path('domain/search/', views.CityListView.as_view()),\n]\n</code></pre>\n<p>And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though</p>\n<pre><code>request.GET.get('q', None).\n</code></pre>\n<p>Here is an example (file <em>views.py</em>)</p>\n<pre><code>class CityListView(generics.ListAPIView):\n serializer_class = CityNameSerializer\n\n def get_queryset(self):\n if self.request.method == 'GET':\n queryset = City.objects.all()\n state_name = self.request.GET.get('q', None)\n if state_name is not None:\n queryset = queryset.filter(state__name=state_name)\n return queryset\n</code></pre>\n<p>In addition, when you write query string in the URL:</p>\n<pre><code>http://servername:port/domain/search/?q=CA\n</code></pre>\n<p>Do not wrap query string in quotes. For example,</p>\n<pre><code>http://servername:port/domain/search/?q="CA"\n</code></pre>\n"
},
{
"answer_id": 57148306,
"author": "mdcg",
"author_id": 10235468,
"author_profile": "https://Stackoverflow.com/users/10235468",
"pm_score": 4,
"selected": false,
"text": "<p>These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following:</p>\n\n<pre><code>http://myserver:port/resource/?status=1\n</code></pre>\n\n<pre><code>request.query_params.get('status', None) => 1\n</code></pre>\n\n<p>If you want to access the parameters passed by POST, you need to access this way:</p>\n\n<pre><code>request.data.get('role', None)\n</code></pre>\n\n<p>Accessing the dictionary (QueryDict) with 'get()', you can set a default value. In the cases above, if 'status' or 'role' are not informed, the values are None.</p>\n"
},
{
"answer_id": 60892217,
"author": "sachi",
"author_id": 13137216,
"author_profile": "https://Stackoverflow.com/users/13137216",
"pm_score": 3,
"selected": false,
"text": "<p>This is another alternate solution that can be implemented:</p>\n<p>In the URL configuration:</p>\n<pre class=\"lang-py prettyprint-override\"><code>urlpatterns = [path('runreport/<str:queryparams>', views.get)]\n</code></pre>\n<p>In the views:</p>\n<pre class=\"lang-py prettyprint-override\"><code>list2 = queryparams.split("&")\n</code></pre>\n"
},
{
"answer_id": 63423068,
"author": "Martín De la Fuente",
"author_id": 6535374,
"author_profile": "https://Stackoverflow.com/users/6535374",
"pm_score": 3,
"selected": false,
"text": "<p>If you only have access to the view object, then you can get the parameters defined in the URL path this way:</p>\n<pre><code>view.kwargs.get('url_param')\n</code></pre>\n<p>If you only have access to the request object, use the following:</p>\n<pre><code>request.resolver_match.kwargs.get('url_param')\n</code></pre>\n<p>Tested on Django 3.</p>\n"
},
{
"answer_id": 64200327,
"author": "Ahmed Shehab",
"author_id": 8404743,
"author_profile": "https://Stackoverflow.com/users/8404743",
"pm_score": 3,
"selected": false,
"text": "<p>You might as well check request.META dictionary to access many useful things like\nPATH_INFO, QUERY_STRING</p>\n<pre><code># for example\nrequest.META['QUERY_STRING']\n\n# or to avoid any exceptions provide a fallback\n\nrequest.META.get('QUERY_STRING', False)\n\n</code></pre>\n<p>you said that it returns empty query dict</p>\n<p>I think you need to tune your url to accept required or optional args or kwargs\nDjango got you all the power you need with regrex like:</p>\n<pre><code>url(r'^project_config/(?P<product>\\w+)/$', views.foo),\n\n</code></pre>\n<p>more about this at <a href=\"https://stackoverflow.com/questions/14351048/django-optional-url-parameters#answer-14351174\">django-optional-url-parameters</a></p>\n"
},
{
"answer_id": 65666694,
"author": "Arseniy Lebedev",
"author_id": 9826267,
"author_profile": "https://Stackoverflow.com/users/9826267",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't know the name of params and want to work with them all, you can use <code>request.GET.keys()</code> or <code>dict(request.GET)</code> functions</p>\n"
},
{
"answer_id": 68829899,
"author": "Omar Magdy",
"author_id": 14819065,
"author_profile": "https://Stackoverflow.com/users/14819065",
"pm_score": 2,
"selected": false,
"text": "<h3>views.py</h3>\n<b>\n<pre class=\"lang-py prettyprint-override\"><code>from rest_framework.response import Response\n\ndef update_product(request, pk):\n return Response({"pk":pk})\n</code></pre>\n</b>\n<p><strong>pk</strong> means <strong>primary_key</strong>.</p>\n<h3>urls.py</h3>\n<b>\n<pre class=\"lang-py prettyprint-override\"><code>from products.views import update_product\nfrom django.urls import path\n\nurlpatterns = [\n ...,\n path('update/products/<int:pk>', update_product)\n]\n</code></pre>\n</b>\n"
},
{
"answer_id": 71331889,
"author": "Odiljon Djamalov",
"author_id": 8532138,
"author_profile": "https://Stackoverflow.com/users/8532138",
"pm_score": 0,
"selected": false,
"text": "<p>url parameters may be captured by <code>request.query_params</code></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227001/"
]
| I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the `HttpRequest` object?
My `HttpRequest.GET` currently returns an empty `QueryDict` object.
I'd like to learn how to do this without a library, so I can get to know Django better. | When a URL is like `domain/search/?q=haha`, you would use `request.GET.get('q', '')`.
`q` is the parameter you want, and `''` is the default value if `q` isn't found.
However, if you are instead just configuring your `URLconf`\*\*, then your captures from the `regex` are passed to the function as arguments (or named arguments).
Such as:
```
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
```
Then in your `views.py` you would have
```
def profile_page(request, username):
# Rest of the method
``` |
150,513 | <p>I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way.</p>
<p>I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts?</p>
| [
{
"answer_id": 150521,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<pre><code><input type=\"text\" style=\"border: 0; background-color: #fff;\" />\n</code></pre>\n\n<p>Where #fff is your background color..</p>\n"
},
{
"answer_id": 150530,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you only want to remove the border and such from texts, you'll need to give them a class. Maybe something like:</p>\n\n<pre><code><input type=\"text\" class=\"print-clean\" .../>\n</code></pre>\n\n<p>And css, loaded with media=\"print\":</p>\n\n<pre><code><link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"/css/print.css\" />\n</code></pre>\n\n<p>would contain something like this:</p>\n\n<pre><code>.print-clean {\n border: none;\n background: transparent;\n}\n</code></pre>\n"
},
{
"answer_id": 150536,
"author": "Maciej",
"author_id": 2631856,
"author_profile": "https://Stackoverflow.com/users/2631856",
"pm_score": 5,
"selected": true,
"text": "<p>Add a separate CSS file for printing by doing something like this:</p>\n\n<pre><code><link rel=\"stylsheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n</code></pre>\n\n<p>add it to the <code><head></code> section of the page.</p>\n\n<p>In this(print.css) file include styling relevant to what you want to see when the page is printed, for example:</p>\n\n<p><code>input{border: 0px}</code> should hide the border of input boxes when printing.</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
| I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way.
I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts? | Add a separate CSS file for printing by doing something like this:
```
<link rel="stylsheet" type="text/css" media="print" href="print.css">
```
add it to the `<head>` section of the page.
In this(print.css) file include styling relevant to what you want to see when the page is printed, for example:
`input{border: 0px}` should hide the border of input boxes when printing. |
150,514 | <p>In the database I have a field named 'body' that has an XML in it. The
method I created in the model looks like this:</p>
<pre><code>def self.get_personal_data_module(person_id)
person_module = find_by_person_id(person_id)
item_module = Hpricot(person_module.body)
personal_info = Array.new
personal_info = {:studies => (item_module/"studies").inner_html,
:birth_place => (item_module/"birth_place").inner_html,
:marrital_status => (item_module/"marrital_status").inner_html}
return personal_info
end
</code></pre>
<p>I want the function to return an object instead of an array. So I can
use Module.studies instead of Model[:studies].</p>
| [
{
"answer_id": 150587,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 3,
"selected": true,
"text": "<p>This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this:</p>\n\n<pre><code>class PersonalData\n attr_accessor :studies\n attr_accessor :birth_place\n attr_accessor :marital_status\n\n def initialize(studies,birth_place,marital_status)\n @studies = studies\n @birth_place = birth_place\n @marital_status = marital_status\n end\nend\n</code></pre>\n\n<p>And your translation code would look like:</p>\n\n<pre><code>def self.get_personal_data_module(person_id) \n person_module = find_by_person_id(person_id) \n item_module = Hpricot(person_module.body) \n personal_info = PersonalData.new((item_module/\"studies\").inner_html,\n (item_module/\"birth_place\").inner_html,\n (item_module/\"marital_status\").innner_html)\n return personal_info \nend\n</code></pre>\n"
},
{
"answer_id": 151636,
"author": "jtbandes",
"author_id": 23649,
"author_profile": "https://Stackoverflow.com/users/23649",
"pm_score": 2,
"selected": false,
"text": "<p>Or, if you want to avoid a model class, you could do something weird:</p>\n\n<pre><code>class Hash\n def to_obj\n self.inject(Object.new) do |obj, ary| # ary is [:key, \"value\"]\n obj.instance_variable_set(\"@#{ary[0]}\", ary[1])\n class << obj; self; end.instance_eval do # do this on obj's metaclass\n attr_reader ary[0].to_sym # add getter method for this ivar\n end\n obj # return obj for next iteration\n end\n end\nend\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>h = {:foo => \"bar\", :baz => \"wibble\"}\no = h.to_obj # => #<Object:0x30bf38 @foo=\"bar\", @baz=\"wibble\">\no.foo # => \"bar\"\no.baz # => \"wibble\"\n</code></pre>\n\n<p>It's like magic!</p>\n"
},
{
"answer_id": 165969,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 1,
"selected": false,
"text": "<p>on a slightly different tack.</p>\n\n<p>The idea of using a class method to do this feels wrong from an OO point of view.</p>\n\n<p>You should really refactor this so that it works from an instance method. </p>\n\n<pre>\n def personal_data_module\n item_module = Hpricot(body) \n {\n :studies => (item_module/\"studies\").inner_html, \n :birth_place => (item_module/\"birth_place\").inner_html, \n :marrital_status => (item_module/\"marrital_status\").inner_html\n }\n end\n</pre>\n\n<p>Then, where you need to use it, instead of doing....</p>\n\n<pre>\nFoobar.get_personal_data_module(the_id)\n</pre>\n\n<p>you would do</p>\n\n<pre>\nFoobar.find_by_person_id(the_id).personal_data_module\n</pre>\n\n<p>This looks worse, but in fact, thats a bit artificial, normally, you would be\nreferencing this from some other object, where in fact you would have a 'handle' on the person object, so would not have to construct it yourself.</p>\n\n<p>For instance, if you have another class, where you reference person_id as a foreign key, you would have</p>\n\n<p>class Organisation\n belongs_to :person\nend</p>\n\n<p>then, where you have an organisation, you could go</p>\n\n<pre>\norganisation.person.personal_information_module\n</pre>\n\n<p>Yes, I know, that breaks demeter, so it would be better to wrap it in a delegate</p>\n\n<pre>\nclass Organisation\n belongs_to :person\n\n def personal_info_module\n person.personal_info_module\n end\nend\n</pre>\n\n<p>And then from controller code, you could just say</p>\n\n<pre>\norganisation.personal_info_module\n</pre>\n\n<p>without worrying about where it comes from at all.</p>\n\n<p>This is because a 'personal_data_module' is really an attribute of that class, not something to be accessed through a class method.</p>\n\n<p>But this also brings up some questions, for instance, is person_id the primary key of this table? is this a legacy situation where the primary key of the table is not called 'id'?</p>\n\n<p>If this is the case, have you told ActiveRecord about this or do you have to use 'find_by_person_id' all over where you would really want to write 'find'?</p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3718/"
]
| In the database I have a field named 'body' that has an XML in it. The
method I created in the model looks like this:
```
def self.get_personal_data_module(person_id)
person_module = find_by_person_id(person_id)
item_module = Hpricot(person_module.body)
personal_info = Array.new
personal_info = {:studies => (item_module/"studies").inner_html,
:birth_place => (item_module/"birth_place").inner_html,
:marrital_status => (item_module/"marrital_status").inner_html}
return personal_info
end
```
I want the function to return an object instead of an array. So I can
use Module.studies instead of Model[:studies]. | This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this:
```
class PersonalData
attr_accessor :studies
attr_accessor :birth_place
attr_accessor :marital_status
def initialize(studies,birth_place,marital_status)
@studies = studies
@birth_place = birth_place
@marital_status = marital_status
end
end
```
And your translation code would look like:
```
def self.get_personal_data_module(person_id)
person_module = find_by_person_id(person_id)
item_module = Hpricot(person_module.body)
personal_info = PersonalData.new((item_module/"studies").inner_html,
(item_module/"birth_place").inner_html,
(item_module/"marital_status").innner_html)
return personal_info
end
``` |
150,517 | <p>This is an almost-duplicate of <a href="https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">Send file using POST from a Python script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
| [
{
"answer_id": 151642,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>Best thing I can think of is to encode it yourself. How about this subroutine?</p>\n\n<pre><code>from urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open(\"http://www.whatever.com/script.cgi\", u\"Liberté Égalité Fraternité\")\n# returns a file-like object\n</code></pre>\n\n<p>(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an \"Upload File\" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)</p>\n"
},
{
"answer_id": 151670,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 1,
"selected": false,
"text": "<p>PyCURL provides an interface to CURL from Python.</p>\n\n<p><a href=\"http://curl.haxx.se/libcurl/python/\" rel=\"nofollow noreferrer\">http://curl.haxx.se/libcurl/python/</a></p>\n\n<p>Curl will do all you need. It can transfer binary files properly, and supports many encodings. However, you have to make sure that the proper character encoding as a custom header when POSTing files.</p>\n\n<p>Specifically, you may need to do a 'file upload' style POST:</p>\n\n<p><a href=\"http://curl.haxx.se/docs/httpscripting.html\" rel=\"nofollow noreferrer\">http://curl.haxx.se/docs/httpscripting.html</a> (Section 4.3)</p>\n\n<p>With curl (or any other HTTP client) you may have to set the content encoding:</p>\n\n<p>Content-Type: text/html; charset=UTF-8</p>\n\n<p>Also, be aware that the request headers must be ascii, and this includes the\nurl (so make sure you properly escape your possibly unicode URLs. There are\nunicode escapes for the HTTP headers) This was recently fixed in Python:</p>\n\n<p><a href=\"http://bugs.python.org/issue3300\" rel=\"nofollow noreferrer\">http://bugs.python.org/issue3300</a></p>\n\n<p>I hope this helps, there is more info on the topic, including setting your default character set on your server, etc.</p>\n"
},
{
"answer_id": 3786024,
"author": "Stattrav",
"author_id": 370682,
"author_profile": "https://Stackoverflow.com/users/370682",
"pm_score": 1,
"selected": false,
"text": "<p>Just use this library and send in files.</p>\n\n<p><a href=\"http://github.com/seisen/urllib2_file/\" rel=\"nofollow\">http://github.com/seisen/urllib2_file/</a></p>\n"
}
]
| 2008/09/29 | [
"https://Stackoverflow.com/questions/150517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23582/"
]
| This is an almost-duplicate of [Send file using POST from a Python script](https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script), but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean. | Best thing I can think of is to encode it yourself. How about this subroutine?
```
from urllib2 import Request, urlopen
from binascii import b2a_base64
def b64open(url, postdata):
req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
return urlopen(req)
conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
```
(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.