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 |
|---|---|---|---|---|---|---|
13,599 | <p>Does anyone know how to transform a enum value to a human readable value?</p>
<p>For example:</p>
<blockquote>
<p>ThisIsValueA should be "This is Value A".</p>
</blockquote>
| [
{
"answer_id": 13602,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Most examples of this that I've seen involve marking your enum values up with [Description] attributes and using refle... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | Does anyone know how to transform a enum value to a human readable value?
For example:
>
> ThisIsValueA should be "This is Value A".
>
>
> | Converting this from a vb code snippet that a certain Ian Horwill left at a [blog post long ago](http://secretgeek.net/progr_purga.asp)... i've since used this in production successfully.
```
/// <summary>
/// Add spaces to separate the capitalized words in the string,
/// i.e. insert a space before each uppercase letter that is
/// either preceded by a lowercase letter or followed by a
/// lowercase letter (but not for the first char in string).
/// This keeps groups of uppercase letters - e.g. acronyms - together.
/// </summary>
/// <param name="pascalCaseString">A string in PascalCase</param>
/// <returns></returns>
public static string Wordify(string pascalCaseString)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}
```
(requires, 'using System.Text.RegularExpressions;')
Thus:
```
Console.WriteLine(Wordify(ThisIsValueA.ToString()));
```
Would return,
```
"This Is Value A".
```
It's much simpler, and less redundant than providing Description attributes.
Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for). |
13,615 | <p>I need to validate an integer to know if is a valid enum value.</p>
<p>What is the best way to do this in C#?</p>
| [
{
"answer_id": 13635,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Brad Abrams specifically warns against <strong><code>Enum.IsDefined</code></strong> in his post <a href=\"https://learn.m... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#? | You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!
`IsDefined` is fine for most scenarios, you could start with:
```
public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
{
retVal = default(TEnum);
bool success = Enum.IsDefined(typeof(TEnum), enumValue);
if (success)
{
retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
}
return success;
}
```
(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension) |
13,620 | <p>(assume php5) consider</p>
<pre><code><?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
</code></pre>
<p>Is there much of a difference between 1 and 2?</p>
<p>If not, what about between 1/2 and 3?</p>
| [
{
"answer_id": 13665,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "<p>Well, as with all \"What might be faster in real life\" questions, you can't beat a real life test.</p>\n\n<pre><code>f... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
] | (assume php5) consider
```
<?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
```
Is there much of a difference between 1 and 2?
If not, what about between 1/2 and 3? | Well, as with all "What might be faster in real life" questions, you can't beat a real life test.
```
function timeFunc($function, $runs)
{
$times = array();
for ($i = 0; $i < $runs; $i++)
{
$time = microtime();
call_user_func($function);
$times[$i] = microtime() - $time;
}
return array_sum($times) / $runs;
}
function Method1()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are $foo";
}
function Method2()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are {$foo}";
}
function Method3()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are " . $foo;
}
print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";
```
Give it a few runs to page everything in, then...
0.0035568
0.0035388
0.0025394
So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, **after** all the work to parse out the variable and trim/copy up the original string.
**Updates By Somnath:**
I added Method4() to above real time logic.
```
function Method4()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = 'these are ' . $foo;
}
print timeFunc('Method4', 10) . "\n";
Results were:
0.0014739
0.0015574
0.0011955
0.001169
```
When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point. |
13,753 | <p>I'm missing something here:</p>
<pre><code>$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher.Filter = ("(objectclass=computer)")
$computers = $objSearcher.findall()
</code></pre>
<p>So the question is why do the two following outputs differ?</p>
<pre><code>$computers | %{
"Server name in quotes $_.properties.name"
"Server name not in quotes " + $_.properties.name
}
PS> $computers[0] | %{"$_.properties.name"; $_.properties.name}
System.DirectoryServices.SearchResult.properties.name
GORILLA
</code></pre>
| [
{
"answer_id": 13760,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>I believe it has to do with the way that PS interpolates information in the \"\". Try this:</p>\n\n<p>\"Server name in quo... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635/"
] | I'm missing something here:
```
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher.Filter = ("(objectclass=computer)")
$computers = $objSearcher.findall()
```
So the question is why do the two following outputs differ?
```
$computers | %{
"Server name in quotes $_.properties.name"
"Server name not in quotes " + $_.properties.name
}
PS> $computers[0] | %{"$_.properties.name"; $_.properties.name}
System.DirectoryServices.SearchResult.properties.name
GORILLA
``` | When you included $\_.properties.name in the string, it was returning the type name of the property. When a variable is included in a string and the string is evaluated, it calls the ToString method on that object referenced by the variable (not including the members specified after).
In this case, the ToString method is returning the **type name**. You can force the evaluation of the variable and members similar to what EBGreen suggested, but by using
```
"Server name in quotes $($_.properties.name)"
```
In the other scenario **PowerShell** is evaluating the variable and members specified first and then adding it to the previous string.
You are right that you are getting back a collection of properties. If you pipe **$computer[0].properties** to get-member, you can explore the object model right from the command line.
The important part is below.
>
> TypeName: System.DirectoryServices.ResultPropertyCollection
>
>
> Name MemberType Definition
>
>
>
>
> ---
>
>
> Values Property System.Collections.ICollection Values {get;}
>
>
> |
13,763 | <p>Is there a function like <code>document.getElementById("FirstDiv").clear()</code>?</p>
| [
{
"answer_id": 13766,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.</p>\n"
},
... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | Is there a function like `document.getElementById("FirstDiv").clear()`? | To answer the original question - there are various ways to do this, but the following would be the simplest.
If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:
```
myChildNode.parentNode.removeChild(myChildNode);
```
Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:
```
function removeElement(node) {
node.parentNode.removeChild(node);
}
```
---
EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory. |
13,775 | <p>I have a .net web application that has a Flex application embedded within a page. This flex application calls a .net webservice. I can trace the execution proccess through the debugger and all looks great until I get the response:</p>
<pre><code>
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request
. ---> System.Xml.XmlException: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest
request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---
</code>
</pre>
<p>The call from flex looks good, the execution through the webservice is good, but this is the response I capture via wireshark, what is going on here?</p>
<p>I have tried several web methods, from "Hello World" to paramatized methods...all comeback with the same response...</p>
<p>I thought it may have something to do with encoding with the "---&gt", but I'm unsure how to control what .net renders as the response.</p>
| [
{
"answer_id": 15292,
"author": "James Avery",
"author_id": 537,
"author_profile": "https://Stackoverflow.com/users/537",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like you might be sending a poorly formed XML document to the service. Can you use Fiddler or something like th... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a .net web application that has a Flex application embedded within a page. This flex application calls a .net webservice. I can trace the execution proccess through the debugger and all looks great until I get the response:
```
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request
. ---> System.Xml.XmlException: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest
request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---
```
The call from flex looks good, the execution through the webservice is good, but this is the response I capture via wireshark, what is going on here?
I have tried several web methods, from "Hello World" to paramatized methods...all comeback with the same response...
I thought it may have something to do with encoding with the "--->", but I'm unsure how to control what .net renders as the response. | It looks like you might be sending a poorly formed XML document to the service. Can you use Fiddler or something like that to get a copy of the actual call that is going to the web service? That would be a huge help in figured out what the issue is. |
13,791 | <p>I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p>
<pre><code>>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
</code></pre>
<p>I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?</p>
| [
{
"answer_id": 13844,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I think you might have missed the r or miscounted the backslashes...</p>\n\n<pre><code>\"\\\\n\" == r\"\\n\"... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370/"
] | I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...
```
>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
```
I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light? | Isn't that what Anders' second example does?
In 2.5 there's also a `string-escape` encoding you can apply:
```
>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is
a test
>>>
``` |
13,851 | <p>I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.</p>
<p>My HTML 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 id="middle">
<img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" />
<div id="ctl00_menuPanel" class="menu">
<a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;">Home</a> |
<a id="ctl00_leden" href="Leden.aspx">Leden</a> |
<a id="ctl00_agenda" href="Agenda.aspx">Agenda</a> |
<a id="ctl00_fotos" href="Fotos.aspx">Foto's</a> |
<a id="ctl00_geschiedenis" href="Geschiedenis.aspx">Geschiedenis</a> |
<a id="ctl00_gastenboek" href="Gastenboek.aspx">Gastenboek</a>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 13854,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 3,
"selected": true,
"text": "<p>Try the IE Developer Toolbar, which will let you inspect what is going on with the elements and give you outlines of the a... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.
My HTML Code:
```html
<div id="middle">
<img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" />
<div id="ctl00_menuPanel" class="menu">
<a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;">Home</a> |
<a id="ctl00_leden" href="Leden.aspx">Leden</a> |
<a id="ctl00_agenda" href="Agenda.aspx">Agenda</a> |
<a id="ctl00_fotos" href="Fotos.aspx">Foto's</a> |
<a id="ctl00_geschiedenis" href="Geschiedenis.aspx">Geschiedenis</a> |
<a id="ctl00_gastenboek" href="Gastenboek.aspx">Gastenboek</a>
</div>
</div>
``` | Try the IE Developer Toolbar, which will let you inspect what is going on with the elements and give you outlines of the areas covered. It might give you a better understanding of the problem. |
13,857 | <p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>
| [
{
"answer_id": 13875,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 6,
"selected": false,
"text": "<p>It's simple: A function that references variables from a containing scope, potentially after flow-of-control has l... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649/"
] | I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them. | [Closure on closures](http://mrevelle.blogspot.com/2006/10/closure-on-closures.html)
>
> Objects are data with methods
> attached, closures are functions with
> data attached.
>
>
>
```
def make_counter():
i = 0
def counter(): # counter() is a closure
nonlocal i
i += 1
return i
return counter
c1 = make_counter()
c2 = make_counter()
print (c1(), c1(), c2(), c2())
# -> 1 2 1 2
``` |
13,938 | <p><img src="https://i.stack.imgur.com/DibJS.jpg" alt="Visual Studio folder structure"></p>
<p>I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned.</p>
<p>My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example</p>
<ul>
<li>Alt+1 runs the tests in project BLL.Test, </li>
<li>Alt+2 runs the tests in project DAL.Tests, </li>
<li>Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and</li>
<li>Alt+4 runs the tests in folder [Tests.Integration].</li>
</ul>
<p>TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome.</p>
<p><img src="https://i.stack.imgur.com/NYnmJ.jpg" alt="TestDriven.net test run output"></p>
<p>Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated.</p>
| [
{
"answer_id": 13953,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 0,
"selected": false,
"text": "<p>This is a bit of fiddly solution, but you could configure some <a href=\"http://blogs.msdn.com/saraford/archive/2008/04/24/d... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446/"
] | 
I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned.
My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example
* Alt+1 runs the tests in project BLL.Test,
* Alt+2 runs the tests in project DAL.Tests,
* Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and
* Alt+4 runs the tests in folder [Tests.Integration].
TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome.

Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated. | I actually found kind of a solution for this on my own by using keyboard command bound to a macro. The macro was recorded from the menu Tools>Macros>Record TemporaryMacro. While recording I selected my [Tests] folder and ran ReSharpers UnitTest.ContextRun. This resulted in the following macro,
```
Sub TemporaryMacro()
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate
DTE.ActiveWindow.Object.GetItem("TestUnitTest\Tests").Select(vsUISelectionType.vsUISelectionTypeSelect)
DTE.ExecuteCommand("ReSharper.UnitTest_ContextRun")
End Sub
```
which was then bound to it's own keyboard command in Tools>Options>Environment>Keyboard.
However, what would be even more awesome is a more general solution where I can configure exactly which projects/folders/classes to run and when. For example by the means of an xml file. This could then easily be checked in to version control and distributed to everyone who works with the project. |
13,941 | <p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."</p>
<p>I know that there's a function that can be used in <em>Cocoa</em> apps, <code>NSBeep</code>, but I don't think that has much anything to do with this.</p>
<p>I've also tried</p>
<pre class="lang-py prettyprint-override"><code>print(\a)
</code></pre>
<p>but that didn't work.</p>
<p>I'm using a Mac, if you couldn't tell by my <em>Cocoa</em> comment, so that may help.</p>
| [
{
"answer_id": 13949,
"author": "gbc",
"author_id": 1667,
"author_profile": "https://Stackoverflow.com/users/1667",
"pm_score": 7,
"selected": true,
"text": "<p>Have you tried :</p>\n\n<pre><code>import sys\nsys.stdout.write('\\a')\nsys.stdout.flush()\n</code></pre>\n\n<p>That works for ... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] | I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."
I know that there's a function that can be used in *Cocoa* apps, `NSBeep`, but I don't think that has much anything to do with this.
I've also tried
```py
print(\a)
```
but that didn't work.
I'm using a Mac, if you couldn't tell by my *Cocoa* comment, so that may help. | Have you tried :
```
import sys
sys.stdout.write('\a')
sys.stdout.flush()
```
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
```
print('\a')
```
(You just need the single quotes around the character sequence). |
13,963 | <p>I want to parse a config file sorta thing, like so:</p>
<pre><code>[KEY:Value]
[SUBKEY:SubValue]
</code></pre>
<p>Now I started with a <code>StreamReader</code>, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.</p>
<p>One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0.</p>
| [
{
"answer_id": 13974,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 0,
"selected": false,
"text": "<p>It looks to me that you would be better off using an XML based config file as there are already .NET classes which can read ... | 2008/08/17 | [
"https://Stackoverflow.com/questions/13963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | I want to parse a config file sorta thing, like so:
```
[KEY:Value]
[SUBKEY:SubValue]
```
Now I started with a `StreamReader`, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.
One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0. | >
> I considered it, but I'm not going to use XML. I am going to be writing this stuff by hand, and hand editing XML makes my brain hurt. :')
>
>
>
Have you looked at [YAML](http://www.yaml.org/)?
You get the benefits of XML without all the pain and suffering. It's used extensively in the ruby community for things like config files, pre-prepared database data, etc
here's an example
```
customer:
name: Orion
age: 26
addresses:
- type: Work
number: 12
street: Bob Street
- type: Home
number: 15
street: Secret Road
```
There appears to be a [C# library here](http://yaml-net-parser.sourceforge.net/default.html), which I haven't used personally, but yaml is pretty simple, so "how hard can it be?" :-)
I'd say it's preferable to inventing your own ad-hoc format (and dealing with parser bugs) |
14,118 | <p>I'm writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sysadmin's server, which freezes randomly every 28 hours or so. </p>
<p>I've gotten all the hard stuff done, I'm just trying to add one last bit of code to break the main loop and log out of AIM when the user types 'quit'.</p>
<p>The problem is, if I try to read from STDIN in the main program loop, it blocks the process until input is entered, essentially rendering the bot inactive. I've tried testing for EOF before reading, but no dice... EOF just always returns false.</p>
<p>Here's below is some sample code I'm working with:</p>
<pre><code>while(1) {
$oscar->do_one_loop();
# Poll to see if any arduino data is coming in over serial port
my $char = $port->lookfor();
# If we get data from arduino, then print it
if ($char) {
print "" . $char ;
}
# reading STDIN blocks until input is received... AAARG!
my $a = <STDIN>;
print $a;
if($a eq "exit" || $a eq "quit" || $a eq 'c' || $a eq 'q') {last;}
}
print "Signing off... ";
$oscar->signoff();
print "Done\n";
print "Closing serial port... ";
$port->close() || warn "close failed";
print "Done\n";
</code></pre>
| [
{
"answer_id": 14124,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 5,
"selected": true,
"text": "<p>The Perl built-in is <a href=\"http://perldoc.perl.org/functions/select.html\" rel=\"noreferrer\"><code>select()</code></a>, whi... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sysadmin's server, which freezes randomly every 28 hours or so.
I've gotten all the hard stuff done, I'm just trying to add one last bit of code to break the main loop and log out of AIM when the user types 'quit'.
The problem is, if I try to read from STDIN in the main program loop, it blocks the process until input is entered, essentially rendering the bot inactive. I've tried testing for EOF before reading, but no dice... EOF just always returns false.
Here's below is some sample code I'm working with:
```
while(1) {
$oscar->do_one_loop();
# Poll to see if any arduino data is coming in over serial port
my $char = $port->lookfor();
# If we get data from arduino, then print it
if ($char) {
print "" . $char ;
}
# reading STDIN blocks until input is received... AAARG!
my $a = <STDIN>;
print $a;
if($a eq "exit" || $a eq "quit" || $a eq 'c' || $a eq 'q') {last;}
}
print "Signing off... ";
$oscar->signoff();
print "Done\n";
print "Closing serial port... ";
$port->close() || warn "close failed";
print "Done\n";
``` | The Perl built-in is [`select()`](http://perldoc.perl.org/functions/select.html), which is a pass-through to the `select()` system call, but for sane people I recommend [`IO::Select`](http://search.cpan.org/dist/IO/lib/IO/Select.pm).
Code sample:
```
#!/usr/bin/perl
use IO::Select;
$s = IO::Select->new();
$s->add(\*STDIN);
while (++$i) {
print "Hiya $i!\n";
sleep(5);
if ($s->can_read(.5)) {
chomp($foo = <STDIN>);
print "Got '$foo' from STDIN\n";
}
}
``` |
14,165 | <p>I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.</p>
| [
{
"answer_id": 14169,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p>Check if your code is including the <strong>windows.h</strong> header file and either your code or other third-part... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers. | Check if your code is including the **windows.h** header file and either your code or other third-party headers have their own **min()**/**max()** definitions. If yes, then prepend your **windows.h** inclusion with a definition of **NOMINMAX** like this:
```
#define NOMINMAX
#include <windows.h>
``` |
14,209 | <p><code>System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.</code></p>
<p>Anybody ever get this error and/or have any idea on it's cause and/or solution?</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=125227&SiteID=1" rel="nofollow noreferrer">This link may have relevant information.</a></p>
<p><strong>Update</strong></p>
<p>The connection string is <code>=.\SQLEXPRESS;AttachDbFilename=C:\temp\HelloWorldTest.mdf;Integrated Security=True</code></p>
<p>The suggested <code>User Instance=false</code> worked.</p>
| [
{
"answer_id": 14214,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>You should add an explicit User Instance=true/false to your connection string</p>\n"
},
{
"answer_id": 1086442,
... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] | `System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.`
Anybody ever get this error and/or have any idea on it's cause and/or solution?
[This link may have relevant information.](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=125227&SiteID=1)
**Update**
The connection string is `=.\SQLEXPRESS;AttachDbFilename=C:\temp\HelloWorldTest.mdf;Integrated Security=True`
The suggested `User Instance=false` worked. | Here is the answer to your problem:
Very often old user instance creates some temp files that prevent a new SQL Express user instance to be created. When those files are deleted everything start working properly.
First of all confirm that user instances are enabled by running the following SQL in SQL Server Management Studio:
```
exec sp_configure 'user instances enabled', 1.
GO
Reconfigure
```
After running the query restart your SQL Server instance. Now delete the following folder:
`C:\Documents and Settings\{YOUR_USERNAME}\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\{SQL_INSTANCE_NAME}`
Make sure that you replace `{YOUR_USERNAME}` and `{SQL_INSTANCE_NAME}` with the appropriate names.
Source: [Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."](http://aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx) |
14,247 | <p>I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and <em>please</em>, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.</p>
<p>There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: <strong>is there a way to do data binding programmatically that doesn't involve a world of hurt?</strong></p>
| [
{
"answer_id": 14261,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "<p>Don't be afraid of MXML. It's great for laying out views. If you write your own <em>reusable</em> components then writing them... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] | I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and *please*, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.
There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: **is there a way to do data binding programmatically that doesn't involve a world of hurt?** | Don't be afraid of MXML. It's great for laying out views. If you write your own *reusable* components then writing them in ActionScript may sometimes give you a little more control, but for non-reusable views MXML is much better. It's more terse, bindings are extemely easy to set up, etc.
However, bindings in pure ActionScript need not be that much of a pain. It will never be as simple as in MXML where a lot of things are done for you, but it can be done with not too much effort.
What you have is `BindingUtils` and it's methods `bindSetter` and `bindProperty`. I almost always use the former, since I usually want to do some work, or call `invalidateProperties` when values change, I almost never just want to set a property.
What you need to know is that these two return an object of the type `ChangeWatcher`, if you want to remove the binding for some reason, you have to hold on to this object. This is what makes manual bindings in ActionScript a little less convenient than those in MXML.
Let's start with a simple example:
```
BindingUtils.bindSetter(nameChanged, selectedEmployee, "name");
```
This sets up a binding that will call the method `nameChanged` when the `name` property on the object in the variable `selectedEmployee` changes. The `nameChanged` method will recieve the new value of the `name` property as an argument, so it should look like this:
```
private function nameChanged( newName : String ) : void
```
The problem with this simple example is that once you have set up this binding it will fire each time the property of the specified object changes. The value of the variable `selectedEmployee` may change, but the binding is still set up for the object that the variable pointed to before.
There are two ways to solve this: either to keep the `ChangeWatcher` returned by `BindingUtils.bindSetter` around and call `unwatch` on it when you want to remove the binding (and then setting up a new binding instead), or bind to yourself. I'll show you the first option first, and then explain what I mean by binding to yourself.
The `currentEmployee` could be made into a getter/setter pair and implemented like this (only showing the setter):
```
public function set currentEmployee( employee : Employee ) : void {
if ( _currentEmployee != employee ) {
if ( _currentEmployee != null ) {
currentEmployeeNameCW.unwatch();
}
_currentEmployee = employee;
if ( _currentEmployee != null ) {
currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, "name");
}
}
}
```
What happens is that when the `currentEmployee` property is set it looks to see if there was a previous value, and if so removes the binding for that object (`currentEmployeeNameCW.unwatch()`), then it sets the private variable, and unless the new value was `null` sets up a new binding for the `name` property. Most importantly it saves the `ChangeWatcher` returned by the binding call.
This is a basic binding pattern and I think it works fine. There is, however, a trick that can be used to make it a bit simpler. You can bind to yourself instead. Instead of setting up and removing bindings each time the `currentEmployee` property changes you can have the binding system do it for you. In your `creationComplete` handler (or constructor or at least some time early) you can set up a binding like so:
```
BindingUtils.bindSetter(currentEmployeeNameChanged, this, ["currentEmployee", "name"]);
```
This sets up a binding not only to the `currentEmployee` property on `this`, but also to the `name` property on this object. So anytime either changes the method `currentEmployeeNameChanged` will be called. There's no need to save the `ChangeWatcher` because the binding will never have to be removed.
The second solution works in many cases, but I've found that the first one is sometimes necessary, especially when working with bindings in non-view classes (since `this` has to be an event dispatcher and the `currentEmployee` has to be bindable for it to work). |
14,278 | <p>I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the <a href="http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx" rel="noreferrer">LoadLibrary</a> WinAPI function to load a dll and calling <a href="http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx" rel="noreferrer">GetProcAddress</a> to get an pointer to a function inside that dll.</p>
<p>My question is how do I dynamically load a plugin in C#/.Net application?</p>
| [
{
"answer_id": 14282,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 5,
"selected": true,
"text": "<p>The following code snippet (C#) constructs an instance of any concrete classes derived from <code>Base</code> found in class li... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534/"
] | I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx) WinAPI function to load a dll and calling [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx) to get an pointer to a function inside that dll.
My question is how do I dynamically load a plugin in C#/.Net application? | The following code snippet (C#) constructs an instance of any concrete classes derived from `Base` found in class libraries (\*.dll) in the application path and stores them in a list.
```
using System.IO;
using System.Reflection;
List<Base> objects = new List<Base>();
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);
foreach (FileInfo file in dir.GetFiles("*.dll"))
{
Assembly assembly = Assembly.LoadFrom(file.FullName);
foreach (Type type in assembly.GetTypes())
{
if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)
{
Base b = type.InvokeMember(null,
BindingFlags.CreateInstance,
null, null, null) as Base;
objects.Add(b);
}
}
}
```
**Edit:** The classes referred to by [Matt](https://stackoverflow.com/questions/14278/how-to-load-plugins-in-net#14305) are probably a better option in .NET 3.5. |
14,281 | <p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p>
<p>Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping?</p>
| [
{
"answer_id": 14304,
"author": "jdd",
"author_id": 242853,
"author_profile": "https://Stackoverflow.com/users/242853",
"pm_score": 0,
"selected": false,
"text": "<p>You could loop through the zip files, reading individual files using the zipfile module and running your regex on those, e... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files.
Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping? | There's nothing that will automatically do what you want.
However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.
```
#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('myfile.zip')
for subfile in f.namelist():
print subfile
data = f.read(subfile)
for line in data.split('\n'):
print line
``` |
14,287 | <p>In my C/C++ program, I'm using <a href="http://opencvlibrary.sourceforge.net/" rel="noreferrer">OpenCV</a> to capture images from my webcam. The camera (<a href="http://en.wikipedia.org/wiki/Quickcam" rel="noreferrer">Logitech QuickCam IM</a>) can capture at resolutions <strong>320x240</strong>, <strong>640x480</strong> and <strong>1280x960</strong>. But, for some strange reason, OpenCV gives me images of resolution <strong>320x240</strong> only. Calls to change the resolution using <strong>cvSetCaptureProperty()</strong> with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam?</p>
| [
{
"answer_id": 14290,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p>There doesn't seem to be a solution. The resolution can be increased to <strong>640x480</strong> using <a href=\"ht... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | In my C/C++ program, I'm using [OpenCV](http://opencvlibrary.sourceforge.net/) to capture images from my webcam. The camera ([Logitech QuickCam IM](http://en.wikipedia.org/wiki/Quickcam)) can capture at resolutions **320x240**, **640x480** and **1280x960**. But, for some strange reason, OpenCV gives me images of resolution **320x240** only. Calls to change the resolution using **cvSetCaptureProperty()** with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam? | There doesn't seem to be a solution. The resolution can be increased to **640x480** using [this hack](http://tech.groups.yahoo.com/group/OpenCV/message/28735) shared by *lifebelt77*. Here are the details reproduced:
Add to **highgui.h**:
```
#define CV_CAP_PROP_DIALOG_DISPLAY 8
#define CV_CAP_PROP_DIALOG_FORMAT 9
#define CV_CAP_PROP_DIALOG_SOURCE 10
#define CV_CAP_PROP_DIALOG_COMPRESSION 11
#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12
```
Add the function **icvSetPropertyCAM\_VFW** to **cvcap.cpp**:
```
static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )
{
int result = -1;
CAPSTATUS capstat;
CAPTUREPARMS capparam;
BITMAPINFO btmp;
switch( property_id )
{
case CV_CAP_PROP_DIALOG_DISPLAY:
result = capDlgVideoDisplay(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);
break;
case CV_CAP_PROP_DIALOG_FORMAT:
result = capDlgVideoFormat(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);
break;
case CV_CAP_PROP_DIALOG_SOURCE:
result = capDlgVideoSource(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);
break;
case CV_CAP_PROP_DIALOG_COMPRESSION:
result = capDlgVideoCompression(capture->capWnd);
break;
case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:
capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
btmp.bmiHeader.biWidth = floor(value/1000);
btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;
btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *
btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *
btmp.bmiHeader.biBitCount / 8;
capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
break;
default:
break;
}
return result;
}
```
and edit **captureCAM\_VFW\_vtable** as following:
```
static CvCaptureVTable captureCAM_VFW_vtable =
{
6,
(CvCaptureCloseFunc)icvCloseCAM_VFW,
(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,
(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,
(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,
(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL
(CvCaptureGetDescriptionFunc)0
};
```
Now rebuilt **highgui.dll**. |
14,300 | <p>For example; with the old command prompt it would be:</p>
<pre><code>cmd.exe /k mybatchfile.bat
</code></pre>
| [
{
"answer_id": 14313,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>Drop into a cmd instance (or indeed PowerShell itself) and type this:</p>\n\n<pre><code>powershell -?\n</code></pre>\n\... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887/"
] | For example; with the old command prompt it would be:
```
cmd.exe /k mybatchfile.bat
``` | Drop into a cmd instance (or indeed PowerShell itself) and type this:
```
powershell -?
```
You'll see that powershell.exe has a "-noexit" parameter which tells it not to exit after executing a "startup command". |
14,330 | <p>How do I convert the RGB values of a pixel to a single monochrome value?</p>
| [
{
"answer_id": 14331,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 6,
"selected": true,
"text": "<p>I found one possible solution in the <a href=\"http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html\" rel=\"... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | How do I convert the RGB values of a pixel to a single monochrome value? | I found one possible solution in the [Color FAQ](http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html). The *luminance component* Y (from the *CIE XYZ system*) captures what is most perceived by humans as color in one channel. So, use those coefficients:
```
mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);
``` |
14,350 | <p>I have a Flex swf hosted at <a href="http://www.a.com/a.swf" rel="nofollow noreferrer">http://www.a.com/a.swf</a>.
I have a flash code on another doamin that tries loading the SWF:</p>
<pre><code>_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);
</code></pre>
<p>On the onLoaderFinish event I try to load classes from the remote SWF and create them:</p>
<pre><code>_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
</code></pre>
<p>When this code runs I get the following exception</p>
<pre><code>SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
at flash.display::LoaderInfo/get applicationDomain()
at NuconomyLoader/onLoaderFinish()
</code></pre>
<p>Is there any way to get this code working?</p>
| [
{
"answer_id": 14384,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 0,
"selected": false,
"text": "<p>Mayhaps <a href=\"http://livedocs.adobe.com/flex/15/flex_docs_en/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flex_Documenta... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1228206/"
] | I have a Flex swf hosted at <http://www.a.com/a.swf>.
I have a flash code on another doamin that tries loading the SWF:
```
_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);
```
On the onLoaderFinish event I try to load classes from the remote SWF and create them:
```
_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
```
When this code runs I get the following exception
```
SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
at flash.display::LoaderInfo/get applicationDomain()
at NuconomyLoader/onLoaderFinish()
```
Is there any way to get this code working? | This is all described in [The Adobe Flex 3 Programming ActionScript 3 PDF](http://livedocs.adobe.com/flex/3/progAS_flex3.pdf) on page 550 (Chapter 27: Flash Player Security / Cross-scripting):
>
> If two SWF files written with ActionScript 3.0 are served from different domains—for example, <http://siteA.com/swfA.swf> and <http://siteB.com/swfB.swf>—then, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain("siteA.com"), swfB.swf gives SWF files from siteA.com permission to script it.
>
>
>
It goes on in some more detail, with diagrams and all. |
14,373 | <p>I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.</p>
<p>Wanted conversion is like this:</p>
<pre><code>CVS branch SVN branch
HEAD -> branches/branchX
branchA -> trunk
branchB -> branches/branchB
branchC -> branches/branchC
</code></pre>
<p>That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.</p>
<p>Both CVS and SVN repositories will be on same linux machine.</p>
<p>How could this be done? </p>
<p>Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough.</p>
| [
{
"answer_id": 14382,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 1,
"selected": false,
"text": "<p>Subversion branches are directories, so you could just move the branches after the import has finished and no history wil... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] | I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.
Wanted conversion is like this:
```
CVS branch SVN branch
HEAD -> branches/branchX
branchA -> trunk
branchB -> branches/branchB
branchC -> branches/branchC
```
That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.
Both CVS and SVN repositories will be on same linux machine.
How could this be done?
Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough. | > I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?
Yes. Subversion also keeps track of changes to the directory structure, and all version history is preserved even if a file is moved in the tree.
I recommend converting the repository with [cvs2svn](http://cvs2svn.tigris.org/), including branches and tags. Once the repository is in Subversion you can move the branches and tags around as you wish. This also keeps the history of the actual tags and branches being renamed, which may be interesting in a historical context later. |
14,375 | <p>I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this: </p>
<pre><code>public interface IEntity { int ID {get;set;} }
public partial class MyEntity: IEntity {
public int ID {
get { return this.IDfield; }
set { this.IDfield=value; }
}
}
</code></pre>
<p>and then trying to delete some entity like this: </p>
<pre><code>IEntity ie=repository.GetByID(1);
repoitory.DeleteOnSubmit(ie);
</code></pre>
<p>throws<br>
The member 'IEntity.ID' has no supported translation to SQL. </p>
<p>fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?</p>
<hr>
<p>Here it is:<br>
Exception message:
The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL. </p>
<p>Code: </p>
<pre><code>var d = repContent.GetAll().Where(x => x.idContent.Equals(idContent));
foreach (var tagConnect in d) <- error line
{
repContet.DeleteOnSubmit(tagConnect);
</code></pre>
<p>(it gets all tags from DB, and deletes them)</p>
<p>And stack trace: </p>
<pre><code>[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.]
System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ...
</code></pre>
<p>When I try do decorate partial class:</p>
<pre><code>[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int idContent
{ get { return this.idEvent; } set { this.idEvent=value; } }
</code></pre>
<p>it throws error "Invalid column name 'idContent'."</p>
| [
{
"answer_id": 14381,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>using System.Data.Linq.Mapping;\n\npublic partial class MyEntity: IEntity \n { [Column(... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407/"
] | I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this:
```
public interface IEntity { int ID {get;set;} }
public partial class MyEntity: IEntity {
public int ID {
get { return this.IDfield; }
set { this.IDfield=value; }
}
}
```
and then trying to delete some entity like this:
```
IEntity ie=repository.GetByID(1);
repoitory.DeleteOnSubmit(ie);
```
throws
The member 'IEntity.ID' has no supported translation to SQL.
fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?
---
Here it is:
Exception message:
The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.
Code:
```
var d = repContent.GetAll().Where(x => x.idContent.Equals(idContent));
foreach (var tagConnect in d) <- error line
{
repContet.DeleteOnSubmit(tagConnect);
```
(it gets all tags from DB, and deletes them)
And stack trace:
```
[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.]
System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ...
```
When I try do decorate partial class:
```
[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int idContent
{ get { return this.idEvent; } set { this.idEvent=value; } }
```
it throws error "Invalid column name 'idContent'." | It appears Microsoft dropped support for `==` operator in interfaces when using linq-to-sql in MVC4 (or maybe it was never supported). You can however use `i.ID.Equals(someId)` in place of the `==` operator.
Casting `IQueryable` to `IEnumerable` works but **should not be used!** The reason is: `IQueryable` has funky implementation of `IEnumerable`. Whatever linq method you'll use on a `IQueryable` through the `IEnumerable` interface will cause the query to be executed first, have all the results fetched to the memory from the DB and eventually running the method localy on the data (normally those methods would be translated to SQL and executed in the DB). Imagine trying to get a single row from a table containing billion rows, fetching all of them only to pick one (and it gets much worse with careless casting of `IQueryable` to `IEnumerable` and lazy loading related data).
Apparently Linq has no problem using `==` operator with interfaces on local data (so only `IQueryable` is affected) and also with Entity Frameworks (or so I heard). |
14,378 | <p>I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that?</p>
| [
{
"answer_id": 14379,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 6,
"selected": true,
"text": "<p>Note that venerable <a href=\"http://www.xmission.com/~nate/glut.html\" rel=\"noreferrer\">Nate Robin's GLUT</a> li... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that? | Note that venerable [Nate Robin's GLUT](http://www.xmission.com/~nate/glut.html) library doesn't support the scrollwheel. But, later implementations of GLUT like [FreeGLUT](http://freeglut.sourceforge.net/) do.
Using the scroll wheel in FreeGLUT is dead simple. Here is how:
Declare a callback function that shall be called whenever the scroll wheel is scrolled. This is the prototype:
```
void mouseWheel(int, int, int, int);
```
Register the callback with the (Free)GLUT function **glutMouseWheelFunc()**.
```
glutMouseWheelFunc(mouseWheel);
```
Define the callback function. The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward.
```
void mouseWheel(int button, int dir, int x, int y)
{
if (dir > 0)
{
// Zoom in
}
else
{
// Zoom out
}
return;
}
```
That's it! |
14,386 | <p>With the <em>Visual Studio 2005 C++ compiler</em>, I get the following warning when my code uses the <code>fopen()</code> and such calls:</p>
<pre class="lang-none prettyprint-override"><code>1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1> c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1> Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'
</code></pre>
<p>How do I prevent this?</p>
| [
{
"answer_id": 14387,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 8,
"selected": true,
"text": "<p>It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solut... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | With the *Visual Studio 2005 C++ compiler*, I get the following warning when my code uses the `fopen()` and such calls:
```none
1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1> c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1> Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'
```
How do I prevent this? | It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like **fopen\_s**), you need to place a definition of **\_CRT\_SECURE\_NO\_DEPRECATE** before your included header files. For example:
```
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
```
The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add **\_CRT\_SECURE\_NO\_DEPRECATE** to *Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions*. |
14,389 | <p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p>
<p>The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within <code>[a-zA-Z0-9'\-]</code>)</p>
<p>How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..</p>
<pre><code>config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
</code></pre>
| [
{
"answer_id": 14391,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>Use a subrange of <code>[\\u0000-\\uFFFF]</code> for what you want.</p>\n\n<p>You can also use the <code>re.UNICODE</co... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)
The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within `[a-zA-Z0-9'\-]`)
How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..
```
config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
``` | Use a subrange of `[\u0000-\uFFFF]` for what you want.
You can also use the `re.UNICODE` compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if `UNICODE` is set, `\w` will match the characters `[0-9_]` plus whatever is classified as alphanumeric in the Unicode character properties database.
See also <http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html>. |
14,402 | <p>In my simple OpenGL program I get the following error about exit redefinition:</p>
<pre><code>1>c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1> c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit'
</code></pre>
<p>I'm using Nate Robins' <a href="http://www.xmission.com/~nate/glut.html" rel="noreferrer">GLUT for Win32</a> and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it?</p>
| [
{
"answer_id": 14403,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Cause:</strong></p>\n\n<p>The <strong>stdlib.h</strong> which ships with the recent versions of Visual Stud... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | In my simple OpenGL program I get the following error about exit redefinition:
```
1>c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1> c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit'
```
I'm using Nate Robins' [GLUT for Win32](http://www.xmission.com/~nate/glut.html) and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it? | **Cause:**
The **stdlib.h** which ships with the recent versions of Visual Studio has a different (and conflicting) definition of the **exit()** function. It clashes with the definition in **glut.h**.
**Solution:**
Override the definition in glut.h with that in stdlib.h. Place the stdlib.h line above the glut.h line in your code.
```
#include <stdlib.h>
#include <GL/glut.h>
``` |
14,413 | <p>I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this?</p>
| [
{
"answer_id": 14414,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Easy solution</strong>: Use <a href=\"http://glew.sourceforge.net/\" rel=\"nofollow noreferrer\">GLEW</a>. ... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this? | **Easy solution**: Use [GLEW](http://glew.sourceforge.net/). See how [here](https://stackoverflow.com/questions/17370/using-glew-to-use-opengl-extensions-under-windows).
**Hard solution**:
If you have a **really strong reason** not to use GLEW, here's how to achieve the same without it:
Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the [OpenGL Extension Registry](http://www.opengl.org/registry/).
>
> Example: I wish to use the capabilities of the [EXT\_framebuffer\_object](http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt) extension. The APIs I wish to use from this extension are:
>
>
>
```
glGenFramebuffersEXT()
glBindFramebufferEXT()
glFramebufferTexture2DEXT()
glCheckFramebufferStatusEXT()
glDeleteFramebuffersEXT()
```
Check if your graphic card supports the extension you wish to use. If it does, then your work is almost done! Download and install the latest drivers and SDKs for your graphics card.
>
> Example: The graphics card in my PC is a **NVIDIA 6600 GT**. So, I visit the [NVIDIA OpenGL Extension Specifications](http://developer.nvidia.com/object/nvidia_opengl_specs.html) webpage and find that the [EXT\_framebuffer\_object](http://www.nvidia.com/dev_content/nvopenglspecs/GL_EXT_framebuffer_object.txt) extension is supported. I then download the latest [NVIDIA OpenGL SDK](http://developer.nvidia.com/object/sdk_home.html) and install it.
>
>
>
Your graphic card manufacturer provides a **glext.h** header file (or a similarly named header file) with all the declarations needed to use the supported OpenGL extensions. (Note that not all extensions might be supported.) Either place this header file somewhere your compiler can pick it up or include its directory in your compiler's include directories list.
Add a `#include <glext.h>` line in your code to include the header file into your code.
Open **[glext.h](http://oss.sgi.com/projects/ogl-sample/ABI/glext.h)**, find the API you wish to use and grab its corresponding *ugly-looking* declaration.
>
> Example: I search for the above framebuffer APIs and find their corresponding ugly-looking declarations:
>
>
>
```
typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
```
All this means is that your header file has the API declaration in 2 forms. One is a wgl-like ugly function pointer declaration. The other is a sane looking function declaration.
For each extension API you wish to use, add in your code declarations of the function name as a type of the ugly-looking string.
>
> Example:
>
>
>
```
PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;
PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
```
Though it looks ugly, all we're doing is to declare function pointers of the type corresponding to the extension API.
Initialize these function pointers with their rightful functions. These functions are exposed by the library or driver. We need to use **wglGetProcAddress()** function to do this.
>
> Example:
>
>
>
```
glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT");
glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT");
glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT");
glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT");
glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT");
```
Don't forget to check the function pointers for *NULL*. If by chance **wglGetProcAddress()** couldn't find the extension function, it would've initialized the pointer with NULL.
>
> Example:
>
>
>
```
if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT
|| NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT)
{
// Extension functions not loaded!
exit(1);
}
```
That's it, we're done! You can now use these function pointers just as if the function calls existed.
>
> Example:
>
>
>
```
glGenFramebuffersEXT(1, &fbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0);
```
**Reference:** [Moving Beyond OpenGL 1.1 for Windows](http://www.gamedev.net/reference/articles/article1929.asp) by Dave Astle — The article is a bit dated, but has all the information you need to understand why this pathetic situation exists on Windows and how to get around it. |
14,451 | <p>What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?</p>
<p>I am looking for something similar to what IE does when you hit F11.</p>
<p>I wish this to be a run time option for the user not a design time decision by my good self.</p>
<p>As Mentioned in the accepted answer </p>
<pre><code>BorderStyle := bsNone;
</code></pre>
<p>was part of the way to do it. Strangely I kept getting a <code>E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol'</code> error when using that line (another type had <code>bsNone</code> defined).</p>
<p>To overcome this I had to use : </p>
<pre><code>BorderStyle := Forms.bsNone;
</code></pre>
| [
{
"answer_id": 14458,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>Maximize the form and <a href=\"http://delphi.about.com/cs/adptips2000/a/bltip0100_5.htm\" rel=\"nofollow noreferrer\">... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1724/"
] | What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?
I am looking for something similar to what IE does when you hit F11.
I wish this to be a run time option for the user not a design time decision by my good self.
As Mentioned in the accepted answer
```
BorderStyle := bsNone;
```
was part of the way to do it. Strangely I kept getting a `E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol'` error when using that line (another type had `bsNone` defined).
To overcome this I had to use :
```
BorderStyle := Forms.bsNone;
``` | Well, this has always worked for me. Seems a bit simpler...
```
procedure TForm52.Button1Click(Sender: TObject);
begin
BorderStyle := bsNone;
WindowState := wsMaximized;
end;
``` |
14,464 | <p>I have a structure which I need to populate and write to disk (several actually).</p>
<p>An example is:</p>
<pre><code>byte-6
bit0 - original_or_copy
bit1 - copyright
bit2 - data_alignment_indicator
bit3 - PES_priority
bit4-bit5 - PES_scrambling control.
bit6-bit7 - reserved
</code></pre>
<p>In C I might do something like the following:</p>
<pre><code>struct PESHeader {
unsigned reserved:2;
unsigned scrambling_control:2;
unsigned priority:1;
unsigned data_alignment_indicator:1;
unsigned copyright:1;
unsigned original_or_copy:1;
};
</code></pre>
<p>Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator? </p>
<p>For a couple of structures, I can just do bit shifting wrapped in an accessor function.</p>
<p>I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write.</p>
| [
{
"answer_id": 14466,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>Could an Enum with the Flags Attribute help maybe? See here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/8447... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006/"
] | I have a structure which I need to populate and write to disk (several actually).
An example is:
```
byte-6
bit0 - original_or_copy
bit1 - copyright
bit2 - data_alignment_indicator
bit3 - PES_priority
bit4-bit5 - PES_scrambling control.
bit6-bit7 - reserved
```
In C I might do something like the following:
```
struct PESHeader {
unsigned reserved:2;
unsigned scrambling_control:2;
unsigned priority:1;
unsigned data_alignment_indicator:1;
unsigned copyright:1;
unsigned original_or_copy:1;
};
```
Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator?
For a couple of structures, I can just do bit shifting wrapped in an accessor function.
I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write. | I'd probably knock together something using attributes, then a conversion class to convert suitably attributed structures to the bitfield primitives. Something like...
```
using System;
namespace BitfieldTest
{
[global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
sealed class BitfieldLengthAttribute : Attribute
{
uint length;
public BitfieldLengthAttribute(uint length)
{
this.length = length;
}
public uint Length { get { return length; } }
}
static class PrimitiveConversion
{
public static long ToLong<T>(T t) where T : struct
{
long r = 0;
int offset = 0;
// For every field suitably attributed with a BitfieldLength
foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())
{
object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false);
if (attrs.Length == 1)
{
uint fieldLength = ((BitfieldLengthAttribute)attrs[0]).Length;
// Calculate a bitmask of the desired length
long mask = 0;
for (int i = 0; i < fieldLength; i++)
mask |= 1 << i;
r |= ((UInt32)f.GetValue(t) & mask) << offset;
offset += (int)fieldLength;
}
}
return r;
}
}
struct PESHeader
{
[BitfieldLength(2)]
public uint reserved;
[BitfieldLength(2)]
public uint scrambling_control;
[BitfieldLength(1)]
public uint priority;
[BitfieldLength(1)]
public uint data_alignment_indicator;
[BitfieldLength(1)]
public uint copyright;
[BitfieldLength(1)]
public uint original_or_copy;
};
public class MainClass
{
public static void Main(string[] args)
{
PESHeader p = new PESHeader();
p.reserved = 3;
p.scrambling_control = 2;
p.data_alignment_indicator = 1;
long l = PrimitiveConversion.ToLong(p);
for (int i = 63; i >= 0; i--)
{
Console.Write( ((l & (1l << i)) > 0) ? "1" : "0");
}
Console.WriteLine();
return;
}
}
}
```
Which produces the expected ...000101011. Of course, it needs more error checking and a slightly saner typing, but the concept is (I think) sound, reusable, and lets you knock out easily maintained structures by the dozen.
adamw |
14,491 | <p>What is the proper way for an MFC application to cleanly close itself?</p>
| [
{
"answer_id": 14492,
"author": "Mike",
"author_id": 1743,
"author_profile": "https://Stackoverflow.com/users/1743",
"pm_score": 4,
"selected": false,
"text": "<pre><code>AfxGetMainWnd()->PostMessage(WM_CLOSE);\n</code></pre>\n"
},
{
"answer_id": 14663,
"author": "Aidan Ry... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743/"
] | What is the proper way for an MFC application to cleanly close itself? | Programatically Terminate an MFC Application
```
void ExitMFCApp()
{
// same as double-clicking on main window close box
ASSERT(AfxGetMainWnd() != NULL);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
```
<http://support.microsoft.com/kb/117320> |
14,505 | <p>In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this:</p>
<pre><code>Color blended = Color.FromArgb(alpha, color);
</code></pre>
<p>or</p>
<pre><code>Color blended = Color.FromArgb(alpha, red, green , blue);
</code></pre>
<p>However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get:</p>
<pre><code>Color.FromArgb(int red, int green, int blue);
</code></pre>
<p>and</p>
<pre><code>Color.FromArgb(int val);
</code></pre>
<p>The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following:</p>
<pre><code>private Color FromARGB(byte alpha, byte red, byte green, byte blue)
{
int val = (alpha << 24) | (red << 16) | (green << 8) | blue;
return Color.FromArgb(val);
}
</code></pre>
<p>But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0.</p>
<p>Has anyone gotten this to work on the Compact Framework?</p>
| [
{
"answer_id": 14525,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": true,
"text": "<p>Apparently, it's not quite that simple, but <a href=\"http://blogs.msdn.com/chrislorton/archive/2006/04/07/570649.aspx... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this:
```
Color blended = Color.FromArgb(alpha, color);
```
or
```
Color blended = Color.FromArgb(alpha, red, green , blue);
```
However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get:
```
Color.FromArgb(int red, int green, int blue);
```
and
```
Color.FromArgb(int val);
```
The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following:
```
private Color FromARGB(byte alpha, byte red, byte green, byte blue)
{
int val = (alpha << 24) | (red << 16) | (green << 8) | blue;
return Color.FromArgb(val);
}
```
But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0.
Has anyone gotten this to work on the Compact Framework? | Apparently, it's not quite that simple, but [still possible](http://blogs.msdn.com/chrislorton/archive/2006/04/07/570649.aspx), if you have Windows Mobile 5.0 or newer. |
14,527 | <p>I need to be able to find the last occurrence of a character within an element.</p>
<p>For example:</p>
<pre><code><mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>
</code></pre>
<p>If I try to locate it through using <code>substring-before(mediaurl, '.')</code> and <code>substring-after(mediaurl, '.')</code> then it will, of course, match on the first dot. </p>
<p>How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.</p>
| [
{
"answer_id": 14547,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>How about tokenize with \"/\" and take the last element from the array ?</p>\n\n<pre><code>Example: tokenize(\"XPath is fun\... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] | I need to be able to find the last occurrence of a character within an element.
For example:
```
<mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>
```
If I try to locate it through using `substring-before(mediaurl, '.')` and `substring-after(mediaurl, '.')` then it will, of course, match on the first dot.
How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT. | The following is an example of a template that would produce the required output in XSLT 1.0:
```
<xsl:template name="getExtension">
<xsl:param name="filename"/>
<xsl:choose>
<xsl:when test="contains($filename, '.')">
<xsl:call-template name="getExtension">
<xsl:with-param name="filename" select="substring-after($filename, '.')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$filename"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="getExtension">
<xsl:with-param name="filename" select="'http://www.blah.com/path/to/file/media.jpg'"/>
</xsl:call-template>
</xsl:template>
``` |
14,577 | <p>Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.</p>
<p>What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:</p>
<pre><code>declare c_lookup_codes for
select distinct lookup_code
from #workinprogress
while(1=1)
begin
fetch c_lookup_codes into @lookup_code
if @@sqlstatus<>0
begin
break
end
exec proc_code_xref @lookup_code @xref_code OUTPUT
update #workinprogress
set xref = @xref_code
where lookup_code = @lookup_code
end
</code></pre>
<p>Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?</p>
<p>_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look_up_code and finally, that it is not possible to have a table with the xref values in as the logic in proc_code_xref is too arcane._</p>
| [
{
"answer_id": 14671,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>Unless you are willing to duplicate the code in the xref proc, there is no way to avoid using a cursor.</p>\n"
},
{
"ans... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.
What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:
```
declare c_lookup_codes for
select distinct lookup_code
from #workinprogress
while(1=1)
begin
fetch c_lookup_codes into @lookup_code
if @@sqlstatus<>0
begin
break
end
exec proc_code_xref @lookup_code @xref_code OUTPUT
update #workinprogress
set xref = @xref_code
where lookup_code = @lookup_code
end
```
Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?
\_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look\_up\_code and finally, that it is not possible to have a table with the xref values in as the logic in proc\_code\_xref is too arcane.\_ | You have to have a XRef table if you want to take out the cursor. Assuming you know the 100 distinct lookup values (and that they're static) it's simple to generate one by calling proc\_code\_xref 100 times and inserting the results into a table |
14,614 | <p>First off, I understand the reasons why an interface or abstract class (in the .NET/C# terminology) cannot have abstract static methods. My question is then more focused on the best design solution.</p>
<p>What I want is a set of "helper" classes that all have their own static methods such that if I get objects A, B, and C from a third party vendor, I can have helper classes with methods such as</p>
<pre>
AHelper.RetrieveByID(string id);
AHelper.RetrieveByName(string name);
AHelper.DumpToDatabase();
</pre>
<p>Since my AHelper, BHelper, and CHelper classes will all basically have the same methods, it seems to makes sense to move these methods to an interface that these classes then derive from. However, wanting these methods to be static precludes me from having a generic interface or abstract class for all of them to derive from.</p>
<p>I could always make these methods non-static and then instantiate the objects first such as</p>
<pre>
AHelper a = new AHelper();
a.DumpToDatabase();
</pre>
<p>However, this code doesn't seem as intuitive to me. What are your suggestions? Should I abandon using an interface or abstract class altogether (the situation I'm in now) or can this possibly be refactored to accomplish the design I'm looking for?</p>
| [
{
"answer_id": 14622,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>In C# 3.0, static methods can be used on interfaces as if they were a part of them by using extension methods, as with... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | First off, I understand the reasons why an interface or abstract class (in the .NET/C# terminology) cannot have abstract static methods. My question is then more focused on the best design solution.
What I want is a set of "helper" classes that all have their own static methods such that if I get objects A, B, and C from a third party vendor, I can have helper classes with methods such as
```
AHelper.RetrieveByID(string id);
AHelper.RetrieveByName(string name);
AHelper.DumpToDatabase();
```
Since my AHelper, BHelper, and CHelper classes will all basically have the same methods, it seems to makes sense to move these methods to an interface that these classes then derive from. However, wanting these methods to be static precludes me from having a generic interface or abstract class for all of them to derive from.
I could always make these methods non-static and then instantiate the objects first such as
```
AHelper a = new AHelper();
a.DumpToDatabase();
```
However, this code doesn't seem as intuitive to me. What are your suggestions? Should I abandon using an interface or abstract class altogether (the situation I'm in now) or can this possibly be refactored to accomplish the design I'm looking for? | Looking at [your response](https://stackoverflow.com/questions/14614/static-methods-in-an-interfaceabstract-class#14655) I am thinking along the following lines:
* You could just have a static method that takes a type parameter and performs the expected logic based on the type.
* You could create a virtual method in your abstract base, where you specify the SQL in the concrete class. So that contains all the common code that is required by both (e.g. exectuting the command and returning the object) while encapsulating the "specialist" bits (e.g. the SQL) in the sub classes.
I prefer the second option, although its of course down to you. If you need me to go into further detail, please let me know and I will be happy to edit/update :) |
14,617 | <p>I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>
| [
{
"answer_id": 14629,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 5,
"selected": false,
"text": "<p>This was the solution I came up with\n<a href=\"http://sourceforge.net/projects/sshtools/\" rel=\"noreferrer\">http://... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769/"
] | I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this? | Another option is to consider looking at the [JSch library](http://www.jcraft.com/jsch/ "JSch library"). JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.
It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.
Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)
```
JSch jsch = new JSch();
String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts( knownHostsFilename );
Session session = jsch.getSession( "remote-username", "remote-host" );
{
// "interactive" version
// can selectively update specified known_hosts file
// need to implement UserInfo interface
// MyUserInfo is a swing implementation provided in
// examples/Sftp.java in the JSch dist
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
// OR non-interactive version. Relies in host key being in known-hosts file
session.setPassword( "remote-password" );
}
session.connect();
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remote-file", "local-file" );
// OR
InputStream in = sftpChannel.get( "remote-file" );
// process inputstream as needed
sftpChannel.exit();
session.disconnect();
``` |
14,698 | <p>When I try to precompile a *.pc file that contains a #warning directive I recieve the following error:</p>
<blockquote>
<p>PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).</p>
</blockquote>
<p>Can I somehow convince Pro*C to ignore the thing if it doesn't know what to do with it? I can't remove the <code>#warning</code> directive as it's used in a header file that I can't change and must include.</p>
| [
{
"answer_id": 14999,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 0,
"selected": false,
"text": "<p>You can't. Pro*C only knows #if and #include. My best advice would be to preprocess the file as part of your build pr... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733/"
] | When I try to precompile a \*.pc file that contains a #warning directive I recieve the following error:
>
> PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).
>
>
>
Can I somehow convince Pro\*C to ignore the thing if it doesn't know what to do with it? I can't remove the `#warning` directive as it's used in a header file that I can't change and must include. | According to the *Pro\*C/C++ Programmer's Guide* (chapter 5 "Advanced Topics"), Pro\*C silently ignores a number of preprocessor directives including #error and #pragma, but sadly not #warning. Since your warning directives are included in a header file, you might be able to use the ORA\_PROC macro:
```
#ifndef ORA_PROC
#include <irrelevant.h>
#endif
```
For some reason, Pro\*C errors out if you try to hide a straight #warning that way, however. |
14,708 | <p>What's the DOS FINDSTR equivalent for <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="noreferrer">PowerShell</a>? I need to search a bunch of log files for "ERROR".</p>
| [
{
"answer_id": 14724,
"author": "Monroecheeseman",
"author_id": 1351,
"author_profile": "https://Stackoverflow.com/users/1351",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the quick answer </p>\n\n<pre><code>Get-ChildItem -Recurse -Include *.log | select-string ERROR \n</code></... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1351/"
] | What's the DOS FINDSTR equivalent for [PowerShell](http://en.wikipedia.org/wiki/Windows_PowerShell)? I need to search a bunch of log files for "ERROR". | Here's the quick answer
```
Get-ChildItem -Recurse -Include *.log | select-string ERROR
```
I found it [here](http://www.interact-sw.co.uk/iangblog/2006/06/03/pshfindstr) which has a great indepth answer! |
14,717 | <p>We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?</p>
<p>Does anyone have some good methods for tracking down expensive queries/processes in this environment?</p>
| [
{
"answer_id": 14730,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>Profiler may seem like a \"needle in a haystack\" approach, but it may turn up something useful. Try running it for a cou... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?
Does anyone have some good methods for tracking down expensive queries/processes in this environment? | This will give you the top 50 statements by average CPU time, check here for other scripts: <http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true>
```
SELECT TOP 50
qs.total_worker_time/qs.execution_count as [Avg CPU Time],
SUBSTRING(qt.text,qs.statement_start_offset/2,
(case when qs.statement_end_offset = -1
then len(convert(nvarchar(max), qt.text)) * 2
else qs.statement_end_offset end -qs.statement_start_offset)/2)
as query_text,
qt.dbid, dbname=db_name(qt.dbid),
qt.objectid
FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY
[Avg CPU Time] DESC
``` |
14,731 | <p>Normally I would just use:</p>
<pre><code>HttpContext.Current.Server.UrlEncode("url");
</code></pre>
<p>But since this is a console application, <code>HttpContext.Current</code> is always going to be <code>null</code>.</p>
<p>Is there another method that does the same thing that I could use?</p>
| [
{
"answer_id": 14734,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the UrlEncode method in the HttpUtility class.</p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469/"
] | Normally I would just use:
```
HttpContext.Current.Server.UrlEncode("url");
```
But since this is a console application, `HttpContext.Current` is always going to be `null`.
Is there another method that does the same thing that I could use? | Try this!
```
Uri.EscapeUriString(url);
```
Or
```
Uri.EscapeDataString(data)
```
No need to reference System.Web.
**Edit:** Please see [another](https://stackoverflow.com/a/34189188/7391) SO answer for more... |
14,801 | <p>Suppose you have the following EJB 3 interfaces/classes:</p>
<pre><code>public interface Repository<E>
{
public void delete(E entity);
}
public abstract class AbstractRepository<E> implements Repository<E>
{
public void delete(E entity){
//...
}
}
public interface FooRepository<Foo>
{
//other methods
}
@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
AbstractRepository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
super.delete(entity);
}
//other methods
}
</code></pre>
<p>And then another bean that accesses the <code>FooRepository</code> bean :</p>
<pre><code>//...
@EJB
private FooRepository fooRepository;
public void someMethod(Foo foo)
{
fooRepository.delete(foo);
}
//...
</code></pre>
<p>However, the overriding method is never executed when the delete method of the <code>FooRepository</code> bean is called. Instead, only the implementation of the delete method that is defined in <code>AbstractRepository</code> is executed. </p>
<p>What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ?</p>
| [
{
"answer_id": 14920,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 1,
"selected": false,
"text": "<p>Can you write a unit test against your FooRepository class just using it as a POJO. If that works as expected then I'm ... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793/"
] | Suppose you have the following EJB 3 interfaces/classes:
```
public interface Repository<E>
{
public void delete(E entity);
}
public abstract class AbstractRepository<E> implements Repository<E>
{
public void delete(E entity){
//...
}
}
public interface FooRepository<Foo>
{
//other methods
}
@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
AbstractRepository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
super.delete(entity);
}
//other methods
}
```
And then another bean that accesses the `FooRepository` bean :
```
//...
@EJB
private FooRepository fooRepository;
public void someMethod(Foo foo)
{
fooRepository.delete(foo);
}
//...
```
However, the overriding method is never executed when the delete method of the `FooRepository` bean is called. Instead, only the implementation of the delete method that is defined in `AbstractRepository` is executed.
What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ? | I tried it with a pojo and it seems to work. I had to modify your code a bit.
I think your interfaces were a bit off, but I'm not sure.
I assumed "Foo" was a concrete type, but if not I can do some more testing for you.
I just wrote a main method to test this.
I hope this helps!
```
public static void main(String[] args){
FooRepository fooRepository = new FooRepositoryImpl();
fooRepository.delete(new Foo("Bar"));
}
public class Foo
{
private String value;
public Foo(String inValue){
super();
value = inValue;
}
public String toString(){
return value;
}
}
public interface Repository<E>
{
public void delete(E entity);
}
public interface FooRepository extends Repository<Foo>
{
//other methods
}
public class AbstractRespository<E> implements Repository<E>
{
public void delete(E entity){
System.out.println("Delete-" + entity.toString());
}
}
public class FooRepositoryImpl extends AbstractRespository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
System.out.println("something before");
super.delete(entity);
}
}
``` |
14,857 | <p><strong>Bounty:</strong> I will send $5 via paypal for an answer that fixes this problem for me.</p>
<p>I'm not sure what VS setting I've changed or if it's a web.config setting or what, but I keep getting this error in the error list and yet all solutions build fine. Here are some examples:</p>
<pre>
Error 5 'CompilerGlobalScopeAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. C:\projects\MyProject\Web\Controls\EmailStory.ascx 609 184 C:\...\Web\
Error 6 'ArrayList' is ambiguous in the namespace 'System.Collections'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 13 28 C:\...\Web\
Error 7 'Exception' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 37 21 C:\...\Web\
Error 8 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 47 64 C:\...\Web\
Error 9 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 140 72 C:\...\Web\
Error 10 'Array' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 147 35 C:\...\Web\
[...etc...]
Error 90 'DateTime' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\App_Code\XsltHelperFunctions.vb 13 8 C:\...\Web\
</pre>
<p>As you can imagine, it's really annoying since there are blue squiggly underlines everywhere in the code, and filtering out relevant errors in the Error List pane is near impossible. I've checked the default ASP.Net web.config and machine.config but nothing seemed to stand out there.</p>
<hr>
<p><em>Edit:</em> Here's some of the source where the errors are occurring:</p>
<pre><code>'Error #5: whole line is blue underlined'
<%= addEmailToList.ToolTip %>
'Error #6: ArrayList is blue underlined'
Private _emails As New ArrayList()
'Error #7: Exception is blue underlined'
Catch ex As Exception
'Error #8: System.EventArgs is blue underlined'
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Error #9: System.EventArgs is blue underlined'
Protected Sub sendMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendMessage.Click
'Error #10: Array is blue underlined'
Me.emailSentTo.Text = Array.Join(";", mailToAddresses)
'Error #90: DateTime is blue underlined'
If DateTime.TryParse(data, dateValue) Then
</code></pre>
<hr>
<p><em>Edit</em>: GacUtil results</p>
<pre>
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4318.0
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d003700430039004
40037004500430036000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00370043003
900450036003100370035000000
Number of items = 2
</pre>
<pre>
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
Number of items = 0
</pre>
<hr>
<p><em>Edit</em>: interesting results from ngen:</p>
<pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.832
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
NGEN Roots:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
ScenarioDefault
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ScenarioNoDependencies
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
NGEN Roots that depend on "mscorlib":
[...a bunch of stuff...]
Native Images:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
</code></pre>
<p>There should only be one mscorlib in the native images, correct? How can I get rid of the others?</p>
| [
{
"answer_id": 14861,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 0,
"selected": false,
"text": "<p>When asking for help diagnosing compilation problems, it often helps to post the offending source code :)</p>\n\n<p>T... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | **Bounty:** I will send $5 via paypal for an answer that fixes this problem for me.
I'm not sure what VS setting I've changed or if it's a web.config setting or what, but I keep getting this error in the error list and yet all solutions build fine. Here are some examples:
```
Error 5 'CompilerGlobalScopeAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. C:\projects\MyProject\Web\Controls\EmailStory.ascx 609 184 C:\...\Web\
Error 6 'ArrayList' is ambiguous in the namespace 'System.Collections'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 13 28 C:\...\Web\
Error 7 'Exception' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 37 21 C:\...\Web\
Error 8 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 47 64 C:\...\Web\
Error 9 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 140 72 C:\...\Web\
Error 10 'Array' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 147 35 C:\...\Web\
[...etc...]
Error 90 'DateTime' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\App_Code\XsltHelperFunctions.vb 13 8 C:\...\Web\
```
As you can imagine, it's really annoying since there are blue squiggly underlines everywhere in the code, and filtering out relevant errors in the Error List pane is near impossible. I've checked the default ASP.Net web.config and machine.config but nothing seemed to stand out there.
---
*Edit:* Here's some of the source where the errors are occurring:
```
'Error #5: whole line is blue underlined'
<%= addEmailToList.ToolTip %>
'Error #6: ArrayList is blue underlined'
Private _emails As New ArrayList()
'Error #7: Exception is blue underlined'
Catch ex As Exception
'Error #8: System.EventArgs is blue underlined'
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Error #9: System.EventArgs is blue underlined'
Protected Sub sendMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendMessage.Click
'Error #10: Array is blue underlined'
Me.emailSentTo.Text = Array.Join(";", mailToAddresses)
'Error #90: DateTime is blue underlined'
If DateTime.TryParse(data, dateValue) Then
```
---
*Edit*: GacUtil results
```
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4318.0
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d003700430039004
40037004500430036000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00370043003
900450036003100370035000000
Number of items = 2
```
```
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
Number of items = 0
```
---
*Edit*: interesting results from ngen:
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.832
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
NGEN Roots:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
ScenarioDefault
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ScenarioNoDependencies
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
NGEN Roots that depend on "mscorlib":
[...a bunch of stuff...]
Native Images:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
```
There should only be one mscorlib in the native images, correct? How can I get rid of the others? | Based on the results of your gacutil output (thanks for doing that; I think it helps), I would say you need to try and run a repair on the .NET Framework install and Visual Studio 2005. I'm not sure if that will fix it, but as you can see from the output of the gacutil, you have none for 2.0.
From my VS2005 Command Prompt, I get:
```
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
Number of items = 1
```
From my VS2003 Command Prompt, I get:
```
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4322.573
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00330037004200440036004600430034000000
Number of items = 2
``` |
14,873 | <p>I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:</p>
<blockquote>
<p>23 queries. 0.448 seconds</p>
</blockquote>
<p>I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code?</p>
| [
{
"answer_id": 14972,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 5,
"selected": true,
"text": "<p>Try adding this to the bottom of the footer in your template:</p>\n\n<pre><code><?php echo $wpdb->num_queries; ?> <?p... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:
>
> 23 queries. 0.448 seconds
>
>
>
I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code? | Try adding this to the bottom of the footer in your template:
```
<?php echo $wpdb->num_queries; ?> <?php _e('queries'); ?>. <?php timer_stop(1); ?> <?php _e('seconds'); ?>
``` |
14,874 | <p>For part of my application I have a need to create an image of a certain view and all of its subviews.</p>
<p>To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.</p>
<p>I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.</p>
| [
{
"answer_id": 14947,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Refe... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | For part of my application I have a need to create an image of a certain view and all of its subviews.
To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.
I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level. | I found that writing the drawing code myself was the best way to:
* deal with potential transparency issues (some of the other options do add a white background to the whole image)
* performance was much better
The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a `[self drawRect:[self bounds]]` in the implementation of `imageWithSubviews`.
```
- (void)drawSubviews
{
BOOL flipped = [self isFlipped];
for ( NSView *subview in [self subviews] ) {
// changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)
// the transform assumes bounds and frame have the same size, and bounds origin is (0,0)
// handling of 'isFlipped' also probably unreliable
NSAffineTransform *transform = [NSAffineTransform transform];
if ( flipped ) {
[transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];
[transform scaleXBy:+1.0 yBy:-1.0];
} else
[transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];
[transform concat];
// recursively draw the subview and sub-subviews
[subview drawRect:[subview bounds]];
[subview drawSubviews];
// reset the transform to get back a clean graphic contexts for the rest of the drawing
[transform invert];
[transform concat];
}
}
- (NSImage *)imageWithSubviews
{
NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];
[image lockFocus];
// it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)
// Use instead an NSAffineTransform
if ( [self isFlipped] ) {
NSAffineTransform *transform = [NSAffineTransform transform];
[transform translateXBy:0 yBy:NSMaxY(self.bounds)];
[transform scaleXBy:+1.0 yBy:-1.0];
[transform concat];
}
[self drawSubviews];
[image unlockFocus];
return image;
}
``` |
14,884 | <p>Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:</p>
<pre><code>Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
</code></pre>
<p>How would you go about finding the best combination programmatically?</p>
<p>My best attempt so far (third or fourth algorithm) is:</p>
<ol>
<li>Find the longest shipper for each leg</li>
<li>Eliminate the most "expensive" one</li>
<li>Find the cheapest shipper for each leg</li>
<li>Calculate the total cost & days</li>
<li>If days are acceptable, finish, else, goto 1</li>
</ol>
<p>Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):</p>
<pre><code>$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " &lt;?&gt; " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
</code></pre>
<p>I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....</p>
<p>EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.</p>
<p>The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.</p>
<p>So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.</p>
| [
{
"answer_id": 14892,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like what you have is called a \"linear programming problem\". It also sounds like a homework problem, no offense... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:
```
Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
```
How would you go about finding the best combination programmatically?
My best attempt so far (third or fourth algorithm) is:
1. Find the longest shipper for each leg
2. Eliminate the most "expensive" one
3. Find the cheapest shipper for each leg
4. Calculate the total cost & days
5. If days are acceptable, finish, else, goto 1
Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):
```
$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " <?> " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
```
I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....
EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.
The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A\* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.
So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm. | Could alter some of the [shortest path algorithms](http://en.wikipedia.org/wiki/Shortest_path_problem), like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way |
14,923 | <p>I'm thinking of learning the <code>ASP.NET MVC</code> framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hierarchy?</p>
<p>Example navigation path:</p>
<p><strong>Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick</strong></p>
<p>Typical (I think) MVC URL:<br/>
<a href="http://example.com/products/category/NonstickCooksets" rel="nofollow noreferrer">http://example.com/products/category/NonstickCooksets</a></p>
<p>Desired URL:<br/>
<a href="http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick" rel="nofollow noreferrer">http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick</a></p>
<p>Can I do this?</p>
| [
{
"answer_id": 14991,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 2,
"selected": false,
"text": "<p>The MVC routing lets you define pretty much any structure you want, you just need to define what each of the pieces mean s... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I'm thinking of learning the `ASP.NET MVC` framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hierarchy?
Example navigation path:
**Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick**
Typical (I think) MVC URL:
<http://example.com/products/category/NonstickCooksets>
Desired URL:
<http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick>
Can I do this? | Zack, if I understand right you want unlimited depth of the subcategories. No biggie, since MVC Preview 3 (I think 3 or 4) this has been solved.
Just define a route like
"{controller}/{action}/{\*categoryPath}"
for an url such as :
<http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick>
you should have a ShopController with a Products action :
```
public class ShopController : Controller
{
...
public ActionResult Products(string categoryPath)
{
// the categoryPath value would be
// "household/kitchen/cookware/cooksets/nonstick". Process it (for ex. split it)
// and then decide what you do..
return View();
}
``` |
14,934 | <p>.NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:</p>
<pre><code>SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);
</code></pre>
<p>I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string? If not, what is the end result? And is this enough to prevent SQL injection attacks?</p>
| [
{
"answer_id": 14946,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/c-api-prepared-statements.html\" rel=\"nofollow noreferrer\">The M... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | .NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:
```
SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);
```
I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string? If not, what is the end result? And is this enough to prevent SQL injection attacks? | [The MySQL manual page](http://dev.mysql.com/doc/refman/5.0/en/c-api-prepared-statements.html) on prepared statements provides lots of information (which should apply to any other RDBMS).
Basically, your statement is parsed and processed ahead of time, and the parameters are sent separately instead of being handled along with the SQL code. This eliminates SQL-injection attacks because the SQL is parsed before the parameters are even set. |
14,943 | <p>What is the best way to disable <kbd>Alt</kbd> + <kbd>F4</kbd> in a c# win form to prevent the user from closing the form?</p>
<p>I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.</p>
| [
{
"answer_id": 14949,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 4,
"selected": false,
"text": "<p>You could handle the <code>FormClosing</code> event and set <code>FormClosingEventArgs.Cancel</code> to <code>true</code>.</... | 2008/08/18 | [
"https://Stackoverflow.com/questions/14943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375/"
] | What is the best way to disable `Alt` + `F4` in a c# win form to prevent the user from closing the form?
I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it. | This does the job:
```
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
```
Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form\_closing event before closing the form:
```
this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Close();
``` |
15,023 | <p>In WindowsForms world you can get a list of available image encoders/decoders with</p>
<pre><code>System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
</code></pre>
<p>My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available </p>
<pre><code>System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
</code></pre>
| [
{
"answer_id": 15388,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 1,
"selected": false,
"text": "<p>Hopefully someone will correct me if I'm wrong, but I don't think there's anything like that in WPF. But hopefully ... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In WindowsForms world you can get a list of available image encoders/decoders with
```
System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
```
My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available
```
System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
``` | You've got to love .NET reflection. I worked on the WPF team and can't quite think of anything better off the top of my head. The following code produces this list on my machine:
```
Bitmap Encoders:
System.Windows.Media.Imaging.BmpBitmapEncoder
System.Windows.Media.Imaging.GifBitmapEncoder
System.Windows.Media.Imaging.JpegBitmapEncoder
System.Windows.Media.Imaging.PngBitmapEncoder
System.Windows.Media.Imaging.TiffBitmapEncoder
System.Windows.Media.Imaging.WmpBitmapEncoder
Bitmap Decoders:
System.Windows.Media.Imaging.BmpBitmapDecoder
System.Windows.Media.Imaging.GifBitmapDecoder
System.Windows.Media.Imaging.IconBitmapDecoder
System.Windows.Media.Imaging.LateBoundBitmapDecoder
System.Windows.Media.Imaging.JpegBitmapDecoder
System.Windows.Media.Imaging.PngBitmapDecoder
System.Windows.Media.Imaging.TiffBitmapDecoder
System.Windows.Media.Imaging.WmpBitmapDecoder
```
There is a comment in the code where to add additional assemblies (if you support plugins for example). Also, you will want to filter the decoder list to remove:
```
System.Windows.Media.Imaging.LateBoundBitmapDecoder
```
More sophisticated filtering using constructor pattern matching is possible, but I don't feel like writing it. :-)
All you need to do now is instantiate the encoders and decoders to use them. Also, you can get better names by retrieving the `CodecInfo` property of the encoder decoders. This class will give you human readable names among other factoids.
```
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Media.Imaging;
namespace Codecs {
class Program {
static void Main(string[] args) {
Console.WriteLine("Bitmap Encoders:");
AllEncoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.WriteLine("\nBitmap Decoders:");
AllDecoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.ReadKey();
}
static IEnumerable<Type> AllEncoderTypes {
get {
return AllSubclassesOf(typeof(BitmapEncoder));
}
}
static IEnumerable<Type> AllDecoderTypes {
get {
return AllSubclassesOf(typeof(BitmapDecoder));
}
}
static IEnumerable<Type> AllSubclassesOf(Type type) {
var r = new Reflector();
// Add additional assemblies here
return r.AllSubclassesOf(type);
}
}
class Reflector {
List<Assembly> assemblies = new List<Assembly> {
typeof(BitmapDecoder).Assembly
};
public IEnumerable<Type> AllSubclassesOf(Type super) {
foreach (var a in assemblies) {
foreach (var t in a.GetExportedTypes()) {
if (t.IsSubclassOf(super)) {
yield return t;
}
}
}
}
}
}
``` |
15,034 | <p>When building a VS 2008 solution with 19 projects I sometimes get:</p>
<pre><code>The "GenerateResource" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.WriteByte(Byte value)
at System.IO.BinaryWriter.Write(Byte value)
at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Windows\Microsoft.NET\Framework\v3.5
</code></pre>
<p>Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.</p>
<p>I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources.</p>
| [
{
"answer_id": 15055,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": true,
"text": "<p>I used to hit this now and again with larger solutions. My tactic was to break the larger solution down into smaller solutions.</... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365/"
] | When building a VS 2008 solution with 19 projects I sometimes get:
```
The "GenerateResource" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.WriteByte(Byte value)
at System.IO.BinaryWriter.Write(Byte value)
at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Windows\Microsoft.NET\Framework\v3.5
```
Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.
I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources. | I used to hit this now and again with larger solutions. My tactic was to break the larger solution down into smaller solutions.
You could also try:
<http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx> |
15,040 | <p>I am using xampp on Windows, but I would like to use something closer to my server setup.</p>
<p><a href="http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/" rel="nofollow noreferrer">Federico Cargnelutti tutorial</a> explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.</p>
<p>ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.</p>
| [
{
"answer_id": 15044,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you have VMware workstation, VMware player or anything that can run vmware appliance, you just need to:</p>\n\n<... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1771/"
] | I am using xampp on Windows, but I would like to use something closer to my server setup.
[Federico Cargnelutti tutorial](http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/) explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.
ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder. | This is my install scrpt, I use it on debian servers, but it will work in Ubuntu (Ubuntu is built on Debian)
```
apt-get -yq update
apt-get -yq upgrade
apt-get -yq install sudo
apt-get -yq install gcc
apt-get -yq install g++
apt-get -yq install make
apt-get -yq install apache2
apt-get -yq install php5
apt-get -yq install php5-curl
apt-get -yq install php5-mysql
apt-get -yq install php5-gd
apt-get -yq install mysql-common
apt-get -yq install mysql-client
apt-get -yq install mysql-server
apt-get -yq install phpmyadmin
apt-get -yq install samba
echo '[global]
workgroup = workgroup
server string = %h server
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
encrypt passwords = true
passdb backend = tdbsam
obey pam restrictions = yes
;invalid users = root
unix password sync = no
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .
socket options = TCP_NODELAY
[homes]
comment = Home Directories
browseable = no
writable = no
create mask = 0700
directory mask = 0700
valid users = %S
[www]
comment = WWW
writable = yes
locking = no
path = /var/www
public = yes' > /etc/samba/smb.conf
(echo SAMBAPASSWORD; echo SAMBAPASSWORD) | smbpasswd -sa root
echo 'NameVirtualHost *
<VirtualHost *>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On
</VirtualHost>' > /etc/apache2/sites-enabled/000-default
/etc/init.d/apache2 stop
/etc/init.d/samba stop
/etc/init.d/apache2 start
/etc/init.d/samba start
```
edit: add this to set your MySQL password
```
/etc/init.d/mysql stop
echo "UPDATE mysql.user SET Password=PASSWORD('MySQLPasswrod') WHERE User='root'; FLUSH PRIVILEGES;" > /root/MySQLPassword
mysqld_safe --init-file=/root/MySQLPassword &
sleep 1
/etc/init.d/mysql stop
sleep 1
/etc/init.d/mysql start
```
end edit
This is a bit specailised but you get the idea, if you save this to a file ('install' for example) all you have to do is:
```
chmod +x install
./install
```
Some of my apt-get commands are not necessary, because apt will automatically get the dependencies but I prefer to be specific, for my installs. |
15,047 | <p>I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.</p>
<p>From what I've read this type of action could be handled by the <a href="http://www.dofactory.com/Patterns/PatternCommand.aspx" rel="noreferrer">Command design pattern</a> with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.</p>
<p>I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared?</p>
| [
{
"answer_id": 15103,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 1,
"selected": false,
"text": "<p>Try open source, .NET editors like <a href=\"http://sharpdevelop.net/OpenSource/SD/\" rel=\"nofollow noreferrer\">SharpDevelop</... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752/"
] | I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.
From what I've read this type of action could be handled by the [Command design pattern](http://www.dofactory.com/Patterns/PatternCommand.aspx) with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.
I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared? | Let's first make sure we know what the Command pattern is:
>
> Command pattern encapsulates a request
> as an object and gives it a known
> public interface. Command Pattern
> ensures that every object receives its
> own commands and provides a decoupling
> between sender and receiver. A sender
> is an object that invokes an
> operation, and a receiver is an object
> that receives the request and acts on
> it.
>
>
>
Here's an example for you. There are many ways you can do this, but I am going to take an interface base approach to make the code more testable for you. I am not sure what language you prefer, but I am writing this in C#.
First, create an interface that describes a Command.
```
public interface ICommand
{
void Execute();
}
```
Second, create command objects that will implement the command interface.
```
public class CutCommand : ICommand
{
public void Execute()
{
// Put code you like to execute when the CutCommand.Execute method is called.
}
}
```
Third, we need to setup our invoker or sender object.
```
public class TextOperations
{
public void Invoke(ICommand command)
{
command.Execute();
}
}
```
Fourth, create the client object that will use the invoker/sender object.
```
public class Client
{
static void Main()
{
TextOperations textOperations = new TextOperations();
textOperation.Invoke(new CutCommand());
}
}
```
I hope you can take this example and put it into use for the application you are working on. If you would like more clarification, just let me know. |
15,053 | <p>I'm trying to create a custom workflow action with an output parameter for error handling. Working from various examples, I can't get Parameter Direction="Out" to work. Everything seems right, but when I try to assign the output to the "error" variable in SharePoint Designer, it places asterisks around it and flags it as a workflow error. Here is what the action XML looks like:</p>
<pre><code><Action Name="Create Folder"
ClassName="ActivityLibrary.CreateFolderActivityTest"
Assembly="ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx"
AppliesTo="all"
CreatesInList="ListId"
Category="Custom">
<RuleDesigner Sentence="Create a folder %1 in the %2 base folder. If an error occurs it will be output to %3.">
<FieldBind Field="FolderName" Text="folder name" Id="1" />
<FieldBind Field="BaseFolderPath" Text="folder path" Id="2"/>
<FieldBind Field="OutError" DesignerType="ParameterNames" Text="out error" Id="3"/>
</RuleDesigner>
<Parameters>
<Parameter Name="FolderName" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="BaseFolderPath" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="OutError" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
</code></pre>
| [
{
"answer_id": 18993,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure the issue is with the parameters and not maybe the variable in SPD? Certainly nothing looks wrong with your XM... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1533/"
] | I'm trying to create a custom workflow action with an output parameter for error handling. Working from various examples, I can't get Parameter Direction="Out" to work. Everything seems right, but when I try to assign the output to the "error" variable in SharePoint Designer, it places asterisks around it and flags it as a workflow error. Here is what the action XML looks like:
```
<Action Name="Create Folder"
ClassName="ActivityLibrary.CreateFolderActivityTest"
Assembly="ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx"
AppliesTo="all"
CreatesInList="ListId"
Category="Custom">
<RuleDesigner Sentence="Create a folder %1 in the %2 base folder. If an error occurs it will be output to %3.">
<FieldBind Field="FolderName" Text="folder name" Id="1" />
<FieldBind Field="BaseFolderPath" Text="folder path" Id="2"/>
<FieldBind Field="OutError" DesignerType="ParameterNames" Text="out error" Id="3"/>
</RuleDesigner>
<Parameters>
<Parameter Name="FolderName" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="BaseFolderPath" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="OutError" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
``` | I think you may want Direction="InOut" from the looks of the binding |
15,056 | <p>What are some macros that you have found useful in Visual Studio for code manipulation and automation? </p>
| [
{
"answer_id": 15107,
"author": "RZachary",
"author_id": 1393,
"author_profile": "https://Stackoverflow.com/users/1393",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to add in code snippets as well, they help to speed up the development time and increase productivity.</p>... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | What are some macros that you have found useful in Visual Studio for code manipulation and automation? | This is one of the handy ones I use on HTML and XML files:
```
''''replaceunicodechars.vb
Option Strict Off
Option Explicit Off
Imports EnvDTE
Imports System.Diagnostics
Public Module ReplaceUnicodeChars
Sub ReplaceUnicodeChars()
DTE.ExecuteCommand("Edit.Find")
ReplaceAllChar(ChrW(8230), "…") ' ellipses
ReplaceAllChar(ChrW(8220), "“") ' left double quote
ReplaceAllChar(ChrW(8221), "”") ' right double quote
ReplaceAllChar(ChrW(8216), "‘") ' left single quote
ReplaceAllChar(ChrW(8217), "’") ' right single quote
ReplaceAllChar(ChrW(8211), "–") ' en dash
ReplaceAllChar(ChrW(8212), "—") ' em dash
ReplaceAllChar(ChrW(176), "°") ' °
ReplaceAllChar(ChrW(188), "¼") ' ¼
ReplaceAllChar(ChrW(189), "½") ' ½
ReplaceAllChar(ChrW(169), "©") ' ©
ReplaceAllChar(ChrW(174), "®") ' ®
ReplaceAllChar(ChrW(8224), "†") ' dagger
ReplaceAllChar(ChrW(8225), "‡") ' double-dagger
ReplaceAllChar(ChrW(185), "¹") ' ¹
ReplaceAllChar(ChrW(178), "²") ' ²
ReplaceAllChar(ChrW(179), "³") ' ³
ReplaceAllChar(ChrW(153), "™") ' ™
''ReplaceAllChar(ChrW(0), "�")
DTE.Windows.Item(Constants.vsWindowKindFindReplace).Close()
End Sub
Sub ReplaceAllChar(ByVal findWhat, ByVal replaceWith)
DTE.Find.FindWhat = findWhat
DTE.Find.ReplaceWith = replaceWith
DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
DTE.Find.MatchCase = False
DTE.Find.MatchWholeWord = False
DTE.Find.MatchInHiddenText = True
DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
DTE.Find.Execute()
End Sub
End Module
```
It's useful when you have to do any kind of data entry and want to escape everything at once. |
15,062 | <p>How do I convert function input parameters to the right type?</p>
<p>I want to return a string that has part of the URL passed into it removed.</p>
<p><strong>This works, but it uses a hard-coded string:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
</code></pre>
<p><strong>This fails:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
</code></pre>
| [
{
"answer_id": 15068,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function CleanUrl([string] $url)\n{\n return $url.Replace(\"http://\", \"\")\n}\n</code></pre>\n"
},
{
"answe... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | How do I convert function input parameters to the right type?
I want to return a string that has part of the URL passed into it removed.
**This works, but it uses a hard-coded string:**
```
function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
```
**This fails:**
```
function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
``` | The concept here is correct.
The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.
PowerShell does have [a replace operator](https://technet.microsoft.com/en-us/library/hh847759.aspx), so you could make your function into
```
function CleanUrl($url)
{
return $url -replace 'http://'
}
``` |
15,163 | <p>In some VB6 code, I have a handler for a TreeView's Collapse event:</p>
<pre><code>Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
</code></pre>
<p>This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.</p>
<p>I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along?</p>
| [
{
"answer_id": 15591,
"author": "Phil Bachmann",
"author_id": 1855,
"author_profile": "https://Stackoverflow.com/users/1855",
"pm_score": 2,
"selected": true,
"text": "<p>I think that like many events in VB, it can't be switched off.</p>\n\n<p>Just set a boolean flag as you've suggested.... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863/"
] | In some VB6 code, I have a handler for a TreeView's Collapse event:
```
Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
```
This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.
I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along? | I think that like many events in VB, it can't be switched off.
Just set a boolean flag as you've suggested. |
15,171 | <p>In the linux file system, where should user scripts be placed?</p>
<p>I'm thinking specifically python scripts to be called by cron.</p>
| [
{
"answer_id": 15177,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 4,
"selected": false,
"text": "<p>If you're talking about scripts created by a user that will be run from that users crontab, I typically put those in e... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] | In the linux file system, where should user scripts be placed?
I'm thinking specifically python scripts to be called by cron. | the information i got:
```
/usr/local/sbin custom script meant for root
/usr/local/bin custom script meant for all users including non-root
```
chatlog snips from irc.debian.org #debian:
```
(02:48:49) c33s: question: where is the _correct_ location, to put custom scripts
for the root user (like a script on a webserver for createing everything needed
for a new webuser)? is it /bin, /usr/local/bin,...? /usr/local/scripts is
mentioned in (*link to this page*)
(02:49:15) Hydroxide: c33s: typically /usr/local/sbin
(02:49:27) Hydroxide: c33s: no idea what /usr/local/scripts would be
(02:49:32) Hydroxide: it's nonstandard
(02:49:53) Hydroxide: if it's a custom script meant for all users including
non-root, then /usr/local/bin
(02:52:43) Hydroxide: c33s: Debian follows the Filesystem Hierarchy Standard,
with a very small number of exceptions, which is online in several formats at
http://www.pathname.com/fhs/ (also linked from http://www.debian.org/devel/ and
separately online at http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html)
(02:53:03) Hydroxide: c33s: if you have the debian-policy package installed, it's
also in several formats at /usr/share/doc/debian-policy/fhs/ on your system
(02:53:37) Hydroxide: c33s: most linux distributions follow that standard, though
usually less strictly and with more deviations than Debian.
```
thanks go out to Hydroxide |
15,204 | <p>What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?</p>
| [
{
"answer_id": 15210,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 6,
"selected": true,
"text": "<p>For C#:</p>\n\n<pre><code>foreach(ObjectType objectItem in objectTypeList)\n{\n // ...do some stuff\n}\n</code></pre>\n\n... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1224/"
] | What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET? | For C#:
```
foreach(ObjectType objectItem in objectTypeList)
{
// ...do some stuff
}
```
Answer for VB.NET from **Purple Ant**:
```
For Each objectItem as ObjectType in objectTypeList
'Do some stuff '
Next
``` |
15,219 | <p>I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.</p>
<p>I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this <a href="http://news.infragistics.com/forums/p/9063/45792.aspx" rel="nofollow noreferrer">discussion</a> with no luck.</p>
<p>What I'm doing so far:</p>
<pre><code>col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
</code></pre>
<p>where <code>myValueList</code> is:</p>
<pre><code>ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
</code></pre>
<p>When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty.</p>
| [
{
"answer_id": 16347,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example from one of my pages:</p>\n\n<pre><code>UltraWebGrid uwgMyGrid = new UltraWebGrid();\nuwgMyGrid.Columns.... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.
I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this [discussion](http://news.infragistics.com/forums/p/9063/45792.aspx) with no luck.
What I'm doing so far:
```
col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
```
where `myValueList` is:
```
ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
```
When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty. | I've found what was wrong.
The column must allow updates.
```
uwgMyGrid.Columns.FromKey("colTest").AllowUpdate = AllowUpdate.Yes;
``` |
15,240 | <p>I'd like to make a debug logging function with the same parameters as <code>printf</code>. But one that can be removed by the pre-processor during optimized builds.</p>
<p>For example:</p>
<pre><code>Debug_Print("Warning: value %d > 3!\n", value);
</code></pre>
<p>I've looked at variadic macros but those aren't available on all platforms. <code>gcc</code> supports them, <code>msvc</code> does not.</p>
| [
{
"answer_id": 15248,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>What platforms are they not available on? stdarg is part of the standard library:</p>\n\n<p><a href=\"http://www.opengroup.org/o... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I'd like to make a debug logging function with the same parameters as `printf`. But one that can be removed by the pre-processor during optimized builds.
For example:
```
Debug_Print("Warning: value %d > 3!\n", value);
```
I've looked at variadic macros but those aren't available on all platforms. `gcc` supports them, `msvc` does not. | I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:
```
#include <stdio.h>
void XTrace0(LPCTSTR lpszText)
{
::OutputDebugString(lpszText);
}
void XTrace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512]; // get rid of this hard-coded buffer
nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
::OutputDebugString(szBuffer);
va_end(args);
}
```
Then a typical #ifdef switch:
```
#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif
```
Well that can be cleaned up quite a bit but it's the basic idea. |
15,247 | <p>Given a list of locations such as</p>
<pre class="lang-html prettyprint-override"><code> <td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
</code></pre>
<p>What's the easiest way to generate a Google Map with pushpins for each location?</p>
| [
{
"answer_id": 15257,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 1,
"selected": false,
"text": "<p>I guess more information would be needed to really give you an answer, but over at Django Pluggables there is a <a href=\"http... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Given a list of locations such as
```html
<td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
```
What's the easiest way to generate a Google Map with pushpins for each location? | I'm assuming you have the basics for Maps in your code already with your API Key.
```
<head>
<script
type="text/javascript"
href="http://maps.google.com/maps?
file=api&v=2&key=xxxxx">
function createMap() {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.44, -122.14), 14);
}
</script>
</head>
<body onload="createMap()" onunload="GUnload()">
```
Everything in Google Maps is based off of latitude (lat) and longitude (lng).
So to create a simple marker you will just create a GMarker with the lat and lng.
```
var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA
var marker = new GMarker(where); // Create marker (Pinhead thingy)
map.setCenter(where); // Center map on marker
map.addOverlay(marker); // Add marker to map
```
However if you don't want to look up the Lat and Lng for each city you can use Google's Geo Coder. Heres an example:
```
var address = "El Cerrito, CA";
var geocoder = new GClientGeocoder;
geocoder.getLatLng(address, function(point) {
if (point) {
map.clearOverlays(); // Clear all markers
map.addOverlay(new GMarker(point)); // Add marker to map
map.setCenter(point, 10); // Center and zoom map on marker
}
});
```
So I would just create an array of GLatLng's of every city from the GeoCoder and then draw them on the map. |
15,254 | <p>Is it possible to actually make use of placement new in portable code when using it for arrays?</p>
<p>It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for the array to go in if this is the case.</p>
<p>The following example shows the problem. Compiled with Visual Studio, this example results in memory corruption:</p>
<pre><code>#include <new>
#include <stdio.h>
class A
{
public:
A() : data(0) {}
virtual ~A() {}
int data;
};
int main()
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = new(pBuffer) A[NUMELEMENTS];
// With VC++, pA will be four bytes higher than pBuffer
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// Debug runtime will assert here due to heap corruption
delete[] pBuffer;
return 0;
}
</code></pre>
<p>Looking at the memory, the compiler seems to be using the first four bytes of the buffer to store a count of the number of items in it. This means that because the buffer is only <code>sizeof(A)*NUMELEMENTS</code> big, the last element in the array is written into unallocated heap.</p>
<p>So the question is can you find out how much additional overhead your implementation wants in order to use placement new[] safely? Ideally, I need a technique that's portable between different compilers. Note that, at least in VC's case, the overhead seems to differ for different classes. For instance, if I remove the virtual destructor in the example, the address returned from new[] is the same as the address I pass in.</p>
| [
{
"answer_id": 15273,
"author": "Yossi Kreinin",
"author_id": 1648,
"author_profile": "https://Stackoverflow.com/users/1648",
"pm_score": 1,
"selected": false,
"text": "<p>I think gcc does the same thing as MSVC, but of course this doesn't make it \"portable\".</p>\n\n<p>I think you can ... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739/"
] | Is it possible to actually make use of placement new in portable code when using it for arrays?
It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for the array to go in if this is the case.
The following example shows the problem. Compiled with Visual Studio, this example results in memory corruption:
```
#include <new>
#include <stdio.h>
class A
{
public:
A() : data(0) {}
virtual ~A() {}
int data;
};
int main()
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = new(pBuffer) A[NUMELEMENTS];
// With VC++, pA will be four bytes higher than pBuffer
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// Debug runtime will assert here due to heap corruption
delete[] pBuffer;
return 0;
}
```
Looking at the memory, the compiler seems to be using the first four bytes of the buffer to store a count of the number of items in it. This means that because the buffer is only `sizeof(A)*NUMELEMENTS` big, the last element in the array is written into unallocated heap.
So the question is can you find out how much additional overhead your implementation wants in order to use placement new[] safely? Ideally, I need a technique that's portable between different compilers. Note that, at least in VC's case, the overhead seems to differ for different classes. For instance, if I remove the virtual destructor in the example, the address returned from new[] is the same as the address I pass in. | Personally I'd go with the option of not using placement new on the array and instead use placement new on each item in the array individually. For example:
```
int main(int argc, char* argv[])
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = (A*)pBuffer;
for(int i = 0; i < NUMELEMENTS; ++i)
{
pA[i] = new (pA + i) A();
}
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// dont forget to destroy!
for(int i = 0; i < NUMELEMENTS; ++i)
{
pA[i].~A();
}
delete[] pBuffer;
return 0;
}
```
Regardless of the method you use, make sure you manually destroy each of those items in the array before you delete pBuffer, as you could end up with leaks ;)
*Note*: I haven't compiled this, but I think it should work (I'm on a machine that doesn't have a C++ compiler installed). It still indicates the point :) Hope it helps in some way!
---
Edit:
The reason it needs to keep track of the number of elements is so that it can iterate through them when you call delete on the array and make sure the destructors are called on each of the objects. If it doesn't know how many there are it wouldn't be able to do this. |
15,266 | <p>Using <strong>NSURLRequest</strong>, I am trying to access a web site that has an expired certificate. When I send the request, my <strong>connection:didFailWithError</strong> delegate method is invoked with the following info:</p>
<pre><code>-1203, NSURLErrorDomain, bad server certificate
</code></pre>
<p>My searches have only turned up one solution: a hidden class method in NSURLRequest:</p>
<pre><code>[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:myHost];
</code></pre>
<p>However, I don't want to use private APIs in a production app for obvious reasons.</p>
<p>Any suggestions on what to do? Do I need to use CFNetwork APIs, and if so, two questions:</p>
<ul>
<li>Any sample code I can use to get started? I haven't found any online.</li>
<li>If I use CFNetwork for this, do I have to ditch NSURL entirely?</li>
</ul>
<hr>
<p>EDIT:</p>
<p>iPhone OS 3.0 introduced a supported method for doing this. More details here: <a href="https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert">How to use NSURLConnection to connect with SSL for an untrusted cert?</a></p>
| [
{
"answer_id": 15963,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "<p>I've hit the same issue - I was developing a SOAP client, and the dev server has a \"homegrown\" certificate. I w... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] | Using **NSURLRequest**, I am trying to access a web site that has an expired certificate. When I send the request, my **connection:didFailWithError** delegate method is invoked with the following info:
```
-1203, NSURLErrorDomain, bad server certificate
```
My searches have only turned up one solution: a hidden class method in NSURLRequest:
```
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:myHost];
```
However, I don't want to use private APIs in a production app for obvious reasons.
Any suggestions on what to do? Do I need to use CFNetwork APIs, and if so, two questions:
* Any sample code I can use to get started? I haven't found any online.
* If I use CFNetwork for this, do I have to ditch NSURL entirely?
---
EDIT:
iPhone OS 3.0 introduced a supported method for doing this. More details here: [How to use NSURLConnection to connect with SSL for an untrusted cert?](https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert) | iPhone OS 3.0 introduced a supported way of doing this that doesn't require the lower-level CFNetwork APIs. More details here:
[How to use NSURLConnection to connect with SSL for an untrusted cert?](https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert) |
15,272 | <p>I want a data structure that will allow querying <em>how many items in last <strong>X</strong> minutes</em>. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).</p>
<p>So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?</p>
<p>The other part that I'm interested in is <em>aging</em> old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program.</p>
| [
{
"answer_id": 15316,
"author": "dmo",
"author_id": 1807,
"author_profile": "https://Stackoverflow.com/users/1807",
"pm_score": 2,
"selected": false,
"text": "<p>I think that an important consideration will be the frequency of querying vs. adding/removing. If you will do frequent queryi... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] | I want a data structure that will allow querying *how many items in last **X** minutes*. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).
So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?
The other part that I'm interested in is *aging* old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program. | A simple linked list can be used for this.
Basically you add new items to the end, and remove too old items from the start, it is a cheap data structure.
example-code:
```
list.push_end(new_data)
while list.head.age >= age_limit:
list.pop_head()
```
If the list will be busy enough to warrant chopping off larger pieces than one at a time, then I agree with [dmo](https://stackoverflow.com/users/1807/dmo), use a tree structure or something similar that allows pruning on a higher level. |
15,310 | <p>First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.</p>
<p>At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API. </p>
<p>So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:</p>
<p>Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.</p>
<p>The web service call is something I'm sure you all have seen before: </p>
<pre><code>data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
</code></pre>
<p>The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.</p>
<p>Here are some of the more obvious things I've tried to get the report working via the web service API: </p>
<ul>
<li>set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server</li>
<li>disabled http keep alives on the report server</li>
<li>increased the script timeout on the report server</li>
<li>set the report to never time out on the server</li>
<li>set the report timeout to several hours on the client call </li>
</ul>
<p>From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated. </p>
<p>Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking. </p>
<ol>
<li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li>
<li>Is there a way to turn on response chunking for SSRS?</li>
<li>Does anyone else have any other theories as to why this runs on the server but not through the API?</li>
</ol>
<p>EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. </p>
| [
{
"answer_id": 16729,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>Does anyone know of anyway to\n reduce/optimize the PDF export phase\n and or the size of... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
] | First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.
At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API.
So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:
Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.
The web service call is something I'm sure you all have seen before:
```
data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
```
The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.
Here are some of the more obvious things I've tried to get the report working via the web service API:
* set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server
* disabled http keep alives on the report server
* increased the script timeout on the report server
* set the report to never time out on the server
* set the report timeout to several hours on the client call
From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated.
Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking.
1. Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?
2. Is there a way to turn on response chunking for SSRS?
3. Does anyone else have any other theories as to why this runs on the server but not through the API?
EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. | >
> 1. Does anyone know of anyway to
> reduce/optimize the PDF export phase
> and or the size of the PDF without
> lowering the total page count?
>
>
>
I have a few ideas and questions:
1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.
2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using [PDFSharp](http://pdfsharp.com/) after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.
>
> 3. Does anyone else have any other
> theories as to why this runs on the
> server but not through the API?
>
>
>
My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through.
You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).
Not solutions, per se, but ideas. Hope it helps. |
15,334 | <p>I have recently started using Vim as my text editor and am currently working on my own customizations.</p>
<p>I suppose keyboard mappings can do pretty much anything, but for the time being I'm using them as a sort of snippets facility almost exclusively.</p>
<p>So, for example, if I type <code>def{TAB}</code> (<code>:imap def{TAB} def ():<ESC>3ha</code>), it expands to:</p>
<pre><code>def |(): # '|' represents the caret
</code></pre>
<p>This works as expected, but I find it annoying when Vim waits for a full command while I'm typing a word containing "def" and am not interested in expanding it.</p>
<ul>
<li>Is there a way to avoid this or use this function more effectively to this end?</li>
<li>Is any other Vim feature better suited for this?</li>
</ul>
<hr>
<p>After taking a quick look at <a href="http://www.vim.org/scripts/script.php?script_id=1318" rel="noreferrer">SnippetsEmu</a>, it looks like it's the best option and much easier to customize than I first thought.</p>
<p>To continue with the previous example:</p>
<pre><code>:Snippet def <{}>():
</code></pre>
<p>Once defined, you can expand your snippet by typing <code>def{TAB}</code>.</p>
| [
{
"answer_id": 15886,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.vim.org/scripts/script.php?script_id=1318\" rel=\"nofollow noreferrer\">SnippetsEmu</a> is a useful sni... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] | I have recently started using Vim as my text editor and am currently working on my own customizations.
I suppose keyboard mappings can do pretty much anything, but for the time being I'm using them as a sort of snippets facility almost exclusively.
So, for example, if I type `def{TAB}` (`:imap def{TAB} def ():<ESC>3ha`), it expands to:
```
def |(): # '|' represents the caret
```
This works as expected, but I find it annoying when Vim waits for a full command while I'm typing a word containing "def" and am not interested in expanding it.
* Is there a way to avoid this or use this function more effectively to this end?
* Is any other Vim feature better suited for this?
---
After taking a quick look at [SnippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318), it looks like it's the best option and much easier to customize than I first thought.
To continue with the previous example:
```
:Snippet def <{}>():
```
Once defined, you can expand your snippet by typing `def{TAB}`. | [SnippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318) is a useful snippets plugin. |
15,390 | <p>What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.</p>
<p>Our JavaScript code is roughly "namespaced" as:</p>
<pre><code>var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
</code></pre>
<p>At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes <em>forever</em> to find anything in the JavaScript code and the browser still has a dozen files to download.</p>
<p>Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?</p>
| [
{
"answer_id": 15402,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 5,
"selected": true,
"text": "<p>The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and oth... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1848/"
] | What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
Our JavaScript code is roughly "namespaced" as:
```
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
```
At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes *forever* to find anything in the JavaScript code and the browser still has a dozen files to download.
Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices? | The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a `<script src='/path/to/js/$file.js' type='text/javascript'>` in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.
When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down. |
15,395 | <p>Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.</p>
<p>The SQL Server 2008 spec sheet promises even better integration - but I can't see it.</p>
<p>What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005?</p>
| [
{
"answer_id": 15431,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>it has full support for the new data types. lol. beyond that you got me, other than possibilities of optimised queries (li... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855/"
] | Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.
The SQL Server 2008 spec sheet promises even better integration - but I can't see it.
What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005? | There is a problem of paging over a joined set that SQL 2005 mis-interprets.
```
var orders = (
from c in Customers
from o in c.Orders
select new {c, o}
).Skip(10).Take(10).ToList();
```
LINQ generates a ROW\_Number against the joined set. SQL2005 generates a bad plan from that code. Here's a link to the [discussion](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3091519&SiteID=1).
Edit#2: I'd like to clarify that I don't know that SQL2008 solves this problem. I'm just hopeful. |
15,399 | <p>My firm have a talented and smart operations staff who are working very hard. I'd like to give them a SQL-execution tool that helps them avoid common, easily-detected SQL mistakes that are easy to make when they are in a hurry. Can anyone suggest such a tool? Details follow.</p>
<p>Part of the operations team remit is writing very complex ad-hoc SQL queries. Not surprisingly, operators sometimes make mistakes in the queries they write because they are so busy. </p>
<p>Luckily, their queries are all SELECTs not data-changing SQL, and they are running on a copy of the database anyway. Still, we'd like to prevent errors in the SQL they run. For instance, sometimes the mistakes lead to long-running queries that slow down the duplicate system they're using and inconvenience others until we find the culprit query and kill it. Worse, occasionally the mistakes lead to apparently-correct answers that we don't catch until much later, with consequent embarrassment. </p>
<p>Our developers also make mistakes in complex code that they write, but they have Eclipse and various plugins (such as <a href="http://findbugs.sourceforge.net/" rel="nofollow noreferrer" title="FindBugs">FindBugs</a>) that catch errors as they type. I'd like to give operators something similar - ideally it would see</p>
<pre><code>SELECT U.NAME, C.NAME FROM USER U, COMPANY C WHERE U.NAME = 'ibell';
</code></pre>
<p>and before you executed, it would say "Hey, did you realise that's a Cartesian product? Are you sure you want to do that?" It doesn't have to be very smart - finding obviously missing join conditions and similar evident errors would be fine.</p>
<p>It looks like <a href="http://www.toadsoft.com/" rel="nofollow noreferrer" title="TOAD">TOAD</a> should do this but I can't seem to find anything about such a feature. Are there other tools like TOAD that can provide this kind of semi-intelligent error correction?</p>
<p>Update: I forgot to mention that we're using MySQL.</p>
| [
{
"answer_id": 15405,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>You might find <a href=\"http://www.red-gate.com/Products/SQL_Prompt/index.htm\" rel=\"nofollow noreferrer\">SQL Prompt</a> f... | 2008/08/18 | [
"https://Stackoverflow.com/questions/15399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My firm have a talented and smart operations staff who are working very hard. I'd like to give them a SQL-execution tool that helps them avoid common, easily-detected SQL mistakes that are easy to make when they are in a hurry. Can anyone suggest such a tool? Details follow.
Part of the operations team remit is writing very complex ad-hoc SQL queries. Not surprisingly, operators sometimes make mistakes in the queries they write because they are so busy.
Luckily, their queries are all SELECTs not data-changing SQL, and they are running on a copy of the database anyway. Still, we'd like to prevent errors in the SQL they run. For instance, sometimes the mistakes lead to long-running queries that slow down the duplicate system they're using and inconvenience others until we find the culprit query and kill it. Worse, occasionally the mistakes lead to apparently-correct answers that we don't catch until much later, with consequent embarrassment.
Our developers also make mistakes in complex code that they write, but they have Eclipse and various plugins (such as [FindBugs](http://findbugs.sourceforge.net/ "FindBugs")) that catch errors as they type. I'd like to give operators something similar - ideally it would see
```
SELECT U.NAME, C.NAME FROM USER U, COMPANY C WHERE U.NAME = 'ibell';
```
and before you executed, it would say "Hey, did you realise that's a Cartesian product? Are you sure you want to do that?" It doesn't have to be very smart - finding obviously missing join conditions and similar evident errors would be fine.
It looks like [TOAD](http://www.toadsoft.com/ "TOAD") should do this but I can't seem to find anything about such a feature. Are there other tools like TOAD that can provide this kind of semi-intelligent error correction?
Update: I forgot to mention that we're using MySQL. | If your people are using the mysql(1) program to run queries, you can use the [safe-updates](http://dev.mysql.com/doc/refman/5.1/en/mysql-tips.html) option (aka i-am-a-dummy) to get you part of what you need. Its name is somewhat misleading; it not only prevents UPDATE and DELETE without a WHERE (which you're not worried about), but also adds an implicit LIMIT 1000 to SELECT statements, and aborts SELECTs that have joins and are estimated to consider over 1,000,000 tuples --- perfect for discouraging Cartesian joins. |
15,470 | <p>I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need?</p>
| [
{
"answer_id": 15474,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": true,
"text": "<p>Just change \"Home\" to an empty string.</p>\n\n<pre><code>routes.MapRoute(\n \"Home\",\n \"\",\n new { action = ... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692/"
] | I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need? | Just change "Home" to an empty string.
```
routes.MapRoute(
"Home",
"",
new { action = Index, controller = Home }
);
``` |
15,478 | <p>GDI+ DrawLines function has a clipping bug that can be reproduced by running the following c# code. When running the code, two line paths appear, that should be identical, because both of them are inside the clipping region. But when the clipping region is set, one of the line segment is not drawn. </p>
<pre><code>protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle(70, 32, 20, 164);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
</code></pre>
<p>Setting the antials mode on the graphics object resolves this. But that is not a real solution.</p>
<p>Does anybody know of a workaround?</p>
| [
{
"answer_id": 15813,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>What appears to be the matter with the code?</p>\n\n<p>OK, the question should be... what should the code do that it doesn't a... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873/"
] | GDI+ DrawLines function has a clipping bug that can be reproduced by running the following c# code. When running the code, two line paths appear, that should be identical, because both of them are inside the clipping region. But when the clipping region is set, one of the line segment is not drawn.
```
protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle(70, 32, 20, 164);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
```
Setting the antials mode on the graphics object resolves this. But that is not a real solution.
Does anybody know of a workaround? | It appears that this is a known bug...
The following code appears to function as you requested:
```
protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Rectangle b = new Rectangle(70, 32, 20, 165);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
```
Note: I have AntiAlias'ed the line and extended your clipping region by 1
it appears that the following work arounds might help (although not tested):
* The pen is more than one pixel thick
* The line is perfectly horizontal or vertical
* The clipping is against the window boundaries rather than a clip rectangle
The following is a list of articles that might / or then again might not help:
<http://www.tech-archive.net/pdf/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0350.pdf>
<http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0368.html>
OR...
the following is also possible:
```
protected override void OnPaint ( PaintEventArgs e )
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle( 70, 32, 20, 164 );
Region reg = new Region( b );
e.Graphics.SetClip( reg, System.Drawing.Drawing2D.CombineMode.Union);
e.Graphics.DrawLines( Pens.Red, points ); // clipped incorrectly
e.Graphics.TranslateTransform( 80, 0 );
e.Graphics.ResetClip();
e.Graphics.DrawLines( Pens.Red, points );
}
```
This effecivly clips using a region combined/unioned (I think) with the ClientRectangle of the canvas/Control. As the region is difned from the rectangle, the results should be what is expected. This code can be proven to work by adding
```
e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );
```
after the setClip() call. This clearly shows the black rectangle only appearing in the clipped region.
This could be a valid workaround if Anti-Aliasing the line is not an option.
Hope this helps |
15,481 | <p>Sometimes a labeled break or continue can make code a lot more readable. </p>
<pre><code>OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
</code></pre>
<p>I was wondering what the common convention for the labels was. All caps? first cap? </p>
| [
{
"answer_id": 15501,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 4,
"selected": false,
"text": "<p>The convention is to avoid labels altogether.</p>\n\n<p>There are very, very few valid reasons to use a label for breakin... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | Sometimes a labeled break or continue can make code a lot more readable.
```
OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
```
I was wondering what the common convention for the labels was. All caps? first cap? | If you have to use them use capitals, this draws attention to them and singles them out from being mistakenly interpreted as "Class" names. Drawing attention to them has the additional benefit of catching someone's eye that will come along and refactor your code and remove them. ;) |
15,486 | <p>So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.</p>
<p>Turns out the IList interface doesn't have a sort method built in. </p>
<p>I ended up using the <code>ArrayList.Adapter(list).Sort(new MyComparer())</code> method to solve the problem but it just seemed a bit "ghetto" to me.</p>
<p>I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.</p>
<p>So my question is, does anyone have an elegant solution to sorting an IList</p>
| [
{
"answer_id": 15491,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 3,
"selected": false,
"text": "<p>You're going to have to do something like that i think (convert it into a more concrete type).</p>\n\n<p>Maybe take it i... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.
Turns out the IList interface doesn't have a sort method built in.
I ended up using the `ArrayList.Adapter(list).Sort(new MyComparer())` method to solve the problem but it just seemed a bit "ghetto" to me.
I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.
So my question is, does anyone have an elegant solution to sorting an IList | How about using LINQ To Objects to sort for you?
Say you have a `IList<Car>`, and the car had an `Engine` property, I believe you could sort as follows:
```
from c in list
orderby c.Engine
select c;
```
*Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.* |
15,514 | <p>In my example below I'm using a <code>dijit.form.DateTextBox</code>:</p>
<pre><code><input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
</code></pre>
<p>So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying <code>The value entered is not valid.</code>. Even if I remove the <code>constraints="{datePattern:'MM/dd/yyyy'}"</code> it still validates. </p>
<p>Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.</p>
| [
{
"answer_id": 15532,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to k... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700/"
] | In my example below I'm using a `dijit.form.DateTextBox`:
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
```
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying `The value entered is not valid.`. Even if I remove the `constraints="{datePattern:'MM/dd/yyyy'}"` it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances. | Try overriding the validate method in your markup.
This will work (just tested):
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
``` |
15,593 | <p>I understand what <a href="http://msdn.microsoft.com/en-us/library/ms404247.aspx" rel="noreferrer">System.WeakReference</a> does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get <i>farther</i> away from this type of behavior and use of this class? </p>
| [
{
"answer_id": 15616,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p>I use it to implement a cache where unused entries are automatically garbage collected:</p>\n\n<pre><code>class Cache&... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1875/"
] | I understand what [System.WeakReference](http://msdn.microsoft.com/en-us/library/ms404247.aspx) does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get *farther* away from this type of behavior and use of this class? | One useful example is the guys who run DB4O object oriented database. There, WeakReferences are used as a kind of light cache: it will keep your objects in memory only as long as your application does, allowing you to put a real cache on top.
Another use would be in the implementation of weak event handlers. Currently, one big source of memory leaks in .NET applications is forgetting to remove event handlers. E.g.
```
public MyForm()
{
MyApplication.Foo += someHandler;
}
```
See the problem? In the above snippet, MyForm will be kept alive in memory forever as long as MyApplication is alive in memory. Create 10 MyForms, close them all, your 10 MyForms will still be in memory, kept alive by the event handler.
Enter WeakReference. You can build a weak event handler using WeakReferences so that someHandler is a weak event handler to MyApplication.Foo, thus fixing your memory leaks!
This isn't just theory. Dustin Campbell from the DidItWith.NET blog posted [an implementation of weak event handlers](http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx) using System.WeakReference. |
15,656 | <p>Another SSRS question here: <br />
We have a development, a QA, a Prod-Backup and a Production SSRS set of servers. <br />
On our production and prod-backup, SSRS will go to sleep if not used for a period of time. <br /><br />
This does not occur on our development or QA server.
<br />In the corporate environment we're in, we don't have physical (or even remote login) access to these machines, and have to work with a team of remote administrators to configure our SSRS application.<br />
<br /> We have asked that they fix, if possible, this issue. So far, they haven't been able to identify the issue, and I would like to know if any of my peers know the answer to this question. Thanks.</p>
| [
{
"answer_id": 15659,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>I vaguely recall having problems with SSRS on one machine when we changed the \"Enable HTTP Keep-Alives\" setting in I... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580/"
] | Another SSRS question here:
We have a development, a QA, a Prod-Backup and a Production SSRS set of servers.
On our production and prod-backup, SSRS will go to sleep if not used for a period of time.
This does not occur on our development or QA server.
In the corporate environment we're in, we don't have physical (or even remote login) access to these machines, and have to work with a team of remote administrators to configure our SSRS application.
We have asked that they fix, if possible, this issue. So far, they haven't been able to identify the issue, and I would like to know if any of my peers know the answer to this question. Thanks. | For anybody using the integrated webserver that is built into SQL Reporting Services (and hence IIS may not even be installed on the box), the setting to control this actually lives in:
```
C:\Program Files\Microsoft SQL Server\
MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config
```
Your directory may be different; version 10\_50 maps to SQL 2008 R2.
You'll be looking for the setting called `RecycleTime`.
Default is 720 (12 hours). Setting it to 0 will disable. |
15,674 | <p>When using Subversion (svn) for source control with multiple projects I've noticed that the revision number increases across all of my projects' directories. To illustrate my svn layout (using fictitious project names): </p>
<pre>
/NinjaProg/branches
/tags
/trunk
/StealthApp/branches
/tags
/trunk
/SnailApp/branches
/tags
/trunk
</pre>
<p>When I perform a commit to the trunk of the Ninja Program, let's say I get that it has been updated to revision 7. The next day let's say that I make a small change to the Stealth Application and it comes back as revision 8.</p>
<p>The question is this: <strong>Is it common accepted practice to, when maintaining multiple projects with one Subversion server, to have unrelated projects' revision number increase across all projects?</strong> Or am I doing it wrong and should be creating individual repositories for each project? Or is it something else entirely?</p>
<p><strong>EDIT:</strong> I delayed in flagging an answer because it had become clear that there are reasons for both approaches, and even though this question came first, I'd like to point to some other questions that are ultimately asking the same question: </p>
<p><a href="https://stackoverflow.com/questions/130447/should-i-store-all-projects-in-one-repository-or-mulitiple">Should I store all projects in one repository or mulitiple?</a></p>
<p><a href="https://stackoverflow.com/questions/252459/one-svn-repository-or-many">One SVN Repository or many?</a> </p>
| [
{
"answer_id": 15676,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 2,
"selected": false,
"text": "<p>This is due to how subversion works. Each revision is really a snapshot of the repository identified by that revision nu... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | When using Subversion (svn) for source control with multiple projects I've noticed that the revision number increases across all of my projects' directories. To illustrate my svn layout (using fictitious project names):
```
/NinjaProg/branches
/tags
/trunk
/StealthApp/branches
/tags
/trunk
/SnailApp/branches
/tags
/trunk
```
When I perform a commit to the trunk of the Ninja Program, let's say I get that it has been updated to revision 7. The next day let's say that I make a small change to the Stealth Application and it comes back as revision 8.
The question is this: **Is it common accepted practice to, when maintaining multiple projects with one Subversion server, to have unrelated projects' revision number increase across all projects?** Or am I doing it wrong and should be creating individual repositories for each project? Or is it something else entirely?
**EDIT:** I delayed in flagging an answer because it had become clear that there are reasons for both approaches, and even though this question came first, I'd like to point to some other questions that are ultimately asking the same question:
[Should I store all projects in one repository or mulitiple?](https://stackoverflow.com/questions/130447/should-i-store-all-projects-in-one-repository-or-mulitiple)
[One SVN Repository or many?](https://stackoverflow.com/questions/252459/one-svn-repository-or-many) | I am surprised no has mentioned that this is discussed in Version Control with Subversion, which is available free online, [here](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.planning.html).
I read up on the issue awhile back and it really seems like a matter of personal choice, there is a good blog post on the subject [here](http://blogs.open.collab.net/svn/2007/04/single_reposito.html). EDIT: *Since the blog appears to be down, ([archived version here](http://replay.web.archive.org/20090228154135/http://blogs.open.collab.net/svn/2007/04/single_reposito.html)), here is some of what Mark Phippard had to say on the subject.*
>
> These are some of the advantages of the single repository approach.
>
>
> 1. Simplified administration. One set of hooks to deploy. One repository to backup. etc.
> 2. Branch/tag flexibility. With the code all in one repository it makes it easier to create a branch or tag involving multiple projects.
> 3. Move code easily. Perhaps you want to take a section of code from one project and use it in another, or turn it into a library for several projects. It is easy to move the code within the same repository and retain the history of the code in the process.
>
>
> Here are some of the drawbacks to the single repository approach, advantages to the multiple repository approach.
>
>
> 1. Size. It might be easier to deal with many smaller repositories than one large one. For example, if you retire a project you can just archive the repository to media and remove it from the disk and free up the storage. Maybe you need to dump/load a repository for some reason, such as to take advantage of a new Subversion feature. This is easier to do and with less impact if it is a smaller repository. Even if you eventually want to do it to all of your repositories, it will have less impact to do them one at a time, assuming there is not a pressing need to do them all at once.
> 2. Global revision number. Even though this should not be an issue, some people perceive it to be one and do not like to see the revision number advance on the repository and for inactive projects to have large gaps in their revision history.
> 3. Access control. While Subversion's authz mechanism allows you to restrict access as needed to parts of the repository, it is still easier to do this at the repository level. If you have a project that only a select few individuals should access, this is easier to do with a single repository for that project.
> 4. Administrative flexibility. If you have multiple repositories, then it is easier to implement different hook scripts based on the needs of the repository/projects. If you want uniform hook scripts, then a single repository might be better, but if each project wants its own commit email style then it is easier to have those projects in separate repositories
>
>
>
When you really think about, the revision numbers in a multiple project repository are going to get high, but you are not going to run out. Keep in mind that you can view a history on a sub directory and quickly see all the revision numbers that pertain to a project. |
15,700 | <p>I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a *.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.</p>
<p>Now, I found this work-around:</p>
<pre><code>Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
</code></pre>
<p>And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle.</p>
| [
{
"answer_id": 15704,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a winforms app you could try using <a href=\"http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886/"
] | I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a \*.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.
Now, I found this work-around:
```
Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
```
And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle. | If you're using a winforms app you could try using [UserProperties](http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx) to store this info. Another possible solution could be [custom configuration sections](http://msdn.microsoft.com/en-us/library/2tw134k3.aspx). |
15,709 | <p>So for my text parsing in C# <a href="https://stackoverflow.com/questions/13963/best-method-of-textfile-parsing-in-c">question</a>, I got directed at YAML. I'm hitting a wall with this library I was recommended, so this is a quickie.</p>
<pre><code>heading:
name: A name
taco: Yes
age: 32
heading:
name: Another name
taco: No
age: 27
</code></pre>
<p>And so on. Is that valid?</p>
| [
{
"answer_id": 15723,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>There appears to be a YAML validator called <a href=\"http://www.kuwata-lab.com/kwalify/\" rel=\"nofollow noreferrer\">K... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So for my text parsing in C# [question](https://stackoverflow.com/questions/13963/best-method-of-textfile-parsing-in-c), I got directed at YAML. I'm hitting a wall with this library I was recommended, so this is a quickie.
```
heading:
name: A name
taco: Yes
age: 32
heading:
name: Another name
taco: No
age: 27
```
And so on. Is that valid? | Partially. YAML supports the notion of multiple consecutive "documents". If this is what you are trying to do here, then yes, it is correct - you have two documents (or document fragments). To make it more explicit, you should separate them with three dashes, like this:
```
---
heading:
name: A name
taco: Yes
age: 32
---
heading:
name: Another name
taco: No
age: 27
```
On the other hand if you wish to make them part of the same document (so that deserializing them would result in a list with two elements), you should write it like the following. Take extra care with the indentation level:
```
- heading:
name: A name
taco: Yes
age: 32
- heading:
name: Another name
taco: No
age: 27
```
In general YAML is concise and human readable / editable, but not really human writable, so you should always use libraries to generate it. Also, take care that there exists some breaking changes between different versions of YAML, which can bite you if you are using libraries in different languages which conform to different versions of the standard. |
15,716 | <p>I have created a UserControl that has a <code>ListView</code> in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the <code>ListView</code> though the property, the <code>ListView</code> stays that way until I compile again and it reverts back to the default state. </p>
<p>How do I get my design changes to stick for the <code>ListView</code>?</p>
| [
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Just so I'm clear, you've done something like this, right?</p>\n\n<pre><code>public ListView MyListView { get { return... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788/"
] | I have created a UserControl that has a `ListView` in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the `ListView` though the property, the `ListView` stays that way until I compile again and it reverts back to the default state.
How do I get my design changes to stick for the `ListView`? | You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ListView MyListView { get { return this.listView1; } }
```
This tells the designer's code generator to output code for it. |
15,729 | <p>As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.</p>
<p>It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds. </p>
<p>Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.</p>
<p>Code snippets would also be helpful where applicable..</p>
| [
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Just so I'm clear, you've done something like this, right?</p>\n\n<pre><code>public ListView MyListView { get { return... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.
It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds.
Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.
Code snippets would also be helpful where applicable.. | You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ListView MyListView { get { return this.listView1; } }
```
This tells the designer's code generator to output code for it. |
15,732 | <p>I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform?</p>
| [
{
"answer_id": 15739,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "<p>Here's how to do it using <a href=\"http://xerces.apache.org/xerces2-j/\" rel=\"noreferrer\">Xerces2</a>. A tutorial for this... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650/"
] | I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform? | The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a [javax.xml.validation.Validator](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html).
```
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd:
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}
```
The schema factory constant is the string `http://www.w3.org/2001/XMLSchema` which defines XSDs. The above code validates a WAR deployment descriptor against the URL `http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd` but you could just as easily validate against a local file.
You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them. |
15,744 | <p>I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?</p>
<blockquote>
<p>Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?</p>
</blockquote>
| [
{
"answer_id": 15749,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 1,
"selected": false,
"text": "<p>Well, defines are used often for compile time constants and macros. This can make your code a bit faster as there are reall... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] | I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?
>
> Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?
>
>
> | In C# `#define` macros, like some of Bernard's examples, are not allowed. The only common use of `#define`/`#if`s in C# is for adding optional debug only code. For example:
```
static void Main(string[] args)
{
#if DEBUG
//this only compiles if in DEBUG
Console.WriteLine("DEBUG")
#endif
#if !DEBUG
//this only compiles if not in DEBUG
Console.WriteLine("RELEASE")
#endif
//This always compiles
Console.ReadLine()
}
``` |
15,774 | <p>I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better?</p>
<p>When I build the site (using <a href="http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx" rel="nofollow noreferrer">Web Deployment Projects</a>), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project. </p>
<p>I'm also looking toward this type of solution to automatically increment build and version numbers.</p>
| [
{
"answer_id": 15780,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 1,
"selected": false,
"text": "<p>CruiseControl.NET solves a different problem (continuous integration) ... however, I've had great success with NAnt for s... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] | I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better?
When I build the site (using [Web Deployment Projects](http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx)), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project.
I'm also looking toward this type of solution to automatically increment build and version numbers. | Here's an example of a Web Deployment Project scripting this sort of task in the .wdproj file:
```
<Target Name="AfterBuild">
<!-- ============================ Script Compression============================ -->
<MakeDir Directories="$(OutputPath)\compressed" />
<Exec Command="java -jar c:\yuicompressor-2.2.5\build\yuicompressor-2.2.5.jar --charset UTF-8 styles.css -o compressed/styles.css" WorkingDirectory="$(OutputPath)" />
<Exec Command="move /Y .\compressed\* .\" WorkingDirectory="$(OutputPath)" />
<RemoveDir Directories="$(OutputPath)\sql" />
<Exec Command="c:\7zip-4.4.2\7za.exe a $(ZipName).zip $(OutputPath)\*" />
</Target>
```
This would allow you to delete a folder.
(I suspect that if you wanted to not have the folder copy over *at all*, the solution file would be the place to specify that, though I haven't had to use that.) |
15,798 | <p>I need to validate an XML string (and not a file)
against a DTD description file. </p>
<p>How can that be done in <code>python</code>?</p>
| [
{
"answer_id": 15931,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 6,
"selected": true,
"text": "<p>Another good option is <a href=\"http://lxml.de/validation.html\" rel=\"noreferrer\">lxml's validation</a> which I fin... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446497/"
] | I need to validate an XML string (and not a file)
against a DTD description file.
How can that be done in `python`? | Another good option is [lxml's validation](http://lxml.de/validation.html) which I find quite pleasant to use.
A simple example taken from the lxml site:
```
from StringIO import StringIO
from lxml import etree
dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True
root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
``` |
15,816 | <p>I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.</p>
<p>Is there any good way to resize a VNC session on the fly?</p>
<p>My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64.</p>
| [
{
"answer_id": 15824,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know there's no way to change the client's resolution just using VNC, as it is just a \"monitor mirroring\" applica... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.
Is there any good way to resize a VNC session on the fly?
My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64. | Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:
```
vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768
```
Then resize with:
```
xrandr -s 1600x1200
xrandr -s 1440x900
xrandr -s 1024x768
``` |
15,828 | <p>Is there a free or open source library to read Excel files (.xls) directly from a C# program? </p>
<p>It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.</p>
| [
{
"answer_id": 15835,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 1,
"selected": false,
"text": "<p>you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manu... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | Is there a free or open source library to read Excel files (.xls) directly from a C# program?
It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step. | ```
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
DataTable data = ds.Tables["anyNameHere"];
```
This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables:
```
var data = ds.Tables["anyNameHere"].AsEnumerable();
```
as this lets me use LINQ to search and build structs from the fields.
```
var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
new MyContact
{
firstName= x.Field<string>("First Name"),
lastName = x.Field<string>("Last Name"),
phoneNumber =x.Field<string>("Phone Number"),
});
``` |
15,838 | <p>Can the performance of this sequential search algorithm (taken from
<a href="http://books.google.co.uk/books?id=to6M9_dbjosC&dq=the+practice+of+programming&pg=PP1&ots=3YH6Ggq0_a&sig=F2-ajdO37xA4iRec2sCyQF55Jjc&hl=en&sa=X&oi=book_result&resnum=1&ct=result" rel="noreferrer">The Practice of Programming</a>) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?</p>
<pre><code>int lookup(char *word, char*array[])
{
int i
for (i = 0; array[i] != NULL; i++)
if (strcmp(word, array[i]) == 0)
return i;
return -1;
}
</code></pre>
| [
{
"answer_id": 15846,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for exa... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] | Can the performance of this sequential search algorithm (taken from
[The Practice of Programming](http://books.google.co.uk/books?id=to6M9_dbjosC&dq=the+practice+of+programming&pg=PP1&ots=3YH6Ggq0_a&sig=F2-ajdO37xA4iRec2sCyQF55Jjc&hl=en&sa=X&oi=book_result&resnum=1&ct=result)) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?
```
int lookup(char *word, char*array[])
{
int i
for (i = 0; array[i] != NULL; i++)
if (strcmp(word, array[i]) == 0)
return i;
return -1;
}
``` | Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for example keeping the list sorted and doing a binary search).
In general optimizing a given algorithm only gets you so far. Choosing a better algorithm (even if it's not completely optimized) can give you a considerable (order of magnitude) performance improvement. |
15,851 | <p>After I was convinced that labeled breaks/continues are a total "nono" over <a href="https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501">here</a>, I need help to remove the label out of my code.</p>
<p>I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.</p>
<p>I hope, the code-fragment is basically understandable… </p>
<pre><code>vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;
matrixLoop:
for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
}
setValueInVector( v, idx );
}
</code></pre>
<p>Please convince me, that there is a more readable/better version without the labels.</p>
| [
{
"answer_id": 15855,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>Easily, my good man.</p>\n\n<pre><code>for( int idx = 0; idx < vectorLength; idx++) {\n if( conditionAtVectorPosition( v... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | After I was convinced that labeled breaks/continues are a total "nono" over [here](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501), I need help to remove the label out of my code.
I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.
I hope, the code-fragment is basically understandable…
```
vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;
matrixLoop:
for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
}
setValueInVector( v, idx );
}
```
Please convince me, that there is a more readable/better version without the labels. | Looking at the solutions presented so far:
* They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself
* Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.
* Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.
* Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed.
All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn't need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule. |
15,899 | <p>I have a <code>XmlDocument</code> in java, created with the <code>Weblogic XmlDocument</code> parser.</p>
<p>I want to replace the content of a tag in this <code>XMLDocument</code> with my own data, or insert the tag if it isn't there.</p>
<pre><code><customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
</code></pre>
<p>For example I want to insert a URL in the location tag:</p>
<pre><code><location>http://something</location>
</code></pre>
<p>but otherwise leave the XML as is.</p>
<p>Currently I use a <code>XMLCursor</code>:</p>
<pre><code> XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
</code></pre>
<p>I tried to find a "quick" <code>xquery</code> way to do this since the <code>XmlDocument</code> has an <code>execQuery</code> method, but didn't find it very easy. </p>
<p>Do anyone have a better way than this? It seems a bit elaborate.</p>
| [
{
"answer_id": 15961,
"author": "alanl",
"author_id": 1464,
"author_profile": "https://Stackoverflow.com/users/1464",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to do this with <code>query</code></p>\n\n<p>try </p>\n\n<pre><code> fn:replace(string,pattern,replace)\n... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] | I have a `XmlDocument` in java, created with the `Weblogic XmlDocument` parser.
I want to replace the content of a tag in this `XMLDocument` with my own data, or insert the tag if it isn't there.
```
<customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
```
For example I want to insert a URL in the location tag:
```
<location>http://something</location>
```
but otherwise leave the XML as is.
Currently I use a `XMLCursor`:
```
XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
```
I tried to find a "quick" `xquery` way to do this since the `XmlDocument` has an `execQuery` method, but didn't find it very easy.
Do anyone have a better way than this? It seems a bit elaborate. | How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.
If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:
```
// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );
for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
Node customDataNode = customDataNodeSet.item( i );
// get the location nodes (if any) within this one customdata node
NodeList locationNodeSet = findNodes(customDataNode, "location" );
if (locationNodeSet.getLength() > 0) {
// replace
locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
}
else {
// insert
Element newLocationNode = document.createElement( "location" );
newLocationNode.setTextContent("http://stackoverflow.com/" );
customDataNode.appendChild( newLocationNode );
}
}
```
And here's the helper method findNodes that does the XPath search.
```
private NodeList findNodes( Object obj, String xPathString )
throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile( xPathString );
return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}
``` |
15,949 | <p>I have a tomcat instance setup but the database connection I have configured in <code>context.xml</code> keeps dying after periods of inactivity.</p>
<p>When I check the logs I get the following error:</p>
<p>com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.</p>
<p>Here is the configuration in context.xml:</p>
<pre><code><Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&amp;useEncoding=true&amp;characterEncoding=UTF-8" />
</code></pre>
<p>I am using <code>autoReconnect=true</code> like the error says to do, but the connection keeps dying. I have never seen this happen before.</p>
<p>I have also verified that all database connections are being closed properly.</p>
| [
{
"answer_id": 16168,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html\" rel=\"noreferrer\">Tomcat Documen... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22/"
] | I have a tomcat instance setup but the database connection I have configured in `context.xml` keeps dying after periods of inactivity.
When I check the logs I get the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait\_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.
Here is the configuration in context.xml:
```
<Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&useEncoding=true&characterEncoding=UTF-8" />
```
I am using `autoReconnect=true` like the error says to do, but the connection keeps dying. I have never seen this happen before.
I have also verified that all database connections are being closed properly. | [Tomcat Documentation](http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html)
DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:
```
* Jakarta-Commons DBCP
* Jakarta-Commons Collections
* Jakarta-Commons Pool
```
This attribute may help you out.
```
removeAbandonedTimeout="60"
```
I'm using the same connection pooling stuff and I'm setting these properties to prevent the same thing it's just not configured through tomcat.
But if the first thing doesn't work try these.
```
testWhileIdle=true
timeBetweenEvictionRunsMillis=300000
``` |
15,954 | <p>How can a <code>sdbm</code> hash function (such as <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow noreferrer">this</a>) be implemented in C# ?</p>
| [
{
"answer_id": 15971,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 2,
"selected": false,
"text": "<p>You can take the C code almost without changes:</p>\n\n<pre><code>uint sdbm( string str )\n{\n uint hash = 0;\n foreac... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658/"
] | How can a `sdbm` hash function (such as [this](http://www.cse.yorku.ca/~oz/hash.html)) be implemented in C# ? | You can take the C code almost without changes:
```
uint sdbm( string str )
{
uint hash = 0;
foreach( char ch in str )
{
hash = ch + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
```
Or did you think of something more sophisticated? |
15,979 | <p>I use solr to search for documents and when trying to search for documents using this query "<code>id:*</code>", I get this query parser exception telling that it cannot parse the query with * or ? as the first character. </p>
<pre><code>HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
type Status report
message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery).
</code></pre>
<p>Is there any patch for getting this to work with just * ? Or is it very costly to do such a query?</p>
| [
{
"answer_id": 16661,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 1,
"selected": false,
"text": "<p>I'm assuming with id:* you're just trying to match all documents, right?</p>\n\n<p>I've never used solr before, but in my ... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I use solr to search for documents and when trying to search for documents using this query "`id:*`", I get this query parser exception telling that it cannot parse the query with \* or ? as the first character.
```
HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
type Status report
message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery).
```
Is there any patch for getting this to work with just \* ? Or is it very costly to do such a query? | If you want all documents, do a query on \*:\*
If you want all documents with a certain field (e.g. id) try id:[\* TO \*] |
15,995 | <p>Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?</p>
<p>Refer <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196" rel="noreferrer">Fate of reduce() in Python 3000</a> by GvR</p>
| [
{
"answer_id": 16049,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this is what you are after but you can <a href=\"http://www.google.com/codesearch\" rel=\"nofollow noreferrer\">... | 2008/08/19 | [
"https://Stackoverflow.com/questions/15995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and \* that we see in the examples?
Refer [Fate of reduce() in Python 3000](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) by GvR | The other uses I've found for it besides + and \* were with and and or, but now we have `any` and `all` to replace those cases.
`foldl` and `foldr` do come up in Scheme a lot...
Here's some cute usages:
**Flatten a list**
Goal: turn `[[1, 2, 3], [4, 5], [6, 7, 8]]` into `[1, 2, 3, 4, 5, 6, 7, 8]`.
```
reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])
```
**List of digits to a number**
Goal: turn `[1, 2, 3, 4, 5, 6, 7, 8]` into `12345678`.
Ugly, slow way:
```
int("".join(map(str, [1,2,3,4,5,6,7,8])))
```
Pretty `reduce` way:
```
reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)
``` |
16,007 | <p>Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.</p>
<pre><code>if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
</code></pre>
| [
{
"answer_id": 16031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>So far as I know there's no single function which does this (maybe you were looking for the inverse of <a href=\"http://msdn... | 2008/08/19 | [
"https://Stackoverflow.com/questions/16007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762/"
] | Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.
```
if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
``` | As far as I know, there's no method to do what you want; at least not directly. I'd store the `photosLocation` as a path relative to the application; for example: `"~/Images/"`. This way, you could use MapPath to get the physical location, and `ResolveUrl` to get the URL (with a bit of help from `System.IO.Path`):
```
string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
if (files.Length > 0)
{
string filenameRelative = photosLocation + Path.GetFilename(files[0])
return Page.ResolveUrl(filenameRelative);
}
}
``` |
16,096 | <p>In WPF, how would I apply multiple styles to a <code>FrameworkElement</code>? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other.</p>
| [
{
"answer_id": 16108,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 5,
"selected": false,
"text": "<p>But you can extend from another.. take a look at the BasedOn property</p>\n\n<pre><code><Style TargetType=\"TextBlock\"&... | 2008/08/19 | [
"https://Stackoverflow.com/questions/16096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | In WPF, how would I apply multiple styles to a `FrameworkElement`? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other. | **I think the simple answer is that you can't do (at least in this version of WPF) what you are trying to do.**
*That is, for any particular element only one Style can be applied.*
However, as others have stated above, maybe you can use `BasedOn` to help you out. Check out the following piece of loose xaml. In it you will see that I have a base style that is setting a property that exists on the base class of the element that I want to apply two styles to. And, in the second style which is based on the base style, I set another property.
**So, the idea here ... is if you can somehow separate the properties that you want to set ... according the inheritance hierarchy of the element you want to set multiple styles on ... you might have a workaround.**
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="baseStyle" TargetType="FrameworkElement">
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style TargetType="Button" BasedOn="{StaticResource baseStyle}">
<Setter Property="Content" Value="Hello World"/>
</Style>
</Page.Resources>
<Grid>
<Button Width="200" Height="50"/>
</Grid>
</Page>
```
Hope this helps.
**Note:**
One thing in particular to note. If you change the `TargetType` in the second style (in first set of xaml above) to `ButtonBase`, the two Styles do not get applied. However, check out the following xaml below to get around that restriction. Basically, it means you need to give the Style a key and reference it with that key.
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="baseStyle" TargetType="FrameworkElement">
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style x:Key="derivedStyle" TargetType="ButtonBase" BasedOn="{StaticResource baseStyle}">
<Setter Property="Content" Value="Hello World"/>
</Style>
</Page.Resources>
<Grid>
<Button Width="200" Height="50" Style="{StaticResource derivedStyle}"/>
</Grid>
</Page>
``` |
16,100 | <p>What's the best way to convert a string to an enumeration value in C#?</p>
<p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.</p>
<p>In an ideal world, I could do something like this:</p>
<pre><code>StatusEnum MyStatus = StatusEnum.Parse("Active");
</code></pre>
<p>but that isn't a valid code.</p>
| [
{
"answer_id": 16103,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 7,
"selected": false,
"text": "<p>You're looking for <a href=\"https://msdn.microsoft.com/en-us/library/aa328348.aspx\" rel=\"noreferrer\">Enum.Parse</... | 2008/08/19 | [
"https://Stackoverflow.com/questions/16100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203/"
] | What's the best way to convert a string to an enumeration value in C#?
I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.
In an ideal world, I could do something like this:
```
StatusEnum MyStatus = StatusEnum.Parse("Active");
```
but that isn't a valid code. | In .NET Core and .NET Framework ≥4.0 [there is a generic parse method](https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx):
```
Enum.TryParse("Active", out StatusEnum myStatus);
```
This also includes C#7's new inline `out` variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the `myStatus` variable.
If you have access to C#7 and the latest .NET this is the best way.
Original Answer
---------------
In .NET it's rather ugly (until 4 or above):
```
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
```
I tend to simplify this with:
```
public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
```
Then I can do:
```
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
```
One option suggested in the comments is to add an extension, which is simple enough:
```
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
```
Finally, you may want to have a default enum to use if the string cannot be parsed:
```
public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
```
Which makes this the call:
```
StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
```
However, I would be careful adding an extension method like this to `string` as (without namespace control) it will appear on all instances of `string` whether they hold an enum or not (so `1234.ToString().ToEnum(StatusEnum.None)` would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do. |
16,110 | <p>I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents. </p>
<p>The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome. </p>
<p>The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.</p>
<p><strong>Edit:</strong> The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.</p>
| [
{
"answer_id": 16119,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>OK, are you sure that is wise? I am picturing two scenarios here:</p>\n\n<ol>\n<li>There is a default button on the form,... | 2008/08/19 | [
"https://Stackoverflow.com/questions/16110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1629/"
] | I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents.
The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome.
The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.
**Edit:** The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again. | Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.
```
TextBox1.Select(0, TextBox1.Text.Length);
``` |
16,155 | <p><strong>Is there a way in PHP to overwrite a method declared by one interface in an interface extending that interface?</strong></p>
<p>The Example:</p>
<p>I'm probably doing something wrong, but here is what I have:</p>
<pre><code>interface iVendor{
public function __construct($vendors_no = null);
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function __construct($vendors_no = null, $shipment = null);
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
</code></pre>
<p>Normally in PHP, when you extend something, you can overwrite any method contained therein (right?). However, when one interface extends another, it won't let you. Unless I'm thinking about this wrong... When I implement the iShipper interface, I don't have to make the Shipper object extend the Vendor object (that implements the iVendor interface). I just say:</p>
<pre><code>class FedEx implements iShipper{}
</code></pre>
<p>and make FedEx implement all of the methods from iVendor and iShipper. However, I need the <code>__construct</code> functions in iVendor and iShipper to be unique. I know I could take out the <code>$shipment = null</code>, but then it wouldn't be as convenient to create Shippers (by just passing in the vendors_no and the shipment while instantiating).</p>
<p>Anyone know how to make this work? My fallback is to have to set the shipment by calling <code>$shipper->setShipment($shipment);</code> on the Shipper after I instantiate it, but I'm hoping for a way to get around having to do that...</p>
<p><em>A little more explanation for the curious:</em><br>
<em>The FedEx Object has methods that go to the FedEx site (using cURL) and gets an estimate for the Shipment in question. I have a UPS Object, a BAXGlobal Object, a Conway Object, etc. Each one has COMPLETELY different methods for actually getting the shipping estimate, but all the system needs to know is that they are a "shipper" and that the methods listed in the interface are callable on them (so it can treat them all exactly the same, and loop through them in a "shippers" array calling <code>getTransitX()</code> to find the best shipper for a shipment).</em> </p>
<p><em>Each "Shipper" is also a "Vendor" though, and is treated as such in other parts of the system (getting and putting in the DB, etc. Our data design is a pile of crap, so FedEx is stored right alongside companies like Dunder Mifflin in the "Vendors" table, which means it gets to have all the properties of every other Vendor, but needs the extra properties and methods supplied by iShipper).</em></p>
| [
{
"answer_id": 16245,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interf... | 2008/08/19 | [
"https://Stackoverflow.com/questions/16155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | **Is there a way in PHP to overwrite a method declared by one interface in an interface extending that interface?**
The Example:
I'm probably doing something wrong, but here is what I have:
```
interface iVendor{
public function __construct($vendors_no = null);
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function __construct($vendors_no = null, $shipment = null);
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
```
Normally in PHP, when you extend something, you can overwrite any method contained therein (right?). However, when one interface extends another, it won't let you. Unless I'm thinking about this wrong... When I implement the iShipper interface, I don't have to make the Shipper object extend the Vendor object (that implements the iVendor interface). I just say:
```
class FedEx implements iShipper{}
```
and make FedEx implement all of the methods from iVendor and iShipper. However, I need the `__construct` functions in iVendor and iShipper to be unique. I know I could take out the `$shipment = null`, but then it wouldn't be as convenient to create Shippers (by just passing in the vendors\_no and the shipment while instantiating).
Anyone know how to make this work? My fallback is to have to set the shipment by calling `$shipper->setShipment($shipment);` on the Shipper after I instantiate it, but I'm hoping for a way to get around having to do that...
*A little more explanation for the curious:*
*The FedEx Object has methods that go to the FedEx site (using cURL) and gets an estimate for the Shipment in question. I have a UPS Object, a BAXGlobal Object, a Conway Object, etc. Each one has COMPLETELY different methods for actually getting the shipping estimate, but all the system needs to know is that they are a "shipper" and that the methods listed in the interface are callable on them (so it can treat them all exactly the same, and loop through them in a "shippers" array calling `getTransitX()` to find the best shipper for a shipment).*
*Each "Shipper" is also a "Vendor" though, and is treated as such in other parts of the system (getting and putting in the DB, etc. Our data design is a pile of crap, so FedEx is stored right alongside companies like Dunder Mifflin in the "Vendors" table, which means it gets to have all the properties of every other Vendor, but needs the extra properties and methods supplied by iShipper).* | [@cmcculloh](https://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196) Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor.
*EDIT:*
*Here's my new model:*
*A. Each interface no longer has a constructor method.*
*B. All Shippers (UPS, FedEx, etc) now implement iShipper (which extends iVendor) and extend the abstract class Shipper (which has all common non-abstract methods for shippers defined in it, getName(), getZip() etc).*
*C. Each Shipper has it's own unique \_construct method which overwrites the abstract \_\_construct($vendors\_no = null, $shipment = null) method contained in Shipper (I don't remember why I'm allowing those to be optional now though. I'd have to go back through my documentation...).*
So:
```
interface iVendor{
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
abstract class Shipper implements iShipper{
abstract public function __construct($vendors_no = null, $shipment = null);
//a bunch of non-abstract common methods...
}
class FedEx extends Shipper implements iShipper{
public function __construct($vendors_no = null, $shipment = null){
//a bunch of setup code...
}
//all my FedEx specific methods...
}
```
*Thanks for the help!*
*ps. since I have now added this to "your" answer, if there is something about it you don't like/think should be different, feel free to change it...* |