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
|
---|---|---|---|---|---|---|
218,531 |
<p>I have a situation where I want to create a signature of a data structure:</p>
<pre><code>my $signature = ds_to_sig(
{ foo => 'bar',
baz => 'bundy',
boing => undef,
number => 1_234_567,
}
);
</code></pre>
<p>The aim should be that if the data structure changes then so should the signature.</p>
<p>Is there an established way to do this?</p>
|
[
{
"answer_id": 218549,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 0,
"selected": false,
"text": "<p>I think the word you're looking for is <a href=\"http://en.wikipedia.org/wiki/Hash_function\" rel=\"nofollow noreferrer\">\"hashing\"</a>.</p>\n\n<p>Basically, you put your data structure through a function that generates a fairly unique value from it. This value would be your signiture.</p>\n"
},
{
"answer_id": 218558,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "<p>I think what you're looking for is a hash function. I would recommend an approach like this:</p>\n\n<pre><code>use Storable;\n$Storable::canonical = 1;\nsub ds_to_sig {\n my $structure = shift;\n return hash(freeze $structure);\n}\n</code></pre>\n\n<p>The function hash can be any hash function, for example the function md5 from <a href=\"http://search.cpan.org/~gaas/Digest-MD5/MD5.pm\" rel=\"noreferrer\">Digest::MD5</a></p>\n"
},
{
"answer_id": 218560,
"author": "Demian Turner",
"author_id": 29615,
"author_profile": "https://Stackoverflow.com/users/29615",
"pm_score": -1,
"selected": false,
"text": "<p>Can't you use an object instead of a struct? That way you could see if an object is an instance of a type without having to compare hashes, etc.</p>\n"
},
{
"answer_id": 218590,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://search.cpan.org/perldoc?Storable\" rel=\"nofollow noreferrer\">Storable</a>::nstore to turn it into a binary representation, and then calculate a checksum (for example with the Digest module).</p>\n\n<p>Both modules are core modules.</p>\n"
},
{
"answer_id": 218598,
"author": "friedo",
"author_id": 20745,
"author_profile": "https://Stackoverflow.com/users/20745",
"pm_score": 4,
"selected": true,
"text": "<p>The best way to do this is to use a deep-structure serialization system like <a href=\"http://search.cpan.org/~ams/Storable-2.18/Storable.pm\" rel=\"noreferrer\">Storable</a>. Two structures with the same data will produce the same blob of Storable output, so they can be compared. </p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Storable ('freeze');\n\n$Storable::canonical = 1;\n\nmy $one = { foo => 42, bar => [ 1, 2, 3 ] };\nmy $two = { foo => 42, bar => [ 1, 2, 3 ] };\n\nmy $one_s = freeze $one;\nmy $two_s = freeze $two;\n\nprint \"match\\n\" if $one_s eq $two_s;\n</code></pre>\n\n<p>...And to prove the inverse:</p>\n\n<pre><code>$one = [ 4, 5, 6 ];\n$one_s = freeze $one;\n\nprint \"no match\" if $one_s ne $two_s;\n</code></pre>\n"
},
{
"answer_id": 218633,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Digest::MD5->new->add(\n Data::Dumper->new([$structure])\n ->Purity(0)\n ->Terse(1)\n ->Indent(0)\n ->Useqq(1)\n ->Sortkeys(1)\n ->Dump()\n)->b64digest();\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349/"
] |
I have a situation where I want to create a signature of a data structure:
```
my $signature = ds_to_sig(
{ foo => 'bar',
baz => 'bundy',
boing => undef,
number => 1_234_567,
}
);
```
The aim should be that if the data structure changes then so should the signature.
Is there an established way to do this?
|
The best way to do this is to use a deep-structure serialization system like [Storable](http://search.cpan.org/~ams/Storable-2.18/Storable.pm). Two structures with the same data will produce the same blob of Storable output, so they can be compared.
```
#!/usr/bin/perl
use strict;
use warnings;
use Storable ('freeze');
$Storable::canonical = 1;
my $one = { foo => 42, bar => [ 1, 2, 3 ] };
my $two = { foo => 42, bar => [ 1, 2, 3 ] };
my $one_s = freeze $one;
my $two_s = freeze $two;
print "match\n" if $one_s eq $two_s;
```
...And to prove the inverse:
```
$one = [ 4, 5, 6 ];
$one_s = freeze $one;
print "no match" if $one_s ne $two_s;
```
|
218,535 |
<p>I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with <em>iText</em> or a Word document with <em>Aspose.Words</em>. I need to preserve any formatting within the HTML documents (within reason, honouring <b> tags is a must, CSS like <span style="blah"> is a nice-to-have). </p>
<p>Both iText and Aspose work (roughly) along the lines:</p>
<pre><code>Document document = new Document( Size.A4, Aspect.PORTRAIT );
document.setFont( "Helvetica", 20, Font.BOLD );
document.insert( "some string" )
document.setBold( true );
document.insert( "A bold string" );
</code></pre>
<p>Therefore (I think) I need some kind of HTML parser which will I can inspect for strings and styles to insert into my document.</p>
<p>Can anybody suggest a good library or a sensible approach to this problem? Platform is Java</p>
|
[
{
"answer_id": 218705,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>Adobe Acrobat Pro allows you to grab sites via HTTP and does an excellent job of preserving the style and layout. I haven't used it from an API aspect, but it may be worth looking into.</p>\n"
},
{
"answer_id": 218830,
"author": "Vinze",
"author_id": 26859,
"author_profile": "https://Stackoverflow.com/users/26859",
"pm_score": 1,
"selected": false,
"text": "<p>If the HTML is \"well-formed XML\" (XHTML) why not use an XML parser (such as Xerces) and then inspect programatically the DOM tree.</p>\n"
},
{
"answer_id": 219780,
"author": "Craig Angus",
"author_id": 15352,
"author_profile": "https://Stackoverflow.com/users/15352",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://htmlparser.sourceforge.net/\" rel=\"nofollow noreferrer\">HTMLparser</a> is a good HTML parser.</p>\n\n<p>I have used this to parse HTML on one of my projects.</p>\n\n<p>You can write your own filters to parse the HTML for what you want, so the \n <code><br></code> tag shouldn't be difficult to parse out</p>\n\n<p>Yo can parse out CSS usin the <a href=\"http://htmlparser.sourceforge.net/javadoc/org/htmlparser/filters/CssSelectorNodeFilter.html\" rel=\"nofollow noreferrer\">CssSelectorNodeFilter</a></p>\n"
},
{
"answer_id": 219821,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>You'd probably be better off getting a component that goes directly from HTML to PDF, or Word, then to try to parse the HTML document and duplicate the formatting yourself based on the HTML. If you want to convert HTML to PDF, and you use .Net, <a href=\"http://www.winnovative-software.com/\" rel=\"nofollow noreferrer\">Winnovative</a> provides a good solution.</p>\n"
},
{
"answer_id": 220508,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 0,
"selected": false,
"text": "<p>Check out the <a href=\"http://code.google.com/p/flying-saucer//\" rel=\"nofollow noreferrer\">flying saucer xhtml renderer</a>- they render well-formed XHTML files to PDF, and let you control the output using CSS. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29620/"
] |
I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with *iText* or a Word document with *Aspose.Words*. I need to preserve any formatting within the HTML documents (within reason, honouring <b> tags is a must, CSS like <span style="blah"> is a nice-to-have).
Both iText and Aspose work (roughly) along the lines:
```
Document document = new Document( Size.A4, Aspect.PORTRAIT );
document.setFont( "Helvetica", 20, Font.BOLD );
document.insert( "some string" )
document.setBold( true );
document.insert( "A bold string" );
```
Therefore (I think) I need some kind of HTML parser which will I can inspect for strings and styles to insert into my document.
Can anybody suggest a good library or a sensible approach to this problem? Platform is Java
|
[HTMLparser](http://htmlparser.sourceforge.net/) is a good HTML parser.
I have used this to parse HTML on one of my projects.
You can write your own filters to parse the HTML for what you want, so the
`<br>` tag shouldn't be difficult to parse out
Yo can parse out CSS usin the [CssSelectorNodeFilter](http://htmlparser.sourceforge.net/javadoc/org/htmlparser/filters/CssSelectorNodeFilter.html)
|
218,578 |
<p>I get the warning "childNodes is null or not an object' with different line numbers, depending on which version of the library I reference (I've tried about three different versions of 1.2.6). Consequently, I get jack for jQuery intellisense.</p>
<p>I can hack this to get it to work, but I'd rather not as I don't understand the full implications of changing the following line:</p>
<pre><code>elem = jQuery.makeArray(div.childNodes);
</code></pre>
<p>to this:</p>
<pre><code>//HACK: VS intellisense fix
if(div && div.childNodes)
elem = jQuery.makeArray(div.childNodes);
</code></pre>
<p>(The changed line only appears once in the source). What gives?</p>
|
[
{
"answer_id": 218678,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": true,
"text": "<p>Have you tried adding a reference to the documentation-only file available here?\n<a href=\"http://blogs.ipona.com/james/archive/2008/02/15/JQuery-IntelliSense-in-Visual-Studio-2008.aspx\" rel=\"nofollow noreferrer\">jQuery IntelliSense in Visual Studio 2008</a></p>\n"
},
{
"answer_id": 292666,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It does work for me;\nNot sure why it is an error for me and why the fix is needed?</p>\n"
},
{
"answer_id": 590521,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 3,
"selected": false,
"text": "<p>I ran into this same issue a little while back. Are you using the jQuery UI files as well? I was and it turned out that the jquery ui javascript file was messing up the intellisense somehow. So I created an empty vsdoc.js file for the jquery ui file and then intellisense started working. My jquery ui file was called jquery-ui-personalized-1.6rc2.min.js. Creating a file called jquery-ui-personalized-1.6rc2.min-vsdoc.js fixed the issue. </p>\n\n<p>I was also using jquery-jtemplates.js but that did not seem to cause a problem. I think it is just the jquery-ui file. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I get the warning "childNodes is null or not an object' with different line numbers, depending on which version of the library I reference (I've tried about three different versions of 1.2.6). Consequently, I get jack for jQuery intellisense.
I can hack this to get it to work, but I'd rather not as I don't understand the full implications of changing the following line:
```
elem = jQuery.makeArray(div.childNodes);
```
to this:
```
//HACK: VS intellisense fix
if(div && div.childNodes)
elem = jQuery.makeArray(div.childNodes);
```
(The changed line only appears once in the source). What gives?
|
Have you tried adding a reference to the documentation-only file available here?
[jQuery IntelliSense in Visual Studio 2008](http://blogs.ipona.com/james/archive/2008/02/15/JQuery-IntelliSense-in-Visual-Studio-2008.aspx)
|
218,604 |
<p>For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?</p>
|
[
{
"answer_id": 218620,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a programming question, but in linux you can use whatmask. </p>\n\n<pre><code>whatmask 72.20.10.0/24\n</code></pre>\n\n<p>returns </p>\n\n<pre><code>IP Entered = ..................: 72.20.10.0\nCIDR = ........................: /24\nNetmask = .....................: 255.255.255.0\nNetmask (hex) = ...............: 0xffffff00\nWildcard Bits = ...............: 0.0.0.255\n------------------------------------------------\nNetwork Address = .............: 72.20.10.0\nBroadcast Address = ...........: 72.20.10.255\nUsable IP Addresses = .........: 254\nFirst Usable IP Address = .....: 72.20.10.1\nLast Usable IP Address = ......: 72.20.10.254\n</code></pre>\n"
},
{
"answer_id": 218621,
"author": "kafuchau",
"author_id": 22371,
"author_profile": "https://Stackoverflow.com/users/22371",
"pm_score": -1,
"selected": false,
"text": "<p>You could try something simple, like taking the bitcount and dividing by 4. That'd give you the leading F's in the mask. And then take the remainder and have a switch from 0 bits to 3 bits.</p>\n"
},
{
"answer_id": 218648,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming 32-bit mask and 32-bit int.</p>\n\n<pre><code>int keepBits = 24; /* actually get it from somewhere else? */\n\nint mask = (0xffffffff >> (32 - keepBits )) << (32 - keepBits);\n</code></pre>\n\n<p>Note: this isn't necessarily the answer to the question \"What's the best way to get the network mask for an interface?\"</p>\n"
},
{
"answer_id": 218661,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 1,
"selected": false,
"text": "<pre><code>int keepbits = 24;\nint mask = keepbits > 0 ? 0x00 - (1<<(32 - keepbits)) : 0xFFFFFFFF;\n</code></pre>\n"
},
{
"answer_id": 218748,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<p>I always do it like that (in your case cidr = 24):</p>\n<pre><code>uint32_t ipv4Netmask;\n\nipv4Netmask = UINT32_MAX;\nipv4Netmask <<= 32 - cidr;\nipv4Netmask = htonl(ipv4Netmask);\n</code></pre>\n<p>This will only work with ipv4Netmask to be actually uint32_t, don't make it int, as int doesn't have to be 32 Bit on every system. The result is converted to network byte order, as that's what most system functions expect.</p>\n<p>Note that this code will fail if <code>cidr</code> is zero as then the code would shift a 32 bit variable by 32 bit and, believe it or not, that is undefined behavior in C. One would expect the result to always be zero but the C standard says that this is not defined to begin with. If your CIDR can be zero (which would only be allowed in the any IP address placeholder 0.0.0.0/0), then the code must catch special case.</p>\n"
},
{
"answer_id": 218826,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a solution in VBScript, FWIW</p>\n\n<pre><code>option explicit\n\n'whatmask 72.20.10.0/24\nIf WScript.Arguments.Unnamed.Count < 1 Then\n WScript.Echo \"WhatMask xxx.xxx.xxx.xxx/xx\"\n Wscript.Quit\nEnd If\n\nDim sToFind\nDim aParts\nDim nSubnet\n\nsToFind = WScript.Arguments(0)\naParts = Split( sToFind, \"/\", 2 )\nnSubnet = aParts(1)\n\nif nSubnet < 1 or nSubnet > 32 then\n WScript.echo \"Subnet out of range [1..32]\"\n Wscript.quit\nend if\n\nDim sBinary\nsBinary = String( nSubnet, \"1\")\nsBinary = sBinary & String( 32 - nSubnet, \"0\" )\n\nwscript.echo \"0x\" & lcase( binary2hexadecimal( sBinary ) )\n\nfunction binary2hexadecimal( sBin )\n dim sSlice\n dim sResult\n dim i\n for i = 1 to len( sBin ) step 4\n sSlice = mid( sBin, i, 4 )\n sResult = sResult & hex( binary2decimal( sSlice ) )\n next\n binary2hexadecimal = sResult\nend function\n\nfunction binary2decimal( sFourbits )\n dim i\n dim bit\n dim nResult\n nResult = 0\n for i = 4 to 1 step -1\n bit = mid(sFourbits, i, 1 )\n nResult = nResult * 2 + bit\n next\n binary2decimal = nResult\nend function\n</code></pre>\n\n<p>From the command line</p>\n\n<pre><code>>whatmask.vbs 123.12.123.17/23\n 0xfffff700\n</code></pre>\n"
},
{
"answer_id": 583404,
"author": "joeforker",
"author_id": 36330,
"author_profile": "https://Stackoverflow.com/users/36330",
"pm_score": 2,
"selected": true,
"text": "<p>Why waste time with subtraction or ternary statements?</p>\n\n<pre><code>int suffix = 24;\nint mask = 0xffffffff ^ 0xffffffff >> suffix;\n</code></pre>\n\n<p>If you know your integer is exactly 32 bits long then you only need to type 0xffffffff once.</p>\n\n<pre><code>int32_t mask = ~(0xffffffff >> suffix);\n</code></pre>\n\n<p>Both compile to the exact same assembly code.</p>\n"
},
{
"answer_id": 2641483,
"author": "Chris Weber",
"author_id": 194653,
"author_profile": "https://Stackoverflow.com/users/194653",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/* C# version merging some of the other contributions and corrected for byte order. */\n\nint cidr = 24;\n\nvar ipv4Netmask = 0xFFFFFFFF;\n\nipv4Netmask <<= 32 - cidr;\n\nbyte[] bytes = BitConverter.GetBytes(ipv4Netmask);\n\nArray.Reverse(bytes);\n\nipv4Netmask = BitConverter.ToUInt32(bytes, 0); \n\n// mask is now ready for use such as:\n\nvar netmask = new IPAddress(ipv4Netmask);\n</code></pre>\n"
},
{
"answer_id": 4462135,
"author": "RichB",
"author_id": 47056,
"author_profile": "https://Stackoverflow.com/users/47056",
"pm_score": 0,
"selected": false,
"text": "<p>Be careful when you use the previous answers with code like: </p>\n\n<pre><code>0xFFFFFFFF << 32 - cidr\n</code></pre>\n\n<p>or</p>\n\n<pre><code>-1 << 32 - cidr\n</code></pre>\n\n<p>In C# at least, it will mask the shift count with 0x1F first. So, for a cidr with prefix 0 (ie the entire IPv4 address range):</p>\n\n<pre><code>int cidr=0;\n0xFFFFFFFF << (32 - cidr) == 0xFFFFFFFF\n</code></pre>\n\n<p>which is not what you want. Instead, you should use:</p>\n\n<pre><code>int cidr=0;\n(int)(0xFFFFFFFFL << (32 - cidr)) == 0\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19655/"
] |
For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?
|
Why waste time with subtraction or ternary statements?
```
int suffix = 24;
int mask = 0xffffffff ^ 0xffffffff >> suffix;
```
If you know your integer is exactly 32 bits long then you only need to type 0xffffffff once.
```
int32_t mask = ~(0xffffffff >> suffix);
```
Both compile to the exact same assembly code.
|
218,608 |
<p>I need to do a few very simple URL manipulations in Java. Like get the value for a parameter in the query, or update it, ... I was expecting to find a simple utility class doing that in the commons-lang package, but no. I know it is a simple problem, but if there is something already written, why do it again ? Do you know of any ?</p>
<p>I would like to have at least the following capabilities :</p>
<pre><code>String myUrl = "http://www.example.com/test.html?toto=1&titi=2";
// get the value of a parameter
String parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "1");
// update a parameter
String newUrl = UrlUtils.updateParameter(myUrl, "toto", 3);
parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "3");
</code></pre>
<p>Ideally, it would take care of all encoding related issues, and work with java.net.Url as well as with Strings.</p>
<p>Thanks for your help !</p>
|
[
{
"answer_id": 218674,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>I think what you want is called a query string parser instead of an url manipulator and here's one: <a href=\"http://ostermiller.org/utils/CGIParser.java.html\" rel=\"noreferrer\">http://ostermiller.org/utils/CGIParser.java.html</a></p>\n"
},
{
"answer_id": 4961599,
"author": "piepera",
"author_id": 255830,
"author_profile": "https://Stackoverflow.com/users/255830",
"pm_score": 2,
"selected": false,
"text": "<p>Apache's httpcomponents library has a URL decoder: <a href=\"http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html\" rel=\"nofollow\">http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html</a></p>\n\n<p>Httpcomponents is the successor to commons http client.</p>\n"
},
{
"answer_id": 21974564,
"author": "youknowjack",
"author_id": 3329499,
"author_profile": "https://Stackoverflow.com/users/3329499",
"pm_score": 2,
"selected": false,
"text": "<p>Indeed has released an efficient Java library for query string and number parsing:</p>\n\n<p><a href=\"http://engineering.indeed.com/blog/2014/02/efficient-query-string-parsing-util-urlparsing/\" rel=\"nofollow\">http://engineering.indeed.com/blog/2014/02/efficient-query-string-parsing-util-urlparsing/</a></p>\n\n<p><a href=\"https://github.com/indeedeng/util/tree/master/urlparsing\" rel=\"nofollow\">https://github.com/indeedeng/util/tree/master/urlparsing</a></p>\n\n<p>(Disclaimer: I am an engineering director at Indeed.)</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23704/"
] |
I need to do a few very simple URL manipulations in Java. Like get the value for a parameter in the query, or update it, ... I was expecting to find a simple utility class doing that in the commons-lang package, but no. I know it is a simple problem, but if there is something already written, why do it again ? Do you know of any ?
I would like to have at least the following capabilities :
```
String myUrl = "http://www.example.com/test.html?toto=1&titi=2";
// get the value of a parameter
String parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "1");
// update a parameter
String newUrl = UrlUtils.updateParameter(myUrl, "toto", 3);
parameterValue = UrlUtils.getParameterValue(myUrl, "toto");
Assert.equals(parameterValue, "3");
```
Ideally, it would take care of all encoding related issues, and work with java.net.Url as well as with Strings.
Thanks for your help !
|
I think what you want is called a query string parser instead of an url manipulator and here's one: <http://ostermiller.org/utils/CGIParser.java.html>
|
218,616 |
<p>Given the Python function:</p>
<pre><code>def a_method(arg1, arg2):
pass
</code></pre>
<p>How can I extract the number and names of the arguments. I.e., given that I have a reference to <code>func</code>, I want the <code>func.[something]</code> to return <code>("arg1", "arg2")</code>.</p>
<p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed <code>"a,b"</code> when I call <code>a_method("a", "b")</code>?</p>
|
[
{
"answer_id": 218625,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 7,
"selected": false,
"text": "<p>In CPython, the number of arguments is</p>\n\n<pre><code>a_method.func_code.co_argcount\n</code></pre>\n\n<p>and their names are in the beginning of</p>\n\n<pre><code>a_method.func_code.co_varnames\n</code></pre>\n\n<p>These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.</p>\n\n<p>One portable way to admit \"pass-through\" arguments is to define your function with the signature <code>func(*args, **kwargs)</code>. This is used a lot in e.g. <a href=\"https://matplotlib.org/\" rel=\"noreferrer\">matplotlib</a>, where the outer API layer passes lots of keyword arguments to the lower-level API.</p>\n"
},
{
"answer_id": 218709,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 10,
"selected": true,
"text": "<p>Take a look at the <a href=\"http://docs.python.org/library/inspect.html\" rel=\"noreferrer\"><code>inspect</code></a> module - this will do the inspection of the various code object properties for you.</p>\n\n<pre><code>>>> inspect.getfullargspec(a_method)\n(['arg1', 'arg2'], None, None, None)\n</code></pre>\n\n<p>The other results are the name of the *args and **kwargs variables, and the defaults provided. ie.</p>\n\n<pre><code>>>> def foo(a, b, c=4, *arglist, **keywords): pass\n>>> inspect.getfullargspec(foo)\n(['a', 'b', 'c'], 'arglist', 'keywords', (4,))\n</code></pre>\n\n<p>Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a <code>ValueError</code> if you use <code>inspect.getfullargspec()</code> on a built-in function.</p>\n\n<p>Since Python 3.3, you can use <a href=\"https://docs.python.org/library/inspect.html#introspecting-callables-with-the-signature-object\" rel=\"noreferrer\"><code>inspect.signature()</code></a> to see the call signature of a callable object:</p>\n\n<pre><code>>>> inspect.signature(foo)\n<Signature (a, b, c=4, *arglist, **keywords)>\n</code></pre>\n"
},
{
"answer_id": 220366,
"author": "hlzr",
"author_id": 19139,
"author_profile": "https://Stackoverflow.com/users/19139",
"pm_score": 4,
"selected": false,
"text": "<p>Here is something I think will work for what you want, using a decorator.</p>\n\n<pre><code>class LogWrappedFunction(object):\n def __init__(self, function):\n self.function = function\n\n def logAndCall(self, *arguments, **namedArguments):\n print \"Calling %s with arguments %s and named arguments %s\" %\\\n (self.function.func_name, arguments, namedArguments)\n self.function.__call__(*arguments, **namedArguments)\n\ndef logwrap(function):\n return LogWrappedFunction(function).logAndCall\n\n@logwrap\ndef doSomething(spam, eggs, foo, bar):\n print \"Doing something totally awesome with %s and %s.\" % (spam, eggs)\n\n\ndoSomething(\"beans\",\"rice\", foo=\"wiggity\", bar=\"wack\")\n</code></pre>\n\n<p>Run it, it will yield the following output:</p>\n\n<pre><code>C:\\scripts>python decoratorExample.py\nCalling doSomething with arguments ('beans', 'rice') and named arguments {'foo':\n 'wiggity', 'bar': 'wack'}\nDoing something totally awesome with beans and rice.\n</code></pre>\n"
},
{
"answer_id": 2991341,
"author": "Damian",
"author_id": 288183,
"author_profile": "https://Stackoverflow.com/users/288183",
"pm_score": 4,
"selected": false,
"text": "<p>I think what you're looking for is the locals method - </p>\n\n<pre><code>\nIn [6]: def test(a, b):print locals()\n ...: \n\nIn [7]: test(1,2) \n{'a': 1, 'b': 2}\n</code></pre>\n"
},
{
"answer_id": 16542145,
"author": "Mehdi Behrooz",
"author_id": 748126,
"author_profile": "https://Stackoverflow.com/users/748126",
"pm_score": 5,
"selected": false,
"text": "<p>In a decorator method, you can list arguments of the original method in this way:</p>\n\n<pre><code>import inspect, itertools \n\ndef my_decorator():\n\n def decorator(f):\n\n def wrapper(*args, **kwargs):\n\n # if you want arguments names as a list:\n args_name = inspect.getargspec(f)[0]\n print(args_name)\n\n # if you want names and values as a dictionary:\n args_dict = dict(itertools.izip(args_name, args))\n print(args_dict)\n\n # if you want values as a list:\n args_values = args_dict.values()\n print(args_values)\n</code></pre>\n\n<p>If the <code>**kwargs</code> are important for you, then it will be a bit complicated:</p>\n\n<pre><code> def wrapper(*args, **kwargs):\n\n args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))\n args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))\n args_values = args_dict.values()\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>@my_decorator()\ndef my_function(x, y, z=3):\n pass\n\n\nmy_function(1, y=2, z=3, w=0)\n# prints:\n# ['x', 'y', 'z', 'w']\n# {'y': 2, 'x': 1, 'z': 3, 'w': 0}\n# [1, 2, 3, 0]\n</code></pre>\n"
},
{
"answer_id": 40363565,
"author": "argaen",
"author_id": 3481357,
"author_profile": "https://Stackoverflow.com/users/3481357",
"pm_score": 5,
"selected": false,
"text": "<p>The Python 3 version is:</p>\n\n<pre><code>def _get_args_dict(fn, args, kwargs):\n args_names = fn.__code__.co_varnames[:fn.__code__.co_argcount]\n return {**dict(zip(args_names, args)), **kwargs}\n</code></pre>\n\n<p>The method returns a dictionary containing both args and kwargs.</p>\n"
},
{
"answer_id": 41526819,
"author": "jeromej",
"author_id": 1524913,
"author_profile": "https://Stackoverflow.com/users/1524913",
"pm_score": -1,
"selected": false,
"text": "<p>What about <code>dir()</code> and <code>vars()</code> now?</p>\n\n<p>Seems doing exactly what is being asked super simply…</p>\n\n<p><strong>Must be called from within the function scope.</strong></p>\n\n<p>But be wary that it will return <em>all</em> local variables so be sure to do it at the very beginning of the function if needed.</p>\n\n<p>Also note that, as pointed out in the comments, this doesn't allow it to be done from outside the scope. So not exactly OP's scenario but still matches the question title. Hence my answer.</p>\n"
},
{
"answer_id": 42949339,
"author": "ASMik09",
"author_id": 1981531,
"author_profile": "https://Stackoverflow.com/users/1981531",
"pm_score": 2,
"selected": false,
"text": "<p>Update for <a href=\"https://stackoverflow.com/questions/218616/getting-method-parameter-names-in-python/218709#218709\">Brian's answer</a>:</p>\n\n<p>If a function in Python 3 has keyword-only arguments, then you need to use <code>inspect.getfullargspec</code>:</p>\n\n<pre><code>def yay(a, b=10, *, c=20, d=30):\n pass\ninspect.getfullargspec(yay)\n</code></pre>\n\n<p>yields this:</p>\n\n<pre><code>FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})\n</code></pre>\n"
},
{
"answer_id": 44261531,
"author": "lovesh",
"author_id": 535962,
"author_profile": "https://Stackoverflow.com/users/535962",
"pm_score": 2,
"selected": false,
"text": "<p>Returns a list of argument names, takes care of partials and regular functions:</p>\n\n<pre><code>def get_func_args(f):\n if hasattr(f, 'args'):\n return f.args\n else:\n return list(inspect.signature(f).parameters)\n</code></pre>\n"
},
{
"answer_id": 45332292,
"author": "Peter Majko",
"author_id": 4528229,
"author_profile": "https://Stackoverflow.com/users/4528229",
"pm_score": 4,
"selected": false,
"text": "<p>Python 3.5+:</p>\n<blockquote>\n<p>DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec()</p>\n</blockquote>\n<p>So previously:</p>\n<pre><code>func_args = inspect.getargspec(function).args\n</code></pre>\n<p>Now:</p>\n<pre><code>func_args = list(inspect.signature(function).parameters.keys())\n</code></pre>\n<p>To test:</p>\n<pre><code>'arg' in list(inspect.signature(function).parameters.keys())\n</code></pre>\n<p>Given that we have function 'function' which takes argument 'arg', this will evaluate as True, otherwise as False.</p>\n<p>Example from the Python console:</p>\n<pre><code>Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32\n>>> import inspect\n>>> 'iterable' in list(inspect.signature(sum).parameters.keys())\nTrue\n</code></pre>\n"
},
{
"answer_id": 45781963,
"author": "Kfir Eisner",
"author_id": 7337300,
"author_profile": "https://Stackoverflow.com/users/7337300",
"pm_score": 4,
"selected": false,
"text": "<p>In Python 3.+ with the <code>Signature</code> object at hand, an easy way to get a mapping between argument names to values, is using the Signature's <code>bind()</code> method!</p>\n\n<p>For example, here is a decorator for printing a map like that:</p>\n\n<pre><code>import inspect\n\ndef decorator(f):\n def wrapper(*args, **kwargs):\n bound_args = inspect.signature(f).bind(*args, **kwargs)\n bound_args.apply_defaults()\n print(dict(bound_args.arguments))\n\n return f(*args, **kwargs)\n\n return wrapper\n\n@decorator\ndef foo(x, y, param_with_default=\"bars\", **kwargs):\n pass\n\nfoo(1, 2, extra=\"baz\")\n# This will print: {'kwargs': {'extra': 'baz'}, 'param_with_default': 'bars', 'y': 2, 'x': 1}\n</code></pre>\n"
},
{
"answer_id": 53715901,
"author": "Alpha",
"author_id": 1332656,
"author_profile": "https://Stackoverflow.com/users/1332656",
"pm_score": 2,
"selected": false,
"text": "<p>In python 3, below is to make <code>*args</code> and <code>**kwargs</code> into a <code>dict</code> (use <code>OrderedDict</code> for python < 3.6 to maintain <code>dict</code> orders):</p>\n\n<pre><code>from functools import wraps\n\ndef display_param(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n\n param = inspect.signature(func).parameters\n all_param = {\n k: args[n] if n < len(args) else v.default\n for n, (k, v) in enumerate(param.items()) if k != 'kwargs'\n }\n all_param .update(kwargs)\n print(all_param)\n\n return func(**all_param)\n return wrapper\n</code></pre>\n"
},
{
"answer_id": 55160591,
"author": "smarie",
"author_id": 7262247,
"author_profile": "https://Stackoverflow.com/users/7262247",
"pm_score": 0,
"selected": false,
"text": "<p>To update a little bit <a href=\"https://stackoverflow.com/a/218709/7262247\">Brian's answer</a>, there is now a nice backport of <code>inspect.signature</code> that you can use in older python versions: <a href=\"https://github.com/testing-cabal/funcsigs\" rel=\"nofollow noreferrer\"><code>funcsigs</code></a>.\nSo my personal preference would go for</p>\n\n<pre><code>try: # python 3.3+\n from inspect import signature\nexcept ImportError:\n from funcsigs import signature\n\ndef aMethod(arg1, arg2):\n pass\n\nsig = signature(aMethod)\nprint(sig)\n</code></pre>\n\n<p>For fun, if you're interested in playing with <code>Signature</code> objects and even creating functions with random signatures dynamically you can have a look at my <a href=\"https://smarie.github.io/python-makefun/\" rel=\"nofollow noreferrer\"><code>makefun</code></a> project.</p>\n"
},
{
"answer_id": 57373751,
"author": "dildeolupbiten",
"author_id": 8016168,
"author_profile": "https://Stackoverflow.com/users/8016168",
"pm_score": 4,
"selected": false,
"text": "<p>Here is another way to get the function parameters without using any module.</p>\n<pre><code>def get_parameters(func):\n keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]\n sorter = {j: i for i, j in enumerate(keys[::-1])} \n values = func.__defaults__[::-1]\n kwargs = {i: j for i, j in zip(keys, values)}\n sorted_args = tuple(\n sorted([i for i in keys if i not in kwargs], key=sorter.get)\n )\n sorted_kwargs = {\n i: kwargs[i] for i in sorted(kwargs.keys(), key=sorter.get)\n } \n return sorted_args, sorted_kwargs\n\n\ndef f(a, b, c="hello", d="world"): var = a\n \n\nprint(get_parameters(f))\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>(('a', 'b'), {'c': 'hello', 'd': 'world'})\n</code></pre>\n"
},
{
"answer_id": 57597386,
"author": "Nikolay Makhalin",
"author_id": 6408118,
"author_profile": "https://Stackoverflow.com/users/6408118",
"pm_score": 3,
"selected": false,
"text": "<p><code>inspect.signature</code> is very slow. Fastest way is </p>\n\n<pre><code>def f(a, b=1, *args, c, d=1, **kwargs):\n pass\n\nf_code = f.__code__\nf_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount] # ('a', 'b', 'c', 'd')\n</code></pre>\n"
},
{
"answer_id": 69107403,
"author": "Brisco",
"author_id": 10603374,
"author_profile": "https://Stackoverflow.com/users/10603374",
"pm_score": -1,
"selected": false,
"text": "<p>I was googling to find how to print function name and supplied arguments for an assignment I had to create a decorator to print them and I used this:</p>\n<pre><code>def print_func_name_and_args(func):\n \n def wrapper(*args, **kwargs):\n print(f"Function name: '{func.__name__}' supplied args: '{args}'")\n func(args[0], args[1], args[2])\n return wrapper\n\n\n@print_func_name_and_args\ndef my_function(n1, n2, n3):\n print(n1 * n2 * n3)\n \nmy_function(1, 2, 3)\n\n#Function name: 'my_function' supplied args: '(1, 2, 3)'\n</code></pre>\n"
},
{
"answer_id": 69762539,
"author": "x4444",
"author_id": 895676,
"author_profile": "https://Stackoverflow.com/users/895676",
"pm_score": -1,
"selected": false,
"text": "<p>Is it possible to use <code>inspect</code> API to read constant argument value <code>-1</code> from the lambda func <code>fun</code> in the code below?</p>\n<pre><code>def my_func(v, axis):\n pass\n\nfun = lambda v: my_func(v, axis=-1)\n</code></pre>\n"
},
{
"answer_id": 71565623,
"author": "Jose Enrique",
"author_id": 3308840,
"author_profile": "https://Stackoverflow.com/users/3308840",
"pm_score": 1,
"selected": false,
"text": "<p>Simple easy to read answer as of python 3.0 onwards:</p>\n<pre><code>import inspect\n\n\nargs_names = inspect.signature(function).parameters.keys()\nargs_dict = {\n **dict(zip(args_names, args)),\n **kwargs,\n}\n\n\n</code></pre>\n"
},
{
"answer_id": 73114235,
"author": "Thiago Lutten Leitão",
"author_id": 19620075,
"author_profile": "https://Stackoverflow.com/users/19620075",
"pm_score": 0,
"selected": false,
"text": "<p>Easiest way to manipulate parameters names of some function:</p>\n<pre><code>parameters_list = list(inspect.signature(self.YOUR_FUNCTION).parameters))\n</code></pre>\n<p>Result:</p>\n<pre><code>['YOUR_FUNCTION_parameter_name_0', 'YOUR_FUNCTION_parameter_name_1', ...]\n</code></pre>\n<p>Making this way will be even easier since you get the specific one:</p>\n<pre><code>parameters_list = list(inspect.signature(self.YOUR_FUNCTION).parameters)[0]\n</code></pre>\n<p>Result:</p>\n<pre><code>'YOUR_FUNCTION_parameter_name_0'\n</code></pre>\n"
},
{
"answer_id": 74437996,
"author": "Zio",
"author_id": 13111269,
"author_profile": "https://Stackoverflow.com/users/13111269",
"pm_score": 0,
"selected": false,
"text": "<p>I have another suggestion for those who, like me, are looking for a solution that puts inside a decorator all parameters and their values (default or not) into a dictonary.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import inspect\n\ndef get_arguments(func, args, kwargs, is_method=False):\n offset = 1 if is_method else 0\n specs = inspect.getfullargspec(func)\n d = {}\n for i, parameter in enumerate(specs.args[offset:]):\n i += offset\n if i < len(args):\n d[parameter] = args[i]\n elif parameter in kwargs:\n d[parameter] = kwargs[parameter]\n else:\n d[parameter] = specs.defaults[i - len(args)]\n return d\n</code></pre>\n<p>Now printing the return value of <strong>get_arguments</strong> inside a decorator like this one</p>\n<pre class=\"lang-py prettyprint-override\"><code>def a_function_decorator(func):\n def inner(*args, **kwargs):\n print(get_arguments(func, args, kwargs))\n return func(*args, **kwargs)\n\n return inner\n</code></pre>\n<p>and apply it on a function like</p>\n<pre class=\"lang-py prettyprint-override\"><code>@a_function_decorator\ndef foo(a, b, c="default_c", d="default_d"):\n pass\n</code></pre>\n<p>will give us</p>\n<pre class=\"lang-py prettyprint-override\"><code>foo(1, 2, d="eek")\n# {'a': 1, 'b': 2, 'c': 'default_c', 'd': 'eek'}\n\nfoo(1, 2, "blah")\n# {'a': 1, 'b': 2, 'c': 'blah', 'd': 'default_c'}\n\nfoo(1, 2)\n# {'a': 1, 'b': 2, 'c': 'default_c', 'd': 'default_d'}\n</code></pre>\n<p>Same works for methods</p>\n<pre class=\"lang-py prettyprint-override\"><code>def a_method_decorator(func):\n def inner(*args, **kwargs):\n print(get_arguments(func, args, kwargs, is_method=True))\n return func(*args, **kwargs)\n\n return inner\n\nclass Bar:\n @a_method_decorator\n def foo(self, a, b, c="default_c", d="default_d"):\n pass\n\nBar().foo(1, 2, d="eek")\n#{'a': 1, 'b': 2, 'c': 'default_c', 'd': 'eek'}\nBar().foo(1, 2, "blah")\n# {'a': 1, 'b': 2, 'c': 'blah', 'd': 'default_c'}\nBar().foo(1, 2)\n# {'a': 1, 'b': 2, 'c': 'default_c', 'd': 'default_d'}\n</code></pre>\n<p>It's certainly not the prettiest solution, but it's the first one I've seen that does exactly what I want.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] |
Given the Python function:
```
def a_method(arg1, arg2):
pass
```
How can I extract the number and names of the arguments. I.e., given that I have a reference to `func`, I want the `func.[something]` to return `("arg1", "arg2")`.
The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed `"a,b"` when I call `a_method("a", "b")`?
|
Take a look at the [`inspect`](http://docs.python.org/library/inspect.html) module - this will do the inspection of the various code object properties for you.
```
>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)
```
The other results are the name of the \*args and \*\*kwargs variables, and the defaults provided. ie.
```
>>> def foo(a, b, c=4, *arglist, **keywords): pass
>>> inspect.getfullargspec(foo)
(['a', 'b', 'c'], 'arglist', 'keywords', (4,))
```
Note that some callables may not be introspectable in certain implementations of Python. For Example, in CPython, some built-in functions defined in C provide no metadata about their arguments. As a result, you will get a `ValueError` if you use `inspect.getfullargspec()` on a built-in function.
Since Python 3.3, you can use [`inspect.signature()`](https://docs.python.org/library/inspect.html#introspecting-callables-with-the-signature-object) to see the call signature of a callable object:
```
>>> inspect.signature(foo)
<Signature (a, b, c=4, *arglist, **keywords)>
```
|
218,638 |
<p>Using the ClearCase find command, how do I find all files in a directory that do not have the name pom.xml? </p>
<p>I'd like to pass other selection options to the ClearCase find command so I'd prefer not to execute another command.</p>
<p>I am using a RedHat linux version of ClearCase. I have tried "cleartool find ! -name pom.xml -print" and that does not work.</p>
<p>PS: I do not use ClearCase by choice, it's mandated on my project. This is one of the reasons I hate it. I've read the man pages several times and see no clear way to do this that works!</p>
|
[
{
"answer_id": 218976,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 2,
"selected": false,
"text": "<p>ClearCase wildcards doesn't have inversion (AFAIR) but you can use grep for this - </p>\n\n<pre><code>cleartool ls -short -nxname | grep -v pom.xml\n</code></pre>\n"
},
{
"answer_id": 224759,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<p>You seem to forget the <strong><em>-exec</em></strong> option of the cleartool find command. </p>\n\n<p>It actually does allow you to execute other commands than cleartool ones, including system ones (like a sh or DOS script). </p>\n\n<p>I know you would \"prefer not to execute another command\", but if that other system script is part of the exec option of a find command... it can be argued it is still <em>one</em> command ;)</p>\n\n<p>So create a simple script like:</p>\n\n<p>(Unix 'print.sh')</p>\n\n<pre><code>#!/bin/sh\nif [ $1 != $2 ] ; then\n echo $1\nfi\n</code></pre>\n\n<p>(windows 'print.bat')</p>\n\n<pre><code>@echo off\nif not \"%1\"==\"%2\" echo \"%1\" \n</code></pre>\n\n<p>Put that script either in your search directory, or add the script path to your %PATH% or $PATH environment.</p>\n\n<p>And finally, use the find command (with all the <a href=\"http://www.samecs.com/commands/cleartool%20commands/find/find.htm\" rel=\"nofollow noreferrer\">other options</a> regarding date filtering, branch filtering and so on)</p>\n\n<p>(Unix)</p>\n\n<pre><code>cleartool find . -nrec -type f -exec './print.sh $CLEARCASE_PN ./pom.xml'\n</code></pre>\n\n<p>(windows)</p>\n\n<pre><code>cleartool find . -nrec -type f -exec \"print.bat %CLEARCASE_PN% .\\pom.xml\"\n</code></pre>\n\n<p>And here you go: \"all files in a directory that do not have the name pom.xml\".</p>\n\n<p>Note: the '-type f' option of the find command allows you to restrict the search to file names only (not directory names).</p>\n"
},
{
"answer_id": 7990062,
"author": "Pulak Agrawal",
"author_id": 1021425,
"author_profile": "https://Stackoverflow.com/users/1021425",
"pm_score": 2,
"selected": false,
"text": "<p>There is another solution which might work for you. Try</p>\n\n<p><a href=\"http://clearantlib.sourceforge.net/ccapply.html\" rel=\"nofollow\">ccapply task</a></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476/"
] |
Using the ClearCase find command, how do I find all files in a directory that do not have the name pom.xml?
I'd like to pass other selection options to the ClearCase find command so I'd prefer not to execute another command.
I am using a RedHat linux version of ClearCase. I have tried "cleartool find ! -name pom.xml -print" and that does not work.
PS: I do not use ClearCase by choice, it's mandated on my project. This is one of the reasons I hate it. I've read the man pages several times and see no clear way to do this that works!
|
You seem to forget the ***-exec*** option of the cleartool find command.
It actually does allow you to execute other commands than cleartool ones, including system ones (like a sh or DOS script).
I know you would "prefer not to execute another command", but if that other system script is part of the exec option of a find command... it can be argued it is still *one* command ;)
So create a simple script like:
(Unix 'print.sh')
```
#!/bin/sh
if [ $1 != $2 ] ; then
echo $1
fi
```
(windows 'print.bat')
```
@echo off
if not "%1"=="%2" echo "%1"
```
Put that script either in your search directory, or add the script path to your %PATH% or $PATH environment.
And finally, use the find command (with all the [other options](http://www.samecs.com/commands/cleartool%20commands/find/find.htm) regarding date filtering, branch filtering and so on)
(Unix)
```
cleartool find . -nrec -type f -exec './print.sh $CLEARCASE_PN ./pom.xml'
```
(windows)
```
cleartool find . -nrec -type f -exec "print.bat %CLEARCASE_PN% .\pom.xml"
```
And here you go: "all files in a directory that do not have the name pom.xml".
Note: the '-type f' option of the find command allows you to restrict the search to file names only (not directory names).
|
218,663 |
<p>I work for a custom cabinetry manufacturer and we write our own pricing program for our product. I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet. I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up. Is there any way in Access VBA to know whether the new record is being pasted or entered manually?</p>
|
[
{
"answer_id": 218783,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps something on the lines of this would suit.</p>\n\n<pre><code>Option Compare Database\nPublic gvarPasted As Boolean\n\nPrivate Sub txtText_AfterUpdate()\nIf Not gvarPasted Then\n 'Open pop-up here\nElse\n gvarPasted = False\nEnd If\nEnd Sub\n\nPrivate Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer)\n'Detect ctrl-V combination\nIf Shift = acCtrlMask And KeyCode = vbKeyV Then\n gvarPasted = True\nEnd If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 218958,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": true,
"text": "<p>You can customize the menu, for example if you add code like so to a standard module:</p>\n\n<pre><code>Public gvarPasted As Boolean\n\nFunction AssignVar()\n gvarPasted = True\n DoCmd.RunCommand acCmdPaste\nEnd Function\n</code></pre>\n\n<p>You can set the Action property of Paste on the menu to this function using the customize option of the toolbar menu. You will also need to create your own shortcut menu (right-click menu) to use in place of the built-in menu. The shortcut menu can either be assigned for all forms or for just the form that requires it. It is also possible to turn off the shortcut menus for all forms.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4549/"
] |
I work for a custom cabinetry manufacturer and we write our own pricing program for our product. I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet. I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up. Is there any way in Access VBA to know whether the new record is being pasted or entered manually?
|
You can customize the menu, for example if you add code like so to a standard module:
```
Public gvarPasted As Boolean
Function AssignVar()
gvarPasted = True
DoCmd.RunCommand acCmdPaste
End Function
```
You can set the Action property of Paste on the menu to this function using the customize option of the toolbar menu. You will also need to create your own shortcut menu (right-click menu) to use in place of the built-in menu. The shortcut menu can either be assigned for all forms or for just the form that requires it. It is also possible to turn off the shortcut menus for all forms.
|
218,681 |
<p>The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.</p>
<p>'****** Console application BEGINS.</p>
<pre><code>Module Main
Const DefaultTestFilePath As String = "D:\Test.xps"
Const DefaultLoopRuns As Integer = 1000
Public Sub Main(ByVal Args As String())
Dim PathToTestXps As String = DefaultTestFilePath
Dim NumberOfLoops As Integer = DefaultLoopRuns
If (Args.Count >= 1) Then PathToTestXps = Args(0)
If (Args.Count >= 2) Then NumberOfLoops = CInt(Args(1))
Console.Clear()
Console.WriteLine("Start - {0}", GC.GetTotalMemory(True))
For LoopCount As Integer = 1 To NumberOfLoops
Console.CursorLeft = 0
Console.Write("Loop {0:d5}", LoopCount)
' The more complex the XPS document and the more loops, the more memory is lost.
Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence
' This line leaks a chunk of memory each time, when commented out it does not.
FixedDocSequence = XPSItem.GetFixedDocumentSequence
End Using
Next
Console.WriteLine()
GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals).
Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True))
Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).")
Console.ReadKey()
End Sub
End Module
</code></pre>
<p>'****** Console application ENDS.</p>
<p>The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).</p>
<p>The code was originally in another thread and class but has been simplified to this.</p>
<p>Any help greatly appreciated.</p>
<p>Ryan</p>
|
[
{
"answer_id": 218776,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>I can't give you any authoritative advice, but I did have a few thoughts:</p>\n\n<ul>\n<li>If you want to watch your memory inside the loop, you need to be collecting memory inside the loop as well. Otherwise you will <em>appear</em> to leak memory by design, since it's more efficient to collect larger blocks less frequently (as needed) rather than constantly be collecting small amounts. In this case the scope block creating the using statement <em>should</em> be enough, but your use of GC.Collect indicates that maybe something else is going on.</li>\n<li>Even GC.Collect is only a suggestion (okay, very <em>strong</em> suggestion, but still a suggestion): it doesn't guarantee that all outstanding memory is collected.</li>\n<li>If the internal XPS code really is leaking memory, the only way to force the OS to collect it is to trick the OS into thinking the application has ended. To do that you could perhaps create a dummy application that handles your xps code and is called from the main app, or moving the xps code into it's own AppDomain inside your main code may be enough as well.</li>\n</ul>\n"
},
{
"answer_id": 219165,
"author": "Ryan O'Neill",
"author_id": 26221,
"author_profile": "https://Stackoverflow.com/users/26221",
"pm_score": 4,
"selected": true,
"text": "<p>Well, I found it. It IS a bug in the framework and to work around it you add a call to UpdateLayout. Using statement can be changed to the following to provide a fix;</p>\n\n<pre><code> Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)\n Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence\n Dim DocPager As Windows.Documents.DocumentPaginator\n\n FixedDocSequence = XPSItem.GetFixedDocumentSequence\n DocPager = FixedDocSequence.DocumentPaginator\n DocPager.ComputePageCount()\n\n ' This is the fix, each page must be laid out otherwise resources are never released.'\n For PageIndex As Integer = 0 To DocPager.PageCount - 1\n DirectCast(DocPager.GetPage(PageIndex).Visual, Windows.Documents.FixedPage).UpdateLayout()\n Next\n FixedDocSequence = Nothing\n End Using\n</code></pre>\n"
},
{
"answer_id": 2410588,
"author": "Sean Aitken",
"author_id": 71524,
"author_profile": "https://Stackoverflow.com/users/71524",
"pm_score": 3,
"selected": false,
"text": "<p>Ran into this today. Interestingly, when I gazed into things using Reflector.NET, I found the fix involved calling UpdateLayout() on the ContextLayoutManager associated with the current Dispatcher. (read: no need to iterate over pages).</p>\n\n<p>Basically, the code to be called (use reflection here) is:</p>\n\n<pre><code>ContextLayoutManager.From(Dispatcher.CurrentDispatcher).UpdateLayout();\n</code></pre>\n\n<p>Definitely feels like a small oversight by MS.</p>\n\n<p>For the lazy or unfamiliar, this code works:</p>\n\n<pre><code>Assembly presentationCoreAssembly = Assembly.GetAssembly(typeof (System.Windows.UIElement));\nType contextLayoutManagerType = presentationCoreAssembly.GetType(\"System.Windows.ContextLayoutManager\");\nobject contextLayoutManager = contextLayoutManagerType.InvokeMember(\"From\",\nBindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new[] {dispatcher});\ncontextLayoutManagerType.InvokeMember(\"UpdateLayout\", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, contextLayoutManager, null);\n</code></pre>\n\n<p>FxCop will complain, but maybe it's fixed in the next framework version. The code posted by the author seems to be \"safer\" if you would prefer not to use reflection.</p>\n\n<p>HTH!</p>\n"
},
{
"answer_id": 4383800,
"author": "Will",
"author_id": 534488,
"author_profile": "https://Stackoverflow.com/users/534488",
"pm_score": 0,
"selected": false,
"text": "<p>Add UpdateLayout cannot solve the issue. \nAccording to <a href=\"http://support.microsoft.com/kb/942443\" rel=\"nofollow\">http://support.microsoft.com/kb/942443</a>, \"preload the PresentationCore.dll file or the PresentationFramework.dll file in the primary application domain\" is needed.</p>\n"
},
{
"answer_id": 7102886,
"author": "edrowland",
"author_id": 514588,
"author_profile": "https://Stackoverflow.com/users/514588",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting. The problem is still present in .net framework 4.0. My code was leaking ferociously. </p>\n\n<p>The proposed fix -- where UpdateLayout is called in a loop immediately after creation of the FixedDocumentSequence did NOT fix the problem for me on a 400 page test document. </p>\n\n<p>However, the following solution DID fix the problem for me. As in previous fixes, I moved the call to GetFixedDocumentSequence() outside the for-each-page loop. The \"using\" clause... fair warning that I'm still not sure it's correct. But it's not hurting. The document is subsequently re-used to generate page previews on-screen. So it doesn't seem to hurt.</p>\n\n<pre><code>DocumentPaginator paginator \n = document.GetFixedDocumentSequence().DocumentPaginator;\nint numberOfPages = paginator.ComputePageCount();\n\n\nfor (int i = 0; i < NumberOfPages; ++i)\n{\n DocumentPage docPage = paginator.GetPage(nPage);\n using (docPage) // using is *probably* correct.\n {\n // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n ((FixedPage)(docPage.Visual)).UpdateLayout();\n\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n // Adding THAT line cured my leak.\n\n RenderTargetBitmap bitmap = GetXpsPageAsBitmap(docPage, dpi);\n\n .... etc...\n }\n\n}\n</code></pre>\n\n<p>In reality, the fix line goes inside my GetXpsPageAsBitmap routine (ommited for clarity), which is pretty much identical to previously posted code.</p>\n\n<p>Thanks to all who contributed.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26221/"
] |
The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.
'\*\*\*\*\*\* Console application BEGINS.
```
Module Main
Const DefaultTestFilePath As String = "D:\Test.xps"
Const DefaultLoopRuns As Integer = 1000
Public Sub Main(ByVal Args As String())
Dim PathToTestXps As String = DefaultTestFilePath
Dim NumberOfLoops As Integer = DefaultLoopRuns
If (Args.Count >= 1) Then PathToTestXps = Args(0)
If (Args.Count >= 2) Then NumberOfLoops = CInt(Args(1))
Console.Clear()
Console.WriteLine("Start - {0}", GC.GetTotalMemory(True))
For LoopCount As Integer = 1 To NumberOfLoops
Console.CursorLeft = 0
Console.Write("Loop {0:d5}", LoopCount)
' The more complex the XPS document and the more loops, the more memory is lost.
Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence
' This line leaks a chunk of memory each time, when commented out it does not.
FixedDocSequence = XPSItem.GetFixedDocumentSequence
End Using
Next
Console.WriteLine()
GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals).
Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True))
Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).")
Console.ReadKey()
End Sub
End Module
```
'\*\*\*\*\*\* Console application ENDS.
The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).
The code was originally in another thread and class but has been simplified to this.
Any help greatly appreciated.
Ryan
|
Well, I found it. It IS a bug in the framework and to work around it you add a call to UpdateLayout. Using statement can be changed to the following to provide a fix;
```
Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)
Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence
Dim DocPager As Windows.Documents.DocumentPaginator
FixedDocSequence = XPSItem.GetFixedDocumentSequence
DocPager = FixedDocSequence.DocumentPaginator
DocPager.ComputePageCount()
' This is the fix, each page must be laid out otherwise resources are never released.'
For PageIndex As Integer = 0 To DocPager.PageCount - 1
DirectCast(DocPager.GetPage(PageIndex).Visual, Windows.Documents.FixedPage).UpdateLayout()
Next
FixedDocSequence = Nothing
End Using
```
|
218,691 |
<p>Is there a way to temporary swap Flex's main application to another then switch back.
Scenario : Main app started, display login box - then go on with main app. Login box is an application as well. </p>
<p>Application.application is a read only property, that attempt failed.</p>
|
[
{
"answer_id": 219404,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a reason why you cannot make the login box a component and then perhaps use a ViewStack to control the viewable components?</p>\n"
},
{
"answer_id": 219600,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 0,
"selected": false,
"text": "<p>That's funny, this is exactly what I am attempting to figure out the best way to do at the moment. I had thought of using a ViewStack, but as I already have a lot of other nested ViewStacks being used, I was also looking into the State tag. If anyone knows \"the right thing\" to do I'll be very interested too!</p>\n"
},
{
"answer_id": 220714,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 0,
"selected": false,
"text": "<p>I've implemented this as a ViewStack on the Application component; seems to work fine. Use the selectedIndex or selectedChild property on the ViewStack to control whether the login or the app UI is displayed.</p>\n\n<pre><code><mx:Application>\n <mx:ViewStack>\n <mx:Box> <!-- or whatever for login-->\n </mx:Box>\n <mx:Box> <!-- application UI widgets here -->\n </mx:Box>\n </mx:ViewStack>\n</mx:Application>\n</code></pre>\n"
},
{
"answer_id": 221956,
"author": "ianmjones",
"author_id": 3023,
"author_profile": "https://Stackoverflow.com/users/3023",
"pm_score": 2,
"selected": false,
"text": "<p>I've had great success with a modular application whereby the main application basically consists of a module loader, that initially loads a logon module.</p>\n\n<p>Once the logon module has done it's stuff (in my case validated inputs, called the logon service and retrieved a token), it dispatches an event (imaginatively called \"LogonEvent\") that contains details required by the main application. I should point out that the logon module itself is just a wrapper for a logon component that does all the real work (so the logon component can be used in a module or ViewStack etc). Having a LogonEvent makes all the difference.</p>\n\n<p>The wrapper application processes the logon event by unloading the logon module, loading the main module that contains the guts of the application, and then sets the required logon details on the loaded module.</p>\n\n<p>The log off button is in the wrapper application so that it can unload the main module and reload the logon module ready for logging in again.</p>\n\n<p>The benefit of this kind of layout is that the relatively small logon module loads pretty quickly. And while the user is logging on, the main module is already getting pre-loaded, so there is generally no wait for the main module to load after log on. If you have one large monolithic application the initial load time could be off putting.</p>\n\n<p>Some bits of code that may help...</p>\n\n<pre><code>private var mainModuleLogOnEventDispatcher:*;\n\n[Bindable]\nprivate var _logOnDetails:LogOnDetails = new LogOnDetails();\n\nprivate function onCreationComplete(event:Event):void\n{\n // Load log on module.\n loadMainModule(\"LogOnModule.swf\");\n\n // Pre-load main module while user is logging on.\n var mm:IModuleInfo = ModuleManager.getModule(\"MainModule.swf\");\n mm.load();\n}\n\n[Bindable]\nprivate function set logOnDetails(value:LogOnDetails):void\n{\n _logOnDetails = value;\n}\n\nprivate function get logOnDetails():LogOnDetails\n{\n return _logOnDetails;\n} \n\nprivate function loadMainModule(moduleName:String):void\n{\n // Unload anything already loaded.\n if (mainModule.url.length > 0)\n {\n mainModule.unloadModule();\n mainModule.url = \"\";\n }\n mainModule.addEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);\n mainModule.url = moduleName;\n}\n\nprivate function handleMainModuleReadyEvent(event:ModuleEvent):void\n{\n // Remove listener, we've caught the event now.\n mainModule.removeEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);\n\n // Add listeners to other events or apply data.\n if (mainModule.url == \"LogOnModule.swf\")\n {\n mainModuleLogOnEventDispatcher = mainModule.child;\n if (mainModule.child != null) {\n mainModuleLogOnEventDispatcher.addEventListener(\"logOnEvent\", handleLogOnEvent);\n }\n }\n if (mainModule.url == \"MainModule.swf\")\n {\n var mm:* = mainModule.child;\n if (mainModule.child != null)\n {\n mm.logOnDetails = logOnDetails;\n }\n } \n}\n\nprivate function handleLogOnEvent(logOnEvent:LogOnEvent):void\n{\n mainModuleLogOnEventDispatcher.removeEventListener(\"logOnEvent\", handleLogOnEvent);\n\n logOnDetails = logOnEvent.logOnDetails;\n\n // Now get person's details and swap in main module if successful.\n var parameters:Object = new Object();\n parameters.cmd = \"viewPerson\";\n parameters.token = logOnDetails.logOnToken;\n viewPersonRequest.send(parameters);\n}\n\nprivate function handleViewPersonRequestResult(event:ResultEvent):void\n{\n\n //*** Loads of setting logonDetails and error handling removed!!! ***//\n loadMainModule(\"MainModule.swf\");\n currentState = \"LoggedOn\";\n return;\n}\n\nprivate function onLogOff(event:MouseEvent):void\n{\n // Make sure we don't auto-logon when we log off.\n var logOnPrefs:SharedObject = SharedObject.getLocal(\"LogOn\", \"/\");\n logOnPrefs.data.loggedOff = true;\n\n var parameters:Object = new Object();\n parameters.cmd = \"logoff\";\n parameters.token = logOnDetails.logOnToken;\n logoffRequest.send(parameters);\n loadMainModule(\"LogOnModule.swf\");\n currentState = \"\";\n}\n\n<!-- *** Loads of view state related mxml removed *** -->\n<mx:VBox width=\"100%\" height=\"100%\" horizontalAlign=\"center\" verticalAlign=\"middle\" id=\"mainModuleVBox\">\n <basic:IJModuleLoader id=\"mainModule\" url=\"\" width=\"100%\" height=\"100%\" horizontalAlign=\"center\" verticalAlign=\"middle\"/>\n</mx:VBox>\n</code></pre>\n\n<p>I should also note that this wrapper application isn't actually an application! This is actually a module itself, which is loaded by either a Flex or AIR application. This way I can have separate Flex and AIR projects that reference a core library project that holds the application module, logon module, main (post logon) module and basically all other components and classes used by the application.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there a way to temporary swap Flex's main application to another then switch back.
Scenario : Main app started, display login box - then go on with main app. Login box is an application as well.
Application.application is a read only property, that attempt failed.
|
I've had great success with a modular application whereby the main application basically consists of a module loader, that initially loads a logon module.
Once the logon module has done it's stuff (in my case validated inputs, called the logon service and retrieved a token), it dispatches an event (imaginatively called "LogonEvent") that contains details required by the main application. I should point out that the logon module itself is just a wrapper for a logon component that does all the real work (so the logon component can be used in a module or ViewStack etc). Having a LogonEvent makes all the difference.
The wrapper application processes the logon event by unloading the logon module, loading the main module that contains the guts of the application, and then sets the required logon details on the loaded module.
The log off button is in the wrapper application so that it can unload the main module and reload the logon module ready for logging in again.
The benefit of this kind of layout is that the relatively small logon module loads pretty quickly. And while the user is logging on, the main module is already getting pre-loaded, so there is generally no wait for the main module to load after log on. If you have one large monolithic application the initial load time could be off putting.
Some bits of code that may help...
```
private var mainModuleLogOnEventDispatcher:*;
[Bindable]
private var _logOnDetails:LogOnDetails = new LogOnDetails();
private function onCreationComplete(event:Event):void
{
// Load log on module.
loadMainModule("LogOnModule.swf");
// Pre-load main module while user is logging on.
var mm:IModuleInfo = ModuleManager.getModule("MainModule.swf");
mm.load();
}
[Bindable]
private function set logOnDetails(value:LogOnDetails):void
{
_logOnDetails = value;
}
private function get logOnDetails():LogOnDetails
{
return _logOnDetails;
}
private function loadMainModule(moduleName:String):void
{
// Unload anything already loaded.
if (mainModule.url.length > 0)
{
mainModule.unloadModule();
mainModule.url = "";
}
mainModule.addEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);
mainModule.url = moduleName;
}
private function handleMainModuleReadyEvent(event:ModuleEvent):void
{
// Remove listener, we've caught the event now.
mainModule.removeEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);
// Add listeners to other events or apply data.
if (mainModule.url == "LogOnModule.swf")
{
mainModuleLogOnEventDispatcher = mainModule.child;
if (mainModule.child != null) {
mainModuleLogOnEventDispatcher.addEventListener("logOnEvent", handleLogOnEvent);
}
}
if (mainModule.url == "MainModule.swf")
{
var mm:* = mainModule.child;
if (mainModule.child != null)
{
mm.logOnDetails = logOnDetails;
}
}
}
private function handleLogOnEvent(logOnEvent:LogOnEvent):void
{
mainModuleLogOnEventDispatcher.removeEventListener("logOnEvent", handleLogOnEvent);
logOnDetails = logOnEvent.logOnDetails;
// Now get person's details and swap in main module if successful.
var parameters:Object = new Object();
parameters.cmd = "viewPerson";
parameters.token = logOnDetails.logOnToken;
viewPersonRequest.send(parameters);
}
private function handleViewPersonRequestResult(event:ResultEvent):void
{
//*** Loads of setting logonDetails and error handling removed!!! ***//
loadMainModule("MainModule.swf");
currentState = "LoggedOn";
return;
}
private function onLogOff(event:MouseEvent):void
{
// Make sure we don't auto-logon when we log off.
var logOnPrefs:SharedObject = SharedObject.getLocal("LogOn", "/");
logOnPrefs.data.loggedOff = true;
var parameters:Object = new Object();
parameters.cmd = "logoff";
parameters.token = logOnDetails.logOnToken;
logoffRequest.send(parameters);
loadMainModule("LogOnModule.swf");
currentState = "";
}
<!-- *** Loads of view state related mxml removed *** -->
<mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle" id="mainModuleVBox">
<basic:IJModuleLoader id="mainModule" url="" width="100%" height="100%" horizontalAlign="center" verticalAlign="middle"/>
</mx:VBox>
```
I should also note that this wrapper application isn't actually an application! This is actually a module itself, which is loaded by either a Flex or AIR application. This way I can have separate Flex and AIR projects that reference a core library project that holds the application module, logon module, main (post logon) module and basically all other components and classes used by the application.
|
218,696 |
<p>Is there a generic way to clone objects in VBA? So that i could copy x to y instead of copying just the pointer?</p>
<pre><code> Dim x As New Class1
Dim y As Class1
x.Color = 1
x.Height = 1
Set y = x
y.Color = 2
Debug.Print "x.Color=" & x.Color & ", x.Height=" & x.Height
</code></pre>
<p>By generic i mean something like <code>Set y = CloneObject(x)</code> rather than having to create my own method for the class copying its properties one by one.</p>
|
[
{
"answer_id": 219123,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there's anything built in, although it would be nice.</p>\n\n<p>I think there should at least be a way to create a Clone method automatically using the VBA Editor. I'll see if I can take a look at it once I've got the kids to bed...</p>\n"
},
{
"answer_id": 220060,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 4,
"selected": true,
"text": "<p>OK, here's the beginning of something that illustrates it:</p>\n\n<p>Create a class, call it, oh, \"Class1\":</p>\n\n<pre><code>Option Explicit\n\nPublic prop1 As Long\nPrivate DontCloneThis As Variant\n\nPublic Property Get PrivateThing()\n PrivateThing = DontCloneThis\nEnd Property\n\nPublic Property Let PrivateThing(value)\n DontCloneThis = value\nEnd Property\n</code></pre>\n\n<p>Now we need to give it a Clone function. In another module, try this:</p>\n\n<p>Option Explicit</p>\n\n<pre><code>Public Sub makeCloneable()\n\nDim idx As Long\nDim line As String\nDim words As Variant\nDim cloneproc As String\n\n' start building the text of our new function\n cloneproc = \"Public Function Clone() As Class1\" & vbCrLf\n cloneproc = cloneproc & \"Set Clone = New Class1\" & vbCrLf\n\n ' get the code for the class and start examining it \n With ThisWorkbook.VBProject.VBComponents(\"Class1\").CodeModule\n\n For idx = 1 To .CountOfLines\n\n line = Trim(.lines(idx, 1)) ' get the next line\n If Len(line) > 0 Then\n line = Replace(line, \"(\", \" \") ' to make words clearly delimited by spaces\n words = Split(line, \" \") ' so we get split on a space\n If words(0) = \"Public\" Then ' can't set things declared Private\n ' several combinations of words possible\n If words(1) = \"Property\" And words(2) = \"Get\" Then\n cloneproc = cloneproc & \"Clone.\" & words(3) & \"=\" & words(3) & vbCrLf\n ElseIf words(1) = \"Property\" And words(2) = \"Set\" Then\n cloneproc = cloneproc & \"Set Clone.\" & words(3) & \"=\" & words(3) & vbCrLf\n ElseIf words(1) <> \"Sub\" And words(1) <> \"Function\" And words(1) <> \"Property\" Then\n cloneproc = cloneproc & \"Clone.\" & words(1) & \"=\" & words(1) & vbCrLf\n End If\n End If\n End If\n Next\n\n cloneproc = cloneproc & \"End Function\"\n\n ' put the code into the class\n .AddFromString cloneproc\n\n End With\n\nEnd Sub\n</code></pre>\n\n<p>Run that, and the following gets added into Class1</p>\n\n<pre><code>Public Function Clone() As Class1\nSet Clone = New Class1\nClone.prop1 = prop1\nClone.PrivateThing = PrivateThing\nEnd Function\n</code></pre>\n\n<p>...which looks like a start. Lots of things I'd clean up (and probably will - this turned out to be fun). A nice Regular Expression to find gettable/lettable/settable attributes, refactoring into several small functions, code to remove old \"Clone\" functions (and put the new one at the end), something a bit more Stringbuilder-ish to DRY (Don't Repeat Yourself) up the concatenations, stuff like that.</p>\n"
},
{
"answer_id": 4816437,
"author": "MarkJ",
"author_id": 15639,
"author_profile": "https://Stackoverflow.com/users/15639",
"pm_score": 3,
"selected": false,
"text": "<p>Scott Whitlock has posted a <a href=\"https://stackoverflow.com/questions/4805475/assignment-of-objects-in-vb6/4805812#4805812\">fantastic answer</a> to this problem on another question. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134/"
] |
Is there a generic way to clone objects in VBA? So that i could copy x to y instead of copying just the pointer?
```
Dim x As New Class1
Dim y As Class1
x.Color = 1
x.Height = 1
Set y = x
y.Color = 2
Debug.Print "x.Color=" & x.Color & ", x.Height=" & x.Height
```
By generic i mean something like `Set y = CloneObject(x)` rather than having to create my own method for the class copying its properties one by one.
|
OK, here's the beginning of something that illustrates it:
Create a class, call it, oh, "Class1":
```
Option Explicit
Public prop1 As Long
Private DontCloneThis As Variant
Public Property Get PrivateThing()
PrivateThing = DontCloneThis
End Property
Public Property Let PrivateThing(value)
DontCloneThis = value
End Property
```
Now we need to give it a Clone function. In another module, try this:
Option Explicit
```
Public Sub makeCloneable()
Dim idx As Long
Dim line As String
Dim words As Variant
Dim cloneproc As String
' start building the text of our new function
cloneproc = "Public Function Clone() As Class1" & vbCrLf
cloneproc = cloneproc & "Set Clone = New Class1" & vbCrLf
' get the code for the class and start examining it
With ThisWorkbook.VBProject.VBComponents("Class1").CodeModule
For idx = 1 To .CountOfLines
line = Trim(.lines(idx, 1)) ' get the next line
If Len(line) > 0 Then
line = Replace(line, "(", " ") ' to make words clearly delimited by spaces
words = Split(line, " ") ' so we get split on a space
If words(0) = "Public" Then ' can't set things declared Private
' several combinations of words possible
If words(1) = "Property" And words(2) = "Get" Then
cloneproc = cloneproc & "Clone." & words(3) & "=" & words(3) & vbCrLf
ElseIf words(1) = "Property" And words(2) = "Set" Then
cloneproc = cloneproc & "Set Clone." & words(3) & "=" & words(3) & vbCrLf
ElseIf words(1) <> "Sub" And words(1) <> "Function" And words(1) <> "Property" Then
cloneproc = cloneproc & "Clone." & words(1) & "=" & words(1) & vbCrLf
End If
End If
End If
Next
cloneproc = cloneproc & "End Function"
' put the code into the class
.AddFromString cloneproc
End With
End Sub
```
Run that, and the following gets added into Class1
```
Public Function Clone() As Class1
Set Clone = New Class1
Clone.prop1 = prop1
Clone.PrivateThing = PrivateThing
End Function
```
...which looks like a start. Lots of things I'd clean up (and probably will - this turned out to be fun). A nice Regular Expression to find gettable/lettable/settable attributes, refactoring into several small functions, code to remove old "Clone" functions (and put the new one at the end), something a bit more Stringbuilder-ish to DRY (Don't Repeat Yourself) up the concatenations, stuff like that.
|
218,733 |
<p>I have a <code>GridView</code> control in an Asp.net application, that has a <code><asp:buttonField></code> of <code>type="image"</code> and <code>CommandName="Delete"</code>.</p>
<p>Is there any way to execute a piece of javascript before reaching the <code>OnRowDelete</code> event?</p>
<p>I want just a simple confirm before deleting the row.</p>
<p>Thanks!</p>
<p><strong>EDIT</strong>: Please Note that <code><asp:ButtonField></code> tag <strong>does not have</strong> an <code>OnClientClick</code> attribute.</p>
|
[
{
"answer_id": 218785,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 6,
"selected": true,
"text": "<p>I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.</p>\n\n<p>On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.</p>\n\n<pre><code><script type=\"text/javascript\">\n function confirmDelete()\n {\n return confirm(\"Are you sure you want to delete this?\");\n }\n</script>\n\n...\n\n<asp:TemplateField>\n <ItemTemplate>\n <asp:ImageButton ID=\"DeleteButton\" runat=\"server\"\n ImageUrl=\"...\" AlternateText=\"Delete\" ToolTip=\"Delete\"\n CommandName=\"Delete\" CommandArgument='<%# Eval(\"ID\") %>'\n OnClientClick=\"return confirmDelete();\" />\n </ItemTemplate>\n</asp:TemplateField>\n</code></pre>\n"
},
{
"answer_id": 219052,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 0,
"selected": false,
"text": "<p>So I have a javascript function:</p>\n\n<pre><code>function confirmDeleteContact() {\n if (confirm(\"Are you sure you want to delete this contact?\")) {\n document.all.answer.value=\"yes\";\n } else {\n document.all.answer.value=\"no\";\n }\n}\n</code></pre>\n\n<p>and I wire it to a grid item like so:</p>\n\n<pre><code>Sub dgbind(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles dgcontacts.ItemDataBound\n Select Case e.Item.ItemType\n Case ListItemType.Item, ListItemType.AlternatingItem\n CType(e.Item.Cells(9).Controls(0), System.Web.UI.WebControls.LinkButton).Attributes.Add(\"onclick\", \"javascript:confirmDeleteContact();\")\n End Select\nEnd Sub\n</code></pre>\n\n<p>This is some old code, so I see a few things I could change up, but the moral is this: If all else fails, add the javascript \"onClick\" during row binding. \"document.all.answer.value\" is a hidden field that has <code>runat=server</code> so that I can read the value upon postback.</p>\n"
},
{
"answer_id": 219104,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "<p>In the <code>GridView</code>'s <code>RowCreated</code> event handler, use <code>FindControl</code> to find the named button, and add to the Attributes collection:</p>\n\n<pre><code>btn.Attributes.Add(\"onclick\", \"return confirm('delete this record?');\");\n</code></pre>\n\n<p>Your ASP.Net code will only be executed if confirm() is true, i.e. has been ok'd.</p>\n"
},
{
"answer_id": 2358775,
"author": "Tod Birdsall",
"author_id": 29613,
"author_profile": "https://Stackoverflow.com/users/29613",
"pm_score": 4,
"selected": false,
"text": "<p>I found that the most elegant way to do this is to use jQuery to wire the onClick event:</p>\n\n<pre><code><script type=\"text/javascript\"> \n $(\".deleteLink\").click(function() {\n return confirm('Are you sure you wish to delete this record?');\n });\n</script>\n\n...\n\n<asp:ButtonField ButtonType=\"Link\" Text=\"Delete\"\n CommandName=\"Delete\" ItemStyle-CssClass=\"deleteLink\" />\n</code></pre>\n\n<p>Notice that I use an arbitrary CSS class to identify the link button.</p>\n"
},
{
"answer_id": 14798490,
"author": "user1308314",
"author_id": 1308314,
"author_profile": "https://Stackoverflow.com/users/1308314",
"pm_score": -1,
"selected": false,
"text": "<p>better for you the add reference System.Windows.Forms if you use buttonfield... It is always available in all .net framework and supports asp.net..</p>\n\n<p>this is your choice if the buttonfield is your best choice..\nsample:</p>\n\n<pre><code>using System.Windows.Forms;\n\nprotected void BorrowItem_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n\n if (e.CommandName == \"Delete\")\n {\n\n if (System.Windows.Forms.MessageBox.Show(\"Do you want to delete\", \"Delete\",MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) != System.Windows.Forms.DialogResult.OK)\n {\n return;\n }\n }\n//Continue execution...\n}\n\n//drimaster\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7595/"
] |
I have a `GridView` control in an Asp.net application, that has a `<asp:buttonField>` of `type="image"` and `CommandName="Delete"`.
Is there any way to execute a piece of javascript before reaching the `OnRowDelete` event?
I want just a simple confirm before deleting the row.
Thanks!
**EDIT**: Please Note that `<asp:ButtonField>` tag **does not have** an `OnClientClick` attribute.
|
I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.
On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.
```
<script type="text/javascript">
function confirmDelete()
{
return confirm("Are you sure you want to delete this?");
}
</script>
...
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server"
ImageUrl="..." AlternateText="Delete" ToolTip="Delete"
CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
OnClientClick="return confirmDelete();" />
</ItemTemplate>
</asp:TemplateField>
```
|
218,760 |
<p>Although elements like <code><div></code>s normally grow to fit their contents, using the <code>float</code> property can cause a startling problem for CSS newbies: <strong>If floated elements have non-floated parent elements, the parent will collapse.</strong></p>
<p>For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div></code></pre>
</div>
</div>
</p>
<p>The parent div in this example will <strong>not expand</strong> to contain its floated children - it will appear to have <code>height: 0</code>.</p>
<h1>How do you solve this problem?</h1>
<p><em>I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.</em></p>
<h2>Solution 1</h2>
<p>Float the parent.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="float: left;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Pros</strong>: Semantic code.<br />
<strong>Cons</strong>: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?</p>
<h2>Solution 2</h2>
<p>Give the parent an explicit height.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="height: 300px;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Pros</strong>: Semantic code.<br />
<strong>Cons</strong>: Not flexible - if the content changes or the browser is resized, the layout will break.</p>
<h2>Solution 3</h2>
<p>Append a "spacer" element inside the parent element, like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
<div class="spacer" style="clear: both;"></div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Pros</strong>: Straightforward to code.<br />
<strong>Cons</strong>: Not semantic; the spacer div exists only as a layout hack.</p>
<h2>Solution 4</h2>
<p>Set parent to <code>overflow: auto</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="overflow: auto;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Pros</strong>: Doesn't require extra div.<br />
<strong>Cons</strong>: Seems like a hack - that's not the <code>overflow</code> property's stated purpose.</p>
<h1>Comments? Other suggestions?</h1>
|
[
{
"answer_id": 218799,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 6,
"selected": false,
"text": "<p>I usually use the <code>overflow: auto</code> trick; although that's not, strictly speaking, the intended use for overflow, it <em>is</em> kinda related - enough to make it easy to remember, certainly. The meaning of <code>float: left</code> itself has been extended for various uses more significantly than overflow is in this example, IMO.</p>\n"
},
{
"answer_id": 218809,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>I use 2 and 4 where applicable (i.e. when I know the content's height or if overflowing doesn't harm). Anywhere else, I go with solution 3. By the way, your first solution has no advantage over 3 (that I can spot) because it isn't any more semantic since it uses the same dummy element.</p>\n\n<p>By the way, I wouldn't be concerned about the fourth solution being a hack. Hacks in CSS would only be harmful if their underlying behaviour is subject to reinterpretation or other change. This way, your hack wouldn't be guaranteed to work. However in this case, your hack relies on the exact behaviour that <code>overflow: auto</code> is meant to have. No harm in hitching a free ride.</p>\n"
},
{
"answer_id": 219487,
"author": "Bryan A",
"author_id": 29707,
"author_profile": "https://Stackoverflow.com/users/29707",
"pm_score": 3,
"selected": false,
"text": "<p>Although the code isn't perfectly semantic, I think it's more straightforward to have what I call a \"clearing div\" at the bottom of every container with floats in it. In fact, I've included the following style rule in my reset block for every project:</p>\n\n<pre><code>.clear \n{\n clear: both;\n}\n</code></pre>\n\n<p>If you're styling for IE6 (god help you), you might want to give this rule a 0px line-height and height as well.</p>\n"
},
{
"answer_id": 617189,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 3,
"selected": false,
"text": "<p>The ideal solution would be to use <code>inline-block</code> for the columns instead of floating. I think the browser support is pretty good if you follow (a) apply <code>inline-block</code> only to elements that are normally inline (eg <code>span</code>); and (b) add <code>-moz-inline-box</code> for Firefox.</p>\n\n<p>Check your page in FF2 as well because I had a ton of problems when nesting certain elements (surprisingly, this is the one case where IE performs much better than FF).</p>\n"
},
{
"answer_id": 2373465,
"author": "tybro0103",
"author_id": 202875,
"author_profile": "https://Stackoverflow.com/users/202875",
"pm_score": 4,
"selected": false,
"text": "<p>Rather than putting <code>overflow:auto</code> on the parent, put <code>overflow:hidden</code></p>\n\n<p>The first CSS I write for any webpage is always:</p>\n\n<pre><code>div {\n overflow:hidden;\n}\n</code></pre>\n\n<p>Then I never have to worry about it.</p>\n"
},
{
"answer_id": 2373514,
"author": "Sarfraz",
"author_id": 139459,
"author_profile": "https://Stackoverflow.com/users/139459",
"pm_score": 4,
"selected": false,
"text": "<p>The problem happens when a floated element is within a container box, that element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow. You can use 2 methods to fix it:</p>\n\n<ul>\n<li><code>{ clear: both; }</code></li>\n<li><code>clearfix</code></li>\n</ul>\n\n<p>Once you understand what is happening, use the method below to “clearfix” it.</p>\n\n<pre><code>.clearfix:after {\n content: \".\";\n display: block;\n clear: both;\n visibility: hidden;\n line-height: 0;\n height: 0;\n}\n\n.clearfix {\n display: inline-block;\n}\n\nhtml[xmlns] .clearfix {\n display: block;\n}\n\n* html .clearfix {\n height: 1%;\n}\n</code></pre>\n\n<p><strong><a href=\"http://www.webtoolkit.info/demo/css-clearfix\" rel=\"noreferrer\">Demonstration :)</a></strong></p>\n"
},
{
"answer_id": 11594657,
"author": "João Paulo Macedo",
"author_id": 1171873,
"author_profile": "https://Stackoverflow.com/users/1171873",
"pm_score": 2,
"selected": false,
"text": "<p>One of the most well known solutions is a variation of your solution number 3 that uses a pseudo element instead of a non-semantic html element.</p>\n\n<p>It goes something like this...</p>\n\n<pre><code>.cf:after {\n content: \" \";\n display: block;\n visibility: hidden;\n height: 0;\n clear: both;\n}\n</code></pre>\n\n<p>You place that in your stylesheet, and all you need is to add the class 'cf' to the element containing the floats. </p>\n\n<p>What I use is another variation which comes from Nicolas Gallagher.</p>\n\n<p>It does the same thing, but it's shorter, looks neater, and maybe used to accomplish another thing that's pretty useful - preventing the child elements' margins from collapsing with it's parents' (but for that you do need something else - read more about it here <a href=\"http://nicolasgallagher.com/micro-clearfix-hack/\" rel=\"nofollow\">http://nicolasgallagher.com/micro-clearfix-hack/</a> ).</p>\n\n<pre><code>.cf:after {\n content: \" \";\n display: table;\n clear: float;\n}\n</code></pre>\n"
},
{
"answer_id": 11597829,
"author": "A.M.K",
"author_id": 900747,
"author_profile": "https://Stackoverflow.com/users/900747",
"pm_score": 9,
"selected": false,
"text": "<h2>Solution 1:</h2>\n\n<p>The most reliable and unobtrusive method appears to be this:</p>\n\n<p>Demo: <a href=\"http://jsfiddle.net/SO_AMK/wXaEH/\" rel=\"noreferrer\">http://jsfiddle.net/SO_AMK/wXaEH/</a></p>\n\n<p><strong>HTML</strong>: </p>\n\n<pre><code><div class=\"clearfix\">\n <div style=\"float: left;\">Div 1</div>\n <div style=\"float: left;\">Div 2</div>\n</div>\n</code></pre>\n\n<p><strong>CSS</strong>: </p>\n\n<pre><code>.clearfix::after { \n content: \" \";\n display: block; \n height: 0; \n clear: both;\n}\n</code></pre>\n\n<p>With a little CSS targeting, you don't even need to add a class to the parent <code>DIV</code>.</p>\n\n<p>This solution is backward compatible with IE8 so you don't need to worry about older browsers failing.</p>\n\n<h2>Solution 2:</h2>\n\n<p>An adaptation of solution 1 has been suggested and is as follows:</p>\n\n<p>Demo: <a href=\"http://jsfiddle.net/wXaEH/162/\" rel=\"noreferrer\">http://jsfiddle.net/wXaEH/162/</a></p>\n\n<p><strong>HTML</strong>: </p>\n\n<pre><code><div class=\"clearfix\">\n <div style=\"float: left;\">Div 1</div>\n <div style=\"float: left;\">Div 2</div>\n</div>\n</code></pre>\n\n<p><strong>CSS</strong>: </p>\n\n<pre><code>.clearfix::after { \n content: \" \";\n display: block; \n height: 0; \n clear: both;\n *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class=\"ie7-clear\"></div>' );\n}\n\n.ie7-clear {\n display: block;\n clear: both;\n}\n</code></pre>\n\n<p>This solution appears to be backward compatible to IE5.5 but is untested.</p>\n\n<h2>Solution 3:</h2>\n\n<p>It's also possible to set <code>display: inline-block;</code> and <code>width: 100%;</code> to emulate a normal block element while not collapsing.</p>\n\n<p>Demo: <a href=\"http://jsfiddle.net/SO_AMK/ae5ey/\" rel=\"noreferrer\">http://jsfiddle.net/SO_AMK/ae5ey/</a></p>\n\n<p><strong>CSS</strong>: </p>\n\n<pre><code>.clearfix {\n display: inline-block;\n width: 100%;\n}\n</code></pre>\n\n<p>This solution should be backward compatible with IE5.5 but has only been tested in IE6.</p>\n"
},
{
"answer_id": 12554475,
"author": "cssisashtandw3tooo",
"author_id": 1692685,
"author_profile": "https://Stackoverflow.com/users/1692685",
"pm_score": 2,
"selected": false,
"text": "<p>The main problem you may find with changing overflow to <code>auto</code> or <code>hidden</code> is that everything can become scrollable with the middle mouse buttom and a user can mess up the entire site layout.</p>\n"
},
{
"answer_id": 12935628,
"author": "lededje",
"author_id": 1753018,
"author_profile": "https://Stackoverflow.com/users/1753018",
"pm_score": 3,
"selected": false,
"text": "<p>Strange no one has come up with a complete answer for this yet, ah well here it is.</p>\n<h2>Solution one: <em>clear: both</em></h2>\n<p>Adding a block element with the style clear:both; onto it will clear the floats past that point and stop the parent of that element from collapsing. <a href=\"http://jsfiddle.net/TVD2X/1/\" rel=\"noreferrer\">http://jsfiddle.net/TVD2X/1/</a></p>\n<p>Pros: Allows you to clear an element and elements you add below will not be effected by the floated elements above and valid css.</p>\n<p>Cons: Requires the another tag to clear the floats, bloating markup.</p>\n<p>Note: To fall back to IE6 and for it to work on abstinent parents (i.e. the input element) you are not able to use :after.</p>\n<h2>Solution two: <em>display: table</em></h2>\n<p>Adding display:table; to the parent to make it shrug off the floats and display with the correct height. <a href=\"http://jsfiddle.net/h9GAZ/1/\" rel=\"noreferrer\">http://jsfiddle.net/h9GAZ/1/</a></p>\n<p>Pros: No extra markup and is a lot neater. Works in IE6+</p>\n<p>Cons: Requires invalid css to make sure everything plays nice in IE6 and 7.</p>\n<p>Note: The IE6 and 7 width auto is used to prevent the width being 100%+padding, which is not the case in newer browsers.</p>\n<h2>A note on the other "solutions"</h2>\n<p>These fixes work back to the lowest supported browser, over 1% usage globally (IE6), which means using :after does not cut it.</p>\n<p>Overflow hidden does show the content but does not prevent the element from collapsing and so does not answer the question. Using an inline block can have buggy results, children having strange margins and so on, table is much better.</p>\n<p>Setting the height does "prevent" the collapse but it is not a proper fix.</p>\n<h2>Invalid css</h2>\n<p>Invalid css never hurt anyone, in fact, it is now the norm. Using browser prefixes is just as invalid as using browser specific hacks and doesn't impact the end user what so ever.</p>\n<h2>In conclusion</h2>\n<p>I use both of the above solutions to make elements react correctly and play nicely with each other, I implore you to do the same.</p>\n"
},
{
"answer_id": 15706960,
"author": "Jonathan",
"author_id": 2225010,
"author_profile": "https://Stackoverflow.com/users/2225010",
"pm_score": 2,
"selected": false,
"text": "<p>Another possible solution which I think is more semantically correct is to change the floated inner elements to be 'display: inline'. This example and what I was working on when I came across this page both use floated divs in much exactly the same way that a span would be used. Instead of using divs, switch to span, or if you are using another element which is by default 'display: block' instead of 'display: inline' then change it to be 'display: inline'. I believe this is the 100% semantically correct solution.</p>\n\n<p>Solution 1, floating the parent, is essentially to change the entire document to be floated.</p>\n\n<p>Solution 2, setting an explicit height, is like drawing a box and saying I want to put a picture here, i.e. use this if you are doing an img tag.</p>\n\n<p>Solution 3, adding a spacer to clear float, is like adding an extra line below your content and will mess with surrounding elements too. If you use this approach you probably want to set the div to be height: 0px.</p>\n\n<p>Solution 4, overflow: auto, is acknowledging that you don't know how to lay out the document and you are admitting that you don't know what to do. </p>\n"
},
{
"answer_id": 18061246,
"author": "jave.web",
"author_id": 1835470,
"author_profile": "https://Stackoverflow.com/users/1835470",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that best way is to set <code>clear:both</code> to the upcoming element.</p>\n\n<p>Here's why:</p>\n\n<p>1) <code>:after</code> selector is not supported in IE6/7 and buggy in FF3, however,\n <br> if you care only about IE8+ and FF3.5+ clearing with :after is probably best for you...</p>\n\n<p>2) <code>overflow</code> is supposed to do something else so this hack isn't reliable enough. </p>\n\n<p>Note to author: there is nothing hacky on clearing... Clearing means to skip the floating fields. CLEAR is with us since HTML3 (who knows, maybe even longer) <a href=\"http://www.w3.org/MarkUp/html3/deflists.html\" rel=\"nofollow\">http://www.w3.org/MarkUp/html3/deflists.html</a> , maybe they should chose a bit different name like page: new, but thats just a detail...</p>\n"
},
{
"answer_id": 19379043,
"author": "Christian Gray",
"author_id": 2881715,
"author_profile": "https://Stackoverflow.com/users/2881715",
"pm_score": 3,
"selected": false,
"text": "<p>My favourite method is using a clearfix class for parent element</p>\n\n<pre><code>.clearfix:after {\n content: \".\";\n display: block;\n height: 0;\n clear: both;\n visibility: hidden;\n}\n\n.clearfix {\n display: inline-block;\n}\n\n* html .clearfix {\n height: 1%;\n}\n\n.clearfix {\n display: block;\n}\n</code></pre>\n"
},
{
"answer_id": 24516684,
"author": "Leons Kalapurakal",
"author_id": 3789139,
"author_profile": "https://Stackoverflow.com/users/3789139",
"pm_score": 2,
"selected": false,
"text": "<p>add this in the parent div at the bottom</p>\n\n<pre><code> <div style=\"clear:both\"></div>\n</code></pre>\n"
},
{
"answer_id": 27205635,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 4,
"selected": false,
"text": "<p>There are several versions of the clearfix, with <strong><a href=\"https://github.com/necolas\">Nicolas Gallagher</a></strong> and <strong><a href=\"https://twitter.com/thierrykoblentz\">Thierry Koblentz</a></strong> as key authors.</p>\n\n<p>If you want support for older browsers, it's best to use this clearfix :</p>\n\n<pre><code>.clearfix:before, .clearfix:after {\n content: \"\";\n display: table;\n}\n\n.clearfix:after {\n clear: both;\n}\n\n.clearfix {\n *zoom: 1;\n}\n</code></pre>\n\n<p>In SCSS, you should use the following technique :</p>\n\n<pre><code>%clearfix {\n &:before, &:after {\n content:\" \";\n display:table;\n }\n\n &:after {\n clear:both;\n }\n\n & {\n *zoom:1;\n }\n}\n\n#clearfixedelement {\n @extend %clearfix;\n}\n</code></pre>\n\n<p>If you don't care about support for older browsers, there's a shorter version :</p>\n\n<pre><code>.clearfix:after {\n content:\"\";\n display:table;\n clear:both;\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376/"
] |
Although elements like `<div>`s normally grow to fit their contents, using the `float` property can cause a startling problem for CSS newbies: **If floated elements have non-floated parent elements, the parent will collapse.**
For example:
```html
<div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
The parent div in this example will **not expand** to contain its floated children - it will appear to have `height: 0`.
How do you solve this problem?
==============================
*I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.*
Solution 1
----------
Float the parent.
```html
<div style="float: left;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
**Pros**: Semantic code.
**Cons**: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?
Solution 2
----------
Give the parent an explicit height.
```html
<div style="height: 300px;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
**Pros**: Semantic code.
**Cons**: Not flexible - if the content changes or the browser is resized, the layout will break.
Solution 3
----------
Append a "spacer" element inside the parent element, like this:
```html
<div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
<div class="spacer" style="clear: both;"></div>
</div>
```
**Pros**: Straightforward to code.
**Cons**: Not semantic; the spacer div exists only as a layout hack.
Solution 4
----------
Set parent to `overflow: auto`.
```html
<div style="overflow: auto;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
**Pros**: Doesn't require extra div.
**Cons**: Seems like a hack - that's not the `overflow` property's stated purpose.
Comments? Other suggestions?
============================
|
Solution 1:
-----------
The most reliable and unobtrusive method appears to be this:
Demo: <http://jsfiddle.net/SO_AMK/wXaEH/>
**HTML**:
```
<div class="clearfix">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
**CSS**:
```
.clearfix::after {
content: " ";
display: block;
height: 0;
clear: both;
}
```
With a little CSS targeting, you don't even need to add a class to the parent `DIV`.
This solution is backward compatible with IE8 so you don't need to worry about older browsers failing.
Solution 2:
-----------
An adaptation of solution 1 has been suggested and is as follows:
Demo: <http://jsfiddle.net/wXaEH/162/>
**HTML**:
```
<div class="clearfix">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
```
**CSS**:
```
.clearfix::after {
content: " ";
display: block;
height: 0;
clear: both;
*zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class="ie7-clear"></div>' );
}
.ie7-clear {
display: block;
clear: both;
}
```
This solution appears to be backward compatible to IE5.5 but is untested.
Solution 3:
-----------
It's also possible to set `display: inline-block;` and `width: 100%;` to emulate a normal block element while not collapsing.
Demo: <http://jsfiddle.net/SO_AMK/ae5ey/>
**CSS**:
```
.clearfix {
display: inline-block;
width: 100%;
}
```
This solution should be backward compatible with IE5.5 but has only been tested in IE6.
|
218,777 |
<p>Is it right to use a private constant in the following situation:</p>
<p>Say I have a game with a lives variable and a startingLives variable. At the start of the game I set the lives variable to equal the startingLives variable. This is how I would normally do it:</p>
<pre><code>private var lives:int = 0;
private var startingLives:int = 3;
private function startGame():void
{
lives = startingLives;
}
</code></pre>
<p>(example code is ActionScript btw)</p>
<p>My question is - should this really be:</p>
<pre><code>private var lives:int = 0;
private const STARTING_LIVES:int = 3;
private function startGame():void
{
lives = STARTING_LIVES;
}
</code></pre>
<p>StartingLives seems unlikely to change at runtime, so should I use a const, and change back to a variable if it turns out not to be constant? </p>
<p>UPDATE: The consensus seems to be that this is a good use of a constant, but what about amdfan's suggestion that you may want to load the value in from a config file?</p>
|
[
{
"answer_id": 218782,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 3,
"selected": true,
"text": "<p>Put it in a constant named <code>DEFAULT_STARTING_LIVES</code>, but also have a variable named startingLives. For now, set startingLives = <code>DEFAULT_STARTING_LIVES</code>. Later, you can set startingLives based on a value from a configuration file. If the file has not been created or is not found, you have a back up.</p>\n\n<p>(thanks to Plinth for the expansion on my original answer.)</p>\n"
},
{
"answer_id": 218784,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>Yeah, this is a good use of a const. As a general rule of thumb, any \"variable\" whose value won't change at runtime should be made a constant. This enables the compiler to optimize those values by putting them in a separate (ROM) area of memory. (NOTE: That's not a guarantee that your compiler will optimize, it just makes it <em>possible</em>.)</p>\n"
},
{
"answer_id": 218788,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "<p>I think a private constant is appropriate where it has no use outside of that context, and would result in clutter if made public.</p>\n\n<p>Certainly using a constant in your case is better than a magic number - especially if you need to use it in more than one place.</p>\n"
},
{
"answer_id": 73078935,
"author": "Levite",
"author_id": 1680919,
"author_profile": "https://Stackoverflow.com/users/1680919",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be a good use of a <strong>constant</strong>. If this necessarily needs to be <strong>private</strong> is another question. Might be helpful to be able to read such a value from the outside (especially since it is not modifiable).</p>\n<p>Generally speaking constant private fields especially might make sense if the contents of the constant are still modifiable, which might be highly unwanted. Usually in programming the field reference (where it points to) may no longer be changed when set to constant, which does not mean that the underlying object's properties are also fixed (which is usually NOT the case). This also sort of belongs to the topic of pass-by-value vs pass-by-reference and its implications for copying (deep vs shallow) etc.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911/"
] |
Is it right to use a private constant in the following situation:
Say I have a game with a lives variable and a startingLives variable. At the start of the game I set the lives variable to equal the startingLives variable. This is how I would normally do it:
```
private var lives:int = 0;
private var startingLives:int = 3;
private function startGame():void
{
lives = startingLives;
}
```
(example code is ActionScript btw)
My question is - should this really be:
```
private var lives:int = 0;
private const STARTING_LIVES:int = 3;
private function startGame():void
{
lives = STARTING_LIVES;
}
```
StartingLives seems unlikely to change at runtime, so should I use a const, and change back to a variable if it turns out not to be constant?
UPDATE: The consensus seems to be that this is a good use of a constant, but what about amdfan's suggestion that you may want to load the value in from a config file?
|
Put it in a constant named `DEFAULT_STARTING_LIVES`, but also have a variable named startingLives. For now, set startingLives = `DEFAULT_STARTING_LIVES`. Later, you can set startingLives based on a value from a configuration file. If the file has not been created or is not found, you have a back up.
(thanks to Plinth for the expansion on my original answer.)
|
218,781 |
<p>Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.</p>
<pre><code>Private sub foo()
try
'Do something'
catch
throw 'And nothing else!'
End Try
End Sub
</code></pre>
<p>My thought was to not even bother (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.</p>
<p>The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads?
Best practice does state "an exception handler for each thread" but mostly we work single-threaded.</p>
<p>The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals.
But then your code would be "littered with try/catch/throws" (to quote another thread here)?</p>
<p>And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?</p>
|
[
{
"answer_id": 218791,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging.</p>\n"
},
{
"answer_id": 218793,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>I would only ever do this while debugging an issue - and I'd remove the code again before checking in. It can occasionally be handy to put a breakpoint in to stop at a particular stack level if an exception is thrown. Beyond that though - no.</p>\n"
},
{
"answer_id": 218795,
"author": "Fabian Buch",
"author_id": 28968,
"author_profile": "https://Stackoverflow.com/users/28968",
"pm_score": 1,
"selected": false,
"text": "<p>Doing it always by default looks like bad design. But there might be reasons for catching and throwing, for example it you want to throw a different exception.</p>\n"
},
{
"answer_id": 218796,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 3,
"selected": false,
"text": "<p>In practice, my thought is, if you don't intend to handle the error, don't catch it.</p>\n"
},
{
"answer_id": 218929,
"author": "Jan",
"author_id": 25727,
"author_profile": "https://Stackoverflow.com/users/25727",
"pm_score": 4,
"selected": false,
"text": "<p>Microsoft recommends not to catch an exception when the only thing you do is to rethrow it immediately (i dont remember the source for now).\nYour code should only catch exceptions that you want to handle for clean up things or similar actions.</p>\n\n<p>So generally its not a good practice to catch and rethrow an exception.</p>\n\n<p>Reasons for catching and replacing it with another exception might be </p>\n\n<ul>\n<li>Logging</li>\n<li>Hiding sensitive information from the caller (Stacktrace, exception details)</li>\n</ul>\n\n<p>And for debugging you might want to change your \"Break when an exception is:\"-Handler (Press Ctrl+Alt+e) the value \"thrown\" on selected CLR Exceptions.</p>\n\n<p>You might want to take a look at the entlib exception handler block (EHB), with which you can establish a pattern on how to deal with exceptions in your code.</p>\n\n<p>Regarding your question on performance i think its not a propblem to have many try/catch blocks in your code but you will get performance hits when your code raises and catches many exceptions.</p>\n"
},
{
"answer_id": 218980,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it's handy for putting a breakpoint in the catch.</p>\n\n<p>An <strong>alternate and cleaner way</strong> is to breakpoint in the constructor of the object you're throwing. You're seeing the program state at a point closer to the source of the error.</p>\n"
},
{
"answer_id": 219235,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 1,
"selected": false,
"text": "<p>You do <b>not</b> need a catch clause to catch exceptions in the Visual Studio debugger. Choose Debug > Exceptions, and select which exceptions you want to catch, all of them if necessary.</p>\n"
},
{
"answer_id": 219337,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 1,
"selected": false,
"text": "<p>If you catch an exception and replace it with another exception, you should typically wrap the original exception in the new one. This is usually done by passing the old exception into the new one's constructor. That way you can dig in as much as necessary to figure out what happened. The main case when you wouldn't is when you need to hide data for security reasons. In these cases, you should try to log the exception data before you clear it out.</p>\n\n<p>The rationale I have seen for wrapping exceptions with new ones, rather than just letting them bubble up the stack, is that exceptions should be at the same symantic level as the methods they are coming from. If I call AuthenticateUser, I don't want to see an SQL exception. Instead, I should see some exception whose name tells me the authentication task could not be completed. If I dig into this exception's inner exceptions, I could then find the SQL exception. Personally, I am still weighing the pros and cons of doing this.</p>\n"
},
{
"answer_id": 219535,
"author": "Bryan",
"author_id": 5423,
"author_profile": "https://Stackoverflow.com/users/5423",
"pm_score": 0,
"selected": false,
"text": "<p>Since there is zero error handling, this catch is useless. If there was logging or some cleanup done sure, but in this situation I'd get rid of the try/catch.</p>\n"
},
{
"answer_id": 226364,
"author": "DCNYAM",
"author_id": 30419,
"author_profile": "https://Stackoverflow.com/users/30419",
"pm_score": 0,
"selected": false,
"text": "<p>This can also be useful if you need to inspect something about the exception, and do something for one circumstance or throw it for other circumstances. For instance, if you need to inspect the error number in a SQLException. You can perform a certain action if the error number is one you're prepared to handle. For others you can simply \"throw\" it so the stack trace is preserved, as mentioned above.</p>\n"
},
{
"answer_id": 4641644,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>One effect of using a catch and immediate rethrow is that any inner \"Finally\" blocks will run before the \"Catch\" occurs (which will in turn be before the exception propagates). This is relevant in two scenarios:</p>\n\n<ol>\n<li>If an exception is ultimately unhandled, it's possible that the unhandled-exception trap may quit the application without running any \"finally\" blocks. Doing a catch and immediate rethrow will ensure that all \"finally\" blocks within the catch will execute, even if the exception ends up ultimately being unhandled.\n<li>It is possible for code in vb.net, and possibly other languages, to act upon an exception before any finally blocks are run. Using a \"try\" block with a catch-and-immediate-rethrow will cause the \"finally\" blocks within that catch block to run before any outer \"try\" blocks get their first look at the exception.\n</ol>\n\n<p>An additional caveat with catch-and-immediate-rethrow: for some reason, a catch and immediate rethrow will trash the stack trace's line number for the function call that caused the exception. I don't know why the current function's entry in the stack trace can't be left alone in that case, but it isn't. If one isn't using a .pdb file to get line-number information, this isn't an issue, but if one wants to use such information, it can be annoying.<p></p>\n\n<p>Generally, the effects mentioned above aren't desirable, but there are occasions when one or both of the first two effects they may be useful, and the third effect tolerable. In those cases, a catch with immediate rethrow may be appropriate, though the reason for it should be documented.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20151/"
] |
Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.
```
Private sub foo()
try
'Do something'
catch
throw 'And nothing else!'
End Try
End Sub
```
My thought was to not even bother (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.
The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads?
Best practice does state "an exception handler for each thread" but mostly we work single-threaded.
The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals.
But then your code would be "littered with try/catch/throws" (to quote another thread here)?
And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?
|
The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging.
|
218,786 |
<p>I keep on hearing about concurrent programing every where.
Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?</p>
|
[
{
"answer_id": 218797,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 3,
"selected": false,
"text": "<p>Concurrency is having multiple threads of execution for a given process. As of today, C++ does not directly support it. However, several libraries exist that will tie a given function to a new thread of execution. The Unix standard is the pthreads library.</p>\n"
},
{
"answer_id": 218817,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 7,
"selected": true,
"text": "<p>Concurrency is about your code doing multiple things at the same time. This is typically done with explicit \"threads\", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.</p>\n\n<p>Thread is short for \"thread of execution\". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread.</p>\n\n<p>In C++0x threads are started using the <code>std::thread</code> class:</p>\n\n<pre><code>void my_function()\n{\n // do stuff\n}\nstd::thread my_thread(my_function); // run my_function in its own thread\n</code></pre>\n\n<p>The new C++0x standard also supports:</p>\n\n<ul>\n<li>atomic values and operations with the <code>std::atomic<></code> class template,</li>\n<li>mutexes for data protection (<code>std::mutex</code>, <code>std::recursive_mutex</code>, etc.)</li>\n<li>lock classes for ease of managing lock lifetime (<code>std::lock_guard<></code>, <code>std::unique_lock<></code>)</li>\n<li><code>std::lock</code> and <code>std::try_lock</code> functions to manage acquiring multiple locks at the same time without risking deadlock</li>\n<li>condition variables to ease waiting for an event (<code>std::condition_variable</code>, <code>std::condition_variable_any</code>)</li>\n<li>futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic \"how do I return a value from a thread\" question.</li>\n<li>thread-safe initialization of local static objects</li>\n<li>the <code>thread_local</code> keyword to declare thread-local data</li>\n</ul>\n\n<p>I gave a more detailed overview of the new C++0x thread library in my article on devx.com: <a href=\"http://www.devx.com/SpecialReports/Article/38883\" rel=\"noreferrer\">Simpler Multithreading in C++0x</a></p>\n\n<p>I write about multithreading and concurrency in C++ on <a href=\"http://www.justsoftwaresolutions.co.uk/blog\" rel=\"noreferrer\">my blog</a>. I'm also writing a book on the topic: <a href=\"http://www.manning.com/williams\" rel=\"noreferrer\">C++ Concurrency in Action</a>.</p>\n"
},
{
"answer_id": 218856,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "<p>When you say \"how c++ new standards facilitate\" concurrent programming, I assume you're talking about the soon (?) to be released C++09 standard.</p>\n\n<p>The new standard as it currently stands in draft form supports the following items that help with concurrent programming:</p>\n\n<ul>\n<li>atomic types and addresses</li>\n<li>a thread class</li>\n<li>thread_local storage (which was just added into the draft standard a few months ago)</li>\n<li>mutual exclusion (mutex classes)</li>\n<li>condition variables - this is particularly nice for Windows, since condition variables are difficult to implement correctly in Win32. This means that eventually Microsoft should provide support for condition variables at least in the MSVC++ runtime, so it will be easy to get correct condition variable semantics on WIn32.</li>\n</ul>\n"
},
{
"answer_id": 219011,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "<p>My slightly different take, specific to future directions of programming paradigms:</p>\n\n<p>Concurrency is about writing your program such that it can be doing multiple things at once if the hardware supports it. Currently, most languages have fairly heavy and complicated mechanisms to allow the programmer to specify this (eg: threads with manual synchronization, OpenMP pre-processor directives, etc.).</p>\n\n<p>As hardware improves, it's going to improve horizontally (more cores) rather than vertically (faster single core). This means apps will need to have \"latent concurrency\" in order to scale with \"faster\" hardware. Languages are currently trying to evolve to best support this, to be in the position of best language for future development.</p>\n\n<p>C++0x is adding more built-in support for the \"old\" methods of programming concurrency. Various compiler vendors are adding \"new\" methods which abstract the threading model and allow run-time decisions on numbers of threads, etc. (based on the hardware of the machine); for Microsoft in particular, see F#, concurrency runtime, parallel extensions, etc.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 219035,
"author": "Dynite",
"author_id": 16177,
"author_profile": "https://Stackoverflow.com/users/16177",
"pm_score": 3,
"selected": false,
"text": "<p>C++CSP2 - Easy Concurrency for C++</p>\n\n<p><a href=\"http://www.cs.kent.ac.uk/projects/ofa/c++csp/\" rel=\"noreferrer\">http://www.cs.kent.ac.uk/projects/ofa/c++csp/</a></p>\n\n<p>CSP is a based on a proper concurrent paradigm as opposed to threads and locks and all other manner of things which are tacked on as an afterthought.</p>\n\n<p>(See Occam-Pi for a concurrent programming language (also based on CSP))</p>\n"
},
{
"answer_id": 17737426,
"author": "Marcus Thornton",
"author_id": 2288882,
"author_profile": "https://Stackoverflow.com/users/2288882",
"pm_score": 1,
"selected": false,
"text": "<p>This is the best article to understand concurrent programming: <a href=\"http://www.nondot.org/sabre/Mirrored/AdvProgLangDesign/finkel07.pdf\" rel=\"nofollow\">Concurrent Programming</a></p>\n\n<p>You will get the full picture of concurrent programming and C++ after reading it.</p>\n\n<p>As a quick summary, we can say that concurrent programming is to do multitasking. When a program gets blocked, it can do other things. Typically we get blocked while waiting for network connections and dealing with I/O. We can facilitate concurrent programming using <code>fork()</code> and thread libraries.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
I keep on hearing about concurrent programing every where.
Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?
|
Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.
Thread is short for "thread of execution". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread.
In C++0x threads are started using the `std::thread` class:
```
void my_function()
{
// do stuff
}
std::thread my_thread(my_function); // run my_function in its own thread
```
The new C++0x standard also supports:
* atomic values and operations with the `std::atomic<>` class template,
* mutexes for data protection (`std::mutex`, `std::recursive_mutex`, etc.)
* lock classes for ease of managing lock lifetime (`std::lock_guard<>`, `std::unique_lock<>`)
* `std::lock` and `std::try_lock` functions to manage acquiring multiple locks at the same time without risking deadlock
* condition variables to ease waiting for an event (`std::condition_variable`, `std::condition_variable_any`)
* futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic "how do I return a value from a thread" question.
* thread-safe initialization of local static objects
* the `thread_local` keyword to declare thread-local data
I gave a more detailed overview of the new C++0x thread library in my article on devx.com: [Simpler Multithreading in C++0x](http://www.devx.com/SpecialReports/Article/38883)
I write about multithreading and concurrency in C++ on [my blog](http://www.justsoftwaresolutions.co.uk/blog). I'm also writing a book on the topic: [C++ Concurrency in Action](http://www.manning.com/williams).
|
218,794 |
<p>I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:</p>
<pre><code>var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
...
});
</code></pre>
<p>The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.</p>
<p>Is there a way to get the fields trimmed <strong>without</strong> doing the following:</p>
<pre><code>$("#name").val( jQuery.trim( $("#name") ) );
</code></pre>
|
[
{
"answer_id": 219013,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 3,
"selected": false,
"text": "<p>Trim all <strong><input></strong> and <strong><textarea></textarea></strong> element values in the DOM:</p>\n\n<pre><code>$('input, textarea').each(function(){\n $(this).val(jQuery.trim($(this).val()));\n});\n</code></pre>\n"
},
{
"answer_id": 219018,
"author": "Josh Bush",
"author_id": 1672,
"author_profile": "https://Stackoverflow.com/users/1672",
"pm_score": 1,
"selected": false,
"text": "<p>You could loop over all of the inputs and trim before submitting.</p>\n\n<pre><code>$(\"input, textarea\").each(function(){\n $(this).val(jQuery.trim($(this).val()));\n});\n</code></pre>\n"
},
{
"answer_id": 219140,
"author": "Jared",
"author_id": 24841,
"author_profile": "https://Stackoverflow.com/users/24841",
"pm_score": 0,
"selected": false,
"text": "<p>Neither of those solutions work, since they actually change the form fields on the page. I just want to modify the value of the field that without changing what the user typed in.</p>\n"
},
{
"answer_id": 219336,
"author": "Jethro Larson",
"author_id": 22425,
"author_profile": "https://Stackoverflow.com/users/22425",
"pm_score": 4,
"selected": true,
"text": "<p>You could try looping through the object and triming everything.</p>\n\n<pre><code>//Serialize form as array\nvar serializedForm = form.serializeArray();\n//trim values\nfor(var i =0, len = serializedForm.length;i<len;i++){\n serializedForm[i] = $.trim(serializedForm[i]);\n}\n//turn it into a string if you wish\nserializedForm = $.param(serializedForm);\n</code></pre>\n"
},
{
"answer_id": 219429,
"author": "Bryan A",
"author_id": 29707,
"author_profile": "https://Stackoverflow.com/users/29707",
"pm_score": 0,
"selected": false,
"text": "<p>One thing you could do is have a separate form with hidden values, and store the actual, trimmed, form values in the hidden values when the user submits, then you can serialize the \"hidden\" form and post that. Just an idea.</p>\n"
},
{
"answer_id": 435977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using ASP.NET where you can have only one form per page, you can submit only the values of a given DIV as follows:</p>\n\n<pre><code>var dataString = \"source=contactDiv\";\ndataString += getDataString(divId, \"input\"); // add inputs\ndataString += getDataString(divId, \"select\"); //add select elements\n</code></pre>\n\n<p>then post the update as follows:</p>\n\n<pre><code>$.post(\"UpdateContact.aspx\",\n dataString,\n afterUpdate,\n \"json\");\n</code></pre>\n\n<p>helper functions</p>\n\n<pre><code>function afterUpdate(data){\n//add some post-update info\n}\n\nfunction getDataString(divId, tagName) {\n var data = \"\";\n var elements = $(\"#\" + divId + \" \" + tagName);\n for (var i = 0; i < elements.length; i++) {\n var el = elements[i];\n var name = el.name;\n var value = $(el).val();\n if (value != null && value != \"undefined\")\n value = $.trim(value + \"\"); //added \"\" to fix IE 6 bug for empty select \n if (el.type == \"checkbox\")\n value = el.checked;\n else if (el.type == \"radio\" && !el.checked)\n value = \"\";\n if (!(value == \"\" || value == \"undefined\" || name == \"\" || name == \"undefined\"))\n data += \"&\" + name + \"=\" + escape(value);\n }\n\n return data;\n}\n</code></pre>\n"
},
{
"answer_id": 1374677,
"author": "Ulf Lindback",
"author_id": 30354,
"author_profile": "https://Stackoverflow.com/users/30354",
"pm_score": 2,
"selected": false,
"text": "<p>A little late, but this was probably what you wanted:</p>\n<pre><code>var form = $("form");\nvar action = form.attr("action");\nvar formArr = form. serializeArray();\n$.each(formArr , function(i, field) {\n formArr[i].value = $.trim(field.value);\n});\nvar serializedForm = $.param(formArr);\n$.post(action, serializedForm, function(data)\n{\n ...\n});\n</code></pre>\n"
},
{
"answer_id": 64290494,
"author": "Billu",
"author_id": 7186739,
"author_profile": "https://Stackoverflow.com/users/7186739",
"pm_score": 0,
"selected": false,
"text": "<p>if you have already included jquery file then use this script</p>\n<pre><code>var formFilters = $('input, textarea');\n formFilters.each(function(){\n $(this).val($(this).val().trim());\n });\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24841/"
] |
I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:
```
var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
...
});
```
The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.
Is there a way to get the fields trimmed **without** doing the following:
```
$("#name").val( jQuery.trim( $("#name") ) );
```
|
You could try looping through the object and triming everything.
```
//Serialize form as array
var serializedForm = form.serializeArray();
//trim values
for(var i =0, len = serializedForm.length;i<len;i++){
serializedForm[i] = $.trim(serializedForm[i]);
}
//turn it into a string if you wish
serializedForm = $.param(serializedForm);
```
|
218,798 |
<p>The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?</p>
|
[
{
"answer_id": 218833,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 5,
"selected": false,
"text": "<p>Is object: </p>\n\n<pre><code>function isObject ( obj ) {\n return obj && (typeof obj === \"object\");\n}\n</code></pre>\n\n<p>Is array:</p>\n\n<pre><code>function isArray ( obj ) { \n return isObject(obj) && (obj instanceof Array);\n}\n</code></pre>\n\n<p>Because arrays are objects you'll want to test if a variable is an array first, and then if it is an object:</p>\n\n<pre><code>if (isArray(myObject)) {\n // do stuff for arrays\n}\nelse if (isObject(myObject)) {\n // do stuff for objects\n}\n</code></pre>\n"
},
{
"answer_id": 218834,
"author": "pawel",
"author_id": 4879,
"author_profile": "https://Stackoverflow.com/users/4879",
"pm_score": 8,
"selected": true,
"text": "<p><strong>Modern browsers support the <code>Array.isArray(obj)</code> method.</strong></p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"noreferrer\">See MDN</a> for documentation and a polyfill.</p>\n\n<p>= <em>original answer from 2008</em> =</p>\n\n<p>you can use the constuctor property of your output: </p>\n\n<pre><code>if(output.constructor == Array){\n}\nelse if(output.constructor == Object){\n}\n</code></pre>\n"
},
{
"answer_id": 218836,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 2,
"selected": false,
"text": "<p>Check for \"constructor\" property on the object. It is Array - it is an array object.</p>\n\n<pre>\n\nvar a = {\n 'b':{length:0},\n 'c':[1,2]\n}\n\nif (a.c.constructor == Array)\n for (var i = 0; i < a.c.length; i++)\n alert(a.c[i]);\nelse\n for (var s in a.b);\n alert(a.b[s]);\n\n</pre>\n"
},
{
"answer_id": 218838,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "<p>Did you mean \"Object\" instead of \"Hash\"?</p>\n\n<pre><code>>>> var a = [];\n>>> var o = {};\n>>> a instanceof Array\ntrue\n>>> o instanceof Array\nfalse\n</code></pre>\n"
},
{
"answer_id": 23716468,
"author": "neoneye",
"author_id": 78336,
"author_profile": "https://Stackoverflow.com/users/78336",
"pm_score": 3,
"selected": false,
"text": "<p>I made a function for determining if it's a dictionary.</p>\n\n<pre><code>exports.is_dictionary = function (obj) {\n if(!obj) return false;\n if(Array.isArray(obj)) return false;\n if(obj.constructor != Object) return false;\n return true;\n};\n\n// return true\ntest.equal(nsa_utils.is_dictionary({}), true);\ntest.equal(nsa_utils.is_dictionary({abc:123, def:456}), true);\n\n// returns false\ntest.equal(nsa_utils.is_dictionary([]), false);\ntest.equal(nsa_utils.is_dictionary([123, 456]), false);\ntest.equal(nsa_utils.is_dictionary(null), false);\ntest.equal(nsa_utils.is_dictionary(NaN), false);\ntest.equal(nsa_utils.is_dictionary('hello'), false);\ntest.equal(nsa_utils.is_dictionary(0), false);\ntest.equal(nsa_utils.is_dictionary(123), false);\n</code></pre>\n"
},
{
"answer_id": 45459626,
"author": "Viktor Ivliiev",
"author_id": 4479867,
"author_profile": "https://Stackoverflow.com/users/4479867",
"pm_score": 0,
"selected": false,
"text": "<p>For parsing json could come in handy :)</p>\n\n<pre><code>isArrayHashs = (attr) ->\n !!attr && attr.constructor == Array && isHash(attr[0])\n\nisHash = (attr) ->\n !!attr && !$.isNumeric(attr) && attr.constructor == Object\n</code></pre>\n\n<p>attr[0].constructor must be:</p>\n\n<ul>\n<li>String</li>\n<li>Numeric</li>\n<li>Array</li>\n<li>Object</li>\n<li>Undefined</li>\n</ul>\n"
},
{
"answer_id": 61426885,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 2,
"selected": false,
"text": "<p>A more practical and precise term than object or hash or dictionary may be <strong>associative array</strong>. Object could apply to many undesirables, e.g. <code>typeof null === 'object'</code> or <code>[1,2,3] instanceof Object</code>. The following two functions work since ES3 and are mutually exclusive.</p>\n<pre><code>function is_array(z) {\n return Object(z) instanceof Array;\n}\n\nconsole.assert(true === is_array([]));\nconsole.assert(true === is_array([1,2,3]));\nconsole.assert(true === is_array(new Array));\nconsole.assert(true === is_array(Array(1,2,3)));\n\nconsole.assert(false === is_array({a:1, b:2}));\nconsole.assert(false === is_array(42));\nconsole.assert(false === is_array("etc"));\nconsole.assert(false === is_array(null));\nconsole.assert(false === is_array(undefined));\nconsole.assert(false === is_array(true));\nconsole.assert(false === is_array(function () {}));\n</code></pre>\n<pre><code>function is_associative_array(z) {\n return String(z) === '[object Object]' && ! (Object(z) instanceof String);\n}\n\nconsole.assert(true === is_associative_array({a:1, b:2}));\nconsole.assert(true === is_associative_array(new function Legacy_Class(){}));\nconsole.assert(true === is_associative_array(new class ES2015_Class{}));\n\nconsole.assert(false === is_associative_array(window));\nconsole.assert(false === is_associative_array(new Date()));\nconsole.assert(false === is_associative_array([]));\nconsole.assert(false === is_associative_array([1,2,3]));\nconsole.assert(false === is_associative_array(Array(1,2,3)));\nconsole.assert(false === is_associative_array(42));\nconsole.assert(false === is_associative_array("etc"));\nconsole.assert(false === is_associative_array(null));\nconsole.assert(false === is_associative_array(undefined));\nconsole.assert(false === is_associative_array(true));\nconsole.assert(false === is_associative_array(function () {}));\n\n</code></pre>\n<p>Notice how this will treat the <strong>instance of a class</strong> as an associative array. (But not the instance of a built-in class, such as Date.)</p>\n<p>The <code>&&</code> clause above is a brutish fix for this obscure white-box test:</p>\n<pre><code>console.assert(false === is_associative_array("[object Object]"));\n</code></pre>\n<p>Caution: these functions will not be efficient for large or many objects.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29653/"
] |
The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?
|
**Modern browsers support the `Array.isArray(obj)` method.**
[See MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) for documentation and a polyfill.
= *original answer from 2008* =
you can use the constuctor property of your output:
```
if(output.constructor == Array){
}
else if(output.constructor == Object){
}
```
|
218,806 |
<p>I am wondering how the JBoss ExceptionSorter classes are able to check for database errors.</p>
<p>The application (the EJB or persistence framework) is holding the reference to the database Connection, so SQLExceptions are caught by the application. How is JBoss able to see the contents of the exception?</p>
<p>Does JBoss wrap the connection and intercept these messages or something like that?</p>
|
[
{
"answer_id": 360041,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>JBoss uses a connection pool for its datasources (org.jboss.resource.adapter.jdbc.local.LocalTxDataSource). The ExceptionSorter takes an SQLException as a parameter which it then just checks for certain strings which map to certain errors. If the errors represent a physical connection problem then they will look somewhat like \"Socket error\" or \"broken pipe\".</p>\n\n<p>This Exception Sorter will then return a boolean value representing the state of the connection back to the connection pool which will then invalidate and remove any connections that returned false.</p>\n\n<p>For an Oracle database:</p>\n\n<pre><code><property name=\"exceptionSorterClassName\"><value>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</value></property>\n</code></pre>\n\n<p>This will work for an Oracle database. Here is the code for that ExceptionSorter implementation:</p>\n\n<p><a href=\"http://kickjava.com/src/org/jboss/resource/adapter/jdbc/vendor/OracleExceptionSorter.java.htm\" rel=\"nofollow noreferrer\">http://kickjava.com/src/org/jboss/resource/adapter/jdbc/vendor/OracleExceptionSorter.java.htm</a></p>\n\n<p>How the internal programming of where or how the connection pool checks the connection is unknown to me. Check the JBoss source code.</p>\n"
},
{
"answer_id": 13593728,
"author": "GreenGiant",
"author_id": 539048,
"author_profile": "https://Stackoverflow.com/users/539048",
"pm_score": 3,
"selected": true,
"text": "<p>If you have ever run a debugger against code running inside JBoss, while that that has an open database connection, you will notice that the connection is actually a JBoss-specific class that wraps the real database connection.</p>\n\n<p>In some cases, you can see this wrapper as a line in the stack trace when an exception is thrown by the database, such as a SQL syntax exception. See last line in example below:</p>\n\n<pre><code>java.sql.SQLException: ORA-00942: table or view does not exist\n at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)\n at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)\n at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)\n at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:810)\n at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1039)\n at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:850)\n at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1134)\n at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3339)\n at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3384)\n at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:342)\n</code></pre>\n\n<p>I imagine this wrapper may provide the exception-inspection you suggested.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25688/"
] |
I am wondering how the JBoss ExceptionSorter classes are able to check for database errors.
The application (the EJB or persistence framework) is holding the reference to the database Connection, so SQLExceptions are caught by the application. How is JBoss able to see the contents of the exception?
Does JBoss wrap the connection and intercept these messages or something like that?
|
If you have ever run a debugger against code running inside JBoss, while that that has an open database connection, you will notice that the connection is actually a JBoss-specific class that wraps the real database connection.
In some cases, you can see this wrapper as a line in the stack trace when an exception is thrown by the database, such as a SQL syntax exception. See last line in example below:
```
java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:810)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1039)
at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:850)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1134)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3339)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3384)
at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:342)
```
I imagine this wrapper may provide the exception-inspection you suggested.
|
218,808 |
<p>I've got a <code>DateTime?</code> that I'm trying to insert into a field using a <code>DbParameter</code>. I'm creating the parameter like so:</p>
<pre><code>DbParameter datePrm = updateStmt.CreateParameter();
datePrm.ParameterName = "@change_date";
</code></pre>
<p>And then I want to put the value of the <code>DateTime?</code> into the <code>dataPrm.Value</code> while accounting for <code>null</code>s.</p>
<p>I thought initially I'd be clever:</p>
<pre><code>datePrm.Value = nullableDate ?? DBNull.Value;
</code></pre>
<p>but that fails with the error</p>
<blockquote>
<p>Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'</p>
</blockquote>
<p>So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:</p>
<pre><code>datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
</code></pre>
<p>but that doesn't work either:</p>
<blockquote>
<p>Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'</p>
</blockquote>
<p>But I don't want to convert between those types!</p>
<p>So far the only thing I can get to work is:</p>
<pre><code>if (nullableDate.HasValue)
datePrm.Value = nullableDate.Value;
else
datePrm.Value = DBNull.Value;
</code></pre>
<p>Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?</p>
<p><strong>Update:</strong> I don't really get why the ?? version doesn't work. MSDN says:</p>
<blockquote>
<p>The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.</p>
</blockquote>
<p>That's exactly what I want!</p>
<p><strong>Update2:</strong> Well it was kind of obvious in the end:</p>
<pre><code>datePrm.Value = nullableDate ?? (object)DBNull.Value;
</code></pre>
|
[
{
"answer_id": 218843,
"author": "dnolan",
"author_id": 29086,
"author_profile": "https://Stackoverflow.com/users/29086",
"pm_score": 3,
"selected": false,
"text": "<p>It would work if you used</p>\n\n<pre><code>datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : DBNull.Value;\n</code></pre>\n"
},
{
"answer_id": 218844,
"author": "Dan",
"author_id": 28537,
"author_profile": "https://Stackoverflow.com/users/28537",
"pm_score": 1,
"selected": false,
"text": "<p>I think the error with your second attempt is due to nullableDate.Value and DBNull.Value being different types and the ternary operator needing to pick one type to return in both cases. I don't have the environment to test this but I think this should work for you:</p>\n\n<pre><code>datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : (object)DBNull.Value;\n</code></pre>\n"
},
{
"answer_id": 218853,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>The way that I do it, is I have a static utility class that just goes through and checks to see if the parameter value is null, then i set the value to do DBNull. I just do that before i call the Execute.</p>\n"
},
{
"answer_id": 218862,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using C# 3.0 you can create an extension method to do this easy:</p>\n\n<pre><code>public static class DBNullableExtensions\n{\n public static object ToDBValue<T>(this Nullable<T> value) where T:struct\n { \n return value.HasValue ? (object)value.Value : DBNull.Value;\n }\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n int? x = null;\n\n Console.WriteLine( x.ToDBValue() == DBNull.Value );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 218896,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 7,
"selected": true,
"text": "<p>Ah ha! I found an even more efficient solution than @Trebz's!</p>\n\n<pre><code>datePrm.Value = nullableDate ?? (object)DBNull.Value;\n</code></pre>\n"
},
{
"answer_id": 29258351,
"author": "Gian Marco",
"author_id": 66629,
"author_profile": "https://Stackoverflow.com/users/66629",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using SQLServer, the <code>System.Data.SqlTypes</code> namespace contains some utility classes that avoid the annoying type casting. For example instead of this:</p>\n\n<pre><code>var val = (object) \"abc\" ?? DBNull.Value;\n</code></pre>\n\n<p>you can write this:</p>\n\n<pre><code>var val = \"abc\" ?? SqlString.Null;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] |
I've got a `DateTime?` that I'm trying to insert into a field using a `DbParameter`. I'm creating the parameter like so:
```
DbParameter datePrm = updateStmt.CreateParameter();
datePrm.ParameterName = "@change_date";
```
And then I want to put the value of the `DateTime?` into the `dataPrm.Value` while accounting for `null`s.
I thought initially I'd be clever:
```
datePrm.Value = nullableDate ?? DBNull.Value;
```
but that fails with the error
>
> Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'
>
>
>
So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:
```
datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
```
but that doesn't work either:
>
> Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'
>
>
>
But I don't want to convert between those types!
So far the only thing I can get to work is:
```
if (nullableDate.HasValue)
datePrm.Value = nullableDate.Value;
else
datePrm.Value = DBNull.Value;
```
Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?
**Update:** I don't really get why the ?? version doesn't work. MSDN says:
>
> The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
>
>
>
That's exactly what I want!
**Update2:** Well it was kind of obvious in the end:
```
datePrm.Value = nullableDate ?? (object)DBNull.Value;
```
|
Ah ha! I found an even more efficient solution than @Trebz's!
```
datePrm.Value = nullableDate ?? (object)DBNull.Value;
```
|
218,825 |
<p>I have three Java <code>JCheckboxes</code> in a column, arranged by setting the layout of the container <code>JPanel</code> to <code>GridLayout(3, 1, 1, 1)</code>. When I run the program, there is too much vertical space between the JCheckBoxes; it looks like more than 1 pixel. Since I've already set the vertical space between the JCheckboxes in the layout to be 1 pixel, how else can I reduce the vertical space between these JCheckboxes?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 219198,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 2,
"selected": false,
"text": "<p>I explored using <code>GridLayout</code>, <code>BorderLayout</code>, and <code>GridBagLayout</code> and I believe that any extra vertical space that is present in your application is due to the sizing of the JCheckBox component, not related to the layout manager. All of the examples below have no space between components in the layout manager. </p>\n\n<p><strong>GridLayout</strong></p>\n\n<pre><code>//Changing to 3,1,1,0 makes slightly smaller (1 pixel) gap vertically \nGridLayout layout = new GridLayout( 3, 1, 1, 0 );\nJPanel main = new JPanel( layout );\nmain.add( new JCheckBox( \"box 1\" ) );\nmain.add( new JCheckBox( \"box 2\" ) );\nmain.add( new JCheckBox( \"box 3\" ) );\n</code></pre>\n\n<p><strong>GridBagLayout</strong></p>\n\n<pre><code>GridBagConstraints gbc = new GridBagConstraints();\nJPanel main = new JPanel( new GridBagLayout() );\ngbc.gridx=0;\ngbc.gridy=0;\ngbc.ipady=0;\nmain.add( new JCheckBox( \"box 1\" ), gbc );\ngbc.gridy=1;\nmain.add( new JCheckBox( \"box 2\" ), gbc );\ngbc.gridy=2;\nmain.add( new JCheckBox( \"box 3\" ), gbc );\n</code></pre>\n\n<p><strong>BorderLayout</strong></p>\n\n<pre><code>JPanel main = new JPanel( new BorderLayout() );\nmain.add( new JCheckBox( \"box 1\" ), BorderLayout.NORTH );\nmain.add( new JCheckBox( \"box 2\" ), BorderLayout.CENTER );\nmain.add( new JCheckBox( \"box 3\" ), BorderLayout.SOUTH );\n</code></pre>\n"
},
{
"answer_id": 221513,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 2,
"selected": false,
"text": "<p>Does it help if you set the checkbox's border?</p>\n\n<pre><code>JCheckBox checkBox = new JCheckBox();\ncheckBox.setBorder(BorderFactory.createEmptyBorder());\n</code></pre>\n\n<p>It may also be due to the Look & Feel's UI delegate's rendering. You typically have little control over this.</p>\n"
},
{
"answer_id": 222160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you Steve and Alex. Both your responses were correct. By setting the border to an empty border, I was able to move the checkboxes closer. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have three Java `JCheckboxes` in a column, arranged by setting the layout of the container `JPanel` to `GridLayout(3, 1, 1, 1)`. When I run the program, there is too much vertical space between the JCheckBoxes; it looks like more than 1 pixel. Since I've already set the vertical space between the JCheckboxes in the layout to be 1 pixel, how else can I reduce the vertical space between these JCheckboxes?
Thanks.
|
I explored using `GridLayout`, `BorderLayout`, and `GridBagLayout` and I believe that any extra vertical space that is present in your application is due to the sizing of the JCheckBox component, not related to the layout manager. All of the examples below have no space between components in the layout manager.
**GridLayout**
```
//Changing to 3,1,1,0 makes slightly smaller (1 pixel) gap vertically
GridLayout layout = new GridLayout( 3, 1, 1, 0 );
JPanel main = new JPanel( layout );
main.add( new JCheckBox( "box 1" ) );
main.add( new JCheckBox( "box 2" ) );
main.add( new JCheckBox( "box 3" ) );
```
**GridBagLayout**
```
GridBagConstraints gbc = new GridBagConstraints();
JPanel main = new JPanel( new GridBagLayout() );
gbc.gridx=0;
gbc.gridy=0;
gbc.ipady=0;
main.add( new JCheckBox( "box 1" ), gbc );
gbc.gridy=1;
main.add( new JCheckBox( "box 2" ), gbc );
gbc.gridy=2;
main.add( new JCheckBox( "box 3" ), gbc );
```
**BorderLayout**
```
JPanel main = new JPanel( new BorderLayout() );
main.add( new JCheckBox( "box 1" ), BorderLayout.NORTH );
main.add( new JCheckBox( "box 2" ), BorderLayout.CENTER );
main.add( new JCheckBox( "box 3" ), BorderLayout.SOUTH );
```
|
218,848 |
<p>I need to give users the ability to optionally add metadata to documents. Another way to state this is the fact that users need to add at least 5 categories to a document.</p>
<p>Basically what I want to do is dynamically add metadata (or categories) to a document on an ad hoc basis. Here are the options that I have thought of:</p>
<p><strong>Option 1:</strong>
Should I do this by dynamically creating new table columns in the database? </p>
<p><strong>Option 2:</strong>
Should I define 5 columns called attirbute1,attirbute2,attirbute3,attirbute4,attirbute5 and then only use and show them if the user requires the attributes. </p>
<p><strong>Option 3:</strong>
Should I create a metadata table that keeps track of the columns and the data associated with them? </p>
<p>What do you think is the best way to achieve this? Can you think of any other ways to easily add this functionality. The problem is that the functionality needs to be very generic.</p>
|
[
{
"answer_id": 218872,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 3,
"selected": false,
"text": "<p>Each document has a unique DocumentID.</p>\n\n<p>Just add another table that has three columns:</p>\n\n<pre>DocumentID\nMetaName\nMetaData</pre>\n\n<p>Then they can add as many pieces of metadata to a given document. If all their documents use the same metanames then it's trivial to search the metadata.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 218874,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 0,
"selected": false,
"text": "<p>All of these options are feasible, and there is not one correct answer. You should weigh your various options and choose the best solution for your situation.</p>\n\n<p>Option 1: Feasible but could really get out of hand as your user count increases. May also have an impact on storage costs.</p>\n\n<p>Option 2: Probably the fastest solution to implement but the least robust solution and a higher maintenance cost. If you need to go to 6 columns, you will have to add another column, etc..</p>\n\n<p>Option 3: Probably the most robust solution is to have a metadata table that captures this information and then build your tables\\columns dynamically based on this metadata. This solution will also probably take the longest and cost the most $$.</p>\n"
},
{
"answer_id": 218879,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>This sounds a lot like tagging. You can probably modify <a href=\"http://rubyforge.org/projects/taggable/\" rel=\"nofollow noreferrer\">acts-as-taggable</a> to do what you need.</p>\n"
},
{
"answer_id": 218882,
"author": "Jacob B",
"author_id": 29664,
"author_profile": "https://Stackoverflow.com/users/29664",
"pm_score": 0,
"selected": false,
"text": "<p>I'd certainly go with option 3: have a table called DocumentCategories, which stores the category each document belongs to. Not only is it \"more relational\", it also will help if your requirements ever change: what if you decide you want 6 categories tomorrow?</p>\n\n<p>Plus, it gives you more options for querying: what if you want to see how many times each category was used, or to select documents by category? With option 3, that's just a join, and it's both fast and easy to write. Options 1 and 2 make doing simple things like that very complicated.</p>\n"
},
{
"answer_id": 218884,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>I would go with option 3. </p>\n\n<p>Dynamically changing the data structure will become very difficult to maintain, and could introduce some <em>interesting</em> bugs. </p>\n\n<p>Having a number of columns that may or may not be needed will still add complexity becuase you will need to check if each column is used. Plus, you will still be restrained to 5 columns.</p>\n\n<p>Option 3, though is very flexible, and allows for growth. Just have a foreign key referring to the document, a column for the name, and a column for the value.</p>\n"
},
{
"answer_id": 218963,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "<p>I would go with three tables.</p>\n\n<p>Document (The document)</p>\n\n<p>Category (The defined categories)</p>\n\n<p>DocumentCategory (A link table connecting documents to categories)</p>\n\n<p>The only downside is that your dbms might not support a good way to constrain this design to require atleast five entries in DocumentCategories per Document, but you could enforce this at the application level.</p>\n"
},
{
"answer_id": 218993,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": 1,
"selected": false,
"text": "<p>One thing you don't make clear is if the number and/or name of attributes is changeable or if it's the same for all documents. This would alter my recommendation somewhat.</p>\n\n<p>Presuming you have an object handle that uniquely describes a given document, I propose a table that manages the meta-data. If you have an unknown number of attributes and unknown names of those attributes, I recommend something like this:</p>\n\n<pre><code>create table DocMetaData\n(\n DocumentHandle varchar NOT NULL,\n MetaDataName varchar NOT NULL,\n MetaDataText varchar NOT NULL\n);\n</code></pre>\n\n<p>You then insert into this table when you have meta-data using the name that's most appropriate. If there's no row, there's no meta-data. If there is meta-data, you clearly have a name for that meta-data, and the data itself. You can include nullability on the metadata itself if you need to, though I'd probably just make it an empty text (something like, <code>default ''</code>), rather than nulls because you get odd behaviors (don't get your row!) if you select a column and it's not there and you didn't explicitly ask for the null value rows. Remember, this design doesn't spell out <code>unique</code> so you've got optionality, only store when you have data...</p>\n\n<p>Of course, if all the possible meta-data attributes are known, you could just spell them out!</p>\n\n<p>Dynamic table creation is a ROYAL pain - I would not do it here.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29441/"
] |
I need to give users the ability to optionally add metadata to documents. Another way to state this is the fact that users need to add at least 5 categories to a document.
Basically what I want to do is dynamically add metadata (or categories) to a document on an ad hoc basis. Here are the options that I have thought of:
**Option 1:**
Should I do this by dynamically creating new table columns in the database?
**Option 2:**
Should I define 5 columns called attirbute1,attirbute2,attirbute3,attirbute4,attirbute5 and then only use and show them if the user requires the attributes.
**Option 3:**
Should I create a metadata table that keeps track of the columns and the data associated with them?
What do you think is the best way to achieve this? Can you think of any other ways to easily add this functionality. The problem is that the functionality needs to be very generic.
|
Each document has a unique DocumentID.
Just add another table that has three columns:
```
DocumentID
MetaName
MetaData
```
Then they can add as many pieces of metadata to a given document. If all their documents use the same metanames then it's trivial to search the metadata.
-Adam
|
218,857 |
<p>I have a class that contains a bunch of properties. It is a mistake by a programmer if they call ToString() on an object of that type. Take this example code:</p>
<pre><code>using System;
public class Foo
{
public int ID = 123;
public string Name = "SomeName";
private string ToString() { return null; }
}
public class MyClass
{
public static void Main()
{
Foo myObj = new Foo();
WL("I want this to be a compiler error: {0}", myObj.ToString());
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
#endregion
}
</code></pre>
<p>You could reason that if ID is what most people want written out as a string, then I should implement ToString so that it returns the ID. However, I believe that is a bad practice because programmers will "accidentally" get working code. A programmer using my class should specify what they want.</p>
<p>Instead, what I would like is if someone calls myObj.ToString() to have that show up as a compile time error. I thought I could do that by creating a private ToString() function, but that doesn't work.</p>
<p>The reason I brought this up is that we ended up with a query string that contained the fully qualified class name rather then an ID. </p>
<p>So the question is: <strong>Is there any way to "hide" the ToString() function so that calling it on an object of my class causes a compiler error?</strong></p>
|
[
{
"answer_id": 218868,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 4,
"selected": false,
"text": "<p>The Obsolete attribute allows you to do this.</p>\n\n<pre><code>[Obsolete(\"Use the XYZ properties instead of .ToString() on Foobar\", true)]\n</code></pre>\n\n<p>The boolean at the end is for whether the compiler should consider use of this member an error.</p>\n"
},
{
"answer_id": 218871,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>Use the override keyword with a public ToString() function to override the System.Object ToString() methiod.</p>\n"
},
{
"answer_id": 218885,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 6,
"selected": false,
"text": "<p><strong>I cannot stress enough how bad an idea this design is.</strong> </p>\n\n<p><code>ToString()</code> is part of the object contract in .Net. If you don't want to implement it then don't override it, and just let it return the type info. What harm could that possible cause?</p>\n\n<p>I don't mean to be so negative, but I am absolutely floored that someone would want to get rid of <code>ToString()</code>.</p>\n\n<p><strong>Some additional points:</strong></p>\n\n<ol>\n<li><p>Why do the programmers using this class assume that <code>ToString()</code> will return an ID? Are other classes in your ecosystem doing this? One can argue that <code>ToString()</code> should return some meaningful data. But you really shouldn't be programming against the results of a <code>ToString()</code> call. <code>ToString()</code> is for a string representations of the class, period. This sounds like an education or communication issue between programmers or departments.</p></li>\n<li><p>Crippling <code>ToString()</code> in any way, whether you can figure out how to at compile time or by throwing an exception at run time, will have ripples. I have <em>never</em> seen this done, and would not expect any class I am using to exhibit this behavior. I think most programmers would have the same expectations. Will future programmers that use your class expect this? What bugs and maintenance nightmares are you causing down the road?</p></li>\n<li><p>What impact does this have in the IDE or debugger, which rely on <code>ToString()</code>?</p></li>\n<li><p>What impact will this have when using databinding technologies that don't bind against a specific type, but use reflection at run-time to pull out values? Most databinding will fall back to calling <code>ToString()</code> on an object if a member is not specified to use.</p></li>\n</ol>\n"
},
{
"answer_id": 218910,
"author": "PhilGriffin",
"author_id": 29294,
"author_profile": "https://Stackoverflow.com/users/29294",
"pm_score": 1,
"selected": false,
"text": "<p>Override ToString to return string.Empty, then you wouldn't have anything appended to the query string. By default if you don't override ToString you'll get Object's version which returns this.GetType() which will give you something like the namespace and class name.</p>\n\n<p>Calling ToString seems a pretty reasonable thing to do, I wouldn't want to raise complier errors for someone doing that.</p>\n"
},
{
"answer_id": 218997,
"author": "mockobject",
"author_id": 29649,
"author_profile": "https://Stackoverflow.com/users/29649",
"pm_score": 3,
"selected": false,
"text": "<p>I completely disagree with using the Obsolete property for this for a few reasons. </p>\n\n<p>To start with you will now have a warning for the ToString() method that you overrode and tagged with the Obsolete property:</p>\n\n<pre><code> [Obsolete(\"dont' use\", true)]\n public override string ToString()\n {\n throw new Exception(\"don't use\");\n }\n</code></pre>\n\n<p>yields this warning:\nWarning 1 Obsolete member 'ClassLibrary1.Foo.ToString()' overrides non-obsolete member 'object.ToString()' d:\\source\\ClassLibrary1\\ClassLibrary1\\Class1.cs 11 32 ClassLibrary1</p>\n\n<p>so now you are stuck with a permanent warning in your code. On top of this, it doesn't exactly solve your issue. What happens when something in the framework implicitly calls ToString() now? The result of the following code is that the code in the body of ToString() is still called:</p>\n\n<pre><code> Foo myObj = new Foo();\n\n Console.WriteLine(myObj);\n</code></pre>\n\n<p>So now you have a warning in your code, and it doesn't actually prevent a developer from doing the same thing all over again. I think the right move here is to try to find a way to throw an appropriate exception at run time rather than trying to mess with the .net object contracts.</p>\n\n<p>Suggestion for catching problem at compile time:\nI realized I had not previously given a suggestion for a solution for this issue. I don't really know what format your id is in for sure so I am only making a guess at it being an int, but why not protect whatever is creating the url with the querystring and pass the id as an int. That way a developer can't accidentally pass in some meaningless string without a compilation error. Like this for instance:</p>\n\n<pre><code>public string CreateItemUrl(int itemId)\n{\n return string.Format(\"someurl.aspx?id={0}\", itemId);\n}\n</code></pre>\n\n<p>Now, calling this:</p>\n\n<pre><code>CreateItemUrl(myObj.Id);\n</code></pre>\n\n<p>becomes much more strongly typed and less error prone than:</p>\n\n<pre><code>string theUrl = string.Format(\"someurl.aspx?id={0}\", myObj);\n</code></pre>\n"
},
{
"answer_id": 219026,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Please, consider your design/opinion to be changed :)</p>\n\n<p>First of all, definition of Foo.ToString does not define an override for Object.ToString() but a new one and should be prefixed with \"new\" keyword to prevent misunderstanding of semantics. Or explicitly declare an \"override\". IMHO, compiler issues corresponding warning.</p>\n\n<p>Even if you'll find a way to prohibit a call to Foo.ToString, it will be prohibited at compile time only when type of \"this\" is known to be Foo or descendant, but ((object) foo).ToString() will be a <em>correct</em> workaround, because ToString is a method of Object interface.</p>\n\n<p>Also, preventing a call of ToString is undesirable since Debugger uses it to present a value. \nSY, Jake</p>\n"
},
{
"answer_id": 219825,
"author": "MichaelGG",
"author_id": 27012,
"author_profile": "https://Stackoverflow.com/users/27012",
"pm_score": 3,
"selected": false,
"text": "<p>I'd take a hybrid approach. (Hey, isn't SO about combing other answers? :))</p>\n\n<p>First, create a new ToString that returns void. No return value means they can't use it to get any accidentally nice code:</p>\n\n<pre><code>public new void ToString() { }\n</code></pre>\n\n<p>Next, add the Obsolete attribute so when people DO call it, they get a warning telling them ToString is bad.</p>\n\n<p>You won't need to override ToString this way, simply hide it with something that's useless. The fact it has no return will break all code, hence causing a compiler error on top of the obsolete message.</p>\n\n<p>People casting to Object are not your concern, if I understand your question directly. You don't want to prevent people from calling ToString and getting type info, you want to prevent them from accidentally thinking ToString provides a useful result. </p>\n\n<p>Edit: Please don't throw an exception or override ToString. That would cause \"bad things\" when your object is treated as an object. Just using \"new\" allows the benefits you asked for, without screwing up other frameworks.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a class that contains a bunch of properties. It is a mistake by a programmer if they call ToString() on an object of that type. Take this example code:
```
using System;
public class Foo
{
public int ID = 123;
public string Name = "SomeName";
private string ToString() { return null; }
}
public class MyClass
{
public static void Main()
{
Foo myObj = new Foo();
WL("I want this to be a compiler error: {0}", myObj.ToString());
RL();
}
#region Helper methods
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
#endregion
}
```
You could reason that if ID is what most people want written out as a string, then I should implement ToString so that it returns the ID. However, I believe that is a bad practice because programmers will "accidentally" get working code. A programmer using my class should specify what they want.
Instead, what I would like is if someone calls myObj.ToString() to have that show up as a compile time error. I thought I could do that by creating a private ToString() function, but that doesn't work.
The reason I brought this up is that we ended up with a query string that contained the fully qualified class name rather then an ID.
So the question is: **Is there any way to "hide" the ToString() function so that calling it on an object of my class causes a compiler error?**
|
**I cannot stress enough how bad an idea this design is.**
`ToString()` is part of the object contract in .Net. If you don't want to implement it then don't override it, and just let it return the type info. What harm could that possible cause?
I don't mean to be so negative, but I am absolutely floored that someone would want to get rid of `ToString()`.
**Some additional points:**
1. Why do the programmers using this class assume that `ToString()` will return an ID? Are other classes in your ecosystem doing this? One can argue that `ToString()` should return some meaningful data. But you really shouldn't be programming against the results of a `ToString()` call. `ToString()` is for a string representations of the class, period. This sounds like an education or communication issue between programmers or departments.
2. Crippling `ToString()` in any way, whether you can figure out how to at compile time or by throwing an exception at run time, will have ripples. I have *never* seen this done, and would not expect any class I am using to exhibit this behavior. I think most programmers would have the same expectations. Will future programmers that use your class expect this? What bugs and maintenance nightmares are you causing down the road?
3. What impact does this have in the IDE or debugger, which rely on `ToString()`?
4. What impact will this have when using databinding technologies that don't bind against a specific type, but use reflection at run-time to pull out values? Most databinding will fall back to calling `ToString()` on an object if a member is not specified to use.
|
218,866 |
<p>I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:</p>
<pre><code>Org1 Emp1 Name, Emp1 Phone, Emp1 Address
Emp2 Name, Emp2 Phone, Emp2 Address
Org2 Emp1 Name, Emp1 Phone, Emp1 Address
Emp2 Name, Emp2 Phone, Emp2 Address
</code></pre>
<p>How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?</p>
<p>Many Thanks.</p>
|
[
{
"answer_id": 218900,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 3,
"selected": true,
"text": "<p>Classic.</p>\n\n<p>Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).</p>\n\n<pre><code>$currentOrg = '';\nwhile ($row = mysql_fetch_object($query)) {\n if ($row->org != $currentOrg) {\n echo \"$row->org\".\n }\n $currentorg = $row->org;\n}\n</code></pre>\n\n<p>Not the most beautiful but so simple.</p>\n"
},
{
"answer_id": 218918,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Get the data\n$data = mysql_query('SELECT org, emp_name, emp_phone, emp_address FROM x');\n\n// Store it all in a 2D array, keyed by org\n$rows = array();\nwhile ($row = mysql_fetch_assoc($data))\n{\n // Initialise each org to an empty array (not really needed in PHP but I prefer it)\n if (empty($rows[$row['org']]))\n $rows[$row['org']] = array();\n\n $rows[$row['org']][] = $row;\n}\n\n// Print it out\nforeach ($rows as $org => $employees)\n{\n print('<tr><td rowspan=\"' . count($employees) . '\">' . htmlentities($org) . '</td>');\n\n foreach ($employees as $i => $employee)\n {\n // If $i == 0, we've already printed the <tr> before the loop\n if ($i)\n print('<tr>');\n\n print('<td>......</td></tr>');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 218922,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>To make a correct <code>rowspan</code>, you need to know the number in advance.</p>\n\n<p>That leaves you with:</p>\n\n<ul>\n<li>iterating the query result twice, counting the values until they change</li>\n<li>asking the DB server for the count</li>\n</ul>\n\n<p>Personally, I would go with method number two. DB servers are quite efficient with counting rows, this will probably be a lot faster when there are many rows to display.</p>\n"
},
{
"answer_id": 218924,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>It could be easier (but less efficient) to make a query for each organisation (plus one query to find how many organisations there are presumably).</p>\n\n<p>A better way to do it would be to loop through the array beforehand. For example:</p>\n\n<pre><code>$sql = $mysqli->query('SELECT * FROM `organisation_members` ORDER BY `organisation` DESC');\n\nif (!$sql || $sql->num_rows) {\n // No data\n} else {\n $data = array();\n while ($row = $sql->fetch_assoc()) {}\n if (!array_key_exists($row['organisation'], $data)) {\n $data[$row['organisation']] = array();\n }\n $data[$row['organisation']][]['name'] = $row['name'];\n // ...\n }\n $sql->close();\n echo '<table>';\n foreach ($data as $org => $people) {\n $people_in_org = count($data[$org]) - 1;\n $counter = 0;\n\n echo '<tr>';\n echo '<td rowspan=\"' . $people_in_org + 1 . '\">' . $org . '</td>';\n\n while ($counter < $people_in_org) {\n if (counter > 0) {\n echo '<tr>';\n }\n echo '<td>' . $people[$counter]['name'] . '</td>';\n // etc\n echo '</tr>';\n }\n }\n echo '</table>';\n}\n</code></pre>\n"
},
{
"answer_id": 218933,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "<p>To conserve memory you could iterate over the resultset while org is the same buffering the rows, when org changes, print the current batch and start buffering the next batch.</p>\n"
},
{
"answer_id": 219031,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 0,
"selected": false,
"text": "<p>It won't help you with the rowspan, but look into the <a href=\"http://dev.mysql.com/doc/refman/4.1/en/group-by-modifiers.html\" rel=\"nofollow noreferrer\"><code>WITH ROLLUP</code></a> modifier. It returns the data in a format similiar to what you want.</p>\n"
},
{
"answer_id": 966010,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>What about using pear's HTML_Table package like in the following example, through i also like Jrgns's ROLLUP version</p>\n\n<pre><code> <?php\n\n require_once \"HTML/Table.php\";\n\n\n\n\n $table = new HTML_Table(array('border'=>'1'));\n $bo=array(\n array('6','a2','a3','a4'),\n array('1','b2','b3','b4'),\n array('1','c2','c3','c4') ,\n array('2','c2','c3','c4') ,\n array('2','c2','c3','c4') ,\n array('4','c2','c3','c4') );\n\n foreach ($bo as $r => $borow)\n $table->addRow($borow);\n\n $rsFirst=0;\n $rsLen=0; \n foreach ($bo as $r => $borow) {\n if ($r!=0 and $borow[0]!=$prevrow[0] ) {\n //jump in values\n $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));\n $rsFirst=$r;\n $rsLen=0;\n }\n $prevrow=$borow;\n $rsLen++; \n if ($r==sizeof($bo) - 1) {\n $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));\n }\n }\n\n\n echo $table->toHTML();\n\n ?>\n</code></pre>\n\n<p>servas, boerl</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29656/"
] |
I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:
```
Org1 Emp1 Name, Emp1 Phone, Emp1 Address
Emp2 Name, Emp2 Phone, Emp2 Address
Org2 Emp1 Name, Emp1 Phone, Emp1 Address
Emp2 Name, Emp2 Phone, Emp2 Address
```
How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?
Many Thanks.
|
Classic.
Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).
```
$currentOrg = '';
while ($row = mysql_fetch_object($query)) {
if ($row->org != $currentOrg) {
echo "$row->org".
}
$currentorg = $row->org;
}
```
Not the most beautiful but so simple.
|
218,888 |
<p>I have 3 classes that are essentially the same but don't implement an interface because they all come from different web services. </p>
<p>e.g.</p>
<ul>
<li>Service1.Object1</li>
<li>Service2.Object1</li>
<li>Service3.Object1</li>
</ul>
<p>They all have the same properties and I am writing some code to map them to each other using an intermediary object which implements my own interface IObject1</p>
<p>I've done this using generics</p>
<pre><code>public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new()
{
//Check the type is allowed
CheckObject1Types("CreateObject1<T>(IObject1[])", typeof(T));
return CreateObjectArray<T>(properties);
}
private static void CheckObject1Types(string method, Type type)
{
if (type == typeof(Service1.Object1)
|| type == typeof(Service2.Object1)
|| type == typeof(Service3.Object1)
|| type == typeof(Service1.Object1[])
|| type == typeof(Service2.Object1[])
|| type == typeof(Service3.Object1[]))
{
return;
}
throw new ArgumentException("Incorrect type passed to ServiceObjectFactory::" + method + ". Type:" + type.ToString());
}
</code></pre>
<p>My client code looks like:</p>
<pre><code>//properties is an array of my intermediary objects
Object1[] props = ServiceObjectFactory.CreateObject1<Object1>(properties);
</code></pre>
<p>What I want to do is get rid of the CheckObject1Types method and use constraints instead so that I get a build error if the types aren't valid, because at the moment I can call this method with any type and the ArgumentException is thrown by the CheckObject1Types method.</p>
<p>So I'd like to do something like:</p>
<pre><code>public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1
{
return CreateObjectArray<T>(properties);
}
</code></pre>
<p>Any ideas?</p>
<p><strong>Edit:</strong> I don't want to change the Reference.cs files for each webservice because all it takes is a team mate to update the web reference and BAM! broken code.</p>
|
[
{
"answer_id": 218930,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>Constraining to a list of classes in an \"OR\" fashion like you want to do isn't possible in C#. (In fact, I'm not even sure it's legal directly in IL either.)</p>\n\n<p>Your only option is to keep using the checktypes style functions. If you own the code for the different webservices, you can also implement a \"sentinel\" interface and use that as your constraint. I know sentinel interfaces are not recommended practice per the Framework Design Guidelines, but they occasionaly have their uses (this being one of them).</p>\n\n<p>As Jon points out, you may be able to make use of prtial classes in order to implement a common interface. If your References.cs implements a class:</p>\n\n<pre><code>namespace TestServices\n{\n internal partial class Service1SoapClient : System.ServiceModel.ClientBase<T>, K\n {\n }\n}\n</code></pre>\n\n<p>You would then create another partial class in the same namespace (call it References.CommonInterface.cs), which can live anywhere in your project, with the following:</p>\n\n<pre><code>namespace TestServices\n{\n internal interface ICommon\n {\n }\n\n internal partial class Service1SoapClient : ICommonInterface\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 218938,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>If you're pulling these objects from a web service you ulitmately do have control over the class definitions used. They don't just spring up out of thin air (even if you do have code generator or visual studio creating them initially). There's still a class file for each of them somewhere that must be compiled with the app, and you should be able to add your common interface to those class definitions.</p>\n"
},
{
"answer_id": 219001,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>Assuming the generated classes are partial, you can create an interface and then add another partial source file to make your generated classes implement the interface. Then you can constrain by interface as normal. No changes to the actual generated code required :)</p>\n"
},
{
"answer_id": 219810,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 0,
"selected": false,
"text": "<p>I would write a converter class that took either of your three objects into a new object that supports the interface you want. Furthermore, I would use reflection so you don't have to type all the assignments manually (unless it's a small object and is not expected to change too much). </p>\n\n<p>Using Reflection would also give you the guarantee that you want to make sure the objects implement whatever properties your new Interfaced object implements, otherwise when a property you expect is not implemented you could have it throw an error.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] |
I have 3 classes that are essentially the same but don't implement an interface because they all come from different web services.
e.g.
* Service1.Object1
* Service2.Object1
* Service3.Object1
They all have the same properties and I am writing some code to map them to each other using an intermediary object which implements my own interface IObject1
I've done this using generics
```
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new()
{
//Check the type is allowed
CheckObject1Types("CreateObject1<T>(IObject1[])", typeof(T));
return CreateObjectArray<T>(properties);
}
private static void CheckObject1Types(string method, Type type)
{
if (type == typeof(Service1.Object1)
|| type == typeof(Service2.Object1)
|| type == typeof(Service3.Object1)
|| type == typeof(Service1.Object1[])
|| type == typeof(Service2.Object1[])
|| type == typeof(Service3.Object1[]))
{
return;
}
throw new ArgumentException("Incorrect type passed to ServiceObjectFactory::" + method + ". Type:" + type.ToString());
}
```
My client code looks like:
```
//properties is an array of my intermediary objects
Object1[] props = ServiceObjectFactory.CreateObject1<Object1>(properties);
```
What I want to do is get rid of the CheckObject1Types method and use constraints instead so that I get a build error if the types aren't valid, because at the moment I can call this method with any type and the ArgumentException is thrown by the CheckObject1Types method.
So I'd like to do something like:
```
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1
{
return CreateObjectArray<T>(properties);
}
```
Any ideas?
**Edit:** I don't want to change the Reference.cs files for each webservice because all it takes is a team mate to update the web reference and BAM! broken code.
|
Assuming the generated classes are partial, you can create an interface and then add another partial source file to make your generated classes implement the interface. Then you can constrain by interface as normal. No changes to the actual generated code required :)
|
218,904 |
<p>I am using TortoiseSVN for my Subversion repository held on a USB drive. When I move from one PC to another, is there a way to automatically identify that files are out of date (without using the Check for Modifications menu). It would be nice just to be able to see that the folder on my hard drive did not match that of the repository, rather than seeing the green tick.</p>
|
[
{
"answer_id": 218913,
"author": "Veynom",
"author_id": 11670,
"author_profile": "https://Stackoverflow.com/users/11670",
"pm_score": 1,
"selected": false,
"text": "<p>Create a batch file which automatically update your local working copy when the USB key is connected.</p>\n"
},
{
"answer_id": 219033,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 3,
"selected": true,
"text": "<p>Try creating a file called <a href=\"http://dailycupoftech.com/usb-drive-autoruninf-tweaking/\" rel=\"nofollow noreferrer\">\"autorun.inf\"</a> in the root directory of your USB key. Then fill it with the following lines:</p>\n\n<pre><code>[autorun]\nopen=CheckForMods.bat\n</code></pre>\n\n<p>Then create a <code>CheckForMods.bat</code> batch file in the root directory that does an <code>svn status -u</code>.</p>\n"
},
{
"answer_id": 2293319,
"author": "Tom J Nowell",
"author_id": 57482,
"author_profile": "https://Stackoverflow.com/users/57482",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/commitmonitor/\" rel=\"nofollow noreferrer\">http://code.google.com/p/commitmonitor/</a></p>\n\n<p>Commit Monitor, it has a portable version you can stick on your USB drive</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21862/"
] |
I am using TortoiseSVN for my Subversion repository held on a USB drive. When I move from one PC to another, is there a way to automatically identify that files are out of date (without using the Check for Modifications menu). It would be nice just to be able to see that the folder on my hard drive did not match that of the repository, rather than seeing the green tick.
|
Try creating a file called ["autorun.inf"](http://dailycupoftech.com/usb-drive-autoruninf-tweaking/) in the root directory of your USB key. Then fill it with the following lines:
```
[autorun]
open=CheckForMods.bat
```
Then create a `CheckForMods.bat` batch file in the root directory that does an `svn status -u`.
|
218,908 |
<p>Is there a best way to turn an integer into its month name in .net?</p>
<p>Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.</p>
|
[
{
"answer_id": 218927,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": false,
"text": "<p>Why not just use <code>somedatetime.ToString(\"MMMM\")</code>?</p>\n"
},
{
"answer_id": 218947,
"author": "Tokabi",
"author_id": 315,
"author_profile": "https://Stackoverflow.com/users/315",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a static method from the <code>Microsoft.VisualBasic</code> namespace:</p>\n\n<pre><code>string monthName = Microsoft.VisualBasic.DateAndTime.MonthName(monthInt, false);\n</code></pre>\n"
},
{
"answer_id": 218948,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 4,
"selected": false,
"text": "<p>Updated with the correct namespace and object:</p>\n\n<pre><code>//This was wrong\n//CultureInfo.DateTimeFormat.MonthNames[index];\n\n//Correct but keep in mind CurrentInfo could be null\nDateTimeFormatInfo.CurrentInfo.MonthNames[index];\n</code></pre>\n"
},
{
"answer_id": 218957,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 9,
"selected": true,
"text": "<p>Try GetMonthName from DateTimeFormatInfo</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx</a></p>\n\n<p>You can do it by:</p>\n\n<pre><code>CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);\n</code></pre>\n"
},
{
"answer_id": 1442023,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>To get abbreviated month value, you can use <code>Enum.Parse();</code></p>\n\n<pre><code>Enum.Parse(typeof(Month), \"0\");\n</code></pre>\n\n<p>This will produce \"Jan\" as result.</p>\n\n<p>Remember this is zero-based index.</p>\n"
},
{
"answer_id": 12257805,
"author": "user1534576",
"author_id": 1534576,
"author_profile": "https://Stackoverflow.com/users/1534576",
"pm_score": 3,
"selected": false,
"text": "<pre><code>DateTime dt = new DateTime(year, month, day);\nResponse.Write(day + \"-\" + dt.ToString(\"MMMM\") + \"-\" + year);\n</code></pre>\n\n<p>In this way, your month will be displayed by their name, not by integer.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] |
Is there a best way to turn an integer into its month name in .net?
Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.
|
Try GetMonthName from DateTimeFormatInfo
<http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx>
You can do it by:
```
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);
```
|
218,909 |
<p><strong>EDIT:</strong> See <a href="https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252">my working code</a> in the answers below.</p>
<hr>
<p><strong>In brief:</strong> I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: <em>File does not begin with '%PDF-'</em>.</p>
<p><strong>In detail:</strong> So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: <em>File does not begin with '%PDF-'</em>. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?</p>
<p>To create the PDF, I'm using <a href="http://xmlgraphics.apache.org/fop" rel="nofollow noreferrer">Apache FOP</a>. I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html#basics" rel="nofollow noreferrer">basic usage pattern</a> and <a href="http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup" rel="nofollow noreferrer">this example code</a>.</p>
<p>Here's my JSP file:</p>
<pre><code><%@ taglib uri="utilTLD" prefix="util" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%-- Construct and initialise the PrintReportsBean --%>
<jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" />
<jsp:setProperty name="printReportsBean" property="*"/>
<c:set scope="page" var="xml" value="${printReportsBean.download}"/>
</code></pre>
<p>Here's my Java Bean method:</p>
<pre><code>//earlier in the class...
private static FopFactory fopFactory = FopFactory.newInstance();
public File getDownload() throws UtilException {
OutputStream out = null;
File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf");
File fo = new File("C:\\somedirectory", "HelloWorld.fo");
try {
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
out = new FileOutputStream(pdf);
out = new BufferedOutputStream(out);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); //identity transformer
Source src = new StreamSource(fo);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return pdf;
} catch (Exception e) {
throw new UtilException("Could not get download. Msg = "+e.getMessage());
} finally {
try {
out.close();
} catch (IOException io) {
throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage());
}
}
}
</code></pre>
<p>I realise that this is a very specific problem, but any help would be much appreciated!</p>
|
[
{
"answer_id": 218942,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 2,
"selected": false,
"text": "<p>Just a guess, but have you checked the MIME type that your JSP page is returning?</p>\n\n<p>edit: if I actually read the code you posted I would see you did set it, so nevermind :)</p>\n\n<p>edit2: Aren't the newlines between JSP tags in your JSP code going to end up in the output stream? Could that throw off the response returned by the server? I don't know anything about the format of a PDF, but does it depend on certain \"marker\" characters being in certain locations in the file? (The error message returned sounds like it does).</p>\n"
},
{
"answer_id": 218962,
"author": "Knobloch",
"author_id": 2878,
"author_profile": "https://Stackoverflow.com/users/2878",
"pm_score": 3,
"selected": true,
"text": "<p>The way I have implemented this type of feature in the past is to make a servlet write the contents of the PDF file out to the response as a stream. I don't have the source code with me any longer (and it's been at least a year since I did any servlet/jsp work), but here is what you might want to try:</p>\n\n<p>In a servlet, get a handle on the response's output stream. Change the mime type of the response to \"application/pdf\", and have the servlet do the file handling you have in your example. Only, instead of returning the File object, have the servlet write the file to the output stream. See examples of file i/o and just replace any outfile.write(...) lines with responseStream.write(...) and you should be set to go. Once you flush and close the output stream, and do the return, if I remember correctly, the browser should be able to pick up the pdf from the response.</p>\n"
},
{
"answer_id": 219102,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with <a href=\"https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#218942\">matt b</a>, maybe its the spaces between JSP tags. Try putting the directive</p>\n\n<pre><code><%@ page trimDirectiveWhitespaces=\"true\" %>\n</code></pre>\n"
},
{
"answer_id": 221252,
"author": "Philip Morton",
"author_id": 21709,
"author_profile": "https://Stackoverflow.com/users/21709",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, I got this working. Here's how I did it:</p>\n\n<p>JSP:</p>\n\n<pre><code><%@ taglib uri=\"utilTLD\" prefix=\"util\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/xml\" prefix=\"x\" %>\n<%@ page language=\"java\" session=\"false\" %>\n<%@ page contentType=\"application/pdf\" %>\n\n<%-- Construct and initialise the PrintReportsBean --%>\n<jsp:useBean id=\"printReportsBean\" scope=\"request\" class=\"some.package.PrintReportsBean\" />\n<jsp:setProperty name=\"printReportsBean\" property=\"*\"/>\n\n<%\n // get report format as input parameter \n ServletOutputStream servletOutputStream = response.getOutputStream();\n\n // reset buffer to remove any initial spaces\n response.resetBuffer(); \n\n response.setHeader(\"Content-disposition\", \"attachment; filename=HelloWorld.pdf\");\n\n // check that user is authorised to download product\n printReportsBean.getDownload(servletOutputStream);\n%>\n</code></pre>\n\n<p>Java Bean method:</p>\n\n<pre><code>//earlier in the class...\nprivate static FopFactory fopFactory = FopFactory.newInstance();\n\npublic void getDownload(ServletOutputStream servletOutputStream) throws UtilException {\n\n OutputStream outputStream = null;\n\n File fo = new File(\"C:\\\\some\\\\path\", \"HelloWorld.fo\");\n\n try {\n\n FOUserAgent foUserAgent = fopFactory.newFOUserAgent();\n\n outputStream = new BufferedOutputStream(servletOutputStream);\n\n Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, outputStream);\n\n TransformerFactory factory = TransformerFactory.newInstance();\n Transformer transformer = factory.newTransformer(); //identity transformer\n\n Source src = new StreamSource(fo);\n\n Result res = new SAXResult(fop.getDefaultHandler());\n\n transformer.transform(src, res);\n\n } catch (Exception e) {\n\n throw new UtilException(\"Could not get download. Msg = \"+e.getMessage());\n\n } finally {\n\n try {\n outputStream.close();\n } catch (IOException io) {\n throw new UtilException(\"Could not close OutputStream. Msg = \"+io.getMessage());\n }\n }\n }\n</code></pre>\n\n<p>Thanks to everyone for their input!</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
**EDIT:** See [my working code](https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252) in the answers below.
---
**In brief:** I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: *File does not begin with '%PDF-'*.
**In detail:** So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: *File does not begin with '%PDF-'*. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?
To create the PDF, I'm using [Apache FOP](http://xmlgraphics.apache.org/fop). I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their [basic usage pattern](http://xmlgraphics.apache.org/fop/0.95/embedding.html#basics) and [this example code](http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup).
Here's my JSP file:
```
<%@ taglib uri="utilTLD" prefix="util" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<%@ page language="java" session="false" %>
<%@ page contentType="application/pdf" %>
<%-- Construct and initialise the PrintReportsBean --%>
<jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" />
<jsp:setProperty name="printReportsBean" property="*"/>
<c:set scope="page" var="xml" value="${printReportsBean.download}"/>
```
Here's my Java Bean method:
```
//earlier in the class...
private static FopFactory fopFactory = FopFactory.newInstance();
public File getDownload() throws UtilException {
OutputStream out = null;
File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf");
File fo = new File("C:\\somedirectory", "HelloWorld.fo");
try {
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
out = new FileOutputStream(pdf);
out = new BufferedOutputStream(out);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); //identity transformer
Source src = new StreamSource(fo);
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return pdf;
} catch (Exception e) {
throw new UtilException("Could not get download. Msg = "+e.getMessage());
} finally {
try {
out.close();
} catch (IOException io) {
throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage());
}
}
}
```
I realise that this is a very specific problem, but any help would be much appreciated!
|
The way I have implemented this type of feature in the past is to make a servlet write the contents of the PDF file out to the response as a stream. I don't have the source code with me any longer (and it's been at least a year since I did any servlet/jsp work), but here is what you might want to try:
In a servlet, get a handle on the response's output stream. Change the mime type of the response to "application/pdf", and have the servlet do the file handling you have in your example. Only, instead of returning the File object, have the servlet write the file to the output stream. See examples of file i/o and just replace any outfile.write(...) lines with responseStream.write(...) and you should be set to go. Once you flush and close the output stream, and do the return, if I remember correctly, the browser should be able to pick up the pdf from the response.
|
218,912 |
<p>Is there a command like <code>cat</code> in linux which can return a specified quantity of characters from a file?</p>
<p>e.g., I have a text file like:</p>
<pre><code>Hello world
this is the second line
this is the third line
</code></pre>
<p>And I want something that would return the first 5 characters, which would be "hello".</p>
<p>thanks</p>
|
[
{
"answer_id": 218928,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://linux.die.net/man/1/head\" rel=\"noreferrer\">head</a>:</p>\n\n<h2>Name</h2>\n\n<p>head - output the first part of files</p>\n\n<h2>Synopsis</h2>\n\n<p><b>head</b> [<i>OPTION</i>]... [<i>FILE</i>]...</p>\n\n<h2>Description</h2>\n\n<p><p>Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when\nFILE is -, read standard input.\n<p>Mandatory arguments to long options are mandatory for short options too.\n<br/>\n<b>-c</b>, <b>--bytes</b>=<i>[-]N</i>\nprint the first N bytes of each file; with the leading '-', print all but the last N bytes of each file</p>\n"
},
{
"answer_id": 218939,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 2,
"selected": false,
"text": "<p>head or tail can do it as well:</p>\n\n<blockquote>\nhead -c X\n</blockquote>\n\n<p>Prints the first X bytes (not necessarily characters if it's a UTF-16 file) of the file. tail will do the same, except for the last X bytes.</p>\n\n<p>This (and cut) are portable.</p>\n"
},
{
"answer_id": 218940,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 9,
"selected": true,
"text": "<p><code>head</code> works too:</p>\n\n<pre><code>head -c 100 file # returns the first 100 bytes in the file\n</code></pre>\n\n<p>..will extract the first 100 bytes and return them. </p>\n\n<p>What's nice about using <code>head</code> for this is that the syntax for <code>tail</code> matches:</p>\n\n<pre><code>tail -c 100 file # returns the last 100 bytes in the file\n</code></pre>\n\n<p>You can combine these to get ranges of bytes. For example, to get the <em>second</em> 100 bytes from a file, read the first 200 with <code>head</code> and use tail to get the last 100:</p>\n\n<pre><code>head -c 200 file | tail -c 100\n</code></pre>\n"
},
{
"answer_id": 218944,
"author": "nkr1pt",
"author_id": 24046,
"author_profile": "https://Stackoverflow.com/users/24046",
"pm_score": 2,
"selected": false,
"text": "<p>you could also grep the line out and then cut it like for instance:</p>\n\n<p>grep 'text' filename | cut -c 1-5</p>\n"
},
{
"answer_id": 219188,
"author": "fcw",
"author_id": 14577,
"author_profile": "https://Stackoverflow.com/users/14577",
"pm_score": 6,
"selected": false,
"text": "<p>You can use dd to extract arbitrary chunks of bytes. </p>\n\n<p>For example,</p>\n\n<pre><code>dd skip=1234 count=5 bs=1\n</code></pre>\n\n<p>would copy bytes 1235 to 1239 from its input to its output, and discard the rest.</p>\n\n<p>To just get the first five bytes from standard input, do:</p>\n\n<pre><code>dd count=5 bs=1\n</code></pre>\n\n<p>Note that, if you want to specify the input file name, dd has old-fashioned argument parsing, so you would do:</p>\n\n<pre><code>dd count=5 bs=1 if=filename\n</code></pre>\n\n<p>Note also that dd verbosely announces what it did, so to toss that away, do:</p>\n\n<pre><code>dd count=5 bs=1 2>&-\n</code></pre>\n\n<p>or</p>\n\n<pre><code>dd count=5 bs=1 2>/dev/null\n</code></pre>\n"
},
{
"answer_id": 1083897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>head -Line_number file_name | tail -1 |cut -c Num_of_chars\n</code></pre>\n\n<p>this script gives the exact number of characters from the specific line and location, e.g.: </p>\n\n<pre><code>head -5 tst.txt | tail -1 |cut -c 5-8\n</code></pre>\n\n<p>gives the chars in line 5 and chars 5 to 8 of line 5, </p>\n\n<p><strong>Note</strong>: <code>tail -1</code> is used to select the last line displayed by the head.</p>\n"
},
{
"answer_id": 26524977,
"author": "bobbyus",
"author_id": 939627,
"author_profile": "https://Stackoverflow.com/users/939627",
"pm_score": 2,
"selected": false,
"text": "<p>I know the answer is in reply to a question asked 6 years ago ...</p>\n\n<p>But I was looking for something similar for a few hours and then found out that:\n<strong>cut -c</strong> does exactly that, with an added bonus that you could also specify an offset.</p>\n\n<p><strong>cut -c 1-5 </strong> will return <strong>Hello</strong> and <strong>cut -c 7-11 </strong> will return <strong>world</strong>. No need for any other command</p>\n"
},
{
"answer_id": 38144668,
"author": "rowanthorpe",
"author_id": 1964463,
"author_profile": "https://Stackoverflow.com/users/1964463",
"pm_score": 2,
"selected": false,
"text": "<p>Even though this was answered/accepted years ago, the presently accepted answer is only correct for one-byte-per-character encodings like iso-8859-1, or for the single-byte subsets of variable-byte character sets (like Latin characters within UTF-8). Even using multiple-byte splices instead would still only work for fixed-multibyte encodings like UTF-16. Given that now UTF-8 is well on its way to being a universal standard, and when looking at <a href=\"https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers#Nationalencyklopedin\" rel=\"nofollow noreferrer\">this list of languages by number of native speakers</a> and <a href=\"http://www.vistawide.com/languages/top_30_languages.htm\" rel=\"nofollow noreferrer\">this list of top 30 languages by native/secondary usage</a>, it is important to point out a simple variable-byte character-friendly (not byte-based) technique, using <code>cut -c</code> and <code>tr</code>/<code>sed</code> with character-classes.</p>\n\n<p>Compare the following which doubly fails due to two common Latin-centric mistakes/presumptions regarding the bytes vs. characters issue (one is <code>head</code> vs. <code>cut</code>, the other is <code>[a-z][A-Z]</code> vs. <code>[:upper:][:lower:]</code>):</p>\n\n<pre><code>$ printf 'Πού μπορώ να μάθω σανσκριτικά;\\n' | \\\n$ head -c 1 | \\\n$ sed -e 's/[A-Z]/[a-z]/g'\n[[unreadable binary mess, or nothing if the terminal filtered it]]\n</code></pre>\n\n<p>to this (note: this worked fine on FreeBSD, but both <code>cut</code> & <code>tr</code> on GNU/Linux still mangled Greek in UTF-8 for me though):</p>\n\n<pre><code>$ printf 'Πού μπορώ να μάθω σανσκριτικά;\\n' | \\\n$ cut -c 1 | \\\n$ tr '[:upper:]' '[:lower:]'\nπ\n</code></pre>\n\n<blockquote>\n <p>Another more recent answer had already proposed \"cut\", but only because of the side issue that it can be used to specify arbitrary offsets, not because of the directly relevant character vs. bytes issue.</p>\n</blockquote>\n\n<p>If your <code>cut</code> doesn't handle <code>-c</code> with variable-byte encodings correctly, for \"the first <code>X</code> characters\" (replace <code>X</code> with your number) you could try:</p>\n\n<ul>\n<li><code>sed -E -e '1 s/^(.{X}).*$/\\1/' -e q</code> - which is limited to the first line though</li>\n<li><code>head -n 1 | grep -E -o '^.{X}'</code> - which is limited to the first line and chains two commands though</li>\n<li><code>dd</code> - which has already been suggested in other answers, but is really cumbersome</li>\n<li>A complicated <code>sed</code> script with sliding window buffer to handle characters spread over multiple lines, but that is probably more cumbersome/fragile than just using something like <code>dd</code></li>\n</ul>\n\n<p>If your <code>tr</code> doesn't handle character-classes with variable-byte encodings correctly you could try:</p>\n\n<ul>\n<li><code>sed -E -e 's/[[:upper:]]/\\L&/g</code> (GNU-specific)</li>\n</ul>\n"
},
{
"answer_id": 46121408,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a simple script that wraps up using the <code>dd</code> approach mentioned here:</p>\n<h1>extract_chars.sh</h1>\n<pre><code>#!/usr/bin/env bash\n\nfunction show_help()\n{\n IT="\nextracts characters X to Y from stdin or FILE\nusage: X Y {FILE}\n\ne.g. \n\n2 10 /tmp/it => extract chars 2-10 from /tmp/it\nEOF\n "\n echo "$IT"\n exit\n}\n\nif [ "$1" == "help" ]\nthen\n show_help\nfi\nif [ -z "$1" ]\nthen\n show_help\nfi\n\nFROM=$1\nTO=$2\nCOUNT=`expr $TO - $FROM + 1`\n\nif [ -z "$3" ]\nthen\n dd skip=$FROM count=$COUNT bs=1 2>/dev/null\nelse\n dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null \nfi\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011/"
] |
Is there a command like `cat` in linux which can return a specified quantity of characters from a file?
e.g., I have a text file like:
```
Hello world
this is the second line
this is the third line
```
And I want something that would return the first 5 characters, which would be "hello".
thanks
|
`head` works too:
```
head -c 100 file # returns the first 100 bytes in the file
```
..will extract the first 100 bytes and return them.
What's nice about using `head` for this is that the syntax for `tail` matches:
```
tail -c 100 file # returns the last 100 bytes in the file
```
You can combine these to get ranges of bytes. For example, to get the *second* 100 bytes from a file, read the first 200 with `head` and use tail to get the last 100:
```
head -c 200 file | tail -c 100
```
|
218,935 |
<p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
|
[
{
"answer_id": 218943,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "<p>This is pretty much Python-independent! It's a classic example of Unix interprocess communication. One good option is to use <code>popen()</code> to open a pipe between the parent and child processes, and pass data/messages back and forth along the pipe.</p>\n\n<p>Take a look at the <a href=\"http://www.python.org/doc/2.5.2/lib/module-subprocess.html\" rel=\"nofollow noreferrer\"><code>subprocess</code> module</a>, which can set up the necessary pipes automatically while spawning child processes.</p>\n"
},
{
"answer_id": 218970,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 2,
"selected": false,
"text": "<p>You have two options: <code>os.popen*</code> in the <code>os</code> module, or you can use the <code>subprocess</code> module to the same effect. The Python manual has pretty documentation and examples for <a href=\"http://www.python.org/doc/2.5.2/lib/module-popen2.html\" rel=\"nofollow noreferrer\" title=\"popen\">popen</a> and <a href=\"http://www.python.org/doc/2.5.2/lib/module-subprocess.html\" rel=\"nofollow noreferrer\" title=\"subprocess\">subprocess</a>.</p>\n"
},
{
"answer_id": 219048,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://docs.python.org/library/subprocess\" rel=\"noreferrer\">Subprocess</a> replaces os.popen, os.system, os.spawn, popen2 and commands. A <a href=\"http://docs.python.org/library/subprocess#replacing-shell-pipe-line\" rel=\"noreferrer\">simple example for piping</a> would be:</p>\n\n<pre><code>p1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n</code></pre>\n\n<p>You could also use a <a href=\"http://docs.python.org/library/mmap.html\" rel=\"noreferrer\">memory mapped file</a> with the flag=MAP_SHARED for shared memory between processes.</p>\n\n<p><a href=\"http://docs.python.org/library/multiprocessing.html\" rel=\"noreferrer\">multiprocessing</a> abstracts both <a href=\"http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes\" rel=\"noreferrer\">pipes</a> and <a href=\"http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes\" rel=\"noreferrer\">shared memory</a> and provides a higher level interface. Taken from the Processing documentation:</p>\n\n<pre><code>from multiprocessing import Process, Pipe\n\ndef f(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=f, args=(child_conn,))\n p.start()\n print parent_conn.recv() # prints \"[42, None, 'hello']\"\n p.join()\n</code></pre>\n"
},
{
"answer_id": 219066,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://docs.python.org/dev/library/multiprocessing.html\" rel=\"noreferrer\">multiprocessing</a> module new in python 2.6 (also available for earlier versions a <a href=\"http://pyprocessing.berlios.de/\" rel=\"noreferrer\">pyprocessing</a></p>\n\n<p>Here's an example from the docs illustrating passing information using a pipe for instance:</p>\n\n<pre><code>from multiprocessing import Process, Pipe\n\ndef f(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=f, args=(child_conn,))\n p.start()\n print parent_conn.recv() # prints \"[42, None, 'hello']\"\n p.join()\n</code></pre>\n"
},
{
"answer_id": 50854805,
"author": "David Fraser",
"author_id": 120398,
"author_profile": "https://Stackoverflow.com/users/120398",
"pm_score": 1,
"selected": false,
"text": "<p>If you are doing low-level operating system forking and really want to avoid using pipes, it is possible to use shared memory-mapped files as well. This is not nearly as nice as using <code>subprocess</code> or <code>popen</code> pipes, but including the answer for completeness...</p>\n\n<p>There's a <a href=\"https://blog.schmichael.com/2011/05/15/sharing-python-data-between-processes-using-mmap/\" rel=\"nofollow noreferrer\">full example here</a>, but basically you can combine the <a href=\"https://docs.python.org/2/library/os.html\" rel=\"nofollow noreferrer\">os</a> file handling and <a href=\"https://docs.python.org/2/library/mmap.html\" rel=\"nofollow noreferrer\">mmap</a> modules:</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code>import mmap, os, tempfile\nfd, tmpfile = tempfile.mkstemp()\nos.write(fd, '\\x00' * mmap.PAGESIZE)\nos.lseek(fd, 0, os.SEEK_SET)\nchild_pid = os.fork()\nif child_pid:\n buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_READ)\n os.waitpid(child_pid, 0)\n child_message = buf.readline()\n print(child_message)\n os.close(fd)\nelse:\n buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)\n buf.write('testing\\n')\n os.close(fd)\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
|
[Subprocess](http://docs.python.org/library/subprocess) replaces os.popen, os.system, os.spawn, popen2 and commands. A [simple example for piping](http://docs.python.org/library/subprocess#replacing-shell-pipe-line) would be:
```
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
```
You could also use a [memory mapped file](http://docs.python.org/library/mmap.html) with the flag=MAP\_SHARED for shared memory between processes.
[multiprocessing](http://docs.python.org/library/multiprocessing.html) abstracts both [pipes](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes) and [shared memory](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) and provides a higher level interface. Taken from the Processing documentation:
```
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
```
|
218,969 |
<p>I have a problem perplexing me to no end. When I run the following query against an access database:</p>
<pre><code>SELECT *
FROM PreferredSpacer INNER JOIN SpacerThickness ON PreferredSpacer.SpacerTypeID = SpacerThickness.SpacerTypeID
ORDER BY PreferredSpacer.UnitTypeID DESC
</code></pre>
<p>(UnitTypeID field is a text type)</p>
<p>The results do not come out sorted as a normal person would expect. They are all over the place with respect to the UnitTypeID field (There are entries starting with 'W' between entries starting with 'C' and 'M'). If I remove the join and just try to order the records in the PreferredSpacer table (which contains the UnitTypeID field) I get my expected results, so I must assume the join has something to do with it.</p>
<p>At the same time however, I honestly can't imagine a tool as ubiquitus as access could have such a glaring issue with a fairly basic query. If I am doing something wrong -- however -- I am not able to see what it could be.</p>
<p>Any assistance would be greatly appreciated. Thanks.</p>
|
[
{
"answer_id": 218995,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 0,
"selected": false,
"text": "<p>Does SpacerThickness have a UnitTypeID column? If so, the \"*\" in the select may mean that it's sorting on PreferredSpacer.UnitTypeID, but selecting SpacerThickness.UnitTypeID. Try selecting PreferredSpacer.UnitTypeID directly.</p>\n"
},
{
"answer_id": 219002,
"author": "David Hay",
"author_id": 17784,
"author_profile": "https://Stackoverflow.com/users/17784",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately the UnitTypeID field only exists on the PreferredSpacer table.</p>\n"
},
{
"answer_id": 219059,
"author": "databyss",
"author_id": 9094,
"author_profile": "https://Stackoverflow.com/users/9094",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see anything that could be wrong with that query.</p>\n\n<p>Is is possible that the joined table size is larger than access is willing to handle?</p>\n"
},
{
"answer_id": 219061,
"author": "David Hay",
"author_id": 17784,
"author_profile": "https://Stackoverflow.com/users/17784",
"pm_score": 0,
"selected": false,
"text": "<p>I tried rewriting it as you said: [EDIT: this was a response to a post that has been deleted, but the content is still valid]</p>\n\n<pre><code>SELECT PreferredSpacer.UnitTypeID\nFROM PreferredSpacer, SpacerThickness\nWHERE PreferredSpacer.SpacerTypeID = SpacerThickness.SpacerTypeID\nORDER BY PreferredSpacer.UnitTypeID DESC\n</code></pre>\n\n<p>And I still get the same results. Here is a C&P of some of the results if that might help anyone.</p>\n\n<pre><code>CPATA\nCPATA\nCFRSA\nCFRSA\nCFRSA\nCFRSA\nCFRSA\nCFDOT\nCFDOT\nCFDOT\nCFDOT\nCFDOT\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOA\nCFDOA\nCFDOA\nCFDOA\nCFDOA\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIA\nCFDIA\nCFDIA\nCFDIA\nCFDIA\nCFDAT\nCFDAT\nCFDAT\nCFDAT\nCFDAT\nCBPATA\nCBPATA\nCBPATA\nCBPATA\nCBPATA\nCBFRSA\nCBFRSA\nCBFRSA\nCBFRSA\nCBFRSA\nCAPURE\nCAPURE\nCAPURE\nCAPURE\nCAPURE\nCADGU\nCADGU\nCADGU\nCADGU\nCADGU\nCADGS\nCADGS\nCADGS\nCADGS\nCADGS\nCOTR\nCOTR\nCOTR\nCOTR\n</code></pre>\n\n<p>As you can see, the results don't seem to follow any overall meaningful order.</p>\n"
},
{
"answer_id": 219075,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "<p>Is that COTR or CzeroTR? Otherwise it looks sorted descending as requested. YesNo?</p>\n"
},
{
"answer_id": 219080,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://support.jodohost.com/showpost.php?s=c5de8ca4a52b460e8c78b60c68f84f88&p=14985&postcount=3\" rel=\"nofollow noreferrer\">Google</a> says:</p>\n\n<blockquote>\n <p>You can not perform an ORDER BY on a text, ntext, or image field (those fields are actually pointers).</p>\n</blockquote>\n\n<p>Its about MSSQL, but i imagine it's the same for Access.</p>\n"
},
{
"answer_id": 219115,
"author": "David Hay",
"author_id": 17784,
"author_profile": "https://Stackoverflow.com/users/17784",
"pm_score": 0,
"selected": false,
"text": "<p>To Remou: It's on O and not a zero, but even if it was there are lots more entries all over the place int he full result set (I just pasted a part of it here to illustrate, the whole thing is about 1,000 rows).</p>\n\n<p>To dummy: Sql has the varchar type, which is what would be used in for this type of data there. Acccess however only has the text data type to cover both long and short strings. Also the order by does work If I am performing it only on the PreferredSpacer table (which is the one that contains the UnitTypeID field), it's only when I do the join that it falls apart.</p>\n"
},
{
"answer_id": 219186,
"author": "David Hay",
"author_id": 17784,
"author_profile": "https://Stackoverflow.com/users/17784",
"pm_score": 2,
"selected": false,
"text": "<p>I figured it out. The tool our customer was using to generate the access DB in question was incorrectly turning varchar fields in SQL to memo fields in access (instead of text, as our tools do), and the memo field does not sort correctly. It seems odd to me that Access will just silently go along with it however, and not try to indicate that a sort on memo will not work as expected, but such is life.</p>\n\n<p>Thanks for the responses everyone.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17784/"
] |
I have a problem perplexing me to no end. When I run the following query against an access database:
```
SELECT *
FROM PreferredSpacer INNER JOIN SpacerThickness ON PreferredSpacer.SpacerTypeID = SpacerThickness.SpacerTypeID
ORDER BY PreferredSpacer.UnitTypeID DESC
```
(UnitTypeID field is a text type)
The results do not come out sorted as a normal person would expect. They are all over the place with respect to the UnitTypeID field (There are entries starting with 'W' between entries starting with 'C' and 'M'). If I remove the join and just try to order the records in the PreferredSpacer table (which contains the UnitTypeID field) I get my expected results, so I must assume the join has something to do with it.
At the same time however, I honestly can't imagine a tool as ubiquitus as access could have such a glaring issue with a fairly basic query. If I am doing something wrong -- however -- I am not able to see what it could be.
Any assistance would be greatly appreciated. Thanks.
|
I figured it out. The tool our customer was using to generate the access DB in question was incorrectly turning varchar fields in SQL to memo fields in access (instead of text, as our tools do), and the memo field does not sort correctly. It seems odd to me that Access will just silently go along with it however, and not try to indicate that a sort on memo will not work as expected, but such is life.
Thanks for the responses everyone.
|
218,987 |
<p>I want to use Sharepoint with python (C-Python)</p>
<p>Has anyone tried this before ?</p>
|
[
{
"answer_id": 219175,
"author": "Rob Windsor",
"author_id": 28785,
"author_profile": "https://Stackoverflow.com/users/28785",
"pm_score": 2,
"selected": false,
"text": "<p>SharePoint exposes several web services which you can use to query and update data.</p>\n\n<p>I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.</p>\n\n<p>This article should give you enough information to get started.</p>\n\n<p><a href=\"http://www.developer.com/tech/article.php/3104621\" rel=\"nofollow noreferrer\">http://www.developer.com/tech/article.php/3104621</a></p>\n"
},
{
"answer_id": 219236,
"author": "enzondio",
"author_id": 21693,
"author_profile": "https://Stackoverflow.com/users/21693",
"pm_score": 2,
"selected": false,
"text": "<p>SOAP with Python is pretty easy. <a href=\"http://www.diveintopython.net/soap_web_services/index.html\" rel=\"nofollow noreferrer\">Here's a tutorial</a> from Dive Into Python.</p>\n"
},
{
"answer_id": 222242,
"author": "Blauohr",
"author_id": 22176,
"author_profile": "https://Stackoverflow.com/users/22176",
"pm_score": 3,
"selected": false,
"text": "<p>To get the wsdl :</p>\n\n<pre><code>import sys\n\n# we use suds -> https://fedorahosted.org/suds\nfrom suds import WebFault\nfrom suds.client import *\nimport urllib2\n\n# my 2 url conf\n# url_sharepoint,url_NTLM_authproxy \nimport myconfig as my \n\n# build url\nwsdl = '_vti_bin/SiteData.asmx?WSDL'\nurl = '/'.join([my.url_sharepoint,wsdl])\n\n\n# we need a NTLM_auth_Proxy -> http://ntlmaps.sourceforge.net/\n# follow instruction and get proxy running\nproxy_handler = urllib2.ProxyHandler({'http': my.url_NTLM_authproxy })\nopener = urllib2.build_opener(proxy_handler)\n\nclient = SoapClient(url, {'opener' : opener})\n\nprint client.wsdl\n</code></pre>\n\n<p>main (mean) problem:\nthe sharepoint-server uses a NTLM-Auth [ :-( ]\nso i had to use the NTLM-Auth-Proxy</p>\n\n<p>To Rob and Enzondio : THANKS for your hints !</p>\n"
},
{
"answer_id": 5403203,
"author": "somewhatoff",
"author_id": 672720,
"author_profile": "https://Stackoverflow.com/users/672720",
"pm_score": 4,
"selected": true,
"text": "<p>I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:</p>\n\n<pre><code>\nfrom suds import WebFault\nfrom suds.client import *\nfrom suds.transport.https import WindowsHttpAuthenticated\n\n\nuser = r'SERVER\\user'\npassword = \"yourpassword\"\nurl = \"http://sharepointserver/_vti_bin/SiteData.asmx?WSDL\"\n\n\nntlm = WindowsHttpAuthenticated(username = user, password = password)\nclient = Client(url, transport=ntlm)\n\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/218987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22176/"
] |
I want to use Sharepoint with python (C-Python)
Has anyone tried this before ?
|
I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:
```
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
user = r'SERVER\user'
password = "yourpassword"
url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
```
|
219,009 |
<p>If I view the HTML generated by one of my Jasper reports in IE7 I see the following: </p>
<pre><code><BR /><BR />
<A name="JR_PAGE_ANCHOR_0_1">
<TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0">
<-- table body omitted -->
</TABLE>
</code></pre>
<p>The two BR tags are added via the JRHtmlExporterParameter.HTML_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.</p>
<p>Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.</p>
<p>Thanks in advance,
Don</p>
|
[
{
"answer_id": 219119,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>That's odd code, the <code><br /></code> tags are XHTML-style, while the unclosed <code>a</code> tags are good old HTML, like the upper case tag names. If you serve such page with plain HTML header/content-type, perhaps IE will be happy.</p>\n\n<p>When you write that Firefox closes the tag, I suppose you mean it correctly doesn't extend the hyperlink span over block tags. Note that FF's view source can display closing tags that are not there when you save the page to disk!</p>\n\n<p>Frankly, I don't know if you can get rid of these anchors with some config. If nobody comes with a real solution, maybe you can download Jasper's source code and search JR_PAGE_ANCHOR in it, looking if the code generating it is conditionally driven.</p>\n\n<p>Or, if you can, you can apply post-processing of the generated code.</p>\n"
},
{
"answer_id": 219362,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "<p>I took Phil's advice and dove into the Jasper source code. I've fixed the problem and submitted it to the project. Details of the cause and resolution are available <a href=\"http://jasperforge.org/tracker/index.php?func=detail&aid=3180&group_id=102&atid=611&action=edit\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 72798989,
"author": "ebey",
"author_id": 8712753,
"author_profile": "https://Stackoverflow.com/users/8712753",
"pm_score": 0,
"selected": false,
"text": "<p>In excel export A1 cell transfor to JR_PAGE_ANCHOR_0_1.Some of tips are setting IS_ONE_PAGE_PER_SHEET property doing true, IS_DETECT_CELL_TYPE doing true but these are not working for me.\nTo avoid from this situation , configure your xlsx report configuration is worked for me (set ignore anchor is key point);</p>\n<pre><code> private final SimpleXlsxReportConfiguration xlsxReportConfiguration;\n JRAbstractExporter exporter;\n\n this.xlsxReportConfiguration = new SimpleXlsxReportConfiguration(); \n ...\n xlsxReportConfiguration.setIgnoreAnchors(true);\n ...\n\n exporter = new JRXlsxExporter();\n exporter.setConfiguration(xlsxReportConfiguration);\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
If I view the HTML generated by one of my Jasper reports in IE7 I see the following:
```
<BR /><BR />
<A name="JR_PAGE_ANCHOR_0_1">
<TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0">
<-- table body omitted -->
</TABLE>
```
The two BR tags are added via the JRHtmlExporterParameter.HTML\_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.
Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.
Thanks in advance,
Don
|
I took Phil's advice and dove into the Jasper source code. I've fixed the problem and submitted it to the project. Details of the cause and resolution are available [here](http://jasperforge.org/tracker/index.php?func=detail&aid=3180&group_id=102&atid=611&action=edit).
|
219,046 |
<p>I'm trying to construct a query that will include a column indicating whether or not a user has downloaded a document. I have a table called HasDownloaded with the following columns: id, documentID, memberID. Finding out whether a user has downloaded a <em>specific</em> document is easy; but I need to generate a query where the results will look like this:</p>
<pre><code>name id
----------------------
abc NULL
bbb 2
ccc 53
ddd NULL
eee 13
</code></pre>
<p>The ID isn't really important; what I'm interested in is whether the document has been downloaded (is it NULL or not).</p>
<p>Here is my query:</p>
<pre><code>SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
WHERE HasDownloaded.memberID = @memberID
</code></pre>
<p>The problem is, this will only return values if an entry exists for the specified user in the HasDownloaded table. I'd like to keep this simple and only have entries in HasDownloaded for documents that <em>have</em> been downloaded. So if user 1 has downloaded abc, bbb, and ccc, I still want ddd and eee to show up in the resulting table, just with the id as NULL. But the WHERE clause only gives me values for which entries exists.</p>
<p>I'm not much of a SQL expert - is there an operator that will give me what I want here? Should I be taking a different approach? Or is this impossible?</p>
|
[
{
"answer_id": 219053,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 6,
"selected": true,
"text": "<p>Move the condition in the WHERE clause to the join condition.</p>\n\n<pre><code>SELECT Documents.name, HasDownloaded.id FROM Documents\nLEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id \n AND HasDownloaded.memberID = @memberID \n</code></pre>\n\n<p>This is necessary whenever you want to refer to a left join-ed table in what would otherwise be the WHERE clause.</p>\n"
},
{
"answer_id": 219149,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "<pre><code>WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId\n</code></pre>\n\n<p>would be the normal way to do that. Some would shorten it to:</p>\n\n<pre><code>WHERE COALESCE(HasDownloaded.memberId, @memberId) = @memberId\n</code></pre>\n\n<p>You can, as Matt B. shows, do it in your JOIN condition - but I think that's much more likely to confuse folks. If you don't understand WHY moving it to the JOIN clause works, then I'd strongly suggest staying away from it.</p>\n"
},
{
"answer_id": 219286,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 2,
"selected": false,
"text": "<p>@Mark: I understand why the JOIN syntax works, but thanks for the warning. I do think your suggestion is more intuitive. I was curious to see which was more efficient. So I ran a quick test (this was rather simplistic, I'm afraid, over only 14 rows and 10 trials):</p>\n\n<p>In the JOIN condition:</p>\n\n<pre><code>AND HasDownloaded.memberID = @memberID\n</code></pre>\n\n<ul>\n<li>Client processing time: 4.6</li>\n<li>Total execution time: 35.5</li>\n<li>Wait time on server replies: 30.9</li>\n</ul>\n\n<p>In the WHERE clause:</p>\n\n<pre><code>WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId\n</code></pre>\n\n<ul>\n<li>Client processing time: 7.7 </li>\n<li>Total execution time: 27.7</li>\n<li>Wait time on server replies: 22.0</li>\n</ul>\n\n<p>It looks like the WHERE clause is ever-so-slightly more efficient. Interesting! Once again, thanks to both of you for your help.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4965/"
] |
I'm trying to construct a query that will include a column indicating whether or not a user has downloaded a document. I have a table called HasDownloaded with the following columns: id, documentID, memberID. Finding out whether a user has downloaded a *specific* document is easy; but I need to generate a query where the results will look like this:
```
name id
----------------------
abc NULL
bbb 2
ccc 53
ddd NULL
eee 13
```
The ID isn't really important; what I'm interested in is whether the document has been downloaded (is it NULL or not).
Here is my query:
```
SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
WHERE HasDownloaded.memberID = @memberID
```
The problem is, this will only return values if an entry exists for the specified user in the HasDownloaded table. I'd like to keep this simple and only have entries in HasDownloaded for documents that *have* been downloaded. So if user 1 has downloaded abc, bbb, and ccc, I still want ddd and eee to show up in the resulting table, just with the id as NULL. But the WHERE clause only gives me values for which entries exists.
I'm not much of a SQL expert - is there an operator that will give me what I want here? Should I be taking a different approach? Or is this impossible?
|
Move the condition in the WHERE clause to the join condition.
```
SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
AND HasDownloaded.memberID = @memberID
```
This is necessary whenever you want to refer to a left join-ed table in what would otherwise be the WHERE clause.
|
219,055 |
<p>I'm trying to get some code working that a previous developer has written.
Yep, he now left the company. :-(</p>
<p>I have a JSON RPC call being made from the JS code.
The JS all runs fine and the callback method gets an object back (not an error object).</p>
<p>But the method on the Java class never gets hit.
The smd method does get hit though.</p>
<hr>
<pre><code>public String smd()
{
return SUCCESS; // break point reaches here
}
@SMDMethod
public void updateRowValueForField(String key, String value, String fieldname)
{
// We never get into this method.
}
</code></pre>
<hr>
<pre><code><package name="EntryBarRPC" namespace="/" extends="star-default">
<action name="ebToggleSelection" class="eboggleSelectionAction" method="smd">
<interceptor-ref name="jsonStack">
<param name="enableSMD">true</param>
</interceptor-ref>
<result type="json">
<param name="enableSMD">true</param>
</result>
</action>
</package>
</code></pre>
<hr>
<p>I'm stumped as to why, or what I'm missing.
I've read <a href="http://cwiki.apache.org/S2PLUGINS/json-plugin.html" rel="nofollow noreferrer">JSON plugin page</a> over and over.</p>
<p>I think I just need another set of eyes.</p>
<p>Note: no errors in the Tomcat console, no JS errors.</p>
<p>Anyone got any clues?
Cheers
Jeff Porter</p>
|
[
{
"answer_id": 219095,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I'm guessing that you need to update the <code>smd()</code> method to actually call <code>updateRowValueForField()</code> rather than simply return immediately. Looks like the previous developer never actually hooked up the methods.</p>\n"
},
{
"answer_id": 219103,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 3,
"selected": true,
"text": "<p>You forgot to include the javascript code. From the example:</p>\n\n<pre><code><s:url id=\"smdUrl\" namespace=\"/nodecorate\" action=\"SMDAction\" />\n<script type=\"text/javascript\">\n //load dojo RPC\n dojo.require(\"dojo.rpc.*\");\n\n //create service object(proxy) using SMD (generated by the json result)\n var service = new dojo.rpc.JsonService(\"${smdUrl}\");\n\n //function called when remote method returns\n var callback = function(bean) {\n alert(\"Price for \" + bean.type + \" is \" + bean.price);\n };\n\n //parameter\n var bean = {type: \"Mocca\"};\n\n //execute remote method\n var defered = service.doSomething(bean, 5);\n\n //attach callback to defered object\n defered.addCallback(callback);\n</script>\n</code></pre>\n\n<p>Are you sure you call service.updateRowValueForField(key, value, fieldname) and not something different? </p>\n\n<p>Further, your method returns a void (e.g. doesn't return anything). What did you expect to get?</p>\n"
},
{
"answer_id": 225392,
"author": "jeff porter",
"author_id": 26778,
"author_profile": "https://Stackoverflow.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p>New version fixes my problems.</p>\n\n<p><a href=\"http://code.google.com/p/jsonplugin/\" rel=\"nofollow noreferrer\">Google JSON plugin</a></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26778/"
] |
I'm trying to get some code working that a previous developer has written.
Yep, he now left the company. :-(
I have a JSON RPC call being made from the JS code.
The JS all runs fine and the callback method gets an object back (not an error object).
But the method on the Java class never gets hit.
The smd method does get hit though.
---
```
public String smd()
{
return SUCCESS; // break point reaches here
}
@SMDMethod
public void updateRowValueForField(String key, String value, String fieldname)
{
// We never get into this method.
}
```
---
```
<package name="EntryBarRPC" namespace="/" extends="star-default">
<action name="ebToggleSelection" class="eboggleSelectionAction" method="smd">
<interceptor-ref name="jsonStack">
<param name="enableSMD">true</param>
</interceptor-ref>
<result type="json">
<param name="enableSMD">true</param>
</result>
</action>
</package>
```
---
I'm stumped as to why, or what I'm missing.
I've read [JSON plugin page](http://cwiki.apache.org/S2PLUGINS/json-plugin.html) over and over.
I think I just need another set of eyes.
Note: no errors in the Tomcat console, no JS errors.
Anyone got any clues?
Cheers
Jeff Porter
|
You forgot to include the javascript code. From the example:
```
<s:url id="smdUrl" namespace="/nodecorate" action="SMDAction" />
<script type="text/javascript">
//load dojo RPC
dojo.require("dojo.rpc.*");
//create service object(proxy) using SMD (generated by the json result)
var service = new dojo.rpc.JsonService("${smdUrl}");
//function called when remote method returns
var callback = function(bean) {
alert("Price for " + bean.type + " is " + bean.price);
};
//parameter
var bean = {type: "Mocca"};
//execute remote method
var defered = service.doSomething(bean, 5);
//attach callback to defered object
defered.addCallback(callback);
</script>
```
Are you sure you call service.updateRowValueForField(key, value, fieldname) and not something different?
Further, your method returns a void (e.g. doesn't return anything). What did you expect to get?
|
219,109 |
<p>Obviously I could create a <code>Calendar</code> object with the date and use <code>get(DAY)</code> on it, but knowing Groovy, I would guess there is an easier, quicker way I just don't know about?</p>
<p><strong>Answer</strong></p>
<pre><code>(date1..date2).size() == 1 // true if two dates are on same calendar day
</code></pre>
|
[
{
"answer_id": 219133,
"author": "Ruben",
"author_id": 26919,
"author_profile": "https://Stackoverflow.com/users/26919",
"pm_score": 4,
"selected": true,
"text": "<p>Quickly opened the Groovy In Action book and found the following sample that should help:</p>\n\n<pre><code>def today = new Date()\ndef yesterday = today-1\nassert (yesterday..today).size() == 2\n</code></pre>\n"
},
{
"answer_id": 35921172,
"author": "Eli Willaert",
"author_id": 6045722,
"author_profile": "https://Stackoverflow.com/users/6045722",
"pm_score": 1,
"selected": false,
"text": "<p>A bit shorter and more readable then the current top answer:</p>\n\n<pre><code>date1 - date2 == 0 //true if two dates are on same calendar day\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
Obviously I could create a `Calendar` object with the date and use `get(DAY)` on it, but knowing Groovy, I would guess there is an easier, quicker way I just don't know about?
**Answer**
```
(date1..date2).size() == 1 // true if two dates are on same calendar day
```
|
Quickly opened the Groovy In Action book and found the following sample that should help:
```
def today = new Date()
def yesterday = today-1
assert (yesterday..today).size() == 2
```
|
219,110 |
<p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost" rel="noreferrer">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="noreferrer">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/" rel="noreferrer">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy" rel="noreferrer">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
|
[
{
"answer_id": 219124,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 5,
"selected": false,
"text": "<p>You can <a href=\"http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side\" rel=\"noreferrer\">run WSGI over CGI as Pep333 demonstrates</a> as an example. However every time there is a request a new Python interpreter is started and the whole context (database connections, etc.) needs to be build which all take time.</p>\n\n<p>The best if you want to run WSGI would be if your host would install <a href=\"http://code.google.com/p/modwsgi/\" rel=\"noreferrer\">mod_wsgi</a> and made an appropriate configuration to defer control to an application of yours.</p>\n\n<p><a href=\"http://trac.saddi.com/flup\" rel=\"noreferrer\">Flup</a> is another way to run with WSGI for any webserver that can speak <a href=\"http://www.fastcgi.com/drupal/\" rel=\"noreferrer\">FCGI</a>, <a href=\"http://www.mems-exchange.org/software/scgi/\" rel=\"noreferrer\">SCGI</a> or AJP. From my experience only FCGI really works, and it can be used in Apache either via <a href=\"http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html\" rel=\"noreferrer\">mod_fastcgi</a> or if you can run a separate Python daemon with <a href=\"http://mproxyfcgi.sourceforge.net/\" rel=\"noreferrer\">mod_proxy_fcgi</a>.</p>\n\n<p><a href=\"http://wsgi.org\" rel=\"noreferrer\">WSGI</a> is a protocol much like CGI, which defines a set of rules how webserver and Python code can interact, it is defined as <a href=\"http://www.python.org/dev/peps/pep-0333\" rel=\"noreferrer\">Pep333</a>. It makes it possible that many different webservers can use many different frameworks and applications using the same application protocol. This is very beneficial and makes it so useful.</p>\n"
},
{
"answer_id": 505534,
"author": "James Brady",
"author_id": 29903,
"author_profile": "https://Stackoverflow.com/users/29903",
"pm_score": 6,
"selected": false,
"text": "<p>I think <a href=\"https://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together/219124#219124\">Florian's answer</a> answers the part of your question about \"what is WSGI\", especially if you read <a href=\"http://www.python.org/dev/peps/pep-0333\" rel=\"noreferrer\">the PEP</a>.</p>\n\n<p>As for the questions you pose towards the end:</p>\n\n<p>WSGI, CGI, FastCGI etc. are all protocols for a web server to <em>run code</em>, and deliver the dynamic content that is produced. Compare this to static web serving, where a plain HTML file is basically delivered as is to the client.</p>\n\n<p><strong>CGI, FastCGI and SCGI are language agnostic.</strong> You can write CGI scripts in Perl, Python, C, bash, whatever. CGI defines <em>which</em> executable will be called, based on the URL, and <em>how</em> it will be called: the arguments and environment. It also defines how the return value should be passed back to the web server once your executable is finished. The variations are basically optimisations to be able to handle more requests, reduce latency and so on; the basic concept is the same.</p>\n\n<p><strong>WSGI is Python only.</strong> Rather than a language agnostic protocol, a standard function signature is defined:</p>\n\n<pre><code>def simple_app(environ, start_response):\n \"\"\"Simplest possible application object\"\"\"\n status = '200 OK'\n response_headers = [('Content-type','text/plain')]\n start_response(status, response_headers)\n return ['Hello world!\\n']\n</code></pre>\n\n<p>That is a complete (if limited) WSGI application. A web server with WSGI support (such as Apache with mod_wsgi) can invoke this function whenever a request arrives.</p>\n\n<p>The reason this is so great is that we can avoid the messy step of converting from a HTTP GET/POST to CGI to Python, and back again on the way out. It's a much more direct, clean and efficient linkage.</p>\n\n<p>It also makes it much easier to have long-running frameworks running behind web servers, if all that needs to be done for a request is a function call. With plain CGI, you'd have to <a href=\"http://tools.cherrypy.org/wiki/RunAsCGI\" rel=\"noreferrer\">start your whole framework up</a> for each individual request.</p>\n\n<p>To have WSGI support, you'll need to have installed a WSGI module (like <a href=\"http://code.google.com/p/modwsgi/\" rel=\"noreferrer\">mod_wsgi</a>), or use a web server with WSGI baked in (like <a href=\"http://tools.cherrypy.org/\" rel=\"noreferrer\">CherryPy</a>). If neither of those are possible, you <em>could</em> use the CGI-WSGI bridge given in the PEP.</p>\n"
},
{
"answer_id": 518104,
"author": "aaron",
"author_id": 21211,
"author_profile": "https://Stackoverflow.com/users/21211",
"pm_score": 3,
"selected": false,
"text": "<p>It's a simple abstraction layer for Python, akin to what the Servlet spec is for Java. Whereas CGI is really low level and just dumps stuff into the process environment and standard in/out, the above two specs model the http request and response as constructs in the language. My impression however is that in Python folks have not quite settled on de-facto implementations so you have a mix of reference implementations, and other utility-type libraries that provide other things along with WSGI support (e.g. Paste). Of course I could be wrong, I'm a newcomer to Python. The \"web scripting\" community is coming at the problem from a different direction (shared hosting, CGI legacy, privilege separation concerns) than Java folks had the luxury of starting with (running a single enterprise container in a dedicated environment against statically compiled and deployed code).</p>\n"
},
{
"answer_id": 520194,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 9,
"selected": true,
"text": "<p><strong>How WSGI, CGI, and the frameworks are all connected?</strong></p>\n\n<p>Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. </p>\n\n<p>In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.</p>\n\n<p>CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.</p>\n\n<p>WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be.</p>\n\n<p>WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.</p>\n\n<p><strong>What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration?</strong></p>\n\n<p>Recall that forking a subprocess is expensive. There are two ways to work around this.</p>\n\n<ol>\n<li><p><strong>Embedded</strong> <code>mod_wsgi</code> or <code>mod_python</code> embeds Python inside Apache; no process is forked. Apache runs the Django application directly.</p></li>\n<li><p><strong>Daemon</strong> <code>mod_wsgi</code> or <code>mod_fastcgi</code> allows Apache to interact with a separate daemon (or \"long-running process\"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod_fastcgi to communicate with this process.</p></li>\n</ol>\n\n<p>Note that <code>mod_wsgi</code> can work in either mode: embedded or daemon.</p>\n\n<p>When you read up on mod_fastcgi, you'll see that Django uses <a href=\"http://pypi.python.org/pypi/flup/\" rel=\"noreferrer\">flup</a> to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this.</p>\n\n<pre><code>Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)\n</code></pre>\n\n<p>Django has several \"django.core.handlers\" for the various interfaces.</p>\n\n<p>For mod_fastcgi, Django provides a <code>manage.py runfcgi</code> that integrates FLUP and the handler.</p>\n\n<p>For mod_wsgi, there's a core handler for this.</p>\n\n<p><strong>How to install WSGI support?</strong></p>\n\n<p>Follow these instructions.</p>\n\n<p><a href=\"https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki\" rel=\"noreferrer\">https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki</a></p>\n\n<p>For background see this</p>\n\n<p><a href=\"http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index</a></p>\n"
},
{
"answer_id": 9932664,
"author": "Richard Boardman",
"author_id": 756617,
"author_profile": "https://Stackoverflow.com/users/756617",
"pm_score": 3,
"selected": false,
"text": "<p>If you are unclear on all the terms in this space, and lets face it, its a confusing acronym-laden one, there's also a good background reader in the form of an official python HOWTO which discusses CGI vs. FastCGI vs. WSGI and so on: <a href=\"http://docs.python.org/howto/webservers.html\">http://docs.python.org/howto/webservers.html</a></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
I have a [Bluehost](http://en.wikipedia.org/wiki/Bluehost) account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in `.htaccess`:
```
Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
```
Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining `.htaccess` commands).
How are [WSGI](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface), CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say [web.py](http://webpy.org/) or [CherryPy](http://en.wikipedia.org/wiki/CherryPy)) on my basic CGI configuration? How to install WSGI support?
|
**How WSGI, CGI, and the frameworks are all connected?**
Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file.
In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.
CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.
WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be.
WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.
**What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration?**
Recall that forking a subprocess is expensive. There are two ways to work around this.
1. **Embedded** `mod_wsgi` or `mod_python` embeds Python inside Apache; no process is forked. Apache runs the Django application directly.
2. **Daemon** `mod_wsgi` or `mod_fastcgi` allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod\_fastcgi to communicate with this process.
Note that `mod_wsgi` can work in either mode: embedded or daemon.
When you read up on mod\_fastcgi, you'll see that Django uses [flup](http://pypi.python.org/pypi/flup/) to create a WSGI-compatible interface from the information provided by mod\_fastcgi. The pipeline works like this.
```
Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)
```
Django has several "django.core.handlers" for the various interfaces.
For mod\_fastcgi, Django provides a `manage.py runfcgi` that integrates FLUP and the handler.
For mod\_wsgi, there's a core handler for this.
**How to install WSGI support?**
Follow these instructions.
<https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki>
For background see this
<http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index>
|
219,135 |
<p>I have been reading carefully through the mediawiki documentation but I have not been able to find out how to create new groups. </p>
<p>When I look at Special:Userrights, I see only 3 groups :
Bots, Sysops, Bureaycrats</p>
<p>I would like to create my own custom groups, so I can use some extensions like the <a href="http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control" rel="noreferrer">http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control</a>.</p>
<p>Can someone tell me how it's done, or point me to some documentation?</p>
|
[
{
"answer_id": 219213,
"author": "jeph perro",
"author_id": 28351,
"author_profile": "https://Stackoverflow.com/users/28351",
"pm_score": 1,
"selected": false,
"text": "<p>I beleive I have found the answer, I just need to add the UserGroup and the permission to the wgGroupPermissions array in the LocalSettings.php file.</p>\n\n<pre><code>$wgGroupPermissions['TomatoUsers']['read'] = true;\n$wgGroupPermissions['TomatoUsers']['edit'] = false;\n</code></pre>\n"
},
{
"answer_id": 223633,
"author": "richardkmiller",
"author_id": 41820,
"author_profile": "https://Stackoverflow.com/users/41820",
"pm_score": 7,
"selected": true,
"text": "<p>You can add permissions for new groups to your LocalSettings.php file and they will automatically appear in the Special:UserRights page.</p>\n\n<p>For example, I wanted to disallow editing by regular users but create a \"Trusted\" group that was allowed to edit. The following code creates a \"Trusted\" group that is equal to the \"user\" group, except that \"Trusted\" users can edit but \"user\" users cannot. </p>\n\n<pre><code>$wgGroupPermissions['Trusted'] = $wgGroupPermissions['user'];\n$wgGroupPermissions['user' ]['edit'] = false;\n$wgGroupPermissions['Trusted']['edit'] = true;\n$wgGroupPermissions['sysop' ]['edit'] = true;\n</code></pre>\n\n<p>On the Special:UserRights page, I can now check the \"Trusted\" box to make users trusted.</p>\n"
},
{
"answer_id": 1541391,
"author": "Compholio",
"author_id": 185828,
"author_profile": "https://Stackoverflow.com/users/185828",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have the reputation to vote up the first answer (which can also be added to extension initialization files), but for when you get to adding users to your groups you may want to consider directly editing the database (ie. if you need to sync the wiki groups with external information). If you open the database \"wikidb\" the \"PREFIX_user_groups\"* table contains the mapping between user IDs (ug_user) and group names (ug_group). This table, combined with the \"PREFIX_user\"* table's name information (user_name) and ID information (user_id), give you all the information to add and remove large numbers of users from groups.</p>\n\n<p>* Replace \"PREFIX\" with the database prefix you used for your wiki.</p>\n"
},
{
"answer_id": 3136585,
"author": "nevi",
"author_id": 378492,
"author_profile": "https://Stackoverflow.com/users/378492",
"pm_score": 2,
"selected": false,
"text": "<p>Here you will find a List of Permissions. <a href=\"http://www.mediawiki.org/wiki/Manual:User_rights\" rel=\"nofollow noreferrer\">http://www.mediawiki.org/wiki/Manual:User_rights</a></p>\n"
},
{
"answer_id": 19148533,
"author": "sir KitKat",
"author_id": 2485995,
"author_profile": "https://Stackoverflow.com/users/2485995",
"pm_score": 3,
"selected": false,
"text": "<p>You can alter the appearance of the group name by creating the following messages:\n(For a group named ninja:)</p>\n\n<ul>\n<li>MediaWiki:Group-ninja (content: Ninjas)</li>\n<li>MediaWiki:Group-ninja-member (content: ninja)</li>\n<li>MediaWiki:Grouppage-ninja (content: Project:Ninjas)</li>\n</ul>\n\n<p>This will insure that the group will be referred to as \"Ninjas\" throughout the interface, and a member will be referred to as a \"ninja\", and overviews will link the groupname to Project:Ninjas.</p>\n\n<p>(source: <a href=\"http://www.mediawiki.org/wiki/Manual:User_rights#Examples\">http://www.mediawiki.org/wiki/Manual:User_rights#Examples</a>)</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28351/"
] |
I have been reading carefully through the mediawiki documentation but I have not been able to find out how to create new groups.
When I look at Special:Userrights, I see only 3 groups :
Bots, Sysops, Bureaycrats
I would like to create my own custom groups, so I can use some extensions like the <http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control>.
Can someone tell me how it's done, or point me to some documentation?
|
You can add permissions for new groups to your LocalSettings.php file and they will automatically appear in the Special:UserRights page.
For example, I wanted to disallow editing by regular users but create a "Trusted" group that was allowed to edit. The following code creates a "Trusted" group that is equal to the "user" group, except that "Trusted" users can edit but "user" users cannot.
```
$wgGroupPermissions['Trusted'] = $wgGroupPermissions['user'];
$wgGroupPermissions['user' ]['edit'] = false;
$wgGroupPermissions['Trusted']['edit'] = true;
$wgGroupPermissions['sysop' ]['edit'] = true;
```
On the Special:UserRights page, I can now check the "Trusted" box to make users trusted.
|
219,138 |
<p>I need to run a Linux CLI command and get its stdout output from C.</p>
<p>I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.</p>
<p>Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.</p>
<p>There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.</p>
|
[
{
"answer_id": 219150,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>popen()</code> and <code>pclose()</code>.</p>\n\n<hr>\n\n<p><code>popen()</code> does not actually wait, of course, but reads on the pipe will block until there is data available.</p>\n\n<p><code>pclose()</code> waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...</p>\n\n<hr>\n\n<p>Possibly already discussed at <A href=\"https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output\"><a href=\"https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output\">How can I run an external program from C and parse its output?</a></A></p>\n"
},
{
"answer_id": 219157,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>Is this it?</p>\n\n<pre>\nNAME\n popen, pclose - process I/O\n\nSYNOPSIS\n #include <stdio.h> \n\n FILE *popen(const char *command, const char *type);\n\n int pclose(FILE *stream);\n\nDESCRIPTION\n The popen() function opens a process by creating a pipe, forking, \nand invoking the shell. Since a pipe is by definition unidirectional, the \ntype argument may specify only reading or writing, not both; the resulting \nstream is correspondingly read-only or write-only.\n\n The command argument is a pointer to a null-terminated string \ncontaining a shell command line. This command is passed to /bin/sh \nusing the -c flag; interpretation, if any, is performed by the shell. \nThe type argument is a pointer to a null-terminated string which must be \neither ‘r’ for reading or ‘w’ for writing.\n\n The return value from popen() is a normal standard I/O stream in \nall respects save that it must be closed with pclose() rather than fclose(). \nWriting to such a stream writes to the standard input of the command; the \ncommand’s standard output is the same as that of the process that called \npopen(), unless this is altered by the command itself. Conversely, reading \nfrom a ‘‘popened’’ stream reads the command’s standard output, and the \ncommand’s standard input is the same as that of the process that called \npopen().\n\n Note that output popen() streams are fully buffered by default.\n\n The pclose() function waits for the associated process to terminate \nand returns the exit status of the command as returned by wait4().\n</pre>\n"
},
{
"answer_id": 219709,
"author": "humble_guru",
"author_id": 23961,
"author_profile": "https://Stackoverflow.com/users/23961",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what I use:</p>\n\n<pre><code> /* simply invoke a app, pipe output*/\n pipe = popen(buf, \"r\" );\n if (pipe == NULL ) {\n printf(\"invoking %s failed: %s\\n\", buf, strerror(errno));\n return 1;\n }\n\n waitfor(10);\n\n while(!feof(pipe) ) {\n if( fgets( buf, 128, pipe ) != NULL ) {\n printf(\"%s\\n\", buf );\n }\n }\n\n /* Close pipe */\n rc = pclose(pipe);\n</code></pre>\n"
},
{
"answer_id": 3156299,
"author": "garagumu",
"author_id": 161699,
"author_profile": "https://Stackoverflow.com/users/161699",
"pm_score": 2,
"selected": false,
"text": "<p>GLib has a nice function for this -- <code>g_spawn_sync()</code>:\n<a href=\"http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-sync\" rel=\"nofollow noreferrer\">http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-sync</a></p>\n\n<p>For example, to run a command and get its exit status and output:</p>\n\n<pre><code>const char *argv[] = { \"your_command\", NULL };\nchar *output = NULL; // will contain command output\nGError *error = NULL;\nint exit_status = 0;\nif (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL, \n &output, NULL, &exit_status, &error))\n{\n // handle error here\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.
|
Is this it?
```
NAME
popen, pclose - process I/O
SYNOPSIS
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
DESCRIPTION
The popen() function opens a process by creating a pipe, forking,
and invoking the shell. Since a pipe is by definition unidirectional, the
type argument may specify only reading or writing, not both; the resulting
stream is correspondingly read-only or write-only.
The command argument is a pointer to a null-terminated string
containing a shell command line. This command is passed to /bin/sh
using the -c flag; interpretation, if any, is performed by the shell.
The type argument is a pointer to a null-terminated string which must be
either ‘r’ for reading or ‘w’ for writing.
The return value from popen() is a normal standard I/O stream in
all respects save that it must be closed with pclose() rather than fclose().
Writing to such a stream writes to the standard input of the command; the
command’s standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, reading
from a ‘‘popened’’ stream reads the command’s standard output, and the
command’s standard input is the same as that of the process that called
popen().
Note that output popen() streams are fully buffered by default.
The pclose() function waits for the associated process to terminate
and returns the exit status of the command as returned by wait4().
```
|
219,139 |
<p>I'm trying to use stl algorithm for_each without proliferating templates throughout my code. std::for_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.</p>
<p>My Question: </p>
<p>Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel!</p>
<pre><code> struct MyFunctor {
virtual ~MyFunctor() {}
virtual void operator()(int a) = 0;
}
namespace {
template<typename FunctorType, typename OperandType> struct
FunctorAdapter
{
FunctorAdapter(FunctorType* functor) : mFunctor(functor) {}
void operator()(OperandType& subject)
{
(*mFunctor)(subject);
}
FunctorType* mFunctor;
}; }
void applyToAll(MyFunctor &f) {
FunctorHelper<MyFunctor, int> tmp(&f);
std::for_each(myvector.begin(), myvector.end(), tmp); }
</code></pre>
<p>Cheers,</p>
<p>Dave </p>
|
[
{
"answer_id": 219199,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the function adapters (and their shims) from <code>functional</code>.</p>\n\n<pre><code>#include <functional>\n\nusing namespace std;\nfor_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) );\n</code></pre>\n\n<p>If your container contains pointers-to-objects, use <code>mem_fun_ptr</code>, else use <code>mem_fun</code>. Next to these, there are wrappers for member functions that take 1 argument: <code>mem_fun1_ptr</code> and <code>mem_fun1</code>.</p>\n\n<p>@Evan: indeed, you could call the member function with the same argument for each object. The first argument of the <code>mem_fun1</code> wrappers is the <code>this</code> pointer, the second is the member function argument:</p>\n\n<pre><code>for_each( vec.begin(), vec.end(), bind2nd( mem_fun_ptr( &MyClass::f ), 1 ) );\n</code></pre>\n\n<p>With more arguments, it becomes more readable to create a loop yourself, or create a custom functor that has const member variables representing the arguments.</p>\n"
},
{
"answer_id": 219208,
"author": "Dan",
"author_id": 27816,
"author_profile": "https://Stackoverflow.com/users/27816",
"pm_score": 0,
"selected": false,
"text": "<p>What about forgetting all the wrapping of the functor pointer, and instead use \n<code>bind(functor_pointer,mem_fun1(&MyFunctor::operator());\n</code>\n as the functor? that way, you don't have to worry about managing the copy in any way shape or form.</p>\n"
},
{
"answer_id": 219275,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 0,
"selected": false,
"text": "<p>why not use BOOST_FOREACH?</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_35_0/doc/html/foreach.html</a></p>\n"
},
{
"answer_id": 219289,
"author": "Jeffrey Martinez",
"author_id": 29703,
"author_profile": "https://Stackoverflow.com/users/29703",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like you could benefit from <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function.html\" rel=\"nofollow noreferrer\">Boost::Function</a>.</p>\n\n<p>If I remember correctly it's a header only library too, so it's easy to get it going with it.</p>\n"
},
{
"answer_id": 219890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Building on @xtofl's answer, since the array contains int's and not \"this\" pointers, I think the correct incantation is</p>\n\n<pre><code>class MyClass\n{\n virtual void process(int number) = 0;\n};\nMyClass *instance = ...;\n\nfor_each( vec.begin(), vec.end(), binder1st(instance, mem_fun_ptr(&MyClass::process) );\n</code></pre>\n\n<p>The only difference versus @xtofl's code is binder1st rather than binder2nd. binder2nd allows you to pass teh same number to various \"this\" pointers. binder1st allows you to pass various numbers to one \"this\" pointer.</p>\n"
},
{
"answer_id": 220220,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 3,
"selected": true,
"text": "<p>tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms.</p>\n\n<pre><code>// requires TR1 support from your compiler / standard library implementation\n#include <functional>\n\nvoid applyToAll(MyFunctor &f) {\n std::for_each(\n myvector.begin(), \n myvector.end(), \n std::tr1::ref(f) \n ); \n}\n</code></pre>\n\n<p>However, NOTE that compilers without decltype support <em>MAY</em> reject passing a reference to an abstract type... so this code may not compile until you get C++0x support.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1575281/"
] |
I'm trying to use stl algorithm for\_each without proliferating templates throughout my code. std::for\_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.
My Question:
Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel!
```
struct MyFunctor {
virtual ~MyFunctor() {}
virtual void operator()(int a) = 0;
}
namespace {
template<typename FunctorType, typename OperandType> struct
FunctorAdapter
{
FunctorAdapter(FunctorType* functor) : mFunctor(functor) {}
void operator()(OperandType& subject)
{
(*mFunctor)(subject);
}
FunctorType* mFunctor;
}; }
void applyToAll(MyFunctor &f) {
FunctorHelper<MyFunctor, int> tmp(&f);
std::for_each(myvector.begin(), myvector.end(), tmp); }
```
Cheers,
Dave
|
tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms.
```
// requires TR1 support from your compiler / standard library implementation
#include <functional>
void applyToAll(MyFunctor &f) {
std::for_each(
myvector.begin(),
myvector.end(),
std::tr1::ref(f)
);
}
```
However, NOTE that compilers without decltype support *MAY* reject passing a reference to an abstract type... so this code may not compile until you get C++0x support.
|
219,151 |
<p>I want to create a WCF-service hosted in IIS6 and disable anonymous authentication in IIS. And don't use SSL.</p>
<p>So only way I have is to use basicHttpBinging with <code>TransportCredentialOnly</code>, itsn't it?</p>
<p>I create a virtual directory, set Windows Integrated Auth and uncheck "Enable Anonymous Access".</p>
<p>Here's my web.config:</p>
<pre><code><system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="MyBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Samples.ServiceFacadeService" behaviorConfiguration="ServiceFacadeServiceBehavior">
<endpoint address="" binding="basicHttpBinding" bindingName="MyBinding"
contract="Samples.IServiceFacadeService">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceFacadeServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</code></pre>
<p>You can see that I even haven't included MEX-enpoint for metadata exchange. Just one endpoint and one binding for it with TransportCredentialOnly security.</p>
<p>But when I tries to start service (invoking a method throught client proxy) I got such exception in the EventLog:</p>
<blockquote>
<p>Exception:
System.ServiceModel.ServiceActivationException:
The service
'/wcftest/ServiceFacadeService.svc'
cannot be activated due to an
exception during compilation. The
exception message is: Security
settings for this service require
'Anonymous' Authentication but it is
not enabled for the IIS application
that hosts this service.. --->
System.NotSupportedException: Security
settings for this service require
'Anonymous' Authentication but it is
not enabled for the IIS application
that hosts this service.</p>
</blockquote>
<p>I have no idea why my service require Anonymous auth? Why?</p>
|
[
{
"answer_id": 219270,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 3,
"selected": false,
"text": "<p>The MEX endpoint may still be the problem (see this <a href=\"http://ahmed0192.spaces.live.com/blog/cns!FD6F44C91F5D2AD9!160.entry\" rel=\"noreferrer\">post</a>). Try disabling MEX like this:</p>\n\n<p></p>\n\n<pre><code><services>\n <!-- Note: the service name must match the configuration name for the service implementation. -->\n <service name=\"MyNamespace.MyServiceType\" behaviorConfiguration=\"MyServiceTypeBehaviors\" >\n <!-- Add the following endpoint. -->\n <!-- Note: your service must have an http base address to add this endpoint. -->\n <endpoint contract=\"IMetadataExchange\" binding=\"mexHttpBinding\" address=\"mex\" />\n </service>\n</services>\n\n<behaviors>\n <serviceBehaviors>\n <behavior name=\"MyServiceTypeBehaviors\" >\n <!-- This disables it. -->\n <serviceMetadata httpGetEnabled=\"false\" />\n </behavior>\n </serviceBehaviors>\n</behaviors>\n</code></pre>\n\n<p></p>\n\n<p>Here is a good <a href=\"http://www.leastprivilege.com/SecuringWCFMetadata.aspx\" rel=\"noreferrer\">post</a> on securing MEX.</p>\n"
},
{
"answer_id": 219516,
"author": "Shrike",
"author_id": 27703,
"author_profile": "https://Stackoverflow.com/users/27703",
"pm_score": 3,
"selected": false,
"text": "<p>The answer found jezell. Thanks.\nI mixed up bindingName and bindingConfiguration :</p>\n\n<pre><code><endpoint address=\"\" binding=\"basicHttpBinding\" bindingName=\"MyBinding\"\n contract=\"Samples.IServiceFacadeService\">\n</endpoint>\n</code></pre>\n\n<p>That's right:</p>\n\n<pre><code><endpoint address=\"\" binding=\"basicHttpBinding\" **bindingConfiguration**=\"MyBinding\"\n contract=\"Samples.IServiceFacadeService\">\n</endpoint>\n</code></pre>\n"
},
{
"answer_id": 3661939,
"author": "Kay Khan",
"author_id": 333701,
"author_profile": "https://Stackoverflow.com/users/333701",
"pm_score": 2,
"selected": false,
"text": "<p>Use basicHttpBinding for your mex endpoint and apply the same bindingConfiguration:</p>\n\n<p> \n \n \n \n \n \n</p>\n\n<p> </p>\n"
},
{
"answer_id": 4806721,
"author": "wcfdude",
"author_id": 590882,
"author_profile": "https://Stackoverflow.com/users/590882",
"pm_score": 1,
"selected": false,
"text": "<p>To get VS wcf service project (new sample project) to work with authentication under IIS, you have to:</p>\n\n<p>1) Allow Anonymous access in IIS<br>\n2) Prefix your public methods with a attribute like this:</p>\n\n<pre><code>[PrincipalPermission(SecurityAction.Demand, Role = \"MyADGroup\")]\npublic string SendMyMessage(string Message)\n{...}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27703/"
] |
I want to create a WCF-service hosted in IIS6 and disable anonymous authentication in IIS. And don't use SSL.
So only way I have is to use basicHttpBinging with `TransportCredentialOnly`, itsn't it?
I create a virtual directory, set Windows Integrated Auth and uncheck "Enable Anonymous Access".
Here's my web.config:
```
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="MyBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Samples.ServiceFacadeService" behaviorConfiguration="ServiceFacadeServiceBehavior">
<endpoint address="" binding="basicHttpBinding" bindingName="MyBinding"
contract="Samples.IServiceFacadeService">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceFacadeServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
```
You can see that I even haven't included MEX-enpoint for metadata exchange. Just one endpoint and one binding for it with TransportCredentialOnly security.
But when I tries to start service (invoking a method throught client proxy) I got such exception in the EventLog:
>
> Exception:
> System.ServiceModel.ServiceActivationException:
> The service
> '/wcftest/ServiceFacadeService.svc'
> cannot be activated due to an
> exception during compilation. The
> exception message is: Security
> settings for this service require
> 'Anonymous' Authentication but it is
> not enabled for the IIS application
> that hosts this service.. --->
> System.NotSupportedException: Security
> settings for this service require
> 'Anonymous' Authentication but it is
> not enabled for the IIS application
> that hosts this service.
>
>
>
I have no idea why my service require Anonymous auth? Why?
|
The MEX endpoint may still be the problem (see this [post](http://ahmed0192.spaces.live.com/blog/cns!FD6F44C91F5D2AD9!160.entry)). Try disabling MEX like this:
```
<services>
<!-- Note: the service name must match the configuration name for the service implementation. -->
<service name="MyNamespace.MyServiceType" behaviorConfiguration="MyServiceTypeBehaviors" >
<!-- Add the following endpoint. -->
<!-- Note: your service must have an http base address to add this endpoint. -->
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<!-- This disables it. -->
<serviceMetadata httpGetEnabled="false" />
</behavior>
</serviceBehaviors>
</behaviors>
```
Here is a good [post](http://www.leastprivilege.com/SecuringWCFMetadata.aspx) on securing MEX.
|
219,219 |
<p>Is it possible to to change a <code><span></code> tag (or <code><div></code>) to preformat its contents like a <code><pre></code> tag would using only CSS?</p>
|
[
{
"answer_id": 219230,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 9,
"selected": true,
"text": "<p>Look at the <a href=\"https://www.w3.org/TR/CSS21/sample.html\" rel=\"noreferrer\">W3C CSS2.1 Default Style Sheet</a> or the <a href=\"https://www.w3.org/TR/CSS22/sample.html\" rel=\"noreferrer\">CSS2.2 Working Draft</a>. Copy all the settings for PRE and put them into your own class.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>pre {\n display: block;\n unicode-bidi: embed;\n font-family: monospace;\n white-space: pre;\n}\n</code></pre>\n"
},
{
"answer_id": 219241,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 6,
"selected": false,
"text": "<p>See <a href=\"http://www.w3.org/TR/CSS21/text.html#propdef-white-space\" rel=\"noreferrer\">the white-space CSS property</a>.</p>\n\n<pre><code>.like-pre { white-space: pre; }\n</code></pre>\n"
},
{
"answer_id": 219242,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 3,
"selected": false,
"text": "<p>Specifically, the property you're looking at is:</p>\n\n<pre><code>white-space: pre\n</code></pre>\n\n<p><a href=\"http://www.quirksmode.org/css/whitespace.html\" rel=\"noreferrer\">http://www.quirksmode.org/css/whitespace.html</a><br>\n<a href=\"http://www.w3.org/TR/CSS21/text.html#white-space-prop\" rel=\"noreferrer\">http://www.w3.org/TR/CSS21/text.html#white-space-prop</a></p>\n"
},
{
"answer_id": 219246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just use the <pre> tag, instead of the span tag? Both are inline, so both should behave in the way you would like. If you have a problem overriding the entire definition of <pre>, just give it a class/id.</p>\n"
},
{
"answer_id": 219254,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 5,
"selected": false,
"text": "<p>This makes a SPAN look like a PRE:</p>\n\n<pre><code>span {\n white-space: pre;\n font-family: monospace;\n display: block;\n}\n</code></pre>\n\n<p>Remember to change the css selector as appropriate.</p>\n"
},
{
"answer_id": 15003581,
"author": "Yanni",
"author_id": 689782,
"author_profile": "https://Stackoverflow.com/users/689782",
"pm_score": 2,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>span {\n white-space: pre;\n font-family: monospace;\n display: block;\n unicode-bidi: embed\n}\n</code></pre>\n"
},
{
"answer_id": 30950709,
"author": "Yesu Raj",
"author_id": 896043,
"author_profile": "https://Stackoverflow.com/users/896043",
"pm_score": 1,
"selected": false,
"text": "<p>Try this style</p>\n\n<pre><code>.pre {\n\nwhite-space: pre-wrap;\nwhite-space: -moz-pre-wrap;\nwhite-space: -pre-wrap;\nwhite-space: -o-pre-wrap;\nword-wrap: break-word;\nline-height: 1.5; \nword-break: break-all;\nwhite-space: pre;\nwhite-space: pre\\9; /* IE7+ */\ndisplay: block;\n}\n</code></pre>\n\n<p>Used the same here - <a href=\"http://www.makemyshop.in/Snapdeal\" rel=\"nofollow\">http://www.makemyshop.in/</a></p>\n"
},
{
"answer_id": 64872281,
"author": "Christophe Le Besnerais",
"author_id": 990193,
"author_profile": "https://Stackoverflow.com/users/990193",
"pm_score": 3,
"selected": false,
"text": "<p>while the accepted answer is indeed correct, if you want the text to wrap you should use:</p>\n<pre><code>white-space: pre-wrap;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
] |
Is it possible to to change a `<span>` tag (or `<div>`) to preformat its contents like a `<pre>` tag would using only CSS?
|
Look at the [W3C CSS2.1 Default Style Sheet](https://www.w3.org/TR/CSS21/sample.html) or the [CSS2.2 Working Draft](https://www.w3.org/TR/CSS22/sample.html). Copy all the settings for PRE and put them into your own class.
```css
pre {
display: block;
unicode-bidi: embed;
font-family: monospace;
white-space: pre;
}
```
|
219,226 |
<p>Recently I have been studying recursion; how to write it, analyze it, etc. I have thought for a while that recurrence and recursion were the same thing, but some problems on recent homework assignments and quizzes have me thinking there are slight differences, that 'recurrence' is the way to describe a recursive program or function.</p>
<p>This has all been very Greek to me until recently, when I realized that there is something called the 'master theorem' used to write the 'recurrence' for problems or programs. I've been reading through the wikipedia page, but, as usual, things are worded in such a way that I don't really understand what it's talking about. I learn much better with examples.</p>
<p>So, a few questions:
Lets say you are given this recurrence:</p>
<blockquote>
<p>r(n) = 2*r(n-2) + r(n-1);<br>
r(1) = r(2)
= 1</p>
</blockquote>
<p>Is this, in fact, in the form of the master theorem? If so, in words, what is it saying? If you were to be trying to write a small program or a tree of recursion based on this recurrence, what would that look like? Should I just try substituting numbers in, seeing a pattern, then writing pseudocode that could recursively create that pattern, or, since this may be in the form of the master theorem, is there a more straightforward, mathematical approach?</p>
<p>Now, lets say you were asked to find the recurrence, T(n), for the number of additions performed by the program created from the previous recurrence. I can see that the base case would probably be T(1) = T(2) = 0, but I'm not sure where to go from there.</p>
<p>Basically, I am asking how to go from a given recurrence to code, and the opposite. Since this looks like the master theorem, I'm wondering if there is a straightforward and mathematical way of going about it.</p>
<p>EDIT: Okay, I've looked through some of my past assignments to find another example of where I'm asked, 'to find the recurrence', which is the part of this question I'm having the post trouble with.</p>
<blockquote>
<p>Recurrence that describes in the best
way the number of addition operations
in the following program fragment
(when called with l == 1 and r == n)</p>
</blockquote>
<pre><code>int example(A, int l, int r) {
if (l == r)
return 2;
return (A[l] + example(A, l+1, r);
}
</code></pre>
|
[
{
"answer_id": 219238,
"author": "David Koelle",
"author_id": 2197,
"author_profile": "https://Stackoverflow.com/users/2197",
"pm_score": 1,
"selected": false,
"text": "<p>Your method, written in code using a recursive function, would look like this:</p>\n\n<pre><code>function r(int n) \n{\n if (n == 2) return 1;\n if (n == 1) return 1;\n return 2 * r(n-2) + r(n-1); // I guess we're assuming n > 2\n}\n</code></pre>\n\n<p>I'm not sure what \"recurrence\" is, but a recursive function is simply one that calls itself. </p>\n\n<p>Recursive functions need an <em>escape clause</em> (some non-recursive case - for example, \"if n==1 return 1\") to prevent a <em>Stack Overflow</em> error (i.e., the function gets called so much that the interpreter runs out of memory or other resources)</p>\n"
},
{
"answer_id": 219250,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 1,
"selected": false,
"text": "<p>A simple program that would implement that would look like:</p>\n\n<pre><code>public int r(int input) {\n if (input == 1 || input == 2) {\n return 1;\n } else {\n return 2 * r(input - 2) + r(input -1)\n }\n}\n</code></pre>\n\n<p>You would also need to make sure that the input is not going to cause an infinite recursion, for example, if the input at the beginning was less than 1. If this is not a valid case, then return an error, if it is valid, then return the appropriate value.</p>\n"
},
{
"answer_id": 219281,
"author": "Ying Xiao",
"author_id": 30202,
"author_profile": "https://Stackoverflow.com/users/30202",
"pm_score": 4,
"selected": true,
"text": "<p>A few years ago, Mohamad Akra and Louay Bazzi proved a result that generalizes the Master method -- it's almost always better. You really shouldn't be using the Master Theorem anymore...</p>\n\n<p>See, for example, this writeup: <a href=\"http://courses.csail.mit.edu/6.046/spring04/handouts/akrabazzi.pdf\" rel=\"noreferrer\">http://courses.csail.mit.edu/6.046/spring04/handouts/akrabazzi.pdf</a></p>\n\n<p>Basically, get your recurrence to look like equation 1 in the paper, pick off the coefficients, and integrate the expression in Theorem 1.</p>\n"
},
{
"answer_id": 3463619,
"author": "Michael M. Adkins",
"author_id": 417828,
"author_profile": "https://Stackoverflow.com/users/417828",
"pm_score": 1,
"selected": false,
"text": "<p>\"I'm not exactly sure what 'recurrence' is either\"</p>\n\n<p>The definition of a \"recurrence relation\" is a sequence of numbers \"whose domain is some infinite set of integers and whose range is a set of real numbers.\" With the additional condition that that the function describing this sequence \"defines one member of the sequence in terms of a previous one.\"</p>\n\n<p>And, the objective behind solving them, I think, is to go from a recursive definition to one that isn't. Say if you had T(0) = 2 and T(n) = 2 + T(n-1) for all n>0, you'd have to go from the expression \"T(n) = 2 + T(n-1)\" to one like \"2n+2\".</p>\n\n<p>sources:\n1) \"Discrete Mathematics with Graph Theory - Second Edition\", by Edgar G. Goodair and Michael M. Parmenter\n2) \"Computer Algorithms C++,\" by Ellis Horowitz, Sartaj Sahni, and Sanguthevar Rajasekaran.</p>\n"
},
{
"answer_id": 3474202,
"author": "Michael M. Adkins",
"author_id": 417828,
"author_profile": "https://Stackoverflow.com/users/417828",
"pm_score": 2,
"selected": false,
"text": "<p>Zachary:</p>\n\n<blockquote>\n <p>Lets say you are given this\n recurrence:</p>\n \n <p>r(n) = 2*r(n-2) + r(n-1); r(1) = r(2)\n = 1</p>\n \n <p>Is this, in fact, in the form of the\n master theorem? If so, in words, what\n is it saying?</p>\n</blockquote>\n\n<p>I think that what your recurrence relation is saying is that for function of \"r\" with \"n\" as its parameter (representing the total number of data sets you're inputting), whatever you get at the nth position of the data-set is the output of the n-1 th position plus twice whatever is the result of the n-2 th position, with no non-recursive work being done. When you try to solve a recurrence relation, you're trying to go about expressing it in a way that doesn't involve recursion.</p>\n\n<p>However, I don't think that that is in the correct form for the Master Theorem Method. Your statement is a \"second order linear recurrence relation with constant coefficients\". Apparently, according to my old Discrete Math textbook, that's the form you need to have in order to solve the recurrence relation. </p>\n\n<p>Here's the form that they give:</p>\n\n<pre><code>r(n) = a*r(n-1) + b*r(n-2) + f(n)\n</code></pre>\n\n<p>For 'a' and 'b' are some constants and f(n) is some function of n. In your statement, a = 1, b = 2, and f(n) = 0. Whenever, f(n) is equal to zero the recurrence relation is known as \"homogenous\". So, your expression is homogenous.</p>\n\n<p>I don't think that you can solve a homogenous recurrence relation using the Master Method Theoerm because f(n) = 0. None of the cases for Master Method Theorem allow for that because n-to-the-power-of-anything can't equal zero. I could be wrong, because I'm not really an expert at this but I don't that it's possible to solve a homogenous recurrence relation using the Master Method.</p>\n\n<p>I that that the way to solve a homogeneous recurrence relation is to go by 5 steps:</p>\n\n<p>1) Form the characteristic equation, which is something of the form of:</p>\n\n<pre><code>x^k - c[1]*x^k-1 - c[2]*x^k-2 - ... - c[k-1]*x - c[k] = 0\n</code></pre>\n\n<p>If you've only got 2 recursive instances in your homogeneous recurrence relation then you only need to change your equation into the Quadratic Equation where</p>\n\n<pre><code>x^2 - a*x - b = 0\n</code></pre>\n\n<p>This is because a recurrence relation of the form of</p>\n\n<pre><code>r(n) = a*r(n-1) + b*r(n-2)\n</code></pre>\n\n<p>Can be re-written as</p>\n\n<pre><code>r(n) - a*r(n-1) - b*r(n-2) = 0\n</code></pre>\n\n<p>2) After your recurrence relation is rewritten as a characteristic equation, next find the roots (x[1] and x[2]) of the characteristic equation.</p>\n\n<p>3) With your roots, your solution will now be one of the two forms:</p>\n\n<pre><code>if x[1]!=x[2]\n c[1]*x[1]^n + c[2]*x[2]^n\nelse\n c[1]*x[1]^n + n*c[2]*x[2]^n\n</code></pre>\n\n<p>for when n>2.\n4) With the new form of your recursive solution, you use the <em>initial conditions</em> (r(1) and r(2)) to find c[1] and c[2]</p>\n\n<p>Going with your example here's what we get:</p>\n\n<p>1) \n r(n) = 1*r(n-1) + 2*r(n-2)\n=> x^2 - x - 2 = 0</p>\n\n<p>2) Solving for x</p>\n\n<pre><code>x = (-1 +- sqrt(-1^2 - 4(1)(-2)))/2(1)\n\n x[1] = ((-1 + 3)/2) = 1\n x[2] = ((-1 - 3)/2) = -2\n</code></pre>\n\n<p>3) Since x[1] != x[2], your solution has the form:</p>\n\n<pre><code>c[1](x[1])^n + c[2](x[2])^n\n</code></pre>\n\n<p>4) Now, use your initial conditions to find the two constants c[1] and c[2]:</p>\n\n<pre><code>c[1](1)^1 + c[2](-2)^1 = 1\nc[1](1)^2 + c[2](-2)^2 = 1\n</code></pre>\n\n<p>Honestly, I'm not sure what your constants are in this situation, I stopped at this point. I guess you'd have to plug in numbers until you'd somehow got a value for both c[1] and c[2] which would both satisfy those two expressions. Either that or perform row reduction on a matrix C where C equals:</p>\n\n<pre><code>[ 1 1 | 1 ]\n[ 1 2 | 1 ] \n</code></pre>\n\n<p>Zachary:</p>\n\n<blockquote>\n <p>Recurrence that describes in the best\n way the number of addition operations\n in the following program fragment\n (when called with l == 1 and r == n)</p>\n</blockquote>\n\n<pre><code>int example(A, int l, int r) {\n if (l == r)\n return 2;\n return (A[l] + example(A, l+1, r);\n}\n</code></pre>\n\n<p>Here's the time complexity values for your given code for when r>l:</p>\n\n<pre><code>int example(A, int l, int r) { => T(r) = 0\n if (l == r) => T(r) = 1\n return 2; => T(r) = 1\n return (A[l] + example(A, l+1, r); => T(r) = 1 + T(r-(l+1))\n}\n\nTotal: T(r) = 3 + T(r-(l+1))\n</code></pre>\n\n<p>Else, when r==l then T(r) = 2, because the if-statement and the return both require 1 step per execution.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23323/"
] |
Recently I have been studying recursion; how to write it, analyze it, etc. I have thought for a while that recurrence and recursion were the same thing, but some problems on recent homework assignments and quizzes have me thinking there are slight differences, that 'recurrence' is the way to describe a recursive program or function.
This has all been very Greek to me until recently, when I realized that there is something called the 'master theorem' used to write the 'recurrence' for problems or programs. I've been reading through the wikipedia page, but, as usual, things are worded in such a way that I don't really understand what it's talking about. I learn much better with examples.
So, a few questions:
Lets say you are given this recurrence:
>
> r(n) = 2\*r(n-2) + r(n-1);
>
> r(1) = r(2)
> = 1
>
>
>
Is this, in fact, in the form of the master theorem? If so, in words, what is it saying? If you were to be trying to write a small program or a tree of recursion based on this recurrence, what would that look like? Should I just try substituting numbers in, seeing a pattern, then writing pseudocode that could recursively create that pattern, or, since this may be in the form of the master theorem, is there a more straightforward, mathematical approach?
Now, lets say you were asked to find the recurrence, T(n), for the number of additions performed by the program created from the previous recurrence. I can see that the base case would probably be T(1) = T(2) = 0, but I'm not sure where to go from there.
Basically, I am asking how to go from a given recurrence to code, and the opposite. Since this looks like the master theorem, I'm wondering if there is a straightforward and mathematical way of going about it.
EDIT: Okay, I've looked through some of my past assignments to find another example of where I'm asked, 'to find the recurrence', which is the part of this question I'm having the post trouble with.
>
> Recurrence that describes in the best
> way the number of addition operations
> in the following program fragment
> (when called with l == 1 and r == n)
>
>
>
```
int example(A, int l, int r) {
if (l == r)
return 2;
return (A[l] + example(A, l+1, r);
}
```
|
A few years ago, Mohamad Akra and Louay Bazzi proved a result that generalizes the Master method -- it's almost always better. You really shouldn't be using the Master Theorem anymore...
See, for example, this writeup: <http://courses.csail.mit.edu/6.046/spring04/handouts/akrabazzi.pdf>
Basically, get your recurrence to look like equation 1 in the paper, pick off the coefficients, and integrate the expression in Theorem 1.
|
219,243 |
<pre><code>function Submit_click()
{
if (!bValidateFields())
return;
}
function bValidateFields() {
/// <summary>Validation rules</summary>
/// <returns>Boolean</returns>
...
}
</code></pre>
<p>So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to <a href="http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx" rel="nofollow noreferrer">this</a> it should. Should it?</p>
|
[
{
"answer_id": 219279,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try adding the <code>/// <reference></code> comment at the top of the external library? I've run into this in the past and it resolved my issue.</p>\n"
},
{
"answer_id": 219294,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": true,
"text": "<p>I recall an issue where having turned off the Navigation Bar in VS stopped a lot of the JS intellisense from working properly. If you have it turned off, try turning the Navigation Bar on again and see if it helps.</p>\n\n<p>Edit: You may also have to do Ctrl+Shift+J to force the IDE to update the intellisense.</p>\n\n<p>Edit2: As @blub said, if there are any issues with the javascript, the intellisense can break. Visual Studio actually evaluates the javascript to create the intellisense, so if there are syntax errors it can fail and not build the intellisense completely, or at all.</p>\n"
},
{
"answer_id": 285922,
"author": "Alan Oursland",
"author_id": 37189,
"author_profile": "https://Stackoverflow.com/users/37189",
"pm_score": 1,
"selected": false,
"text": "<p>The XML comments have to be inside the function, not above it.\nIn Visual Studio 2008, the XML comment information is only display for files referenced with a /// <reference... item.</p>\n\n<p>Visual Studio 2010 will display XML comment information for functions in the file your are editing and for files you are referencing.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28098/"
] |
```
function Submit_click()
{
if (!bValidateFields())
return;
}
function bValidateFields() {
/// <summary>Validation rules</summary>
/// <returns>Boolean</returns>
...
}
```
So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to [this](http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx) it should. Should it?
|
I recall an issue where having turned off the Navigation Bar in VS stopped a lot of the JS intellisense from working properly. If you have it turned off, try turning the Navigation Bar on again and see if it helps.
Edit: You may also have to do Ctrl+Shift+J to force the IDE to update the intellisense.
Edit2: As @blub said, if there are any issues with the javascript, the intellisense can break. Visual Studio actually evaluates the javascript to create the intellisense, so if there are syntax errors it can fail and not build the intellisense completely, or at all.
|
219,245 |
<p>I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral </p>
<p>Here is the select I am using now:</p>
<pre><code>SELECT SomeStringColumn from SomeTable
</code></pre>
<p>Here is the select I would like to use:
SELECT hex( SomeStringColumn ) from SomeTable</p>
<p>Unfortunately nothing is that simple... Informix gives me that message:
<em>Character to numeric conversion error</em></p>
<p>Any idea?</p>
|
[
{
"answer_id": 219310,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 4,
"selected": false,
"text": "<p>Can you use Cast and the fn_varbintohexstr?</p>\n\n<pre><code>SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary)) \nFROM SomeTable\n</code></pre>\n\n<p>I'm not sure if you have that function in your database system, it is in MS-SQL.</p>\n\n<p>I just tried it in my SQL server MMC on one of my tables:</p>\n\n<pre><code>SELECT master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1\nFROM Customer\n</code></pre>\n\n<p>This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:</p>\n\n<pre><code>SELECT hex(CAST(Addr1 AS VARBINARY)) AS Expr1\nFROM Customer\n</code></pre>\n"
},
{
"answer_id": 219321,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "<p>If it is possible for you to do this in the database client in code it might be easier.</p>\n\n<p>Otherwise the error probably means that the built in hex function can't work with your values as you expect. I would double check the input value is trimmed and in the format first, it might be that simple. Then I would consult the database documentation that describes the hex function and see what its expected input would be and compare that to some of your values and find out what the difference is and how to change your values to match that of the expected input.</p>\n\n<p>A simple google search for \"informix hex function\" brought up the first result page with the sentence: \"Must be a literal integer or some other expression that returns an integer\". If your data type is a string, first convert the string to an integer. It looks like at first glance you do something with the cast function (I am not sure about this).</p>\n\n<pre><code>select hex(cast SomeStringColumn as int)) from SomeTable\n</code></pre>\n"
},
{
"answer_id": 1637783,
"author": "jhamm",
"author_id": 103927,
"author_profile": "https://Stackoverflow.com/users/103927",
"pm_score": 3,
"selected": false,
"text": "<p>The following works in Sql 2005.</p>\n\n<pre><code>select convert(varbinary, SomeStringColumn) from SomeTable\n</code></pre>\n"
},
{
"answer_id": 8929661,
"author": "Boklucius",
"author_id": 697489,
"author_profile": "https://Stackoverflow.com/users/697489",
"pm_score": 0,
"selected": false,
"text": "<p>what about:</p>\n\n<pre><code>declare @hexstring varchar(max);\nset @hexstring = 'E0F0C0';\nselect cast('' as xml).value('xs:hexBinary( substring(sql:variable(\"@hexstring\"), sql:column(\"t.pos\")) )', 'varbinary(max)')\nfrom (select case substring(@hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)\n</code></pre>\n\n<p>I saw this here:\n<a href=\"http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx</a></p>\n\n<p>Sorrry, that work only on >MS SQL 2005</p>\n"
},
{
"answer_id": 43771962,
"author": "gusmundo",
"author_id": 4762664,
"author_profile": "https://Stackoverflow.com/users/4762664",
"pm_score": 0,
"selected": false,
"text": "<p>OLD Post but in my case I also had to remove the 0x part of the hex so I used the below code. (I'm using MS SQL)</p>\n\n<p><code>convert(varchar, convert(Varbinary(MAX), YOURSTRING),2)</code></p>\n"
},
{
"answer_id": 67249360,
"author": "Ben",
"author_id": 21347,
"author_profile": "https://Stackoverflow.com/users/21347",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n<pre><code>select convert(varbinary, '0xa3c0', 1)\n</code></pre>\n<p>The hex number needs to have an even number of digits. To get around that, try:</p>\n<pre><code>select convert(varbinary, '0x' + RIGHT('00000000' + REPLACE('0xa3c','0x',''), 8), 1)\n</code></pre>\n"
},
{
"answer_id": 74224916,
"author": "Евген Марчен",
"author_id": 20350683,
"author_profile": "https://Stackoverflow.com/users/20350683",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SUBSTRING(CONVERT(varbinary,Addr1 ) ,1,1) as Expr1\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/244/"
] |
I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral
Here is the select I am using now:
```
SELECT SomeStringColumn from SomeTable
```
Here is the select I would like to use:
SELECT hex( SomeStringColumn ) from SomeTable
Unfortunately nothing is that simple... Informix gives me that message:
*Character to numeric conversion error*
Any idea?
|
Can you use Cast and the fn\_varbintohexstr?
```
SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary))
FROM SomeTable
```
I'm not sure if you have that function in your database system, it is in MS-SQL.
I just tried it in my SQL server MMC on one of my tables:
```
SELECT master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
```
This worked as expected. possibly what I know as master.dbo.fn\_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:
```
SELECT hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
```
|
219,285 |
<p>Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files we write ourselves. How do you manage them all? How do you minify them in an organized way? </p>
|
[
{
"answer_id": 219309,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 2,
"selected": false,
"text": "<p>First of all, <a href=\"http://developer.yahoo.com/yui/compressor/\" rel=\"nofollow noreferrer\"><strong>YUI Compressor</strong></a>.</p>\n\n<p>Keeping them organized is up to you, but most groups that I've seen have just <strong>come up with a convention</strong> that makes sense for their application.</p>\n\n<p>It's generally optimal to <strong>package up your files</strong> in such a way that you have a small handful of packages which can be included on any given page for optimal caching.</p>\n\n<p>You also might consider dividing your javascript up into segments that are <strong>easy to share</strong> across the team.</p>\n"
},
{
"answer_id": 219333,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>I will have a folder for all javascript, and a sub folder of that for 3rd party/shared libraries, and sub folders for each component of the site to keep everything organized.</p>\n\n<p>For example:</p>\n\n<pre><code>/\n+--/javascript/\n +-- lib/\n +-- admin/\n +-- compnent1/\n +-- compnent2/\n</code></pre>\n\n<p>Then run everything through a minifier/obfuscator during the build process.</p>\n"
},
{
"answer_id": 219339,
"author": "Ericko",
"author_id": 1620279,
"author_profile": "https://Stackoverflow.com/users/1620279",
"pm_score": 0,
"selected": false,
"text": "<p>I'v been using this lately:\n<a href=\"http://code.google.com/apis/ajaxlibs/\" rel=\"nofollow noreferrer\">http://code.google.com/apis/ajaxlibs/</a></p>\n\n<p>And then have a \"jscripts\" folder where I keep my custom code. </p>\n"
},
{
"answer_id": 219348,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Organization</strong></p>\n\n<p>All of my scripts are maintained in a directory structure that I follow whenever I work on a site. The directory structure normally goes something like this:</p>\n\n<pre><code>+--root\n |--javascript\n |--lib\n |--prototype.js\n |--scriptaculous\n |--scriptaculous.js\n |--effects.js\n |--..\n |--myOwnScript.js\n |--myOwnScript2.js\n</code></pre>\n\n<p>If, on the off chance, that I'm working on a team uses an inordinate amount of scripts, then I'll normally create a <em>custom</em> directory in which we'll organize scripts by relationship. This doesn't happen terribly often, though.</p>\n\n<p><strong>Compression</strong></p>\n\n<p>Though there are a lot of different compressors and obfuscators out there, I always come back to <a href=\"http://developer.yahoo.com/yui/compressor/\" rel=\"noreferrer\">YUI Compressor.</a></p>\n\n<p><strong>Inclusion</strong></p>\n\n<p>Unless a site is using some form of a master page, CMS, or something that dictates what can be included on a page beyond my control, I only included the scripts necessarily <em>for the given page</em> just for the small performance sake. If a page doesn't require any script, there will be no script inclusions on that page.</p>\n"
},
{
"answer_id": 219462,
"author": "schonarth",
"author_id": 22116,
"author_profile": "https://Stackoverflow.com/users/22116",
"pm_score": 0,
"selected": false,
"text": "<p>In my last project, we had three kinds of JS files, all of them inside a JS folder.</p>\n\n<ol>\n<li><strong>Library code</strong>. A bunch of functions used on most all of the pages, so they were put together in one or a few files.</li>\n<li><strong>Classes</strong>. These had their own files, organized in folders as needed, but not necessarily so.</li>\n<li><strong>Ad hoc JS</strong>. Code that was specific to that page. These were saved in files that had the same name as the JSP pages they were supposed to run in.</li>\n</ol>\n\n<p>The biggest effort was in having most of the code on the first two kinds, having custom code only know what to call, and when.</p>\n"
},
{
"answer_id": 219539,
"author": "VirtuosiMedia",
"author_id": 13281,
"author_profile": "https://Stackoverflow.com/users/13281",
"pm_score": 0,
"selected": false,
"text": "<p>This might be a different approach than what you're looking for, but I've been playing around with the idea of JavaScript templates in our blog engine. In a nutshell, you assign a Javascript template to a page id using the database and it will dynamically include and minify all the JavaScript files associated with that template and create a file in a server-side cache with the template id as a file name. When a page is loaded, it calls the template file which first checks if the file exists in the cache and loads it if it does. If it doesn't exist, it creates it on the fly and includes it. I also use the template file to gzip the conglomerate JavaScript file. </p>\n\n<p>The template idea would work well for site-wide JavaScript (like a JavaScript library), but it doesn't cover page-specific JavaScript. However, you can still use the same approach for page specific JavaScript by including a second file that does the same as above.</p>\n"
},
{
"answer_id": 219700,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 2,
"selected": false,
"text": "<p>Cal Henderson (of Flickr fame) wrote <a href=\"http://www.thinkvitamin.com/features/webapps/serving-javascript-fast\" rel=\"nofollow noreferrer\">Serving JavaScript Fast</a> a while back. It covers asset delivery, not organization, but it might answer some of your questions.</p>\n\n<p>Here are the bullet points:</p>\n\n<ul>\n<li>Yes, you ought to concatenate JavaScript files in production to minimize the number of HTTP requests.</li>\n<li>BUT you might not want to concatenate into one giant file; you might want to break it into logical pieces and spread the transfer cost over several pages.</li>\n<li>gzip compression is good, but you shouldn't serve gzipped assets to IE <= 6, so you might also want to minify/compress your JavaScript.</li>\n</ul>\n\n<p>I'll add a few bullet points of my own:</p>\n\n<ul>\n<li>You ought to come up with a solution that works for both development and production. In development mode, it should pull in extra JavaScript files on demand; in production it should bundle everything ahead of time. Switching from one behavior to the other should be as easy as setting a flag.</li>\n<li>Rails 2.0 handles all this through an <a href=\"http://maintainable.com/articles/rails_asset_cache\" rel=\"nofollow noreferrer\">asset cache</a>; other web app frameworks might offer similar solutions.</li>\n<li>As another answer suggests, placing third-party libraries in a <code>lib</code> directory is a good start. You can also divide your own JS files into sub-directories if it makes sense. Ideally, you'll be able to arrange them in such a way that the files in a given sub-directory can be concatenated into one file.</li>\n</ul>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files we write ourselves. How do you manage them all? How do you minify them in an organized way?
|
**Organization**
All of my scripts are maintained in a directory structure that I follow whenever I work on a site. The directory structure normally goes something like this:
```
+--root
|--javascript
|--lib
|--prototype.js
|--scriptaculous
|--scriptaculous.js
|--effects.js
|--..
|--myOwnScript.js
|--myOwnScript2.js
```
If, on the off chance, that I'm working on a team uses an inordinate amount of scripts, then I'll normally create a *custom* directory in which we'll organize scripts by relationship. This doesn't happen terribly often, though.
**Compression**
Though there are a lot of different compressors and obfuscators out there, I always come back to [YUI Compressor.](http://developer.yahoo.com/yui/compressor/)
**Inclusion**
Unless a site is using some form of a master page, CMS, or something that dictates what can be included on a page beyond my control, I only included the scripts necessarily *for the given page* just for the small performance sake. If a page doesn't require any script, there will be no script inclusions on that page.
|
219,323 |
<p>Here is a stripped down version of what I use to authenticate users, it works fine on my PHP v5.0.2/MySQL 4.0.21 server, but fails on my PHP v5.1.6/MySQL v5.0.45 server.</p>
<p>In the code below, should I be aware of anything that might not be supported by the newer version of PHP & MySQL? Global variables have been enabled.</p>
<pre><code><?php
if(!isset($HTTP_POST_VARS['username'])&&!isset($HTTP_POST_VARS['password']))
{
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.
<form method="post" action="<?php echo $PHP_SELF;?>">
<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="username"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php
}
else
{
// connect to mysql
include('../cgi-bin/db.php');
$username = $HTTP_POST_VARS['username'];
$password = md5($HTTP_POST_VARS['password']);
if(!$db)
{
echo 'Cannot connect to database.';
exit;
}
// select the appropriate database
$mysql = mysql_select_db('quickwebcms');
if(!$mysql)
{
echo 'Cannot select database.';
exit;
}
// query the database to see if there is a record which matches
$query = "select count(*) from auth where
username = '$username' and
password = '$password'";
$result = mysql_query( $query );
if(!$result)
{
echo 'Cannot run query.';
exit;
}
$count = mysql_result( $result, 0, 0 );
if ( $count > 0 )
{
// visitor's name and password combination are correct
echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
}
else
{
// visitor's name and password combination are not correct
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
}
?>
</code></pre>
|
[
{
"answer_id": 219341,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 3,
"selected": true,
"text": "<p>I'm guessing it might be because of <code>$HTTP_POST_VARS</code>. Try replacing that with <code>$_POST</code>. If it still doesn't work, try putting the following snippet right after <code><?php</code>:</p>\n\n<pre>\n<code>// Enable displaying errors\nerror_reporting(E_ALL);\nini_set('display_errors', '1');\n</code></pre>\n"
},
{
"answer_id": 219354,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 2,
"selected": false,
"text": "<p>Try setting <a href=\"http://www.php.net/manual/en/ini.core.php#ini.register-long-arrays\" rel=\"nofollow noreferrer\">register_long_arrays</a> = On in php.ini and see if that fixes your issues. </p>\n\n<p>On another note you shouldn't be building your queries up like that. Look into using <a href=\"http://www.php.net/mysql_real_escape_string\" rel=\"nofollow noreferrer\">PHP MySQL escaping</a>.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
Here is a stripped down version of what I use to authenticate users, it works fine on my PHP v5.0.2/MySQL 4.0.21 server, but fails on my PHP v5.1.6/MySQL v5.0.45 server.
In the code below, should I be aware of anything that might not be supported by the newer version of PHP & MySQL? Global variables have been enabled.
```
<?php
if(!isset($HTTP_POST_VARS['username'])&&!isset($HTTP_POST_VARS['password']))
{
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.
<form method="post" action="<?php echo $PHP_SELF;?>">
<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="username"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php
}
else
{
// connect to mysql
include('../cgi-bin/db.php');
$username = $HTTP_POST_VARS['username'];
$password = md5($HTTP_POST_VARS['password']);
if(!$db)
{
echo 'Cannot connect to database.';
exit;
}
// select the appropriate database
$mysql = mysql_select_db('quickwebcms');
if(!$mysql)
{
echo 'Cannot select database.';
exit;
}
// query the database to see if there is a record which matches
$query = "select count(*) from auth where
username = '$username' and
password = '$password'";
$result = mysql_query( $query );
if(!$result)
{
echo 'Cannot run query.';
exit;
}
$count = mysql_result( $result, 0, 0 );
if ( $count > 0 )
{
// visitor's name and password combination are correct
echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
}
else
{
// visitor's name and password combination are not correct
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
}
?>
```
|
I'm guessing it might be because of `$HTTP_POST_VARS`. Try replacing that with `$_POST`. If it still doesn't work, try putting the following snippet right after `<?php`:
```
// Enable displaying errors
error_reporting(E_ALL);
ini_set('display_errors', '1');
```
|
219,338 |
<p>I'm using JQuery's jquery.corner.js to create rounded corners on some td tags, and they look fine in IE EXCEPT </p>
<ol>
<li>if you open a new tab and then come back to the page</li>
<li>if you go to another tab, click a link, then come back to the page</li>
<li>if you hover over a javascript-executing div / menu (I think).</li>
</ol>
<p>The rounded corners are replaced with horizontal lines, and text within the td tag is pushed down. Once the page is refreshed, however, the rendering is back to normal. In all cases it works perfectly in Firefox.</p>
<p>Any ideas?</p>
<p>For reference, the Javascript code I'm using is as follows (it's a MOSS 2007 page):</p>
<pre><code>$(document).ready(function(){
$("table.ms-navheader td").corner("top");
});
</code></pre>
<p>Here's a sample HTML page that displays the problem perfectly:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="jquery.corner.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function()
{
$("div").corner("top");
$("td").corner();
});
//-->
</script>
</head>
<body>
<table>
<tr>
<td style="background-color: blue">
TD that will be messed up.
</td>
</tr>
</table>
<div style="background-color: green">
divs don't get messed up.
</div>
</body>
</html>
</code></pre>
<p>In the above code, the TD will be messed up once you open up a new tab, but not the div. I don't have much control over the HTML emitted by MOSS, otherwise I might have bitten the bullet and used DIVs here instead of a table.</p>
|
[
{
"answer_id": 219358,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 2,
"selected": false,
"text": "<p>I've had nothing but trouble with rounded corners Javascript libraries (especially with IE6 and 7)</p>\n\n<p>In the end I've reverted to more traditional approaches involving images. A bit more of a chore to setup, but works perfectly.</p>\n"
},
{
"answer_id": 219363,
"author": "Bryan A",
"author_id": 29707,
"author_profile": "https://Stackoverflow.com/users/29707",
"pm_score": 0,
"selected": false,
"text": "<p>It's a bit hard to visualize the issue you're having, a link would be really helpful. Make sure your height and width properties are defined for each cell of your table. It could potentially be a hasLayout issue.</p>\n"
},
{
"answer_id": 219376,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with RichH, I think that all of the popular JavaScript libraries leave something to be desired when trying to created rounded corners. </p>\n\n<p>I always find myself using cornershop: <a href=\"http://wigflip.com/cornershop/\" rel=\"nofollow noreferrer\">http://wigflip.com/cornershop/</a>, it is an image / css generator that takes the pain out of making rounded edges manually. </p>\n"
},
{
"answer_id": 221356,
"author": "penderi",
"author_id": 32027,
"author_profile": "https://Stackoverflow.com/users/32027",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to try this plugin instead jquery.curvycorners.js.</p>\n\n<p>We use it on our project with no problem at all - you may need to append/prepend with spans but it's very straightforward. </p>\n\n<p>Best thing -> anti-aliased by default.</p>\n\n<p><a href=\"http://blue-anvil.com/jquerycurvycorners/test.html\" rel=\"nofollow noreferrer\">http://blue-anvil.com/jquerycurvycorners/test.html</a></p>\n"
},
{
"answer_id": 544095,
"author": "Bob Weber",
"author_id": 65810,
"author_profile": "https://Stackoverflow.com/users/65810",
"pm_score": 0,
"selected": false,
"text": "<p>I've searched and haven't found a solution to rounded corners in jquery UI tabs. The jquery themeroller supports rounded corners, but the documentation says they don't work in IE.</p>\n\n<p>Here is a good page with 25 different rounded corner methods\n<a href=\"http://www.cssjuice.com/25-rounded-corners-techniques-with-css/\" rel=\"nofollow noreferrer\">http://www.cssjuice.com/25-rounded-corners-techniques-with-css/</a></p>\n"
},
{
"answer_id": 950410,
"author": "Kris",
"author_id": 22237,
"author_profile": "https://Stackoverflow.com/users/22237",
"pm_score": 0,
"selected": false,
"text": "<p>I've had similar problems, even in firefox, I found that if you apply 'corners' to a element which has a class which sets a background color the corners never get applied. In my case I add a class called 'selected' which gives a different background colour to the selected 'tab' in a UL. To prevent this I apply the background colour using js instead of css after I have added the corners:</p>\n\n<pre><code>$('.selected').css('background-color', '#3296C0');\n</code></pre>\n\n<p>Also it you add a :hover which changes the background colour the corners are squared back off on hover. The solution I have so far is to use a onhover event which reapply the corners (you could set the color here as well). </p>\n\n<pre><code> $('#top-nav li a').hover(function(){\n $(this).corners('top');\n });\n</code></pre>\n\n<p>As for IE6 - a nightmare - it would not be so bad if I could detect IE6 and just not add corners leaving them squared. Not even tried IE 7 yet...</p>\n"
},
{
"answer_id": 1443711,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 3,
"selected": false,
"text": "<p>In IE I had better results with the <em><a href=\"http://www.filamentgroup.com/lab/achieving_rounded_corners_in_internet_explorer_for_jquery_ui_with_dd_roundi/\" rel=\"nofollow noreferrer\">DD_Roundies</a></em> library. Only works in IE though. For Firefox you need to add -moz-border-radius styles.</p>\n"
},
{
"answer_id": 2897264,
"author": "Gafroninja",
"author_id": 348982,
"author_profile": "https://Stackoverflow.com/users/348982",
"pm_score": 2,
"selected": false,
"text": "<p>curvycorners.js and jquery.curvycorners.js only work if you don't want to use any transitions.</p>\n\n<p>if you have an accordion or fade in/out tab effect, the element with the rounded corners doesn't render correctly after change.</p>\n"
},
{
"answer_id": 6011575,
"author": "Ozioma",
"author_id": 754882,
"author_profile": "https://Stackoverflow.com/users/754882",
"pm_score": 1,
"selected": false,
"text": "<p>to make jquery curvy corners work in IE simply give the element a background color. \nNo sure why it's so...just works like magic!</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1943/"
] |
I'm using JQuery's jquery.corner.js to create rounded corners on some td tags, and they look fine in IE EXCEPT
1. if you open a new tab and then come back to the page
2. if you go to another tab, click a link, then come back to the page
3. if you hover over a javascript-executing div / menu (I think).
The rounded corners are replaced with horizontal lines, and text within the td tag is pushed down. Once the page is refreshed, however, the rendering is back to normal. In all cases it works perfectly in Firefox.
Any ideas?
For reference, the Javascript code I'm using is as follows (it's a MOSS 2007 page):
```
$(document).ready(function(){
$("table.ms-navheader td").corner("top");
});
```
Here's a sample HTML page that displays the problem perfectly:
```
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="jquery.corner.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function()
{
$("div").corner("top");
$("td").corner();
});
//-->
</script>
</head>
<body>
<table>
<tr>
<td style="background-color: blue">
TD that will be messed up.
</td>
</tr>
</table>
<div style="background-color: green">
divs don't get messed up.
</div>
</body>
</html>
```
In the above code, the TD will be messed up once you open up a new tab, but not the div. I don't have much control over the HTML emitted by MOSS, otherwise I might have bitten the bullet and used DIVs here instead of a table.
|
In IE I had better results with the *[DD\_Roundies](http://www.filamentgroup.com/lab/achieving_rounded_corners_in_internet_explorer_for_jquery_ui_with_dd_roundi/)* library. Only works in IE though. For Firefox you need to add -moz-border-radius styles.
|
219,360 |
<p>I've got a unfinished project that a developer just didn't finish and didn't leave any documentation about the installation process. I've downloaded the production directory to my windows machine (running InstantRails 2), I created the databases as required in the <code>database.yml</code> and I tried to run the <code>rake:db:migrate --trace</code> but I'm receiving the following error message:</p>
<pre><code>(in D:/projects/broke2)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
rake aborted!
uninitialized constant Admin
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:279:in `load_missing_constant'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:468:in `const_missing'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:480:in `const_missing'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:285:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/string/inflections.rb:143:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:481:in `migrations'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/mysql_adapter.rb:15:in `inject'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `inject'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `migrations'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:431:in `migrate'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain'
D:/InstantRails-2.0-win/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31
D:/InstantRails-2.0-win/ruby/bin/rake:19:in `load'
D:/InstantRails-2.0-win/ruby/bin/rake:19
</code></pre>
<p>I'm a regular Rails developer (it's not my first app) but I never saw this error and I don't have a clue where to start to debug.</p>
|
[
{
"answer_id": 219383,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say your problem is in the <code>uninitialized constant Admin</code> part of your migration issue. Have you tried finding where Admin is initialized and including the path to that wherever you're using it? (Also, what's the contents of the rake task you're running?)</p>\n"
},
{
"answer_id": 219397,
"author": "Luke Francl",
"author_id": 17965,
"author_profile": "https://Stackoverflow.com/users/17965",
"pm_score": 3,
"selected": true,
"text": "<p>Sometimes Rails will throw this error if there's a syntax error where Admin is defined.</p>\n\n<p>Try looking for admin.rb and make sure that it parses.</p>\n\n<p>Also, you may want to try running the migrations one at a time (<code>rake db:migrate VERSION=1</code>, etc.) to see if that helps you track down which migration causes the error, or if it is a problem simply booting the application.</p>\n"
},
{
"answer_id": 219436,
"author": "VP.",
"author_id": 18642,
"author_profile": "https://Stackoverflow.com/users/18642",
"pm_score": 0,
"selected": false,
"text": "<p>It don't points me where i have a Admin constant. There is a way to check at least where should I look? my models, my controllers, etc?</p>\n\n<p>rake db:migrate VERSION=1, gives me a error already. As I told you, am I just trying to finish a project unfinished by another guy.</p>\n\n<p>How can i do a migration file per file?</p>\n\n<p>Regards,</p>\n\n<p>Victor</p>\n"
},
{
"answer_id": 222654,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect you had a migration that created a table and added some data using a model. Later in the project the model got renamed or removed (as did the table maybe?). As the model no longer existed the migrations failed to run, but no one noticed as by that point they were only running a few migrations at a time, not from a clean database.</p>\n\n<p>The lesson here ... if you rename models or tables (or update their validations and fields) then check your migrations run from scratch as well on the current production version.</p>\n"
},
{
"answer_id": 222914,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can try loading the schema all at once instead of executing each migration:</p>\n\n<p>rake db:schema:load</p>\n\n<p>As RichH said there might have been a change to the schema not reflected in the migrations</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
I've got a unfinished project that a developer just didn't finish and didn't leave any documentation about the installation process. I've downloaded the production directory to my windows machine (running InstantRails 2), I created the databases as required in the `database.yml` and I tried to run the `rake:db:migrate --trace` but I'm receiving the following error message:
```
(in D:/projects/broke2)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
rake aborted!
uninitialized constant Admin
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:279:in `load_missing_constant'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:468:in `const_missing'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:480:in `const_missing'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:285:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/string/inflections.rb:143:in `constantize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:481:in `migrations'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/mysql_adapter.rb:15:in `inject'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `inject'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `migrations'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:431:in `migrate'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain'
D:/InstantRails-2.0-win/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run'
D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31
D:/InstantRails-2.0-win/ruby/bin/rake:19:in `load'
D:/InstantRails-2.0-win/ruby/bin/rake:19
```
I'm a regular Rails developer (it's not my first app) but I never saw this error and I don't have a clue where to start to debug.
|
Sometimes Rails will throw this error if there's a syntax error where Admin is defined.
Try looking for admin.rb and make sure that it parses.
Also, you may want to try running the migrations one at a time (`rake db:migrate VERSION=1`, etc.) to see if that helps you track down which migration causes the error, or if it is a problem simply booting the application.
|
219,368 |
<p>I got a little problem I can't figure out. I have a server side MarshalByRefObject that I'm trying to wrap a transparent proxy around on the client side. Here's the setup:</p>
<pre><code>public class ClientProgram {
public static void Main( string[] args ) {
ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
test = (ITest)new MyProxy( test ).GetTransparentProxy();
test.Foo();
}
}
public class MyProxy : RealProxy {
private MarshalByRefObject _object;
public MyProxy( ITest pInstance )
: base( pInstance.GetType() ) {
_object = (MarshalByRefObject)pInstance;
}
public override IMessage Invoke( IMessage msg ) {
return RemotingServices.ExecuteMessage( _object, (IMethodCallMessage)msg );
}
}
</code></pre>
<p>The problem is that the call to RemotingServices.ExecuteMethod, an exception is thrown with the message "ExecuteMessage can be called only from the native context of the object.". Can anyone point out how to get this to work correctly? I need to inject some code before and after the method calls on remote objects. Cheers!</p>
|
[
{
"answer_id": 219442,
"author": "bh213",
"author_id": 28912,
"author_profile": "https://Stackoverflow.com/users/28912",
"pm_score": 0,
"selected": false,
"text": "<p>I did that a while ago and forgot exact procedure, but try using RemotingServices.GetRealProxy to get proxy from <em>test</em> object and pass this into your MyProxy and call invoke on it.</p>\n\n<p>Something like this:</p>\n\n<pre><code>ITest test = (ITest)Activator.GetObject( typeof( ITest ), \"http://127.0.0.1:8765/Test.rem\" );\nRealProxy p2 = RemotingServices.GetRealProxy(test)\ntest = (ITest)new MyProxy( p2 ).GetTransparentProxy();\ntest.Foo();\n</code></pre>\n\n<p>You'll have to update MyProxy class to work with RealProxy insted of direct class</p>\n"
},
{
"answer_id": 219531,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Got it. your comment put me on the right track. The key is to unwrap the proxy and call invoke on it. THANK YOU!!!!!</p>\n\n<pre><code>public class ClientProgram {\n public static void Main( string[] args ) {\n ITest test = (ITest)Activator.GetObject( typeof( ITest ), \"http://127.0.0.1:8765/Test.rem\" );\n ITest test2 = (ITest)new MyProxy( test ).GetTransparentProxy();\n test2.Foo();\n }\n }\n\npublic class MyProxy : RealProxy {\n\n private object _obj;\n\n public MyProxy( object pObj )\n : base( typeof( ITest ) ) {\n _obj = pObj;\n }\n\n public override IMessage Invoke( IMessage msg ) {\n RealProxy rp = RemotingServices.GetRealProxy( _obj );\n return rp.Invoke( msg );\n }\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I got a little problem I can't figure out. I have a server side MarshalByRefObject that I'm trying to wrap a transparent proxy around on the client side. Here's the setup:
```
public class ClientProgram {
public static void Main( string[] args ) {
ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
test = (ITest)new MyProxy( test ).GetTransparentProxy();
test.Foo();
}
}
public class MyProxy : RealProxy {
private MarshalByRefObject _object;
public MyProxy( ITest pInstance )
: base( pInstance.GetType() ) {
_object = (MarshalByRefObject)pInstance;
}
public override IMessage Invoke( IMessage msg ) {
return RemotingServices.ExecuteMessage( _object, (IMethodCallMessage)msg );
}
}
```
The problem is that the call to RemotingServices.ExecuteMethod, an exception is thrown with the message "ExecuteMessage can be called only from the native context of the object.". Can anyone point out how to get this to work correctly? I need to inject some code before and after the method calls on remote objects. Cheers!
|
Got it. your comment put me on the right track. The key is to unwrap the proxy and call invoke on it. THANK YOU!!!!!
```
public class ClientProgram {
public static void Main( string[] args ) {
ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
ITest test2 = (ITest)new MyProxy( test ).GetTransparentProxy();
test2.Foo();
}
}
public class MyProxy : RealProxy {
private object _obj;
public MyProxy( object pObj )
: base( typeof( ITest ) ) {
_obj = pObj;
}
public override IMessage Invoke( IMessage msg ) {
RealProxy rp = RemotingServices.GetRealProxy( _obj );
return rp.Invoke( msg );
}
}
```
|
219,369 |
<p>I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem? </p>
<pre><code><ListView
x:Name="TechSchoolListView"
ClipToBounds="False"
Width="Auto" Height="Auto"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Top"
ItemTemplate="{DynamicResource TechSchoolDataTemplate}"
ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}"
SelectedIndex="1"
SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}"
SelectionChanged="TechSchoolList_SelectionChanged"
ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}"
ScrollViewer.CanContentScroll="False"
ScrollViewer.VerticalScrollBarVisibility="Disabled" >
<ListView.Background>
<SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/>
</ListView.Background>
</ListView>
</code></pre>
|
[
{
"answer_id": 219448,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": true,
"text": "<p>You should use <a href=\"http://msdn.microsoft.com/en-us/library/aa346420.aspx\" rel=\"nofollow noreferrer\">ContainerFromElement</a> to get the item's container, which is a visual and from there you can get the coordinates. You can't express this in XAML, however. You need to do it in code, on one of the ListView events, raised when the selected item is changed. Btw, keep in mind that the item can be its own container.</p>\n\n<p>You can't do this in XAML, as there's no attached property on the item that shows the item is selected. (though I haven't played with WPF in a while, so that might have changed)</p>\n"
},
{
"answer_id": 219450,
"author": "ChaosSpeeder",
"author_id": 205962,
"author_profile": "https://Stackoverflow.com/users/205962",
"pm_score": 2,
"selected": false,
"text": "<p>Now I have found a solution by myself. I have searched for a simple property, but it made no sense, because all UI Elements in the WPF are relative.</p>\n\n<p>This code seems to be working:</p>\n\n<pre><code> UIElement selectedContainer = (UIElement) TechSchoolListView.ItemContainerGenerator.ContainerFromIndex(TechSchoolListView.SelectedIndex);\n Point cursorPos = selectedContainer.TranslatePoint(new Point(selectedContainer.DesiredSize.Width, 0.0), Page);\n PanelCursor.Height = selectedContainer.DesiredSize.Height;\n PanelCursor.Margin = new Thickness(400, cursorPos.Y, 0.0, 0.0);\n</code></pre>\n"
},
{
"answer_id": 68728584,
"author": "PWCoder",
"author_id": 14960250,
"author_profile": "https://Stackoverflow.com/users/14960250",
"pm_score": 0,
"selected": false,
"text": "<p>Although Franci Penov's answer is correct I would like to give a code sample to show how what he was saying worked for me.</p>\n<pre><code>UIElement selectedContainer = (UIElement)(sender as \nListView).ItemContainerGenerator.ContainerFromIndex((sender as \nListView).SelectedIndex);\nPoint startPoint = selectedContainer.PointToScreen(new Point(0,0));\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205962/"
] |
I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem?
```
<ListView
x:Name="TechSchoolListView"
ClipToBounds="False"
Width="Auto" Height="Auto"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Top"
ItemTemplate="{DynamicResource TechSchoolDataTemplate}"
ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}"
SelectedIndex="1"
SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}"
SelectionChanged="TechSchoolList_SelectionChanged"
ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}"
ScrollViewer.CanContentScroll="False"
ScrollViewer.VerticalScrollBarVisibility="Disabled" >
<ListView.Background>
<SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/>
</ListView.Background>
</ListView>
```
|
You should use [ContainerFromElement](http://msdn.microsoft.com/en-us/library/aa346420.aspx) to get the item's container, which is a visual and from there you can get the coordinates. You can't express this in XAML, however. You need to do it in code, on one of the ListView events, raised when the selected item is changed. Btw, keep in mind that the item can be its own container.
You can't do this in XAML, as there's no attached property on the item that shows the item is selected. (though I haven't played with WPF in a while, so that might have changed)
|
219,396 |
<p>I'm writing a mobile content adaptation plugin for a bespoke CMS in PHP. The CMS contains <code><img/></code> links to images with absolute URLs which are all 400 pixels wide and vary in height.</p>
<p>I'd like to parse the HTML (which is stored in MySQL) and re-scale each image to a new width - this will vary according to the device. I'd also like to cache the images to prevent needlessly resizing them on-the-fly every time the page is loaded</p>
<p>What's the best way for me to achieve this in PHP using either ImageMagick or GD? </p>
|
[
{
"answer_id": 219407,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p>what about doing something a bit different. basically off load the caching/resizing to an on demand model. so say your application is being run on device A, which requires 200x200 images. you'd change the image links to:</p>\n\n<pre><code><img src=\"/images/image.php?height=200&width=200&source=filename.jpg\" />\n</code></pre>\n\n<p>image.php could be a script which does the following:</p>\n\n<ul>\n<li>make sure the existing file exists, and grab it from cache if it exists at this size</li>\n<li>if not, resize the image and cache it</li>\n</ul>\n\n<p>the next time your app looks for that image, it would be sent back at the 200px size. alternatively, if the app is now looking for a 300x300 image, that would be built/cached on the new request.</p>\n"
},
{
"answer_id": 219459,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>SEE\n<a href=\"https://stackoverflow.com/questions/140734/best-way-to-cache-resized-images-using-php-and-mysql\">Best way to cache resized images using PHP and MySQL</a><br>\nfor really good ideas on caching mechanism (especially apache webserver intervention concept)</p>\n\n<p>and</p>\n\n<p><a href=\"http://phpthumb.sourceforge.net/\" rel=\"nofollow noreferrer\">http://phpthumb.sourceforge.net/</a> which encapsulates using both/either ImageMagick or GD.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm writing a mobile content adaptation plugin for a bespoke CMS in PHP. The CMS contains `<img/>` links to images with absolute URLs which are all 400 pixels wide and vary in height.
I'd like to parse the HTML (which is stored in MySQL) and re-scale each image to a new width - this will vary according to the device. I'd also like to cache the images to prevent needlessly resizing them on-the-fly every time the page is loaded
What's the best way for me to achieve this in PHP using either ImageMagick or GD?
|
what about doing something a bit different. basically off load the caching/resizing to an on demand model. so say your application is being run on device A, which requires 200x200 images. you'd change the image links to:
```
<img src="/images/image.php?height=200&width=200&source=filename.jpg" />
```
image.php could be a script which does the following:
* make sure the existing file exists, and grab it from cache if it exists at this size
* if not, resize the image and cache it
the next time your app looks for that image, it would be sent back at the 200px size. alternatively, if the app is now looking for a 300x300 image, that would be built/cached on the new request.
|
219,402 |
<p>I want to find a linux command that can return a part of the string. In most programming languages, it's the <code>substr()</code> function. Does bash have any command that can be used for this purpose. I want to be able to do something like this...
<code>substr "abcdefg" 2 3</code> - prints <code>cde</code>.</p>
<hr>
<p>Subsequent similar question:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/428109/extract-substring-in-bash">Extract substring in Bash</a></li>
</ul>
|
[
{
"answer_id": 219409,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 7,
"selected": false,
"text": "<p>From the bash manpage:</p>\n\n<pre><code>${parameter:offset}\n${parameter:offset:length}\n Substring Expansion. Expands to up to length characters of\n parameter starting at the character specified by offset.\n[...]\n</code></pre>\n\n<hr>\n\n<p>Or, if you are not sure of having <code>bash</code>, consider using <code>cut</code>.</p>\n"
},
{
"answer_id": 219416,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 5,
"selected": false,
"text": "<p>In bash you can try this:</p>\n\n<pre><code>stringZ=abcABC123ABCabc\n# 0123456789.....\n# 0-based indexing.\n\necho ${stringZ:0:2} # prints ab\n</code></pre>\n\n<p>More samples in <a href=\"http://tldp.org/LDP/abs/html/string-manipulation.html\" rel=\"noreferrer\" title=\"here\">The Linux Documentation Project</a> </p>\n"
},
{
"answer_id": 219418,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<pre><code>${string:position:length}\n</code></pre>\n"
},
{
"answer_id": 219427,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 9,
"selected": true,
"text": "<p>If you are looking for a shell utility to do something like that, you can use the <code>cut</code> command.</p>\n\n<p>To take your example, try:</p>\n\n<pre><code>echo \"abcdefg\" | cut -c3-5\n</code></pre>\n\n<p>which yields</p>\n\n<pre><code>cde\n</code></pre>\n\n<p>Where <code>-cN-M</code> tells the cut command to return columns <code>N</code> to <code>M</code>, inclusive.</p>\n"
},
{
"answer_id": 220464,
"author": "camh",
"author_id": 23744,
"author_profile": "https://Stackoverflow.com/users/23744",
"pm_score": 4,
"selected": false,
"text": "<p><code>expr(1)</code> has a substr subcommand:</p>\n\n<pre><code>expr substr <string> <start-index> <length>\n</code></pre>\n\n<p>This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra \"echo\" process you need to use cut(1).</p>\n"
},
{
"answer_id": 8107620,
"author": "ata",
"author_id": 378193,
"author_profile": "https://Stackoverflow.com/users/378193",
"pm_score": 5,
"selected": false,
"text": "<p>In \"pure\" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in <a href=\"http://linux.die.net/man/1/bash\" rel=\"noreferrer\">parameter expansion</a> :</p>\n\n<pre><code>${parameter//substring/replacement}\n${parameter##remove_matching_prefix}\n${parameter%%remove_matching_suffix}\n</code></pre>\n\n<p>Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):</p>\n\n<pre><code>${parameter:offset}\n${parameter:offset:length}\n${parameter:offset:length}\n</code></pre>\n\n<p>And of course, the much useful expansions that operate on whether the parameter is null:</p>\n\n<pre><code>${parameter:+use this if param is NOT null}\n${parameter:-use this if param is null}\n${parameter:=use this and assign to param if param is null}\n${parameter:?show this error if param is null}\n</code></pre>\n\n<p>They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being <code>$(command substitution)</code> combined with sed or any other external filter). But, they are so easily found by typing <code>man bash</code> that I don't feel it merits to further extend this post.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15595/"
] |
I want to find a linux command that can return a part of the string. In most programming languages, it's the `substr()` function. Does bash have any command that can be used for this purpose. I want to be able to do something like this...
`substr "abcdefg" 2 3` - prints `cde`.
---
Subsequent similar question:
* [Extract substring in Bash](https://stackoverflow.com/questions/428109/extract-substring-in-bash)
|
If you are looking for a shell utility to do something like that, you can use the `cut` command.
To take your example, try:
```
echo "abcdefg" | cut -c3-5
```
which yields
```
cde
```
Where `-cN-M` tells the cut command to return columns `N` to `M`, inclusive.
|
219,420 |
<p>Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:</p>
<pre><code>char * reverse(const char * str)
{
int length = strlen(str);
char * reversed_string = new char[length+1];
for(int i = 0; i < length; ++i)
{
reversed_string[i] = str[(length-1) - i];
}
//need to null terminate the string
reversed_string[length] = '\0';
return reversed_string;
}
int main(int argc, char * argv[])
{
char * rev_str = reverse("Testing");
cout << "Your string reversed is this: " << rev_str << endl;
delete rev_str;
rev_str = 0;
return 0;
}
</code></pre>
|
[
{
"answer_id": 219432,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 4,
"selected": false,
"text": "<p>I had this question once. That's the first answer that comes to mind, but the follow-up is, \"now do it without allocating any memory.\"</p>\n\n<pre><code>int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n char c = string[i];\n string[i] = string[length - i];\n string[length - i] = c;\n}\n</code></pre>\n\n<p>EDIT: Some folks have expressed disdain for not using pointers. This is a tiny bit more readable, though not completely optimal. Others have entered the pointer solution, so I won't repeat it here.</p>\n\n<p>One commenter challenged that it should be doable without a (stack based) holding cell for the swap. The mechanism for doing that is bitwise XOR. Replace the inside of the loop with</p>\n\n<pre><code>string[i] = string[i] ^ string[length - i];\nstring[length - i] = string[i] ^ string[length - i];\nstring[i] = string[i] ^ string[length - i];\n</code></pre>\n\n<p>But in general, modern compilers can optimize out the local variable of a naive swap. For details, <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"noreferrer\">See Wikipedia</a></p>\n"
},
{
"answer_id": 219447,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "<p>this works nicely:</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <cstring>\n\nvoid reverse_string(char *str) { \n char *end = str + strlen(str) - 1;\n while (str < end) {\n std::iter_swap(str++, end--);\n }\n}\n\nint main() {\n char s[] = \"this is a test\";\n reverse_string(s);\n std::cout << \"[\" << s << \"]\" << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 219449,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 3,
"selected": false,
"text": "<pre><code>if( string[0] )\n{\n char *end = string + strlen(string)-1;\n while( start < end )\n {\n char temp = *string;\n *string++ = *end;\n *end-- = temp;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 219455,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://cppreference.com/wiki/stl/algorithm/reverse\" rel=\"noreferrer\"><code>std::reverse</code></a> from <code><algorithm></code> works for strings and <code>char</code> arrays:</p>\n\n<pre><code>string str = \"Hello\";\nchar chx[] = \"Hello\";\n\nreverse(str.begin(), str.end());\nreverse(chx, chx + strlen(chx));\n\ncout << str << endl;\ncout << chx << endl;\n</code></pre>\n\n<p>/EDIT: This, of course, modifies the original string. But STL to the rescue. The following creates a new reversed string. Unfortunately (?), this doesn't work directly on C <code>char</code> arrays without creating an additional (implicit) copy:</p>\n\n<pre><code>string reverse_string(string const& old) {\n return string(old.rbegin(), old.rend());\n}\n\ncout << reverse_string(\"Hello\") << endl;\n</code></pre>\n"
},
{
"answer_id": 219478,
"author": "Adam Ness",
"author_id": 21973,
"author_profile": "https://Stackoverflow.com/users/21973",
"pm_score": 0,
"selected": false,
"text": "<p>I would have solved it sort of like this (my c is a bit rusty though, forgive me)</p>\n\n<pre><code>char *reverse( const char *source ) {\n int len = strlen( source );\n char *dest = new char[ len + 1 ];\n int i = 0;\n int j = len;\n while( j > 0 ) {\n dest[j--] = src[i++];\n }\n dest[i] = \\0;\n return dest;\n}\n</code></pre>\n"
},
{
"answer_id": 219486,
"author": "Sol",
"author_id": 27029,
"author_profile": "https://Stackoverflow.com/users/27029",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, given the constraint that the original string be left unmodified, I think the original approach given in the question is the best. All these fancy approaches to reversing in place people are posting are great, but once copying the given string is factored in, they are all less efficient than simply copying the string backwards.</p>\n"
},
{
"answer_id": 219505,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "<p>We've used this question before -- with the surprisingly results of finding a lot of people that can't do it (even with significant C/C++ experience!). I prefer the in-place variant since it saves some overhead, and has the added twist of only needing to iterate over strlen(s)/2 characters.</p>\n\n<p>Your solution in an interview would be fine. A (correct!) solution using pointer instead of array syntax would rate a bit higher since it shows a greater comfort level with pointers which are so critical in C/C++ programming.</p>\n\n<p>The minor critiques would be to point out that strlen returns a size_t not an int, and you should use delete [] on rev_str.</p>\n"
},
{
"answer_id": 219560,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 0,
"selected": false,
"text": "<p>It wouldn't be more efficient, but you could demonstrate knowledge of data structures by doing something like pushing each letter onto a stack, and then popping them off into your newly allocated buffer.</p>\n\n<p>It would take two passes and a scratch stack, but I would probably trust myself more to get this right the first time then to not make an off-by one error like the above.</p>\n\n<pre><code>char* stringReverse(const char* sInput)\n{\n std::size_t nLen = strlen(sInput);\n std::stack<char> charStack;\n for(std::size_t i = 0; i < nLen; ++i)\n {\n charStack.push(sInput[i]);\n }\n char * result = new char[nLen + 1];\n std::size_t counter = 0;\n while (!charStack.empty())\n {\n result[counter++] = charStack.top();\n charStack.pop();\n }\n result[counter] = '\\0';\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 219638,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 2,
"selected": false,
"text": "<p>Uh? No one did it with pointers?</p>\n\n<pre><code>char *reverse(const char *s) {\n size_t n = strlen(s);\n char *dest = new char[n + 1];\n char *d = (dest + n - 1);\n\n dest[n] = 0;\n while (*s) {\n *d-- = *s++\n }\n\n return dest;\n}\n</code></pre>\n\n<p>Hopefully years of Java haven't ruined my C ;-)</p>\n\n<p><strong><em>Edit</em></strong>: replaced all those strlen calls with an extra var. What does strlen return these days? (Thanks <a href=\"https://stackoverflow.com/users/20481/plinth\">plinth</a>).</p>\n"
},
{
"answer_id": 219673,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>Your code is straight forward and unsurprising. A few things:</p>\n\n<ol>\n<li>Use size_t instead of int for your loop index</li>\n<li>While your compiler is most likely smart enough to figure out that (length -1) is invariant, it's probably not smart enough to figure out that (length-1)-i is best replaced by a different loop variable that is decremented in each pass</li>\n<li>I'd use pointers instead of array syntax - it will look cleaner to me to have *dst-- = *src++; in the loop.</li>\n</ol>\n\n<p>In other words:</p>\n\n<pre><code>char *dst = reversed_string + length;\n*dst-- = '\\0';\nwhile (*src) {\n *dst-- = *src++;\n}\n</code></pre>\n"
},
{
"answer_id": 219864,
"author": "Adam Straughan",
"author_id": 14019,
"author_profile": "https://Stackoverflow.com/users/14019",
"pm_score": 0,
"selected": false,
"text": "<p>When asking this question as an interviewer, I am looking to a clean, understandable solution and may ask how the initial solution could be made more efficient. I'm not interested in 'smart' solutions.</p>\n\n<p>I am thinking about thing like; has the candidate made the old with off by one error in their loop, do they pre-allocate enough memory, do they check to bad input, do they use <em>sufficiently</em> efficient types.</p>\n\n<p>Unfortunately, as already pointed out, too many people can't even do this.</p>\n"
},
{
"answer_id": 219880,
"author": "mmocny",
"author_id": 29701,
"author_profile": "https://Stackoverflow.com/users/29701",
"pm_score": 2,
"selected": false,
"text": "<p>@Konrad Rudolph: (sorry I don't have the \"experience\" to post a comment)</p>\n\n<p>I want to point out that the STL supplies a <a href=\"http://cppreference.com/wiki/stl/algorithm/reverse_copy\" rel=\"nofollow noreferrer\">reverse_copy()</a> algorithm, similar to <a href=\"http://cppreference.com/wiki/stl/algorithm/reverse\" rel=\"nofollow noreferrer\">reverse()</a>. You need not introduce a temporary the way you did, just allocate a new char * of the right size.</p>\n"
},
{
"answer_id": 219926,
"author": "user23167",
"author_id": 23167,
"author_profile": "https://Stackoverflow.com/users/23167",
"pm_score": 1,
"selected": false,
"text": "<p>WRT: \"Now do it without temporary holding variable\"... Something like this perhaps (and keeping array indexing for now):</p>\n\n<pre><code>int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n string[i] ^= string[length - i];\n string[length - i] ^= string[i];\n string[i] ^= string[length - i];\n}\n</code></pre>\n"
},
{
"answer_id": 220048,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is highly unportable but x86 assembler instruction <em>bswap</em> lets you swap four bytes by means of just one instruction which can be a good path to boost the code.</p>\n\n<p>This is an example of how to get it working with GCC.</p>\n\n<pre><code>/* \n * reverse.c\n *\n * $20081020 23:33 fernando DOT miguelez AT gmail DOT com$\n */\n\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define MAX_CHARS 10 * 1024 * 1024\n\n/*\n * Borrowed from http://coding.derkeiler.com/Archive/Assembler/comp.lang.asm.x86/2007-03/msg00004.html\n * GNU Compiler syntax\n */\ninline uint32_t bswap(uint32_t val)\n{\n __asm__(\"bswap %0\" : \"=r\" (val) : \"0\" (val));\n return val;\n}\n\nchar * reverseAsm(const char * str)\n{\n int i;\n int length = strlen(str);\n int dwordLength = length/4;\n\n if(length % 4 != 0)\n {\n printf(\"Error: Input string length must be multiple of 4: %d\\n\", length); \n return NULL;\n }\n\n char * reversed_string = (char *) malloc(length+1);\n for(i = 0; i < dwordLength; i++)\n {\n *(((uint32_t *) reversed_string) + dwordLength - i - 1) = bswap(*(((uint32_t *) str) + i));\n }\n\n reversed_string[length] = '\\0';\n\n return reversed_string;\n}\n\nchar * reverse(const char * str)\n{\n int i;\n int length = strlen(str);\n char * reversed_string = (char *) malloc(length+1);\n\n for(i = 0; i < length; ++i)\n {\n reversed_string[i] = str[(length-1) - i];\n }\n\n //need to null terminate the string\n\n reversed_string[length] = '\\0';\n\n return reversed_string;\n}\n\nint main(void)\n{\n int i;\n char *reversed_str, *reversed_str2;\n clock_t start, total;\n char *str = (char *) malloc(MAX_CHARS+1);\n\n str[MAX_CHARS] = '\\0';\n\n srand(time(0));\n\n for(i = 0; i < MAX_CHARS; i++)\n {\n str[i] = 'A' + rand() % 26; \n }\n\n start = clock();\n reversed_str = reverse(str);\n total = clock() - start;\n if(reversed_str != NULL)\n {\n printf(\"Total clock ticks to reverse %d chars with pure C method: %d\\n\", MAX_CHARS, total); \n free(reversed_str);\n }\n start = clock();\n reversed_str2 = reverseAsm(str);\n total = clock() - start;\n if(reversed_str2 != NULL)\n {\n printf(\"Total clock ticks to reverse %d chars with ASM+C method: %d\\n\", MAX_CHARS, total); \n free(reversed_str2);\n }\n\n free(str);\n\n return 0;\n}\n</code></pre>\n\n<p>The results on my old computer under Cygwin:</p>\n\n<pre><code>fer@fernando /cygdrive/c/tmp$ ./reverse.exe\nTotal clock ticks to reverse 10485760 chars with pure C method: 221\nTotal clock ticks to reverse 10485760 chars with ASM+C method: 140\n</code></pre>\n"
},
{
"answer_id": 220096,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 0,
"selected": false,
"text": "<p>String reversed in place, no temp variable.</p>\n\n<pre><code>static inline void\nbyteswap (char *a, char *b)\n{\n *a = *a^*b;\n *b = *a^*b;\n *a = *a^*b;\n}\n\nvoid\nreverse (char *string)\n{\n char *end = string + strlen(string) - 1;\n\n while (string < end) {\n byteswap(string++, end--);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 220125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>A method that doesn't need temporary variables</p>\n\n<pre><code>int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n string[i] ^= string[length - i] ^= string[i] ^= string[length - i];\n}\n</code></pre>\n"
},
{
"answer_id": 220620,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 0,
"selected": false,
"text": "<p>If I was doing the interviewing I would be a bit more fussy with the quality of the solution in terms of its robustness, not just it's performance.</p>\n\n<p><strong>All</strong> of the answers submitted thus far will fail if passed a null pointer - most of them leap to immediately calling <code>strlen()</code> on a possible null pointer - which will probably segfault your process.</p>\n\n<p>Many of the answers are obsessive about performance to the point that they miss one of the key issues of the question: reverse a <code>const char *</code>, i.e. you need to make a reversed <em>copy</em>, not reverse in-place. You'll find it difficult to halve the number of iterations if a copy is required!</p>\n\n<p>This is an interview question, so we want to look at the details of the algorithm, but in the real world this just highlights the value of using standard libraries whenever possible.</p>\n"
},
{
"answer_id": 224532,
"author": "Lodle",
"author_id": 23339,
"author_profile": "https://Stackoverflow.com/users/23339",
"pm_score": 0,
"selected": false,
"text": "<p>.</p>\n\n<pre><code>char * reverse(const char * str)\n{\n if (!str)\n return NULL;\n\n int length = strlen(str);\n char * reversed_string = new char[length+1];\n\n for(int i = 0; i < length/2; ++i)\n {\n reversed_string[i] = str[(length-1) - i];\n reversed_string[(length-1) - i] = str[i];\n }\n //need to null terminate the string\n reversed_string[length] = '\\0';\n\n return reversed_string;\n\n}\n</code></pre>\n\n<p>Half the time but same complexity (note may be off by one error)</p>\n"
},
{
"answer_id": 695055,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Above for loop has typo.\nCheck of loop variable i should be <= instead of <, othrewise will fail for odd no of elements.\nfor(int i = 0; i <= length/2; ++i)</p>\n"
},
{
"answer_id": 1540738,
"author": "Marius",
"author_id": 174650,
"author_profile": "https://Stackoverflow.com/users/174650",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot (should not) do this:</p>\n\n<blockquote>\n<pre><code>string[i] ^= string[length - i] ^= string[i] ^= string[length - i];\n</code></pre>\n</blockquote>\n\n<p>From: <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm#Code_example\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/XOR_swap_algorithm#Code_example</a></p>\n\n<ul>\n<li>*\"This code has undefined behavior, since it modifies the lvalue <em>x twice without an intervening sequence point.</em></li>\n</ul>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char \* and return a pointer to a new char \*. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:
```
char * reverse(const char * str)
{
int length = strlen(str);
char * reversed_string = new char[length+1];
for(int i = 0; i < length; ++i)
{
reversed_string[i] = str[(length-1) - i];
}
//need to null terminate the string
reversed_string[length] = '\0';
return reversed_string;
}
int main(int argc, char * argv[])
{
char * rev_str = reverse("Testing");
cout << "Your string reversed is this: " << rev_str << endl;
delete rev_str;
rev_str = 0;
return 0;
}
```
|
I had this question once. That's the first answer that comes to mind, but the follow-up is, "now do it without allocating any memory."
```
int length = strlen(string);
for(int i = 0; i < length/2; i++) {
char c = string[i];
string[i] = string[length - i];
string[length - i] = c;
}
```
EDIT: Some folks have expressed disdain for not using pointers. This is a tiny bit more readable, though not completely optimal. Others have entered the pointer solution, so I won't repeat it here.
One commenter challenged that it should be doable without a (stack based) holding cell for the swap. The mechanism for doing that is bitwise XOR. Replace the inside of the loop with
```
string[i] = string[i] ^ string[length - i];
string[length - i] = string[i] ^ string[length - i];
string[i] = string[i] ^ string[length - i];
```
But in general, modern compilers can optimize out the local variable of a naive swap. For details, [See Wikipedia](http://en.wikipedia.org/wiki/XOR_swap_algorithm)
|
219,434 |
<p>What query can return the names of all the stored procedures in a SQL Server database</p>
<p>If the query could exclude system stored procedures, that would be even more helpful.</p>
|
[
{
"answer_id": 219440,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select * \n from dbo.sysobjects\n where xtype = 'P'\n and status > 0\n</code></pre>\n"
},
{
"answer_id": 219441,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 7,
"selected": false,
"text": "<pre><code>SELECT name, \n type\n FROM dbo.sysobjects\n WHERE (type = 'P')\n</code></pre>\n"
},
{
"answer_id": 219460,
"author": "Mike",
"author_id": 1573,
"author_profile": "https://Stackoverflow.com/users/1573",
"pm_score": 5,
"selected": false,
"text": "<p>From my understanding the \"preferred\" method is to use the information_schema tables:</p>\n\n<pre><code>select * \n from information_schema.routines \n where routine_type = 'PROCEDURE'\n</code></pre>\n"
},
{
"answer_id": 219510,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 10,
"selected": true,
"text": "<p>As Mike stated, the best way is to use <code>information_schema</code>. As long as you're not in the master database, system stored procedures won't be returned.</p>\n\n<pre><code>SELECT * \n FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES\n WHERE ROUTINE_TYPE = 'PROCEDURE'\n</code></pre>\n\n<p>If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):</p>\n\n<pre><code>SELECT * \n FROM [master].INFORMATION_SCHEMA.ROUTINES\n WHERE ROUTINE_TYPE = 'PROCEDURE' \n AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')\n</code></pre>\n"
},
{
"answer_id": 219561,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately <code>INFORMATION_SCHEMA</code> doesn't contain info about the system procs.</p>\n\n<pre><code>SELECT *\n FROM sys.objects\n WHERE objectproperty(object_id, N'IsMSShipped') = 0\n AND objectproperty(object_id, N'IsProcedure') = 1\n</code></pre>\n"
},
{
"answer_id": 219565,
"author": "cbeuker",
"author_id": 15952,
"author_profile": "https://Stackoverflow.com/users/15952",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using SQL Server 2005 the following will work:</p>\n\n<pre><code>select *\n from sys.procedures\n where is_ms_shipped = 0\n</code></pre>\n"
},
{
"answer_id": 12858086,
"author": "NeverHopeless",
"author_id": 751527,
"author_profile": "https://Stackoverflow.com/users/751527",
"pm_score": 3,
"selected": false,
"text": "<p>This can also help to list procedure except the system procedures:</p>\n\n<pre><code>select * from sys.all_objects where type='p' and is_ms_shipped=0\n</code></pre>\n"
},
{
"answer_id": 13698511,
"author": "Reza Zendehboudi",
"author_id": 1859377,
"author_profile": "https://Stackoverflow.com/users/1859377",
"pm_score": 0,
"selected": false,
"text": "<p>This, list all things that you want</p>\n\n<p>In Sql Server 2005, 2008, 2012 :</p>\n\n<pre><code>Use [YourDataBase]\n\nEXEC sp_tables @table_type = \"'PROCEDURE'\" \nEXEC sp_tables @table_type = \"'TABLE'\"\nEXEC sp_tables @table_type = \"'VIEW'\" \n</code></pre>\n\n<p>OR</p>\n\n<pre><code>SELECT * FROM information_schema.tables\nSELECT * FROM information_schema.VIEWS\n</code></pre>\n"
},
{
"answer_id": 21876363,
"author": "Narendra Sharma",
"author_id": 3243879,
"author_profile": "https://Stackoverflow.com/users/3243879",
"pm_score": 4,
"selected": false,
"text": "<p>The following will Return All Procedures in selected database</p>\n\n<pre><code>SELECT * FROM sys.procedures\n</code></pre>\n"
},
{
"answer_id": 27623196,
"author": "LostCajun",
"author_id": 4389023,
"author_profile": "https://Stackoverflow.com/users/4389023",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote this simple tsql to list the text of all stored procedures. Be sure to substitute your database name in field.</p>\n\n<pre><code>use << database name >>\ngo\n\ndeclare @aQuery nvarchar(1024);\ndeclare @spName nvarchar(64);\ndeclare allSP cursor for\nselect p.name from sys.procedures p where p.type_desc = 'SQL_STORED_PROCEDURE' order by p.name;\nopen allSP;\nfetch next from allSP into @spName;\nwhile (@@FETCH_STATUS = 0)\nbegin\n set @aQuery = 'sp_helptext [Extract.' + @spName + ']';\n exec sp_executesql @aQuery;\n fetch next from allSP;\nend;\nclose allSP;\ndeallocate allSP;\n</code></pre>\n"
},
{
"answer_id": 27842463,
"author": "HaveNoDisplayName",
"author_id": 2686013,
"author_profile": "https://Stackoverflow.com/users/2686013",
"pm_score": 1,
"selected": false,
"text": "<p>This will returned all sp name </p>\n\n<pre><code>Select * \nFROM sys.procedures where [type] = 'P' \n AND is_ms_shipped = 0 \n AND [name] not like 'sp[_]%diagram%'\n</code></pre>\n"
},
{
"answer_id": 27919038,
"author": "MovGP0",
"author_id": 601990,
"author_profile": "https://Stackoverflow.com/users/601990",
"pm_score": 4,
"selected": false,
"text": "<p>You can try this query to get stored procedures and functions: </p>\n\n<pre><code>SELECT name, type\nFROM dbo.sysobjects\nWHERE type IN (\n 'P', -- stored procedures\n 'FN', -- scalar functions \n 'IF', -- inline table-valued functions\n 'TF' -- table-valued functions\n)\nORDER BY type, name\n</code></pre>\n"
},
{
"answer_id": 40074774,
"author": "The_Coder",
"author_id": 5142270,
"author_profile": "https://Stackoverflow.com/users/5142270",
"pm_score": 1,
"selected": false,
"text": "<p>This will give just the names of the stored procedures.</p>\n\n<pre><code>select specific_name\nfrom information_schema.routines\nwhere routine_type = 'PROCEDURE';\n</code></pre>\n"
},
{
"answer_id": 42396905,
"author": "Ardalan Shahgholi",
"author_id": 2063547,
"author_profile": "https://Stackoverflow.com/users/2063547",
"pm_score": 4,
"selected": false,
"text": "<p>You can use one of the below queries to find the list of Stored Procedures in one database : </p>\n\n<p>Query1 :</p>\n\n<pre><code> SELECT \n *\n FROM sys.procedures;\n</code></pre>\n\n<p>Query2 :</p>\n\n<pre><code> SELECT \n * \n FROM information_schema.routines \n WHERE ROUTINE_TYPE = 'PROCEDURE' \n</code></pre>\n\n<p>If you want to find the list of <strong>all SPs in all Databases</strong> you can use the below query :</p>\n\n<pre><code> CREATE TABLE #ListOfSPs \n (\n DBName varchar(100), \n [OBJECT_ID] INT,\n SPName varchar(100)\n )\n\n EXEC sp_msforeachdb 'USE [?]; INSERT INTO #ListOfSPs Select ''?'', Object_Id, Name FROM sys.procedures'\n\n SELECT \n * \n FROM #ListOfSPs\n</code></pre>\n"
},
{
"answer_id": 42489206,
"author": "BaffledBill",
"author_id": 4462742,
"author_profile": "https://Stackoverflow.com/users/4462742",
"pm_score": 2,
"selected": false,
"text": "<p>I've tweaked LostCajun's excellent post above to exclude system stored procedures. I also removed \"Extract.\" from the code because I couldn't figure out what it's for and it gave me errors. The \"fetch next\" statement inside the loop also needed an \"into\" clause.</p>\n\n<pre><code>use <<databasename>>\ngo\n\ndeclare @aQuery nvarchar(1024);\ndeclare @spName nvarchar(64);\ndeclare allSP cursor for\n select p.name \n from sys.procedures p \n where p.type_desc = 'SQL_STORED_PROCEDURE' \n and LEFT(p.name,3) NOT IN ('sp_','xp_','ms_')\n order by p.name;\nopen allSP;\nfetch next from allSP into @spName;\nwhile (@@FETCH_STATUS = 0)\nbegin\n set @aQuery = 'sp_helptext [' + @spName + ']';\n exec sp_executesql @aQuery;\n fetch next from allSP into @spName;\nend;\nclose allSP;\ndeallocate allSP;\n</code></pre>\n"
},
{
"answer_id": 42918726,
"author": "Sandeep",
"author_id": 2579287,
"author_profile": "https://Stackoverflow.com/users/2579287",
"pm_score": 0,
"selected": false,
"text": "<p>Try this codeplex link, this utility help to localize all stored procedure from sql database.</p>\n\n<p><a href=\"https://exportmssqlproc.codeplex.com/\" rel=\"nofollow noreferrer\">https://exportmssqlproc.codeplex.com/</a></p>\n"
},
{
"answer_id": 45021288,
"author": "Lorena Pita",
"author_id": 5307277,
"author_profile": "https://Stackoverflow.com/users/5307277",
"pm_score": 3,
"selected": false,
"text": "<p>Select All Stored Procedures and Views</p>\n\n<pre><code>select name,type,type_desc\nfrom sys.objects\nwhere type in ('V','P')\norder by name,type\n</code></pre>\n"
},
{
"answer_id": 48549349,
"author": "Ray Koren",
"author_id": 4352494,
"author_profile": "https://Stackoverflow.com/users/4352494",
"pm_score": 3,
"selected": false,
"text": "<p>Just the names:</p>\n\n<pre><code>SELECT SPECIFIC_NAME \nFROM YOUR_DB_NAME.information_schema.routines \nWHERE routine_type = 'PROCEDURE'\n</code></pre>\n"
},
{
"answer_id": 49272619,
"author": "Chandan Ravandur N",
"author_id": 9490070,
"author_profile": "https://Stackoverflow.com/users/9490070",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from DatabaseName.INFORMATION_SCHEMA.ROUTINES where routine_type = 'PROCEDURE'\n\nselect * from DatabaseName.INFORMATION_SCHEMA.ROUTINES where routine_type ='procedure' and left(ROUTINE_NAME,3) not in('sp_', 'xp_', 'ms_')\n\n\n SELECT name, type FROM dbo.sysobjects\n WHERE (type = 'P')\n</code></pre>\n"
},
{
"answer_id": 51018866,
"author": "Mohsen",
"author_id": 1970972,
"author_profile": "https://Stackoverflow.com/users/1970972",
"pm_score": 2,
"selected": false,
"text": "<p>the best way to get objects is use sys.sql_modules. you can find every thing that you want from this table and join this table with other table to get more information by object_id</p>\n\n<pre><code>SELECT o. object_id,o.name AS name,o.type_desc,m.definition,schemas.name scheamaName\nFROM sys.sql_modules m \n INNER JOIN sys.objects o ON m.object_id=o.OBJECT_ID\n INNER JOIN sys.schemas ON schemas.schema_id = o.schema_id\n WHERE [TYPE]='p'\n</code></pre>\n"
},
{
"answer_id": 53813524,
"author": "user1556937",
"author_id": 1556937,
"author_profile": "https://Stackoverflow.com/users/1556937",
"pm_score": 0,
"selected": false,
"text": "<pre><code>USE DBNAME\n\nselect ROUTINE_NAME from information_schema.routines \nwhere routine_type = 'PROCEDURE'\n\n\nGO \n</code></pre>\n\n<p>This will work on mssql.</p>\n"
},
{
"answer_id": 55048379,
"author": "Alexandru-Codrin Panaite",
"author_id": 10293835,
"author_profile": "https://Stackoverflow.com/users/10293835",
"pm_score": 1,
"selected": false,
"text": "<p>This is gonna show all the stored procedures and the code:</p>\n\n<pre><code>select sch.name As [Schema], obj.name AS [Stored Procedure], code.definition AS [Code] from sys.objects as obj\n join sys.sql_modules as code on code.object_id = obj.object_id\n join sys.schemas as sch on sch.schema_id = obj.schema_id\n where obj.type = 'P'\n</code></pre>\n"
},
{
"answer_id": 60977025,
"author": "Ankur Tiwari",
"author_id": 13187987,
"author_profile": "https://Stackoverflow.com/users/13187987",
"pm_score": 0,
"selected": false,
"text": "<p>Select list of stored procedure in SQL server. Refer here for more:\n<a href=\"https://coderrooms.blogspot.com/2017/06/select-list-of-stored-procedure-in-sql.html\" rel=\"nofollow noreferrer\">https://coderrooms.blogspot.com/2017/06/select-list-of-stored-procedure-in-sql.html</a></p>\n"
},
{
"answer_id": 66020596,
"author": "Lannie Reyes",
"author_id": 15134535,
"author_profile": "https://Stackoverflow.com/users/15134535",
"pm_score": 0,
"selected": false,
"text": "<p>exec sp_stored_procedures;\n<a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-stored-procedures-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">Docs.Microsoft.com</a></p>\n<p>Easy to remember.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What query can return the names of all the stored procedures in a SQL Server database
If the query could exclude system stored procedures, that would be even more helpful.
|
As Mike stated, the best way is to use `information_schema`. As long as you're not in the master database, system stored procedures won't be returned.
```
SELECT *
FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
```
If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):
```
SELECT *
FROM [master].INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')
```
|
219,475 |
<p>I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.</p>
<p>Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.</p>
|
[
{
"answer_id": 219524,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": false,
"text": "<p>Let's suppose you can use a character set of, say, 40 symbols of unambiguous upper,lower and numeric characters.</p>\n\n<p>For a sequence of n chars, you've got 40<sup>n</sup> combinations</p>\n\n<ul>\n<li>40<sup>4</sup> = 2,560,000 </li>\n<li>40<sup>5</sup> = 102,400,000</li>\n<li>40<sup>6</sup> = 4,096,000,000</li>\n<li>40<sup>7</sup> = 163,840,000,000</li>\n<li>40<sup>8</sup> = 6,553,600,000,000</li>\n</ul>\n\n<p>Thus 8 chars gives a pretty good space to work in - if you generated 10 million codes, you'd have to try hundreds of thousands of combinations to brute force a code. </p>\n\n<p>Or you come at from the other direction - give the number of <em>possible</em> codes, how many codes <em>should</em> you generate to avoid the trap they call the <a href=\"http://en.wikipedia.org/wiki/Birthday_paradox\" rel=\"nofollow noreferrer\">Birthday Paradox</a>?</p>\n\n<p>Taking the 8 char code, 6,553,600,000,000 is approx 2<sup>42</sup>, thus you might reasonably generate 2<sup>21</sup> codes from it, or 2,097,152</p>\n"
},
{
"answer_id": 219557,
"author": "ojrac",
"author_id": 20760,
"author_profile": "https://Stackoverflow.com/users/20760",
"pm_score": 5,
"selected": true,
"text": "<p>If you need about 10 million unique keys (for example), the best approach is to pick a key-space that's exponentially bigger, and start randomly generating. Read about the <a href=\"http://en.wikipedia.org/wiki/Birthday_paradox\" rel=\"noreferrer\">Birthday Paradox</a> -- it's the main thing you should be worried about. If you want 2^n unique and secure keys, make sure there are at least 2^(2 * n) possible values. Here's a rough O(n log n) algorithm:</p>\n\n<ul>\n<li>Use a key space of at least 2^50 (so, in other words, allow 2^50 possible unique values), and you'll have barely any collisions in your entire dataset -- and anyone brute forcing your keys will have about even odds of getting a key if they try 2^25 of them.</li>\n<li>generate as many random numbers as you need</li>\n<li>index the database on your key (this is the O(n lg n) step: the sort)</li>\n<li>page through the DB and iterate over the entire data set to trim duplicates (pseudocode below)</li>\n<li>Delete the duplicate rows, and you're done.</li>\n</ul>\n\n<p>Pseudocode:</p>\n\n<pre><code>$last = null;\nwhile ($current = getnext()) {\n if ($last == $current) {\n push($toDelete, $current);\n }\n $last = $current;\n}\n</code></pre>\n"
},
{
"answer_id": 219652,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use a one time password algorithm?</p>\n\n<p>RFC4225 details one based on HMAC algorithm. </p>\n\n<p><a href=\"http://www.ietf.org/rfc/rfc4226.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc4226.txt</a></p>\n\n<p>but instead of using 0-9 digits base10 encoding, use base32.</p>\n"
},
{
"answer_id": 252076,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 0,
"selected": false,
"text": "<p>Whatver method you use, I would suggest you add a check digit or two as a \"first-line\" defence against people mis-entering or trying to invent a number.</p>\n"
},
{
"answer_id": 1349329,
"author": "kalinma",
"author_id": 165110,
"author_profile": "https://Stackoverflow.com/users/165110",
"pm_score": -1,
"selected": false,
"text": "<p>Oddly enough, with the following seed I was only able to generate 32 unique strings.</p>\n\n<p>ABCDEFGHJKLMNPQRSTUVWXYZ23456789</p>\n\n<p>With a longer seed I was able to generate many more--generated 40,000 unique strings successfully.</p>\n\n<p>ABCDEFGHJKLMNPQRSTUVWXYZ234567892345678923456789ABCDEFGHJKLMNPQRSTUVWXYZ234567892345678923456789ABCDEFGHJKLMNPQRSTUVWXYZ234567892345678923456789</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19411/"
] |
I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.
Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.
|
If you need about 10 million unique keys (for example), the best approach is to pick a key-space that's exponentially bigger, and start randomly generating. Read about the [Birthday Paradox](http://en.wikipedia.org/wiki/Birthday_paradox) -- it's the main thing you should be worried about. If you want 2^n unique and secure keys, make sure there are at least 2^(2 \* n) possible values. Here's a rough O(n log n) algorithm:
* Use a key space of at least 2^50 (so, in other words, allow 2^50 possible unique values), and you'll have barely any collisions in your entire dataset -- and anyone brute forcing your keys will have about even odds of getting a key if they try 2^25 of them.
* generate as many random numbers as you need
* index the database on your key (this is the O(n lg n) step: the sort)
* page through the DB and iterate over the entire data set to trim duplicates (pseudocode below)
* Delete the duplicate rows, and you're done.
Pseudocode:
```
$last = null;
while ($current = getnext()) {
if ($last == $current) {
push($toDelete, $current);
}
$last = $current;
}
```
|
219,482 |
<p>If anyone has experience using Oracle text (<code>CTXSYS.CONTEXT</code>), I'm wondering how to handle user input when the user wants to search for names that may contain an apostrophe.</p>
<p>Escaping the ' seems to work in some cases, but not for 's at the end of the word - s is in the list of stop words, and so seems to get removed.</p>
<p>We currently change simple query text (i.e. anything that's just letters) to <code>%text%</code>, for example: </p>
<pre><code>contains(field, :text) > 0
</code></pre>
<p>A search for <strong>O'Neil</strong> works, but <strong>Joe's</strong> doesn't.</p>
<p>Has anyone using Oracle Text dealt with this issue?</p>
|
[
{
"answer_id": 220417,
"author": "yogman",
"author_id": 24349,
"author_profile": "https://Stackoverflow.com/users/24349",
"pm_score": -1,
"selected": false,
"text": "<p>Forget about sanitizing. Why? Refer to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/SQL_injection</a> .</p>\n\n<p>It depends on the kind of database interface API you are using. Perl DBI, ODBC, JDBC support parameterized queries or prepared statements. If you're using a native DBI and it doesn't support it, then God bless you.</p>\n"
},
{
"answer_id": 9026658,
"author": "KarlP",
"author_id": 92018,
"author_profile": "https://Stackoverflow.com/users/92018",
"pm_score": 2,
"selected": false,
"text": "<p>Escape all special characters with backslashes. Curly braces won't work with substring searches as they define complete tokens. Eg %{ello}% won't match the token 'Hello' </p>\n\n<p>Escaped space characters will be included in the search token, so the search string '%stay\\ near\\ me%' will be treated as a literal string \"stay near me\" and will not invoke the 'near' operator.</p>\n\n<p>If you are indexing short strings (like names, etc ) and you want Oracle Text to behave exactly as the like operator, you must write your own lexer that won't create tokens for individual words. (Unfortunately CATSEARCH does not support substring search...)</p>\n\n<p>It is probably a good idea to change the searches to use oracle text's semantics, with token matching, but for some applications, the wildcard expansion of multiple (short) tokens and numeric tokens will create too many hits for search strings that the users reasonably would expect to work. </p>\n\n<p>Eg, a search for \"%I\\ AM\\ NUMBER\\ 9%\" will most likely fail if there are a lot of numeric tokens in the indexed data, since all tokens ending with 'I' and starting with '9' must be searched and merged before the result can be returned. </p>\n\n<p>'I' and 'AM' is probably also in the default stoplist and will be totally ignored, so for this hypothetical application, a null stoplist may be used if these tokens are important.</p>\n"
},
{
"answer_id": 41787290,
"author": "Dima Korobskiy",
"author_id": 534217,
"author_profile": "https://Stackoverflow.com/users/534217",
"pm_score": 1,
"selected": false,
"text": "<p>Using <code>PARAMETERS('STOPLIST ctxsys.empty_stoplist')</code> when indexing would include all alphabetical tokens in the index. Accented characters are indexed as well. Non-alphabetical characters are generally treated as whitespace by BASIC_LEXER.</p>\n\n<p>Also, CONTEXT grammar uses a lot of operators that include symbols and reserved words such as WITHIN, NEAR, ABOUT. These all have to be escaped somehow in the input. If you need to search for substrings, the correct approach to escaping is to escape <em>all</em> characters with <code>\\</code>. This is an answer to a related question here: <a href=\"https://stackoverflow.com/questions/30194480/oracle-text-escaping-with-curly-braces-and-wildcards\">Oracle text escaping with curly braces and wildcards</a>. If your requirements is to search for whole terms (names, etc.) you can use simpler <code>{input}</code> escaping.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4782/"
] |
If anyone has experience using Oracle text (`CTXSYS.CONTEXT`), I'm wondering how to handle user input when the user wants to search for names that may contain an apostrophe.
Escaping the ' seems to work in some cases, but not for 's at the end of the word - s is in the list of stop words, and so seems to get removed.
We currently change simple query text (i.e. anything that's just letters) to `%text%`, for example:
```
contains(field, :text) > 0
```
A search for **O'Neil** works, but **Joe's** doesn't.
Has anyone using Oracle Text dealt with this issue?
|
Escape all special characters with backslashes. Curly braces won't work with substring searches as they define complete tokens. Eg %{ello}% won't match the token 'Hello'
Escaped space characters will be included in the search token, so the search string '%stay\ near\ me%' will be treated as a literal string "stay near me" and will not invoke the 'near' operator.
If you are indexing short strings (like names, etc ) and you want Oracle Text to behave exactly as the like operator, you must write your own lexer that won't create tokens for individual words. (Unfortunately CATSEARCH does not support substring search...)
It is probably a good idea to change the searches to use oracle text's semantics, with token matching, but for some applications, the wildcard expansion of multiple (short) tokens and numeric tokens will create too many hits for search strings that the users reasonably would expect to work.
Eg, a search for "%I\ AM\ NUMBER\ 9%" will most likely fail if there are a lot of numeric tokens in the indexed data, since all tokens ending with 'I' and starting with '9' must be searched and merged before the result can be returned.
'I' and 'AM' is probably also in the default stoplist and will be totally ignored, so for this hypothetical application, a null stoplist may be used if these tokens are important.
|
219,519 |
<p>What I'm looking for is a basic equivalent of JavaScript's <code>Array::join()</code> whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a <code>StringBuilder</code> or whatnot, but there <em>must</em> be something built into the .NET BCL.</p>
<p>EDIT: Array of <em>anything</em>, not necessarily <code>string</code> or <code>char</code>. I'd prefer the method to simply call <code>ToString()</code> on each subscript <code>object</code>. <code>String.Join()</code> is great except that you pass it an array of strings.</p>
|
[
{
"answer_id": 219521,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": true,
"text": "<p>If the array contains strings, you can just use <a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow noreferrer\"><code>String.Join()</code></a>. If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.</p>\n\n<p><strong>Update:</strong> Using @JaredPar's code as the basis for a more generic example:</p>\n\n<pre><code>char sep = GetSeparatorChar();\nobject[] toJoin = GetToJoin();\nstring joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());\n</code></pre>\n\n<p>Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.</p>\n"
},
{
"answer_id": 219526,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "<p>I'm unclear as to whether or not you are joining an array of characters or strings.</p>\n\n<p>For Strings</p>\n\n<pre><code>\nchar sep = GetSeparatorChar();\nstring[] toJoin = GetToJoin();\nstring joined = toJoin.Aggregate((x,y) => x+sep.ToString()+y);\n</code></pre>\n"
},
{
"answer_id": 219567,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>If String.Join doesn't do it for you - e.g. you have an <code>IEnumerable<string></code> instead of a <code>string[]</code> or you have a collection of some other type, see <a href=\"https://stackoverflow.com/questions/145856/how-to-join-int-to-a-charcter-separated-string-in-c\">this earlier question</a>.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
What I'm looking for is a basic equivalent of JavaScript's `Array::join()` whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a `StringBuilder` or whatnot, but there *must* be something built into the .NET BCL.
EDIT: Array of *anything*, not necessarily `string` or `char`. I'd prefer the method to simply call `ToString()` on each subscript `object`. `String.Join()` is great except that you pass it an array of strings.
|
If the array contains strings, you can just use [`String.Join()`](http://msdn.microsoft.com/en-us/library/57a79xd0.aspx). If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.
**Update:** Using @JaredPar's code as the basis for a more generic example:
```
char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());
```
Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.
|
219,547 |
<p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow noreferrer">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p>
<ul>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1200req/s</strong></li>
<li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>40req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1000req/s</strong></li>
<li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>32req/s</strong></li>
</ul>
<p>Nothing changes in the code between the two calls, I can’t figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p>
<p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
|
[
{
"answer_id": 219642,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 0,
"selected": false,
"text": "<p>I found <a href=\"http://www.mail-archive.com/[email protected]/msg22589.html\" rel=\"nofollow noreferrer\">this article</a> on backlog on tomcat / java which gives an interesting insight in the backlog:</p>\n\n<blockquote>\n <p>for example, if all threads are busy\n in java handling requests, the kernel\n will handle SYN and TCP handshakes\n until its backlog is full. when the\n backlog is full, it will simply drop\n future SYN requests. it will not send\n a RST, ie causing \"Connection refused\"\n on the client, instead the client will\n assume the package was lost and\n retransmit the SYN. hopefully, the\n backlog queue will have cleared up by\n then.</p>\n</blockquote>\n\n<p>As I interpret it, by asking ab to create more simultaneous connection than your\nsocket is configured to handle packets get dropped, not refused, and I do not know\nhow ab handles that. It may be that it retransmits the SYN, but possibly after waiting\na while. This may even be specced somewhere (TCP protocol?).</p>\n\n<p>As said, I do not know but I hope this hints at the cause. </p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 219671,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 4,
"selected": true,
"text": "<p>I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level:</p>\n\n<pre><code>import thread, socket, Queue\n\nconnections = Queue.Queue()\nnum_threads = 10\nbacklog = 10\n\ndef request():\n while 1:\n conn = connections.get()\n data = ''\n while '\\r\\n\\r\\n' not in data:\n data += conn.recv(4048)\n conn.sendall('HTTP/1.1 200 OK\\r\\n\\r\\nHello World')\n conn.close()\n\nif __name__ == '__main__':\n for _ in range(num_threads):\n thread.start_new_thread(request, ())\n\n acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n acceptor.bind(('', 1234))\n acceptor.listen(backlog)\n while 1:\n conn, addr = acceptor.accept()\n connections.put(conn)\n</code></pre>\n\n<p>which on my machine does:</p>\n\n<pre><code>ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 8695.03 [#/sec]\nab -n 10000 -c 11 http://127.0.0.1:1234/ --> 8529.41 [#/sec]\n</code></pre>\n"
},
{
"answer_id": 219676,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>it looks like you're not really getting concurrency. apparently, when you do socket.accept(), the main thread doesn't go immediately back to waiting for the next connection. maybe your connection-handling thread is only python code, so you're getting sequentialized by the SIL (single interpreder lock).</p>\n\n<p>if there's not heavy communications between threads, better use a multi-process scheme (with a pool of pre-spawned processes, of course)</p>\n"
},
{
"answer_id": 219824,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "<p>For the heck of it I also implemented an asynchronous version:</p>\n\n<pre><code>import socket, Queue, select\n\nclass Request(object):\n def __init__(self, conn):\n self.conn = conn\n self.fileno = conn.fileno\n self.perform = self._perform().next\n\n def _perform(self):\n data = self.conn.recv(4048)\n while '\\r\\n\\r\\n' not in data:\n msg = self.conn.recv(4048)\n if msg:\n data += msg\n yield\n else:\n break\n reading.remove(self)\n writing.append(self)\n\n data = 'HTTP/1.1 200 OK\\r\\n\\r\\nHello World'\n while data:\n sent = self.conn.send(data)\n data = data[sent:]\n yield\n writing.remove(self)\n self.conn.close()\n\nclass Acceptor:\n def __init__(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', 1234))\n sock.listen(10)\n self.sock = sock\n self.fileno = sock.fileno\n\n def perform(self):\n conn, addr = self.sock.accept()\n reading.append(Request(conn))\n\nif __name__ == '__main__':\n reading = [Acceptor()]\n writing = list()\n\n while 1:\n readable, writable, error = select.select(reading, writing, [])\n for action in readable + writable:\n try: action.perform()\n except StopIteration: pass\n</code></pre>\n\n<p>which performs:</p>\n\n<pre><code>ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 16822.13 [#/sec]\nab -n 10000 -c 11 http://127.0.0.1:1234/ --> 15704.41 [#/sec]\n</code></pre>\n"
},
{
"answer_id": 222713,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, so I ran the code on a totally different server - (a vps I got at slicehost), not a single problem (everything works as expected) so honestly I think it's something wrong with my laptop now ;p </p>\n\n<p>Thanks for everyones help though!</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452521/"
] |
I have a python script that is a http-server: <http://paste2.org/p/89701>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:
* socket.listen(**10**) and ab -n 50 -c **10** <http://localhost/> = **1200req/s**
* socket.listen(**10**) and ab -n 50 -c **11** <http://localhost/> = **40req/s**
* socket.listen(**100**) and ab -n 5000 -c **100** <http://localhost/> = **1000req/s**
* socket.listen(**100**) and ab -n 5000 -c **101** <http://localhost/> = **32req/s**
Nothing changes in the code between the two calls, I can’t figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.
*I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!*
|
I cannot confirm your results, and your server is coded fishy. I whipped up my own server and do not have this problem either. Let's move the discussion to a simpler level:
```
import thread, socket, Queue
connections = Queue.Queue()
num_threads = 10
backlog = 10
def request():
while 1:
conn = connections.get()
data = ''
while '\r\n\r\n' not in data:
data += conn.recv(4048)
conn.sendall('HTTP/1.1 200 OK\r\n\r\nHello World')
conn.close()
if __name__ == '__main__':
for _ in range(num_threads):
thread.start_new_thread(request, ())
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
acceptor.bind(('', 1234))
acceptor.listen(backlog)
while 1:
conn, addr = acceptor.accept()
connections.put(conn)
```
which on my machine does:
```
ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 8695.03 [#/sec]
ab -n 10000 -c 11 http://127.0.0.1:1234/ --> 8529.41 [#/sec]
```
|
219,559 |
<p>I have a table of data, and I allow people to add meta data to that table.</p>
<p>I give them an interface that allows them to treat it as though they're adding extra columns to the table their data is stored in, but I'm actually storing the data in another table.</p>
<pre><code>Data Table
DataID
Data
Meta Table
DataID
MetaName
MetaData
</code></pre>
<p>So if they wanted a table that stored the data, the date, and a name, then I'd have the data in the data table, and the word "Date" in metaname, and the date in MetaData, and another row in the meta table with "Name" in metaname and the name in metadata. </p>
<p>I now need a query that takes the information from these tables and presents it as though coming from a single table with the two additional columns "Data" and "Name" so to the customer it would look like there's a single table with their custom columns:</p>
<pre><code>MyTable
Data
Date
Name
</code></pre>
<p>Or, in other words, how do I go from here:</p>
<pre><code>Data Table
DataID Data
1 Testing!
2 Hello, World!
Meta Table
DataID MetaName MetaData
1 Date 20081020
1 Name adavis
2 Date 20081019
2 Name mdavis
</code></pre>
<p>To here:</p>
<pre><code>MyTable
Data Date Name
Testing! 20081020 adavis
Hello, World! 20081019 mdavis
</code></pre>
<p>Years ago when I did this in MySQL using PHP, I did two queries, the first to get the extra meta data, the second to join them all together. I'm hoping that modern databases have alternate methods of dealing with this.</p>
<p>Related to option 3 of <a href="https://stackoverflow.com/questions/218848/design-decision-dynamically-adding-data-question#218872">this question</a>.</p>
<p>-Adam</p>
|
[
{
"answer_id": 219578,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT DataTable.Data AS Data, MetaTable.MetaData AS Date, MetaTable.MetaName AS Name\nFROM DataTable, MetaTable\nWHERE DataTable.DataID = MetaTable.DataID\n</code></pre>\n\n<p>You'll probably want to add an additional clause (AND Data = 'some value') to return the rows the user is interested in.</p>\n"
},
{
"answer_id": 219580,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, you can do this on the server-side only with a dynamic <code>SQL</code> stored procedure. </p>\n\n<p>Effectively the code you want to generate dynamically is:</p>\n\n<pre><code>SELECT [Data Table].*\n ,[MyTable Date].MetaData\n ,[MyTable Name].MetaData\nFROM [Data Table]\nLEFT JOIN [MyTable] AS [MyTable Date]\n ON [MyTable Date].DataID = [Data Table].DataID\n AND [MyTable Date].MetaName = 'Date'\nLEFT JOIN [MyTable] AS [MyTable Name]\n ON [MyTable Name].DataID = [Data Table].DataID\n AND [MyTable Name].MetaName = 'Name'\n</code></pre>\n\n<p>And here's code to do it:</p>\n\n<pre><code>DECLARE @sql AS varchar(max)\nDECLARE @select_list AS varchar(max)\nDECLARE @join_list AS varchar(max)\nDECLARE @CRLF AS varchar(2)\nDECLARE @Tab AS varchar(1)\n\nSET @CRLF = CHAR(13) + CHAR(10)\nSET @Tab = CHAR(9)\n\nSELECT @select_list = COALESCE(@select_list, '')\n + @Tab + ',[MyTable_' + PIVOT_CODE + '].[MetaData]' + @CRLF\n ,@join_list = COALESCE(@join_list, '')\n + 'LEFT JOIN [MyTable] AS [MyTable_' + PIVOT_CODE + ']' + @CRLF\n + @Tab + 'ON [MyTable_' + PIVOT_CODE + '].DataID = [DataTable].DataID' + @CRLF\n + @Tab + 'AND [MyTable_' + PIVOT_CODE + '].MetaName = ''' + PIVOT_CODE + '''' + @CRLF\nFROM (\n SELECT DISTINCT MetaName AS PIVOT_CODE\n FROM [MyTable]\n) AS PIVOT_CODES\n\nSET @sql = 'SELECT [DataTable].*' + @CRLF\n + @select_list\n + 'FROM [DataTable]' + @CRLF\n + @join_list\nPRINT @sql\n--EXEC (@sql)\n</code></pre>\n\n<p>You could use a similar dynamic technique using the <code>CASE</code> statement example to perform the pivot.</p>\n"
},
{
"answer_id": 219601,
"author": "Jeff Fritz",
"author_id": 29156,
"author_profile": "https://Stackoverflow.com/users/29156",
"pm_score": 3,
"selected": true,
"text": "<p>You want to pivot each of your name-value pair rows in the MyTable... Try this sql:</p>\n\n<pre><code>DECLARE @Data TABLE (\n DataID INT IDENTITY(1,1) PRIMARY KEY,\n Data VARCHAR(MAX)\n)\n\nDECLARE @Meta TABLE (\n DataID INT ,\n MetaName VARCHAR(MAX),\n MetaData VARCHAR(MAX)\n)\n\nINSERT INTO @Data\nSELECT 'Data'\n\nINSERT INTO @Meta\nSELECT 1, 'Date', CAST(GetDate() as VARCHAR(20))\nUNION\nSELECT 1, 'Name', 'Joe Test'\n\nSELECT * FROM @Data\n\nSELECT * FROM @Meta\n\nSELECT \n D.DataID,\n D.Data,\n MAX(CASE MetaName WHEN 'Date' THEN MetaData ELSE NULL END) as Date,\n MAX(CASE MetaName WHEN 'Name' THEN MetaData ELSE NULL END) as Name\nFROM\n @Meta M\nJOIN @Data D ON M.DataID = D.DataID \nGROUP BY\n D.DataID,\n D.Data\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
I have a table of data, and I allow people to add meta data to that table.
I give them an interface that allows them to treat it as though they're adding extra columns to the table their data is stored in, but I'm actually storing the data in another table.
```
Data Table
DataID
Data
Meta Table
DataID
MetaName
MetaData
```
So if they wanted a table that stored the data, the date, and a name, then I'd have the data in the data table, and the word "Date" in metaname, and the date in MetaData, and another row in the meta table with "Name" in metaname and the name in metadata.
I now need a query that takes the information from these tables and presents it as though coming from a single table with the two additional columns "Data" and "Name" so to the customer it would look like there's a single table with their custom columns:
```
MyTable
Data
Date
Name
```
Or, in other words, how do I go from here:
```
Data Table
DataID Data
1 Testing!
2 Hello, World!
Meta Table
DataID MetaName MetaData
1 Date 20081020
1 Name adavis
2 Date 20081019
2 Name mdavis
```
To here:
```
MyTable
Data Date Name
Testing! 20081020 adavis
Hello, World! 20081019 mdavis
```
Years ago when I did this in MySQL using PHP, I did two queries, the first to get the extra meta data, the second to join them all together. I'm hoping that modern databases have alternate methods of dealing with this.
Related to option 3 of [this question](https://stackoverflow.com/questions/218848/design-decision-dynamically-adding-data-question#218872).
-Adam
|
You want to pivot each of your name-value pair rows in the MyTable... Try this sql:
```
DECLARE @Data TABLE (
DataID INT IDENTITY(1,1) PRIMARY KEY,
Data VARCHAR(MAX)
)
DECLARE @Meta TABLE (
DataID INT ,
MetaName VARCHAR(MAX),
MetaData VARCHAR(MAX)
)
INSERT INTO @Data
SELECT 'Data'
INSERT INTO @Meta
SELECT 1, 'Date', CAST(GetDate() as VARCHAR(20))
UNION
SELECT 1, 'Name', 'Joe Test'
SELECT * FROM @Data
SELECT * FROM @Meta
SELECT
D.DataID,
D.Data,
MAX(CASE MetaName WHEN 'Date' THEN MetaData ELSE NULL END) as Date,
MAX(CASE MetaName WHEN 'Name' THEN MetaData ELSE NULL END) as Name
FROM
@Meta M
JOIN @Data D ON M.DataID = D.DataID
GROUP BY
D.DataID,
D.Data
```
|
219,570 |
<p>I was asked for a comprehensive breakdown on space used within a specific database.
I know I can use <em>sys.dm_db_partition_stats</em> in SQL Server 2005 to figure out how much space each <em>table</em> in a database is using, but is there any way to determine the individual and total size of the <em>stored procedures</em> in a database? (Short of opening each one and counting the characters, of course.)</p>
<p>Total space used by stored procs is not likely to be significant (compared to actual <em>data</em>), but with hundreds of them, it could add up.</p>
|
[
{
"answer_id": 219605,
"author": "Dave_H",
"author_id": 17109,
"author_profile": "https://Stackoverflow.com/users/17109",
"pm_score": 2,
"selected": false,
"text": "<p>A slightly better way than counting the characters, is to use information schema.routines. You could sum the length of each Routine Definition as (Note each routine definition will max out at 4,000 characters, see below for a method that doesn't have this restriction):</p>\n\n<pre>\nselect Sum(Len(Routine_Definition)) from information_schema.routines \nwhere routine_type = 'PROCEDURE'\n</pre>\n\n<p>Or you could return the length of each sp</p>\n\n<pre>\nselect Len(Routine_Definition), * from information_schema.routines \nwhere routine_type = 'PROCEDURE'\n</pre>\n\n<p>It's unlikely that the length of your stored procedures is the problem. Usually running out of space with a database is due to things like not backing up the log file (and then shrinking it using dbcc shrinkfile or dbcc shrinkdatabase).</p>\n\n<p>In Sql 2000, here is a routine that would provide the length without the 4000 character limit of above:</p>\n\n<pre>\nDECLARE @Name VarChar(250)\nDECLARE RoutineCursor CURSOR FOR\n select Routine_Name from information_schema.routines where routine_type = 'PROCEDURE'\n\nDECLARE @Results TABLE\n ( SpName VarChar(250),\n SpLength Int\n )\n\nCREATE TABLE ##SpText\n ( SpText VarChar(8000) )\n\nOPEN RoutineCursor\nFETCH NEXT FROM RoutineCursor INTO @Name\n\nWHILE @@FETCH_STATUS = 0\n BEGIN\n INSERT INTO ##SpText (SpText) EXEC sp_helptext @Name\n\n INSERT INTO @Results (SpName, SpLength) (SELECT @Name, Sum(Len(SpText)) FROM ##SpText)\n TRUNCATE TABLE ##SpText\n\n FETCH NEXT FROM RoutineCursor INTO @Name\n END\n\nCLOSE RoutineCursor\nDEALLOCATE RoutineCursor\nDROP TABLE ##SpText\n\nSELECT SpName, SpLength FROM @Results ORDER BY SpLength DESC\nSELECT Sum(SpLength) FROM @Results\n\n</pre>\n"
},
{
"answer_id": 219675,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "<p>Dave_H's solution hits a limit of 4,000 character in the information_schema.routines table</p>\n\n<p>Try this, first you generate the a table with the full text of the sprocs, then sum the character lengths.</p>\n\n<pre><code>--create a temp table to hold the data\ncreate table ##sptext (sptext varchar(1000))\ngo\n\n--generate the code to insert the full text of your sprocs\nselect 'insert into ##sptext (sptext) exec sp_helptext '''+specific_name+''';'\nfrom information_schema.routines \nwhere routine_type = 'PROCEDURE'\ngo\n\n/*Copy the output back to your query analyzer and run it*/\n\n--now sum the results \nselect sum(len(sptext))\nfrom ##sptext\n</code></pre>\n"
},
{
"answer_id": 219740,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 5,
"selected": true,
"text": "<pre><code>;WITH ROUTINES AS (\n -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit\n SELECT o.type_desc AS ROUTINE_TYPE\n ,o.[name] AS ROUTINE_NAME\n ,m.definition AS ROUTINE_DEFINITION\n FROM sys.sql_modules AS m\n INNER JOIN sys.objects AS o\n ON m.object_id = o.object_id\n)\nSELECT SUM(LEN(ROUTINE_DEFINITION))\nFROM ROUTINES\n</code></pre>\n"
},
{
"answer_id": 41878293,
"author": "StuKay",
"author_id": 7084741,
"author_profile": "https://Stackoverflow.com/users/7084741",
"pm_score": 2,
"selected": false,
"text": "<p>Need to use DATALENGTH rather than LEN to get the number of bytes rather than the number of characters because the definition column of the sys.sql_modules catalogue view is NVARCHAR(MAX) i.e. Unicode</p>\n\n<pre><code>SELECT Type,\n SUM(Chars) SizeChars,\n SUM(Bytes) SizeBytes,\n SUM(Bytes) / 1024. SizeKB,\n CAST(SUM(Bytes) / 1024 AS VARCHAR) + '.' + CAST(SUM(Bytes) % 1024 AS VARCHAR) SizeKBRemBytes\nFROM\n(\nSELECT o.type_desc Type, \n LEN(sm.definition) Chars,\n DATALENGTH(sm.definition) Bytes\n FROM sys.sql_modules sm\n JOIN sys.objects o ON sm.object_id = o.object_id\n) x\nGROUP BY Type\nORDER BY Type\n</code></pre>\n"
},
{
"answer_id": 56776691,
"author": "Konstantin Taranov",
"author_id": 2298061,
"author_profile": "https://Stackoverflow.com/users/2298061",
"pm_score": 2,
"selected": false,
"text": "<p>Improve Cade Roux answer:</p>\n\n<pre><code>/*\n<documentation>\n <summary>Count size in bytes veiws, triggers, procedures and function in database.</summary>\n <returns>1 data set: RoutinType, SUM LENGTH of objects, SUM DATALENGTH.</returns>\n <issues>No</issues>\n <author>Cade Roux</author>\n <created>2008-10-20</created>\n <modified>2019-06-26 by Konstantin Taranov</modified>\n <version>1.0</version>\n <sourceLink>https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Objects_Size_In_Database.sql</sourceLink>\n <originalLink>https://stackoverflow.com/a/219740/2298061</originalLink>\n</documentation>\n*/\n\nSET NOCOUNT ON;\nSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;\n\nWITH CTE_Routine AS (\n /* Can not use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit */\n SELECT o.type_desc AS RoutineType\n , o.[name] AS RoutineName\n , m.[definition] AS RoutineDefinition\n FROM sys.sql_modules AS m \n INNER JOIN sys.objects AS o ON m.object_id = o.object_id\n)\nSELECT RoutineType\n , SUM(LEN(RoutineDefinition)) AS RoutineLen\n /* DATALENGTH for counting trailing space in the end of objects definitions */\n , SUM(DATALENGTH(RoutineDefinition)) / 2 AS RoutineDatalength\nFROM CTE_Routine\nGROUP BY RoutineType;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21398/"
] |
I was asked for a comprehensive breakdown on space used within a specific database.
I know I can use *sys.dm\_db\_partition\_stats* in SQL Server 2005 to figure out how much space each *table* in a database is using, but is there any way to determine the individual and total size of the *stored procedures* in a database? (Short of opening each one and counting the characters, of course.)
Total space used by stored procs is not likely to be significant (compared to actual *data*), but with hundreds of them, it could add up.
|
```
;WITH ROUTINES AS (
-- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit
SELECT o.type_desc AS ROUTINE_TYPE
,o.[name] AS ROUTINE_NAME
,m.definition AS ROUTINE_DEFINITION
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS o
ON m.object_id = o.object_id
)
SELECT SUM(LEN(ROUTINE_DEFINITION))
FROM ROUTINES
```
|
219,574 |
<p>One thing I've run into a few times is a service class (like a JBoss service) that has gotten overly large due to helper inner classes. I've yet to find a good way to break the class out. These helpers are usually threads. Here's an example:</p>
<pre><code>/** Asset service keeps track of the metadata about assets that live on other
* systems. Complications include the fact the assets have a lifecycle and their
* physical representation lives on other systems that have to be polled to find
* out if the Asset is still there. */
public class AssetService
{
//...various private variables
//...various methods
public AssetService()
{
Job pollerJob = jobService.schedule( new AssetPoller() );
Job lifeCycleJob = jobService.schedule( AssetLifecycleMonitor() );
}
class AssetPoller
{
public void run()
{
// contact remote systems and update this service's private variables that
// track the assets.
}
}
class AssetLifecycleMonitor
{
public void run()
{
// look for assets that have meet criteria for a lifecycle shift
// and update this service's private variables as relevant.
}
}
}
</code></pre>
<p>So, what can happen if I have a couple helpers and they're at all complex, is the overall class file can get really large. I like the inner classes in that it makes clear the classes are wholly owned by the service and exist only to help that service. I've tried breaking the classes out and passing the parent service as a reference, which works mostly, but things I don't like are:
<li>I end up exposing package level accessors so the broken out classes can get to the variables, whereas before I didn't expose the setters at all since the inner classes had direct access.
<li> Plus, things get a bit more wordy as I'm constantly calling accessors rather than the underlying variables. A minor nit, granted.
<li> Convenience methods (e.g. checkAssetIsValid() or some such) need package level exposure now so the helper classes can call them, where as before as inner classes they could be private.
<li> Even worse, I need to pass the service implementation class to the helper classes constructors since I don't want to expose these helpers methods in the interface the service implements because that forces them to be public. This can create some unit test/mocking issues.
<li> Worse yet, any synchronization I wanted to do gets leaked out through some external convenience method (e.g. lockDownAssets() during a poller update). Before, the internal classes had access to private Locks.</p>
<p>So, in short, breaking the classes out loses some of the encapsulation I like. But leaving them in can lead to some large java files. I've yet to find a good way to deal with this. C++ had the concept of "friends" which I've rarely missed, but would actually help in this case.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 219644,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p>Yeap. Probably you need to re-refactor those helpers and not move them all as they are. Some things belong to the service some other to the helper. Probable new classes should be used to encapsulate the data. </p>\n\n<p>One posibility you can use is to AOP to provide fine-grained access, and include in the point cut that the method should be only invoked from the \"friend\" class. Still your method would be exposed :( </p>\n\n<p>I guess there is no easy solution for this.</p>\n"
},
{
"answer_id": 219660,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 2,
"selected": false,
"text": "<p>The line between encapsulation and separation can be difficult to walk. However, I think the main issue here is that you need some kind of solid interaction model to use as a basis of separating your classes.</p>\n\n<p>I think it's reasonable to have external helper utility classes which are used in many places, as long as they don't side effect I don't see an issue. It's also reasonable to have static helper classes, as long as they are well organized, which contain often used methods such as checkAssetIsValid(). This is assuming that checkAssetIsValid does not need to access any external state other than the object you are passing it.</p>\n\n<p>The most important thing for separation is not to have objects which share permanent references in many of these classes. I like to look to functional programming for guidance. Each class should not be reaching into the guts of other classes and changing state. Instead each class which does work should produce and consume container objects. </p>\n\n<p>Visualization can be very helpful too. I noticed a thread on the topic of Java Visualization tools <a href=\"http://www.velocityreviews.com/forums/t138598-uml-class-diagram-generator.html\" rel=\"nofollow noreferrer\">here</a>. Ideally, your class interaction diagram should look more like a tree than a graph.</p>\n\n<p>Also, I just want to note that refactoring a large class into smaller classes can be extremely difficult. It's best to build a suite of unit tests for the public interface at the very least so that it will become immediately obvious if you break something. I know tests have saved me countless hours in the past.</p>\n\n<p>Hopefully some of this will be helpful. I'm kind of just rambling on here.</p>\n"
},
{
"answer_id": 219688,
"author": "caskey",
"author_id": 114986,
"author_profile": "https://Stackoverflow.com/users/114986",
"pm_score": 2,
"selected": false,
"text": "<p>Don't forget to consider why you're trying to break up your large class. Is it for software engineering purposes? E.g. it's a programming hotspot and you have such a large file it causes complicated merges on your developer team?</p>\n\n<p>Is it just a general desire to avoid large classes? In which case it may be that your time would be better spent improving the code you do have.</p>\n\n<p>Is the code becoming difficult to manage, e.g. debugging and ensuring avoidance of unintended side effects is becoming more difficult.</p>\n\n<p>Rick's comment about using unit tests to ensure continued consistent behavior is very valuable and a good idea. It may be that the current design simply precludes refactoring and you're better off re-implementing the same behavior starting from the interface of the original. Be ready for plenty of regresssion testing!</p>\n"
},
{
"answer_id": 219887,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not a fan of excessive use of inner classes. I think that they don't really offer any advantage (when used in the extreme) that putting the code in a normal class wouldn't, and they just serve to make the class file unnecessarily large and hard to follow.</p>\n\n<p>What's the harm if you have to increase the visibility of a few methods? Is it going to completely break your abstraction or interface? I think too often programmers tend to make everything private by default, where there isn't really much of a harm in letting some other classes call your methods - if your design is truly OO-based, that is.</p>\n\n<p>If all of your \"inner helper classes\" need access to some of the same methods, consider putting them in a base class so they can be shared via inheritance.</p>\n"
},
{
"answer_id": 220319,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 4,
"selected": true,
"text": "<p>On bytecode level inner classes are just plain Java classes. Since the Java bytecode verifier does not allow access to private members, it generates synthetic accessor methods for each private field which you use. Also, in order to link the inner class with its enclosing instance, the compiler adds synthetic pointer to the outer 'this'.</p>\n\n<p>Considering this, the inner classes are just a layer of syntax sugar. They are convenient and you have listed some good points, so I'd list some negative aspects which you might want to consider:</p>\n\n<ul>\n<li>Your inner class has a hidden dependency to the <em>whole</em> parent class, which obfuscates its inbound interface. If you extract it as package-private class you have a chance to improve your design and make it more maintainable. Initially it's more verbose, but often you'd find that:\n\n<ul>\n<li>Instead of exposing 10 accessors you actually want to share a single value object. Often you would find that you don't really need a reference to the whole outer class. This also works well with IoC. </li>\n<li>Instead of providing methods for explicit locking, it's more maintainable to encapsulate the operation with its context in a separate class (or move it to one of the two classes - outer or formerly-inner).</li>\n<li>Convenience methods belong in package private utility classes. You can use the Java5 static import to make them appear as local.</li>\n</ul></li>\n<li>Your outer class can bypass any protection levels and access private members of your inner class directly. This is not bad thing per se, but it takes away one of the language means of expressing your design.</li>\n<li>Since your inner class is embedded in exactly one outer class, the only way to reuse it is to subclass the outer class. An alternative would be to pass explicit reference to a package-private interface that the outer class implements. This would allow you to mock the outer and better test the inner class.</li>\n<li>Though recent debuggers are quite good, I have experienced problems with debugging inner classes before (conditional breakpoint scope confusion, not stopping at breakpoints, etc.)</li>\n<li>Private classes bloat your bytecode. See my first paragraph - often there is an API that you could use and reduce the number of synthetic cruft.</li>\n</ul>\n\n<p>P.S. I'm talking about non-trivial inner classes (especially ones that do not implement any interfaces). Three line listener implementations are good.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29734/"
] |
One thing I've run into a few times is a service class (like a JBoss service) that has gotten overly large due to helper inner classes. I've yet to find a good way to break the class out. These helpers are usually threads. Here's an example:
```
/** Asset service keeps track of the metadata about assets that live on other
* systems. Complications include the fact the assets have a lifecycle and their
* physical representation lives on other systems that have to be polled to find
* out if the Asset is still there. */
public class AssetService
{
//...various private variables
//...various methods
public AssetService()
{
Job pollerJob = jobService.schedule( new AssetPoller() );
Job lifeCycleJob = jobService.schedule( AssetLifecycleMonitor() );
}
class AssetPoller
{
public void run()
{
// contact remote systems and update this service's private variables that
// track the assets.
}
}
class AssetLifecycleMonitor
{
public void run()
{
// look for assets that have meet criteria for a lifecycle shift
// and update this service's private variables as relevant.
}
}
}
```
So, what can happen if I have a couple helpers and they're at all complex, is the overall class file can get really large. I like the inner classes in that it makes clear the classes are wholly owned by the service and exist only to help that service. I've tried breaking the classes out and passing the parent service as a reference, which works mostly, but things I don't like are:
- I end up exposing package level accessors so the broken out classes can get to the variables, whereas before I didn't expose the setters at all since the inner classes had direct access.
- Plus, things get a bit more wordy as I'm constantly calling accessors rather than the underlying variables. A minor nit, granted.
- Convenience methods (e.g. checkAssetIsValid() or some such) need package level exposure now so the helper classes can call them, where as before as inner classes they could be private.
- Even worse, I need to pass the service implementation class to the helper classes constructors since I don't want to expose these helpers methods in the interface the service implements because that forces them to be public. This can create some unit test/mocking issues.
- Worse yet, any synchronization I wanted to do gets leaked out through some external convenience method (e.g. lockDownAssets() during a poller update). Before, the internal classes had access to private Locks.
So, in short, breaking the classes out loses some of the encapsulation I like. But leaving them in can lead to some large java files. I've yet to find a good way to deal with this. C++ had the concept of "friends" which I've rarely missed, but would actually help in this case.
Thoughts?
|
On bytecode level inner classes are just plain Java classes. Since the Java bytecode verifier does not allow access to private members, it generates synthetic accessor methods for each private field which you use. Also, in order to link the inner class with its enclosing instance, the compiler adds synthetic pointer to the outer 'this'.
Considering this, the inner classes are just a layer of syntax sugar. They are convenient and you have listed some good points, so I'd list some negative aspects which you might want to consider:
* Your inner class has a hidden dependency to the *whole* parent class, which obfuscates its inbound interface. If you extract it as package-private class you have a chance to improve your design and make it more maintainable. Initially it's more verbose, but often you'd find that:
+ Instead of exposing 10 accessors you actually want to share a single value object. Often you would find that you don't really need a reference to the whole outer class. This also works well with IoC.
+ Instead of providing methods for explicit locking, it's more maintainable to encapsulate the operation with its context in a separate class (or move it to one of the two classes - outer or formerly-inner).
+ Convenience methods belong in package private utility classes. You can use the Java5 static import to make them appear as local.
* Your outer class can bypass any protection levels and access private members of your inner class directly. This is not bad thing per se, but it takes away one of the language means of expressing your design.
* Since your inner class is embedded in exactly one outer class, the only way to reuse it is to subclass the outer class. An alternative would be to pass explicit reference to a package-private interface that the outer class implements. This would allow you to mock the outer and better test the inner class.
* Though recent debuggers are quite good, I have experienced problems with debugging inner classes before (conditional breakpoint scope confusion, not stopping at breakpoints, etc.)
* Private classes bloat your bytecode. See my first paragraph - often there is an API that you could use and reduce the number of synthetic cruft.
P.S. I'm talking about non-trivial inner classes (especially ones that do not implement any interfaces). Three line listener implementations are good.
|
219,581 |
<p>I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms. How can this be done?</p>
|
[
{
"answer_id": 219771,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 2,
"selected": true,
"text": "<p>I haven't tried this myself but I would give it a shot:</p>\n\n<pre><code>System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip();\nformToolTip .SetToolTip(item, \"Row Tooltip\");\n</code></pre>\n\n<p>Where <code>item</code> corresponds to the cell you're setting the tool tip for.</p>\n"
},
{
"answer_id": 278498,
"author": "Russ",
"author_id": 32772,
"author_profile": "https://Stackoverflow.com/users/32772",
"pm_score": 0,
"selected": false,
"text": "<pre><code>row.cells[indexof].ToolTipText= \"tootip here\".\n</code></pre>\n\n<p>In winforms, it doesn't look like you can do the whole row.</p>\n\n<p>if you NEED the whole row you can loop through the cells.</p>\n\n<pre><code> foreach (DataGridViewCell cell in row.Cells)\n {\n cell.ToolTipText = \"tooltip here\";\n }\n</code></pre>\n"
},
{
"answer_id": 1198722,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>If TypeOf control Is TabControl Then\n For Each control1 In control.Controls\n If TypeOf control1 Is TabPage Then\n strControlText = fnGetLanguage(control1.Text)\n End If\n For Each control2 In control1.Controls\n If TypeOf control2 Is label Then\n strControlText = control2.Text\n ' strToolTipText = ToolTip.GetToolTip(control2)\n If strControlText.Contains(\"*\") Then\n strDizi = Split(strControlText, \" \")\n strControlText = fnGetLanguage(strDizi(0))\n Else\n strControlText = fnGetLanguage(control2.Text)\n End If\n ElseIf TypeOf control2 Is DataGridView Then\n For i = 0 To control2.ColumnCount - 1\n strControlText = control2.Columns(i).HeaderText\n strControlText = fnGetLanguage(strControlText)\n Next\n ElseIf TypeOf control2 Is ComboBox Then\n strControlText = control2.Text\n 'strToolTipText = ToolTip.GetToolTip(control2)\n If control2.DataSource Is Nothing Then\n For i = 0 To control2.Items.Count - 1\n strControlText = control2.Items(i)\n strControlText = fnGetLanguage(strControlText)\n Next\n Else\n For i = 0 To control2.Items.Count - 1\n strControlText = control2.Items(i).ToString\n strControlText = fnGetLanguage(strControlText)\n Next\n End If\n End If\n Next\n Next\nEnd If\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
] |
I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms. How can this be done?
|
I haven't tried this myself but I would give it a shot:
```
System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip();
formToolTip .SetToolTip(item, "Row Tooltip");
```
Where `item` corresponds to the cell you're setting the tool tip for.
|
219,590 |
<p>What is the best way to localize a collection (IEnumerable)?
From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list. </p>
<p>How can i get the code underneath working? Any ideas? Maybe better options? </p>
<pre><code>public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo)
{
foreach(string item in items)
{
/*Error underneath, cannot assign to item*/
item = ResourceHelper.GetString(item, cultureInfo);
}
return (items);
}
</code></pre>
|
[
{
"answer_id": 219611,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>have you tried something where you <a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx\" rel=\"nofollow noreferrer\">yield</a> the item?</p>\n\n<pre><code>public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)\n{\n foreach (string item in items)\n {\n yield return ResourceHelper.GetString(item,culture);\n }\n}\n</code></pre>\n\n<p>this won't change any other the items in the collection you are enumerating over, but it will return what you want it to.</p>\n"
},
{
"answer_id": 219727,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Simple change to get it to return a new enumerable collection of localized values:</p>\n\n<pre><code>public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo cultureInfo)\n{\n List<string> newItems = new List<string>();\n foreach(string item in items)\n {\n newItems.Add( ResourceHelper.GetString(item, cultureInfo) );\n }\n return newItems;\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27857/"
] |
What is the best way to localize a collection (IEnumerable)?
From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list.
How can i get the code underneath working? Any ideas? Maybe better options?
```
public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo)
{
foreach(string item in items)
{
/*Error underneath, cannot assign to item*/
item = ResourceHelper.GetString(item, cultureInfo);
}
return (items);
}
```
|
have you tried something where you [yield](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx) the item?
```
public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)
{
foreach (string item in items)
{
yield return ResourceHelper.GetString(item,culture);
}
}
```
this won't change any other the items in the collection you are enumerating over, but it will return what you want it to.
|
219,594 |
<p>I'm wondering what the best way is to have a "if all else fails catch it".</p>
<p>I mean, you're handling as much exceptions as possible in your application,
but still there are bound to be bugs, so I need to have something that
catches all unhandled exceptions so I can collect information and store
them in a database or submit them to a web service.</p>
<p>Does the AppDomain.CurrentDomain.UnhandledException event capture everything?
Even if the application is multithreaded?</p>
<p>Side note: Windows Vista exposes native API functions that allow any application
to recover itself after a crash... can't think of the name now... but I'd rather not
use it, as many of our users are still using Windows XP.</p>
|
[
{
"answer_id": 219607,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 4,
"selected": false,
"text": "<p>In ASP.NET, you use the <code>Application_Error</code> function in the <code>Global.asax</code> file.</p>\n\n<p>In WinForms, you use the <code>MyApplication_UnhandledException</code> in the <code>ApplicationEvents</code> file </p>\n\n<p>Both of these functions are called if an unhandled exception occurs in your code. You can log the exception and present a nice message to the user from these functions.</p>\n"
},
{
"answer_id": 219641,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 2,
"selected": false,
"text": "<p>For WinForms, don't forget to attach to the current Thread's unhandled exception event too (especially if you are using multi threading).</p>\n\n<p>Some links on best practices <a href=\"http://msdn.microsoft.com/en-us/library/seyhszts.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://dturini.blogspot.com/2005/02/exception-handling-best-practices-in.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET\" rel=\"nofollow noreferrer\">here (probably the best exception handling article for .net)</a></p>\n"
},
{
"answer_id": 219646,
"author": "Bob Nadler",
"author_id": 2514,
"author_profile": "https://Stackoverflow.com/users/2514",
"pm_score": 4,
"selected": false,
"text": "<p>For Winform applications, in addition to AppDomain.CurrentDomain.UnhandledException I also use <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\" rel=\"noreferrer\">Application.ThreadException</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.setunhandledexceptionmode.aspx\" rel=\"noreferrer\">Application.SetUnhandledExceptionMode</a> (w/ UnhandledExceptionMode.CatchException). This combination seems to catch everything.</p>\n"
},
{
"answer_id": 219703,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": false,
"text": "<p>On the main thread, you have the following options:</p>\n\n<ul>\n<li>Console or Service application: <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx\" rel=\"nofollow noreferrer\"><code>AppDomain.CurrentDomain.UnhandledException</code></a></li>\n<li>WinForms application: <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\" rel=\"nofollow noreferrer\"><code>Application.ThreadException</code></a></li>\n<li>Web application: Global.asax's <code>Application_Error</code></li>\n</ul>\n\n<p>For other threads:</p>\n\n<ul>\n<li>Secondary threads have no unhandled-exceptions; use <a href=\"http://www.codeproject.com/KB/threads/SafeThread.aspx\" rel=\"nofollow noreferrer\">SafeThread</a></li>\n<li>Worker threads: (timer, threadpool) there is no safety net at all!</li>\n</ul>\n\n<p>Bear in mind that these events do not <em>handle</em> exceptions, they merely <em>report</em> them to the application--often when it is far too late to do anything useful/sane about them</p>\n\n<p>Logging exceptions is good, but monitoring applications is better ;-)</p>\n\n<p>Caveat: I am the author of the <a href=\"http://www.codeproject.com/KB/threads/SafeThread.aspx\" rel=\"nofollow noreferrer\">SafeThread</a> article.</p>\n"
},
{
"answer_id": 219917,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 2,
"selected": false,
"text": "<p>There's also a cool thing called <a href=\"http://code.google.com/p/elmah/\" rel=\"nofollow noreferrer\">ELMAH</a> that will log any ASP.NET errors that occur in a web application. I know you're asking about a Winform App solution, but I felt this could be beneficial to anyone needing this type of thing on a web app. We use it where I work and it's been very helpful in debugging (especially on production servers!)</p>\n\n<p>Here's some features that it has (pulled right off the page):</p>\n\n<blockquote>\n <ul>\n <li>Logging of nearly all unhandled exceptions.</li>\n <li>A web page to remotely view the entire log of recoded exceptions.</li>\n <li>A web page to remotely view the full details of any one logged exception.</li>\n <li>In many cases, you can review the original yellow screen of death that\n ASP.NET generated for a given\n exception, even with customErrors mode\n turned off.</li>\n <li>An e-mail notification of each error at the time it occurs.</li>\n <li>An RSS feed of the last 15 errors from the log.</li>\n <li>A number of backing storage implementations for the log, including\n in-memory, Microsoft SQL Server and\n several contributed by the community.</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 220083,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 2,
"selected": false,
"text": "<p>You can monitor most exceptions in that handler even in multithreaded apps, but .NET (starting with 2.0) won't allow you to cancel unhandled exceptions unless you enable the 1.1 compatibility mode. When that happens the AppDomain will be shut down no matter what. The best you could do is launch the app in a different AppDomain so that you can handle this exception and create a new AppDomain to restart the app. </p>\n"
},
{
"answer_id": 886887,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 0,
"selected": false,
"text": "<p>I am using the following approach, which works and reduces greatly the amount of code ( yet I am not sure if there is a better way or what the pitfalls of it might be.\nWhenever you call: \nI quess the quys giving minuses would be polite enough to clarify their actions ; )</p>\n\n<pre><code>try \n{\n CallTheCodeThatMightThrowException()\n }\ncatch (Exception ex)\n{\n System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();\n Utils.ErrorHandler.Trap ( ref objUser, st, ex );\n} //eof catch\n</code></pre>\n\n<p>And here is the ErrorHandler code : \nJust to make clear- : objUser - is the object modelling the appusers ( you might get info such as domain name , department , region etc. for logging purposes\nILog logger - is the logging object - e.g. the one performing the logging activities\nStackTrace st - the StackTrace object giving you debugging info for your app</p>\n\n<pre><code>using System;\nusing log4net; //or another logging platform\n\nnamespace GenApp.Utils\n{\n public class ErrorHandler\n {\n public static void Trap ( Bo.User objUser, ILog logger, System.Diagnostics.StackTrace st, Exception ex )\n {\n if (ex is NullReferenceException)\n { \n //do stuff for this ex type\n } //eof if\n\n if (ex is System.InvalidOperationException) \n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.IndexOutOfRangeException) \n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.Data.SqlClient.SqlException)\n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.FormatException)\n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is Exception)\n {\n //do stuff for this ex type\n } //eof catch\n\n } //eof method \n\n }//eof class \n} //eof namesp\n</code></pre>\n"
},
{
"answer_id": 1055954,
"author": "bohdan_trotsenko",
"author_id": 58768,
"author_profile": "https://Stackoverflow.com/users/58768",
"pm_score": 6,
"selected": true,
"text": "<p>I have just played with AppDomain's UnhandledException behavior,\n(this is the last stage the unhandled exception is registered at)</p>\n\n<p>Yes, after processing the event handlers your application will be terminated and the nasty \"... program stopped working dialog\" shown.</p>\n\n<p>:)\nYou <em>still</em> can avoid that.</p>\n\n<p>Check out:</p>\n\n<pre><code>class Program\n{\n void Run()\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n\n Console.WriteLine(\"Press enter to exit.\");\n\n do\n {\n (new Thread(delegate()\n {\n throw new ArgumentException(\"ha-ha\");\n })).Start();\n\n } while (Console.ReadLine().Trim().ToLowerInvariant() == \"x\");\n\n\n Console.WriteLine(\"last good-bye\");\n }\n\n int r = 0;\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n Interlocked.Increment(ref r);\n Console.WriteLine(\"handled. {0}\", r);\n Console.WriteLine(\"Terminating \" + e.IsTerminating.ToString());\n\n Thread.CurrentThread.IsBackground = true;\n Thread.CurrentThread.Name = \"Dead thread\"; \n\n while (true)\n Thread.Sleep(TimeSpan.FromHours(1));\n //Process.GetCurrentProcess().Kill();\n }\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"...\");\n (new Program()).Run();\n }\n}\n</code></pre>\n\n<p><strong>P.S.</strong> Do handle the unhandled for Application.ThreadException (WinForms) or DispatcherUnhandledException (WPF) at the higher level.</p>\n"
},
{
"answer_id": 1482364,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "<p>In a manged GUI app, by default, exceptions that originate in the GUI thread are handled by whatever is assigned to the Application.ThreadException.</p>\n\n<p>Exceptions that originate in the other threads are handled by AppDomain.CurrentDomain.UnhandledException.</p>\n\n<p>If you want your GUI thread exceptions to work just like your-non GUI ones, so that they get handled by AppDomain.CurrentDomain.UnhandledException, you can do this:</p>\n\n<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);\n</code></pre>\n\n<p>An advantage to catching the GUI thread exceptions using ThreadException is that you can give the use the options of letting the app continue. To make sure no config files are overriding default behavior, you can call: </p>\n\n<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);\n</code></pre>\n\n<p>You are still vulnerable to exceptions from badly behaved native dlls. If a native dll installs its own handler using Win32 SetUnhandledExceptionFilter, it is supposed to save the pointer to the previous filter and call it too. If it doesn't do that, your handler wont' get called.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
I'm wondering what the best way is to have a "if all else fails catch it".
I mean, you're handling as much exceptions as possible in your application,
but still there are bound to be bugs, so I need to have something that
catches all unhandled exceptions so I can collect information and store
them in a database or submit them to a web service.
Does the AppDomain.CurrentDomain.UnhandledException event capture everything?
Even if the application is multithreaded?
Side note: Windows Vista exposes native API functions that allow any application
to recover itself after a crash... can't think of the name now... but I'd rather not
use it, as many of our users are still using Windows XP.
|
I have just played with AppDomain's UnhandledException behavior,
(this is the last stage the unhandled exception is registered at)
Yes, after processing the event handlers your application will be terminated and the nasty "... program stopped working dialog" shown.
:)
You *still* can avoid that.
Check out:
```
class Program
{
void Run()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Console.WriteLine("Press enter to exit.");
do
{
(new Thread(delegate()
{
throw new ArgumentException("ha-ha");
})).Start();
} while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
Console.WriteLine("last good-bye");
}
int r = 0;
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Interlocked.Increment(ref r);
Console.WriteLine("handled. {0}", r);
Console.WriteLine("Terminating " + e.IsTerminating.ToString());
Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "Dead thread";
while (true)
Thread.Sleep(TimeSpan.FromHours(1));
//Process.GetCurrentProcess().Kill();
}
static void Main(string[] args)
{
Console.WriteLine("...");
(new Program()).Run();
}
}
```
**P.S.** Do handle the unhandled for Application.ThreadException (WinForms) or DispatcherUnhandledException (WPF) at the higher level.
|
219,598 |
<p>I’m writing a test that expects to receive an event from an object that it is calling. Specifically, I am calling out to an object that connects to an AIX machine via SSH (using the open source Granados project), then disconnecting, and I want to make sure I receive the OnConnectionClosed event that is being raised during the disconnect. It sounds simple enough, and I’ve written many tests like this in the past, but this time some strange behavior is occurring that I believe is related to threading.</p>
<p>Basically, the object I call is raising the ‘OnConnectionClosed’ event on a different thread than what I call it from. What I’m seeing is that when I run the test by selecting ‘Debug Test’ from the UI, it passes, but if I choose ‘Run Test’, it fails (even if there are no breakpoints set during the debug run). I’ve done some Googling and found <a href="http://plainoldstan.blogspot.com/2008/09/run-unit-test-on-mta-thread-vsts-test.html" rel="nofollow noreferrer">this post</a> that seems to indicate that by default the MSTest host runs in Single Thread mode but that a config change can make it run in Multi Thread mode. This sounded like it would logically fix my problem, but of course, it did not.</p>
<p>Some other posts I’ve come across also make me think that MSTest is simply not monitoring the background threads (so the events raised by them are not being ‘heard’). This would also make sense, and since it seems to work in debug mode, and it seems like the fix above should logically solve that problem, then I’m confused as to why it’s not working. It is possible that I’m simply not correctly dealing with the threads, although I would expect that to still be a problem in debug mode if it were the case.</p>
<p>Has anyone else tried to test something in a similar way? If so, did you encounter similar problems? And if so, how did you resolve them?</p>
<p>I’ve pasted the relevant unit test code below (I’ve removed the connection info for security reasons). </p>
<pre><code>[TestClass]
public class SSHReaderTests
{
private bool received = false;
private delegate bool SimpleFunc();
[TestInitialize]
public void MyTestInitialize()
{
received = false;
}
[TestMethod]
public void Should_raise_OnReaderConnectionClosed_event_after_successful_connection_is_disconnected()
{
IReader reader = new SSHReader();
reader.OnReaderConnectionClosed += delegate
{
received = true;
};
reader.Connect("*****", "*****", "*****");
//Assert.IsTrue(reader.IsConnected);
reader.Disconnect();
//Assert.IsFalse(reader.IsConnected);
Assert.IsTrue(WaitUntilTrue(delegate {
return received; }, 30000, 1000));
}
private static bool WaitUntilTrue(SimpleFunc func, int timeoutInMillis, int timeBetweenChecksInMillis)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
{
if (func())
return true;
Thread.Sleep(timeBetweenChecksInMillis);
}
return false;
}
}
</code></pre>
|
[
{
"answer_id": 219922,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 2,
"selected": false,
"text": "<p>Use the WaitHandle classes in the System.Threading namespace. Either, AutoResetEvent or ManualResetEvent. The difference between the two is that AutoResetEvent lets one thread proceed each time it is set, while ManualResetEvent releases all waiting threads on set.</p>\n\n<p>The reason your example doesn't work has to do with compiler optimizations. The code does not actually get compiled to what you would think at first glance. Most likely, the compiler will do something like place the local variable in a register and never actually fetch it during your loop that checks. You can avoid this type of thing with the volatile keyword, but I would highly recommend reading up on threading and concurrency for more details. Joe Duffy's blog at <a href=\"http://www.bluebytesoftware.com\" rel=\"nofollow noreferrer\">http://www.bluebytesoftware.com</a> is a great resource to get started, and I highly recommend his Concurrency Programming on Windows book that is coming out soon.</p>\n"
},
{
"answer_id": 220067,
"author": "Kevin Dostalek",
"author_id": 22732,
"author_profile": "https://Stackoverflow.com/users/22732",
"pm_score": 0,
"selected": false,
"text": "<p>Not exactly what you arr asking about, but you may find some workable solutions or at least ideas by checking out the MS Research project called <a href=\"http://research.microsoft.com/projects/CHESS\" rel=\"nofollow noreferrer\">CHESS</a>. It's for multithreaded concurrency testing in .net.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I’m writing a test that expects to receive an event from an object that it is calling. Specifically, I am calling out to an object that connects to an AIX machine via SSH (using the open source Granados project), then disconnecting, and I want to make sure I receive the OnConnectionClosed event that is being raised during the disconnect. It sounds simple enough, and I’ve written many tests like this in the past, but this time some strange behavior is occurring that I believe is related to threading.
Basically, the object I call is raising the ‘OnConnectionClosed’ event on a different thread than what I call it from. What I’m seeing is that when I run the test by selecting ‘Debug Test’ from the UI, it passes, but if I choose ‘Run Test’, it fails (even if there are no breakpoints set during the debug run). I’ve done some Googling and found [this post](http://plainoldstan.blogspot.com/2008/09/run-unit-test-on-mta-thread-vsts-test.html) that seems to indicate that by default the MSTest host runs in Single Thread mode but that a config change can make it run in Multi Thread mode. This sounded like it would logically fix my problem, but of course, it did not.
Some other posts I’ve come across also make me think that MSTest is simply not monitoring the background threads (so the events raised by them are not being ‘heard’). This would also make sense, and since it seems to work in debug mode, and it seems like the fix above should logically solve that problem, then I’m confused as to why it’s not working. It is possible that I’m simply not correctly dealing with the threads, although I would expect that to still be a problem in debug mode if it were the case.
Has anyone else tried to test something in a similar way? If so, did you encounter similar problems? And if so, how did you resolve them?
I’ve pasted the relevant unit test code below (I’ve removed the connection info for security reasons).
```
[TestClass]
public class SSHReaderTests
{
private bool received = false;
private delegate bool SimpleFunc();
[TestInitialize]
public void MyTestInitialize()
{
received = false;
}
[TestMethod]
public void Should_raise_OnReaderConnectionClosed_event_after_successful_connection_is_disconnected()
{
IReader reader = new SSHReader();
reader.OnReaderConnectionClosed += delegate
{
received = true;
};
reader.Connect("*****", "*****", "*****");
//Assert.IsTrue(reader.IsConnected);
reader.Disconnect();
//Assert.IsFalse(reader.IsConnected);
Assert.IsTrue(WaitUntilTrue(delegate {
return received; }, 30000, 1000));
}
private static bool WaitUntilTrue(SimpleFunc func, int timeoutInMillis, int timeBetweenChecksInMillis)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.ElapsedMilliseconds < timeoutInMillis)
{
if (func())
return true;
Thread.Sleep(timeBetweenChecksInMillis);
}
return false;
}
}
```
|
Use the WaitHandle classes in the System.Threading namespace. Either, AutoResetEvent or ManualResetEvent. The difference between the two is that AutoResetEvent lets one thread proceed each time it is set, while ManualResetEvent releases all waiting threads on set.
The reason your example doesn't work has to do with compiler optimizations. The code does not actually get compiled to what you would think at first glance. Most likely, the compiler will do something like place the local variable in a register and never actually fetch it during your loop that checks. You can avoid this type of thing with the volatile keyword, but I would highly recommend reading up on threading and concurrency for more details. Joe Duffy's blog at <http://www.bluebytesoftware.com> is a great resource to get started, and I highly recommend his Concurrency Programming on Windows book that is coming out soon.
|
219,604 |
<p>How would you convert a parapraph to hex notation, and then back again into its original string form?</p>
<p>(C#)</p>
<p>A side note: would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?</p>
|
[
{
"answer_id": 219619,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public string ConvertToHex(string asciiString)\n{\n string hex = \"\";\n foreach (char c in asciiString)\n {\n int tmp = c;\n hex += String.Format(\"{0:x2}\", (uint)System.Convert.ToUInt32(tmp.ToString()));\n }\n return hex;\n}\n</code></pre>\n"
},
{
"answer_id": 219620,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>What exactly do you mean by \"hex notation\"? That usually refers to encoding binary data, not text. You'd need to encode the text somehow (e.g. using UTF-8) and then encode the binary data as text by converting each byte to a pair of characters.</p>\n\n<pre><code>using System;\nusing System.Text;\n\npublic class Hex\n{\n static void Main()\n {\n string original = \"The quick brown fox jumps over the lazy dog.\";\n\n byte[] binary = Encoding.UTF8.GetBytes(original);\n string hex = BytesToHex(binary);\n Console.WriteLine(\"Hex: {0}\", hex);\n byte[] backToBinary = HexToBytes(hex);\n\n string restored = Encoding.UTF8.GetString(backToBinary);\n Console.WriteLine(\"Restored: {0}\", restored);\n }\n\n private static readonly char[] HexChars = \"0123456789ABCDEF\".ToCharArray();\n\n public static string BytesToHex(byte[] data)\n {\n StringBuilder builder = new StringBuilder(data.Length*2);\n foreach(byte b in data)\n {\n builder.Append(HexChars[b >> 4]);\n builder.Append(HexChars[b & 0xf]);\n }\n return builder.ToString();\n }\n\n public static byte[] HexToBytes(string text)\n {\n if ((text.Length & 1) != 0)\n {\n throw new ArgumentException(\"Invalid hex: odd length\");\n }\n byte[] ret = new byte[text.Length/2];\n for (int i=0; i < text.Length; i += 2)\n {\n ret[i/2] = (byte)(ParseNybble(text[i]) << 4 | ParseNybble(text[i+1]));\n }\n return ret;\n }\n\n private static int ParseNybble(char c)\n {\n if (c >= '0' && c <= '9')\n {\n return c-'0';\n }\n if (c >= 'A' && c <= 'F')\n {\n return c-'A'+10;\n }\n if (c >= 'a' && c <= 'f')\n {\n return c-'A'+10;\n }\n throw new ArgumentOutOfRangeException(\"Invalid hex digit: \" + c);\n }\n}\n</code></pre>\n\n<p>No, doing this would not shrink it at all. Quite the reverse - you'd end up with a lot more text! However, you could compress the binary form. In terms of representing arbitrary binary data as text, Base64 is more efficient than plain hex. Use <a href=\"http://msdn.microsoft.com/en-us/library/dhx0d524.aspx\" rel=\"noreferrer\">Convert.ToBase64String</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx\" rel=\"noreferrer\">Convert.FromBase64String</a> for the conversions.</p>\n"
},
{
"answer_id": 219635,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 0,
"selected": false,
"text": "<p>While I can't help much on the C# implementation, I would highly recommend <a href=\"http://en.wikipedia.org/wiki/Lzw\" rel=\"nofollow noreferrer\">LZW</a> as a simple-to-implement data compression algorithm for you to use.</p>\n"
},
{
"answer_id": 223444,
"author": "Patrick Szalapski",
"author_id": 7453,
"author_profile": "https://Stackoverflow.com/users/7453",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps the answer can be more quickly reached if we ask: what are you really trying to do? Converting an ordinary string to a string of a hex representation seems like the wrong approach to anything, unless you are making a hexidecimal/encoding tutorial for the web.</p>\n"
},
{
"answer_id": 1065167,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static byte[] HexToBinary(string s) {\n byte[] b = new byte[s.Length / 2];\n for (int i = 0; i < b.Length; i++)\n b[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);\n return b;\n}\nstatic string BinaryToHex(byte[] b) {\n StringBuilder sb = new StringBuilder(b.Length * 2);\n for (int i = 0; i < b.Length; i++)\n sb.Append(Convert.ToString(256 + b[i], 16).Substring(1, 2));\n return sb.ToString();\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How would you convert a parapraph to hex notation, and then back again into its original string form?
(C#)
A side note: would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?
|
What exactly do you mean by "hex notation"? That usually refers to encoding binary data, not text. You'd need to encode the text somehow (e.g. using UTF-8) and then encode the binary data as text by converting each byte to a pair of characters.
```
using System;
using System.Text;
public class Hex
{
static void Main()
{
string original = "The quick brown fox jumps over the lazy dog.";
byte[] binary = Encoding.UTF8.GetBytes(original);
string hex = BytesToHex(binary);
Console.WriteLine("Hex: {0}", hex);
byte[] backToBinary = HexToBytes(hex);
string restored = Encoding.UTF8.GetString(backToBinary);
Console.WriteLine("Restored: {0}", restored);
}
private static readonly char[] HexChars = "0123456789ABCDEF".ToCharArray();
public static string BytesToHex(byte[] data)
{
StringBuilder builder = new StringBuilder(data.Length*2);
foreach(byte b in data)
{
builder.Append(HexChars[b >> 4]);
builder.Append(HexChars[b & 0xf]);
}
return builder.ToString();
}
public static byte[] HexToBytes(string text)
{
if ((text.Length & 1) != 0)
{
throw new ArgumentException("Invalid hex: odd length");
}
byte[] ret = new byte[text.Length/2];
for (int i=0; i < text.Length; i += 2)
{
ret[i/2] = (byte)(ParseNybble(text[i]) << 4 | ParseNybble(text[i+1]));
}
return ret;
}
private static int ParseNybble(char c)
{
if (c >= '0' && c <= '9')
{
return c-'0';
}
if (c >= 'A' && c <= 'F')
{
return c-'A'+10;
}
if (c >= 'a' && c <= 'f')
{
return c-'A'+10;
}
throw new ArgumentOutOfRangeException("Invalid hex digit: " + c);
}
}
```
No, doing this would not shrink it at all. Quite the reverse - you'd end up with a lot more text! However, you could compress the binary form. In terms of representing arbitrary binary data as text, Base64 is more efficient than plain hex. Use [Convert.ToBase64String](http://msdn.microsoft.com/en-us/library/dhx0d524.aspx) and [Convert.FromBase64String](http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx) for the conversions.
|
219,637 |
<p>The code is,</p>
<pre><code>set VAR=before
if "%VAR%" == "before" (
set VAR=after;
echo %VAR%
)
</code></pre>
<p>What will the preceding Windows .bat file code segment display? Why? (i.e. why doesn't it behave as you might first think)?</p>
|
[
{
"answer_id": 219658,
"author": "Sean Sexton",
"author_id": 22357,
"author_profile": "https://Stackoverflow.com/users/22357",
"pm_score": 3,
"selected": true,
"text": "<p>Obviously, you'd think the output would be \"after\", given that we reset the env variable inside the loop. </p>\n\n<p>But the output will actually be \"before\". The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it's executed. So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered. </p>\n\n<p>You can make this work by using delayed environment variable expansion (need to enable it). If it's enabled, you can then do:</p>\n\n<pre><code>set VAR=before\n\nif \"%VAR%\" == \"before\" (\n\n set VAR=after;\n\n echo !VAR!\n\n)\n</code></pre>\n\n<p>You can enable delayed environment variable expansion using the /v option when starting cmd.exe.</p>\n\n<p>[Backstory--many of us still use legacy .bat files to drive things like make procedures, etc. Obviously there are better scripting tools, but not always an option to use them. I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing. So it's useful to understand how the interpreter does variable substitution].</p>\n"
},
{
"answer_id": 219667,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>The substitution for <code>%VAR%</code> occurs before the execution of the command. Even though there are several commands spread over several lines, the grouping of them in parens <code>(...)</code> causes the cmd.exe parser to read the whole thing in as a single command. So what gets executed looks like the following to the interpreter.</p>\n\n<pre><code>set VAR=before\n\nif \"before\" == \"before\" (\n\nset VAR=after;\n\necho before\n\n)\n</code></pre>\n\n<p>This is one of the many things that make batch file processing rather painful hen trying to do anything more than simple stuff.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22357/"
] |
The code is,
```
set VAR=before
if "%VAR%" == "before" (
set VAR=after;
echo %VAR%
)
```
What will the preceding Windows .bat file code segment display? Why? (i.e. why doesn't it behave as you might first think)?
|
Obviously, you'd think the output would be "after", given that we reset the env variable inside the loop.
But the output will actually be "before". The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it's executed. So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered.
You can make this work by using delayed environment variable expansion (need to enable it). If it's enabled, you can then do:
```
set VAR=before
if "%VAR%" == "before" (
set VAR=after;
echo !VAR!
)
```
You can enable delayed environment variable expansion using the /v option when starting cmd.exe.
[Backstory--many of us still use legacy .bat files to drive things like make procedures, etc. Obviously there are better scripting tools, but not always an option to use them. I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing. So it's useful to understand how the interpreter does variable substitution].
|
219,668 |
<p>I'm looking for best practices to integrate log4net to SharePoint for web request, feature activation and all timer stuff. </p>
<p>I have several subprojects in my farm, and I would like to have only one Log4Net.config file.</p>
<p><strong>[Edit]</strong><br>
Not only I need to configure log4net for the web application, which is easy to do (I use global.asax, and a log4net.config file, so I can modify log settings withtout reloading the webapp), but I also need to log asynchronous events:</p>
<ul>
<li>Event Handler (like ItemAdded)</li>
<li>Timer Jobs</li>
<li>...</li>
</ul>
|
[
{
"answer_id": 219702,
"author": "Nat",
"author_id": 13813,
"author_profile": "https://Stackoverflow.com/users/13813",
"pm_score": 0,
"selected": false,
"text": "<p>You could release the config file as part of the solution package(s) to the 12 hive (use <a href=\"http://www.codeplex.com/stsdev\" rel=\"nofollow noreferrer\">STSDev</a>) to create any packages). This would give you a set location for the config and any changes to it can be released in a controlled manner (i.e. no need for manual editm, just roll back and re-install the solution).</p>\n"
},
{
"answer_id": 222646,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 1,
"selected": false,
"text": "<p>Firstly, you will need to modify the web.config where your SharePoint virtual directory resides. This is because you'll need to add SafeControl entries to trust the log4net assembly. You can update the web.config programmatically using the SPWebConfigModification class in a feature receiver. As you have to modify web.config anyway, you may want to consider including your log4net config inside and not set up an external log4net config.</p>\n\n<p>However, if you'd still like to do this, it may work if you add the following to the web.config file:</p>\n\n<pre><code><configuration ...>\n ...\n <configSections>\n <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />\n </configSections>\n <log4net configSource=\"log4Net.config\">\n ...\n</configuration>\n</code></pre>\n\n<p>The log4net.config file should then be able to live alongside your web.config. As Nat says, you could deploy this file as a solution package.</p>\n\n<p>Assuming you are attempting to run a minimal trust, you will need to update your Code Access Security file to include the log4net assemblies as well. All of your custom SharePoint code should then automatically use your log4net configuration.</p>\n"
},
{
"answer_id": 1767221,
"author": "TheCodeKing",
"author_id": 215057,
"author_profile": "https://Stackoverflow.com/users/215057",
"pm_score": 3,
"selected": false,
"text": "<p>I implemented this recently and came up with a solution that worked for me.</p>\n\n<p>Deploy your log4net config file to the 12 hive and the log4net dll into the GAC using a globally scoped solution. Then in your application code explicitly initialize log4net from the location of your global file. This allows you to log feature receiver, timer jobs and web application code. </p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = \n @\"C:\\Program Files\\Common Files\\Microsoft Shared\\\" + \n @\"Web Server Extensions\\12\\CONFIG\\log4net.config\", Watch = true)]\n</code></pre>\n\n<p>see here <a href=\"http://www.codeproject.com/KB/sharepoint/SharepointLog4Net.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/sharepoint/SharepointLog4Net.aspx</a></p>\n"
},
{
"answer_id": 2223737,
"author": "Athens Holloway",
"author_id": 176880,
"author_profile": "https://Stackoverflow.com/users/176880",
"pm_score": 0,
"selected": false,
"text": "<p>I developed a log4net feature and packaged it in a wsp file. The feature receiver adds an httpmodule to the the web.config and the httpmodule loads the log4net.config from the layouts direcory when the application start event is raised in the http module.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22970/"
] |
I'm looking for best practices to integrate log4net to SharePoint for web request, feature activation and all timer stuff.
I have several subprojects in my farm, and I would like to have only one Log4Net.config file.
**[Edit]**
Not only I need to configure log4net for the web application, which is easy to do (I use global.asax, and a log4net.config file, so I can modify log settings withtout reloading the webapp), but I also need to log asynchronous events:
* Event Handler (like ItemAdded)
* Timer Jobs
* ...
|
I implemented this recently and came up with a solution that worked for me.
Deploy your log4net config file to the 12 hive and the log4net dll into the GAC using a globally scoped solution. Then in your application code explicitly initialize log4net from the location of your global file. This allows you to log feature receiver, timer jobs and web application code.
```
[assembly: log4net.Config.XmlConfigurator(ConfigFile =
@"C:\Program Files\Common Files\Microsoft Shared\" +
@"Web Server Extensions\12\CONFIG\log4net.config", Watch = true)]
```
see here <http://www.codeproject.com/KB/sharepoint/SharepointLog4Net.aspx>
|
219,716 |
<p>A cross join performs a cartesian product on the tuples of the two sets.</p>
<pre><code>SELECT *
FROM Table1
CROSS JOIN Table2
</code></pre>
<p>Which circumstances render such an SQL operation particularly useful?</p>
|
[
{
"answer_id": 219738,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 4,
"selected": false,
"text": "<p>You're typically not going to want a full Cartesian product for most database queries. The whole power of relational databases is that you can apply whatever restrictions you might be interested in to allow you to avoid pulling unnecessary rows from the db.</p>\n\n<p>I suppose one contrived example where you might want that is if you have a table of employees and a table of jobs that need doing and want to see all possible assignments of one employee to one job.</p>\n"
},
{
"answer_id": 219753,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 5,
"selected": false,
"text": "<p>Generate data for testing.</p>\n"
},
{
"answer_id": 219758,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 8,
"selected": true,
"text": "<p>If you have a \"grid\" that you want to populate completely, like size and color information for a particular article of clothing:</p>\n\n<pre><code>select \n size,\n color\nfrom\n sizes CROSS JOIN colors\n</code></pre>\n\n<p>Maybe you want a table that contains a row for every minute in the day, and you want to use it to verify that a procedure has executed each minute, so you might cross three tables:</p>\n\n<pre><code>select\n hour,\n minute\nfrom\n hours CROSS JOIN minutes\n</code></pre>\n\n<p>Or you have a set of standard report specs that you want to apply to every month in the year:</p>\n\n<pre><code>select\n specId,\n month\nfrom\n reports CROSS JOIN months\n</code></pre>\n\n<p>The problem with maintaining these as views is that in most cases, you don't want a complete product, particularly with respect to clothes. You can add <code>MINUS</code> logic to the query to remove certain combinations that you don't carry, but you might find it easier to populate a table some other way and not use a Cartesian product.</p>\n\n<p>Also, you might end up trying the cross join on tables that have perhaps a few more rows than you thought, or perhaps your <code>WHERE</code> clause was partially or completely missing. In that case, your DBA will notify you promptly of the omission. Usually he or she will not be happy.</p>\n"
},
{
"answer_id": 219768,
"author": "thoroughly",
"author_id": 8943,
"author_profile": "https://Stackoverflow.com/users/8943",
"pm_score": 1,
"selected": false,
"text": "<p>Imagine you had a series of queries you want to issue over a specific combination of items and dates (prices, availability, etc..). You could load the items and dates into separate temp tables and have your queries cross join the tables. This may be more convenient than the alternative of enumerating the items and dates in IN clauses, especially since some databases limit the number of elements in an IN clause.</p>\n"
},
{
"answer_id": 219773,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>Ok, this probably won't answer the question, but, if it's true (and I'm not even sure of that) it's a fun bit of history.</p>\n\n<p>In the early days of Oracle, one of the developers realized that he needed to duplicate every row in a table (for example, it's possible it was a table of events and he needed to change it separate \"start event\" and \"end event\" entries). He realized that if he had a table with just two rows, he could do a cross join, selecting just the columns in the first table, and get exactly had he needed. So he created a simple table, which he naturally enough called \"DUAL\".</p>\n\n<p>Later, he need to do something which could only be done via a select from a table, even though the action itself had nothing to do with the table, (perhaps he forgot his watch and wanted to read the time via SELECT SYSDATE FROM...) He realized that he still had his DUAL table lying around, and used that. After a while, he tired of seeing the time printed twice, so he eventual deleted one of the rows.</p>\n\n<p>Others at Oracle started using his table, and eventually, it was decided to include it in the standard Oracle installation.</p>\n\n<p>Which explains why a table whose only significance is that it has one row has a name which means \"two\".</p>\n"
},
{
"answer_id": 219840,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Takes something like a digits table, which has ten rows for the digits 0-9. You can use cross join on that table a few times to a get result that has however many rows you need, with the results numbered appropriately. This has a number of uses. For example, you can combine it with a datadd() function to get a set for every day in a given year.</p>\n"
},
{
"answer_id": 220042,
"author": "Kevin Dostalek",
"author_id": 22732,
"author_profile": "https://Stackoverflow.com/users/22732",
"pm_score": 4,
"selected": false,
"text": "<p>The key is \"show me all possible combinations\". I've used these in conjunction with other calculated fields an then sorted/filtered those.</p>\n\n<p>For example, say you are building an arbitrage (trading) application. You have sellers offering products at a price and buyers asking for products at a cost. You do a cross join on the product key (to match up the potential buyers and sellers), calculate the spread between cost and price, then sort desc. on this to give you (the middleman) the most profitable trades to execute. Almost always you'll have other bounding filter criteria of course.</p>\n"
},
{
"answer_id": 222705,
"author": "Jeff Jones",
"author_id": 22391,
"author_profile": "https://Stackoverflow.com/users/22391",
"pm_score": 2,
"selected": false,
"text": "<p>This is an interesting way to use a cross join to <a href=\"http://books.google.com/books?id=qNXaiM_gNbYC&pg=PA378&lpg=PA378&dq=crosstab+by+cross+join&source=web&ots=TM2CFUH4rA&sig=T7D9_bjsPV4c2CkOgcgX2mmFMMc&hl=en&sa=X&oi=book_result&resnum=2&ct=result#PPA378,M1\" rel=\"nofollow noreferrer\">create a crosstab report</a>. I found it in <a href=\"http://books.google.com/books?id=qNXaiM_gNbYC\" rel=\"nofollow noreferrer\">Joe Celko's SQL For Smarties</a>, and have used it several times. It does take a little setup, but has been worth the time invested.</p>\n"
},
{
"answer_id": 54937085,
"author": "HankerPL",
"author_id": 2800785,
"author_profile": "https://Stackoverflow.com/users/2800785",
"pm_score": 1,
"selected": false,
"text": "<p>you can use it <strong>CROSS JOIN</strong> to:</p>\n<ul>\n<li>generate data for testing purposes</li>\n<li>combine all properties - you need all possible combination of e.g blood groups (A,B,..) with Rh-/+, etc...\n<em><strong>--tune it for your purposes;) - I'm not expert in this area;)</strong></em></li>\n</ul>\n<pre><code>CREATE TABLE BL_GRP_01 (GR_1 text);\nCREATE TABLE RH_VAL_01 (RH_VAL text);\nINSERT INTO BL_GRP_01 VALUES ('A'), ('B'), ('AB'), ('O');\nINSERT INTO RH_VAL_01 VALUES ('+'), ('-');\n\nSELECT CONCAT(x.GR_1, y.RH_val)\n FROM BL_GRP_01 x\n CROSS JOIN RH_VAL_01 y\nORDER BY CONCAT(x.GR_1, y.RH_VAL);\n</code></pre>\n<ul>\n<li>create a join for 2 tables without a common id and then group it using max(),etc.. to find highest possible combination</li>\n</ul>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27765/"
] |
A cross join performs a cartesian product on the tuples of the two sets.
```
SELECT *
FROM Table1
CROSS JOIN Table2
```
Which circumstances render such an SQL operation particularly useful?
|
If you have a "grid" that you want to populate completely, like size and color information for a particular article of clothing:
```
select
size,
color
from
sizes CROSS JOIN colors
```
Maybe you want a table that contains a row for every minute in the day, and you want to use it to verify that a procedure has executed each minute, so you might cross three tables:
```
select
hour,
minute
from
hours CROSS JOIN minutes
```
Or you have a set of standard report specs that you want to apply to every month in the year:
```
select
specId,
month
from
reports CROSS JOIN months
```
The problem with maintaining these as views is that in most cases, you don't want a complete product, particularly with respect to clothes. You can add `MINUS` logic to the query to remove certain combinations that you don't carry, but you might find it easier to populate a table some other way and not use a Cartesian product.
Also, you might end up trying the cross join on tables that have perhaps a few more rows than you thought, or perhaps your `WHERE` clause was partially or completely missing. In that case, your DBA will notify you promptly of the omission. Usually he or she will not be happy.
|
219,719 |
<p>SQL databases seem to be the cornerstone of most software. However, it seems optimized for textual data. In fact when doing any queries involving numerical data, integers specifically, it seems inefficient that the numbers are getting converted to text and then back to native formats both ways between the application and the database. This same inefficiency seems to apply to BLOB data as well. My understanding is that even with something like Linq to SQL, this two way conversion is occuring in the background.</p>
<p>Are there general ways to bypass this overhead with SQL? Are there certain database management systems that handle this more efficiently than others (ie, with non-standard extensions/API's)?</p>
<p>Clarification. In the following select statement, the list of numbers after IN could be more easily passed as a raw array of int, but there seems to be no way of achieving that optimization level.</p>
<pre><code>SELECT foo FROM bar WHERE baz IN (23, 34, 45, 9854004, ...)
</code></pre>
|
[
{
"answer_id": 219750,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "<p>Numerical data in a database is not stored as text. I guess it depends on the database, but it certainly doesn't have to be and isn't.</p>\n<p>BLOBs are stored exactly how you set them -- by definition, the DB has no way to interpret the information -- I guess it could compress if it found that to be useful. BLOBs are not translated into text.</p>\n<p>Here's how Oracle stores numbers:</p>\n<p><a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#i16209\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#i16209</a></p>\n<blockquote>\n<p>Internal Numeric Format</p>\n<p>Oracle Database stores numeric data in variable-length format. Each value is stored in scientific notation, with 1 byte used to store the exponent and up to 20 bytes to store the mantissa. The resulting value is limited to 38 digits of precision. Oracle Database does not store leading and trailing zeros. For example, the number 412 is stored in a format similar to 4.12 x 102, with 1 byte used to store the exponent(2) and 2 bytes used to store the three significant digits of the mantissa(4,1,2). Negative numbers include the sign in their length.</p>\n</blockquote>\n<p>MySQL info here:</p>\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html</a></p>\n<p>Look at the table -- a TINYINT is represented in 1 byte (range -128 - 127), not possible if stored as text.</p>\n<p>EDIT: With the clarification -- I would say use the API in your language that looks something like this (pseudocode)</p>\n<pre><code>stmt = conn.Prepare("SELECT * FROM TABLE where x in (?, ?, ?)");\nstmt.SetInt(0, x);\nstmt.SetInt(1, y);\nstmt.SetInt(2, z);\n</code></pre>\n<p>I don't believe that the underlying protocols use text for the transport of parameters.</p>\n"
},
{
"answer_id": 219774,
"author": "Roger Durham",
"author_id": 29760,
"author_profile": "https://Stackoverflow.com/users/29760",
"pm_score": 2,
"selected": false,
"text": "<p>Don't suppose. Measure.</p>\n\n<p>Format conversion is not likely to be a measurable cost for database work, unless you are misusing the database as an arithmetic engine.</p>\n\n<p>The IO cost for LOBs, especially for CLOBS with character conversion, can become significant; the remedy here, once you know that the simplest thing that might work actually has a noticeable performance impact, is to minimize the number of times you copy the LOB data. Use whatever SQL parameter binding style allows you to transfer the data directly between its point of creation or use, and the database -- often this is binding the LOB to a stream or I/O channel.</p>\n\n<p>But don't do this until you have a way to measure the impact, and have measurements showing that this is your bottleneck.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1892/"
] |
SQL databases seem to be the cornerstone of most software. However, it seems optimized for textual data. In fact when doing any queries involving numerical data, integers specifically, it seems inefficient that the numbers are getting converted to text and then back to native formats both ways between the application and the database. This same inefficiency seems to apply to BLOB data as well. My understanding is that even with something like Linq to SQL, this two way conversion is occuring in the background.
Are there general ways to bypass this overhead with SQL? Are there certain database management systems that handle this more efficiently than others (ie, with non-standard extensions/API's)?
Clarification. In the following select statement, the list of numbers after IN could be more easily passed as a raw array of int, but there seems to be no way of achieving that optimization level.
```
SELECT foo FROM bar WHERE baz IN (23, 34, 45, 9854004, ...)
```
|
Don't suppose. Measure.
Format conversion is not likely to be a measurable cost for database work, unless you are misusing the database as an arithmetic engine.
The IO cost for LOBs, especially for CLOBS with character conversion, can become significant; the remedy here, once you know that the simplest thing that might work actually has a noticeable performance impact, is to minimize the number of times you copy the LOB data. Use whatever SQL parameter binding style allows you to transfer the data directly between its point of creation or use, and the database -- often this is binding the LOB to a stream or I/O channel.
But don't do this until you have a way to measure the impact, and have measurements showing that this is your bottleneck.
|
219,770 |
<p>In Visual Studio, I often use objects only for RAII purposes. For example:</p>
<pre><code>ScopeGuard close_guard = MakeGuard( &close_file, file );
</code></pre>
<p>The whole purpose of <em>close_guard</em> is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "<em>local variable is initialized but not referenced</em>". I want to turn this warning off for this specific case.</p>
<p>How do you deal with this kind of situation? Visual Studio thinks that this object is useless, but this is wrong since it has a non-trivial destructor.</p>
<p>I wouldn't want to use a <em>#pragma warning</em> directive for this since it would turn off this warning even for legitimate reasons.</p>
|
[
{
"answer_id": 219786,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding 'volatile' to the ScopeGuard declaration.</p>\n"
},
{
"answer_id": 219791,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Method 1:</strong> Use the <code>#pragma warning</code> directive.</p>\n\n<p><code>#pragma warning</code> allows selective modification of the behavior of compiler warning messages.</p>\n\n<pre><code>#pragma warning( push )\n#pragma warning( disable : 4705 ) // replace 4705 with warning number\n\nScopeGuard close_guard = MakeGuard( &close_file, file );\n\n#pragma warning( pop )\n</code></pre>\n\n<p>This code saves the current warning state, then it disables the warning for a specific warning code and then restores the last saved warning state.</p>\n\n<p><strong>Method 2:</strong> Use a workaround like the following. Visual Studio will be happy and so will you. This workaround is used in many Microsoft samples and also in other projects.</p>\n\n<pre><code>ScopeGuard close_guard = MakeGuard( &close_file, file );\nclose_guard;\n</code></pre>\n\n<p>Or you can create a <code>#define</code> to workaround the warning.</p>\n\n<pre><code>#define UNUSED_VAR(VAR) VAR\n...\nScopeGuard close_guard = MakeGuard( &close_file, file );\nUNUSED_VAR(close_guard);\n</code></pre>\n\n<hr>\n\n<p>Some users stated that the code presented will not work because ScopeGuard is a typedef. This assumption is wrong.</p>\n\n<p><a href=\"http://www.ddj.com/cpp/184403758\" rel=\"noreferrer\">http://www.ddj.com/cpp/184403758</a></p>\n\n<blockquote>\n <p>According to the C++ Standard, a\n reference initialized with a temporary\n value makes that temporary value live\n for the lifetime of the reference\n itself.</p>\n</blockquote>\n"
},
{
"answer_id": 219792,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>We use:</p>\n\n<pre><code>static_cast<void>(close_guard);\n</code></pre>\n\n<p>for variables that the compiler is complaining about.</p>\n"
},
{
"answer_id": 219795,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 1,
"selected": false,
"text": "<p>You can scope the #pragma warning around that line of code only by using</p>\n\n<pre><code>#pragma warning(push)\n#pragma warning(disable:XXXX)\nyour code here;\n#pragma warning(pop)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#pragma warning(disable:XXXX)\nyour code here;\n#pragma warning(default:XXXX)\n</code></pre>\n\n<p>You can also use <code>UNREFERENCED_PARAMETER(close_guard);</code> after the line of code above.</p>\n"
},
{
"answer_id": 219796,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>In some of VC++ header files, MS defines a macro:</p>\n\n<pre><code>#define UNUSED(x) x\n</code></pre>\n\n<p>used like:</p>\n\n<pre><code>ScopeGuard close_guard = MakeGuard( &close_file, file );\nUNUSED(close_guard);\n</code></pre>\n\n<p>Which silences the warning, and documents it.</p>\n"
},
{
"answer_id": 219809,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>If your object has a non-trivial destructor, Visual Studio should <em>not</em> be giving you that warning. The following code does not generate any warnings in VS2005 with warnings turned all the way up (/W4):</p>\n\n<pre><code>\nclass Test\n{\npublic:\n ~Test(void) { printf(\"destructor\\n\"); }\n};\n\nTest foo(void) { return Test(); }\n\nint main(void)\n{\n Test t = foo();\n printf(\"moo\\n\");\n\n return 0;\n}\n</code></pre>\n\n<p>Commenting out the destructor gives a warning; the code as-is does not.</p>\n"
},
{
"answer_id": 219812,
"author": "Jeffrey Martinez",
"author_id": 29703,
"author_profile": "https://Stackoverflow.com/users/29703",
"pm_score": 0,
"selected": false,
"text": "<p>I use smink's post above and have only to add that I stick a comment next to the #define saying // used to suppress warning [warning number] in visual studio</p>\n"
},
{
"answer_id": 219813,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": -1,
"selected": false,
"text": "<p>The core issue here seems to really be that the compiler does not quite understand what you are going at... which seems to be to use scoping semantics in C++ to get some code called when a variable is deallocated even when it is not being used. Right? That mechanism itself strikes me as borderline... a compiler should have the right to remove unused variables but the C++ construction semantics really messes these things up. No other way to do this that is less sleight-of-hand?</p>\n"
},
{
"answer_id": 219823,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p><em>Well, in this case ScopeGuard is actually a typedef to a reference type. This wouldn't work unfortunately.</em></p>\n\n<p>Wouldn't that mean the whole ScopeGuard doesn't work, because in that case the destructor won't be called???</p>\n"
},
{
"answer_id": 219832,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 1,
"selected": false,
"text": "<p>I guess in practice, I would grudingly go with the #pragma disable... or 'UNUSED'. However, as a main rule, code should be kept clean of warnings even at the cost of some extra bulk. It should compile in multiple different compilers on different platforms and operating systems without warnings. If it does not, the code has be to fixed so that it does. Maintaining code that generates warnings at gcc -Wall level is not a good idea.</p>\n\n<p>Compiler warnings are your friend, and should be heeded as a matter or principle. Even when it means things have to be implemented in a bit bulkier and more verbose ways. Pays for itself in the long run as the code is ported, maintained, and lives on forever...</p>\n"
},
{
"answer_id": 220205,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 0,
"selected": false,
"text": "<p>You could explicitly create the ScopeGuardImpl1 object, provided that there aren't so many parameters in the cases you're using that the result is unreadable. That way you'd avoid the reference-initialized-with-temporary that the VS warning apparently fails to understand. The cost is having to spell things out longhand, rather than getting the MakeGuard template magic.</p>\n"
},
{
"answer_id": 220280,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 2,
"selected": false,
"text": "<p>I'd use macro all the way in this case:</p>\n\n<pre><code>#define SCOPE_GUARD(guard, fn, param) \\\n ScopeGuard guard = MakeGuard(fn, param); \\\n static_cast<void>(guard)\n</code></pre>\n\n<p>now your code is nice and short:</p>\n\n<pre><code>SCOPE_GUARD(g1, &file_close, file1);\nSCOPE_GUARD(g2, &file_close, file2);\n</code></pre>\n\n<p>One advantage of this approach is that later on you can add <code>__LINE__</code>, <code>__func__</code> etc to log the guard actions later if needed.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9936/"
] |
In Visual Studio, I often use objects only for RAII purposes. For example:
```
ScopeGuard close_guard = MakeGuard( &close_file, file );
```
The whole purpose of *close\_guard* is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "*local variable is initialized but not referenced*". I want to turn this warning off for this specific case.
How do you deal with this kind of situation? Visual Studio thinks that this object is useless, but this is wrong since it has a non-trivial destructor.
I wouldn't want to use a *#pragma warning* directive for this since it would turn off this warning even for legitimate reasons.
|
**Method 1:** Use the `#pragma warning` directive.
`#pragma warning` allows selective modification of the behavior of compiler warning messages.
```
#pragma warning( push )
#pragma warning( disable : 4705 ) // replace 4705 with warning number
ScopeGuard close_guard = MakeGuard( &close_file, file );
#pragma warning( pop )
```
This code saves the current warning state, then it disables the warning for a specific warning code and then restores the last saved warning state.
**Method 2:** Use a workaround like the following. Visual Studio will be happy and so will you. This workaround is used in many Microsoft samples and also in other projects.
```
ScopeGuard close_guard = MakeGuard( &close_file, file );
close_guard;
```
Or you can create a `#define` to workaround the warning.
```
#define UNUSED_VAR(VAR) VAR
...
ScopeGuard close_guard = MakeGuard( &close_file, file );
UNUSED_VAR(close_guard);
```
---
Some users stated that the code presented will not work because ScopeGuard is a typedef. This assumption is wrong.
<http://www.ddj.com/cpp/184403758>
>
> According to the C++ Standard, a
> reference initialized with a temporary
> value makes that temporary value live
> for the lifetime of the reference
> itself.
>
>
>
|
219,776 |
<p>I wanna get the Timedate value from another page using request.querystring and then use it an query to compare and pull up the matching datas. The function for the query in linq is:</p>
<pre><code> protected void User_Querytime()
{
DataClasses2DataContext dc1 = new DataClasses2DataContext();
String Data = Request.QueryString["TimeOfMessage"];
var query7 = from u in dc1.syncback_logs
where u.TimeOfMessage = Data
orderby u.TimeOfMessage descending
select u;
GridView1.DataSource = query7;
GridView1.DataBind();
}
</code></pre>
<p>Here the "Request.QueryString["TimeOfMessage"]" which i get is DateTime (ex:8/25/2008 9:07:19 AM). I wanted to compare it against the "u.TimeOfMessage" in database and pull up the matching records. </p>
<p>When I use todatetime function to convert from string to datetime ,the value returned is bool and hence not able to compare it against the "Timeofmessage" which is datetime format in database. Can anyone help me in this?</p>
|
[
{
"answer_id": 219805,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "<p>Do you mean Convert.ToDateTime? This returns DateTime (not bool).\nDo you mean DateTime.TryParse? Simply use any of:</p>\n\n<pre><code>DateTime when = DateTime.Parse(data);\nDateTime when = DateTime.ParseExact(data);\nDateTime when = Convert.ToDateTime(data);\n</code></pre>\n\n<p>Then use \"when\" in the query. I'm not sure the purpose of ordering by it if you know they are all equal, though... did I miss something?</p>\n\n<p>If the issue is that you want <em>only</em> the time part (not the date part), could you clarify that?</p>\n"
},
{
"answer_id": 263888,
"author": "Christoph",
"author_id": 34464,
"author_profile": "https://Stackoverflow.com/users/34464",
"pm_score": 0,
"selected": false,
"text": "<p>the TryParse indeed results a bool (as the success of the parsing):</p>\n\n<pre><code>Dim DateText = Request.QueryString(\"date\")\nDim MyDate As DateTime = Nothing\nIf DateTime.TryParse(DateText, MyDate) Then\n '--Date was passed correctly\nEnd If\n</code></pre>\n\n<p>regards\nChristoph</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I wanna get the Timedate value from another page using request.querystring and then use it an query to compare and pull up the matching datas. The function for the query in linq is:
```
protected void User_Querytime()
{
DataClasses2DataContext dc1 = new DataClasses2DataContext();
String Data = Request.QueryString["TimeOfMessage"];
var query7 = from u in dc1.syncback_logs
where u.TimeOfMessage = Data
orderby u.TimeOfMessage descending
select u;
GridView1.DataSource = query7;
GridView1.DataBind();
}
```
Here the "Request.QueryString["TimeOfMessage"]" which i get is DateTime (ex:8/25/2008 9:07:19 AM). I wanted to compare it against the "u.TimeOfMessage" in database and pull up the matching records.
When I use todatetime function to convert from string to datetime ,the value returned is bool and hence not able to compare it against the "Timeofmessage" which is datetime format in database. Can anyone help me in this?
|
Do you mean Convert.ToDateTime? This returns DateTime (not bool).
Do you mean DateTime.TryParse? Simply use any of:
```
DateTime when = DateTime.Parse(data);
DateTime when = DateTime.ParseExact(data);
DateTime when = Convert.ToDateTime(data);
```
Then use "when" in the query. I'm not sure the purpose of ordering by it if you know they are all equal, though... did I miss something?
If the issue is that you want *only* the time part (not the date part), could you clarify that?
|
219,783 |
<p>I can't seems to change the default color of the required field validator. In the source it is:</p>
<pre><code><span class="required">*</span>
<asp:RequiredFieldValidator ID="valReq_txtTracks" runat="server"
ControlToValidate="txtTracks"
Display="Dynamic" />
</code></pre>
<p>Here's what I have in my .skin file:</p>
<pre><code><asp:RequiredFieldValidator runat="server"
CssClass="error-text"
ErrorMessage="required" />
</code></pre>
<p>In the rendered source I see:</p>
<pre><code><span class="required">*</span>
<span id="ctl00_ctl00_cphContent_cphContent_valReq_txtTracks" class="error-text" style="color:Red;display:none;">required</span>
</code></pre>
<p>Notice the "style=color:Red;". That needs to go. I can't override it with a css-class because it's inline CSS. What should I do?</p>
|
[
{
"answer_id": 219793,
"author": "bob",
"author_id": 23805,
"author_profile": "https://Stackoverflow.com/users/23805",
"pm_score": 1,
"selected": false,
"text": "<p>I read somewhere to use the !important tag in your css class to override the inline css...</p>\n"
},
{
"answer_id": 219794,
"author": "mohammedn",
"author_id": 29268,
"author_profile": "https://Stackoverflow.com/users/29268",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try to add style attribute with empty string in the skin file:</p>\n\n<pre><code><asp:RequiredFieldValidator runat=\"server\" \n CssClass=\"error-text\"\n style=\"\"\n ErrorMessage=\"required\" />\n</code></pre>\n"
},
{
"answer_id": 219814,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 6,
"selected": true,
"text": "<p>There is a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.forecolor.aspx\" rel=\"noreferrer\">RequiredFieldValidator.ForeColor</a> property you can set to control the color. Note that if you want to set the color in CSS, then you need to set ForeColor=\"\" to clear it on the control.</p>\n"
},
{
"answer_id": 501372,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Using <code>!important</code> seems to work fine in Firefox and IE, but for some reason not in Google Chrome... no biggie though, Chrome's share is still very low.</p>\n\n<pre><code>.form_error\n{\n font: bold 15px arial black,arial,verdana,helvetica !important; \n color: #ff0000 !important;\n}\n</code></pre>\n"
},
{
"answer_id": 6838471,
"author": "Eric",
"author_id": 371596,
"author_profile": "https://Stackoverflow.com/users/371596",
"pm_score": 3,
"selected": false,
"text": "<p>I know this an old thread, but I ran into this another day. It's kind of odd that setting style sheet does not override the text color of the validator. In my case, I had a whole bunch of different validators and extended validators that I wanted to override text color for, so instead of a theme and skin file, I created custom control adapter that handles rendering of BaseValidator control. Inside the rendering method, I just set <code>ForeColor = Color.Empty</code>. Hopefully this helps other people who ran into this situation and want to override text color for all kind of validators (required field, regular expression, compare,...).</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
] |
I can't seems to change the default color of the required field validator. In the source it is:
```
<span class="required">*</span>
<asp:RequiredFieldValidator ID="valReq_txtTracks" runat="server"
ControlToValidate="txtTracks"
Display="Dynamic" />
```
Here's what I have in my .skin file:
```
<asp:RequiredFieldValidator runat="server"
CssClass="error-text"
ErrorMessage="required" />
```
In the rendered source I see:
```
<span class="required">*</span>
<span id="ctl00_ctl00_cphContent_cphContent_valReq_txtTracks" class="error-text" style="color:Red;display:none;">required</span>
```
Notice the "style=color:Red;". That needs to go. I can't override it with a css-class because it's inline CSS. What should I do?
|
There is a [RequiredFieldValidator.ForeColor](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.forecolor.aspx) property you can set to control the color. Note that if you want to set the color in CSS, then you need to set ForeColor="" to clear it on the control.
|
219,788 |
<p>I have a large (700kb) Flex .swf file representing the main file of a site. </p>
<p>For performance testing I wanted to try and move it off to Amazon S3 hosting (which i have already done with certain videos and large files). </p>
<p>I went ahead and did that, and updated the html page to reference the remote .swf.</p>
<p>It turns out that Flash will load any resources relative to the .swf file accessing the resource - no matter what the root of the html page is. So my resources are now being loaded from the remote site (where they don't exist).</p>
<p>There are two obvious things I could do :
* copy all my resources remotely (not ready for this since i'm just testing now)
* add in some layer of abstraction to every URL that the .swf accesses to derive a new path.</p>
<p>I really want to flick a switch and say 'load everything relative to [original server]'.</p>
<p>Does such a thing exist or am I stuck loading everythin from the remote machine unless I fully qualify every path?</p>
<p>i want to avoid anything 'hacky' like : subclass Image and hack the path there</p>
|
[
{
"answer_id": 220518,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 0,
"selected": false,
"text": "<p>You could try specifying the <code>base</code> parameter of your SWF's embed/object tags. In theory it defines the base path that will be used to resolve relative paths for loading, but I don't know if it will work if the <code>base</code> value points to a different server from where the SWF is.</p>\n\n<p>See the docs on embed/object params <a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701&sliceId=1\" rel=\"nofollow noreferrer\">here</a>. Scroll down to \"<code>base</code>\" at the middle.</p>\n\n<p>If that doesn't work, another thing I've seen people do is to pass in a custom base path via <code>flashvars</code>. Then inside your SWF, you check if that base path is defined, and if so prepend it to relative URLs before loading.</p>\n"
},
{
"answer_id": 221028,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 1,
"selected": false,
"text": "<p>Append a slash before your urls, this should load relative to the domain instead of the current folder:</p>\n\n<pre><code>foo.load('/like/this/image.jpg')\n</code></pre>\n\n<p>This is a bit quick and dirty, feeding a \"relative\" url via a querystring (<a href=\"https://stackoverflow.com/questions/219788/loading-flex-resources-relative-to-server-root-as-opposed-to-swf-location#220518\">or the base parameter</a>) would be way more flexible.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
I have a large (700kb) Flex .swf file representing the main file of a site.
For performance testing I wanted to try and move it off to Amazon S3 hosting (which i have already done with certain videos and large files).
I went ahead and did that, and updated the html page to reference the remote .swf.
It turns out that Flash will load any resources relative to the .swf file accessing the resource - no matter what the root of the html page is. So my resources are now being loaded from the remote site (where they don't exist).
There are two obvious things I could do :
\* copy all my resources remotely (not ready for this since i'm just testing now)
\* add in some layer of abstraction to every URL that the .swf accesses to derive a new path.
I really want to flick a switch and say 'load everything relative to [original server]'.
Does such a thing exist or am I stuck loading everythin from the remote machine unless I fully qualify every path?
i want to avoid anything 'hacky' like : subclass Image and hack the path there
|
Append a slash before your urls, this should load relative to the domain instead of the current folder:
```
foo.load('/like/this/image.jpg')
```
This is a bit quick and dirty, feeding a "relative" url via a querystring ([or the base parameter](https://stackoverflow.com/questions/219788/loading-flex-resources-relative-to-server-root-as-opposed-to-swf-location#220518)) would be way more flexible.
|
219,798 |
<h2>I'm looking to add some lookup lists in the database, but I want them to be easy localizable (SQL 2005, ADO.NET)</h2>
<p>This would include:</p>
<ul>
<li>Easy Management of multiple languages at the same time</li>
<li>Easy Retrieval of values from the database</li>
<li>Fallback language (in case the selected language is missing)</li>
</ul>
<p>I was thinking about having a table that would store the multi-language lookup-list (using for different languages the same id) and use a function that would return the value of the look-up list - by receiving the ID and the Language.</p>
<p>One of the pitfalls would be that i have to manually add a language parameter to every query that uses the lookup list.</p>
<p>I'm looking into a solution that would let me send the parameter as a "session/global variable", or that would send the parameter automatically with the sql query, and the function to retrieve it by itself (either to attach the parameter automatically, either to be able to read the parameter).</p>
<p>The solution can look something like this, but I don't mind if it is different, as long as it doesn't give the parameter explicitly to the Query (pseudocode):</p>
<blockquote>
<pre><code>1. Send the language using "the method"
2. Execute Query
3. Get the localized results
</code></pre>
</blockquote>
<p>Clarification:</p>
<ol>
<li><p>Normally the query would look like this (remember using the lookup function):</p>
<p><code>SELECT .., GetLookupList1(lookup_ID, language), .. FROM TABLE</code></p></li>
</ol>
<p>The GetLookupList1 is a user defined function that retrieves the lookup value for a lookup table. By using this function, the SQL Code is easier to read and maintain.</p>
<p>The body of the function would be something like:</p>
<pre><code>SELECT @result = LookupValue FROM LookupTable1 WHERE ID=@Lookup_ID and Language=@lang
RETURN @result
</code></pre>
<ol start="2">
<li><p>What I want is to be able to remove the language parameter from the function to some kind of a static variable, available only for the current connection/statement/command, so the query would look like</p>
<p><code>SELECT .., GetLookupList1(lookup_ID), .. FROM TABLE</code></p></li>
</ol>
|
[
{
"answer_id": 219871,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<p>If you structure your data like this:</p>\n\n<pre><code>MessageToken DisplayText LangCode\nfirewood Fire wood en\nfirewood Bois de chauffage fr\n</code></pre>\n\n<p>When you make your query, just supply the default languageId (if blank) or the supplied languageId. Use a standard list of tokens for the messages.</p>\n\n<pre><code>Select DisplayText from (some table) where MessageToken = 'firewood' and LangId = 'en'\n</code></pre>\n"
},
{
"answer_id": 223381,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 2,
"selected": false,
"text": "<p>Since there are no user-defined global variables in SQL Server, you'll have to use one of two approaches:</p>\n\n<ol>\n<li>Tables - temporary or permanent. Example with permanent tables: <a href=\"http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx\" rel=\"nofollow noreferrer\">http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx</a>. </li>\n<li>SET CONTEXT_INFO: <a href=\"http://msdn.microsoft.com/en-us/library/ms187768.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms187768.aspx</a>. Context_info lets you associate 128 binary bytes to a session/connection. It works but be careful. If you get in the habit of using it, you run the risk of accidentally overwriting it in another context. There's only one per session/connection. </li>\n</ol>\n\n<p>Example context_info t-sql:</p>\n\n<pre><code>declare @languagein varchar(30), @contextin varbinary(128),\n @languageout varchar(30), @contextout varbinary(128)\n\nselect @languagein = 'ro-RO'\nselect @contextin = cast(@languagein as varbinary(128))\nset context_info @contextin\n\n--do whatever you like here: queries, stored procs. \n--context_info stays 'ro-RO' for the duration of the session/connection\n\nselect @contextout = context_info()\nset @languageout = replace(cast(@contextout as varchar(30)),0x00, '')\nprint @languageout\n</code></pre>\n\n<p>Another technique I've used in localization is a three part coalesce to insure a result. Check for language-region first, then language, then a default. Based on your query:</p>\n\n<pre><code>SELECT COALESCE(langregion.LookupValue, lang.LookupValue, fallback.LookupValue) LookupVal\nFROM LookupTable1 fallback\nLEFT OUTER JOIN LookupTable1 lang \n ON lang.ID = fallback.ID AND lang.Lang = @language\nLEFT OUTER JOIN LookupTable1 langregion \n ON langregion.ID = fallback.ID AND langregion.Lang = @languagewithregion\nWHERE fallback.ID = @Lookup_ID\nAND fallback.Lang = @defaultlanguage\n</code></pre>\n"
},
{
"answer_id": 232650,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 0,
"selected": false,
"text": "<p>After studying the problem in detail I have found the following:</p>\n\n<ol>\n<li><p>I could use the <code>SET CONTEXT_INFO</code>, but I would have to inject some SQL to solve the problem.</p></li>\n<li><p>The best option would be not to store localized data in the look-up tables. Instead, store some identification strings, and use custom localization logic in the application to match the strings to localized data. For the .NET framework it would be implemented by using resources, with a custom resource provider if I want to retreive localized information from a databse.</p></li>\n</ol>\n\n<p>Thank you for your answers.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23795/"
] |
I'm looking to add some lookup lists in the database, but I want them to be easy localizable (SQL 2005, ADO.NET)
----------------------------------------------------------------------------------------------------------------
This would include:
* Easy Management of multiple languages at the same time
* Easy Retrieval of values from the database
* Fallback language (in case the selected language is missing)
I was thinking about having a table that would store the multi-language lookup-list (using for different languages the same id) and use a function that would return the value of the look-up list - by receiving the ID and the Language.
One of the pitfalls would be that i have to manually add a language parameter to every query that uses the lookup list.
I'm looking into a solution that would let me send the parameter as a "session/global variable", or that would send the parameter automatically with the sql query, and the function to retrieve it by itself (either to attach the parameter automatically, either to be able to read the parameter).
The solution can look something like this, but I don't mind if it is different, as long as it doesn't give the parameter explicitly to the Query (pseudocode):
>
>
> ```
> 1. Send the language using "the method"
> 2. Execute Query
> 3. Get the localized results
>
> ```
>
>
Clarification:
1. Normally the query would look like this (remember using the lookup function):
`SELECT .., GetLookupList1(lookup_ID, language), .. FROM TABLE`
The GetLookupList1 is a user defined function that retrieves the lookup value for a lookup table. By using this function, the SQL Code is easier to read and maintain.
The body of the function would be something like:
```
SELECT @result = LookupValue FROM LookupTable1 WHERE ID=@Lookup_ID and Language=@lang
RETURN @result
```
2. What I want is to be able to remove the language parameter from the function to some kind of a static variable, available only for the current connection/statement/command, so the query would look like
`SELECT .., GetLookupList1(lookup_ID), .. FROM TABLE`
|
If you structure your data like this:
```
MessageToken DisplayText LangCode
firewood Fire wood en
firewood Bois de chauffage fr
```
When you make your query, just supply the default languageId (if blank) or the supplied languageId. Use a standard list of tokens for the messages.
```
Select DisplayText from (some table) where MessageToken = 'firewood' and LangId = 'en'
```
|
219,800 |
<p>Here is a snippet of the file <em>/proc/self/smaps</em>:</p>
<pre><code>00af8000-00b14000 r-xp 00000000 fd:00 16417 /lib/ld-2.8.so
Size: 112 kB
Rss: 88 kB
Pss: 1 kB
Shared_Clean: 88 kB
Shared_Dirty: 0 kB
Private_Clean: 0 kB
Private_Dirty: 0 kB
Referenced: 88 kB
Swap: 0 kB
00b14000-00b15000 r--p 0001c000 fd:00 16417 /lib/ld-2.8.so
Size: 4 kB
Rss: 4 kB
Pss: 4 kB
Shared_Clean: 0 kB
Shared_Dirty: 0 kB
Private_Clean: 0 kB
Private_Dirty: 4 kB
Referenced: 4 kB
Swap: 0 kB
</code></pre>
<p>It shows that this process <em>(self)</em> is linked to <em>/lib/ld-2.8.so</em> and two (of the many) byte ranges mapped into memory.</p>
<p>The first range of 88kb (22 4kb pages) is <em>shared</em> and <em>clean</em>, that is it has not been written to. This is probably code.</p>
<p>The second range of 4kb (a single page) is not shared and it is <em>dirty</em> -- the process has written to it since it was memory mapped from the file on disk. This is probably data.</p>
<p><em>But what is in that memory?</em></p>
<p>How do you convert the memory range <em>00b14000-00b15000</em> into useful information such as the line number of the file in which a large static structure is declared?</p>
<p>The technique will need to take account of <a href="http://en.wikipedia.org/wiki/Prelinking" rel="nofollow noreferrer">prelinking</a> and <a href="http://en.wikipedia.org/wiki/Address_space_layout_randomization" rel="nofollow noreferrer">address space randomization</a>, such as from <a href="http://en.wikipedia.org/wiki/ExecShield" rel="nofollow noreferrer">execshield</a>, and also <a href="http://fedoraproject.org/wiki/StackTraces" rel="nofollow noreferrer">separate debugging symbols</a>.</p>
<p><em>(The motivation is to identify popular libraries which also create dirty memory and to fix them, for example by by declaring structures const).</em></p>
|
[
{
"answer_id": 219830,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 0,
"selected": false,
"text": "<p>You'll need to extract information from Linux's memory handler to determine how the application's virtual memory map relates to the pages given. It gets trickier if you also want to track information in pages that have been swapped out of memory.</p>\n\n<p>You'll find <a href=\"http://tldp.org/LDP/khg/HyperNews/get/memory/linuxmm.html\" rel=\"nofollow noreferrer\">some information here</a> which will get you started. The process table includes some paging information, but you'll likely have to poke around to several different areas to get all the deep information you're looking for.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 220659,
"author": "Phillip Whelan",
"author_id": 25305,
"author_profile": "https://Stackoverflow.com/users/25305",
"pm_score": 3,
"selected": false,
"text": "<p>The format of smaps is: </p>\n\n<p>[BOTTOM]-[TOP] [PERM] [FILE OFFSET]</p>\n\n<p>b80e9000-b80ea000 rw-p 0001b000 08:05 605294 /lib/ld-2.8.90.so</p>\n\n<p>So there the actual content of the file '/lib/ld-2.8.90.so' at file offset 0x0001b000 is mapped at 0xb80e9000 in that program's memory.</p>\n\n<p>To extract the line number or C code of the mapped address you need to match it with the ELF section of the executable or library file and then extract the GDB symbols (if said executable or library still has them).</p>\n\n<p>The GDB file formats are documented (superficially) at <a href=\"http://sourceware.org/gdb/current/onlinedocs/gdbint_7.html#SEC60\" rel=\"nofollow noreferrer\">http://sourceware.org/gdb/current/onlinedocs/gdbint_7.html#SEC60</a></p>\n"
},
{
"answer_id": 220922,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 2,
"selected": false,
"text": "<p>Look at <a href=\"http://www.paradyn.org/html/symtab2.1-features.html\" rel=\"nofollow noreferrer\">SymtabAPI</a> from the ParaDyn project (U. Wisc/U. Maryland). It runs on a number of platforms, and supports more than just ELF files (I believe it also supports COFF and a few others). There's <a href=\"http://ftp.cs.wisc.edu/par-distr-sys/releases/release5.1/doc/symtabProgGuide.pdf\" rel=\"nofollow noreferrer\">documentation here</a>.</p>\n\n<p>Specifically, you might take a look at the AddressLookup class; I think it does exactly what you want. There are also some facilities (getLoadAddresses()) for finding out what .so's are loaded at any given time, and I believe you can also extract the extent of the code sections of loaded modules, so you can tell what's in certain parts of memory.</p>\n\n<p>Caveat: I think it will handle address space randomization properly, but I am not entirely sure.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Here is a snippet of the file */proc/self/smaps*:
```
00af8000-00b14000 r-xp 00000000 fd:00 16417 /lib/ld-2.8.so
Size: 112 kB
Rss: 88 kB
Pss: 1 kB
Shared_Clean: 88 kB
Shared_Dirty: 0 kB
Private_Clean: 0 kB
Private_Dirty: 0 kB
Referenced: 88 kB
Swap: 0 kB
00b14000-00b15000 r--p 0001c000 fd:00 16417 /lib/ld-2.8.so
Size: 4 kB
Rss: 4 kB
Pss: 4 kB
Shared_Clean: 0 kB
Shared_Dirty: 0 kB
Private_Clean: 0 kB
Private_Dirty: 4 kB
Referenced: 4 kB
Swap: 0 kB
```
It shows that this process *(self)* is linked to */lib/ld-2.8.so* and two (of the many) byte ranges mapped into memory.
The first range of 88kb (22 4kb pages) is *shared* and *clean*, that is it has not been written to. This is probably code.
The second range of 4kb (a single page) is not shared and it is *dirty* -- the process has written to it since it was memory mapped from the file on disk. This is probably data.
*But what is in that memory?*
How do you convert the memory range *00b14000-00b15000* into useful information such as the line number of the file in which a large static structure is declared?
The technique will need to take account of [prelinking](http://en.wikipedia.org/wiki/Prelinking) and [address space randomization](http://en.wikipedia.org/wiki/Address_space_layout_randomization), such as from [execshield](http://en.wikipedia.org/wiki/ExecShield), and also [separate debugging symbols](http://fedoraproject.org/wiki/StackTraces).
*(The motivation is to identify popular libraries which also create dirty memory and to fix them, for example by by declaring structures const).*
|
The format of smaps is:
[BOTTOM]-[TOP] [PERM] [FILE OFFSET]
b80e9000-b80ea000 rw-p 0001b000 08:05 605294 /lib/ld-2.8.90.so
So there the actual content of the file '/lib/ld-2.8.90.so' at file offset 0x0001b000 is mapped at 0xb80e9000 in that program's memory.
To extract the line number or C code of the mapped address you need to match it with the ELF section of the executable or library file and then extract the GDB symbols (if said executable or library still has them).
The GDB file formats are documented (superficially) at <http://sourceware.org/gdb/current/onlinedocs/gdbint_7.html#SEC60>
|
219,808 |
<p>I am completely new to LINQ in C#/.NET. I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?</p>
<p>I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime. </p>
<p>Any suggestions very welcome.</p>
|
[
{
"answer_id": 219877,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<p>There's a method called <a href=\"http://msdn.microsoft.com/en-us/library/bb396189.aspx\" rel=\"nofollow noreferrer\">CopyToDataTable</a>. That method will only help if you already have a IEnumerable(DataRow)</p>\n\n<p>Here's how I'd do this:</p>\n\n<pre><code>//extension method to convert my type to an object array.\npublic static object[] ToObjectArray(this MyClass theSource)\n{\n object[] result = new object[3];\n result[0] = theSource.FirstDouble;\n result[1] = theSource.SecondDouble;\n result[2] = theSource.TheDateTime;\n\n return result;\n}\n\n\n//some time later, new up a dataTable, set it's columns, and then...\n\nDataTable myTable = new DataTable()\n\nDataColumn column1 = new DataColumn();\ncolumn1.DataType = GetType(\"System.Double\");\ncolumn1.ColumnName = \"FirstDouble\";\nmyTable.Add(column1);\n\nDataColumn column2 = new DataColumn();\ncolumn2.DataType = GetType(\"System.Double\");\ncolumn2.ColumnName = \"SecondDouble\";\nmyTable.Add(column2);\n\nDataColumn column3 = new DataColumn();\ncolumn3.DataType = GetType(\"System.DateTime\");\ncolumn3.ColumnName = \"TheDateTime\";\nmyTable.Add(column3);\n\n// ... Each Element becomes an array, and then a row\nMyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());\n</code></pre>\n"
},
{
"answer_id": 220155,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "<p>if <code>MyObjectType</code> is a linq-generated entity, and those objects are not already associated to a data context you can call </p>\n\n<pre><code>foreach( MyObjectType value in myList )\n{\n dataContext.MyObkectTypes.InsertOnSubmit(value);\n}\ndataContext.SubmitChanges();\n</code></pre>\n\n<p>However, at this time linq-to-sql isn't terribly efficient at bulk updates. If myList was 1000 items, you would have 1000 insert statements.</p>\n\n<p>For very large lists you could convert the <code>List<MyObjectType></code> into xml and use sql servers ability to bulk insert using xml. You would attach the sql server stored procedure to the datacontext.</p>\n\n<pre><code>string xml = CreateInsertXml( myList );\ndataContext.usp_MyObjectsBulkInsertXml(xml);\n</code></pre>\n\n<hr>\n\n<p>example of sql server stored procedure for bulk insert via xml</p>\n\n<pre><code>-- XML is expected in the following format:\n--\n-- <List>\n-- <Item>\n-- <PlotID>1234</PlotID>\n-- <XValue>2.4</SmsNumber> \n-- <YValue>3.2</ContactID>\n-- <ResultDate>12 Mar 2008</ResultDate>\n-- </Item>\n-- <Item>\n-- <PlotID>3241</PlotID>\n-- <XValue>1.4</SmsNumber> \n-- <YValue>5.2</ContactID>\n-- <ResultDate>3 Mar 2008</ResultDate>\n-- </Item>\n-- </List>\n\nCREATE PROCEDURE [dbo].usp_MyObjectsBulkInsertXml\n(\n @MyXML XML\n)\nAS\n\nDECLARE @DocHandle INT\nEXEC sp_xml_preparedocument @DocHandle OUTPUT, @MyXML\n\nINSERT INTO MyTable (\n PlotID,\n XValue,\n YValue,\n ResultDate\n) \nSELECT\n X.PlotID,\n X.XValue,\n X.YValue,\n X.ResultDate\nFROM OPENXML(@DocHandle, N'/List/Item', 2)\nWITH (\n PlotID INT,\n XValue FLOAT,\n YValue FLOAT,\n ResultDate DATETIME\n) X\n\nEXEC sp_xml_removedocument @DocHandle\n\nGO\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25462/"
] |
I am completely new to LINQ in C#/.NET. I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?
I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime.
Any suggestions very welcome.
|
There's a method called [CopyToDataTable](http://msdn.microsoft.com/en-us/library/bb396189.aspx). That method will only help if you already have a IEnumerable(DataRow)
Here's how I'd do this:
```
//extension method to convert my type to an object array.
public static object[] ToObjectArray(this MyClass theSource)
{
object[] result = new object[3];
result[0] = theSource.FirstDouble;
result[1] = theSource.SecondDouble;
result[2] = theSource.TheDateTime;
return result;
}
//some time later, new up a dataTable, set it's columns, and then...
DataTable myTable = new DataTable()
DataColumn column1 = new DataColumn();
column1.DataType = GetType("System.Double");
column1.ColumnName = "FirstDouble";
myTable.Add(column1);
DataColumn column2 = new DataColumn();
column2.DataType = GetType("System.Double");
column2.ColumnName = "SecondDouble";
myTable.Add(column2);
DataColumn column3 = new DataColumn();
column3.DataType = GetType("System.DateTime");
column3.ColumnName = "TheDateTime";
myTable.Add(column3);
// ... Each Element becomes an array, and then a row
MyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());
```
|
219,815 |
<p>I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "<a href="https://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651">How do C# Events work behind the scenes?</a>", produced a great answer that explains some subtle points very well. </p>
<p>The answer to the above question makes this point:</p>
<blockquote>
<p>When you declare a field-like event
... the compiler generates the methods
and a private field (of the same type
as the delegate). Within the class,
when you refer to ElementAddedEvent
you're referring to the field. Outside
the class, you're referring to the
field</p>
</blockquote>
<p>An MSDN article linked from the same question ("<a href="http://msdn.microsoft.com/en-us/library/aa664455.aspx" rel="nofollow noreferrer">Field-like events</a>") adds:</p>
<blockquote>
<p>The notion of raising an event is
precisely equivalent to invoking the
delegate represented by the event —
thus, there are no special language
constructs for raising events.</p>
</blockquote>
<p>Wanting to examine further, I built a test project in order to view the IL that an event and a delegate are compiled to:</p>
<pre><code>public class TestClass
{
public EventHandler handler;
public event EventHandler FooEvent;
public TestClass()
{ }
}
</code></pre>
<p>I expected the delegate field <code>handler</code> and the event <code>FooEvent</code> to compile to roughly the same IL code, with some additional methods to wrap access to the compiler-generated <code>FooEvent</code> field. But the IL generated wasn't quite what I expected: </p>
<pre><code>.class public auto ansi beforefieldinit TestClass
extends [mscorlib]System.Object
{
.event [mscorlib]System.EventHandler FooEvent
{
.addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler)
.removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler)
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
// Constructor IL hidden
}
.field private class [mscorlib]System.EventHandler FooEvent
.field public class [mscorlib]System.EventHandler handler
}
</code></pre>
<p>Since events are nothing more than delegates with compiler-generated <code>add</code> and <code>remove</code> methods, I didn't expect to see events treated as anything more than that in IL. But the add and remove methods are defined in a section that begins <code>.event</code>, not <code>.method</code> as normal methods are. </p>
<p>My ultimate questions are: if events are implemented simply as delegates with accessor methods, what is the point of having a <code>.event</code> IL section? Couldn't they be implemented in IL without this by using <code>.method</code> sections? Is <code>.event</code> equivalent to <code>.method</code>? </p>
|
[
{
"answer_id": 219835,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>I'm not sure that is surprising... compare to the same for properties vs fields (since properties before the same function as events: encapsulation via accessors):</p>\n\n<pre><code>.field public string Foo // public field\n.property instance string Bar // public property\n{\n .get instance string MyType::get_Bar()\n .set instance void MyType::set_Bar(string)\n}\n</code></pre>\n\n<p>Also - events <em>do not</em> mention anything about fields; they <em>only</em> define the accessors (add/remove). The delegate backer is an implementation detail; it just so happens that field-like-events declare a field as a backing member - in the same way that auto-implemented-properties declare a field as a backing member. Other implementations are possible (and very common, especially in forms etc).</p>\n\n<p>Other common implementations:</p>\n\n<p>Sparse-events (Controls, etc) - EventHandlerList (or similar):</p>\n\n<pre><code>// only one instance field no matter how many events;\n// very useful if we expect most events to be unsubscribed\nprivate EventHandlerList events = new EventHandlerList();\nprotected EventHandlerList Events {\n get { return events; } // usually lazy\n}\n\n// this code repeated per event\nprivate static readonly object FooEvent = new object();\npublic event EventHandler Foo\n{\n add { Events.AddHandler(FooEvent, value); }\n remove { Events.RemoveHandler(FooEvent, value); }\n}\nprotected virtual void OnFoo()\n{\n EventHandler handler = Events[FooEvent] as EventHandler;\n if (handler != null) handler(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>(the above is pretty-much the backbone of win-forms events)</p>\n\n<p>Facade (although this confuses the \"sender\" a little; some intermediary code is often helpful):</p>\n\n<pre><code>private Bar wrappedObject; // via ctor\npublic event EventHandler SomeEvent\n{\n add { wrappedObject.SomeOtherEvent += value; }\n remove { wrappedObject.SomeOtherEvent -= value; }\n}\n</code></pre>\n\n<p>(the above can also be used to effectively rename an event)</p>\n"
},
{
"answer_id": 219837,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Events aren't the same as delegates. Events encapsulate adding/removing a handler for an event. The handler is represented with a delegate.</p>\n\n<p>You <em>could</em> just write AddClickHandler/RemoveClickHandler etc for every event - but it would be relatively painful, and wouldn't make it easy for tools like VS to separate out events from anything else.</p>\n\n<p>This is just like properties really - you could write GetSize/SetSize etc (as you do in Java) but by separating out properties, there are syntactical shortcuts available and better tool support.</p>\n"
},
{
"answer_id": 219878,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 1,
"selected": false,
"text": "<p>The point of having events that are a pair of add, remove, methods is <strong>encapsulation</strong>.</p>\n\n<p>Most of the time events are used as is, but other times you don't want to store the delegates attached to the event in a field, or you want to do extra processing on add or remove event methods. </p>\n\n<p>For example one way to implement <a href=\"http://vaultofthoughts.net/EventPropertiesMemoryEfficientEvents.aspx\" rel=\"nofollow noreferrer\">memory efficient events</a> is to store the delegates in a dictionary rather than a private field, because fields are always allocated while a dictionary only grows in size when items are added. This model is similar with what Winforms and WPF uses make make efficient use of memory (winforms and WPF uses keyed dictionaries to store delegates not lists)</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28350/"
] |
I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "[How do C# Events work behind the scenes?](https://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651)", produced a great answer that explains some subtle points very well.
The answer to the above question makes this point:
>
> When you declare a field-like event
> ... the compiler generates the methods
> and a private field (of the same type
> as the delegate). Within the class,
> when you refer to ElementAddedEvent
> you're referring to the field. Outside
> the class, you're referring to the
> field
>
>
>
An MSDN article linked from the same question ("[Field-like events](http://msdn.microsoft.com/en-us/library/aa664455.aspx)") adds:
>
> The notion of raising an event is
> precisely equivalent to invoking the
> delegate represented by the event —
> thus, there are no special language
> constructs for raising events.
>
>
>
Wanting to examine further, I built a test project in order to view the IL that an event and a delegate are compiled to:
```
public class TestClass
{
public EventHandler handler;
public event EventHandler FooEvent;
public TestClass()
{ }
}
```
I expected the delegate field `handler` and the event `FooEvent` to compile to roughly the same IL code, with some additional methods to wrap access to the compiler-generated `FooEvent` field. But the IL generated wasn't quite what I expected:
```
.class public auto ansi beforefieldinit TestClass
extends [mscorlib]System.Object
{
.event [mscorlib]System.EventHandler FooEvent
{
.addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler)
.removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler)
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
// Constructor IL hidden
}
.field private class [mscorlib]System.EventHandler FooEvent
.field public class [mscorlib]System.EventHandler handler
}
```
Since events are nothing more than delegates with compiler-generated `add` and `remove` methods, I didn't expect to see events treated as anything more than that in IL. But the add and remove methods are defined in a section that begins `.event`, not `.method` as normal methods are.
My ultimate questions are: if events are implemented simply as delegates with accessor methods, what is the point of having a `.event` IL section? Couldn't they be implemented in IL without this by using `.method` sections? Is `.event` equivalent to `.method`?
|
I'm not sure that is surprising... compare to the same for properties vs fields (since properties before the same function as events: encapsulation via accessors):
```
.field public string Foo // public field
.property instance string Bar // public property
{
.get instance string MyType::get_Bar()
.set instance void MyType::set_Bar(string)
}
```
Also - events *do not* mention anything about fields; they *only* define the accessors (add/remove). The delegate backer is an implementation detail; it just so happens that field-like-events declare a field as a backing member - in the same way that auto-implemented-properties declare a field as a backing member. Other implementations are possible (and very common, especially in forms etc).
Other common implementations:
Sparse-events (Controls, etc) - EventHandlerList (or similar):
```
// only one instance field no matter how many events;
// very useful if we expect most events to be unsubscribed
private EventHandlerList events = new EventHandlerList();
protected EventHandlerList Events {
get { return events; } // usually lazy
}
// this code repeated per event
private static readonly object FooEvent = new object();
public event EventHandler Foo
{
add { Events.AddHandler(FooEvent, value); }
remove { Events.RemoveHandler(FooEvent, value); }
}
protected virtual void OnFoo()
{
EventHandler handler = Events[FooEvent] as EventHandler;
if (handler != null) handler(this, EventArgs.Empty);
}
```
(the above is pretty-much the backbone of win-forms events)
Facade (although this confuses the "sender" a little; some intermediary code is often helpful):
```
private Bar wrappedObject; // via ctor
public event EventHandler SomeEvent
{
add { wrappedObject.SomeOtherEvent += value; }
remove { wrappedObject.SomeOtherEvent -= value; }
}
```
(the above can also be used to effectively rename an event)
|
219,827 |
<p>I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploading a file).
Does anybody know a library or has some code to achieve this? I want to post different values and additionally (but only sometimes) a file.</p>
<p>Thanks for your help,
Sebastian</p>
|
[
{
"answer_id": 220015,
"author": "dnolan",
"author_id": 29086,
"author_profile": "https://Stackoverflow.com/users/29086",
"pm_score": 6,
"selected": true,
"text": "<p>This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.</p>\n\n<pre><code>public class PostData\n{\n\n private List<PostDataParam> m_Params;\n\n public List<PostDataParam> Params\n {\n get { return m_Params; }\n set { m_Params = value; }\n }\n\n public PostData()\n {\n m_Params = new List<PostDataParam>();\n\n // Add sample param\n m_Params.Add(new PostDataParam(\"email\", \"MyEmail\", PostDataParamType.Field));\n }\n\n\n /// <summary>\n /// Returns the parameters array formatted for multi-part/form data\n /// </summary>\n /// <returns></returns>\n public string GetPostData()\n {\n // Get boundary, default is --AaB03x\n string boundary = ConfigurationManager.AppSettings[\"ContentBoundary\"].ToString();\n\n StringBuilder sb = new StringBuilder();\n foreach (PostDataParam p in m_Params)\n {\n sb.AppendLine(boundary);\n\n if (p.Type == PostDataParamType.File)\n {\n sb.AppendLine(string.Format(\"Content-Disposition: file; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\", p.Name, p.FileName));\n sb.AppendLine(\"Content-Type: text/plain\");\n sb.AppendLine();\n sb.AppendLine(p.Value); \n }\n else\n {\n sb.AppendLine(string.Format(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", p.Name));\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n }\n\n sb.AppendLine(boundary);\n\n return sb.ToString(); \n }\n}\n\npublic enum PostDataParamType\n{\n Field,\n File\n}\n\npublic class PostDataParam\n{\n\n\n public PostDataParam(string name, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n Type = type;\n }\n\n public string Name;\n public string FileName;\n public string Value;\n public PostDataParamType Type;\n}\n</code></pre>\n\n<p>To send the data you then need to:</p>\n\n<pre><code>HttpWebRequest oRequest = null;\noRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);\noRequest.ContentType = \"multipart/form-data\"; \noRequest.Method = \"POST\";\nPostData pData = new PostData();\n\nbyte[] buffer = encoding.GetBytes(pData.GetPostData());\n\n// Set content length of our data\noRequest.ContentLength = buffer.Length;\n\n// Dump our buffered postdata to the stream, booyah\noStream = oRequest.GetRequestStream();\noStream.Write(buffer, 0, buffer.Length);\noStream.Close();\n\n// get the response\noResponse = (HttpWebResponse)oRequest.GetResponse();\n</code></pre>\n\n<p>Hope thats clear, i've cut and pasted from a few sources to get that tidier.</p>\n"
},
{
"answer_id": 359222,
"author": "jumoel",
"author_id": 1555170,
"author_profile": "https://Stackoverflow.com/users/1555170",
"pm_score": 4,
"selected": false,
"text": "<p>Building on dnolans example, this is the version I could actually get to work (there were some errors with the boundary, encoding wasn't set) :-)</p>\n\n<p>To send the data:</p>\n\n<pre><code>HttpWebRequest oRequest = null;\noRequest = (HttpWebRequest)HttpWebRequest.Create(\"http://you.url.here\");\noRequest.ContentType = \"multipart/form-data; boundary=\" + PostData.boundary;\noRequest.Method = \"POST\";\nPostData pData = new PostData();\nEncoding encoding = Encoding.UTF8;\nStream oStream = null;\n\n/* ... set the parameters, read files, etc. IE:\n pData.Params.Add(new PostDataParam(\"email\", \"[email protected]\", PostDataParamType.Field));\n pData.Params.Add(new PostDataParam(\"fileupload\", \"filename.txt\", \"filecontents\" PostDataParamType.File));\n*/\n\nbyte[] buffer = encoding.GetBytes(pData.GetPostData());\n\noRequest.ContentLength = buffer.Length;\n\noStream = oRequest.GetRequestStream();\noStream.Write(buffer, 0, buffer.Length);\noStream.Close();\n\nHttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();\n</code></pre>\n\n<p>The PostData class should look like:</p>\n\n<pre><code>public class PostData\n{\n // Change this if you need to, not necessary\n public static string boundary = \"AaB03x\";\n\n private List<PostDataParam> m_Params;\n\n public List<PostDataParam> Params\n {\n get { return m_Params; }\n set { m_Params = value; }\n }\n\n public PostData()\n {\n m_Params = new List<PostDataParam>();\n }\n\n /// <summary>\n /// Returns the parameters array formatted for multi-part/form data\n /// </summary>\n /// <returns></returns>\n public string GetPostData()\n {\n StringBuilder sb = new StringBuilder();\n foreach (PostDataParam p in m_Params)\n {\n sb.AppendLine(\"--\" + boundary);\n\n if (p.Type == PostDataParamType.File)\n {\n sb.AppendLine(string.Format(\"Content-Disposition: file; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\", p.Name, p.FileName));\n sb.AppendLine(\"Content-Type: application/octet-stream\");\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n else\n {\n sb.AppendLine(string.Format(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", p.Name));\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n }\n\n sb.AppendLine(\"--\" + boundary + \"--\");\n\n return sb.ToString();\n }\n}\n\npublic enum PostDataParamType\n{\n Field,\n File\n}\n\npublic class PostDataParam\n{\n public PostDataParam(string name, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n Type = type;\n }\n\n public PostDataParam(string name, string filename, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n FileName = filename;\n Type = type;\n }\n\n public string Name;\n public string FileName;\n public string Value;\n public PostDataParamType Type;\n}\n</code></pre>\n"
},
{
"answer_id": 526261,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to simulate a browser login to a website to get a login cookie, and the login form was multipart/form-data.</p>\n\n<p>I took some clues from the other answers here, and then tried to get my own scenario working. It took a bit of frustrating trial and error before it worked right, but here is the code:</p>\n\n<pre><code> public static class WebHelpers\n {\n /// <summary>\n /// Post the data as a multipart form\n /// </summary>\n public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, string> values)\n {\n string formDataBoundary = \"---------------------------\" + WebHelpers.RandomHexDigits(12);\n string contentType = \"multipart/form-data; boundary=\" + formDataBoundary;\n\n string formData = WebHelpers.MakeMultipartForm(values, formDataBoundary);\n return WebHelpers.PostForm(postUrl, userAgent, contentType, formData);\n }\n\n /// <summary>\n /// Post a form\n /// </summary>\n public static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, string formData)\n {\n HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;\n\n if (request == null)\n {\n throw new NullReferenceException(\"request is not a http request\");\n }\n\n // Add these, as we're doing a POST\n request.Method = \"POST\";\n request.ContentType = contentType;\n request.UserAgent = userAgent;\n request.CookieContainer = new CookieContainer();\n\n // We need to count how many bytes we're sending. \n byte[] postBytes = Encoding.UTF8.GetBytes(formData);\n request.ContentLength = postBytes.Length;\n\n using (Stream requestStream = request.GetRequestStream())\n {\n // Push it out there\n requestStream.Write(postBytes, 0, postBytes.Length);\n requestStream.Close();\n }\n\n return request.GetResponse() as HttpWebResponse;\n }\n\n /// <summary>\n /// Generate random hex digits \n /// </summary>\n public static string RandomHexDigits(int count)\n {\n Random random = new Random();\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < count; i++)\n {\n int digit = random.Next(16);\n result.AppendFormat(\"{0:x}\", digit);\n }\n\n return result.ToString();\n }\n\n /// <summary>\n /// Turn the key and value pairs into a multipart form\n /// </summary>\n private static string MakeMultipartForm(Dictionary<string, string> values, string boundary)\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (var pair in values)\n {\n sb.AppendFormat(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\\r\\n\", boundary, pair.Key, pair.Value);\n }\n\n sb.AppendFormat(\"--{0}--\\r\\n\", boundary);\n\n return sb.ToString(); \n }\n }\n}\n</code></pre>\n\n<p>It doesn't handle file data, just form since that's all that I needed. I called like this:</p>\n\n<pre><code> try\n {\n using (HttpWebResponse response = WebHelpers.MultipartFormDataPost(postUrl, UserAgentString, this.loginForm)) \n {\n if (response != null)\n {\n Cookie loginCookie = response.Cookies[\"logincookie\"];\n .....\n</code></pre>\n"
},
{
"answer_id": 769093,
"author": "Brian Grinstead",
"author_id": 76137,
"author_profile": "https://Stackoverflow.com/users/76137",
"pm_score": 6,
"selected": false,
"text": "<p>Thanks for the answers, everybody! I recently had to get this to work, and used your suggestions heavily. However, there were a couple of tricky parts that did not work as expected, mostly having to do with actually including the file (which was an important part of the question). There are a lot of answers here already, but I think this may be useful to someone in the future (I could not find many clear examples of this online). I <a href=\"http://www.briangrinstead.com/blog/multipart-form-post-in-c\" rel=\"noreferrer\">wrote a blog post</a> that explains it a little more.</p>\n\n<p>Basically, I first tried to pass in the file data as a UTF8 encoded string, but I was having problems with encoding files (it worked fine for a plain text file, but when uploading a Word Document, for example, if I tried to save the file that was passed through to the posted form using Request.Files[0].SaveAs(), opening the file in Word did not work properly. I found that if you write the file data directly using a Stream (rather than a StringBuilder), it worked as expected. Also, I made a couple of modifications that made it easier for me to understand.</p>\n\n<p>By the way, the <a href=\"http://www.ietf.org/rfc/rfc2388.txt\" rel=\"noreferrer\">Multipart Forms Request for Comments</a> and the <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2\" rel=\"noreferrer\">W3C Recommendation for mulitpart/form-data</a> are a couple of useful resources in case anyone needs a reference for the specification.</p>\n\n<p>I changed the WebHelpers class to be a bit smaller and have simpler interfaces, it is now called <code>FormUpload</code>. If you pass a <code>FormUpload.FileParameter</code> you can pass the byte[] contents along with a file name and content type, and if you pass a string, it will treat it as a standard name/value combination. </p>\n\n<p><strong>Here is the FormUpload class:</strong></p>\n\n<pre><code>// Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt\n// http://www.briangrinstead.com/blog/multipart-form-post-in-c\npublic static class FormUpload\n{\n private static readonly Encoding encoding = Encoding.UTF8;\n public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)\n {\n string formDataBoundary = String.Format(\"----------{0:N}\", Guid.NewGuid());\n string contentType = \"multipart/form-data; boundary=\" + formDataBoundary;\n\n byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);\n\n return PostForm(postUrl, userAgent, contentType, formData);\n }\n private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)\n {\n HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;\n\n if (request == null)\n {\n throw new NullReferenceException(\"request is not a http request\");\n }\n\n // Set up the request properties.\n request.Method = \"POST\";\n request.ContentType = contentType;\n request.UserAgent = userAgent;\n request.CookieContainer = new CookieContainer();\n request.ContentLength = formData.Length;\n\n // You could add authentication here as well if needed:\n // request.PreAuthenticate = true;\n // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;\n // request.Headers.Add(\"Authorization\", \"Basic \" + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(\"username\" + \":\" + \"password\")));\n\n // Send the form data to the request.\n using (Stream requestStream = request.GetRequestStream())\n {\n requestStream.Write(formData, 0, formData.Length);\n requestStream.Close();\n }\n\n return request.GetResponse() as HttpWebResponse;\n }\n\n private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)\n {\n Stream formDataStream = new System.IO.MemoryStream();\n bool needsCLRF = false;\n\n foreach (var param in postParameters)\n {\n // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.\n // Skip it on the first parameter, add it to subsequent parameters.\n if (needsCLRF)\n formDataStream.Write(encoding.GetBytes(\"\\r\\n\"), 0, encoding.GetByteCount(\"\\r\\n\"));\n\n needsCLRF = true;\n\n if (param.Value is FileParameter)\n {\n FileParameter fileToUpload = (FileParameter)param.Value;\n\n // Add just the first part of this param, since we will write the file data directly to the Stream\n string header = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{2}\\\";\\r\\nContent-Type: {3}\\r\\n\\r\\n\",\n boundary,\n param.Key,\n fileToUpload.FileName ?? param.Key,\n fileToUpload.ContentType ?? \"application/octet-stream\");\n\n formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));\n\n // Write the file data directly to the Stream, rather than serializing it to a string.\n formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);\n }\n else\n {\n string postData = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\",\n boundary,\n param.Key,\n param.Value);\n formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));\n }\n }\n\n // Add the end of the request. Start with a newline\n string footer = \"\\r\\n--\" + boundary + \"--\\r\\n\";\n formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));\n\n // Dump the Stream into a byte[]\n formDataStream.Position = 0;\n byte[] formData = new byte[formDataStream.Length];\n formDataStream.Read(formData, 0, formData.Length);\n formDataStream.Close();\n\n return formData;\n }\n\n public class FileParameter\n {\n public byte[] File { get; set; }\n public string FileName { get; set; }\n public string ContentType { get; set; }\n public FileParameter(byte[] file) : this(file, null) { }\n public FileParameter(byte[] file, string filename) : this(file, filename, null) { }\n public FileParameter(byte[] file, string filename, string contenttype)\n {\n File = file;\n FileName = filename;\n ContentType = contenttype;\n }\n }\n}\n</code></pre>\n\n<p><strong>Here is the calling code, which uploads a file and a few normal post parameters:</strong></p>\n\n<pre><code>// Read file data\nFileStream fs = new FileStream(\"c:\\\\people.doc\", FileMode.Open, FileAccess.Read);\nbyte[] data = new byte[fs.Length];\nfs.Read(data, 0, data.Length);\nfs.Close();\n\n// Generate post objects\nDictionary<string, object> postParameters = new Dictionary<string, object>();\npostParameters.Add(\"filename\", \"People.doc\");\npostParameters.Add(\"fileformat\", \"doc\");\npostParameters.Add(\"file\", new FormUpload.FileParameter(data, \"People.doc\", \"application/msword\"));\n\n// Create request and receive response\nstring postURL = \"http://localhost\";\nstring userAgent = \"Someone\";\nHttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);\n\n// Process response\nStreamReader responseReader = new StreamReader(webResponse.GetResponseStream());\nstring fullResponse = responseReader.ReadToEnd();\nwebResponse.Close();\nResponse.Write(fullResponse);\n</code></pre>\n"
},
{
"answer_id": 950609,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Below is the code which I'm using </p>\n\n<pre><code> //This URL not exist, it's only an example.\n string url = \"http://myBox.s3.amazonaws.com/\";\n //Instantiate new CustomWebRequest class\n CustomWebRequest wr = new CustomWebRequest(url);\n //Set values for parameters\n wr.ParamsCollection.Add(new ParamsStruct(\"key\", \"${filename}\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"acl\", \"public-read\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"success_action_redirect\", \"http://www.yahoo.com\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"x-amz-meta-uuid\", \"14365123651274\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"x-amz-meta-tag\", \"\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"AWSAccessKeyId\", \"zzzz\")); \n wr.ParamsCollection.Add(new ParamsStruct(\"Policy\", \"adsfadsf\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"Signature\", \"hH6lK6cA=\"));\n //For file type, send the inputstream of selected file\n StreamReader sr = new StreamReader(@\"file.txt\");\n wr.ParamsCollection.Add(new ParamsStruct(\"file\", sr, ParamsStruct.ParamType.File, \"file.txt\"));\n\n wr.PostData();\n</code></pre>\n\n<p>from the following link I've downloaded the same code\n<a href=\"http://www.codeproject.com/KB/cs/multipart_request_C_.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/multipart_request_C_.aspx</a></p>\n\n<p>Any Help</p>\n"
},
{
"answer_id": 1040461,
"author": "eeeeaaii",
"author_id": 128431,
"author_profile": "https://Stackoverflow.com/users/128431",
"pm_score": 3,
"selected": false,
"text": "<p>In the version of .NET I am using you also have to do this:</p>\n\n<pre><code>System.Net.ServicePointManager.Expect100Continue = false;\n</code></pre>\n\n<p>If you don't, the <code>HttpWebRequest</code> class will automatically add the <code>Expect:100-continue</code> request header which fouls everything up.</p>\n\n<p>Also I learned the hard way that you have to have the right number of dashes. whatever you say is the \"boundary\" in the <code>Content-Type</code> header has to be preceded by two dashes</p>\n\n<pre><code>--THEBOUNDARY\n</code></pre>\n\n<p>and at the end</p>\n\n<pre><code>--THEBOUNDARY--\n</code></pre>\n\n<p>exactly as it does in the example code. If your boundary is a lot of dashes followed by a number then this mistake won't be obvious by looking at the http request in a proxy server</p>\n"
},
{
"answer_id": 1844241,
"author": "TheQult",
"author_id": 219491,
"author_profile": "https://Stackoverflow.com/users/219491",
"pm_score": 2,
"selected": false,
"text": "<p>A little optimization of the class before.\nIn this version the files are not totally loaded into memory.</p>\n\n<p>Security advice: a check for the boundary is missing, if the file contains the bounday it will crash.</p>\n\n<pre><code>namespace WindowsFormsApplication1\n{\n public static class FormUpload\n {\n private static string NewDataBoundary()\n {\n Random rnd = new Random();\n string formDataBoundary = \"\";\n while (formDataBoundary.Length < 15)\n {\n formDataBoundary = formDataBoundary + rnd.Next();\n }\n formDataBoundary = formDataBoundary.Substring(0, 15);\n formDataBoundary = \"-----------------------------\" + formDataBoundary;\n return formDataBoundary;\n }\n\n public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)\n {\n string boundary = NewDataBoundary();\n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);\n\n // Set up the request properties\n request.Method = \"POST\";\n request.ContentType = \"multipart/form-data; boundary=\" + boundary;\n request.UserAgent = \"PhasDocAgent 1.0\";\n request.CookieContainer = new CookieContainer();\n\n foreach (var cookie in cookies)\n {\n request.CookieContainer.Add(cookie);\n }\n\n #region WRITING STREAM\n using (Stream formDataStream = request.GetRequestStream())\n {\n foreach (var param in postParameters)\n {\n if (param.Value.StartsWith(\"file://\"))\n {\n string filepath = param.Value.Substring(7);\n\n // Add just the first part of this param, since we will write the file data directly to the Stream\n string header = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{2}\\\";\\r\\nContent-Type: {3}\\r\\n\\r\\n\",\n boundary,\n param.Key,\n Path.GetFileName(filepath) ?? param.Key,\n MimeTypes.GetMime(filepath));\n\n formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);\n\n // Write the file data directly to the Stream, rather than serializing it to a string.\n\n byte[] buffer = new byte[2048];\n\n FileStream fs = new FileStream(filepath, FileMode.Open);\n\n for (int i = 0; i < fs.Length; )\n {\n int k = fs.Read(buffer, 0, buffer.Length);\n if (k > 0)\n {\n formDataStream.Write(buffer, 0, k);\n }\n i = i + k;\n }\n fs.Close();\n }\n else\n {\n string postData = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\\r\\n\",\n boundary,\n param.Key,\n param.Value);\n formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);\n }\n }\n // Add the end of the request\n byte[] footer = Encoding.UTF8.GetBytes(\"\\r\\n--\" + boundary + \"--\\r\\n\");\n formDataStream.Write(footer, 0, footer.Length);\n request.ContentLength = formDataStream.Length;\n formDataStream.Close();\n }\n #endregion\n\n return request.GetResponse() as HttpWebResponse;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3211654,
"author": "Luis Domingues",
"author_id": 387607,
"author_profile": "https://Stackoverflow.com/users/387607",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for the code, it saved me a lot of time (including the Except100 error!).</p>\n\n<p>Anyway, I found a bug in the code, here:</p>\n\n<pre><code>formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length);\n</code></pre>\n\n<p>In case your POST data is utf-16, postData.Length, will return the number of characters and not the number of bytes. This will truncate the data being posted (for example, if you have 2 chars that are encoded as utf-16, they take 4 bytes, but postData.Length will say it takes 2 bytes, and you loose the 2 final bytes of the posted data).</p>\n\n<p>Solution - replace that line with:</p>\n\n<pre><code>byte[] aPostData=encoding.GetBytes(postData);\nformDataStream.Write(aPostData, 0, aPostData.Length);\n</code></pre>\n\n<p>Using this, the length is calculated by the size of the byte[], not the string size.</p>\n"
},
{
"answer_id": 12458948,
"author": "Yavanosta",
"author_id": 1103991,
"author_profile": "https://Stackoverflow.com/users/1103991",
"pm_score": 0,
"selected": false,
"text": "<p>My implementation</p>\n\n<pre><code>/// <summary>\n/// Sending file via multipart\\form-data\n/// </summary>\n/// <param name=\"url\">URL for send</param>\n/// <param name=\"file\">Local file path</param>\n/// <param name=\"paramName\">Request file param</param>\n/// <param name=\"contentType\">Content-Type file headr</param>\n/// <param name=\"nvc\">Additional post params</param>\nprivate static string httpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)\n{\n //delimeter\n var boundary = \"---------------------------\" + DateTime.Now.Ticks.ToString(\"x\");\n\n //creating request\n var wr = (HttpWebRequest)WebRequest.Create(url);\n wr.ContentType = \"multipart/form-data; boundary=\" + boundary;\n wr.Method = \"POST\";\n wr.KeepAlive = true;\n\n //sending request\n using(var requestStream = wr.GetRequestStream())\n {\n using (var requestWriter = new StreamWriter(requestStream, Encoding.UTF8))\n {\n //params\n const string formdataTemplate = \"Content-Disposition: form-data; name=\\\"{0}\\\"\\r\\n\\r\\n{1}\";\n foreach (string key in nvc.Keys)\n {\n requestWriter.Write(boundary);\n requestWriter.Write(String.Format(formdataTemplate, key, nvc[key]));\n }\n requestWriter.Write(boundary);\n\n //file header\n const string headerTemplate = \"Content-Disposition: form-data; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\\r\\nContent-Type: {2}\\r\\n\\r\\n\";\n requestWriter.Write(String.Format(headerTemplate, paramName, file, contentType));\n\n //file content\n using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))\n {\n fileStream.CopyTo(requestStream);\n }\n\n requestWriter.Write(\"\\r\\n--\" + boundary + \"--\\r\\n\");\n }\n }\n\n //reading response\n try\n {\n using (var wresp = (HttpWebResponse)wr.GetResponse())\n {\n if (wresp.StatusCode == HttpStatusCode.OK)\n {\n using (var responseStream = wresp.GetResponseStream())\n {\n if (responseStream == null)\n return null;\n using (var responseReader = new StreamReader(responseStream))\n {\n return responseReader.ReadToEnd();\n }\n }\n }\n\n throw new ApplicationException(\"Error while upload files. Server status code: \" + wresp.StatusCode.ToString());\n }\n }\n catch (Exception ex)\n {\n throw new ApplicationException(\"Error while uploading file\", ex);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18233515,
"author": "codevision",
"author_id": 354473,
"author_profile": "https://Stackoverflow.com/users/354473",
"pm_score": 5,
"selected": false,
"text": "<p>With .NET 4.5 you currently could use System.Net.Http namespace. Below the example for uploading single file using multipart form data.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Net.Http;\n\nnamespace HttpClientTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n var client = new HttpClient();\n var content = new MultipartFormDataContent();\n content.Add(new StreamContent(File.Open(\"../../Image1.png\", FileMode.Open)), \"Image\", \"Image.png\");\n content.Add(new StringContent(\"Place string content here\"), \"Content-Id in the HTTP\"); \n var result = client.PostAsync(\"https://hostname/api/Account/UploadAvatar\", content);\n Console.WriteLine(result.Result.ToString());\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29876/"
] |
I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploading a file).
Does anybody know a library or has some code to achieve this? I want to post different values and additionally (but only sometimes) a file.
Thanks for your help,
Sebastian
|
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.
```
public class PostData
{
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
// Add sample param
m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
// Get boundary, default is --AaB03x
string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine(boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: text/plain");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine(boundary);
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
```
To send the data you then need to:
```
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();
byte[] buffer = encoding.GetBytes(pData.GetPostData());
// Set content length of our data
oRequest.ContentLength = buffer.Length;
// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();
```
Hope thats clear, i've cut and pasted from a few sources to get that tidier.
|
219,833 |
<p>I'm collecting metadata using the sys.* views, and according to the documentation, the sys.identity_columns view will return the seed and increment values like so.</p>
<pre><code>CREATE TABLE ident_test (
test_id int IDENTITY(1000,10),
other int
)
SELECT name, seed_value, increment_value
FROM sys.identity_columns
WHERE object_id = OBJECT_ID( 'ident_test' )
</code></pre>
<p>However, the above query just returns one column. Is it just me?</p>
<p>(Note: I've had to change this question somewhat from its earlier version.)</p>
|
[
{
"answer_id": 219850,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure you are running this in a database with tables with <code>IDENTITY</code> columns?</p>\n\n<pre><code>SELECT c.name, i.seed_value, i.increment_value\nFROM sys.columns c\nINNER JOIN sys.identity_columns i\n ON i.object_id = c.object_id\n AND i.column_id = c.column_id\n</code></pre>\n\n<p>Returns rows for me in a regular production database with a few identities.</p>\n\n<p>Using a <code>LEFT JOIN</code> returns these rows as well as many which are not <code>IDENTITY</code></p>\n\n<p>I ran this on another database, and I noticed some <code>NULL</code>s are returned (even in the <code>INNER JOIN</code> case). This is because some of the columns are in <code>VIEW</code>s.</p>\n\n<p>Try adding:</p>\n\n<pre><code>INNER JOIN sys.tables t\nON t.object_id = c.object_id\n</code></pre>\n\n<p>To filter only to actual <code>IDENTITY</code> columns in tables.</p>\n"
},
{
"answer_id": 219854,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 2,
"selected": true,
"text": "<p>Shouldn't you reverse the from and join, like this:</p>\n\n<pre><code>SELECT c.name, i.seed_value, i.increment_value\nfrom sys.identity_columns i\njoin sys.columns c\n ON i.object_id = c.object_id\n AND i.column_id = c.column_id\n</code></pre>\n"
},
{
"answer_id": 219865,
"author": "Ryan O'Neill",
"author_id": 26221,
"author_profile": "https://Stackoverflow.com/users/26221",
"pm_score": 0,
"selected": false,
"text": "<p>You are missing the Where clause. Your query is effectively saying 'Give me all of sys.columns and any matching rows from sys.identity_columns you have (but give me null if there are no matching rows)'.</p>\n\n<p>By adding the Where clause below you'll change it to only return where an exact match is returned, which is the same as an inner join in this instance really. </p>\n\n<p>SELECT\n c.name, i.seed_value, i.increment_value\nFROM\n sys.columns c\nLEFT OUTER JOIN sys.identity_columns i\n ON i.object_id = c.object_id\n AND i.column_id = c.column_id\nWhere I.seed_value is not null</p>\n\n<p>So I think your data is correct, there are no results to view though.</p>\n"
},
{
"answer_id": 220053,
"author": "Adam Straughan",
"author_id": 14019,
"author_profile": "https://Stackoverflow.com/users/14019",
"pm_score": 0,
"selected": false,
"text": "<p>your query returns what I'd expect [see below]; it returns the single meta-data row about the single identity column (test_ID) in table (ident_test), the oter column (other) has no meta-data in the sys.identity_column as is is not an identity.</p>\n\n<pre>\nSELECT name, seed_value, increment_value\n FROM sys.identity_columns\n WHERE object_id = OBJECT_ID( 'ident_test' )\n\nselect name, is_identity, is_nullable\nfrom sys.columns\nWHERE object_id = OBJECT_ID( 'ident_test' )\n</pre>\n\n<p>Which gives</p>\n\n<pre>\nname seed_value increment_value\n-----------------------------------------\ntest_id 1000 10\n(1 row(s) affected)\n\nname is_identity is_nullable\n-------------------------------------\ntest_id 1 0\nother 0 1\n\n(2 row(s) affected)\n</pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
I'm collecting metadata using the sys.\* views, and according to the documentation, the sys.identity\_columns view will return the seed and increment values like so.
```
CREATE TABLE ident_test (
test_id int IDENTITY(1000,10),
other int
)
SELECT name, seed_value, increment_value
FROM sys.identity_columns
WHERE object_id = OBJECT_ID( 'ident_test' )
```
However, the above query just returns one column. Is it just me?
(Note: I've had to change this question somewhat from its earlier version.)
|
Shouldn't you reverse the from and join, like this:
```
SELECT c.name, i.seed_value, i.increment_value
from sys.identity_columns i
join sys.columns c
ON i.object_id = c.object_id
AND i.column_id = c.column_id
```
|
219,851 |
<p>I want a method of the class: "<code>One</code>" ("<code>AccessibleWithinSameNamespace</code>") to be accessible by the class: "<code>Two</code>", without having "<code>Two</code>" extending "<code>One</code>".</p>
<p>Both classes are in the same namespace, so I'm thinking that maybe there's an access-modifier that emulates the "<em>protected</em>" modifyer, but for namespaces.</p>
<p>Some code:</p>
<pre><code>namespace Test
{
class One
{
public void AccessibleToAll()
{
}
protected void AccessibleWithinSameNamespace()
{
// I am not public
// I can be accessed from other classes
// within the same namespace of my class
}
}
}
namespace Test
{
class Two
{
public Two()
{
One one = new One();
// I am able to access this method because my class
// is in the same namespace as the class: "One"
one.AccessibleWithinSameNamespace();
}
}
}
</code></pre>
|
[
{
"answer_id": 219858,
"author": "Jorge Villuendas Zapatero",
"author_id": 27097,
"author_profile": "https://Stackoverflow.com/users/27097",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx\" rel=\"nofollow noreferrer\">internal</a> modifier if both classes are in the same assembly.</p>\n\n<p>With your example:</p>\n\n<pre><code>namespace Test\n{\n class One\n {\n public void AccessibleToAll()\n {\n }\n\n\n internal void AccessibleWithinSameNamespace()\n {\n // I am not public\n\n // I can be accessed from other classes\n // within the same namespace of my class\n }\n }\n}\n\nnamespace Test\n{\n class Two\n {\n public Two()\n {\n One one = new One();\n\n // I am able to access this method because my class\n // is in the same namespace as the class: \"One\"\n one.AccessibleWithinSameNamespace();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 219885,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>C# and .NET have no concept of \"within the same namespace\". Internal is the closest equivalent.</p>\n"
},
{
"answer_id": 219896,
"author": "David B Heise",
"author_id": 13124,
"author_profile": "https://Stackoverflow.com/users/13124",
"pm_score": 1,
"selected": false,
"text": "<p>The problem isn't the access modifier for the namespace its the access modifier for the function. \"Protected\" means that it can be accessed by child classes, not by other classes even if they're in the same namespace. </p>\n\n<p>You have several solutions to choose from...\n1. you can make the access modifier for the function \"internal\" then all classes/functions inside the same assembly (or marked with some cool assembly flags so that they pretend to be in the same assembly) can access it\n2. Make \"TWO\" a sub class of \"One\" then two can call into it (but not via an instance of \"One\" as shown in the same code</p>\n"
},
{
"answer_id": 219918,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "<p>Since namespaces are arbitrary - they can't really be a security boundary. Anyone can create an assembly that reuses your namespace Test.</p>\n\n<p>The best you can do is limit by assembly using the already mentioned internal (and <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">InternalsVisibleTo</a> if needed).</p>\n\n<p>Edit: InternalsVisibleTo allows <em>other</em> assemblies to access <a href=\"http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx\" rel=\"nofollow noreferrer\">internal</a> methods and classes as if they were in the same assembly. You can strong name the other assemblies, which provides security. This is commonly used for test assemblies to test internal members of the main assembly, without bloating the main assembly by including the test code.</p>\n\n<p>Note that, the VB.NET compiler does not respect InternalsVisibleTo - so a VB assembly cannot call into an InternalsVisibleTo attributed assembly. However, C# can call into a VB.NET assembly that has the appropiate InternalsVisibleTo attribute.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
I want a method of the class: "`One`" ("`AccessibleWithinSameNamespace`") to be accessible by the class: "`Two`", without having "`Two`" extending "`One`".
Both classes are in the same namespace, so I'm thinking that maybe there's an access-modifier that emulates the "*protected*" modifyer, but for namespaces.
Some code:
```
namespace Test
{
class One
{
public void AccessibleToAll()
{
}
protected void AccessibleWithinSameNamespace()
{
// I am not public
// I can be accessed from other classes
// within the same namespace of my class
}
}
}
namespace Test
{
class Two
{
public Two()
{
One one = new One();
// I am able to access this method because my class
// is in the same namespace as the class: "One"
one.AccessibleWithinSameNamespace();
}
}
}
```
|
You can use the [internal](http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx) modifier if both classes are in the same assembly.
With your example:
```
namespace Test
{
class One
{
public void AccessibleToAll()
{
}
internal void AccessibleWithinSameNamespace()
{
// I am not public
// I can be accessed from other classes
// within the same namespace of my class
}
}
}
namespace Test
{
class Two
{
public Two()
{
One one = new One();
// I am able to access this method because my class
// is in the same namespace as the class: "One"
one.AccessibleWithinSameNamespace();
}
}
}
```
|
219,870 |
<p>I have a WordPress site (2.6.2) in which I have set the Home page to a static page instead of the normal posts page. The ID of this page is 2, so in the WordPress template I have changed the <code>wp_list_pages</code> to look like this:</p>
<pre><code><?php wp_list_pages('exclude=2&title_li=&depth=1' ); ?>
</code></pre>
<p>this works fine, but now the Home page doesn't get "lit up" when it's selected (because in fact it's page_id 2 that is selected, and it doesn't show in the menu). Is there any easy way around this?</p>
<p>If not, in broad outlines, what's the hard way around this? Make my own version of the <code>wp_list_pages</code> function?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 219911,
"author": "Ruben",
"author_id": 26919,
"author_profile": "https://Stackoverflow.com/users/26919",
"pm_score": 2,
"selected": false,
"text": "<p>You can set a static page as the front page in the Administration > Settings > Reading panel after logging in as the administrator.</p>\n\n<p>The Wordpress manual entry on this subject can be found <a href=\"http://codex.wordpress.org/Creating_a_Static_Front_Page\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 220157,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 3,
"selected": true,
"text": "<p>Setting a static page as the front page doens't highlight the menu link, which is at the heart of the question.</p>\n\n<p>So, you could server-side customize (hack) the wp_list_pages function, but here's a client-side option if you so choose:</p>\n\n<p>Use the jQuery library (conveniently it comes with WP 2.2+), call:</p>\n\n<pre><code>wp_enqueue_script('jquery');\n</code></pre>\n\n<p>or load your own version:</p>\n\n<pre><code>wp_enqueue_script( 'jquery', '/path/to/your/jquery.js', false, '1.2.1');\n</code></pre>\n\n<hr>\n\n<p>Now add a bit of javascript in your template, something like:</p>\n\n<pre><code>if(window.location.href == 'http://www.example.com/'){ //checks for root path - \"home\" ('http://www.example.com/?p=7' or 'http://www.example.com/2008-10/7' will not match)\n jQuery('#nav > ul > li > a:first').addClass('current_page_item');\n}\n</code></pre>\n\n<p>The <em>a:first</em> portion assumes the first link in your menu is the home/frontpage link. If it's not, select via href value or position. Here's by postion:</p>\n\n<p>~~~~~~~~~~~~~~~</p>\n\n<pre><code>jQuery(jQuery('#nav > ul > li > a')[3]).addClass('current_page_item'); //add 'current_page_item' css class so menu item highlighting occurs\n</code></pre>\n\n<p>Example:</p>\n\n<blockquote>\n <p><div id=\"nav\" ></p>\n \n <p><ul ><br>\n <li > <a >Link 0 </a > </li ><br>\n <li > <a >Link 1 </a > </li ><br>\n <li > <a >Link 2 </a > </li ><br>\n <strong><li > <a >Link 3 </a > </li ></strong><br>\n <li > <a >Link 4 </a > </li ><br>\n <li > <a >Link 5 </a > </li ><br>\n </ul > </p>\n \n <p></div ></p>\n</blockquote>\n\n<hr>\n\n<p>Caveats: </p>\n\n<ol>\n<li>Check for the actual name of your menu div id (<em>#nav</em> shown here)</li>\n<li>A nested ul/li menu structure (so more than one level) will require additional code to properly selection the correct <em>a</em> element.</li>\n<li>If menu links are going to change, don't use a positional selection technique, use another hook, like the href value of the link to the home/front page.</li>\n<li>The <em>if(window.location.href == '<a href=\"http://www.example.com/\" rel=\"nofollow noreferrer\">http://www.example.com/</a>')</em> portion may need to be a regex if more variation is involved (https, multiple subdomains, etc).</li>\n</ol>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8047/"
] |
I have a WordPress site (2.6.2) in which I have set the Home page to a static page instead of the normal posts page. The ID of this page is 2, so in the WordPress template I have changed the `wp_list_pages` to look like this:
```
<?php wp_list_pages('exclude=2&title_li=&depth=1' ); ?>
```
this works fine, but now the Home page doesn't get "lit up" when it's selected (because in fact it's page\_id 2 that is selected, and it doesn't show in the menu). Is there any easy way around this?
If not, in broad outlines, what's the hard way around this? Make my own version of the `wp_list_pages` function?
Thanks!
|
Setting a static page as the front page doens't highlight the menu link, which is at the heart of the question.
So, you could server-side customize (hack) the wp\_list\_pages function, but here's a client-side option if you so choose:
Use the jQuery library (conveniently it comes with WP 2.2+), call:
```
wp_enqueue_script('jquery');
```
or load your own version:
```
wp_enqueue_script( 'jquery', '/path/to/your/jquery.js', false, '1.2.1');
```
---
Now add a bit of javascript in your template, something like:
```
if(window.location.href == 'http://www.example.com/'){ //checks for root path - "home" ('http://www.example.com/?p=7' or 'http://www.example.com/2008-10/7' will not match)
jQuery('#nav > ul > li > a:first').addClass('current_page_item');
}
```
The *a:first* portion assumes the first link in your menu is the home/frontpage link. If it's not, select via href value or position. Here's by postion:
~~~~~~~~~~~~~~~
```
jQuery(jQuery('#nav > ul > li > a')[3]).addClass('current_page_item'); //add 'current_page_item' css class so menu item highlighting occurs
```
Example:
>
> <div id="nav" >
>
>
> <ul >
>
> <li > <a >Link 0 </a > </li >
>
> <li > <a >Link 1 </a > </li >
>
> <li > <a >Link 2 </a > </li >
>
> **<li > <a >Link 3 </a > </li >**
>
> <li > <a >Link 4 </a > </li >
>
> <li > <a >Link 5 </a > </li >
>
> </ul >
>
>
> </div >
>
>
>
---
Caveats:
1. Check for the actual name of your menu div id (*#nav* shown here)
2. A nested ul/li menu structure (so more than one level) will require additional code to properly selection the correct *a* element.
3. If menu links are going to change, don't use a positional selection technique, use another hook, like the href value of the link to the home/front page.
4. The *if(window.location.href == '<http://www.example.com/>')* portion may need to be a regex if more variation is involved (https, multiple subdomains, etc).
|
219,873 |
<p>I've written a IE Toolbar in C# and everything is working fine except that when I open a child Windows Form from my toolbar, the tab key doesn't work on the child form to allow me to move from field to field.</p>
<p>The interesting part is that when I open my child form using form.showDialog() instead of form.show() the tabs work like normal.</p>
<p>The toolbar I've created is based on this <a href="http://lamp.codeproject.com/KB/shell/dotnetbandobjects.aspx?fid=3788&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2766883&fr=301#xx0xx" rel="nofollow noreferrer">article</a> and this <a href="https://secure.codeproject.com/KB/cs/Issuewithbandobjects.aspx" rel="nofollow noreferrer">article</a> </p>
<p>I've implemented TranslateAcceleratorIO as mentioned in several articles, but still no luck.</p>
<p>Here are my implmentations of TranslateAcceleratorIO() and HasFocusIO() (implemented in my toolband class)</p>
<pre><code> [DllImport("user32.dll")]
public static extern int TranslateMessage(ref MSG lpMsg);
[DllImport("user32", EntryPoint = "DispatchMessage")]
static extern bool DispatchMessage(ref MSG msg);
public int HasFocusIO()
{
return this.ContainsFocus ? 0 : 1; //S_OK : S_FALSE;
}
public int TranslateAcceleratorIO(ref MSG msg)
{
if (msg.message == 0x100)//WM_KEYDOWN
if (msg.wParam == (uint)Keys.Tab || msg.wParam ==(uint)Keys.F6)
{
if (SelectNextControl(
ActiveControl,
ModifierKeys == Keys.Shift ? false : true,
true,
true,
false)
)
{
return 0;//S_OK
}
}
else
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
return 0;//S_OK
}
return 1;//S_FALSE
}
</code></pre>
<p>I've also tried having TranslateAccelerator like this with no luck:</p>
<pre><code> public int TranslateAcceleratorIO(ref MSG msg)
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
return 0;//S_OK
}
</code></pre>
<p>Has anybody else run into this issue?</p>
|
[
{
"answer_id": 220016,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 1,
"selected": false,
"text": "<p>Are you also implementing HasFocusIO? I believe your main toolbar class must also implement HasFocusIO and return true.</p>\n\n<p>These types of problems with IE toolbars were the bane of my existence for a while. I think what I eventually ended up doing was creating separate UI threads and making my dialogs modal in those threads, which eliminated a bunch of weird issues. But I think implementing HasFocusIO and TranslateAcceleratorIO should work for this particular one.</p>\n"
},
{
"answer_id": 222302,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 0,
"selected": false,
"text": "<p>Where are you implementing these? It's hard to tell from what you have there, are you implementing them in your Form or are you implementing them in your deskband class? </p>\n\n<p>You need to implement them in your DeskBand implementation, and HasFocusIO needs to return true whenever one of your windows has focus (not just when the toolbar has focus). Then the messages for Tab, Delete, arrow keys, etc should be dispatched to the TranslateAcceleratorIO, also in your deskband, and from there you'll have to pass them along to your form. </p>\n\n<p>The IE plugin framework is incredibly hacky that way.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26500/"
] |
I've written a IE Toolbar in C# and everything is working fine except that when I open a child Windows Form from my toolbar, the tab key doesn't work on the child form to allow me to move from field to field.
The interesting part is that when I open my child form using form.showDialog() instead of form.show() the tabs work like normal.
The toolbar I've created is based on this [article](http://lamp.codeproject.com/KB/shell/dotnetbandobjects.aspx?fid=3788&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2766883&fr=301#xx0xx) and this [article](https://secure.codeproject.com/KB/cs/Issuewithbandobjects.aspx)
I've implemented TranslateAcceleratorIO as mentioned in several articles, but still no luck.
Here are my implmentations of TranslateAcceleratorIO() and HasFocusIO() (implemented in my toolband class)
```
[DllImport("user32.dll")]
public static extern int TranslateMessage(ref MSG lpMsg);
[DllImport("user32", EntryPoint = "DispatchMessage")]
static extern bool DispatchMessage(ref MSG msg);
public int HasFocusIO()
{
return this.ContainsFocus ? 0 : 1; //S_OK : S_FALSE;
}
public int TranslateAcceleratorIO(ref MSG msg)
{
if (msg.message == 0x100)//WM_KEYDOWN
if (msg.wParam == (uint)Keys.Tab || msg.wParam ==(uint)Keys.F6)
{
if (SelectNextControl(
ActiveControl,
ModifierKeys == Keys.Shift ? false : true,
true,
true,
false)
)
{
return 0;//S_OK
}
}
else
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
return 0;//S_OK
}
return 1;//S_FALSE
}
```
I've also tried having TranslateAccelerator like this with no luck:
```
public int TranslateAcceleratorIO(ref MSG msg)
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
return 0;//S_OK
}
```
Has anybody else run into this issue?
|
Are you also implementing HasFocusIO? I believe your main toolbar class must also implement HasFocusIO and return true.
These types of problems with IE toolbars were the bane of my existence for a while. I think what I eventually ended up doing was creating separate UI threads and making my dialogs modal in those threads, which eliminated a bunch of weird issues. But I think implementing HasFocusIO and TranslateAcceleratorIO should work for this particular one.
|
219,881 |
<p>Is there a preference or behavior difference between using:</p>
<pre><code>if(obj.getClass().isArray()) {}
</code></pre>
<p>and</p>
<pre><code>if(obj instanceof Object[]) {}
</code></pre>
<p>?</p>
|
[
{
"answer_id": 219891,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 5,
"selected": false,
"text": "<p>In the latter case, if obj is null you won't get a NullPointerException but a false.</p>\n"
},
{
"answer_id": 219898,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 0,
"selected": false,
"text": "<p>There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.</p>\n\n<p>If it confuses readers of your code (because <code>String[] instanceof Object[]</code> is true), you may want to use the first to be more explicit if code reviewers keep asking about it.</p>\n"
},
{
"answer_id": 219908,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "<p>If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's \"Wrong\" or anything, but anything involving reflection is generally less obvious and less clear.</p>\n"
},
{
"answer_id": 219998,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 9,
"selected": true,
"text": "<p>In most cases, you should use the <code>instanceof</code> operator to test whether an object is an array.</p>\n\n<p>Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a <code>Integer[]</code> or an <code>int[]</code>. You'd want to guard your casts with <code>instanceof</code>:</p>\n\n<pre><code>if (obj instanceof Integer[]) {\n Integer[] array = (Integer[]) obj;\n /* Use the boxed array */\n} else if (obj instanceof int[]) {\n int[] array = (int[]) obj;\n /* Use the primitive array */\n} else ...\n</code></pre>\n\n<p>At the JVM level, the <code>instanceof</code> operator translates to a specific <a href=\"http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#instanceof\" rel=\"noreferrer\">\"instanceof\"</a> byte code, which is optimized in most JVM implementations.</p>\n\n<p>In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the <code>isArray()</code> method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.</p>\n\n<p>There are two special cases: null references and references to primitive arrays.</p>\n\n<p>A null reference will cause <code>instanceof</code> to result <code>false</code>, while the <code>isArray</code> throws a <code>NullPointerException</code>.</p>\n\n<p>Applied to a primitive array, the <code>instanceof</code> yields <code>false</code> unless the component type on the right-hand operand exactly matches the component type. In contrast, <code>isArray()</code> will return <code>true</code> for any component type.</p>\n"
},
{
"answer_id": 221631,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": false,
"text": "<p>If <code>obj</code> is of type <code>int[]</code> say, then that will have an array <code>Class</code> but not be an instance of <code>Object[]</code>. So what do you want to do with <code>obj</code>. If you are going to cast it, go with <code>instanceof</code>. If you are going to use reflection, then use <code>.getClass().isArray()</code>.</p>\n"
},
{
"answer_id": 1681141,
"author": "Sebastien Tardif",
"author_id": 203525,
"author_profile": "https://Stackoverflow.com/users/203525",
"pm_score": 2,
"selected": false,
"text": "<p><code>getClass().isArray()</code> is significantly slower on Sun Java 5 or 6 JRE than on IBM.</p>\n\n<p>So much that using <code>clazz.getName().charAt(0) == '['</code> is faster on Sun JVM.</p>\n"
},
{
"answer_id": 4572932,
"author": "Trenton D. Adams",
"author_id": 559584,
"author_profile": "https://Stackoverflow.com/users/559584",
"pm_score": 2,
"selected": false,
"text": "<p>Java array reflection is for cases where you don't have an instance of the Class available to do \"instanceof\" on. For example, if you're writing some sort of injection framework, that injects values into a new instance of a class, such as JPA does, then you need to use the isArray() functionality.</p>\n\n<p>I blogged about this earlier in December.\n<a href=\"http://blog.adamsbros.org/2010/12/08/java-array-reflection/\" rel=\"nofollow\">http://blog.adamsbros.org/2010/12/08/java-array-reflection/</a></p>\n"
},
{
"answer_id": 12873642,
"author": "dturanski",
"author_id": 1743446,
"author_profile": "https://Stackoverflow.com/users/1743446",
"pm_score": 2,
"selected": false,
"text": "<p>I recently ran into an issue upgrading a Groovy application from JDK 5 to JDK 6. Using <code>isArray()</code> failed in JDK6:</p>\n\n<pre><code>MissingMethodException:\nNo signature of sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl.isArray() ...\n</code></pre>\n\n<p>Changing to <code>instanceof Object[]</code> fixed this. </p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5309/"
] |
Is there a preference or behavior difference between using:
```
if(obj.getClass().isArray()) {}
```
and
```
if(obj instanceof Object[]) {}
```
?
|
In most cases, you should use the `instanceof` operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a `Integer[]` or an `int[]`. You'd want to guard your casts with `instanceof`:
```
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
```
At the JVM level, the `instanceof` operator translates to a specific ["instanceof"](http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#instanceof) byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the `isArray()` method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause `instanceof` to result `false`, while the `isArray` throws a `NullPointerException`.
Applied to a primitive array, the `instanceof` yields `false` unless the component type on the right-hand operand exactly matches the component type. In contrast, `isArray()` will return `true` for any component type.
|
219,904 |
<p>If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:</p>
<pre><code>private object m_myProp;
public object MyProp
{
get { return m_myProp; }
}
protected void SetMyProp(object value)
{
m_myProp = value;
}
</code></pre>
<p>Is there a better way?</p>
|
[
{
"answer_id": 219913,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "<pre><code>private object m_myProp;\npublic object MyProp\n{\n get { return m_myProp; }\n protected set { m_myProp = value; }\n}\n</code></pre>\n\n<p>Or in C# 3.0</p>\n\n<pre><code>public object MyProp {get; protected set;}\n</code></pre>\n"
},
{
"answer_id": 219929,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>Having a setter and getter isn't really any better than having a variable at that level of visibility.</p>\n\n<p>Therefore you could just make the variable itself protected and the reader public.</p>\n\n<p>That said, setters and getters are an indicator of bad OO--are you sure you need them? You should be asking the object to do something with its members, not asking it for its members then manipulating them outside the object.</p>\n\n<p>This is a very general rule and there are a lot of exceptions.</p>\n"
},
{
"answer_id": 219931,
"author": "Brendan Enrick",
"author_id": 22381,
"author_profile": "https://Stackoverflow.com/users/22381",
"pm_score": 3,
"selected": false,
"text": "<p>This is definitely the way to go.</p>\n\n<pre><code>public object MyProp {get; protected set;}\n</code></pre>\n\n<p>If you're on an older version of C# then this is the way to go.</p>\n\n<pre><code>private object _myProp;\npublic object MyProp\n{\n get { return _myProp; }\n protected set { _myProp = value; }\n}\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27414/"
] |
If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:
```
private object m_myProp;
public object MyProp
{
get { return m_myProp; }
}
protected void SetMyProp(object value)
{
m_myProp = value;
}
```
Is there a better way?
|
```
private object m_myProp;
public object MyProp
{
get { return m_myProp; }
protected set { m_myProp = value; }
}
```
Or in C# 3.0
```
public object MyProp {get; protected set;}
```
|
219,914 |
<p>I've often used pointers to const objects, like so...</p>
<pre><code>const int *p;
</code></pre>
<p>That simply means that you can't change the integer that <code>p</code> is pointing at through <code>p</code>. But I've also seen reference to const pointers, declared like this...</p>
<pre><code>int* const p;
</code></pre>
<p>As I understand it, that means that the pointer variable <em>itself</em> is constant -- you can change the integer it points at all day long, but you can't make it point at something else.</p>
<p>What possible use would that have?</p>
|
[
{
"answer_id": 219932,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Same as a \"const int\" ... if the compiler knows it's not going to change, it can be optimization assumptions based on that.</p>\n\n<pre><code>struct MyClass\n{\n char* const ptr;\n MyClass(char* str) :ptr(str) {}\n\n void SomeFunc(MyOtherClass moc)\n {\n for(int i=0; i < 100; ++i)\n { \n printf(\"%c\", ptr[i]);\n moc.SomeOtherFunc(this);\n }\n }\n}\n</code></pre>\n\n<p>Now, the compiler could do quite a bit to optimize that loop --- provided it knows that SomeOtherFunc() does not change the value of ptr. With the const, the compiler knows that, and can make the assumptions. Without it, the compiler has to assume that SomeOtherFunc will change ptr.</p>\n"
},
{
"answer_id": 219956,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": true,
"text": "<p>When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.</p>\n\n<p>For instance, I have a <a href=\"http://flickr.com/photos/adavis/2945502665/\" rel=\"noreferrer\">32 bit MIPs processor</a> that has a <a href=\"http://flickr.com/photos/adavis/2946164671/\" rel=\"noreferrer\">little LCD</a> attached to it. I have to write my LCD data to a specific port in memory, which then gets sent to the LCD controller.</p>\n\n<p>I could #define that number, but then I also have to cast it as a pointer, and the C compiler doesn't have as many options when I do that. </p>\n\n<p>Further, I might need it to be volatile, which can also be cast, but it's easier and clearer to use the syntax provided - a const pointer to a volatile memory location.</p>\n\n<p>For PC programs, an example would be: If you design DOS VGA games (there are tutorials online which are fun to go through to learn basic low level graphics) then you need to write to the VGA memory, which might be referenced as an offset from a const pointer.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 219957,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 3,
"selected": false,
"text": "<p>another example:\nif you know where it was initialized, you can avoid future NULL checks.\nThe compiler guarantees you that the pointer never changed (to NULL)…</p>\n"
},
{
"answer_id": 219960,
"author": "epotter",
"author_id": 26339,
"author_profile": "https://Stackoverflow.com/users/26339",
"pm_score": 2,
"selected": false,
"text": "<p>I have seen some OLE code where you there was an object passed in from outside the code and to work with it, you had to access the specific memory that it passed in. So we used const pointers to make sure that functions always manipulated the values than came in through the OLE interface.</p>\n"
},
{
"answer_id": 219962,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>In any non-const C++ member function, the <code>this</code> pointer is of type <code>C * const</code>, where <code>C</code> is the class type -- you can change what it points to (i.e. its members), but you can't change it to point to a different instance of a <code>C</code>. For <code>const</code> member functions, <code>this</code> is of type <code>const C * const</code>. There are also (rarely encountered) <code>volatile</code> and <code>const volatile</code> member functions, for which <code>this</code> also has the <code>volatile</code> qualifier.</p>\n"
},
{
"answer_id": 219965,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 2,
"selected": false,
"text": "<p>I've always used them when I wanted to avoid unintended modification to the pointer (such as pointer arithmetic, or inside a function). You can also use them for Singleton patterns.</p>\n\n<p>'this' is a hardcoded constant pointer.</p>\n"
},
{
"answer_id": 219973,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 5,
"selected": false,
"text": "<p>It allows you to protect the pointer from being changed. This means you can protect assumptions you make based on the pointer never changing or from unintentional modification, for example:</p>\n\n<pre><code>int* const p = &i;\n\n...\n\np++; /* Compiler error, oops you meant */\n(*p)++; /* Increment the number */\n</code></pre>\n"
},
{
"answer_id": 220025,
"author": "DavidG",
"author_id": 25893,
"author_profile": "https://Stackoverflow.com/users/25893",
"pm_score": -1,
"selected": false,
"text": "<p>always think of a pointer as an int. this means that</p>\n\n<pre><code>object* var;\n</code></pre>\n\n<p>actually can be thought of as</p>\n\n<pre><code>int var;\n</code></pre>\n\n<p>so, a const pointer simply means that:</p>\n\n<pre><code>const object* var;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>const int var;\n</code></pre>\n\n<p>and hence u can't change the address that the pointer points too, and thats all. To prevent data change, u must make it a pointer to a const object.</p>\n"
},
{
"answer_id": 220043,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>Several good reasons have been given as answers to this questions (memory-mapped devices and just plain old defensive coding), but I'd be willing to bet that most instances where you see this it's actually an error and that the intent was to have to item be a pointer-to-const.</p>\n\n<p>I certainly have no data to back up this hunch, but I'd still make the bet.</p>\n"
},
{
"answer_id": 220062,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p>One use is in low-level (device driver or embedded) code where you need to reference a specific address that's mapped to an input/output device like a hardware pin. Some languages allow you to link variables at specific addresses (e.g. Ada has <code>use at</code>). In C the most idiomatic way to do this is to declare a constant pointer. Note that such usages should also have the <code>volatile</code> qualifier.</p>\n\n<p>Other times it's just defensive coding. If you have a pointer that <em>shouldn't</em> change it's wise to declare it such that it <em>cannot</em> change. This will allow the compiler (and lint tools) to detect erroneous attempts to modify it.</p>\n"
},
{
"answer_id": 220144,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 0,
"selected": false,
"text": "<p>Think of <strong>type*</strong> and <strong>const type*</strong> as types themselves. Then, you can see why you might want to have a const of those types.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
I've often used pointers to const objects, like so...
```
const int *p;
```
That simply means that you can't change the integer that `p` is pointing at through `p`. But I've also seen reference to const pointers, declared like this...
```
int* const p;
```
As I understand it, that means that the pointer variable *itself* is constant -- you can change the integer it points at all day long, but you can't make it point at something else.
What possible use would that have?
|
When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.
For instance, I have a [32 bit MIPs processor](http://flickr.com/photos/adavis/2945502665/) that has a [little LCD](http://flickr.com/photos/adavis/2946164671/) attached to it. I have to write my LCD data to a specific port in memory, which then gets sent to the LCD controller.
I could #define that number, but then I also have to cast it as a pointer, and the C compiler doesn't have as many options when I do that.
Further, I might need it to be volatile, which can also be cast, but it's easier and clearer to use the syntax provided - a const pointer to a volatile memory location.
For PC programs, an example would be: If you design DOS VGA games (there are tutorials online which are fun to go through to learn basic low level graphics) then you need to write to the VGA memory, which might be referenced as an offset from a const pointer.
-Adam
|
219,982 |
<p>e.g,</p>
<pre><code>foo1
foo2
foo10
foo100
</code></pre>
<p>rather than</p>
<pre><code>foo1
foo10
foo100
foo2
</code></pre>
<p>Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.</p>
|
[
{
"answer_id": 219985,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<p>You can use functions in your order-by clause. In this case,\nyou can split the non-numeric and numeric portions of the\nfield and use them as two of the ordering criteria.</p>\n\n<pre><code>select * from t\n order by to_number(regexp_substr(a,'^[0-9]+')),\n to_number(regexp_substr(a,'[0-9]+$')),\n a;\n</code></pre>\n\n<p>You can also create a function-based index to support this:</p>\n\n<pre><code>create index t_ix1\n on t (to_number(regexp_substr(a, '^[0-9]+')),\n to_number(regexp_substr(a, '[0-9]+$')), \n a);\n</code></pre>\n"
},
{
"answer_id": 4246927,
"author": "Coder",
"author_id": 516287,
"author_profile": "https://Stackoverflow.com/users/516287",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following function to 0-pad all sequences of digits shorter than 10 that could be found in the value, so that the total length of each to become 10 digits. It is compatible even with mixed sets of values that have one, many or none sequences of digits in them.</p>\n\n<pre><code>CREATE OR replace function NATURAL_ORDER(\n P_STR varchar2\n) return varchar2\nIS\n/** --------------------------------------------------------------------\n Replaces all sequences of numbers shorter than 10 digits by 0-padded\n numbers that exactly 10 digits in length. Usefull for ordering-by\n using NATURAL ORDER algorithm.\n */\n l_result varchar2( 32700 );\n l_len integer;\n l_ix integer;\n l_end integer;\nbegin\n l_result := P_STR;\n l_len := LENGTH( l_result );\n l_ix := 1;\n while l_len > 0 loop\n l_ix := REGEXP_INSTR( l_result, '[0-9]{1,9}', l_ix, 1, 0 );\n EXIT when l_ix = 0;\n l_end := REGEXP_INSTR( l_result, '[^0-9]|$', l_ix, 1, 0 );\n if ( l_end - l_ix >= 10 ) then\n l_ix := l_end;\n else\n l_result := substr( l_result, 1, l_ix - 1 )\n || LPAD( SUBSTR( l_result, l_ix, l_end-l_ix ), 10, '0' )\n || substr( l_result, l_end )\n ;\n l_ix := l_ix + 10;\n end if;\n end loop;\n return l_result;\nend;\n/\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>select 'ABC' || LVL || 'DEF' as STR\n from (\n select LEVEL as LVL\n from DUAL\n start with 1=1\n connect by LEVEL <= 35\n )\n order by NATURAL_ORDER( STR )\n</code></pre>\n"
},
{
"answer_id": 32215335,
"author": "Vladimir Sitnikov",
"author_id": 1261287,
"author_profile": "https://Stackoverflow.com/users/1261287",
"pm_score": 2,
"selected": false,
"text": "<h1>For short strings, small number of numerics</h1>\n\n<p>If number of \"numerics\" and the maximum length are limited, there is a regexp-based solution.</p>\n\n<p>The idea is:</p>\n\n<ul>\n<li>Pad all numerics with 20 zeroes</li>\n<li>Remove excessive zeroes using another regexp. This might be slow due to <a href=\"http://www.regular-expressions.info/catastrophic.html\" rel=\"nofollow noreferrer\">regexp backtracking</a>.</li>\n</ul>\n\n<p>Assumptions:</p>\n\n<ul>\n<li>Maximum length of numerics is known beforehand (e.g. 20)</li>\n<li>All the numerics can be padded (in other words, <code>lpad('1 ', 3000, '1 ')</code> will fail due do unable to fit padded numerics into <code>varchar2(4000)</code>)</li>\n</ul>\n\n<p>The following query is optimized for \"short numerics\" case (see <code>*?</code>) and it takes 0.4 seconds. However, when using such approach, you need to predefine padding length.</p>\n\n<pre><code>select * from (\n select dbms_random.string('X', 30) val from xmltable('1 to 1000')\n)\norder by regexp_replace(regexp_replace(val, '(\\d+)', lpad('0', 20, '0')||'\\1')\n , '0*?(\\d{21}(\\D|$))', '\\1');\n</code></pre>\n\n<h1>\"Clever\" approach</h1>\n\n<p>Even though separate <code>natural_sort</code> function can be handy, there is a little-known trick to do that in pure SQL.</p>\n\n<p>Key ideas:</p>\n\n<ul>\n<li>Strip leading zeroes from all the numerics so <code>02</code> is ordered between <code>1</code> and <code>3</code>: <code>regexp_replace(val, '(^|\\D)0+(\\d+)', '\\1\\2')</code>. Note: this might result in \"unexpected\" sorting of <code>10.02</code> > <code>10.1</code> (since <code>02</code> is converted to <code>2</code>), however there is no single answer how things like <code>10.02.03</code> should be sorted</li>\n<li>Convert <code>\"</code> to <code>\"\"</code> so text with quotes works properly</li>\n<li>Convert input string to comma delimited format: <code>'\"'||regexp_replace(..., '([^0-9]+)', '\",\"\\1\",\"')||'\"'</code></li>\n<li>Convert csv to the list of items via <code>xmltable</code></li>\n<li>Augment numeric-like items so string sort works properly</li>\n<li>Use <code>length(length(num))||length(num)||num</code> instead of <code>lpad(num, 10, '0')</code> as the latter is less compact and does not support 11+ digit numbers.\nNote: </li>\n</ul>\n\n<p>Response time is something like 3-4 seconds for sorting list of 1000 random strings of length 30 (the generation of the random strings takes 0.2 sec itself).\nThe main time consumer is <code>xmltable</code> that splits text into rows.\nIf using PL/SQL instead of <code>xmltable</code> to split string into rows the response time reduces to 0.4sec for the same 1000 rows.</p>\n\n<p>The following query performs natural sort of 100 random alpha-numeric strings (note: it produces wrong results in Oracle 11.2.0.4 and it works in 12.1.0.2):</p>\n\n<pre><code>select *\n from (\n select (select listagg(case when regexp_like(w, '^[0-9]')\n then length(length(w))||length(w)||w else w\n end\n ) within group (order by ord)\n from xmltable(t.csv columns w varchar2(4000) path '.'\n , ord for ordinality) q\n ) order_by\n , t.*\n from (\n select '\"'||regexp_replace(replace(\n regexp_replace(val, '(^|\\D)0+(\\d+)', '\\1\\2')\n , '\"', '\"\"')\n , '([^0-9]+)', '\",\"\\1\",\"')||'\"' csv\n , t.*\n from (\n select dbms_random.string('X', 30) val from xmltable('1 to 100')\n ) t\n ) t\n ) t\norder by order_by;\n</code></pre>\n\n<p>The fun part is this <code>order by</code> can be expressed without subqueries, so it is a handy tool to make your reviewer crazy (it works in both 11.2.0.4 and 12.1.0.2):</p>\n\n<pre><code>select *\n from (select dbms_random.string('X', 30) val from xmltable('1 to 100')) t\n order by (\n select listagg(case when regexp_like(w, '^[0-9]')\n then length(length(w))||length(w)||w else w\n end\n ) within group (order by ord)\n from xmltable('$X'\n passing xmlquery(('\"'||regexp_replace(replace(\n regexp_replace(t.val, '(^|\\D)0+(\\d+)', '\\1\\2')\n , '\"', '\"\"')\n , '([^0-9]+)', '\",\"\\1\",\"')||'\"')\n returning sequence\n ) as X\n columns w varchar2(4000) path '.', ord for ordinality) q\n);\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/219982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
e.g,
```
foo1
foo2
foo10
foo100
```
rather than
```
foo1
foo10
foo100
foo2
```
Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.
|
You can use functions in your order-by clause. In this case,
you can split the non-numeric and numeric portions of the
field and use them as two of the ordering criteria.
```
select * from t
order by to_number(regexp_substr(a,'^[0-9]+')),
to_number(regexp_substr(a,'[0-9]+$')),
a;
```
You can also create a function-based index to support this:
```
create index t_ix1
on t (to_number(regexp_substr(a, '^[0-9]+')),
to_number(regexp_substr(a, '[0-9]+$')),
a);
```
|
220,010 |
<p>Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program. </p>
<p>I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?</p>
<p>I'm just wondering what others do to organize their programs without breaking the rules?</p>
|
[
{
"answer_id": 220056,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 0,
"selected": false,
"text": "<p>If I am understanding you correctly, it sounds like the lifetime of your dialog objects is too long. Rather than maintaining the dialogs for the duration of your program, you should consider creating and destroying them as they are needed.</p>\n\n<p>Also, global variables (or singletons) are OK so long as the thing that the variable represents is truly a global thing that persists for the lifetime of the program, rather than just a place-holder for an object of lesser duration. Using globals for the wrong things for simplicity sake will come back to bite you eventually, even if the globals are stored on the main dialog.</p>\n"
},
{
"answer_id": 230888,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 2,
"selected": false,
"text": "<p>I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.</p>\n\n<p>The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.</p>\n\n<p>The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.</p>\n\n<p>A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .</p>\n\n<p>Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.</p>\n\n<p>Place your singleton in the theApp</p>\n\n<pre><code>class CsolverApp : public CWinApp\n{\npublic:\n\ncData theData;\n\n…\n</code></pre>\n\n<p>Now to access this from anywhere in your code</p>\n\n<pre><code>#include “solver.h”\n\ntheApp.theData.somepublicmethod();\n</code></pre>\n"
},
{
"answer_id": 235647,
"author": "Paul Sonier",
"author_id": 28053,
"author_profile": "https://Stackoverflow.com/users/28053",
"pm_score": 1,
"selected": false,
"text": "<p>It does make sense to look at this from the MVC (Model - View - Controller) viewpoint. (That the naming of MFC is an homage to MVC is another sick joke on Microsoft's part; it is hard and unintuitive (but by no means impossible) to manage the types of abstractions that are necessary in \"true\" MVC within MFC.)</p>\n\n<p>Specifically, it sounds like you've thought out the basis for MVC design; you have the classes that do the underlying business logic work (the Model), and you know they should be separated from the UI components (the View). The issue that comes in now is the third part of the MVC trinity; the Controller.</p>\n\n<p>MFC makes this stuff tough by apparently purposefully obfuscating the MVC process, by making you start with a Dialog. In your instance, the Dialog that MFC is starting you off with should be the Controller, and NOT the View. What your Dialog (Controller) is doing for you is managing your UI components (View) and allowing them to interact with your \"work\" classes (Model). What makes this tough again is that your UI components, to be visible, most likely need to be attached to your Dialog to be visible.</p>\n\n<p>To get this sort of thing right, you really have to basically implement your Controller as a high-level object that gets instantiated from your Dialog; your Dialog is where the initial control flow comes in, your Controller gets control flow, and from there, it should treat the Dialog as just another UI component (albeit one with special status).</p>\n\n<p>This allows you to have the proper level of encapsulation; your Controller invokes your business logic (Model) classes, which can communicate with each other or with the Controller as appropriate; they are segregated from the View by the Controller, instead of being embedded in the UI components and (likely) taking the \"easy way\" of over-privileged access to UI elements (\"Hmm, I need this object to get some input from the user; I could refactor, but it'll be so much easier to just throw a dialog box up, since I have the top-level window handle...\").</p>\n\n<p>Once your Controller object is the home to all of the business logic objects, things become easier; you can use the Controller to provide cross-object access for any objects that need other objects. Think about which classes need to be Singletons, and use them sparingly. Resources that need contention management (such as hardware resources) are great examples of \"natural singletons\"; things which lend themselves to a singleton approach. You may also choose to make your Controller a singleton; depending on the requirements for access to it. Specifically, in your Dependency Injection scenario, the Controller is where you'd instantiate the objects and manage the dependencies.</p>\n\n<p>This is the basic MVC approach; but, like I say, MFC makes it unusually hard and unintuitive, because of the fundamental design of MFC. I learned MUCH more about MVC <strong>AFTER</strong> an initial <strong>VERY</strong> negative impression about it due to MFC; if you can, I recommend looking into what MVC implementations look like in other languages.</p>\n\n<p>Good luck!</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23504/"
] |
Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program.
I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?
I'm just wondering what others do to organize their programs without breaking the rules?
|
I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.
The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.
The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.
A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .
Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.
Place your singleton in the theApp
```
class CsolverApp : public CWinApp
{
public:
cData theData;
…
```
Now to access this from anywhere in your code
```
#include “solver.h”
theApp.theData.somepublicmethod();
```
|
220,020 |
<h2>Caution: This question is over nine years old!</h2>
<p>Your best option is to search for newer questions, or to search the answers below looking for your specific version of MVC, as many answers here are obsolete now. </p>
<p>If you do find an answer that works for your version, please make sure the answer contains the version of MVC you are using.<br>
<sub><sub>(The original question starts below)</sub></sub></p>
<hr>
<p>This seems a bit bizarre to me, but as far as I can tell, this is how you do it.</p>
<p>I have a collection of objects, and I want users to select one or more of them. This says to me "form with checkboxes." My objects don't have any concept of "selected" (they're rudimentary POCO's formed by deserializing a wcf call). So, I do the following:</p>
<pre><code>public class SampleObject{
public Guid Id {get;set;}
public string Name {get;set;}
}
</code></pre>
<p>In the view:</p>
<pre><code><%
using (Html.BeginForm())
{
%>
<%foreach (var o in ViewData.Model) {%>
<%=Html.CheckBox(o.Id)%>&nbsp;<%= o.Name %>
<%}%>
<input type="submit" value="Submit" />
<%}%>
</code></pre>
<p>And, in the controller, this is the only way I can see to figure out what objects the user checked:</p>
<pre><code>public ActionResult ThisLooksWeird(FormCollection result)
{
var winnars = from x in result.AllKeys
where result[x] != "false"
select x;
// yadda
}
</code></pre>
<p>Its freaky in the first place, and secondly, for those items the user checked, the FormCollection lists its value as "true false" rather than just true. </p>
<p>Obviously, I'm missing something. I think this is built with the idea in mind that the objects in the collection that are acted upon within the html form are updated using <code>UpdateModel()</code> or through a ModelBinder. </p>
<p>But my objects aren't set up for this; does that mean that this is the only way? Is there another way to do it?</p>
|
[
{
"answer_id": 220041,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 5,
"selected": false,
"text": "<p>Here's what I've been doing.</p>\n\n<p>View:</p>\n\n<pre>\n<code>\n<input type=\"checkbox\" name=\"applyChanges\" />\n</code>\n</pre>\n\n<p>Controller:</p>\n\n<pre>\n<code>\nvar checkBox = Request.Form[\"applyChanges\"];\n\nif (checkBox == \"on\")\n{\n...\n}\n</code>\n</pre>\n\n<p>I found the Html.* helper methods not so useful in some cases, and that I was better off doing it in plain old HTML. This being one of them, the other one that comes to mind is radio buttons.</p>\n\n<p>Edit: this is on Preview 5, obviously YMMV between versions.</p>\n"
},
{
"answer_id": 220073,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 9,
"selected": true,
"text": "<p>Html.CheckBox is doing something weird - if you view source on the resulting page, you'll see there's an <code><input type=\"hidden\" /></code> being generated alongside each checkbox, which explains the \"true false\" values you're seeing for each form element.</p>\n\n<p>Try this, which definitely works on ASP.NET MVC Beta because I've just tried it.</p>\n\n<p>Put this in the view instead of using Html.CheckBox():</p>\n\n<pre><code><% using (Html.BeginForm(\"ShowData\", \"Home\")) { %>\n <% foreach (var o in ViewData.Model) { %>\n <input type=\"checkbox\" name=\"selectedObjects\" value=\"<%=o.Id%>\">\n <%= o.Name %>\n <%}%>\n <input type=\"submit\" value=\"Submit\" />\n<%}%>\n</code></pre>\n\n<p>Your checkboxes are all called <code>selectedObjects</code>, and the <code>value</code> of each checkbox is the GUID of the corresponding object.</p>\n\n<p>Then post to the following controller action (or something similar that does something useful instead of Response.Write())</p>\n\n<pre><code>public ActionResult ShowData(Guid[] selectedObjects) {\n foreach (Guid guid in selectedObjects) {\n Response.Write(guid.ToString());\n }\n Response.End();\n return (new EmptyResult());\n}\n</code></pre>\n\n<p>This example will just write the GUIDs of the boxes you checked; ASP.NET MVC maps the GUID values of the selected checkboxes into the <code>Guid[] selectedObjects</code> parameter for you, and even parses the strings from the Request.Form collection into instantied GUID objects, which I think is rather nice.</p>\n"
},
{
"answer_id": 435851,
"author": "Andrea Balducci",
"author_id": 54215,
"author_profile": "https://Stackoverflow.com/users/54215",
"pm_score": 7,
"selected": false,
"text": "<p>HtmlHelper adds an hidden input to notify the controller about Unchecked status.\nSo to have the correct checked status:</p>\n\n<pre><code>bool bChecked = form[key].Contains(\"true\");\n</code></pre>\n"
},
{
"answer_id": 479205,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": false,
"text": "<p>You should also use <code><label for=\"checkbox1\">Checkbox 1</label></code> because then people can click on the label text as well as the checkbox itself. Its also easier to style and at least in IE it will be highlighted when you tab through the page's controls.</p>\n\n<pre><code><%= Html.CheckBox(\"cbNewColors\", true) %><label for=\"cbNewColors\">New colors</label>\n</code></pre>\n\n<p>This is not just a 'oh I could do it' thing. Its a significant user experience enhancement. Even if not all users know they can click on the label many will. </p>\n"
},
{
"answer_id": 479220,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": false,
"text": "<p>In case you're wondering WHY they put a hidden field in with the same name as the checkbox the reason is as follows :</p>\n\n<p>Comment from the sourcecode MVCBetaSource\\MVC\\src\\MvcFutures\\Mvc\\<b>ButtonsAndLinkExtensions.cs</b></p>\n\n<blockquote>\n <p>Render an additional <code><input\n type=\"hidden\".../></code> for checkboxes.\n This addresses scenarios where\n unchecked checkboxes are not sent in\n the request. Sending a hidden input\n makes it possible to know that the\n checkbox was present on the page when\n the request was submitted.</p>\n</blockquote>\n\n<p>I guess behind the scenes they need to know this for binding to parameters on the controller action methods. You could then have a tri-state boolean I suppose (bound to a nullable bool parameter). I've not tried it but I'm hoping thats what they did.</p>\n"
},
{
"answer_id": 2085580,
"author": "Farhan Zia",
"author_id": 123008,
"author_profile": "https://Stackoverflow.com/users/123008",
"pm_score": 2,
"selected": false,
"text": "<p>This issue is happening in the release 1.0 as well. Html.Checkbox() causes another hidden field to be added with the same name/id as of your original checkbox. And as I was trying loading up a checkbox array using document.GetElemtentsByName(), you can guess how things were getting messed up. It's a bizarre.</p>\n"
},
{
"answer_id": 2484678,
"author": "Fluffy",
"author_id": 298157,
"author_profile": "https://Stackoverflow.com/users/298157",
"pm_score": 3,
"selected": false,
"text": "<p>They appear to be opting to read the first value only, so this is \"true\" when the checkbox is checked, and \"false\" when only the hidden value is included. This is easily fetched with code like this:</p>\n\n<pre><code>model.Property = collection[\"ElementId\"].ToLower().StartsWith(\"true\");\n</code></pre>\n"
},
{
"answer_id": 2493106,
"author": "Darcy",
"author_id": 277140,
"author_profile": "https://Stackoverflow.com/users/277140",
"pm_score": 3,
"selected": false,
"text": "<p>I'd also like to point out that you can name each checkbox a different name, and have that name part of the actionresults parameters.</p>\n\n<p>Example,</p>\n\n<p>View: </p>\n\n<pre><code> <%= Html.CheckBox(\"Rs232CheckBox\", false, new { @id = \"rs232\" })%>RS-232\n\n <%= Html.CheckBox(\"Rs422CheckBox\", false, new { @id = \"rs422\" })%>RS-422\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>public ActionResults MyAction(bool Rs232CheckBox, bool Rs422CheckBox) {\n ...\n}\n</code></pre>\n\n<p>The values from the view are passed to the action since the names are the same.</p>\n\n<p>I know this solution isn't ideal for your project, but I thought I'd throw the idea out there.</p>\n"
},
{
"answer_id": 2975516,
"author": "nautic20",
"author_id": 358604,
"author_profile": "https://Stackoverflow.com/users/358604",
"pm_score": 3,
"selected": false,
"text": "<p>@Dylan Beattie Great Find!!! I Thank you much. To expand even further, this technique also works perfect with the View Model approach. MVC is so cool, it's smart enough to bind an array of Guids to a property by the same name of the Model object bound to the View. Example:</p>\n\n<p>ViewModel:</p>\n\n<pre><code>public class SampleViewModel\n{\n public IList<SampleObject> SampleObjectList { get; set; }\n public Guid[] SelectedObjectIds { get; set; }\n\n public class SampleObject\n {\n public Guid Id { get; set; }\n public string Name { get; set; }\n }\n}\n</code></pre>\n\n<p>View:</p>\n\n<pre><code><asp:Content ID=\"Content2\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n<h2>Sample View</h2>\n<table>\n <thead> \n <tr>\n <th>Checked</th>\n <th>Object Name</th>\n </tr>\n </thead> \n<% using (Html.BeginForm()) %>\n<%{%> \n <tbody>\n <% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n <% } %>\n </tbody>\n</table>\n<input type=\"submit\" value=\"Submit\" />\n<%}%> \n</code></pre>\n\n<p></p>\n\n<p>Controller:</p>\n\n<pre><code> [AcceptVerbs(HttpVerbs.Get)]\n public ActionResult SampleView(Guid id)\n {\n //Object to pass any input objects to the View Model Builder \n BuilderIO viewModelBuilderInput = new BuilderIO();\n\n //The View Model Builder is a conglomerate of repositories and methods used to Construct a View Model out of Business Objects\n SampleViewModel viewModel = sampleViewModelBuilder.Build(viewModelBuilderInput);\n\n return View(\"SampleView\", viewModel);\n }\n\n [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult SampleView(SampleViewModel viewModel)\n {\n // The array of Guids successfully bound to the SelectedObjectIds property of the View Model!\n return View();\n }\n</code></pre>\n\n<p>Anyone familiar with the View Model philosophy will rejoice, this works like a Champ!</p>\n"
},
{
"answer_id": 3087936,
"author": "bluwater2001",
"author_id": 175111,
"author_profile": "https://Stackoverflow.com/users/175111",
"pm_score": 3,
"selected": false,
"text": "<pre><code><input type = \"checkbox\" name = \"checkbox1\" /> <label> Check to say hi.</label>\n</code></pre>\n\n<p>From the Controller:</p>\n\n<pre><code> [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult Index(FormCollection fc)\n {\n\n var s = fc[\"checkbox1\"];\n\n if (s == \"on\")\n {\n string x = \"Hi\";\n }\n }\n</code></pre>\n"
},
{
"answer_id": 3998715,
"author": "Jeroen",
"author_id": 484412,
"author_profile": "https://Stackoverflow.com/users/484412",
"pm_score": 2,
"selected": false,
"text": "<p>this is what i did to loose the double values when using the Html.CheckBox(...</p>\n\n<pre><code>Replace(\"true,false\",\"true\").Split(',')\n</code></pre>\n\n<p>with 4 boxes checked, unchecked, unchecked, checked it turns\ntrue,false,false,false,true,false\ninto \ntrue,false,false,true. \njust what i needed</p>\n"
},
{
"answer_id": 4159141,
"author": "Skadoosh",
"author_id": 268730,
"author_profile": "https://Stackoverflow.com/users/268730",
"pm_score": 0,
"selected": false,
"text": "<p>How about something like this?</p>\n\n<pre><code>bool isChecked = false;\nif (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)\n ModelState.AddModelError(”chkHuman”, “Nice try.”);\n</code></pre>\n"
},
{
"answer_id": 4553251,
"author": "pawlom84",
"author_id": 557001,
"author_profile": "https://Stackoverflow.com/users/557001",
"pm_score": 0,
"selected": false,
"text": "<p>My solution is:</p>\n\n<pre><code><input type=\"checkbox\" id=\"IsNew-checkbox\" checked=\"checked\" /> \n<input type=\"hidden\" id=\"IsNew\" name=\"IsNew\" value=\"true\" /> \n<script language=\"javascript\" type=\"text/javascript\" > \n $('#IsNew-checkbox').click(function () { \n if ($('#IsNew-checkbox').is(':checked')) { \n $('#IsNew').val('true'); \n } else { \n $('#IsNew').val('false'); \n } \n }); \n</script> \n</code></pre>\n\n<p>More you can find here:\n<a href=\"http://www.blog.mieten.pl/2010/12/asp-net-mvc-custom-checkbox-as-solution-of-string-was-not-recognized-as-a-valid-boolean/\" rel=\"nofollow\">http://www.blog.mieten.pl/2010/12/asp-net-mvc-custom-checkbox-as-solution-of-string-was-not-recognized-as-a-valid-boolean/</a></p>\n"
},
{
"answer_id": 5737367,
"author": "eyesnz",
"author_id": 142413,
"author_profile": "https://Stackoverflow.com/users/142413",
"pm_score": 0,
"selected": false,
"text": "<p>When using the checkbox HtmlHelper, I much prefer to work with the posted checkbox form data as an array. I don't really know why, I know the other methods work, but I think I just prefer to treat comma separated strings as an array as much as possible.</p>\n\n<p>So doing a 'checked' or true test would be:</p>\n\n<pre><code>//looking for [true],[false]\nbool isChecked = form.GetValues(key).Contains(\"true\"); \n</code></pre>\n\n<p>Doing a false check would be:</p>\n\n<pre><code>//looking for [false],[false] or [false]\nbool isNotChecked = !form.GetValues(key).Contains(\"true\"); \n</code></pre>\n\n<p>The main difference is to use <code>GetValues</code> as this returns as an array.</p>\n"
},
{
"answer_id": 7013596,
"author": "doronAv",
"author_id": 888237,
"author_profile": "https://Stackoverflow.com/users/888237",
"pm_score": 0,
"selected": false,
"text": "<p>Just do this on <code>$(document).ready</code> : </p>\n\n<pre><code>$('input:hidden').each(function(el) {\n var that = $(this)[0];\n if(that.id.length < 1 ) {\n\n console.log(that.id);\n that.parentElement.removeChild(that);\n\n }\n});\n</code></pre>\n"
},
{
"answer_id": 7782174,
"author": "Shawn Mclean",
"author_id": 400861,
"author_profile": "https://Stackoverflow.com/users/400861",
"pm_score": 5,
"selected": false,
"text": "<p>I'm surprised none of these answers used the built in MVC features for this.</p>\n\n<p>I wrote a blog post about this <a href=\"http://shawnmclean.com/asp-net-mvc-multiple-check-boxes-in-an-array-or-list/\" rel=\"nofollow\">here</a>, which even actually links the labels to the checkbox. I used the <em>EditorTemplate</em> folder to accomplish this in a clean and modular way.</p>\n\n<p>You will simply end up with a new file in the EditorTemplate folder that looks like this:</p>\n\n<pre><code>@model SampleObject\n\[email protected](m => m.IsChecked)\[email protected](m => m.Id)\[email protected](m => m.IsChecked, Model.Id)\n</code></pre>\n\n<p>in your actual view, there will be no need to loop this, simply 1 line of code:</p>\n\n<pre><code>@Html.EditorFor(x => ViewData.Model)\n</code></pre>\n\n<p>Visit my <a href=\"http://shawnmclean.com/asp-net-mvc-multiple-check-boxes-in-an-array-or-list/\" rel=\"nofollow\">blog post</a> for more details.</p>\n"
},
{
"answer_id": 8745716,
"author": "kk-dev11",
"author_id": 1076915,
"author_profile": "https://Stackoverflow.com/users/1076915",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way to do is so...</p>\n\n<p>You set the name and value.</p>\n\n<p><code><input type=\"checkbox\" name=\"selectedProducts\" value=\"@item.ProductId\" />@item.Name</code></p>\n\n<p>Then on submitting grab the values of checkboxes and save in an int array.\nthen the appropriate LinQ Function. That's it..</p>\n\n<pre><code>[HttpPost]\n public ActionResult Checkbox(int[] selectedObjects)\n {\n var selected = from x in selectedObjects\n from y in db\n where y.ObjectId == x\n select y; \n\n return View(selected);\n }\n</code></pre>\n"
},
{
"answer_id": 10710496,
"author": "BraveNewMath",
"author_id": 551811,
"author_profile": "https://Stackoverflow.com/users/551811",
"pm_score": 2,
"selected": false,
"text": "<p>From what I can gather, the model doesn't want to guess whether checked = true or false, I got around this by setting a value attribute on the checkbox element with jQuery before submitting the form like this:</p>\n\n<pre><code> $('input[type=\"checkbox\"]').each(function () {\n $(this).attr('value', $(this).is(':checked'));\n }); \n</code></pre>\n\n<p>This way, you don't need a hidden element just to store the value of the checkbox.</p>\n"
},
{
"answer_id": 11042576,
"author": "Dan VanWinkle",
"author_id": 412339,
"author_profile": "https://Stackoverflow.com/users/412339",
"pm_score": 2,
"selected": false,
"text": "<p>I know that this question was written when MVC3 wasn't out, but for anyone who comes to this question and are using MVC3, you may want the \"correct\" way to do this.</p>\n\n<p>While I think that doing the whole</p>\n\n<pre><code>Contains(\"true\");\n</code></pre>\n\n<p>thing is great and clean, and works on all MVC versions, the problem is that it doesn't take culture into account (as if it really matters in the case of a bool).</p>\n\n<p>The \"correct\" way to figure out the value of a bool, at least in MVC3, is to use the ValueProvider.</p>\n\n<pre><code>var value = (bool)ValueProvider.GetValue(\"key\").ConvertTo(typeof(bool));\n</code></pre>\n\n<p>I do this in one of my client's sites when I edit permissions:</p>\n\n<pre><code>var allPermissionsBase = Request.Params.AllKeys.Where(x => x.Contains(\"permission_\")).ToList();\nvar allPermissions = new List<KeyValuePair<int, bool>>();\n\nforeach (var key in allPermissionsBase)\n{\n // Try to parse the key as int\n int keyAsInt;\n int.TryParse(key.Replace(\"permission_\", \"\"), out keyAsInt);\n\n // Try to get the value as bool\n var value = (bool)ValueProvider.GetValue(key).ConvertTo(typeof(bool));\n}\n</code></pre>\n\n<p>Now, the beauty of this is you can use this with just about any simple type, and it will even be correct based on the Culture (think money, decimals, etc).</p>\n\n<p>The ValueProvider is what is used when you form your Actions like this:</p>\n\n<pre><code>public ActionResult UpdatePermissions(bool permission_1, bool permission_2)\n</code></pre>\n\n<p>but when you are trying to dynamically build these lists and check the values, you will never know the Id at compile time, so you have to process them on the fly.</p>\n"
},
{
"answer_id": 16054941,
"author": "treborian",
"author_id": 2289733,
"author_profile": "https://Stackoverflow.com/users/2289733",
"pm_score": 0,
"selected": false,
"text": "<p>I had nearly the same Problem but the return Value of my Controller was blocked with other Values.</p>\n\n<p>Found a simple Solution but it seems a bit rough.</p>\n\n<p>Try to type <code>Viewbag.</code> in your Controller and now you give it a name like <code>Viewbag.Checkbool</code></p>\n\n<p>Now switch to the View and try this <code>@Viewbag.Checkbool</code> with this you will get the value out of the Controller.</p>\n\n<p>My Controller Parameters look like this:</p>\n\n<pre><code>public ActionResult Anzeigen(int productid = 90, bool islive = true)\n</code></pre>\n\n<p>and my Checkbox will update like this:</p>\n\n<pre><code><input id=\"isLive\" type=\"checkbox\" checked=\"@ViewBag.Value\" ONCLICK=\"window.location.href = '/MixCategory/Anzeigen?isLive=' + isLive.checked.toString()\" />\n</code></pre>\n"
},
{
"answer_id": 22028124,
"author": "Ravi Ram",
"author_id": 665387,
"author_profile": "https://Stackoverflow.com/users/665387",
"pm_score": 0,
"selected": false,
"text": "<p>Using @mmacaulay , I came up with this for bool:</p>\n\n<pre><code>// MVC Work around for checkboxes.\nbool active = (Request.Form[\"active\"] == \"on\");\n</code></pre>\n\n<p>If checked\nactive = true</p>\n\n<p>If unchecked\nactive = false</p>\n"
},
{
"answer_id": 22331632,
"author": "ChinaHelloWorld",
"author_id": 3001024,
"author_profile": "https://Stackoverflow.com/users/3001024",
"pm_score": 2,
"selected": false,
"text": "<p>Same as nautic20's answer, just simply use MVC default model binding checkbox list with same name as a collection property of string/int/enum in ViewModel. That is it.</p>\n\n<p>But one issue need to point out. In each checkbox component, you should not put \"Id\" in it which will affect MVC model binding.</p>\n\n<p>Following code will work for model binding:</p>\n\n<pre><code> <% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n <% } %>\n</code></pre>\n\n<p>Following codes will not binding to model (difference here is it assigned id for each checkbox)</p>\n\n<pre><code><% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" id=\"[some unique key]\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n<% } %>\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Caution: This question is over nine years old!
----------------------------------------------
Your best option is to search for newer questions, or to search the answers below looking for your specific version of MVC, as many answers here are obsolete now.
If you do find an answer that works for your version, please make sure the answer contains the version of MVC you are using.
(The original question starts below)
---
This seems a bit bizarre to me, but as far as I can tell, this is how you do it.
I have a collection of objects, and I want users to select one or more of them. This says to me "form with checkboxes." My objects don't have any concept of "selected" (they're rudimentary POCO's formed by deserializing a wcf call). So, I do the following:
```
public class SampleObject{
public Guid Id {get;set;}
public string Name {get;set;}
}
```
In the view:
```
<%
using (Html.BeginForm())
{
%>
<%foreach (var o in ViewData.Model) {%>
<%=Html.CheckBox(o.Id)%> <%= o.Name %>
<%}%>
<input type="submit" value="Submit" />
<%}%>
```
And, in the controller, this is the only way I can see to figure out what objects the user checked:
```
public ActionResult ThisLooksWeird(FormCollection result)
{
var winnars = from x in result.AllKeys
where result[x] != "false"
select x;
// yadda
}
```
Its freaky in the first place, and secondly, for those items the user checked, the FormCollection lists its value as "true false" rather than just true.
Obviously, I'm missing something. I think this is built with the idea in mind that the objects in the collection that are acted upon within the html form are updated using `UpdateModel()` or through a ModelBinder.
But my objects aren't set up for this; does that mean that this is the only way? Is there another way to do it?
|
Html.CheckBox is doing something weird - if you view source on the resulting page, you'll see there's an `<input type="hidden" />` being generated alongside each checkbox, which explains the "true false" values you're seeing for each form element.
Try this, which definitely works on ASP.NET MVC Beta because I've just tried it.
Put this in the view instead of using Html.CheckBox():
```
<% using (Html.BeginForm("ShowData", "Home")) { %>
<% foreach (var o in ViewData.Model) { %>
<input type="checkbox" name="selectedObjects" value="<%=o.Id%>">
<%= o.Name %>
<%}%>
<input type="submit" value="Submit" />
<%}%>
```
Your checkboxes are all called `selectedObjects`, and the `value` of each checkbox is the GUID of the corresponding object.
Then post to the following controller action (or something similar that does something useful instead of Response.Write())
```
public ActionResult ShowData(Guid[] selectedObjects) {
foreach (Guid guid in selectedObjects) {
Response.Write(guid.ToString());
}
Response.End();
return (new EmptyResult());
}
```
This example will just write the GUIDs of the boxes you checked; ASP.NET MVC maps the GUID values of the selected checkboxes into the `Guid[] selectedObjects` parameter for you, and even parses the strings from the Request.Form collection into instantied GUID objects, which I think is rather nice.
|
220,021 |
<p>I am trying to use log4net in an ASP.NET application with Visual Studio 2005. I have declared an instance of the logger like so:</p>
<pre><code>Private Shared ReadOnly log As ILog = LogManager.GetLogger("")
</code></pre>
<p>I am trying to use it in the following manner:</p>
<pre><code>If log.IsDebugEnabled Then
log.Debug("Integration Services Constructed")
End If
</code></pre>
<p>Here is my configuration:</p>
<pre class="lang-xml prettyprint-override"><code><log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="..\\logs\\logfile.log"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="1MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
</code></pre>
<p>Unfortunately, <code>log.IsDebugEnabled</code> is always false. <br /> How do I configure log4net so that I can log only debug messages?</p>
|
[
{
"answer_id": 220034,
"author": "Anson Smith",
"author_id": 28685,
"author_profile": "https://Stackoverflow.com/users/28685",
"pm_score": 6,
"selected": true,
"text": "<p>Before calling LogManager.GetLogger(\"\")</p>\n\n<p>You have to call log4net.Config.XmlConfigurator.Configure(); \nIn an ASP.NET app you probably want to put this call in Application_Start </p>\n"
},
{
"answer_id": 220037,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, do it like Anson said. Also, if you are calling Configure in a class library you can do that by adding an attribute to your class:</p>\n\n<pre><code>[assembly: XmlConfigurator(Watch = true)]\n</code></pre>\n\n<p>and if you're using <code>log4net.config</code> file, use it like that instead:</p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = \"log4net.config\", Watch = true)]\n</code></pre>\n"
},
{
"answer_id": 13671118,
"author": "Anantha",
"author_id": 1066661,
"author_profile": "https://Stackoverflow.com/users/1066661",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using a separate configuration file for log4net, do this: after following all the other setup instructions, make sure that u right click on the file in the visual studio solution explorer, select properties, expand the \"Advanced\" option group, set the \"Copy To Output Directory\" value as \"Copy always\". That will do the magic... :) cheers!!</p>\n"
},
{
"answer_id": 21675765,
"author": "Revan",
"author_id": 2879268,
"author_profile": "https://Stackoverflow.com/users/2879268",
"pm_score": 0,
"selected": false,
"text": "<p>Use this in any method before you use log :</p>\n\n<p>log4net.Config.XmlConfigurator.Configure();</p>\n\n<p>In App.Config ,the settings should be :</p>\n\n<pre><code><root>\n <level value=\"ALL\" />\n <appender-ref ref=\"AppenderName\" />\n </root>\n</code></pre>\n"
},
{
"answer_id": 22522189,
"author": "developer9",
"author_id": 1079542,
"author_profile": "https://Stackoverflow.com/users/1079542",
"pm_score": 1,
"selected": false,
"text": "<p>VB.NET - </p>\n\n<pre><code><Assembly: log4net.Config.XmlConfigurator(Watch:=True)> \n</code></pre>\n"
},
{
"answer_id": 26756171,
"author": "Protector one",
"author_id": 125938,
"author_profile": "https://Stackoverflow.com/users/125938",
"pm_score": 2,
"selected": false,
"text": "<p>If you are setting log4net up in code rather than in a config file, you can call <code>log4net.Config.BasicConfigurator.Configure</code> before <code>GetLogger</code>.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19977/"
] |
I am trying to use log4net in an ASP.NET application with Visual Studio 2005. I have declared an instance of the logger like so:
```
Private Shared ReadOnly log As ILog = LogManager.GetLogger("")
```
I am trying to use it in the following manner:
```
If log.IsDebugEnabled Then
log.Debug("Integration Services Constructed")
End If
```
Here is my configuration:
```xml
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="..\\logs\\logfile.log"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="1MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="DEBUG" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
</log4net>
```
Unfortunately, `log.IsDebugEnabled` is always false.
How do I configure log4net so that I can log only debug messages?
|
Before calling LogManager.GetLogger("")
You have to call log4net.Config.XmlConfigurator.Configure();
In an ASP.NET app you probably want to put this call in Application\_Start
|
220,031 |
<p>Previously, settings for deployments of an ASP.NET application were stored in multiple configuration files under the Web.config config sections using a KEY/VALUE format. We are moving these 'site module options' to the database for a variety of reasons. </p>
<p>Here are the two options we are mulling over at the moment:
<br> 1. A single table with the applicationId, moduleId, and key as a Primary Key with a Value field.
<br><strong>Pros:</strong>
<br> - This mimics the file access.
<br> - It is easy to select entire sections to cache in hashtables/value objects.
<br><strong>Cons:</strong>
<br> - More difficult to update since each key needs to be updated individually.
<br> - Must cast each value if it's not a string. </p>
<p><br> 2. Individual tables for each section which separate stored procedures, classes, etc.
<br><strong>Pros:</strong>
<br> - Data is guaranteed to be consistent since the column and object types are typed.
<br> - Updating is done in one trip to the database through an explicit interface.
<br><strong>Cons:</strong>
<br> - Must change the application interface to access the
<br> - Must update the objects, database tables, and stored procedures each time something changes. </p>
<p>Do either of these sound like good ideas or is there another way I may have overlooked? </p>
|
[
{
"answer_id": 223450,
"author": "Brad Patton",
"author_id": 27989,
"author_profile": "https://Stackoverflow.com/users/27989",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand what you are proposing correctly. I would do the first approach. It leverages what you have already built. I would use the hash tables for caching inside of wrapper classes that can provide stongly typed interfaces for the properties.</p>\n\n<p>For example:</p>\n\n<pre><code>/// <summary>\n/// The time passwords expire, in days, if ExpirePasswords is on\n/// </summary>\npublic int PasswordExpirationDays {\n get { return ParseUtils.ParseInt(this[\"PasswordExpirationDays\"], PW_MAX_AGE);}\n set { this[\"PasswordExpirationDays\"] = value.ToString(); }\n}\n</code></pre>\n"
},
{
"answer_id": 226357,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to group like settings together into their own classes, and then use XML serialization/deserialization to store and retrieve instances of these settings classes to and from the database.</p>\n\n<p>This doesn't specifically provide advantages above and beyond a key/value pair other than you don't have to yourself perform any type conversions (this is done behind the scenes as part of the serialization/deserialization process - so it still does happen). I find this sort of approach ideally suited for solving configuration issues such as you are facing. Its clean, quick to implement, very easy to expand, and very easy to test. You don't have to spend time creating a feature rich API to get at your settings, especially if you've already got your configuration subclassed out.</p>\n\n<p>Also in a pinch you can direct your settings to come from database tables or the file system without altering your serialization/deserialization code (this is very nice during development).</p>\n\n<p>Finally if you are using SQL Server (and likely Oracle, though I have no experience with Oracle and XML) and you think about the design of your settings class up front, you can define an XML schema for your serialized configuration object instances so you can use XQuery to quickly get a configuration setting's value without having to fully deserialize.</p>\n"
},
{
"answer_id": 1150704,
"author": "JBrooks",
"author_id": 136059,
"author_profile": "https://Stackoverflow.com/users/136059",
"pm_score": 0,
"selected": false,
"text": "<p>This is how we did it - <a href=\"http://blog.digitaltools.com/post/2009/02/25/Moving-AppSettings-to-a-Database-Table.aspx\" rel=\"nofollow noreferrer\">Click Here</a> </p>\n\n<p>We were more concerned with the fact that different environments (Dev, Test, QA and Prod), had different values for the same key. Now we have only 2 keys in a WebEnvironment.Config file that never gets promoted. The first key is which environment are you in and the second one is the connection string.</p>\n\n<p>The table gets loaded up once to a dictionary and then we can use it in our code like this:</p>\n\n<pre><code> cApp.AppSettings[\"MySetting\"];\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Previously, settings for deployments of an ASP.NET application were stored in multiple configuration files under the Web.config config sections using a KEY/VALUE format. We are moving these 'site module options' to the database for a variety of reasons.
Here are the two options we are mulling over at the moment:
1. A single table with the applicationId, moduleId, and key as a Primary Key with a Value field.
**Pros:**
- This mimics the file access.
- It is easy to select entire sections to cache in hashtables/value objects.
**Cons:**
- More difficult to update since each key needs to be updated individually.
- Must cast each value if it's not a string.
2. Individual tables for each section which separate stored procedures, classes, etc.
**Pros:**
- Data is guaranteed to be consistent since the column and object types are typed.
- Updating is done in one trip to the database through an explicit interface.
**Cons:**
- Must change the application interface to access the
- Must update the objects, database tables, and stored procedures each time something changes.
Do either of these sound like good ideas or is there another way I may have overlooked?
|
If I understand what you are proposing correctly. I would do the first approach. It leverages what you have already built. I would use the hash tables for caching inside of wrapper classes that can provide stongly typed interfaces for the properties.
For example:
```
/// <summary>
/// The time passwords expire, in days, if ExpirePasswords is on
/// </summary>
public int PasswordExpirationDays {
get { return ParseUtils.ParseInt(this["PasswordExpirationDays"], PW_MAX_AGE);}
set { this["PasswordExpirationDays"] = value.ToString(); }
}
```
|
220,051 |
<p>I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!</p>
|
[
{
"answer_id": 220072,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 3,
"selected": true,
"text": "<p>You can read a file into an array of lines and do all the splitting with:</p>\n\n<pre><code>$lines = file(\"filename\");\nforeach($lines as $line) {\n $parts = explode(\"|\", $line);\n // do the database inserts here\n}\n</code></pre>\n\n<p>If you already have all the text in a variable as you said (e.g., with something like file_get_contents() ), you can explode on \\n first and then do the same foreach statement as above.</p>\n"
},
{
"answer_id": 220078,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 0,
"selected": false,
"text": "<p>If the file is small, you can use <a href=\"http://www.php.net/file\" rel=\"nofollow noreferrer\">file() t</a>o read it into an array, one line per element.</p>\n\n<p>Failing that, read the file in loop using <a href=\"http://www.php.net/fgets\" rel=\"nofollow noreferrer\">fgets()</a></p>\n\n<pre><code>$handle = fopen(\"/tmp/inputfile.txt\", \"r\");\nwhile (!feof($handle)) {\n $buffer = fgets($handle, 4096);\n echo $buffer;\n}\nfclose($handle);\n</code></pre>\n"
},
{
"answer_id": 220081,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 2,
"selected": false,
"text": "<p>If you are reading out of your textarea post, you can use the explode function using the newline character as your separator to get each \"line\" in the variable as a new element of an array, then you can do explode on your array elements.</p>\n\n<p>i.e. </p>\n\n<pre><code>$sometext = \"balh | balh blah| more blah \\n extra balh |some blah |this blah\";\n\n$lines = explode(\"\\n\", $sometext);\nforeach($lines as $oneLine)\n{\n $lineElements[] = explode(\"|\", $oneLine);\n}\n</code></pre>\n\n<p>then you have a 2d array of your elems.</p>\n\n<p>If you are reading out of a file, you can simply use the file function documented here:</p>\n\n<p><a href=\"http://us2.php.net/manual/en/function.file.php\" rel=\"nofollow noreferrer\">http://us2.php.net/manual/en/function.file.php</a></p>\n\n<p>to get each line of the file as an element of an array.</p>\n"
},
{
"answer_id": 220086,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 0,
"selected": false,
"text": "<p>You can use explode to get both:</p>\n\n<pre><code>$myFile = \"File.txt\";\n$fh = fopen($myFile, 'r');\n$data = fread($fh);\nfclose($fh);\n$newLines = explode(\"\\n\",$data);\n\nforeach($newLines as $s)\n{\n $parsed = explode(\"|\",$s);\n foreach($parsed as $item)\n {\n // do your db load here\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10914453,
"author": "HenryHayes",
"author_id": 1439760,
"author_profile": "https://Stackoverflow.com/users/1439760",
"pm_score": 1,
"selected": false,
"text": "<p>There is a ready-built PHP parsing library that can auto-detect the CSV format.</p>\n\n<p>Example:</p>\n\n<pre><code>$reader = new Dfp_Datafeed_File_Reader();\n$reader->setLocation('test.csv');\n\nforeach ($reader AS $record) {\n print_r($record);\n}\n</code></pre>\n\n<p>It's available to download <a href=\"https://github.com/henryhayes/dfp\" rel=\"nofollow\">here</a>, and there's some documentation <a href=\"http://code.google.com/p/datafeed/wiki/ExampleUsage\" rel=\"nofollow\">here</a>.</p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!
|
You can read a file into an array of lines and do all the splitting with:
```
$lines = file("filename");
foreach($lines as $line) {
$parts = explode("|", $line);
// do the database inserts here
}
```
If you already have all the text in a variable as you said (e.g., with something like file\_get\_contents() ), you can explode on \n first and then do the same foreach statement as above.
|
220,097 |
<p>I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)</p>
|
[
{
"answer_id": 220141,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "<p>There's <a href=\"http://www.codeproject.com/KB/shell/shellid3tagreader.aspx\" rel=\"noreferrer\">a CodeProject article</a> for an ID3 reader. And a <a href=\"http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=160880&page=1\" rel=\"noreferrer\">thread at kixtart.org</a> that has more information for other properties. Basically, you need to call the <a href=\"http://msdn.microsoft.com/en-us/library/bb787870(VS.85).aspx\" rel=\"noreferrer\"><code>GetDetailsOf()</code> method</a> on the <em>folder</em> shell object for <code>shell32.dll</code>.</p>\n"
},
{
"answer_id": 220193,
"author": "mockobject",
"author_id": 29649,
"author_profile": "https://Stackoverflow.com/users/29649",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure what types of files you are trying to write the properties for but <a href=\"http://github.com/mono/taglib-sharp\" rel=\"nofollow noreferrer\">taglib-sharp</a> is an excellent open source tagging library that wraps up all this functionality nicely. It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.</p>\n\n<p><strong>EDIT:</strong> I've updated the link to taglib sharp. The old link no longer worked.</p>\n\n<p><strong>EDIT:</strong> Updated the link once again per kzu's comment.</p>\n"
},
{
"answer_id": 325659,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 5,
"selected": false,
"text": "<p>This sample in VB.NET reads all extended properties:</p>\n\n<pre><code>Sub Main()\n Dim arrHeaders(35)\n\n Dim shell As New Shell32.Shell\n Dim objFolder As Shell32.Folder\n\n objFolder = shell.NameSpace(\"C:\\tmp\")\n\n For i = 0 To 34\n arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)\n Next\n For Each strFileName In objfolder.Items\n For i = 0 To 34\n Console.WriteLine(i & vbTab & arrHeaders(i) & \": \" & objfolder.GetDetailsOf(strFileName, i))\n Next\n Next\n\n End Sub\n</code></pre>\n\n<p>You have to add a reference to <em>Microsoft Shell Controls and Automation</em> from the <em>COM</em> tab of the <em>References</em> dialog.</p>\n"
},
{
"answer_id": 2096315,
"author": "csharptest.net",
"author_id": 164392,
"author_profile": "https://Stackoverflow.com/users/164392",
"pm_score": 8,
"selected": true,
"text": "<p>For those of not crazy about VB, here it is in c#:</p>\n\n<p>Note, you have to add a reference to <em>Microsoft Shell Controls and Automation</em> from the COM tab of the References dialog.</p>\n\n<pre><code>public static void Main(string[] args)\n{\n List<string> arrHeaders = new List<string>();\n\n Shell32.Shell shell = new Shell32.Shell();\n Shell32.Folder objFolder;\n\n objFolder = shell.NameSpace(@\"C:\\temp\\testprop\");\n\n for( int i = 0; i < short.MaxValue; i++ )\n {\n string header = objFolder.GetDetailsOf(null, i);\n if (String.IsNullOrEmpty(header))\n break;\n arrHeaders.Add(header);\n }\n\n foreach(Shell32.FolderItem2 item in objFolder.Items())\n {\n for (int i = 0; i < arrHeaders.Count; i++)\n {\n Console.WriteLine(\n $\"{i}\\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3547482,
"author": "JERKER",
"author_id": 344887,
"author_profile": "https://Stackoverflow.com/users/344887",
"pm_score": 3,
"selected": false,
"text": "<p>Thank you guys for this thread! It helped me when I wanted to figure out an exe's file version. However, I needed to figure out the last bit myself of what is called Extended Properties.</p>\n\n<p>If you open properties of an exe (or dll) file in Windows Explorer, you get a Version tab, and a view of Extended Properties of that file. I wanted to access one of those values.</p>\n\n<p>The solution to this is the property indexer FolderItem.ExtendedProperty and if you drop all spaces in the property's name, you'll get the value. E.g. File Version goes FileVersion, and there you have it.</p>\n\n<p>Hope this helps anyone else, just thought I'd add this info to this thread. Cheers!</p>\n"
},
{
"answer_id": 15111611,
"author": "RajeshKdev",
"author_id": 900307,
"author_profile": "https://Stackoverflow.com/users/900307",
"pm_score": 3,
"selected": false,
"text": "<p><code>GetDetailsOf()</code> Method - Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification. File Properties may vary based on the <code>Windows-OS</code> version.</p>\n\n<pre><code>List<string> arrHeaders = new List<string>();\n\n Shell shell = new ShellClass();\n Folder rFolder = shell.NameSpace(_rootPath);\n FolderItem rFiles = rFolder.ParseName(filename);\n\n for (int i = 0; i < short.MaxValue; i++)\n {\n string value = rFolder.GetDetailsOf(rFiles, i).Trim();\n arrHeaders.Add(value);\n }\n</code></pre>\n"
},
{
"answer_id": 37986932,
"author": "Martin Schneider",
"author_id": 1951524,
"author_profile": "https://Stackoverflow.com/users/1951524",
"pm_score": 5,
"selected": false,
"text": "<h1>Solution 2016</h1>\n<p>Add following NuGet packages to your project:</p>\n<ul>\n<li><code>Microsoft.WindowsAPICodePack-Shell</code> by Microsoft</li>\n<li><code>Microsoft.WindowsAPICodePack-Core</code> by Microsoft</li>\n</ul>\n<h3>Read and Write Properties</h3>\n<pre><code>using Microsoft.WindowsAPICodePack.Shell;\nusing Microsoft.WindowsAPICodePack.Shell.PropertySystem;\n\nstring filePath = @"C:\\temp\\example.docx";\nvar file = ShellFile.FromFilePath(filePath);\n\n// Read and Write:\n\nstring[] oldAuthors = file.Properties.System.Author.Value;\nstring oldTitle = file.Properties.System.Title.Value;\n\nfile.Properties.System.Author.Value = new string[] { "Author #1", "Author #2" };\nfile.Properties.System.Title.Value = "Example Title";\n\n// Alternate way to Write:\n\nShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();\npropertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });\npropertyWriter.Close();\n</code></pre>\n<p><strong>Important:</strong></p>\n<p>The file must be a valid one, created by the specific assigned software. Every file type has specific extended file properties and not all of them are writable.</p>\n<p>If you right-click a file on desktop and cannot edit a property, you wont be able to edit it in code too.</p>\n<p>Example:</p>\n<ul>\n<li>Create txt file on desktop, rename its extension to docx. You can't\nedit its <code>Author</code> or <code>Title</code> property.</li>\n<li>Open it with Word, edit and save\nit. Now you can.</li>\n</ul>\n<p>So just make sure to use some <code>try</code> <code>catch</code></p>\n<p>Further Topic:\n<a href=\"https://learn.microsoft.com/en-us/windows/win32/properties/building-property-handlers\" rel=\"nofollow noreferrer\">Microsoft Docs: Implementing Property Handlers</a></p>\n"
},
{
"answer_id": 46648086,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/3547482/661933\">Jerker's answer </a>is little simpler. Here's sample code which works <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/bb774055(v=vs.85).aspx\" rel=\"nofollow noreferrer\">from MS</a>:</p>\n\n<pre><code>var folder = new Shell().NameSpace(folderPath);\nforeach (FolderItem2 item in folder.Items())\n{\n var company = item.ExtendedProperty(\"Company\");\n var author = item.ExtendedProperty(\"Author\");\n // Etc.\n}\n</code></pre>\n\n<p>For those who can't reference shell32 statically, you can invoke it dynamically like this:</p>\n\n<pre><code>var shellAppType = Type.GetTypeFromProgID(\"Shell.Application\");\ndynamic shellApp = Activator.CreateInstance(shellAppType);\nvar folder = shellApp.NameSpace(folderPath);\nforeach (var item in folder.Items())\n{\n var company = item.ExtendedProperty(\"Company\");\n var author = item.ExtendedProperty(\"Author\");\n // Etc.\n}\n</code></pre>\n"
},
{
"answer_id": 49972293,
"author": "Rohan",
"author_id": 2191900,
"author_profile": "https://Stackoverflow.com/users/2191900",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li>After looking at a number of solutions on this thread and elsewhere\nthe following code was put together. This is only to read a property.</li>\n<li>I could not get the\nShell32.FolderItem2.ExtendedProperty function to work, it is supposed\nto take a string value and return the correct value and type for that\nproperty... this was always null for me and developer reference resources were very thin.</li>\n<li>The <a href=\"https://stackoverflow.com/questions/24081665/windows-api-code-pack-where-is-it\">WindowsApiCodePack</a> seems\nto have been abandoned by Microsoft which brings us the code below.</li>\n</ul>\n\n<p>Use:</p>\n\n<pre><code>string propertyValue = GetExtendedFileProperty(\"c:\\\\temp\\\\FileNameYouWant.ext\",\"PropertyYouWant\");\n</code></pre>\n\n<ol>\n<li>Will return you the value of the extended property you want as a\nstring for the given file and property name.</li>\n<li>Only loops until it found the specified property - not until\nall properties are discovered like some sample code</li>\n<li><p>Will work on Windows versions like Windows server 2008 where you will get the error <a href=\"https://stackoverflow.com/questions/31403956/exception-when-using-shell32-to-get-file-extended-properties\">\"Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'\"</a> if just trying to create the Shell32 Object normally.</p>\n\n<pre><code>public static string GetExtendedFileProperty(string filePath, string propertyName)\n{\n string value = string.Empty;\n string baseFolder = Path.GetDirectoryName(filePath);\n string fileName = Path.GetFileName(filePath);\n\n //Method to load and execute the Shell object for Windows server 8 environment otherwise you get \"Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'\"\n Type shellAppType = Type.GetTypeFromProgID(\"Shell.Application\");\n Object shell = Activator.CreateInstance(shellAppType);\n Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember(\"NameSpace\", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });\n\n //Parsename will find the specific file I'm looking for in the Shell32.Folder object\n Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);\n if (folderitem != null)\n {\n for (int i = 0; i < short.MaxValue; i++)\n {\n //Get the property name for property index i\n string property = shellFolder.GetDetailsOf(null, i);\n\n //Will be empty when all possible properties has been looped through, break out of loop\n if (String.IsNullOrEmpty(property)) break;\n\n //Skip to next property if this is not the specified property\n if (property != propertyName) continue; \n\n //Read value of property\n value = shellFolder.GetDetailsOf(folderitem, i);\n }\n }\n //returns string.Empty if no value was found for the specified property\n return value;\n}\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 57445289,
"author": "pasx",
"author_id": 683319,
"author_profile": "https://Stackoverflow.com/users/683319",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a solution for reading - not writing - the extended properties based on what I found on this page and at <a href=\"http://answers.flyppdevportal.com/MVC/Post/Thread/4a17c71b-ed01-44bd-977a-c8ceb237c538?category=vbgeneral\" rel=\"nofollow noreferrer\">help with shell32 objects</a>.</p>\n\n<p>To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:</p>\n\n<pre><code> var i = 0;\n while (true)\n {\n ...\n if (String.IsNullOrEmpty(header)) break;\n ...\n i++;\n</code></pre>\n\n<p>On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:</p>\n\n<pre><code> private Dictionary<string, string> GetExtendedProperties(string filePath)\n {\n var directory = Path.GetDirectoryName(filePath);\n var shell = new Shell32.Shell();\n var shellFolder = shell.NameSpace(directory);\n var fileName = Path.GetFileName(filePath);\n var folderitem = shellFolder.ParseName(fileName);\n var dictionary = new Dictionary<string, string>();\n var i = -1;\n while (++i < 320)\n {\n var header = shellFolder.GetDetailsOf(null, i);\n if (String.IsNullOrEmpty(header)) continue;\n var value = shellFolder.GetDetailsOf(folderitem, i);\n if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);\n Console.WriteLine(header +\": \" + value);\n }\n Marshal.ReleaseComObject(shell);\n Marshal.ReleaseComObject(shellFolder);\n return dictionary;\n }\n</code></pre>\n\n<p>As mentioned you need to reference the Com assembly Interop.Shell32.</p>\n\n<p>If you get an STA related exception, you will find the solution here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/31403956/exception-when-using-shell32-to-get-file-extended-properties\">Exception when using Shell32 to get File extended properties</a></p>\n\n<p>I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.</p>\n\n<p>BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.</p>\n\n<p>On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc. \n<a href=\"https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-getting-file-properties</a></p>\n\n<p>And finally, I posted <strong>a much better solution that uses WindowsAPICodePack <a href=\"https://stackoverflow.com/questions/19261078/getting-extended-file-properties-in-c-sharp-net\">there</a></strong></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769/"
] |
I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)
|
For those of not crazy about VB, here it is in c#:
Note, you have to add a reference to *Microsoft Shell Controls and Automation* from the COM tab of the References dialog.
```
public static void Main(string[] args)
{
List<string> arrHeaders = new List<string>();
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder objFolder;
objFolder = shell.NameSpace(@"C:\temp\testprop");
for( int i = 0; i < short.MaxValue; i++ )
{
string header = objFolder.GetDetailsOf(null, i);
if (String.IsNullOrEmpty(header))
break;
arrHeaders.Add(header);
}
foreach(Shell32.FolderItem2 item in objFolder.Items())
{
for (int i = 0; i < arrHeaders.Count; i++)
{
Console.WriteLine(
$"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
}
}
}
```
|
220,100 |
<p>How do I enable double-buffering of a control using C# (Windows forms)?</p>
<p>I have a panel control which I am drawing stuff into and also an owner-drawn tab control. Both suffer from flicker, so how can I enable double-buffering?</p>
|
[
{
"answer_id": 220107,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>some info here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form\">How to double buffer .NET controls on a form?</a></p>\n"
},
{
"answer_id": 220166,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 5,
"selected": true,
"text": "<p>In the constructor of your control, set the DoubleBuffered property, and/or ControlStyle appropriately.</p>\n\n<p>For example, I have a simple DoubleBufferedPanel whose constructor is the following:</p>\n\n<pre><code>this.DoubleBuffered = true;\nthis.SetStyle(ControlStyles.UserPaint | \n ControlStyles.AllPaintingInWmPaint |\n ControlStyles.ResizeRedraw |\n ControlStyles.ContainerControl |\n ControlStyles.OptimizedDoubleBuffer |\n ControlStyles.SupportsTransparentBackColor\n , true);\n</code></pre>\n"
},
{
"answer_id": 221272,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": -1,
"selected": false,
"text": "<p>Use the DoubleBuffered property, inherited from the System.Windows.Forms.Control.</p>\n\n<pre><code>System.Windows.Forms.Form myForm = new System.Windows.forms.Form();\nmyForm.DoubleBuffered = true;\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
How do I enable double-buffering of a control using C# (Windows forms)?
I have a panel control which I am drawing stuff into and also an owner-drawn tab control. Both suffer from flicker, so how can I enable double-buffering?
|
In the constructor of your control, set the DoubleBuffered property, and/or ControlStyle appropriately.
For example, I have a simple DoubleBufferedPanel whose constructor is the following:
```
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.ContainerControl |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.SupportsTransparentBackColor
, true);
```
|
220,123 |
<p>I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.</p>
|
[
{
"answer_id": 220148,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 0,
"selected": false,
"text": "<p>A few pieces of information can be gathered without too much trouble:</p>\n\n<ul>\n<li>Use GetDriveType to find the first removeable drive, test if writeable media exists (which will largely rule out CD drives). May also want to look at further strings that are available when you query the drive information via win32.</li>\n<li>Use libusb to see where the first storage class USB device is (will likely be a flash or hard drive)</li>\n<li>This <a href=\"http://bytes.com/forum/thread234006.html\" rel=\"nofollow noreferrer\">C# article</a> points towards win32 disk drive classes you might be able to tap into.</li>\n</ul>\n\n<p>Post your answer here when you find it!</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 220836,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 1,
"selected": false,
"text": "<p>I know your question is tagged Win32, but this is quite simple with .NET:</p>\n\n<pre><code>foreach (IO.DriveInfo drive in IO.DriveInfo.GetDrives()) {\n if ((drive.DriveType == IO.DriveType.Removable)) {\n // this is a removable drive\n }\n}\n</code></pre>\n\n<p>See drive.Name and drive.VolumeLabel for getting the label. You can also get the size, and make an educated guess that it's a USB stick (and a big enough one) -- Removable can mean either Floppy or USB, <a href=\"http://msdn.microsoft.com/en-us/library/system.io.drivetype.aspx\" rel=\"nofollow noreferrer\">according to the docs</a>.</p>\n\n<p>As a side note, from a UI perspective, I'd suggest the first time you find a new drive, present it to the user and ask \"is this the drive you want to use for backups?\". Otherwise, there is a big potential for accidentally wiping out data on a usb key that happened to be plugged in. Nothing destroys the credibility of a backup program like when it destroys your data. :)</p>\n"
},
{
"answer_id": 221048,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use <a href=\"http://msdn.microsoft.com/en-us/library/aa363431.aspx\" rel=\"nofollow noreferrer\">RegisterDeviceNotification</a> function. <a href=\"https://stackoverflow.com/questions/161257/what-languagemethods-to-use-to-listen-to-removeable-drives-in-windows\">Here</a> is some pointers about how to do it. And one more <a href=\"http://www.codeproject.com/KB/system/HwDetect.aspx\" rel=\"nofollow noreferrer\">sample code</a> </p>\n\n<p>You can enumerate all mass storage devices using <a href=\"http://support.microsoft.com/kb/259695\" rel=\"nofollow noreferrer\">this</a> sample. In General look for SetupDiXXX api's. </p>\n\n<p>Please note that taking in consideration dynamic nature of usb devices, using notification mechanism is mandatory IMHO. You might find your self analyzing device that already detached or missing new device that just arrived. </p>\n"
},
{
"answer_id": 223808,
"author": "Stacey Richards",
"author_id": 1142,
"author_profile": "https://Stackoverflow.com/users/1142",
"pm_score": 2,
"selected": true,
"text": "<p>I spent a little time looking around and found a function called SetupDiEnumDeviceInfo which did provide a solution to know whether a hard drive was removable or not but with that information I still can't (yet) map what I find back to a drive letter!</p>\n\n<p>Here's what I have so far (following code creates a dll):</p>\n\n<pre><code>#include \"stdafx.h\"\n#include <setupapi.h>\n#include <devguid.h>\n#include <cfgmgr32.h>\nextern \"C\" __declspec(dllexport) int usb_hard_drives() {\n HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);\n if (hdevinfo == INVALID_HANDLE_VALUE) return -1;\n DWORD MemberIndex = 0;\n SP_DEVINFO_DATA sp_devinfo_data;\n ZeroMemory(&sp_devinfo_data, sizeof(sp_devinfo_data));\n sp_devinfo_data.cbSize = sizeof(sp_devinfo_data);\n int c = 0;\n while (SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &sp_devinfo_data)) {\n DWORD PropertyRegDataType;\n DWORD RequiredSize;\n DWORD PropertyBuffer;\n if (SetupDiGetDeviceRegistryProperty(hdevinfo, &sp_devinfo_data, SPDRP_CAPABILITIES, &PropertyRegDataType, (PBYTE)&PropertyBuffer, sizeof(PropertyBuffer), &RequiredSize)) {\n if (PropertyBuffer && CM_DEVCAP_REMOVABLE == CM_DEVCAP_REMOVABLE) {\n // do something here to identify the drive letter.\n c++;\n }\n } \n MemberIndex++;\n }\n SetupDiDestroyDeviceInfoList(hdevinfo);\n return c;\n}\n</code></pre>\n"
},
{
"answer_id": 12184547,
"author": "Joel",
"author_id": 124220,
"author_profile": "https://Stackoverflow.com/users/124220",
"pm_score": 1,
"selected": false,
"text": "<p>I found a great function in the Win32 API for testing the type of drive.</p>\n\n<pre><code>if( 2 == ::getDriveType( <driveletter> )){\n // its removable \n}\n</code></pre>\n\n<p>Return values of function:</p>\n\n<p>DRIVE_UNKNOWN\n0: The drive type cannot be determined. </p>\n\n<p>DRIVE_NO_ROOT_DIR\n1: The root path is invalid; for example, there is no volume mounted at the specified path. </p>\n\n<p>DRIVE_REMOVABLE\n2: The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader. </p>\n\n<p>DRIVE_FIXED\n3: The drive has fixed media; for example, a hard disk drive or flash drive. </p>\n\n<p>DRIVE_REMOTE\n4: The drive is a remote (network) drive. </p>\n\n<p>DRIVE_CDROM\n5: The drive is a CD-ROM drive.</p>\n\n<p>DRIVE_RAMDISK\n6: The drive is a RAM disk.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa364939(v=vs.85).aspx</a></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
] |
I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.
|
I spent a little time looking around and found a function called SetupDiEnumDeviceInfo which did provide a solution to know whether a hard drive was removable or not but with that information I still can't (yet) map what I find back to a drive letter!
Here's what I have so far (following code creates a dll):
```
#include "stdafx.h"
#include <setupapi.h>
#include <devguid.h>
#include <cfgmgr32.h>
extern "C" __declspec(dllexport) int usb_hard_drives() {
HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);
if (hdevinfo == INVALID_HANDLE_VALUE) return -1;
DWORD MemberIndex = 0;
SP_DEVINFO_DATA sp_devinfo_data;
ZeroMemory(&sp_devinfo_data, sizeof(sp_devinfo_data));
sp_devinfo_data.cbSize = sizeof(sp_devinfo_data);
int c = 0;
while (SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &sp_devinfo_data)) {
DWORD PropertyRegDataType;
DWORD RequiredSize;
DWORD PropertyBuffer;
if (SetupDiGetDeviceRegistryProperty(hdevinfo, &sp_devinfo_data, SPDRP_CAPABILITIES, &PropertyRegDataType, (PBYTE)&PropertyBuffer, sizeof(PropertyBuffer), &RequiredSize)) {
if (PropertyBuffer && CM_DEVCAP_REMOVABLE == CM_DEVCAP_REMOVABLE) {
// do something here to identify the drive letter.
c++;
}
}
MemberIndex++;
}
SetupDiDestroyDeviceInfoList(hdevinfo);
return c;
}
```
|
220,126 |
<p>Let's say I have the following code:</p>
<pre><code>@sites = Site.find(session[:sites]) # will be an array of Site ids
@languages = Language.for_sites(@sites)
</code></pre>
<p>for_sites is a named_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.</p>
<p>Instead of calling the Language object on the second line, I'd ideally like to say </p>
<pre><code>@sites.languages
</code></pre>
<p>and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.</p>
|
[
{
"answer_id": 220504,
"author": "JasonOng",
"author_id": 6048,
"author_profile": "https://Stackoverflow.com/users/6048",
"pm_score": 0,
"selected": false,
"text": "<p>Your instance variable @sites is an Array object and not Site so I don't think named_scope can be used. You can open up Array class to achieve this effect though (yikes)</p>\n\n<pre><code>class Array\n\n def languages\n ...\n end\n\nend\n</code></pre>\n"
},
{
"answer_id": 220593,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>If you added a <code>has_many</code> or <code>has_and_belongs_to_many</code> linking languages to sites, then you could use an include and do something like this:</p>\n\n<pre><code>Site.find( :all, :conditions =>{:id => session[:sites]}, :include => :languages )\n</code></pre>\n\n<p>You can make a named scope to do the :id => session[:sites] thing, eg:</p>\n\n<pre><code>class Site\n named_scope :for_ids, lambda{ |x| {:conditions => {:id => x }\nend\n</code></pre>\n\n<p>and then do</p>\n\n<pre><code>Site.for_ids(session[:sites]).find(:all, :include => :languages)\n</code></pre>\n\n<p>Hope this gives you some ideas</p>\n"
},
{
"answer_id": 221487,
"author": "Andrew",
"author_id": 17408,
"author_profile": "https://Stackoverflow.com/users/17408",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use named_scopes for both?</p>\n\n<pre><code>class Site\n named_scope :sites, lambda{|ids| :conditions => \"id in (#{ids.join(',')})\"}\n named_scope :languages, :include => :languages ... (whatever your named scope does)\nend\n</code></pre>\n\n<p>call:</p>\n\n<pre><code>Site.sites(session[:sites]).languages\n</code></pre>\n\n<p>or, if you want language objects back</p>\n\n<pre><code>Site.sites(session[:sites]).languages.collect{|site| site.languages}.flatten\n</code></pre>\n\n<p>You can also do it directly on the Language object.\nI'm using :joins because Rails 2.1 splits up and :include into two queries which means we can't use sites in the :conditions</p>\n\n<pre><code>class Language\n named_scope :for_sites, lambda{|site_ids| :joins => 'inner join sites on languages.site_id = sites.id' :conditions => \"sites.id in (#{site_ids.join(',')})\"}\nend\n</code></pre>\n\n<p>call:</p>\n\n<pre><code>Language.for_sites(session[:sites])\n</code></pre>\n\n<p>In both examples I've assumed that session[:sites] is completely controlled by you and not subject to SQL injection. If not, make sure you deal with cleaning up the ID's</p>\n"
},
{
"answer_id": 229990,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 3,
"selected": true,
"text": "<p>You could extend the array returned by Site.find.</p>\n\n<pre><code>class Site\n def find(*args)\n result = super\n result.extend LanguageAggregator if Array === result\n result\n end\nend\n\nmodule LanguageAggregator\n def languages\n Language.find(:all, :conditions => [ 'id in (?)', self.collect { |site| site.id } ])\n end\nend\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140/"
] |
Let's say I have the following code:
```
@sites = Site.find(session[:sites]) # will be an array of Site ids
@languages = Language.for_sites(@sites)
```
for\_sites is a named\_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has\_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.
Instead of calling the Language object on the second line, I'd ideally like to say
```
@sites.languages
```
and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.
|
You could extend the array returned by Site.find.
```
class Site
def find(*args)
result = super
result.extend LanguageAggregator if Array === result
result
end
end
module LanguageAggregator
def languages
Language.find(:all, :conditions => [ 'id in (?)', self.collect { |site| site.id } ])
end
end
```
|
220,142 |
<p>I need to output the contents of a text field using MS Query Analyzer. I have tried this:</p>
<pre><code>select top 1 text from myTable
</code></pre>
<p>(where text is a <code>text</code> field)</p>
<p>and</p>
<pre><code>DECLARE @data VarChar(8000)
select top 1 @data = text from myTable
PRINT @data
</code></pre>
<p>The first one prints only the first 2000 or so characters and the second only prints the first 8000 characters. Is there any way to get all of the text?</p>
<p>Notes:</p>
<ul>
<li>must work with SQL Server 7</li>
</ul>
|
[
{
"answer_id": 220232,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 4,
"selected": true,
"text": "<p>I don't think you can use varchar(MAX) in MSSQL7, so here's something that will give you all the data (note, what I'm understanding is you just want to visually see the data, and you aren't going put it in a variable or return it).</p>\n\n<p>So, this will print off the entire string so you can visually see what's in the field:</p>\n\n<pre><code>DECLARE @limit as int,\n @charLen as int,\n @current as int,\n @chars as varchar(8000)\n\nSET @limit = 8000\n\nSELECT TOP 1 @charLen = LEN(text)\nFROM myTable\n\nSET @current = 1\n\nWHILE @current < @charLen\nBEGIN\n SELECT TOP 1 @chars = SUBSTRING(text,@current,@limit)\n FROM myTable\n PRINT @chars\n\n SET @current = @current + @limit\nEND\n</code></pre>\n"
},
{
"answer_id": 220286,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't used Query Analyzer in a while, however you can adjust the maximum amount of characters displayed in the results window in the Options window. See the <a href=\"http://msdn.microsoft.com/en-us/library/aa217017(SQL.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a> documentation.</p>\n"
},
{
"answer_id": 7834425,
"author": "Daniel",
"author_id": 172885,
"author_profile": "https://Stackoverflow.com/users/172885",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://shortfastcode.blogspot.com/2011/10/getting-around-sql-server-print-8000.html\" rel=\"nofollow\">http://shortfastcode.blogspot.com/2011/10/getting-around-sql-server-print-8000.html</a></p>\n\n<p>Use this stored proc. THe only down side is you get a line break every 8000 charachters :(</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[LongPrint]\n @String NVARCHAR(MAX)\n\nAS\n\n/*\nExample:\n\nexec LongPrint @string =\n'This String\nExists to test\nthe system.'\n\n*/\n\n/* This procedure is designed to overcome the limitation\nin the SQL print command that causes it to truncate strings\nlonger than 8000 characters (4000 for nvarchar).\n\nIt will print the text passed to it in substrings smaller than 4000\ncharacters. If there are carriage returns (CRs) or new lines (NLs in the text),\nit will break up the substrings at the carriage returns and the\nprinted version will exactly reflect the string passed.\n\nIf there are insufficient line breaks in the text, it will\nprint it out in blocks of 4000 characters with an extra carriage\nreturn at that point.\n\nIf it is passed a null value, it will do virtually nothing.\n\nNOTE: This is substantially slower than a simple print, so should only be used\nwhen actually needed.\n */\n\nDECLARE\n @CurrentEnd BIGINT, /* track the length of the next substring */\n @offset tinyint /*tracks the amount of offset needed */\n\nset @string = replace( replace(@string, char(13) + char(10), char(10)) , char(13), char(10))\n\nWHILE LEN(@String) > 1\nBEGIN\n\nIF CHARINDEX(CHAR(10), @String) between 1 AND 4000\n BEGIN\n\nSET @CurrentEnd = CHARINDEX(char(10), @String) -1\n set @offset = 2\n END\n ELSE\n BEGIN\n SET @CurrentEnd = 4000\n set @offset = 1\n END\n\nPRINT SUBSTRING(@String, 1, @CurrentEnd)\n\nset @string = SUBSTRING(@String, @CurrentEnd+@offset, 1073741822)\n\nEND /*End While loop*/\n</code></pre>\n\n<p>This was originally posted on SQLServerCentral.com at <a href=\"http://www.sqlservercentral.com/scripts/Print/63240/\" rel=\"nofollow\">http://www.sqlservercentral.com/scripts/Print/63240/</a></p>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80/"
] |
I need to output the contents of a text field using MS Query Analyzer. I have tried this:
```
select top 1 text from myTable
```
(where text is a `text` field)
and
```
DECLARE @data VarChar(8000)
select top 1 @data = text from myTable
PRINT @data
```
The first one prints only the first 2000 or so characters and the second only prints the first 8000 characters. Is there any way to get all of the text?
Notes:
* must work with SQL Server 7
|
I don't think you can use varchar(MAX) in MSSQL7, so here's something that will give you all the data (note, what I'm understanding is you just want to visually see the data, and you aren't going put it in a variable or return it).
So, this will print off the entire string so you can visually see what's in the field:
```
DECLARE @limit as int,
@charLen as int,
@current as int,
@chars as varchar(8000)
SET @limit = 8000
SELECT TOP 1 @charLen = LEN(text)
FROM myTable
SET @current = 1
WHILE @current < @charLen
BEGIN
SELECT TOP 1 @chars = SUBSTRING(text,@current,@limit)
FROM myTable
PRINT @chars
SET @current = @current + @limit
END
```
|
220,147 |
<p>Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Intersection.</p>
<p>I am looking for a generic solution which can handle n number of rows in #t2.</p>
<pre><code>-- SQL Code Begin
create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2
go
create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key
go
insert into #t1
select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union
select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union
select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17
-- 1 --> 11, 12, 13, 14
-- 2 --> 13, 15, 16, 17
-- 3 --> 13, 12, 16, 17
insert into #t2 (key1)
select 1 union select 2 union select 3
-- SQL Code End
</code></pre>
<p>The output I am looking for is,</p>
<pre><code>1001 11 (A')
1001 14 (A')
1002 12 (A I C - A I B I C)
1003 13 (A I B I C)
1004 15 (B')
1005 16 (B I C - A I B I C)
1005 17 (B I C - A I B I C)
</code></pre>
<p>The output has 5 segments, instead of the possible 7 as two of them are NULL.</p>
|
[
{
"answer_id": 220284,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>SELECT key2,\n CASE\n WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC'\n WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC'\n WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC'\n WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB'\n WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A'\n WHEN InA = 0 and InB = 1 and InC = 0 THEN 'B'\n WHEN InA = 0 and InB = 0 and InC = 1 THEN 'C'\n ELSE 'I''m broke'\n END as [SubSet]\nFROM\n\n(\nSELECT key2,\n MAX(CASE WHEN key1 = 1 THEN 1 ELSE 0 END) as InA,\n MAX(CASE WHEN key1 = 2 THEN 1 ELSE 0 END) as InB,\n MAX(CASE WHEN key1 = 3 THEN 1 ELSE 0 END) as InC\nFROM #t1\nWHERE key1 in (1, 2, 3)\nGROUP BY key2\n) sub\n\nORDER BY key2\n</code></pre>\n"
},
{
"answer_id": 220990,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "<p>If you can popluate the table 2 as </p>\n\n<pre><code>1, Key1-Value 1\n2, Key1-Value 2\n4, Key1-Value 3\n</code></pre>\n\n<p>likewise if you have more key1's then the identity column as you have, should be populated as a binary tree.\nso that the values in t2 would be </p>\n\n<pre><code>1 , 1\n2 , 2\n4 , 3\n</code></pre>\n\n<p>Then you need to do a select:</p>\n\n<pre><code>select sum(identity), key2\nfrom t1, t2\nwhere t1.key1 = t2.key1\ngroupby key2\n</code></pre>\n\n<p>the output you will get will be </p>\n\n<pre><code>1 11\n5 12\n7 13\n1 14\n2 15\n6 16\n6 17\n</code></pre>\n\n<p>you can see that 1,2,4 will be A',B',C' 2 will be A|B , 7 will be A|B|C and likewise</p>\n"
},
{
"answer_id": 221130,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 3,
"selected": true,
"text": "<p>If I have understood the problem correctly, I think you may have to resort to using a loop to cope with 'n' number of rows</p>\n\n<pre><code>DECLARE @Key2 INT\nDECLARE @Subset VARCHAR(1000)\nDECLARE @tblResults TABLE\n(\n Key2 INT,\n Subset VARCHAR(1000)\n)\n\nSET @Subset = ''\nSELECT @Key2 = MIN(Key2) FROM #t1\n\nWHILE @Key2 IS NOT NULL\nBEGIN\n SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10))\n FROM #t1\n WHERE Key2 = @Key2\n\n INSERT INTO @tblResults (Key2, Subset)\n VALUES (@Key2, @Subset)\n\n SET @Subset = ''\n SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2\nEND\n\nSELECT * FROM @tblResults\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26309/"
] |
Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Intersection.
I am looking for a generic solution which can handle n number of rows in #t2.
```
-- SQL Code Begin
create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2
go
create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key
go
insert into #t1
select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union
select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union
select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17
-- 1 --> 11, 12, 13, 14
-- 2 --> 13, 15, 16, 17
-- 3 --> 13, 12, 16, 17
insert into #t2 (key1)
select 1 union select 2 union select 3
-- SQL Code End
```
The output I am looking for is,
```
1001 11 (A')
1001 14 (A')
1002 12 (A I C - A I B I C)
1003 13 (A I B I C)
1004 15 (B')
1005 16 (B I C - A I B I C)
1005 17 (B I C - A I B I C)
```
The output has 5 segments, instead of the possible 7 as two of them are NULL.
|
If I have understood the problem correctly, I think you may have to resort to using a loop to cope with 'n' number of rows
```
DECLARE @Key2 INT
DECLARE @Subset VARCHAR(1000)
DECLARE @tblResults TABLE
(
Key2 INT,
Subset VARCHAR(1000)
)
SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1
WHILE @Key2 IS NOT NULL
BEGIN
SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10))
FROM #t1
WHERE Key2 = @Key2
INSERT INTO @tblResults (Key2, Subset)
VALUES (@Key2, @Subset)
SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2
END
SELECT * FROM @tblResults
```
|
220,159 |
<p>I'd like to log the <em>call trace</em> during certain points, like failed assertions, or uncaught exceptions.</p>
|
[
{
"answer_id": 220168,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Tasks/ControllingAppResponse.html\" rel=\"nofollow noreferrer\">This</a> pretty much tells you what to do.</p>\n\n<p>Essentially you need to set up the applications exception handling to log, something like: </p>\n\n<pre><code>#import <ExceptionHandling/NSExceptionHandler.h>\n\n[[NSExceptionHandler defaultExceptionHandler] \n setExceptionHandlingMask: NSLogUncaughtExceptionMask | \n NSLogUncaughtSystemExceptionMask | \n NSLogUncaughtRuntimeErrorMask]\n</code></pre>\n"
},
{
"answer_id": 220198,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "<p>For exceptions, you can use the NSStackTraceKey member of the exception's userInfo dictionary to do this. See <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/Exceptions/Tasks/ControllingAppResponse.html#//apple_ref/doc/uid/20000473-DontLinkElementID_3\" rel=\"nofollow noreferrer\">Controlling a Program's Response to Exceptions</a> on Apple's website.</p>\n"
},
{
"answer_id": 220241,
"author": "vt.",
"author_id": 3905,
"author_profile": "https://Stackoverflow.com/users/3905",
"pm_score": 3,
"selected": false,
"text": "<p>Cocoa already logs the stack trace on uncaught exceptions to the console although they're just raw memory addresses. If you want symbolic information in the console there's some <a href=\"https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Exceptions/Tasks/ControllingAppResponse.html\" rel=\"nofollow noreferrer\">sample code</a> from Apple.</p>\n\n<p>If you want to generate a stack trace at an arbitrary point in your code (and you're on Leopard), see the backtrace man page. Before Leopard, you actually had to dig through the call stack itself.</p>\n"
},
{
"answer_id": 2322894,
"author": "smokris",
"author_id": 64860,
"author_profile": "https://Stackoverflow.com/users/64860",
"pm_score": 10,
"selected": true,
"text": "<p>This code works on any thread:</p>\n<pre><code>NSLog(@"%@", NSThread.callStackSymbols);\n</code></pre>\n<blockquote>\n<p>Returns an array containing the call stack symbols. Each element is an <code>NSString</code> object with a value in a format determined by the <code>backtrace_symbols()</code> function.</p>\n</blockquote>\n"
},
{
"answer_id": 14228652,
"author": "Zayin Krige",
"author_id": 541634,
"author_profile": "https://Stackoverflow.com/users/541634",
"pm_score": 5,
"selected": false,
"text": "<p>n13's answer didn't quite work - I modified it slightly to come up with this</p>\n\n<pre><code>#import <UIKit/UIKit.h>\n\n#import \"AppDelegate.h\"\n\nint main(int argc, char *argv[])\n{\n @autoreleasepool {\n int retval;\n @try{\n retval = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));\n }\n @catch (NSException *exception)\n {\n NSLog(@\"Gosh!!! %@\", [exception callStackSymbols]);\n @throw;\n }\n return retval;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 53263697,
"author": "Dipak",
"author_id": 1482311,
"author_profile": "https://Stackoverflow.com/users/1482311",
"pm_score": 1,
"selected": false,
"text": "<p>In swift print this way:</p>\n\n<pre><code>print(\"stack trace:\\(Thread.callStackSymbols)\")\n</code></pre>\n"
},
{
"answer_id": 69894408,
"author": "miragessee",
"author_id": 5592365,
"author_profile": "https://Stackoverflow.com/users/5592365",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to get it as NSString.</p>\n<pre><code>[NSThread callStackSymbols].description\n</code></pre>\n"
}
] |
2008/10/20
|
[
"https://Stackoverflow.com/questions/220159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10184/"
] |
I'd like to log the *call trace* during certain points, like failed assertions, or uncaught exceptions.
|
This code works on any thread:
```
NSLog(@"%@", NSThread.callStackSymbols);
```
>
> Returns an array containing the call stack symbols. Each element is an `NSString` object with a value in a format determined by the `backtrace_symbols()` function.
>
>
>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.