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 |
|---|---|---|---|---|---|---|
52,794 | <p>How do I create a branch in subversion that is deeper' than just the 'branches' directory?</p>
<p>I have the standard <code>trunk</code>, <code>tags</code> and <code>branches</code> structure and I want to create a branch that is several directories deeper than the 'branches' tag.</p>
<p>Using the standard svn move method, it gives me a <strong>folder not found</strong> error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.</p>
<p>What do I need to do to create this?</p>
<p>For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?</p>
| [
{
"answer_id": 52799,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": true,
"text": "<pre><code>svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject\n</... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | How do I create a branch in subversion that is deeper' than just the 'branches' directory?
I have the standard `trunk`, `tags` and `branches` structure and I want to create a branch that is several directories deeper than the 'branches' tag.
Using the standard svn move method, it gives me a **folder not found** error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.
What do I need to do to create this?
For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version\_1/project/subproject' (which does not exist yet)? | ```
svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject
```
That should create the directory you want to put the subproject in (`--parents` means "create the intermediate directories for me"). |
52,797 | <p>Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. </p>
<p>Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.</p>
<p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p>
<p>My test library is located in say </p>
<blockquote>
<p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p>
</blockquote>
<p>and I would like to get this path:</p>
<blockquote>
<p>C:\projects\myapplication\daotests\bin\Debug\</p>
</blockquote>
<p>The three suggestions so far fail me when I run from the MbUnit Gui:</p>
<ul>
<li><p><code>Environment.CurrentDirectory</code>
gives <em>c:\Program Files\MbUnit</em></p></li>
<li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code>
gives <em>C:\Documents and
Settings\george\Local
Settings\Temp\ ....\DaoTests.dll</em></p></li>
<li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code>
gives the same as the previous.</p></li>
</ul>
| [
{
"answer_id": 52802,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": false,
"text": "<p>This should work, unless the assembly is <em>shadow copied</em>:</p>\n\n<pre><code>string path = System.Reflection.Assem... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code.
Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.
**Edit**: People seem to be misunderstanding what I'm asking.
My test library is located in say
>
> C:\projects\myapplication\daotests\bin\Debug\daotests.dll
>
>
>
and I would like to get this path:
>
> C:\projects\myapplication\daotests\bin\Debug\
>
>
>
The three suggestions so far fail me when I run from the MbUnit Gui:
* `Environment.CurrentDirectory`
gives *c:\Program Files\MbUnit*
* `System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location`
gives *C:\Documents and
Settings\george\Local
Settings\Temp\ ....\DaoTests.dll*
* `System.Reflection.Assembly.GetExecutingAssembly().Location`
gives the same as the previous. | **Note**: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0>
**Original answer:**
I've defined the following property as we use this often in unit testing.
```
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
```
The `Assembly.Location` property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use `CodeBase` which gives you the path in URI format, then `UriBuild.UnescapeDataString` removes the `File://` at the beginning, and `GetDirectoryName` changes it to the normal windows format. |
52,806 | <p>As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.</p>
<p>An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.</p>
<p>Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (<code>Model->find()</code>, etc.), but I'm not sanguine about this.</p>
<p>Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work...</p>
| [
{
"answer_id": 52814,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 2,
"selected": false,
"text": "<p>Shouldn't be too bad, you just need a group by (this is off the type of my head, so forgive syntax errors):</p>\n\n<pre>... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5030/"
] | As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.
An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.
Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (`Model->find()`, etc.), but I'm not sanguine about this.
Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work... | Heh, I was just about to come back with essentially the same answer (using Cake's Model::find):
```
$this->loadModel('Comment');
$this->Comment->find( 'all', array(
'fields' => array('COUNT(Comment.id) AS popularCount'),
'conditions' => array(
'Comment.created >' => strtotime('-1 month')
),
'group' => 'Comment.blog_post_id',
'order' => 'popularCount DESC',
'contain' => array(
'Entry' => array(
'fields' => array( 'Entry.title' )
)
)
));
```
It's not perfect, but it works and can be improved on.
I made an additional improvement, using the Containable behaviour to extract the Entry data instead of the Comment data. |
52,821 | <pre><code>var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();
</code></pre>
| [
{
"answer_id": 52870,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 0,
"selected": false,
"text": "<p>Well - I don't know if your initial code block would work, but I'm guessing you have to mark your new e2 as inser... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | ```
var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();
``` | The sub items will be saved along with the main item, and even identities will be set properly, if you give your DataClasses an association between these classes.
You do this by adding LoadOptions to your O/R-Designer DataClasses like this:
```
MyDataContext mydc = new MyDataContext();
System.Data.Linq.DataLoadOptions lo = new System.Data.Linq.DataLoadOptions();
lo.LoadWith<E1>(p => p.e2s);
mydc.LoadOptions = lo;
```
This way LINQ will take care of adding the sub-items, you don't need to InsertOnSubmit every one by itself.
A side effect: upon loading the item, the subitems will be retrieved, too. |
52,822 | <p>How can you import a foxpro DBF file in SQL Server?</p>
| [
{
"answer_id": 52828,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 5,
"selected": true,
"text": "<p>Use a linked server or use openrowset, example</p>\n\n<pre><code>SELECT * into SomeTable\nFROM OPENROWSET('MSDASQL', 'Drive... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] | How can you import a foxpro DBF file in SQL Server? | Use a linked server or use openrowset, example
```
SELECT * into SomeTable
FROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;
SourceDB=\\SomeServer\SomePath\;
SourceType=DBF',
'SELECT * FROM SomeDBF')
``` |
52,824 | <p>Is it possible to merge to a branch that is not a direct parent or child in TFS? I suspect that the answer is no as this is what I've experienced while using it. However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one <strong>might</strong> be approved before feature two). This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.</p>
<p>Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production. This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.</p>
<p>What techniques can be used otherwise to mitigate a scenario such as the one(s) described above?</p>
| [
{
"answer_id": 52841,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK you can do this as long as the branches were created off of the same original folder.</p>\n\n<ul>\n<li>trunk/<... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5416/"
] | Is it possible to merge to a branch that is not a direct parent or child in TFS? I suspect that the answer is no as this is what I've experienced while using it. However, it seems that at certain times it would be really useful when there are different features being worked on that may have different approval cycles (ie. feature one **might** be approved before feature two). This becomes exceedingly difficult when we have production branches where we have to merge some feature into a previous branch so we can release before the next full version.
Our current branching strategy is to develop in the trunk (or mainline as we call it), and create a branch to stabilize and release to production. This branch can then be used to create hotfixes and other things while mainline can diverge for upcoming features.
What techniques can be used otherwise to mitigate a scenario such as the one(s) described above? | I agree with Harpreet that you may want to revisit how you you have setup you branching structure. However you if you really want to perform this type of merge you can through something called a baseless merge. It runs from the tfs command prompt,
```
Tf merge /baseless <<source path>> <<target path>> /recursive
```
Additional info about baseless merges can be found [here](http://www.codeplex.com/VSTSGuidance/Wiki/View.aspx?title=How%20To%3A%20Perform%20a%20Baseless%20Merge%20in%20Team%20Foundation%20Server&referringTitle=View%20More)
Also I found this document to be invaluable when constructing our tfs branching structure
[Microsoft Team Foundation Server Branching Guidance](http://vsarbranchingguide.codeplex.com/) |
52,842 | <p><code>System.IO.Directory.GetFiles()</code> returns a <code>string[]</code>. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date? </p>
<p><strong>Update:</strong> MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient.</p>
| [
{
"answer_id": 52847,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim Files() As String\nFiles = System.IO.Directory.GetFiles(\"C:\... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | `System.IO.Directory.GetFiles()` returns a `string[]`. What is the default sort order for the returned values? I'm assuming by name, but if so how much does the current culture effect it? Can you change it to something like creation date?
**Update:** MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time. That information is lost once you have the array (it contains only strings). I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this. Seems very inefficient. | If you're interested in properties of the files such as CreationTime, then it would make more sense to use System.IO.DirectoryInfo.GetFileSystemInfos().
You can then sort these using one of the extension methods in System.Linq, e.g.:
```
DirectoryInfo di = new DirectoryInfo("C:\\");
FileSystemInfo[] files = di.GetFileSystemInfos();
var orderedFiles = files.OrderBy(f => f.CreationTime);
```
Edit - sorry, I didn't notice the .NET2.0 tag so ignore the LINQ sorting. The suggestion to use System.IO.DirectoryInfo.GetFileSystemInfos() still holds though. |
52,844 | <p>I am using a wxGenericDirCtrl, and I would like to know if there is a way to hide directories, I'd especially like to hide siblings of parent nodes.</p>
<p>For example if my directory structure looks like this:</p>
<pre><code>+-a
|
+-b
| |
| +-whatever
|
+-c
| |
| +-d
| |
| +-e
| |
| +-f
|
+-g
|
+-whatever
</code></pre>
<p>If my currently selected directory is /a/c/d is there any way to hide b and g, so that the tree looks like this in my ctrl:</p>
<pre><code>+-a
|
+-c
|
+-[d]
|
+-e
|
+-f
</code></pre>
<p>I'm currently working with a directory structure that has lots and lots directories that are irrelevant to most users, so it would be nice to be able to clean it up.</p>
<p><strong>Edit</strong>:
If it makes a difference, I am using wxPython, and so far, I have only tested my code on linux using the GTK backend, but I do plan to make it multi-platform and using it on Windows and Mac using the native backends.</p>
| [
{
"answer_id": 60745,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that's possible.</p>\n\n<p>It would be relatively easy to add this functionality to the underlying C++ ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] | I am using a wxGenericDirCtrl, and I would like to know if there is a way to hide directories, I'd especially like to hide siblings of parent nodes.
For example if my directory structure looks like this:
```
+-a
|
+-b
| |
| +-whatever
|
+-c
| |
| +-d
| |
| +-e
| |
| +-f
|
+-g
|
+-whatever
```
If my currently selected directory is /a/c/d is there any way to hide b and g, so that the tree looks like this in my ctrl:
```
+-a
|
+-c
|
+-[d]
|
+-e
|
+-f
```
I'm currently working with a directory structure that has lots and lots directories that are irrelevant to most users, so it would be nice to be able to clean it up.
**Edit**:
If it makes a difference, I am using wxPython, and so far, I have only tested my code on linux using the GTK backend, but I do plan to make it multi-platform and using it on Windows and Mac using the native backends. | Listing/walking directories in Python is very easy, so I would recommend trying to "roll your own" using one of the simple tree controls (such as TreeCtrl or CustomTreeCtrl). It should really be quite easy to call the directory listing code when some directory is expanded and return the result. |
52,874 | <p>I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.</p>
<p>Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 52882,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>Run a command inside a timer like pinging the server..</p>\n"
},
{
"answer_id": 52885,
"author": "zigdon"... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active.
Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake.
Any ideas? | I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though.
It's a hack, not an elegant solution.
```
import java.awt.*;
import java.util.*;
public class Hal{
public static void main(String[] args) throws Exception{
Robot hal = new Robot();
Random random = new Random();
while(true){
hal.delay(1000 * 60);
int x = random.nextInt() % 640;
int y = random.nextInt() % 480;
hal.mouseMove(x,y);
}
}
}
``` |
52,880 | <p>Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password?</p>
| [
{
"answer_id": 52886,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": false,
"text": "<p>It is <a href=\"http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI\" rel=\"nofollow noreferrer\">there</a>. Still ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Does Google Reader have an API and if so, how can I get the count of the number of unread posts for a specific user knowing their username and password? | This URL will give you a count of unread posts per feed. You can then iterate over the feeds and sum up the counts.
<http://www.google.com/reader/api/0/unread-count?all=true>
Here is a minimalist example in Python...parsing the xml/json and summing the counts is left as an exercise for the reader:
```py
import urllib
import urllib2
username = 'username@gmail.com'
password = '******'
# Authenticate to obtain SID
auth_url = 'https://www.google.com/accounts/ClientLogin'
auth_req_data = urllib.urlencode({'Email': username,
'Passwd': password,
'service': 'reader'})
auth_req = urllib2.Request(auth_url, data=auth_req_data)
auth_resp = urllib2.urlopen(auth_req)
auth_resp_content = auth_resp.read()
auth_resp_dict = dict(x.split('=') for x in auth_resp_content.split('\n') if x)
auth_token = auth_resp_dict["Auth"]
# Create a cookie in the header using the SID
header = {}
header['Authorization'] = 'GoogleLogin auth=%s' % auth_token
reader_base_url = 'http://www.google.com/reader/api/0/unread-count?%s'
reader_req_data = urllib.urlencode({'all': 'true',
'output': 'xml'})
reader_url = reader_base_url % (reader_req_data)
reader_req = urllib2.Request(reader_url, None, header)
reader_resp = urllib2.urlopen(reader_req)
reader_resp_content = reader_resp.read()
print reader_resp_content
```
And some additional links on the topic:
* <http://code.google.com/p/pyrfeed/wiki/GoogleReaderAPI>
* [How do you access an authenticated Google App Engine service from a (non-web) python client?](https://stackoverflow.com/questions/101742/how-do-you-access-an-authenticated-google-app-engine-service-from-a-non-web-pyt)
* <http://blog.gpowered.net/2007/08/google-reader-api-functions.html> |
52,898 | <p>I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.</p>
<p>Example:</p>
<p>Visual Studio:</p>
<pre><code>SELECT [column1], [column2] etc...
</code></pre>
<p>My own way:</p>
<pre><code>SELECT column1, column2 etc...
</code></pre>
| [
{
"answer_id": 52900,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": false,
"text": "<p>The brackets can be used when column names are reserved words.</p>\n\n<p>If you are programatically generating the SQL sta... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433/"
] | I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.
Example:
Visual Studio:
```
SELECT [column1], [column2] etc...
```
My own way:
```
SELECT column1, column2 etc...
``` | The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column `[First Name]` (with a space) – but then you'd need to use brackets every time you referred to that column.
The newer tools add them everywhere just in case or for consistency. |
52,927 | <p>I frequently find myself writing code like this:</p>
<pre><code>List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
</code></pre>
<p>Better would be something like this:</p>
<pre><code>List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
</code></pre>
<p>I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? </p>
| [
{
"answer_id": 52940,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "<p>Do this:</p>\n\n<pre><code>list.ForEach(i => Console.Write(\"{0}\\t\", i));\n</code></pre>\n\n<hr>\n\n<p>EDIT: To ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4593/"
] | I frequently find myself writing code like this:
```
List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
```
Better would be something like this:
```
List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
```
I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? | Do this:
```
list.ForEach(i => Console.Write("{0}\t", i));
```
---
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :) |
52,950 | <p>I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:</p>
<p>before: <code>File.h</code></p>
<p>after: <code>file.h</code></p>
<p>I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?</p>
<p><strong>[edit]</strong>
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.</p>
| [
{
"answer_id": 53116,
"author": "MarkB",
"author_id": 2996,
"author_profile": "https://Stackoverflow.com/users/2996",
"pm_score": 9,
"selected": true,
"text": "<p>Since version 1.5.6 there is an <code>ignorecase</code> option available in the <code>[core]</code> section of <code>.git/con... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:
before: `File.h`
after: `file.h`
I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?
**[edit]**
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope. | Since version 1.5.6 there is an `ignorecase` option available in the `[core]` section of `.git/config`
e.g. add `ignorecase = true`
To change it for just one repo, from that folder run:
```
git config core.ignorecase true
```
To change it globally:
```
git config --global core.ignorecase true
``` |
52,952 | <p>So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch?</p>
| [
{
"answer_id": 299772,
"author": "adparadox",
"author_id": 1962,
"author_profile": "https://Stackoverflow.com/users/1962",
"pm_score": -1,
"selected": false,
"text": "<p>You can't just test reader[\"field\"] for null or DBNull because a IndexOutOfRangeException is thrown if the column is... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader. Any fields that aren't in the reader would be left null on the resulting object. How do you test if a reader contains a specific field without just wrapping it in a try/catch? | This should do the trick:
```
Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean
For i As Integer = 0 To reader.FieldCount - 1
If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True
Next
Return False
End Function
```
or (in C#)
```
public static bool ReaderContainsColumn(IDataReader reader, string name)
{
for (int i = 0; i < reader.FieldCount; i++) {
if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true;
}
return false;
}
```
:o) |
52,954 | <p>Right now my ant task looks like.</p>
<pre><code><javadoc sourcepath="${source}" destdir="${doc}">
<link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>
</code></pre>
<p>And I'm getting this warning:</p>
<pre><code>javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list
</code></pre>
<p>How do I get the javadoc to properly link to the API? I am behind a proxy.</p>
| [
{
"answer_id": 52973,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<p>You probably need the <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html\" rel=\"noreferrer\">http.pr... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5118/"
] | Right now my ant task looks like.
```
<javadoc sourcepath="${source}" destdir="${doc}">
<link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>
```
And I'm getting this warning:
```
javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list
```
How do I get the javadoc to properly link to the API? I am behind a proxy. | You probably need the [http.proxyHost and http.proxyPort system properties](http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html) set. For example, `ANT_OPTS="-Dhttp.proxyHost=proxy.y.com" ant doc`
Alternatively, you could set the "offline" flag and provide a package list, but that could be a pain for the Java core. |
52,964 | <p>What is the best way to sort the results of a sql query into a random order within a stored procedure?</p>
| [
{
"answer_id": 52976,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 4,
"selected": false,
"text": "<pre><code>select foo from Bar order by newid()\n</code></pre>\n"
},
{
"answer_id": 52982,
"author": "harpo",
"... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5466/"
] | What is the best way to sort the results of a sql query into a random order within a stored procedure? | This is a duplicate of [SO# 19412](https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql). Here's the answer I gave there:
```
select top 1 * from mytable order by newid()
```
In SQL Server 2005 and up, you can use TABLESAMPLE to get a random sample that's repeatable:
```
SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;
``` |
52,981 | <p>So, I have 2 database instances, one is for development in general, another was copied from development for unit tests.</p>
<p>Something changed in the development database that I can't figure out, and I don't know how to see what is different.</p>
<p>When I try to delete from a particular table, with for example:</p>
<pre><code>delete from myschema.mytable where id = 555
</code></pre>
<p>I get the following normal response from the unit test DB indicating no row was deleted:</p>
<blockquote>
<p>SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000</p>
</blockquote>
<p>However, the development database fails to delete at all with the following error:</p>
<blockquote>
<p>DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0440N No authorized routine named "=" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884</p>
</blockquote>
<p>My best guess is there is some trigger or view that was added or changed that is causing the problem, but I have no idea how to go about finding the problem... has anyone had this problem or know how to figure out what the root of the problem is?</p>
<p>(note that this is a DB2 database)</p>
| [
{
"answer_id": 53000,
"author": "w4ik",
"author_id": 4232,
"author_profile": "https://Stackoverflow.com/users/4232",
"pm_score": 0,
"selected": false,
"text": "<p>You might have an open transaction on the dev db...that gets me sometimes on SQL Server</p>\n"
},
{
"answer_id": 5301... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | So, I have 2 database instances, one is for development in general, another was copied from development for unit tests.
Something changed in the development database that I can't figure out, and I don't know how to see what is different.
When I try to delete from a particular table, with for example:
```
delete from myschema.mytable where id = 555
```
I get the following normal response from the unit test DB indicating no row was deleted:
>
> SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000
>
>
>
However, the development database fails to delete at all with the following error:
>
> DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0440N No authorized routine named "=" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884
>
>
>
My best guess is there is some trigger or view that was added or changed that is causing the problem, but I have no idea how to go about finding the problem... has anyone had this problem or know how to figure out what the root of the problem is?
(note that this is a DB2 database) | Hmm, applying the great oracle to this question, I came up with:
<http://bytes.com/forum/thread830774.html>
It seems to suggest that another table has a foreign key pointing at the problematic one, when that FK on the other table is dropped, the delete should work again. (Presumably you can re-create the foreign key as well)
Does that help any? |
52,984 | <p>How do I setup an Ant task to generate <a href="http://emma.sourceforge.net" rel="noreferrer">Emma</a> code coverage reports?</p>
| [
{
"answer_id": 52994,
"author": "Rob Spieldenner",
"author_id": 5118,
"author_profile": "https://Stackoverflow.com/users/5118",
"pm_score": 5,
"selected": true,
"text": "<p>To answer questions about where the source and instrumented directories are (these can be switched to whatever your... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5118/"
] | How do I setup an Ant task to generate [Emma](http://emma.sourceforge.net) code coverage reports? | To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):
```
<property file="build.properties" />
<property name="source" location="src/main/java" />
<property name="test.source" location="src/test/java" />
<property name="target.dir" location="target" />
<property name="target" location="${target.dir}/classes" />
<property name="test.target" location="${target.dir}/test-classes" />
<property name="instr.target" location="${target.dir}/instr-classes" />
```
Classpaths:
```
<path id="compile.classpath">
<fileset dir="lib/main">
<include name="*.jar" />
</fileset>
</path>
<path id="test.compile.classpath">
<path refid="compile.classpath" />
<pathelement location="lib/test/junit-4.6.jar" />
<pathelement location="${target}" />
</path>
<path id="junit.classpath">
<path refid="test.compile.classpath" />
<pathelement location="${test.target}" />
</path>
```
First you need to setup where Ant can find the Emma libraries:
```
<path id="emma.lib" >
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
```
Then import the task:
```
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
```
Then instrument the code:
```
<target name="coverage.instrumentation">
<mkdir dir="${instr.target}"/>
<mkdir dir="${coverage}"/>
<emma>
<instr instrpath="${target}" destdir="${instr.target}" metadatafile="${coverage}/metadata.emma" mode="copy">
<filter excludes="*Test*"/>
</instr>
</emma>
<!-- Update the that will run the instrumented code -->
<path id="test.classpath">
<pathelement location="${instr.target}"/>
<path refid="junit.classpath"/>
<pathelement location="${emma.dir}/emma.jar"/>
</path>
</target>
```
Then run a target with the proper VM arguments like:
```
<jvmarg value="-Demma.coverage.out.file=${coverage}/coverage.emma" />
<jvmarg value="-Demma.coverage.out.merge=true" />
```
Finally generate your report:
```
<target name="coverage.report" depends="coverage.instrumentation">
<emma>
<report sourcepath="${source}" depth="method">
<fileset dir="${coverage}" >
<include name="*.emma" />
</fileset>
<html outfile="${coverage}/coverage.html" />
</report>
</emma>
</target>
``` |
52,989 | <p>I have a generic Repository<T> class I want to use with an ObjectDataSource. Repository<T> lives in a separate project called DataAccess. According to <a href="http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/767f1a821d9b23da/b1e045958ae427a5?lnk=st#b1e045958ae427a5" rel="noreferrer">this post from the MS newsgroups</a> (relevant part copied below):</p>
<blockquote>
<p>Internally, the ObjectDataSource is calling Type.GetType(string) to get the
type, so we need to follow the guideline documented in Type.GetType on how
to get type using generics. You can refer to MSDN Library on Type.GetType:</p>
<p><a href="http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx</a></p>
<p>From the document, you will learn that you need to use backtick (`) to
denotes the type name which is using generics.</p>
<p>Also, here we must specify the assembly name in the type name string.</p>
<p>So, for your question, the answer is to use type name like follows:</p>
<p>TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"</p>
</blockquote>
<p>Okay, makes sense. When I try it, however, the page throws an exception:</p>
<pre><code><asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" />
</code></pre>
<blockquote>
<p>[InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]</p>
</blockquote>
<p>The curious thing is that this only happens when I'm viewing the page. When I open the "Configure Data Source" dialog from the VS2008 designer, it properly shows me the methods on my generic Repository class. Passing the TypeName string to Type.GetType() while debugging also returns a valid type. So what gives?</p>
| [
{
"answer_id": 53106,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 5,
"selected": true,
"text": "<p>Do something like this.</p>\n\n<pre><code>Type type = typeof(Repository<MessageCategory);\nstring assemblyQualifiedName ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/52989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160/"
] | I have a generic Repository<T> class I want to use with an ObjectDataSource. Repository<T> lives in a separate project called DataAccess. According to [this post from the MS newsgroups](http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/767f1a821d9b23da/b1e045958ae427a5?lnk=st#b1e045958ae427a5) (relevant part copied below):
>
> Internally, the ObjectDataSource is calling Type.GetType(string) to get the
> type, so we need to follow the guideline documented in Type.GetType on how
> to get type using generics. You can refer to MSDN Library on Type.GetType:
>
>
> <http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx>
>
>
> From the document, you will learn that you need to use backtick (`) to
> denotes the type name which is using generics.
>
>
> Also, here we must specify the assembly name in the type name string.
>
>
> So, for your question, the answer is to use type name like follows:
>
>
> TypeName="TestObjectDataSourceAssembly.MyDataHandler`1[System.String],TestObjectDataSourceAssembly"
>
>
>
Okay, makes sense. When I try it, however, the page throws an exception:
```
<asp:ObjectDataSource ID="MyDataSource" TypeName="MyProject.Repository`1[MyProject.MessageCategory],DataAccess" />
```
>
> [InvalidOperationException: The type specified in the TypeName property of ObjectDataSource 'MyDataSource' could not be found.]
>
>
>
The curious thing is that this only happens when I'm viewing the page. When I open the "Configure Data Source" dialog from the VS2008 designer, it properly shows me the methods on my generic Repository class. Passing the TypeName string to Type.GetType() while debugging also returns a valid type. So what gives? | Do something like this.
```
Type type = typeof(Repository<MessageCategory);
string assemblyQualifiedName = type.AssemblyQualifiedName;
```
get the value of assemblyQualifiedName and paste it into the TypeName field. Note that Type.GetType(string), the value passed in must be
>
> The assembly-qualified name of the type to get. See [AssemblyQualifiedName](http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx). If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
>
>
>
So, it may work by passing in that string in your code, because that class is in the currently executing assembly (where you are calling it), where as the ObjectDataSource is not.
Most likely the type you are looking for is
```
MyProject.Repository`1[MyProject.MessageCategory, DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null], DataAccess, Version=1.0.0.0, Culture=neutral, PublicKey=null
``` |
53,025 | <p>I've been utilizing the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a> in my Flex projects, with asynchronous callback routes required between:</p>
<ul>
<li>whoever instantiated a given command object and the command object,</li>
<li>the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.</li>
</ul>
<p>Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.</p>
<p>Currently I have done this using <strong>callback function references</strong> with specific kinds of signatures, but I was wondering <em>if someone knew of a better (or an alternative) way?</em></p>
<p>Here's an example to illustrate my current method:</p>
<ul>
<li>I might have a view object that spawns a <code>DeleteObjectCommand</code> instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say <code>"deleteObjectSuccessHandler()"</code> and <code>"deleteObjectFailureHandler()"</code> in this example) as callback function references to the command class's constructor.</li>
<li>Then the command object would repeat this pattern with its connection to the "data access" object.</li>
<li>When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its <code>deleteObjectSuccessHandler()</code> or <code>deleteObjectFailureHandler()</code> called.</li>
</ul>
| [
{
"answer_id": 53743,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>Many of the Flex RPC classes, like <code>RemoteObject</code>, <code>HTTPService</code>, etc. return <a href=\"http://livedocs... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111/"
] | I've been utilizing the [command pattern](http://en.wikipedia.org/wiki/Command_pattern) in my Flex projects, with asynchronous callback routes required between:
* whoever instantiated a given command object and the command object,
* the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.
Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.
Currently I have done this using **callback function references** with specific kinds of signatures, but I was wondering *if someone knew of a better (or an alternative) way?*
Here's an example to illustrate my current method:
* I might have a view object that spawns a `DeleteObjectCommand` instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say `"deleteObjectSuccessHandler()"` and `"deleteObjectFailureHandler()"` in this example) as callback function references to the command class's constructor.
* Then the command object would repeat this pattern with its connection to the "data access" object.
* When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its `deleteObjectSuccessHandler()` or `deleteObjectFailureHandler()` called. | I'll try one more idea:
Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):
```
public function deleteThing( id : String ) : DeferredResponse {
var deferredResponse : DeferredResponse = new DeferredResponse();
var asyncToken : AsyncToken = theRemoteObject.deleteThing(id);
var result : Function = function( o : Object ) : void {
deferredResponse.notifyResultListeners(o);
}
var fault : Function = function( o : Object ) : void {
deferredResponse.notifyFaultListeners(o);
}
asyncToken.addResponder(new ClosureResponder(result, fault));
return localAsyncToken;
}
```
The `DeferredResponse` and `ClosureResponder` classes don't exist, of course. Instead of inventing your own you could use `AsyncToken` instead of `DeferredResponse`, but the public version of `AsyncToken` doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. `ClosureResponder` is just an implementation of `IResponder` that can call a function on success or failure.
Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures `result` or `fault` gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.
In the command it would look something like this:
```
public function execute( ) : void {
var deferredResponse : DeferredResponse = dao.deleteThing("3");
deferredResponse.addEventListener(ResultEvent.RESULT, onResult);
deferredResponse.addEventListener(FaultEvent.FAULT, onFault);
}
```
or, you could repeat the pattern, having the `execute` method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.
But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be [Mate](http://mate.asfusion.com). |
53,026 | <p>I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema.
I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.</p>
<p>Any ideas?</p>
<blockquote>
<p>Reiterating again: Please don't answer
I can write an application. I know
that, And that is exactly what I'm
trying to avoid.</p>
</blockquote>
| [
{
"answer_id": 53032,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>I do not think you can use the Management Studio GUI to update XML-columns without writing the UPDATE-command yourself.</p>\n... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
] | I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema.
I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.
Any ideas?
>
> Reiterating again: Please don't answer
> I can write an application. I know
> that, And that is exactly what I'm
> trying to avoid.
>
>
> | This is an old question, but I needed to do this today. The best I can come up with is to write a query that generates SQL code that can be edited in the query editor - it's sort of lame but it saves you copy/pasting stuff.
Note: you may need to go into Tools > Options > Query Results > Results to Text and set the maximum number of characters displayed to a large enough number to fit your XML fields.
e.g.
```
select 'update [table name] set [xml field name] = ''' +
convert(varchar(max), [xml field name]) +
''' where [primary key name] = ' +
convert(varchar(max), [primary key name]) from [table name]
```
which produces a lot of queries that look like this (with some sample table/field names):
```
update thetable set thedata = '<root><name>Bob</name></root>' where thekey = 1
```
You then copy these queries from the results window back up to the query window, edit the xml strings, and then run the queries.
(Edit: changed 10 to max to avoid error) |
53,041 | <p>Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs</p>
<p>Does anyone know for sure where these come from, and what they are used for?</p>
| [
{
"answer_id": 53048,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb165951(VS.80).aspx\" rel=\"noreferrer\">According to MSDN</a>: </p>\n\n<bl... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs
Does anyone know for sure where these come from, and what they are used for? | Neither GUID is the same GUID as from AssemblyInfo.cs (that is the GUID for the assembly itself, not tied to Visual Studio but the end product of the build).
So, for a typical line in the sln file (open the .sln in notepad or editor-of-choice if you wish to see this):
```
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
```
The second GUID is a unique GUID for the project itself. The solution file uses this to map other settings to that project:
```
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55A1FD06-FB00-4F8A-9153-C432357F5CAC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
```
The first GUID is actually a GUID that is the unique GUID for the solution itself (I believe). If you have a solution with more than one project, you'll actually see something like the following:
```
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleSandbox", "ConsoleSandbox\ConsoleSandbox.csproj", "{55A1FD06-FB00-4F8A-9153-C432357F5CAC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Composite", "..\CompositeWPF\Source\CAL\Composite\Composite.csproj", "{77138947-1D13-4E22-AEE0-5D0DD046CA34}"
EndProject
``` |
53,046 | <p>In python, there are some special variables and filenames that are surrounded by double-underscores. For example, there is the</p>
<pre><code>__file__
</code></pre>
<p>variable. I am only able to get them to show up correctly inside of a code block. What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis?</p>
| [
{
"answer_id": 53052,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 6,
"selected": true,
"text": "<p>__file__</p>\n\n<p>Put a backslash before the first underscore.</p>\n\n<p>Like this:</p>\n\n<pre><code>\\__file__\n</code>... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | In python, there are some special variables and filenames that are surrounded by double-underscores. For example, there is the
```
__file__
```
variable. I am only able to get them to show up correctly inside of a code block. What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis? | \_\_file\_\_
Put a backslash before the first underscore.
Like this:
```
\__file__
``` |
53,064 | <p>I want to embed an .asp page on an html page. I cannot use an iframe. I tried:</p>
<pre><code><object width="100%" height="1500" type="text/html" data="url.asp">
alt : <a href="url.asp">url</a>
</object>"
</code></pre>
<p>works great in ff but not ie7. Any ideas? Is it possible to use the object tag to embed .asp pages for IE or does it only work in ff?</p>
| [
{
"answer_id": 53083,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 1,
"selected": false,
"text": "<p>You might be able to fake it using javascript. You could either use AJAX to load the page, then insert the HTML, o... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | I want to embed an .asp page on an html page. I cannot use an iframe. I tried:
```
<object width="100%" height="1500" type="text/html" data="url.asp">
alt : <a href="url.asp">url</a>
</object>"
```
works great in ff but not ie7. Any ideas? Is it possible to use the object tag to embed .asp pages for IE or does it only work in ff? | I've solved it in the past using Javascript and XMLHttp. It can get a bit hacky depending on the circumstances. In particular, you have to watch out for the inner page failing and how it affects/downgrades the outer one (hopefully you can keep it downgrading elegantly).
Search for XMLHttp (or check [this great tutorial](http://www.jibbering.com/2002/4/httprequest.html)) and request the "child" page from the outer one, rendering the HTML you need. Preferably you can get just the specific data you need and process it in Javascript. |
53,102 | <p>From the <em>Immediate Window</em> in Visual Studio: </p>
<pre><code>> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
</code></pre>
<p>It seems that they should both be the same. </p>
<p>The old FileSystemObject.BuildPath() didn't work this way...</p>
| [
{
"answer_id": 53110,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 2,
"selected": false,
"text": "<p>Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For exampl... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | From the *Immediate Window* in Visual Studio:
```
> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
```
It seems that they should both be the same.
The old FileSystemObject.BuildPath() didn't work this way... | This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.
[System.IO.Path.Combine](http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx)
"If path2 contains an absolute path, this method returns path2."
[Here's the actual Combine method](http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264) from the .NET source. You can see that it calls [CombineNoChecks](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745), which then calls [IsPathRooted](http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d) on path2 and returns that path if so:
```
public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
```
I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine(). |
53,108 | <p>I have a table similar to this:</p>
<pre><code>CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
</code></pre>
<p>I can use the parentid field to arrange data into a tree structure.</p>
<p>Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?</p>
<p><strong>UPDATE:</strong> I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.</p>
<p>BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow!</p>
| [
{
"answer_id": 53119,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>is this SQL Server? Couldn't you write a TSQL stored procedure that loops through and unions the results together? ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] | I have a table similar to this:
```
CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
```
I can use the parentid field to arrange data into a tree structure.
Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?
**UPDATE:** I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.
BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow! | There are a few ways to do what you need in PostgreSQL.
* If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <http://www.postgresql.org/docs/8.3/interactive/tablefunc.html>
* Also check out the ltree contrib, which you could adapt your table to use: <http://www.postgresql.org/docs/8.3/interactive/ltree.html>
* Or you can traverse the tree yourself with a PL/PGSQL function.
Something like this:
```
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
``` |
53,112 | <p>What are good ways of dealing with the issues surrounding plugin code that interacts with outside system?</p>
<p>To give a concrete and representative example, suppose I would like to use Subversion and Eclipse to develop plugins for WordPress. The main code body of WordPress is installed on the webserver, and the plugin code needs to be available in a subdirectory of that server.</p>
<p>I could see how you could simply checkout a copy of your code directly under the web directory on a development machine, but how would you also then integrate this with the IDE?</p>
<p>I am making the assumption here that all the code for the plugin is located under a single directory.</p>
<p>Do most people just add the plugin as a project in an IDE and then place the working folder for the project wherever the 'main' software system wants it to be? Or do people use some kind of symlinks to their home directory?</p>
| [
{
"answer_id": 53119,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>is this SQL Server? Couldn't you write a TSQL stored procedure that loops through and unions the results together? ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | What are good ways of dealing with the issues surrounding plugin code that interacts with outside system?
To give a concrete and representative example, suppose I would like to use Subversion and Eclipse to develop plugins for WordPress. The main code body of WordPress is installed on the webserver, and the plugin code needs to be available in a subdirectory of that server.
I could see how you could simply checkout a copy of your code directly under the web directory on a development machine, but how would you also then integrate this with the IDE?
I am making the assumption here that all the code for the plugin is located under a single directory.
Do most people just add the plugin as a project in an IDE and then place the working folder for the project wherever the 'main' software system wants it to be? Or do people use some kind of symlinks to their home directory? | There are a few ways to do what you need in PostgreSQL.
* If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <http://www.postgresql.org/docs/8.3/interactive/tablefunc.html>
* Also check out the ltree contrib, which you could adapt your table to use: <http://www.postgresql.org/docs/8.3/interactive/ltree.html>
* Or you can traverse the tree yourself with a PL/PGSQL function.
Something like this:
```
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
``` |
53,128 | <p>I have a webapp that uses JNDI lookups to get a connection to the database.</p>
<p>The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.</p>
<p>Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.</p>
<pre><code>public class DatabaseBean {
private static final Logger logger = Logger.getLogger(DatabaseBean.class);
private Connection conn;
private PreparedStatement prepStmt;
/**
* Zero argument constructor
* Setup generic databse connection in here to avoid redundancy
* The connection details are in /META-INF/context.xml
*/
public DatabaseBean() {
try {
InitialContext initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite");
conn = ds.getConnection();
}
catch (SQLException SQLEx) {
logger.fatal("There was a problem with the database connection.");
logger.fatal(SQLEx);
logger.fatal(SQLEx.getCause());
}
catch (NamingException nameEx) {
logger.fatal("There was a naming exception");
logger.fatal(nameEx);
logger.fatal(nameEx.getCause());
}
}
/**
* Execute a query. Do not use for statements (update delete insert etc).
*
* @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null.
* @see #executeUpdate() for running update, insert delete etc.
*/
public ResultSet executeQuery() {
ResultSet result = null;
try {
result = prepStmt.executeQuery();
logger.debug(prepStmt.toString());
}
catch (SQLException SQLEx) {
logger.fatal("There was an error running a query");
logger.fatal(SQLEx);
}
return result;
}
</code></pre>
<p><em>SNIP</em></p>
<pre><code>public void close() {
try {
prepStmt.close();
prepStmt = null;
conn.close();
conn = null;
} catch (SQLException SQLEx) {
logger.warn("There was an error closing the database connection.");
}
}
}
</code></pre>
<p>This is inside a javabean that uses the database connection.</p>
<pre><code>public LinkedList<ImportantNoticeBean> getImportantNotices() {
DatabaseBean noticesDBBean = new DatabaseBean();
LinkedList<ImportantNoticeBean> listOfNotices = new LinkedList<ImportantNoticeBean>();
try {
PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " +
"FROM importantnotices, users " +
"WHERE importantnotices.username = users.username " +
"AND NOW() >= date_from AND NOW() <= date_to;");
noticesDBBean.setPrepStmt(preStmt);
ResultSet result = noticesDBBean.executeQuery();
while (result.next()) {
ImportantNoticeBean noticeBean = new ImportantNoticeBean();
noticeBean.setAuthor(result.getString("pseudonym"));
noticeBean.setMessage(result.getString("message"));
noticeBean.setDateTo(result.getDate("date_to"));
noticeBean.setDateFrom(result.getDate("date_from"));
listOfNotices.add(noticeBean);
}
result.close();
} catch (SQLException SQLEx) {
logger.error("There was an error in ImportantNoticesBean.getImportantNotices()");
logger.error(SQLEx);
} finally {
noticesDBBean.close();
}
return listOfNotices;
}
<Context reloadable="true">
<Resource name="jdbc/mysite"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysite"
maxActive="10"
maxIdle="5"
maxWait="6000"
removeAbandoned="true"
logAbandoned="false"
removeAbandonedTimeout="20"
/>
</Context>
</code></pre>
| [
{
"answer_id": 53285,
"author": "Binil Thomas",
"author_id": 3973,
"author_profile": "https://Stackoverflow.com/users/3973",
"pm_score": 2,
"selected": false,
"text": "<p>You seem to be closing the connection properly - except for the case where prepStmt.close() throws a SQLException, I ... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] | I have a webapp that uses JNDI lookups to get a connection to the database.
The connection works fine and returns the query no problems. The issue us that the connection does not close properly and is stuck in the 'sleep' mode (according to mysql administrator). This means that they become unusable nad then I run out of connections.
Can someone give me a few pointers as to what I can do to make the connection return to the pool successfully.
```
public class DatabaseBean {
private static final Logger logger = Logger.getLogger(DatabaseBean.class);
private Connection conn;
private PreparedStatement prepStmt;
/**
* Zero argument constructor
* Setup generic databse connection in here to avoid redundancy
* The connection details are in /META-INF/context.xml
*/
public DatabaseBean() {
try {
InitialContext initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/mysite");
conn = ds.getConnection();
}
catch (SQLException SQLEx) {
logger.fatal("There was a problem with the database connection.");
logger.fatal(SQLEx);
logger.fatal(SQLEx.getCause());
}
catch (NamingException nameEx) {
logger.fatal("There was a naming exception");
logger.fatal(nameEx);
logger.fatal(nameEx.getCause());
}
}
/**
* Execute a query. Do not use for statements (update delete insert etc).
*
* @return A ResultSet of the execute query. A set of size zero if no results were returned. It is never null.
* @see #executeUpdate() for running update, insert delete etc.
*/
public ResultSet executeQuery() {
ResultSet result = null;
try {
result = prepStmt.executeQuery();
logger.debug(prepStmt.toString());
}
catch (SQLException SQLEx) {
logger.fatal("There was an error running a query");
logger.fatal(SQLEx);
}
return result;
}
```
*SNIP*
```
public void close() {
try {
prepStmt.close();
prepStmt = null;
conn.close();
conn = null;
} catch (SQLException SQLEx) {
logger.warn("There was an error closing the database connection.");
}
}
}
```
This is inside a javabean that uses the database connection.
```
public LinkedList<ImportantNoticeBean> getImportantNotices() {
DatabaseBean noticesDBBean = new DatabaseBean();
LinkedList<ImportantNoticeBean> listOfNotices = new LinkedList<ImportantNoticeBean>();
try {
PreparedStatement preStmt = noticesDBBean.getConn().prepareStatement("SELECT pseudonym, message, date_to, date_from " +
"FROM importantnotices, users " +
"WHERE importantnotices.username = users.username " +
"AND NOW() >= date_from AND NOW() <= date_to;");
noticesDBBean.setPrepStmt(preStmt);
ResultSet result = noticesDBBean.executeQuery();
while (result.next()) {
ImportantNoticeBean noticeBean = new ImportantNoticeBean();
noticeBean.setAuthor(result.getString("pseudonym"));
noticeBean.setMessage(result.getString("message"));
noticeBean.setDateTo(result.getDate("date_to"));
noticeBean.setDateFrom(result.getDate("date_from"));
listOfNotices.add(noticeBean);
}
result.close();
} catch (SQLException SQLEx) {
logger.error("There was an error in ImportantNoticesBean.getImportantNotices()");
logger.error(SQLEx);
} finally {
noticesDBBean.close();
}
return listOfNotices;
}
<Context reloadable="true">
<Resource name="jdbc/mysite"
auth="Container"
type="javax.sql.DataSource"
username="user"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysite"
maxActive="10"
maxIdle="5"
maxWait="6000"
removeAbandoned="true"
logAbandoned="false"
removeAbandonedTimeout="20"
/>
</Context>
``` | >
> The issue us that the connection does not close properly and is stuck in the 'sleep' mode
>
>
>
This was actually only half right.
The problem I ran into was actually that each app was defining a new connection to the database sever. So each time I closed all the connections App A would make a bunch of new connections as per it's WEB.xml config file and run happily. App B would do the same. The problem is that they are *independent pools* which try to grab up to the server defined limit. It is a kind of race condition I guess. So when App A has finished with the connections it sits waiting to to use them again until the timeout has passed while App B who needs the connection now is denied the resources even though App A has finished with the and should be back in the pool. Once the timeout has passed, the connection is freed up and B (or C etc) can get at it again.
e.g. if the limit is 10 (mySQL profile limit) and each app has been configured to use a max of 10 the there will be 20 attempts at connections. Obviously this is a bad situation.
The solution is to RTFM and put the [connection details in the right place](http://tomcat.apache.org/tomcat-5.5-doc/config/context.html). This does make shared posting a pain but there are ways around it (such as linking to other xml files from the context).
Just to be explicit: I put the connection details in the WEB.xml for each app and the had a fight about it. |
53,161 | <p>what I'm after is something I can feed a number into and it will return the highest order bit. I'm sure there's a simple way. Below is an example output (left is the input)</p>
<pre>1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32</pre>
| [
{
"answer_id": 53174,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "<p>Continually remove the low order bit comes to mind...</p>\n\n<pre><code>int highest_order_bit( int x )\n{\n int y = x;\... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057/"
] | what I'm after is something I can feed a number into and it will return the highest order bit. I'm sure there's a simple way. Below is an example output (left is the input)
```
1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32
``` | This should do the trick.
```
int hob (int num)
{
if (!num)
return 0;
int ret = 1;
while (num >>= 1)
ret <<= 1;
return ret;
}
```
hob(1234) returns 1024
hob(1024) returns 1024
hob(1023) returns 512 |
53,162 | <p>Given:</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>How do I write the above in two lines?</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| [
{
"answer_id": 53173,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "<p>Put a <code>\\</code> at the end of your line or enclose the statement in parens <code>( .. )</code>. From <a href=\"http://w... | 2008/09/09 | [
"https://Stackoverflow.com/questions/53162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Given:
```
e = 'a' + 'b' + 'c' + 'd'
```
How do I write the above in two lines?
```
e = 'a' + 'b' +
'c' + 'd'
``` | What is the line? You can just have arguments on the next line without any problems:
```
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
```
Otherwise you can do something like this:
```
if (a == True and
b == False):
```
or with explicit line break:
```
if a == True and \
b == False:
```
Check the [style guide](http://www.python.org/dev/peps/pep-0008/) for more information.
Using parentheses, your example can be written over multiple lines:
```
a = ('1' + '2' + '3' +
'4' + '5')
```
The same effect can be obtained using explicit line break:
```
a = '1' + '2' + '3' + \
'4' + '5'
```
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go. |
53,208 | <p>In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this. </p>
<p>I want the child processes to be automatically closed <strong>if my main processes crashes</strong> or is closed.</p>
<p>Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 53212,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": -1,
"selected": false,
"text": "<p>You'd probably have to keep a list of the processes you start, and kill them off one by one when you exit your program. I... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | In C++ Windows app, I launch several long running child processes (currently I use CreateProcess(...) to do this.
I want the child processes to be automatically closed **if my main processes crashes** or is closed.
Because of the requirement that this needs to work for a crash of the "parent", I believe this would need to be done using some API/feature of the operating system. So that all the "child" processes are cleaned up.
How do I do this? | The Windows API supports objects called "Job Objects". The following code will create a "job" that is configured to shut down all processes when the main application ends (when its handles are cleaned up). This code should only be run once.:
```cpp
HANDLE ghJob = CreateJobObject( NULL, NULL); // GLOBAL
if( ghJob == NULL)
{
::MessageBox( 0, "Could not create job object", "TEST", MB_OK);
}
else
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
// Configure all child processes associated with the job to terminate when the
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if( 0 == SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)))
{
::MessageBox( 0, "Could not SetInformationJobObject", "TEST", MB_OK);
}
}
```
Then when each child process is created, execute the following code to launch each child each process and add it to the job object:
```cpp
STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
// Launch child process - example is notepad.exe
if (::CreateProcess( NULL, "notepad.exe", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
::MessageBox( 0, "CreateProcess succeeded.", "TEST", MB_OK);
if(ghJob)
{
if(0 == AssignProcessToJobObject( ghJob, processInfo.hProcess))
{
::MessageBox( 0, "Could not AssignProcessToObject", "TEST", MB_OK);
}
}
// Can we free handles now? Not sure about this.
//CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
```
VISTA NOTE: See [AssignProcessToJobObject always return "access denied" on Vista](http://social.msdn.microsoft.com/Forums/en-US/windowssecurity/thread/71c9599e-a3d5-4b79-bfc1-1800565c5b8a) if you encounter access-denied issues with AssignProcessToObject() on vista. |
53,224 | <p>I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as &#196;&#196;RITALO!<br>
That is, html uses escaped markup for the special characters, such as &#196;</p>
<p>Is there a simple way of reading the html into the correct python string? If it was XML/XHTML it would be easy, the parser would do it.</p>
| [
{
"answer_id": 53226,
"author": "Nick Fortescue",
"author_id": 5346,
"author_profile": "https://Stackoverflow.com/users/5346",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tried it myself, but have you tried</p>\n\n<p><a href=\"http://zesty.ca/python/scrape.html\" rel=\"nofoll... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5346/"
] | I want to scrape some information off a football (soccer) web page using simple python regexp's. The problem is that players such as the first chap, ÄÄRITALO, comes out as ÄÄRITALO!
That is, html uses escaped markup for the special characters, such as Ä
Is there a simple way of reading the html into the correct python string? If it was XML/XHTML it would be easy, the parser would do it. | I would recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for HTML scraping. You also need to tell it to convert HTML entities to the corresponding Unicode characters, like so:
```
>>> from BeautifulSoup import BeautifulSoup
>>> html = "<html>ÄÄRITALO!</html>"
>>> soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
>>> print soup.contents[0].string
ÄÄRITALO!
```
(It would be nice if the standard [codecs](http://docs.python.org/lib/module-codecs.html) module included a codec for this, such that you could do `"some_string".decode('html_entities')` but unfortunately it doesn't!)
**EDIT:**
Another solution:
Python developer Fredrik Lundh (author of elementtree, among other things) has [a function to unsecape HTML entities](http://docs.python.org/lib/module-codecs.html) on his website, which works with decimal, hex and named entities (BeautifulSoup will not work with the hex ones). |
53,225 | <p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
| [
{
"answer_id": 53237,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://docs.python.org/2/reference/datamodel.html?highlight=im_self\" rel=\"nofollow noreferrer\"><strong>i... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to? | ```py
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
```
[User-defined methods:](https://docs.python.org/2.7/reference/datamodel.html#index-40)
>
> When a user-defined method object is
> created by retrieving a user-defined
> function object from a class, its
> `im_self` attribute is `None` and the
> method object is said to be unbound.
> When one is created by retrieving a
> user-defined function object from a
> class via one of its instances, its
> `im_self` attribute is the instance, and
> the method object is said to be bound.
> In either case, the new method's
> `im_class` attribute is the class from
> which the retrieval takes place, and
> its `im_func` attribute is the original
> function object.
>
>
>
In Python [2.6 and 3.0](https://docs.python.org/2.7/whatsnew/2.6.html):
>
> Instance method objects have new
> attributes for the object and function
> comprising the method; the new synonym
> for `im_self` is `__self__`, and `im_func`
> is also available as `__func__`. The old
> names are still supported in Python
> 2.6, but are gone in 3.0.
>
>
> |
53,256 | <p>I have two elements:</p>
<pre><code><input a>
<input b onclick="...">
</code></pre>
<p>When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so <code>document.getElementsByName</code> is out. Looking into the event object, I thought <code>event.target.parentNode</code> would have some function like <code>getElementsByName</code>, but this does not seem to be the case with <td>s. Is there any simple way to do this?</p>
| [
{
"answer_id": 53261,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": true,
"text": "<p>If <code>a</code> and <code>b</code> are next to each other and have the same parent, you can use the <code>prevSibling</c... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429/"
] | I have two elements:
```
<input a>
<input b onclick="...">
```
When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so `document.getElementsByName` is out. Looking into the event object, I thought `event.target.parentNode` would have some function like `getElementsByName`, but this does not seem to be the case with <td>s. Is there any simple way to do this? | If `a` and `b` are next to each other and have the same parent, you can use the `prevSibling` property of `b` to find `a`. |
53,260 | <p>Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.</p>
<p>Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.</p>
<p>Can anyone recommend a way to handle this scenario when HTTP POST data is involved?</p>
<p>Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.</p>
<hr>
<p><strong>Edit</strong> : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.</p>
| [
{
"answer_id": 53267,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": false,
"text": "<p>This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.
Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.
Can anyone recommend a way to handle this scenario when HTTP POST data is involved?
Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.
---
**Edit** : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment. | 2 choices:
1. Write out the messy form from the login page, and JavaScript form.submit() it to the page.
2. Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:
```
CommentController {
void AddComment() {
if (!Request.User.IsAuthenticated && !AuthenticateUser()) {
return;
}
// add comment to database
}
bool AuthenticateUser() {
if (Request.Form["username"] == "") {
// show login page
foreach (Key key in Request.Form) {
// copy form values
ViewData.Form.Add("hidden", key, Request.Form[key]);
}
ViewData.Form.Action = Request.Url;
ShowLoginView();
return false;
} else {
// validate login
return TryLogin(Request.Form["username"], Request.Form["password"]);
}
}
}
``` |
53,292 | <p>I'm trying to use the <a href="http://optiflag.rubyforge.org/discussion.html" rel="nofollow noreferrer">Optiflag</a> package in my Ruby code and whenever I try to do the necessary <code>require optiflag.rb</code>, my program fails with the standard <code>no such file to load -- optiflag</code> message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas?</p>
| [
{
"answer_id": 53313,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 3,
"selected": true,
"text": "<p>is it a gem? Are you doing </p>\n\n<pre><code>require 'rubygems'\nrequire 'optiflag'\n</code></pre>\n\n<p>or equivalent?<... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | I'm trying to use the [Optiflag](http://optiflag.rubyforge.org/discussion.html) package in my Ruby code and whenever I try to do the necessary `require optiflag.rb`, my program fails with the standard `no such file to load -- optiflag` message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas? | is it a gem? Are you doing
```
require 'rubygems'
require 'optiflag'
```
or equivalent? |
53,316 | <p>I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:</p>
<pre><code>@CollectionOfElements(fetch = EAGER)
@JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note"))
@Column(name = "substitution")
@IndexColumn(name = "listIndex", base = 0)
@Lob
private List<String> substitutions;
</code></pre>
<p>So basically I may have a Note with some subsitutions, say <code>"foo"</code> and <code>"fizzbuzz"</code>. So in my main table I could have a Note with id 4 and in my <code>NOTE_JOIN_TABLE</code> I would have two rows, <code>"foo"</code> and <code>"fizzbuzz"</code> that both have a relationship to the Note.</p>
<p>However, when one of these is inserted into the DB <strong>the larger substitution values are cropped to be as long as the shortest.</strong> So in this case I would have <code>"foo"</code> and <code>"fiz"</code> in the DB instead of <code>"foo"</code> and <code>"fizzbuzz"</code>.</p>
<p>Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate.</p>
| [
{
"answer_id": 53308,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 0,
"selected": false,
"text": "<p>Are you trying to implement a client to a web service hosted somewhere else? If so, Java's not necessary. You can do w... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | I have a one to many relationship between two tables. The many table contains a clob column. The clob column looks like this in hibernate:
```
@CollectionOfElements(fetch = EAGER)
@JoinTable(name = NOTE_JOIN_TABLE, joinColumns = @JoinColumn(name = "note"))
@Column(name = "substitution")
@IndexColumn(name = "listIndex", base = 0)
@Lob
private List<String> substitutions;
```
So basically I may have a Note with some subsitutions, say `"foo"` and `"fizzbuzz"`. So in my main table I could have a Note with id 4 and in my `NOTE_JOIN_TABLE` I would have two rows, `"foo"` and `"fizzbuzz"` that both have a relationship to the Note.
However, when one of these is inserted into the DB **the larger substitution values are cropped to be as long as the shortest.** So in this case I would have `"foo"` and `"fiz"` in the DB instead of `"foo"` and `"fizzbuzz"`.
Do you have any idea why this is happening? I have checked and confirmed they aren't being cropped anywhere in our code, it's defintely hibernate. | To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure out how to traverse the XML returned. If you can't do Java, then I suggest PHP because it could be already installed, and have the proper modules loaded. This link might be helpful:
<http://www.onlamp.com/pub/a/php/2007/07/26/php-web-services.html> |
53,353 | <p>Below I present three options for simplifying my database access when only a single connection is involved (this is often the case for the web apps I work on).</p>
<p>The general idea is to make the DB connection transparent, such that it connects the first time my script executes a query, and then it remains connected until the script terminates.</p>
<p>I'd like to know which one you think is the best and why. I don't know the names of any design patterns that these might fit so sorry for not using them. And if there's any <em>better</em> way of doing this with PHP5, please share.</p>
<p>To give a brief introduction: there is a DB_Connection class containing a query method. This is a third-party class which is out of my control and whose interface I've simplified for the purpose of this example. In each option I've also provided an example model for an imaginary DB "items" table to give some context.</p>
<p>Option 3 is the one that provides me with the interface I like most, but I don't think it's practical unfortunately.</p>
<p>I've described the pros and cons (that I can see) of each in the comment blocks below.</p>
<p>At the moment I lean towards Option 1 since the burden is put on my DB wrapper class instead of on the models.</p>
<p>All comments appreciated!</p>
<p>Note: For some reason, the Stack Overflow preview is showing an encoded HTML entity instead of underscores. If the post comes through like that, please take this into account.</p>
<pre><code><?php
/**
* This is the 3rd-party DB interface I'm trying to wrap.
* I've simplified the interface to one method for this example.
*
* This class is used in each option below.
*/
class DB_Connection {
public function &query($sql) { }
}
/**
* OPTION 1
*
* Cons: Have to wrap every public DB_Connection method.
* Pros: The model code is simple.
*/
class DB {
private static $connection;
private static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function &query($sql) {
$dbh = self::getConnection();
return $dbh->query($sql);
}
}
class Item {
public static function &getList() {
return DB::query("SELECT * FROM items");
}
}
/**
* OPTION 2
*
* Pros: Don't have to wrap every DB_Connection function like in Option 1
* Cons: Every function in the model is responsible for checking the connection
*/
class DB {
protected static $connection = null;
public function connect() {
self::$connection = new DB_Connection();
}
}
class Item extends DB {
public static function &getList() {
if (!self::$connection) $this->connect();
return self::$connection->query("SELECT * FROM items");
}
}
/**
* OPTION 3
*
* Use magic methods
*
* Pros: Simple model code AND don't have to reimplement the DB_Connection interface
* Cons: __callStatic requires PHP 5.3.0 and its args can't be passed-by-reference.
*/
class DB {
private static $connection = null;
public static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function __callStatic($name, $args) {
if (in_array($name, get_class_methods('DB_Connection'))) {
return call_user_func_array(
array(self::getConnection(), $name), $args);
}
}
}
</code></pre>
| [
{
"answer_id": 53399,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 4,
"selected": true,
"text": "<p>Doh! Someone else here at work figured this out. It was really simple and I should have been able to sort it, but hey, that's... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Below I present three options for simplifying my database access when only a single connection is involved (this is often the case for the web apps I work on).
The general idea is to make the DB connection transparent, such that it connects the first time my script executes a query, and then it remains connected until the script terminates.
I'd like to know which one you think is the best and why. I don't know the names of any design patterns that these might fit so sorry for not using them. And if there's any *better* way of doing this with PHP5, please share.
To give a brief introduction: there is a DB\_Connection class containing a query method. This is a third-party class which is out of my control and whose interface I've simplified for the purpose of this example. In each option I've also provided an example model for an imaginary DB "items" table to give some context.
Option 3 is the one that provides me with the interface I like most, but I don't think it's practical unfortunately.
I've described the pros and cons (that I can see) of each in the comment blocks below.
At the moment I lean towards Option 1 since the burden is put on my DB wrapper class instead of on the models.
All comments appreciated!
Note: For some reason, the Stack Overflow preview is showing an encoded HTML entity instead of underscores. If the post comes through like that, please take this into account.
```
<?php
/**
* This is the 3rd-party DB interface I'm trying to wrap.
* I've simplified the interface to one method for this example.
*
* This class is used in each option below.
*/
class DB_Connection {
public function &query($sql) { }
}
/**
* OPTION 1
*
* Cons: Have to wrap every public DB_Connection method.
* Pros: The model code is simple.
*/
class DB {
private static $connection;
private static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function &query($sql) {
$dbh = self::getConnection();
return $dbh->query($sql);
}
}
class Item {
public static function &getList() {
return DB::query("SELECT * FROM items");
}
}
/**
* OPTION 2
*
* Pros: Don't have to wrap every DB_Connection function like in Option 1
* Cons: Every function in the model is responsible for checking the connection
*/
class DB {
protected static $connection = null;
public function connect() {
self::$connection = new DB_Connection();
}
}
class Item extends DB {
public static function &getList() {
if (!self::$connection) $this->connect();
return self::$connection->query("SELECT * FROM items");
}
}
/**
* OPTION 3
*
* Use magic methods
*
* Pros: Simple model code AND don't have to reimplement the DB_Connection interface
* Cons: __callStatic requires PHP 5.3.0 and its args can't be passed-by-reference.
*/
class DB {
private static $connection = null;
public static function &getConnection() {
if (!self::$connection) {
self::$connection = new DB_Connection();
}
return self::$connection;
}
public static function __callStatic($name, $args) {
if (in_array($name, get_class_methods('DB_Connection'))) {
return call_user_func_array(
array(self::getConnection(), $name), $args);
}
}
}
``` | Doh! Someone else here at work figured this out. It was really simple and I should have been able to sort it, but hey, that's how it goes sometimes.
Here the fix:
On the web server, copy the 'aspnet\_client' folder from 'C:\Inetpub\wwwroot' to 'C:\Inetpub\wwwroot\your-website-name'.
That's all we did and it's now working.
Hope this saves someone from all the fuss I just went through. |
53,365 | <p><em>(see <a href="https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly">here</a> for the problem I'm trying to solve)</em></p>
<p>How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.</p>
<p>I have the following in my log4j config:</p>
<pre><code>log4j.logger.net.sf.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.net.sf.hibernate.type=DEBUG
log4j.logger.org.hibernate.type=DEBUG
</code></pre>
<p>Which produces output such as:</p>
<pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
</code></pre>
<p>However you'll note that it never displays <code>parameter: 3</code> which is our clob.</p>
<p>What I would really want is something like:</p>
<pre><code>(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.type.ClobType) binding 'something' to parameter: 3
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
(org.hibernate.type.ClobType) binding 'something else' to parameter: 3
</code></pre>
<p>How do I get it to show this in the log?</p>
| [
{
"answer_id": 53419,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 2,
"selected": true,
"text": "<p>Try using:</p>\n\n<pre><code>log4j.logger.net.sf.hibernate=DEBUG\nlog4j.logger.org.hibernate=DEBUG\n</code></pre>\n\n... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | *(see [here](https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly) for the problem I'm trying to solve)*
How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.
I have the following in my log4j config:
```
log4j.logger.net.sf.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.net.sf.hibernate.type=DEBUG
log4j.logger.org.hibernate.type=DEBUG
```
Which produces output such as:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
```
However you'll note that it never displays `parameter: 3` which is our clob.
What I would really want is something like:
```
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '0' to parameter: 2
(org.hibernate.type.ClobType) binding 'something' to parameter: 3
(org.hibernate.SQL) insert into NoteSubstitutions (note, listIndex, substitution) values (?, ?, ?)
(org.hibernate.type.LongType) binding '170650' to parameter: 1
(org.hibernate.type.IntegerType) binding '1' to parameter: 2
(org.hibernate.type.ClobType) binding 'something else' to parameter: 3
```
How do I get it to show this in the log? | Try using:
```
log4j.logger.net.sf.hibernate=DEBUG
log4j.logger.org.hibernate=DEBUG
```
That's the finest level you'll get. If it does not show the information you want, then it's not possible. |
53,379 | <p>Does anyone have examples of how to use <a href="http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php" rel="nofollow noreferrer">DBMS_APPLICATION_INFO</a> package with JBOSS? </p>
<p>We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.</p>
<p>I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.</p>
<p>Has anyone done this before?</p>
| [
{
"answer_id": 53449,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 2,
"selected": true,
"text": "<p>yes, you can write a wrapper class around your connection pool, and a wraper around the connection\nso lets say yo... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] | Does anyone have examples of how to use [DBMS\_APPLICATION\_INFO](http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php) package with JBOSS?
We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS\_APPLICATION\_INFO so I can more easily track which sections of the application is causing database issues.
I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.
Has anyone done this before? | yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnection(String datasourceName, String module, String action){
OracleConnection conn=getConnection(datasourceName);
CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setString(1,module);
call.setString(2,action);
call.execute();
finally{
call.close();
}
return new WrappedOracleConnection(conn);
}
```
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
```
public class WrappedOracleConnection extends OracleConnection{
public void close(){
CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setNull(1,Types.VARCHAR);
call.setNull(2,Types.VARCHAR);
call.execute();
finally{
call.close();
}
}
// and you need to implement every other method
//for example
public CallableStatement prepareCall(String command){
return super.prepareCall(command);
}
...
}
```
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool). |
53,395 | <p>I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.</p>
<p>Abstract class:</p>
<pre><code>public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
</code></pre>
<p>Children:</p>
<pre><code>public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
</code></pre>
<p>Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to <em>ToList</em> method of the <em>MyObjects</em> base class, as we do not specifically know the type of T at this point. </p>
<p><strong>EDIT</strong>
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.</p>
<p><strong>EDIT</strong>
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)</p>
<p>@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds</p>
<p><strong>EDIT</strong> @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.</p>
<p><strong>EDIT</strong>@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects. </p>
<p>@Rob <strong>Again</strong> Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.</p>
<p><strong>QUALIFYING EDIT</strong> in case I have been a little confusing</p>
<p>To be more precise, (I may have let my latest implementation of this get it too complex):</p>
<p>lets say I have 2 object types, B and C inheriting from object A.</p>
<p>Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A. </p>
<p>The above example was a watered-down example of the <em>List Of Less Specific</em> problem's latest incarnation.</p>
<p>Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand</p>
<p>@Rob <strong>Yet Again</strong> and Sara</p>
<p>Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.</p>
<p>The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).</p>
<p>My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.</p>
<p>I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.</p>
| [
{
"answer_id": 53402,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for <em>different</em> classes... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.
Abstract class:
```
public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
```
Children:
```
public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
```
Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to *ToList* method of the *MyObjects* base class, as we do not specifically know the type of T at this point.
**EDIT**
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.
**EDIT**
@Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)
@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds
**EDIT** @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.
**EDIT**@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects.
@Rob **Again** Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.
**QUALIFYING EDIT** in case I have been a little confusing
To be more precise, (I may have let my latest implementation of this get it too complex):
lets say I have 2 object types, B and C inheriting from object A.
Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A.
The above example was a watered-down example of the *List Of Less Specific* problem's latest incarnation.
Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand
@Rob **Yet Again** and Sara
Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.
The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).
My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.
I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it. | If you have
```
class B : A
class C : A
```
And you have
```
List<B> listB;
List<C> listC;
```
that you wish to treat as a List of the parent type
Then you should use
```
List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
``` |
53,435 | <p>I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process.</p>
<p>I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain.</p>
<p>When this crash happens, where can I find the crash dump for analysis?</p>
| [
{
"answer_id": 53457,
"author": "Gareth Jenkins",
"author_id": 1521,
"author_profile": "https://Stackoverflow.com/users/1521",
"pm_score": 1,
"selected": false,
"text": "<p>A quick search found <a href=\"http://www.iisfaq.com/default.aspx?view=P197\" rel=\"nofollow noreferrer\">IISState<... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] | I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process.
I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain.
When this crash happens, where can I find the crash dump for analysis? | Download Debugging tools for Windows:
<http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx>
Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES:
<http://support.microsoft.com/kb/286350>
The command should be something like (if you are using IIS6):
```
cscript adplus.vbs -crash -pn w3wp.exe
```
This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a \*.DMP file).
You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump...
By default, WinDBG will show you (next to the command line) the thread were the process crashed.
The first thing you need to do in WinDBG is to load the .NET Framework extensions:
```
.loadby sos mscorwks
```
then, you will display the managed callstack:
```
!clrstack
```
if the thread was not running managed code, then you'll need to check the native stack:
```
kpn 200
```
This should give you some ideas. To continue troubleshooting I recommend you read the following article:
<http://msdn.microsoft.com/en-us/library/ee817663.aspx> |
53,472 | <p>I have some Ruby code which takes dates on the command line in the format:</p>
<pre><code>-d 20080101,20080201..20080229,20080301
</code></pre>
<p>I want to run for all dates between <code>20080201</code> and <code>20080229</code> inclusive and the other dates present in the list.</p>
<p>I can get the string <code>20080201..20080229</code>, so is the best way to convert this to a Range instance? Currently, I am using <code>eval</code>, but it feels like there should be a better way.</p>
<hr>
<p>@Purfideas I was kind of looking for a more general answer for converting any string of type <code>int..int</code> to a Range I guess.</p>
| [
{
"answer_id": 53504,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 2,
"selected": false,
"text": "<p>assuming you want the range to iterate properly through months etc, try</p>\n\n<pre><code>require 'date'\n\nends = '2008... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4121/"
] | I have some Ruby code which takes dates on the command line in the format:
```
-d 20080101,20080201..20080229,20080301
```
I want to run for all dates between `20080201` and `20080229` inclusive and the other dates present in the list.
I can get the string `20080201..20080229`, so is the best way to convert this to a Range instance? Currently, I am using `eval`, but it feels like there should be a better way.
---
@Purfideas I was kind of looking for a more general answer for converting any string of type `int..int` to a Range I guess. | But then just do
```
ends = '20080201..20080229'.split('..').map{|d| Integer(d)}
ends[0]..ends[1]
```
anyway I don't recommend eval, for security reasons |
53,473 | <p>I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:</p>
<pre><code><p height="30">
</code></pre>
<p>I want to apply a <code>class="h30"</code> to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an <code>id</code> or <code>class</code>. Help?</p>
| [
{
"answer_id": 53475,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>Attributes are just properties (usually). So just try:</p>\n\n<pre><code>for (e in ...) {\n if (e.height == 30) {\n... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5512/"
] | I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:
```
<p height="30">
```
I want to apply a `class="h30"` to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an `id` or `class`. Help? | I would highly recommend using something like jquery where adding classes is trivial:
```
$("#someId").addClass("newClass");
```
so in your case:
```
$("p[height='30']").addClass("h30");
```
so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it. |
53,480 | <p>Hey, I'm using <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshteins</a> algorithm to get distance between source and target string.</p>
<p>also I have method which returns value from 0 to 1:</p>
<pre><code>/// <summary>
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range,
/// which means that if the score gets a maximum value (equal to 1)
/// then the two string are absolutely similar
/// </summary>
/// <param name="string1">The string1.</param>
/// <param name="string2">The string2.</param>
/// <returns></returns>
public static float CalculateSimilarity(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) return 0.0f;
float dis = LevenshteinDistance.Compute(s1, s2);
float maxLen = s1.Length;
if (maxLen < s2.Length)
maxLen = s2.Length;
if (maxLen == 0.0F)
return 1.0F;
else return 1.0F - dis / maxLen;
}
</code></pre>
<p>but this for me is not enough. Because I need more complex way to match two sentences.</p>
<p>For example I want automatically tag some music, I have original song names, and i have songs with trash, like <em>super, quality,</em> years like <em>2007, 2008,</em> etc..etc.. also some files have just <a href="http://trash..thash..song_name_mp3.mp3" rel="nofollow noreferrer">http://trash..thash..song_name_mp3.mp3</a>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?</p>
<p>here is my current algo:</p>
<pre><code>/// <summary>
/// if we need to ignore this target.
/// </summary>
/// <param name="targetString">The target string.</param>
/// <returns></returns>
private bool doIgnore(String targetString)
{
if ((targetString != null) && (targetString != String.Empty))
{
for (int i = 0; i < ignoreWordsList.Length; ++i)
{
//* if we found ignore word or target string matching some some special cases like years (Regex).
if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
}
}
return false;
}
/// <summary>
/// Removes the duplicates.
/// </summary>
/// <param name="list">The list.</param>
private void removeDuplicates(List<String> list)
{
if ((list != null) && (list.Count > 0))
{
for (int i = 0; i < list.Count - 1; ++i)
{
if (list[i] == list[i + 1])
{
list.RemoveAt(i);
--i;
}
}
}
}
/// <summary>
/// Does the fuzzy match.
/// </summary>
/// <param name="targetTitle">The target title.</param>
/// <returns></returns>
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
TitleMatchResult matchResult = null;
if (targetTitle != null && targetTitle != String.Empty)
{
try
{
//* change target title (string) to lower case.
targetTitle = targetTitle.ToLower();
//* scores, we will select higher score at the end.
Dictionary<Title, float> scores = new Dictionary<Title, float>();
//* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
//* remove all trash from keywords, like super, quality, etc..
targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
//* sort keywords.
targetKeywords.Sort();
//* remove some duplicates.
removeDuplicates(targetKeywords);
//* go through all original titles.
foreach (Title sourceTitle in titles)
{
float tempScore = 0f;
//* split orig. title to keywords list.
List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
sourceKeywords.Sort();
removeDuplicates(sourceKeywords);
//* go through all source ttl keywords.
foreach (String keyw1 in sourceKeywords)
{
float max = float.MinValue;
foreach (String keyw2 in targetKeywords)
{
float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
if (currentScore > max)
{
max = currentScore;
}
}
tempScore += max;
}
//* calculate average score.
float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count));
//* if average score is bigger than minimal score and target title is not in this source title ignore list.
if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle))
{
//* add score.
scores.Add(sourceTitle, averageScore);
}
}
//* choose biggest score.
float maxi = float.MinValue;
foreach (KeyValuePair<Title, float> kvp in scores)
{
if (kvp.Value > maxi)
{
maxi = kvp.Value;
matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
}
}
}
catch { }
}
//* return result.
return matchResult;
}
</code></pre>
<p>This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one.. </p>
<p>Ideas? Suggestions? Algos?</p>
<p>by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.):
<a href="https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms">Approximate string matching algorithms</a></p>
| [
{
"answer_id": 53531,
"author": "Greg",
"author_id": 4123,
"author_profile": "https://Stackoverflow.com/users/4123",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like what you want may be a longest substring match. That is, in your example, two files like</p>\n\n<p>trash..thas... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
] | Hey, I'm using [Levenshteins](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to get distance between source and target string.
also I have method which returns value from 0 to 1:
```
/// <summary>
/// Gets the similarity between two strings.
/// All relation scores are in the [0, 1] range,
/// which means that if the score gets a maximum value (equal to 1)
/// then the two string are absolutely similar
/// </summary>
/// <param name="string1">The string1.</param>
/// <param name="string2">The string2.</param>
/// <returns></returns>
public static float CalculateSimilarity(String s1, String s2)
{
if ((s1 == null) || (s2 == null)) return 0.0f;
float dis = LevenshteinDistance.Compute(s1, s2);
float maxLen = s1.Length;
if (maxLen < s2.Length)
maxLen = s2.Length;
if (maxLen == 0.0F)
return 1.0F;
else return 1.0F - dis / maxLen;
}
```
but this for me is not enough. Because I need more complex way to match two sentences.
For example I want automatically tag some music, I have original song names, and i have songs with trash, like *super, quality,* years like *2007, 2008,* etc..etc.. also some files have just <http://trash..thash..song_name_mp3.mp3>, other are normal. I want to create an algorithm which will work just more perfect than mine now.. Maybe anyone can help me?
here is my current algo:
```
/// <summary>
/// if we need to ignore this target.
/// </summary>
/// <param name="targetString">The target string.</param>
/// <returns></returns>
private bool doIgnore(String targetString)
{
if ((targetString != null) && (targetString != String.Empty))
{
for (int i = 0; i < ignoreWordsList.Length; ++i)
{
//* if we found ignore word or target string matching some some special cases like years (Regex).
if (targetString == ignoreWordsList[i] || (isMatchInSpecialCases(targetString))) return true;
}
}
return false;
}
/// <summary>
/// Removes the duplicates.
/// </summary>
/// <param name="list">The list.</param>
private void removeDuplicates(List<String> list)
{
if ((list != null) && (list.Count > 0))
{
for (int i = 0; i < list.Count - 1; ++i)
{
if (list[i] == list[i + 1])
{
list.RemoveAt(i);
--i;
}
}
}
}
/// <summary>
/// Does the fuzzy match.
/// </summary>
/// <param name="targetTitle">The target title.</param>
/// <returns></returns>
private TitleMatchResult doFuzzyMatch(String targetTitle)
{
TitleMatchResult matchResult = null;
if (targetTitle != null && targetTitle != String.Empty)
{
try
{
//* change target title (string) to lower case.
targetTitle = targetTitle.ToLower();
//* scores, we will select higher score at the end.
Dictionary<Title, float> scores = new Dictionary<Title, float>();
//* do split special chars: '-', ' ', '.', ',', '?', '/', ':', ';', '%', '(', ')', '#', '\"', '\'', '!', '|', '^', '*', '[', ']', '{', '}', '=', '!', '+', '_'
List<String> targetKeywords = new List<string>(targetTitle.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
//* remove all trash from keywords, like super, quality, etc..
targetKeywords.RemoveAll(delegate(String x) { return doIgnore(x); });
//* sort keywords.
targetKeywords.Sort();
//* remove some duplicates.
removeDuplicates(targetKeywords);
//* go through all original titles.
foreach (Title sourceTitle in titles)
{
float tempScore = 0f;
//* split orig. title to keywords list.
List<String> sourceKeywords = new List<string>(sourceTitle.Name.Split(ignoreCharsList, StringSplitOptions.RemoveEmptyEntries));
sourceKeywords.Sort();
removeDuplicates(sourceKeywords);
//* go through all source ttl keywords.
foreach (String keyw1 in sourceKeywords)
{
float max = float.MinValue;
foreach (String keyw2 in targetKeywords)
{
float currentScore = StringMatching.StringMatching.CalculateSimilarity(keyw1.ToLower(), keyw2);
if (currentScore > max)
{
max = currentScore;
}
}
tempScore += max;
}
//* calculate average score.
float averageScore = (tempScore / Math.Max(targetKeywords.Count, sourceKeywords.Count));
//* if average score is bigger than minimal score and target title is not in this source title ignore list.
if (averageScore >= minimalScore && !sourceTitle.doIgnore(targetTitle))
{
//* add score.
scores.Add(sourceTitle, averageScore);
}
}
//* choose biggest score.
float maxi = float.MinValue;
foreach (KeyValuePair<Title, float> kvp in scores)
{
if (kvp.Value > maxi)
{
maxi = kvp.Value;
matchResult = new TitleMatchResult(maxi, kvp.Key, MatchTechnique.FuzzyLogic);
}
}
}
catch { }
}
//* return result.
return matchResult;
}
```
This works normally but just in some cases, a lot of titles which should match, does not match... I think I need some kind of formula to play with weights and etc, but i can't think of one..
Ideas? Suggestions? Algos?
by the way I already know this topic (My colleague already posted it but we cannot come with a proper solution for this problem.):
[Approximate string matching algorithms](https://stackoverflow.com/questions/49263/approximate-string-matching-algorithms) | Your problem here may be distinguishing between noise words and useful data:
* Rolling\_Stones.Best\_of\_2003.Wild\_Horses.mp3
* Super.Quality.Wild\_Horses.mp3
* Tori\_Amos.Wild\_Horses.mp3
You may need to produce a dictionary of noise words to ignore. That seems clunky, but I'm not sure there's an algorithm that can distinguish between band/album names and noise. |
53,482 | <p>I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall?</p>
| [
{
"answer_id": 53483,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>A quick Google resulted in this answer. In the root shell type:</p>\n\n<pre><code>mysqladmin -u root password <... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall? | **Step 1**
Stop database:
```
shell> /etc/init.d/mysql stop
```
**Step 2**
Restart database
* without password autentification
* without connection to the network
Access to database is only possible through it's sock file '/var/lib/mysql/mysql.sock'.
```
shell> mysqld --user=mysql --pid-file=/var/lib/mysql/mysqld.pid \
--socket=/var/lib/mysql/mysql.sock --datadir=/var/lib/mysql \
--skip-grant-tables --skip-networking &
```
**Step 3**
Connect to the database and change password:
```
shell> mysql --database mysql --socket=/var/lib/mysql/mysql.sock
```
If you want to, show all users:
```
mysql> select User, password from user;
```
Set new password:
```
mysql> update user set password=password('NEW PASS') WHERE User='USERNAME';
```
Leave database connection:
```
mysql> exit
```
**Step 4**
Restart database server "normally".
```
shell> kill `cat /var/lib/mysql/mysqld.pid`
shell> /etc/init.d/mysql start
``` |
53,491 | <p>How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.</p>
<p>I just tried</p>
<pre><code>grant all privileges on *.* to root@'%' identified by '*****' with grant option;
</code></pre>
<p>And restarted MySQL Server with no success.</p>
| [
{
"answer_id": 53512,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.
I just tried
```
grant all privileges on *.* to root@'%' identified by '*****' with grant option;
```
And restarted MySQL Server with no success. | You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on localhost only.
Change the `bind-address` parameter to your machine's IP address.
If this is an old MySQL installation, you should comment out the skip-networking parameter.
Afterwards, restart MySQL and you'll be set |
53,497 | <p>I'm having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with <code>::</code> or leading zeros omitted from each byte pair). </p>
<p>Can someone suggest a regular expression that would fulfill the requirement?</p>
<p>I'm considering expanding each byte pair and matching the result with a simpler regex.</p>
| [
{
"answer_id": 53499,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 5,
"selected": false,
"text": "<p>From \"<a href=\"http://vernon.mauery.com/content/projects/linux/ipv6_regex\" rel=\"noreferrer\">IPv6 regex</a>\": <... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | I'm having trouble writing a regular expression that matches valid IPv6 addresses, including those in their compressed form (with `::` or leading zeros omitted from each byte pair).
Can someone suggest a regular expression that would fulfill the requirement?
I'm considering expanding each byte pair and matching the result with a simpler regex. | I was unable to get @Factor Mystic's answer to work with POSIX regular expressions, so I wrote one that works with POSIX regular expressions and PERL regular expressions.
It should match:
* IPv6 addresses
* zero compressed IPv6 addresses ([section 2.2 of rfc5952](https://www.rfc-editor.org/rfc/rfc5952#section-2.2))
* link-local IPv6 addresses with zone index ([section 11 of rfc4007](https://www.rfc-editor.org/rfc/rfc4007#section-11))
* IPv4-Embedded IPv6 Address ([section 2 of rfc6052](https://www.rfc-editor.org/rfc/rfc6052#section-2))
* IPv4-mapped IPv6 addresses ([section 2.1 of rfc2765](https://www.rfc-editor.org/rfc/rfc2765#section-2.1))
* IPv4-translated addresses ([section 2.1 of rfc2765](https://www.rfc-editor.org/rfc/rfc2765#section-2.1))
IPv6 Regular Expression:
```
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
```
For ease of reading, the following is the above regular expression split at major OR points into separate lines:
```
# IPv6 RegEx
(
([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| # 1:2:3:4:5:6:7:8
([0-9a-fA-F]{1,4}:){1,7}:| # 1:: 1:2:3:4:5:6:7::
([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:[0-9a-fA-F]{1,4}){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
([0-9a-fA-F]{1,4}:){1,4}:
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}
(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]) # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
# IPv4 RegEx
((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
```
To make the above easier to understand, the following "pseudo" code replicates the above:
```
IPV4SEG = (25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])
IPV4ADDR = (IPV4SEG\.){3,3}IPV4SEG
IPV6SEG = [0-9a-fA-F]{1,4}
IPV6ADDR = (
(IPV6SEG:){7,7}IPV6SEG| # 1:2:3:4:5:6:7:8
(IPV6SEG:){1,7}:| # 1:: 1:2:3:4:5:6:7::
(IPV6SEG:){1,6}:IPV6SEG| # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8
(IPV6SEG:){1,5}(:IPV6SEG){1,2}| # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8
(IPV6SEG:){1,4}(:IPV6SEG){1,3}| # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8
(IPV6SEG:){1,3}(:IPV6SEG){1,4}| # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8
(IPV6SEG:){1,2}(:IPV6SEG){1,5}| # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8
IPV6SEG:((:IPV6SEG){1,6})| # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8
:((:IPV6SEG){1,7}|:)| # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::
fe80:(:IPV6SEG){0,4}%[0-9a-zA-Z]{1,}| # fe80::7:8%eth0 fe80::7:8%1 (link-local IPv6 addresses with zone index)
::(ffff(:0{1,4}){0,1}:){0,1}IPV4ADDR| # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 (IPv4-mapped IPv6 addresses and IPv4-translated addresses)
(IPV6SEG:){1,4}:IPV4ADDR # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address)
)
```
I posted a script on GitHub which tests the regular expression: <https://gist.github.com/syzdek/6086792> |
53,501 | <p>I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible?</p>
| [
{
"answer_id": 53508,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms682489(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateToolhelp32Snap... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible? | ```
Process this_process = Process.GetCurrentProcess();
int parent_pid = 0;
using (ManagementObject MgmtObj = new ManagementObject("win32_process.handle='" + this_process.Id.ToString() + "'"))
{
MgmtObj.Get();
parent_pid = Convert.ToInt32(MgmtObj["ParentProcessId"]);
}
string parent_process_name = Process.GetProcessById(parent_pid).ProcessName;
``` |
53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| [
{
"answer_id": 53522,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 14,
"selected": true,
"text": "<pre><code>if not a:\n print("List is empty")\n</code></pre>\n<p>Using the <a href=\"https://docs.python.org/libra... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | For example, if passed the following:
```
a = []
```
How do I check to see if `a` is empty? | ```
if not a:
print("List is empty")
```
Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic. |
53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| [
{
"answer_id": 53549,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 4,
"selected": false,
"text": "<p>If you <em>do</em> find you need to write unique code for an environment, use pythons </p>\n\n<pre><code>import mymod... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation? | If you *do* find you need to write unique code for an environment, use pythons
```
import mymodule_jython as mymodule
import mymodule_cpython as mymodule
```
have this stuff in a simple module (''module\_importer''?) and write your code like this:
```
from module_importer import mymodule
```
This way, all you need to do is alter `module_importer.py` per platform. |
53,545 | <p>I have an exe with an <code>App.Config</code> file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities.</p>
<p>The question is how can I access the app.config property in the exe from the wrapper dll?</p>
<p>Maybe I should be a little bit more in my questions, I have the following app.config content with the exe:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
</code></pre>
<p>The question is how to how to get "myValue" out from the wrapper dll?</p>
<hr>
<p>thanks for your solution.</p>
<p>Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">configuration manager libraries and the like</a>.</p>
<p>I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties. </p>
| [
{
"answer_id": 53552,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": "<p>It's an xml file, you can use Linq-XML or DOM based approaches to parse out the relevant information.<br>\n(that said I'd q... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I have an exe with an `App.Config` file. Now I want to create a wrapper dll around the exe in order to consume some of the functionalities.
The question is how can I access the app.config property in the exe from the wrapper dll?
Maybe I should be a little bit more in my questions, I have the following app.config content with the exe:
```
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
```
The question is how to how to get "myValue" out from the wrapper dll?
---
thanks for your solution.
Actually my initial concept was to avoid XML file reading method or LINQ or whatever. My preferred solution was to use the [configuration manager libraries and the like](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx).
I'll appreciate any help that uses the classes that are normally associated with accessing app.config properties. | After some testing, I found a way to do this.
1. Add the App.Config file to the test project. Use "Add as a link" option.
2. Use `System.Configuration.ConfigurationManager.AppSettings["myKey"]` to access the value. |
53,562 | <p>What are the steps required to enable Hibernate's second-level cache, when using the Java Persistence API (annotated entities)? How do I check that it's working? I'm using JBoss 4.2.2.GA.</p>
<p>From the Hibernate documentation, it seems that I need to enable the cache and specify a cache provider in <em>persistence.xml</em>, like:</p>
<pre><code><property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.HashtableCacheProvider" />
</code></pre>
<p>What else is required? Do I need to add <em>@Cache</em> annotations to my JPA entities?</p>
<p>How can I tell if the cache is working? I have tried accessing cache statistics after running a Query, but <em>Statistics.getSecondLevelCacheStatistics</em> returns null, perhaps because I don't know what 'region' name to use.</p>
| [
{
"answer_id": 53992,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 3,
"selected": true,
"text": "<p>I believe you need to add the cache annotations to tell hibernate how to use the second-level cache (read-only, read-wr... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] | What are the steps required to enable Hibernate's second-level cache, when using the Java Persistence API (annotated entities)? How do I check that it's working? I'm using JBoss 4.2.2.GA.
From the Hibernate documentation, it seems that I need to enable the cache and specify a cache provider in *persistence.xml*, like:
```
<property name="hibernate.cache.use_second_level_cache"
value="true" />
<property name="hibernate.cache.provider_class"
value="org.hibernate.cache.HashtableCacheProvider" />
```
What else is required? Do I need to add *@Cache* annotations to my JPA entities?
How can I tell if the cache is working? I have tried accessing cache statistics after running a Query, but *Statistics.getSecondLevelCacheStatistics* returns null, perhaps because I don't know what 'region' name to use. | I believe you need to add the cache annotations to tell hibernate how to use the second-level cache (read-only, read-write, etc). This was the case in my app (using spring / traditional hibernate and ehcache, so your mileage may vary). Once the caches were indicated, I started seeing messages that they were in use from hibernate. |
53,569 | <p>What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is:</p>
<pre><code>git log $(git merge-base HEAD branch)..branch
</code></pre>
<p>The documentation for <a href="http://git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> indicates that <code>git diff A...B</code> is equivalent to <code>git diff $(git-merge-base A B) B</code>. On the other hand, the documentation for <a href="http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html" rel="noreferrer">git-rev-parse</a> indicates that <code>r1...r2</code> is defined as <code>r1 r2 --not $(git merge-base --all r1 r2)</code>.</p>
<p>Why are these different? Note that <code>git diff HEAD...branch</code> gives me the diffs I want, but the corresponding git log command gives me more than what I want.</p>
<p>In pictures, suppose this:</p>
<pre>
x---y---z---branch
/
---a---b---c---d---e---HEAD
</pre>
<p>I would like to get a log containing commits x, y, z.</p>
<ul>
<li><code>git diff HEAD...branch</code> gives these commits</li>
<li>however, <code>git log HEAD...branch</code> gives x, y, z, c, d, e.</li>
</ul>
| [
{
"answer_id": 53573,
"author": "Lily Ballard",
"author_id": 582,
"author_profile": "https://Stackoverflow.com/users/582",
"pm_score": 9,
"selected": true,
"text": "<p>In the context of a revision list, <code>A...B</code> is how <code>git-rev-parse</code> defines it. git-log takes a revi... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
] | What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is:
```
git log $(git merge-base HEAD branch)..branch
```
The documentation for [git-diff](http://git-scm.com/docs/git-diff) indicates that `git diff A...B` is equivalent to `git diff $(git-merge-base A B) B`. On the other hand, the documentation for [git-rev-parse](http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html) indicates that `r1...r2` is defined as `r1 r2 --not $(git merge-base --all r1 r2)`.
Why are these different? Note that `git diff HEAD...branch` gives me the diffs I want, but the corresponding git log command gives me more than what I want.
In pictures, suppose this:
```
x---y---z---branch
/
---a---b---c---d---e---HEAD
```
I would like to get a log containing commits x, y, z.
* `git diff HEAD...branch` gives these commits
* however, `git log HEAD...branch` gives x, y, z, c, d, e. | In the context of a revision list, `A...B` is how `git-rev-parse` defines it. git-log takes a revision list. `git-diff` does not take a list of revisions - it takes one or two revisions, and has defined the `A...B` syntax to mean how it's defined in the `git-diff` manpage. If `git-diff` did not explicitly define `A...B`, then that syntax would be invalid. Note that the `git-rev-parse` manpage describes `A...B` in the "Specifying Ranges" section, and everything in that section is only valid in situations where a revision range is valid (i.e. when a revision list is desired).
To get a log containing just x, y, and z, try `git log HEAD..branch` (two dots, not three). This is identical to `git log branch --not HEAD`, and means all commits on branch that aren't on HEAD. |
53,599 | <p>Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me.</p>
| [
{
"answer_id": 53697,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this helps? (<a href=\"http://social.msdn.microsoft.com/forums/en-US/regexp/thread/5e87fce9-ec73-42eb-b2eb-c821e95e0d... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] | Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me. | I'd consider usage of [gettext](http://en.wikipedia.org/wiki/Gettext) and [.PO files](http://gnu.cs.pu.edu.tw/software/gettext/manual/html_node/PO-Files.html), if your program fits GNU license
1) I'd suggest extracting from .rc files using state machine algorithm.
```
void ProcessLine(const char * str)
{
if (strstr(str, " DIALOG"))
state = Scan;
else if (strstr(str, " MENU"))
state = Scan;
else if (strstr(str, " STRINGTABLE"))
state = Scan;
else if (strstr(str, "END"))
state = DontScan;
if (state == Scan)
{
const char * cur = sLine;
string hdr = ...// for example "# file.rc:453"
string msgid;
string msgid = "";
while (ExtractString(sLine, cur, msgid))
{
if (msgid.empty())
continue;
if (IsPredefined(msgid))
continue;
if (msgid.find("IDB_") == 0 || msgid.find("IDC_") == 0)
continue;
WritePoString(hdr, msgid, msgstr);
}
}
}
```
2) When extracting string inside ExtractString() you should consider that char " is represented as "", and there are also chars like \t \n \r. So state machine is also a good option here.
The following string:
```
LTEXT "Mother has washed ""Sony"", then \taquarium\\shelves\r\nand probably floors",IDC_TEXT1,24,14,224,19
```
represents such label on a dialog:
```
Mother has washed "Sony", then aquarium\shelves
and probably floors
```
3) Then on program startup you should load .po file via gettext and for each dialog translate its string on startup using a function like this:
```
int TranslateDialog(CWnd& wnd)
{
int i = 0;
CWnd *pChild;
CString text;
//Translate Title
wnd.GetWindowText(text);
LPCTSTR translation = Translate(text);
window.SetWindowText(translation);
//Translate child windows
pChild=wnd.GetWindow(GW_CHILD);
while(pChild)
{
i++;
Child->GetWindowText(Text);//including NULL
translation = Translate(Text);
pChild->SetWindowText(translation);
pChild = pChild->GetWindow(GW_HWNDNEXT);
}
return i;
}
``` |
53,623 | <p>I want to get whois information of a domain name from my c#/java programs. Is there a simple way to do this? </p>
| [
{
"answer_id": 53631,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 2,
"selected": false,
"text": "<p>I think, the easiest way is a socket connection to a whois server on port 43. Send the domainname followed by a newline and... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I want to get whois information of a domain name from my c#/java programs. Is there a simple way to do this? | I found a perfect C# example on dotnet-snippets.com (*which doesn't exist anymore*).
It's 11 lines of code to copy and paste straight into your own application.
```
/// <summary>
/// Gets the whois information.
/// </summary>
/// <param name="whoisServer">The whois server.</param>
/// <param name="url">The URL.</param>
/// <returns></returns>
private string GetWhoisInformation(string whoisServer, string url)
{
StringBuilder stringBuilderResult = new StringBuilder();
TcpClient tcpClinetWhois = new TcpClient(whoisServer, 43);
NetworkStream networkStreamWhois = tcpClinetWhois.GetStream();
BufferedStream bufferedStreamWhois = new BufferedStream(networkStreamWhois);
StreamWriter streamWriter = new StreamWriter(bufferedStreamWhois);
streamWriter.WriteLine(url);
streamWriter.Flush();
StreamReader streamReaderReceive = new StreamReader(bufferedStreamWhois);
while (!streamReaderReceive.EndOfStream)
stringBuilderResult.AppendLine(streamReaderReceive.ReadLine());
return stringBuilderResult.ToString();
}
``` |
53,629 | <p>Is it possible to see the history of changes to a particular line of code in a Subversion repository?</p>
<p>I'd like, for instance, to be able to see when a particular statement was added or when that statement was changed, even if its line number is not the same any more.</p>
| [
{
"answer_id": 53633,
"author": "Maximilian",
"author_id": 1733,
"author_profile": "https://Stackoverflow.com/users/1733",
"pm_score": 0,
"selected": false,
"text": "<p>svn blame shows you which checkin modified any line in a file the last time.</p>\n\n<p>This works on old revisions too.... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] | Is it possible to see the history of changes to a particular line of code in a Subversion repository?
I'd like, for instance, to be able to see when a particular statement was added or when that statement was changed, even if its line number is not the same any more. | I don't know a method for tracking statements through time in Subversion.
It is simple however to see when any particular line in a file was last changed using `svn blame`. Check the SVNBook: [`svn blame` reference](http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html):
**Synopsis**
```
svn blame TARGET[@REV]...
```
**Description**
Show author and revision information in-line for the specified files or URLs. Each line of text is annotated at the beginning with the author (username) and the revision number for the last change to that line. |
53,664 | <p>I've started using Vim to develop Perl scripts and am starting to find it very powerful. </p>
<p>One thing I like is to be able to open multiple files at once with:</p>
<pre><code>vi main.pl maintenance.pl
</code></pre>
<p>and then hop between them with:</p>
<pre><code>:n
:prev
</code></pre>
<p>and see which file are open with:</p>
<pre><code>:args
</code></pre>
<p>And to add a file, I can say: </p>
<pre><code>:n test.pl
</code></pre>
<p>which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type <code>:args</code> I only have <code>test.pl</code> open.</p>
<p>So how can I add and remove files in my args list?</p>
| [
{
"answer_id": 53667,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say <code>:tab... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I've started using Vim to develop Perl scripts and am starting to find it very powerful.
One thing I like is to be able to open multiple files at once with:
```
vi main.pl maintenance.pl
```
and then hop between them with:
```
:n
:prev
```
and see which file are open with:
```
:args
```
And to add a file, I can say:
```
:n test.pl
```
which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type `:args` I only have `test.pl` open.
So how can I add and remove files in my args list? | Why not use tabs (introduced in Vim 7)?
You can switch between tabs with `:tabn` and `:tabp`,
With `:tabe <filepath>` you can add a new tab; and with a regular `:q` or `:wq` you close a tab.
If you map `:tabn` and `:tabp` to your `F7`/`F8` keys you can easily switch between files.
If there are not that many files or you don't have Vim 7 you can also split your screen in multiple files: `:sp <filepath>`. Then you can switch between splitscreens with `Ctrl`+`W` and then an arrow key in the direction you want to move (or instead of arrow keys, `w` for next and `W` for previous splitscreen) |
53,676 | <p>When trying to connect to an <code>ORACLE</code> user via TOAD (Quest Software) or any other means (<code>Oracle Enterprise Manager</code>) I get this error:</p>
<blockquote>
<p><code>ORA-011033: ORACLE initialization or shutdown in progress</code></p>
</blockquote>
| [
{
"answer_id": 53684,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 8,
"selected": true,
"text": "<p>After some googling, I found the advice to do the following, and it worked:</p>\n\n<pre><code>SQL> startup mount\n\nO... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5351/"
] | When trying to connect to an `ORACLE` user via TOAD (Quest Software) or any other means (`Oracle Enterprise Manager`) I get this error:
>
> `ORA-011033: ORACLE initialization or shutdown in progress`
>
>
> | After some googling, I found the advice to do the following, and it worked:
```
SQL> startup mount
ORACLE Instance started
SQL> recover database
Media recovery complete
SQL> alter database open;
Database altered
``` |
53,728 | <p>I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.</p>
<p>Is there some way to do an XSS attack even if HTML Encode is used?</p>
| [
{
"answer_id": 53739,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.
Is there some way to do an XSS attack even if HTML Encode is used? | No.
Putting aside the subject of allowing some tags (not really the point of the question), HtmlEncode simply does NOT cover all XSS attacks.
For instance, consider server-generated client-side javascript - the server dynamically outputs htmlencoded values directly into the client-side javascript, htmlencode will **not stop** injected script from executing.
Next, consider the following pseudocode:
```
<input value=<%= HtmlEncode(somevar) %> id=textbox>
```
Now, in case its not immediately obvious, if somevar (sent by the user, of course) is set for example to
```
a onclick=alert(document.cookie)
```
the resulting output is
```
<input value=a onclick=alert(document.cookie) id=textbox>
```
which would clearly work. Obviously, this can be (almost) any other script... and HtmlEncode would not help much.
There are a few additional vectors to be considered... including the third flavor of XSS, called DOM-based XSS (wherein the malicious script is generated dynamically on the client, e.g. based on # values).
Also don't forget about UTF-7 type attacks - where the attack looks like
```
+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-
```
Nothing much to encode there...
The solution, of course (in addition to proper and restrictive white-list input validation), is to perform **context-sensitive** encoding: HtmlEncoding is great IF you're output context IS HTML, or maybe you need JavaScriptEncoding, or VBScriptEncoding, or AttributeValueEncoding, or... etc.
If you're using MS ASP.NET, you can use their Anti-XSS Library, which provides all of the necessary context-encoding methods.
Note that all encoding should not be restricted to user input, but also stored values from the database, text files, etc.
Oh, and don't forget to explicitly set the charset, both in the HTTP header AND the META tag, otherwise you'll still have UTF-7 vulnerabilities...
Some more information, and a pretty definitive list (constantly updated), check out RSnake's Cheat Sheet: <http://ha.ckers.org/xss.html> |
53,734 | <p>If you're creating a temporary table within a stored procedure and want to add an index or two on it, to improve the performance of any additional statements made against it, what is the best approach? Sybase says <a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc20020_1251/html/databases/databases644.htm" rel="noreferrer">this</a>:</p>
<p><em>"the table must contain data when the index is created. If you create the temporary table and create the index on an empty table, Adaptive Server does not create column statistics such as histograms and densities. If you insert data rows after creating the index, the optimizer has incomplete statistics."</em></p>
<p>but recently a colleague mentioned that if I create the temp table and indices in a different stored procedure to the one which actually uses the temporary table, then Adaptive Server optimiser <em>will</em> be able to make use of them.</p>
<p>On the whole, I'm not a big fan of wrapper procedures that add little value, so I've not actually got around to testing this, but I thought I'd put the question out there, to see if anyone had any other approaches or advice?</p>
| [
{
"answer_id": 53814,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "<p>What's the problem with adding the indexes after you put data into the temp table?</p>\n\n<p>One thing you need to be... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | If you're creating a temporary table within a stored procedure and want to add an index or two on it, to improve the performance of any additional statements made against it, what is the best approach? Sybase says [this](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc20020_1251/html/databases/databases644.htm):
*"the table must contain data when the index is created. If you create the temporary table and create the index on an empty table, Adaptive Server does not create column statistics such as histograms and densities. If you insert data rows after creating the index, the optimizer has incomplete statistics."*
but recently a colleague mentioned that if I create the temp table and indices in a different stored procedure to the one which actually uses the temporary table, then Adaptive Server optimiser *will* be able to make use of them.
On the whole, I'm not a big fan of wrapper procedures that add little value, so I've not actually got around to testing this, but I thought I'd put the question out there, to see if anyone had any other approaches or advice? | A few thoughts:
* If your temporary table is so big that you have to index it, then is there a better way to solve the problem?
* You can force it to use the index (if you are sure that the index is the correct way to access the table) by giving an optimiser hint, of the form:
```
SELECT *
FROM #table (index idIndex)
WHERE id = @id
```
If you are interested in performance tips in general, I've answered a couple of other questions about that at some length here:
* [Favourite performance tuning tricks](https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176)
* [How do you optimize tables for specific queries?](https://stackoverflow.com/questions/137226/how-do-you-optimize-tables-for-specific-queries#138949) |
53,744 | <p>I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well</p>
<p>This: </p>
<pre><code>\#\#
</code></pre>
<p>prints: </p>
<pre><code>\#\#
</code></pre>
<p>I would like: </p>
<pre><code>##
</code></pre>
| [
{
"answer_id": 53747,
"author": "Thomas",
"author_id": 4980,
"author_profile": "https://Stackoverflow.com/users/4980",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe, the following site helps? <a href=\"http://velocity.apache.org/tools/1.4/generic/EscapeTool.html\" rel=\"nofollow no... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well
This:
```
\#\#
```
prints:
```
\#\#
```
I would like:
```
##
``` | If you don't want to bother with the EscapeTool, you can do this:
```
#set( $H = '#' )
$H$H
``` |
53,757 | <p>Which compiles to faster code: "ans = n * 3" or "ans = n+(n*2)"?</p>
<p>Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box.</p>
<p>Would this be different if there was some dereferencing involved, that is, which of these would be faster?</p>
<pre>
long a;
long *pn;
long ans;
...
*pn = some_number;
ans = *pn * 3;
</pre>
<p>Or</p>
<pre>
ans = *pn+(*pn*2);
</pre>
<p>Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case?</p>
| [
{
"answer_id": 53759,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 7,
"selected": true,
"text": "<p>IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first pl... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137/"
] | Which compiles to faster code: "ans = n \* 3" or "ans = n+(n\*2)"?
Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box.
Would this be different if there was some dereferencing involved, that is, which of these would be faster?
```
long a;
long *pn;
long ans;
...
*pn = some_number;
ans = *pn * 3;
```
Or
```
ans = *pn+(*pn*2);
```
Or, is it something one need not worry about as optimizing compilers are likely to account for this in any case? | IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place. |
53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow noreferrer">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| [
{
"answer_id": 53791,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you try <a href=\"http://grinder.sourceforge.net\" rel=\"nofollow noreferrer\">The Grinder 3</a> to load... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357/"
] | I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)
I've chosen the [Weibull](http://en.wikipedia.org/wiki/Weibull_distribution) distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)
I use this distribution to generate the number of requests that should be sent each day between a given start and end date
I've hacked together an algorithm in Python that sort of works but it feels kludgy:
```
how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
```
What better ways are there to do this? | This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. `dev` is the std deviation in the Guassian noise, which controls the roughness. Note that this is *not* the 'right' way to generate what you want, but it's easy.
```
import math
from datetime import datetime, timedelta, date
from random import gauss
how_many_responses = 1000
start_date = date(2008, 5, 1)
end_date = date(2008, 6, 1)
num_days = (end_date - start_date).days + 1
timeline = [start_date + timedelta(i) for i in xrange(num_days)]
def weibull(x, k, l):
return (k / l) * (x / l)**(k-1) * math.e**(-(x/l)**k)
dev = 0.1
samples = [i * 1.25/(num_days-1) for i in range(num_days)]
probs = [weibull(i, 2, 0.5) for i in samples]
noise = [gauss(0, dev) for i in samples]
simdata = [max(0., e + n) for (e, n) in zip(probs, noise)]
events = [int(p * (how_many_responses / sum(probs))) for p in simdata]
histogram = zip(timeline, events)
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
``` |
53,811 | <p>Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?</p>
<p>I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size.</p>
| [
{
"answer_id": 53819,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>We always use maximize for optimal speed but then, all the code I write in C++ is somehow related to bioinformatics... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] | Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?
I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size. | As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the [Gentoo forums](http://forums.gentoo.org/) about it. Some good flags for GCC can be found in the [wiki](http://gentoo-wiki.com/Safe_Cflags).
In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a Core2Duo, -O2 gave better results over all.
There's also a [small script](http://www.pixelbeat.org/scripts/gcccpuopt) if you are interested in the x86 (32 bit) specific flags that are the most optimized.
If you use gcc and really want to optimize a specific application, try [ACOVEA](http://www.coyotegulch.com/products/acovea/). It runs a set of benchmarks, then recompile them with all possible combinations of compile flags. There's an example using Huffman encoding on the site (lower is better):
```
A relative graph of fitnesses:
Acovea Best-of-the-Best: ************************************** (2.55366)
Acovea Common Options: ******************************************* (2.86788)
-O1: ********************************************** (3.0752)
-O2: *********************************************** (3.12343)
-O3: *********************************************** (3.1277)
-O3 -ffast-math: ************************************************** (3.31539)
-Os: ************************************************* (3.30573)
```
(Note that it found -Os to be the slowest on this Opteron system.) |
53,820 | <p>In the application I'm developping (in Java/swing), I have to show a full screen window on the <em>second</em> screen of the user.
I did this using a code similar to the one you'll find below...
Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized...</p>
<p>Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows?</p>
<p>Thanks for the help,</p>
<pre><code>import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.Rectangle;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
public class FullScreenTest {
private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35"
private JPanel jContentPane = null;
private JToggleButton jToggleButton = null;
private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37"
private JLabel jLabel = null;
private Window window;
/**
* This method initializes jFrame
*
* @return javax.swing.JFrame
*/
private JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new Dimension(474, 105));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setContentPane(getJContentPane());
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToggleButton(), null);
}
return jContentPane;
}
/**
* This method initializes jToggleButton
*
* @return javax.swing.JToggleButton
*/
private JToggleButton getJToggleButton() {
if (jToggleButton == null) {
jToggleButton = new JToggleButton();
jToggleButton.setBounds(new Rectangle(50, 23, 360, 28));
jToggleButton.setText("Show Full Screen Window on 2nd screen");
jToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
showFullScreenWindow(jToggleButton.isSelected());
}
});
}
return jToggleButton;
}
protected void showFullScreenWindow(boolean b) {
if(window==null){
window = initFullScreenWindow();
}
window.setVisible(b);
}
private Window initFullScreenWindow() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
GraphicsDevice gd = gds[1];
JWindow window = new JWindow(gd.getDefaultConfiguration());
window.setContentPane(getJFSPanel());
gd.setFullScreenWindow(window);
return window;
}
/**
* This method initializes jFSPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJFSPanel() {
if (jFSPanel == null) {
jLabel = new JLabel();
jLabel.setBounds(new Rectangle(18, 19, 500, 66));
jLabel.setText("Hello ! Now, juste open windows explorer and see what happens...");
jFSPanel = new JPanel();
jFSPanel.setLayout(null);
jFSPanel.setSize(new Dimension(500, 107));
jFSPanel.add(jLabel, null);
}
return jFSPanel;
}
/**
* @param args
*/
public static void main(String[] args) {
FullScreenTest me = new FullScreenTest();
me.getJFrame().setVisible(true);
}
}
</code></pre>
| [
{
"answer_id": 53831,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 2,
"selected": true,
"text": "<p>Usually when an application is in \"full screen\" mode it will take over the entire desktop. For a user to get to ano... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2965/"
] | In the application I'm developping (in Java/swing), I have to show a full screen window on the *second* screen of the user.
I did this using a code similar to the one you'll find below...
Be, as soon as I click in a window opened by windows explorer, or as soon as I open windows explorer (i'm using windows XP), the full screen window is minimized...
Do you know any way or workaround to fix this problem, or is there something important I did not understand with full screen windows?
Thanks for the help,
```
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import java.awt.Rectangle;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
public class FullScreenTest {
private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="94,35"
private JPanel jContentPane = null;
private JToggleButton jToggleButton = null;
private JPanel jFSPanel = null; // @jve:decl-index=0:visual-constraint="392,37"
private JLabel jLabel = null;
private Window window;
/**
* This method initializes jFrame
*
* @return javax.swing.JFrame
*/
private JFrame getJFrame() {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new Dimension(474, 105));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setContentPane(getJContentPane());
}
return jFrame;
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToggleButton(), null);
}
return jContentPane;
}
/**
* This method initializes jToggleButton
*
* @return javax.swing.JToggleButton
*/
private JToggleButton getJToggleButton() {
if (jToggleButton == null) {
jToggleButton = new JToggleButton();
jToggleButton.setBounds(new Rectangle(50, 23, 360, 28));
jToggleButton.setText("Show Full Screen Window on 2nd screen");
jToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
showFullScreenWindow(jToggleButton.isSelected());
}
});
}
return jToggleButton;
}
protected void showFullScreenWindow(boolean b) {
if(window==null){
window = initFullScreenWindow();
}
window.setVisible(b);
}
private Window initFullScreenWindow() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
GraphicsDevice gd = gds[1];
JWindow window = new JWindow(gd.getDefaultConfiguration());
window.setContentPane(getJFSPanel());
gd.setFullScreenWindow(window);
return window;
}
/**
* This method initializes jFSPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJFSPanel() {
if (jFSPanel == null) {
jLabel = new JLabel();
jLabel.setBounds(new Rectangle(18, 19, 500, 66));
jLabel.setText("Hello ! Now, juste open windows explorer and see what happens...");
jFSPanel = new JPanel();
jFSPanel.setLayout(null);
jFSPanel.setSize(new Dimension(500, 107));
jFSPanel.add(jLabel, null);
}
return jFSPanel;
}
/**
* @param args
*/
public static void main(String[] args) {
FullScreenTest me = new FullScreenTest();
me.getJFrame().setVisible(true);
}
}
``` | Usually when an application is in "full screen" mode it will take over the entire desktop. For a user to get to another window they would have to alt-tab to it. At that point windows would minimize the full screen app so that the other application could come to the front.
This sounds like it may be a bug (undocumented feature...) in windows. It should probably not be doing this for a dual screen setup.
One option to fix this is rather than setting it to be "full screen" just make the window the same size as the screen with location (0,0). You can get screen information from the [GraphicsConfigurations on the GraphicsDevice](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/GraphicsDevice.html#getConfigurations%28%29). |
53,824 | <p>I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication.</p>
<p>To perform the handshake, I am using this code:</p>
<pre><code>SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Default, false);
</code></pre>
<p>Unfortunately, this results in the SslStream transmitting a CertificateRequest containing the subjectnames of all certificates in my CryptoAPI Trusted Root Store.</p>
<p>I would like to be able to override this. It is not an option for me to require the user to install or remove certificates from the Trusted Root Store.</p>
<p>It looks like the SslStream uses SSPI/SecureChannel underneath, so if anyone knows how to do the equivalent with that API, that would be helpful, too.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 54321,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 2,
"selected": false,
"text": "<p>What the certificate validation is doing is validating all certificates in the chain. In order to truely do that it... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5542/"
] | I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication.
To perform the handshake, I am using this code:
```
SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Default, false);
```
Unfortunately, this results in the SslStream transmitting a CertificateRequest containing the subjectnames of all certificates in my CryptoAPI Trusted Root Store.
I would like to be able to override this. It is not an option for me to require the user to install or remove certificates from the Trusted Root Store.
It looks like the SslStream uses SSPI/SecureChannel underneath, so if anyone knows how to do the equivalent with that API, that would be helpful, too.
Any ideas? | It does not look like this is currently possible using the .NET libraries.
I solved it by using the Mono class library implementation of System.Security.SslStream, which gives better access to overriding the servers behavior during the handshake. |
53,844 | <p>I would like to do the equivalent of:</p>
<pre><code>object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
</code></pre>
<p>Following Biri s <a href="http://www.codeproject.com/KB/cs/evalcscode.aspx" rel="noreferrer">link</a>, I got this snippet (modified to remove obsolete method <code>ICodeCompiler.CreateCompiler()</code>:</p>
<pre><code>private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
</code></pre>
| [
{
"answer_id": 54339,
"author": "JJJ",
"author_id": 5547,
"author_profile": "https://Stackoverflow.com/users/5547",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>What are the performance implications of doing this?</p>\n</blockquote>\n\n<p>We use a system based on somethi... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I would like to do the equivalent of:
```
object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
```
Following Biri s [link](http://www.codeproject.com/KB/cs/evalcscode.aspx), I got this snippet (modified to remove obsolete method `ICodeCompiler.CreateCompiler()`:
```
private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
``` | I have written an open source project, [Dynamic Expresso](https://github.com/davideicardi/DynamicExpresso/), that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into [Expression Trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) without using compilation or reflection.
You can write something like:
```
var interpreter = new Interpreter();
var result = interpreter.Eval("8 / 2 + 2");
```
or
```
var interpreter = new Interpreter()
.SetVariable("service", new ServiceExample());
string expression = "x > 4 ? service.aMethod() : service.AnotherMethod()";
Lambda parsedExpression = interpreter.Parse(expression,
new Parameter("x", typeof(int)));
parsedExpression.Invoke(5);
```
My work is based on Scott Gu article <http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx> . |
53,849 | <p>Java has a convenient split method:</p>
<pre><code>String str = "The quick brown fox";
String[] results = str.split(" ");
</code></pre>
<p>Is there an easy way to do this in C++?</p>
| [
{
"answer_id": 53862,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a sample tokenizer class that might do what you want </p>\n\n<pre><code>//Header file\nclass Tokenizer \n{\n public... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | Java has a convenient split method:
```
String str = "The quick brown fox";
String[] results = str.split(" ");
```
Is there an easy way to do this in C++? | C++ standard library algorithms are pretty universally based around iterators rather than concrete containers. Unfortunately this makes it hard to provide a Java-like `split` function in the C++ standard library, even though nobody argues that this would be convenient. But what would its return type be? `std::vector<std::basic_string<…>>`? Maybe, but then we’re forced to perform (potentially redundant and costly) allocations.
Instead, C++ offers a plethora of ways to split strings based on arbitrarily complex delimiters, but none of them is encapsulated as nicely as in other languages. The numerous ways [fill whole blog posts](https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/).
At its simplest, you could iterate using [`std::string::find`](http://en.cppreference.com/w/cpp/string/basic_string/find) until you hit `std::string::npos`, and extract the contents using [`std::string::substr`](https://en.cppreference.com/w/cpp/string/basic_string/substr).
A more fluid (and idiomatic, but basic) version for splitting on whitespace would use a [`std::istringstream`](https://en.cppreference.com/w/cpp/io/basic_istringstream):
```
auto iss = std::istringstream{"The quick brown fox"};
auto str = std::string{};
while (iss >> str) {
process(str);
}
```
Using [`std::istream_iterator`s](https://en.cppreference.com/w/cpp/iterator/istream_iterator), the contents of the string stream could also be copied into a vector using its iterator range constructor.
Multiple libraries (such as [Boost.Tokenizer](https://www.boost.org/doc/libs/1_70_0/libs/tokenizer/doc/tokenizer.htm)) offer specific tokenisers.
More advanced splitting require regular expressions. C++ provides the [`std::regex_token_iterator`](https://en.cppreference.com/w/cpp/regex/regex_token_iterator) for this purpose in particular:
```
auto const str = "The quick brown fox"s;
auto const re = std::regex{R"(\s+)"};
auto const vec = std::vector<std::string>(
std::sregex_token_iterator{begin(str), end(str), re, -1},
std::sregex_token_iterator{}
);
``` |
53,911 | <p>Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.</p>
<p>The problem is that after I search and find, I need to MANUALLY find my way back to where I was.</p>
<p>Is there an automatic way to go back to where I was when I initiated my last search?</p>
| [
{
"answer_id": 53924,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": false,
"text": "<p>I've always done by it setting a mark.</p>\n\n<ol>\n<li><p>In command-mode, press <strong><kbd>m</kbd><em>[letter]</em></s... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.
The problem is that after I search and find, I need to MANUALLY find my way back to where I was.
Is there an automatic way to go back to where I was when I initiated my last search? | `Ctrl`+`O` takes me to the previous location. Don't know about location before the search.
Edit: Also, ````.` will take you to the last change you made. |
53,945 | <p>I am currently loading a lightbox style popup that loads it's HTML from an XHR call. This content is then displayed in a 'modal' popup using <code>element.innerHTML = content</code> This works like a charm.</p>
<p>In another section of this website I use a Flickr 'badge' (<a href="http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/" rel="noreferrer">http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/</a>) to load flickr images dynamically. This is done including a script tag that loads a flickr javascript, which in turn does some <code>document.write</code> statments.</p>
<p>Both of them work perfectly when included in the HTML. Only when loading the flickr badge code <em>inside</em> the lightbox, no content is rendered at all. It seems that using <code>innerHTML</code> to write <code>document.write</code> statements is taking it a step too far, but I cannot find any clue in the javascript implementations (FF2&3, IE6&7) of this behavior.</p>
<p>Can anyone clarify if this should or shouldn't work? Thanks.</p>
| [
{
"answer_id": 54002,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p>Can I get some clarification first to make sure I get the problem?</p>\n\n<p><code>document.write</code> calls will add c... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4174/"
] | I am currently loading a lightbox style popup that loads it's HTML from an XHR call. This content is then displayed in a 'modal' popup using `element.innerHTML = content` This works like a charm.
In another section of this website I use a Flickr 'badge' (<http://www.elliotswan.com/2006/08/06/custom-flickr-badge-api-documentation/>) to load flickr images dynamically. This is done including a script tag that loads a flickr javascript, which in turn does some `document.write` statments.
Both of them work perfectly when included in the HTML. Only when loading the flickr badge code *inside* the lightbox, no content is rendered at all. It seems that using `innerHTML` to write `document.write` statements is taking it a step too far, but I cannot find any clue in the javascript implementations (FF2&3, IE6&7) of this behavior.
Can anyone clarify if this should or shouldn't work? Thanks. | In general, script tags aren't executed when using innerHTML. In your case, this is good, because the `document.write` call would wipe out everything that's already in the page. However, that leaves you without whatever HTML document.write was supposed to add.
jQuery's HTML manipulation methods will execute scripts in HTML for you, the trick is then capturing the calls to `document.write` and getting the HTML in the proper place. If it's simple enough, then something like this will do:
```
var content = '';
document.write = function(s) {
content += s;
};
// execute the script
$('#foo').html(markupWithScriptInIt);
$('#foo .whereverTheDocumentWriteContentGoes').html(content);
```
It gets complicated though. If the script is on another domain, it will be loaded asynchronously, so you'll have to wait until it's done to get the content. Also, what if it just writes the HTML into the middle of the fragment without a wrapper element that you can easily select? [writeCapture.js](http://github.com/iamnoah/writeCapture) (full disclosure: I wrote it) handles all of these problems. I'd recommend just using it, but at the very least you can look at the code to see how it handles everything.
EDIT: Here is a [page](http://iamnoah.github.com/writeCapture/lbFlickrDemo.html) demonstrating what sounds like the effect you want. |
53,965 | <pre><code>$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
</code></pre>
<p>I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma followed by the numerical digits and then the semicolon.</p>
<p>I'll provide an example:</p>
<p>Start:</p>
<pre><code>hello world 1007;
</code></pre>
<p>End:</p>
<pre><code>hello world,1007;
</code></pre>
| [
{
"answer_id": 53988,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p>Should those forward-slashes be backslashes? You'll need to escape them for PHP too unless you change your double-quotes ... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | ```
$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
```
I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma followed by the numerical digits and then the semicolon.
I'll provide an example:
Start:
```
hello world 1007;
```
End:
```
hello world,1007;
``` | The two `|` at the start and end probably are incorrect - and should both be forward-slashes.
All other forward slashes should be backward slashes (and need escaping).
And since PHP 4.04 `$n` is the preferred way of referring to a capture group.
```
$output = preg_replace("/(\\D)\\s+(\\d+;)/", "$1,$2", $output);
```
If you use single quotes you don't need to escape your backslashes:
```
$output = preg_replace('/(\D)\s+(\d+;)/', '$1,$2', $output);
``` |
53,967 | <p>I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom <code>IEnumerator</code> interface that iterates through the values.</p>
<pre><code>public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
</code></pre>
| [
{
"answer_id": 53986,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>Use yield return.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c#39... | 2008/09/10 | [
"https://Stackoverflow.com/questions/53967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] | I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom `IEnumerator` interface that iterates through the values.
```
public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
``` | First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection).
Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.
Raymond Chen's recent series of blog posts ("The implementation of iterators in C# and its consequences") is a good place to get up to speed.
* Part 1: <https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx>
* Part 2: <https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx>
* Part 3: <https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx>
* Part 4: <https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx> |
54,010 | <p>I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.</p>
<p>Say I have a list of tuples ( <code>List[Tuple2[String, String]]</code>, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand?</p>
| [
{
"answer_id": 54123,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 3,
"selected": false,
"text": "<p>You could try using <a href=\"http://www.scala-lang.org/api/current/index.html#scala.collection.parallel.ParIterableLik... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've recently been working on a beginner's project in Scala, and have a beginner question about Scala's Lists.
Say I have a list of tuples ( `List[Tuple2[String, String]]`, for example). Is there a convenience method to return the first occurence of a specified tuple from the List, or is it necessary to iterate through the list by hand? | ```
scala> val list = List(("A", "B", 1), ("C", "D", 1), ("E", "F", 1), ("C", "D", 2), ("G", "H", 1))
list: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1))
scala> list find {e => e._1 == "C" && e._2 == "D"}
res0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1))
``` |
54,043 | <p>I would like to be able to do such things as</p>
<pre><code>var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds);
var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters);
m1.ToKilograms();
m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon);
</code></pre>
<p>If there isn't something like this already, anybody interested in doing it as an os project?</p>
| [
{
"answer_id": 54049,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Check out the <a href=\"http://www.codeproject.com/KB/library/Measurement_Conversion.aspx\" rel=\"nofollow noreferr... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I would like to be able to do such things as
```
var m1 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Pounds);
var m2 = new UnitOfMeasureQuantityPair(123.00, UnitOfMeasure.Liters);
m1.ToKilograms();
m2.ToPounds(new Density(7.0, DensityType.PoundsPerGallon);
```
If there isn't something like this already, anybody interested in doing it as an os project? | Check out the [Measurement Unit Conversion Library](http://www.codeproject.com/KB/library/Measurement_Conversion.aspx) on The Code Project. |
54,059 | <p>Say I have a linked list of numbers of length <code>N</code>. <code>N</code> is very large and I don’t know in advance the exact value of <code>N</code>. </p>
<p>How can I most efficiently write a function that will return <code>k</code> completely <em>random numbers</em> from the list?</p>
| [
{
"answer_id": 54070,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your ra... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Say I have a linked list of numbers of length `N`. `N` is very large and I don’t know in advance the exact value of `N`.
How can I most efficiently write a function that will return `k` completely *random numbers* from the list? | There's a very nice and efficient algorithm for this using a method called **reservoir sampling**.
Let me start by giving you its **history**:
**Knuth** calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.
**McLeod and Bellhouse, 1983** (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.
**Vitter 1985** (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.
In **pseudocode** the algorithm is:
```
Let R be the result array of size s
Let I be an input queue
> Fill the reservoir array
for j in the range [1,s]:
R[j]=I.pop()
elements_seen=s
while I is not empty:
elements_seen+=1
j=random(1,elements_seen) > This is inclusive
if j<=s:
R[j]=I.pop()
else:
I.pop()
```
Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it *still* assures you that each element you encounter has an equal probability of ending up in `R` (that is, there is no bias). Furthermore, `R` contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an [online algorithm](https://en.wikipedia.org/wiki/Online_algorithm).
**Why does this work?**
McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.
We proceed via proof by induction.
Say we want to generate a set of `s` elements and that we have already seen `n>s` elements.
Let's assume that our current `s` elements have already each been chosen with probability `s/n`.
By the definition of the algorithm, we choose element `n+1` with probability `s/(n+1)`.
Each element already part of our result set has a probability `1/s` of being replaced.
The probability that an element from the `n`-seen result set is replaced in the `n+1`-seen result set is therefore `(1/s)*s/(n+1)=1/(n+1)`. Conversely, the probability that an element is not replaced is `1-1/(n+1)=n/(n+1)`.
Thus, the `n+1`-seen result set contains an element either if it was part of the `n`-seen result set and was not replaced---this probability is `(s/n)*n/(n+1)=s/(n+1)`---or if the element was chosen---with probability `s/(n+1)`.
The definition of the algorithm tells us that the first `s` elements are automatically included as the first `n=s` members of the result set. Therefore, the `n-seen` result set includes each element with `s/n` (=1) probability giving us the necessary base case for the induction.
**References**
1. McLeod, A. Ian, and David R. Bellhouse. "A convenient algorithm for drawing a simple random sample." Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. ([Link](http://www.jstor.org/stable/10.2307/2347297))
2. Vitter, Jeffrey S. "Random sampling with a reservoir." ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. ([Link](http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf)) |
54,068 | <p>I'm looking at a new computer which will probably have vista on it. But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions? For instance you couldn't run IIS on Windows ME. Can you still run IIS on the home editions of vista? </p>
| [
{
"answer_id": 54070,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your ra... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | I'm looking at a new computer which will probably have vista on it. But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions? For instance you couldn't run IIS on Windows ME. Can you still run IIS on the home editions of vista? | There's a very nice and efficient algorithm for this using a method called **reservoir sampling**.
Let me start by giving you its **history**:
**Knuth** calls this Algorithm R on p. 144 of his 1997 edition of Seminumerical Algorithms (volume 2 of The Art of Computer Programming), and provides some code for it there. Knuth attributes the algorithm to Alan G. Waterman. Despite a lengthy search, I haven't been able to find Waterman's original document, if it exists, which may be why you'll most often see Knuth quoted as the source of this algorithm.
**McLeod and Bellhouse, 1983** (1) provide a more thorough discussion than Knuth as well as the first published proof (that I'm aware of) that the algorithm works.
**Vitter 1985** (2) reviews Algorithm R and then presents an additional three algorithms which provide the same output, but with a twist. Rather than making a choice to include or skip each incoming element, his algorithm predetermines the number of incoming elements to be skipped. In his tests (which, admittedly, are out of date now) this decreased execution time dramatically by avoiding random number generation and comparisons on each in-coming number.
In **pseudocode** the algorithm is:
```
Let R be the result array of size s
Let I be an input queue
> Fill the reservoir array
for j in the range [1,s]:
R[j]=I.pop()
elements_seen=s
while I is not empty:
elements_seen+=1
j=random(1,elements_seen) > This is inclusive
if j<=s:
R[j]=I.pop()
else:
I.pop()
```
Note that I've specifically written the code to avoid specifying the size of the input. That's one of the cool properties of this algorithm: you can run it without needing to know the size of the input beforehand and it *still* assures you that each element you encounter has an equal probability of ending up in `R` (that is, there is no bias). Furthermore, `R` contains a fair and representative sample of the elements the algorithm has considered at all times. This means you can use this as an [online algorithm](https://en.wikipedia.org/wiki/Online_algorithm).
**Why does this work?**
McLeod and Bellhouse (1983) provide a proof using the mathematics of combinations. It's pretty, but it would be a bit difficult to reconstruct it here. Therefore, I've generated an alternative proof which is easier to explain.
We proceed via proof by induction.
Say we want to generate a set of `s` elements and that we have already seen `n>s` elements.
Let's assume that our current `s` elements have already each been chosen with probability `s/n`.
By the definition of the algorithm, we choose element `n+1` with probability `s/(n+1)`.
Each element already part of our result set has a probability `1/s` of being replaced.
The probability that an element from the `n`-seen result set is replaced in the `n+1`-seen result set is therefore `(1/s)*s/(n+1)=1/(n+1)`. Conversely, the probability that an element is not replaced is `1-1/(n+1)=n/(n+1)`.
Thus, the `n+1`-seen result set contains an element either if it was part of the `n`-seen result set and was not replaced---this probability is `(s/n)*n/(n+1)=s/(n+1)`---or if the element was chosen---with probability `s/(n+1)`.
The definition of the algorithm tells us that the first `s` elements are automatically included as the first `n=s` members of the result set. Therefore, the `n-seen` result set includes each element with `s/n` (=1) probability giving us the necessary base case for the induction.
**References**
1. McLeod, A. Ian, and David R. Bellhouse. "A convenient algorithm for drawing a simple random sample." Journal of the Royal Statistical Society. Series C (Applied Statistics) 32.2 (1983): 182-184. ([Link](http://www.jstor.org/stable/10.2307/2347297))
2. Vitter, Jeffrey S. "Random sampling with a reservoir." ACM Transactions on Mathematical Software (TOMS) 11.1 (1985): 37-57. ([Link](http://www.mathcs.emory.edu/~cheung/Courses/584-StreamDB/Syllabus/papers/RandomSampling/1985-Vitter-Random-sampling-with-reservior.pdf)) |
54,138 | <p>I have a third-party app that creates HTML-based reports that I need to display. I have <em>some</em> control over how they look, but in general it's pretty primitive. I <em>can</em> inject some javascript, though. I'd like to try to inject some jQuery goodness into it to tidy it up some. One specific thing I would like to do is to take a table (an actual HTML <table>) that always contains one row and a variable number of columns and magically convert that into a tabbed view where the contents (always one <div> that I can supply an ID if necessary) of each original table cell represents a sheet in the tabbed view. I haven't found any good (read: simple) examples of re-parenting items like this, so I'm not sure where to begin. Can someone provide some hints on how I might try this?</p>
| [
{
"answer_id": 54145,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>You could do this with jQuery but it may make additional maintenance a nightmare. I would recommend against do... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a third-party app that creates HTML-based reports that I need to display. I have *some* control over how they look, but in general it's pretty primitive. I *can* inject some javascript, though. I'd like to try to inject some jQuery goodness into it to tidy it up some. One specific thing I would like to do is to take a table (an actual HTML <table>) that always contains one row and a variable number of columns and magically convert that into a tabbed view where the contents (always one <div> that I can supply an ID if necessary) of each original table cell represents a sheet in the tabbed view. I haven't found any good (read: simple) examples of re-parenting items like this, so I'm not sure where to begin. Can someone provide some hints on how I might try this? | Given a html page like this:
```
<body><br/>
<table id="my-table">`<br/>
<tr><br/>
<td><div>This is the contents of Column One</div></td><br/>
<td><div>This is the contents of Column Two</div></td><br/>
<td><div>This is the contents of Column Three</div></td><br/>
<td><div>Contents of Column Four blah blah</div></td><br/>
<td><div>Column Five is here</div></td><br/>
</tr><br/>
</table><br/>
</body><br/>
```
the following jQuery code converts the table cells into tabs (tested in FF 3 and IE 7)
```
$(document).ready(function() {
var tabCounter = 1;
$("#my-table").after("<div id='tab-container' class='flora'><ul id='tab-list'></ul></div>");
$("#my-table div").appendTo("#tab-container").each(function() {
var id = "fragment-" + tabCounter;
$(this).attr("id", id);
$("#tab-list").append("<li><span><a href='#" + id + "'>Tab " + tabCounter + "</a></span></li>");
tabCounter++;
});
$("#tab-container > ul").tabs();
});
```
To get this to work I referenced the following jQuery files
* jquery-latest.js
* ui.core.js
* ui.tabs.js
And I referenced the flora.all.css stylesheet. Basically I copied the header section from the [jQuery tab example](http://docs.jquery.com/UI/Tabs#Example) |
54,142 | <p>How does the comma operator work in C++?</p>
<p>For instance, if I do:</p>
<pre><code>a = b, c;
</code></pre>
<p>Does a end up equaling b or c? </p>
<p>(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)</p>
<p><strong>Update:</strong> This question has exposed a nuance when using the comma operator. Just to document this:</p>
<pre><code>a = b, c; // a is set to the value of b!
a = (b, c); // a is set to the value of c!
</code></pre>
<p>This question was actually inspired by a typo in code. What was intended to be</p>
<pre><code>a = b;
c = d;
</code></pre>
<p>Turned into</p>
<pre><code>a = b, // <- Note comma typo!
c = d;
</code></pre>
| [
{
"answer_id": 54146,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 7,
"selected": true,
"text": "<p>It would be equal to <code>b</code>.</p>\n\n<p>The comma operator has a lower precedence than assignment.</p>\n"
... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541/"
] | How does the comma operator work in C++?
For instance, if I do:
```
a = b, c;
```
Does a end up equaling b or c?
(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)
**Update:** This question has exposed a nuance when using the comma operator. Just to document this:
```
a = b, c; // a is set to the value of b!
a = (b, c); // a is set to the value of c!
```
This question was actually inspired by a typo in code. What was intended to be
```
a = b;
c = d;
```
Turned into
```
a = b, // <- Note comma typo!
c = d;
``` | It would be equal to `b`.
The comma operator has a lower precedence than assignment. |
54,147 | <p>I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?</p>
<p>The script needs to find the active textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.</p>
<p><strong>EDIT:</strong> It is also ok to insert the character "last" in the previously active textbox.</p>
| [
{
"answer_id": 54162,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<p>Note that if the user pushes a button, focus on the textbox will be lost and there will be no caret position!</p>\n"
... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523/"
] | I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?
The script needs to find the active textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.
**EDIT:** It is also ok to insert the character "last" in the previously active textbox. | I think Jason Cohen is incorrect. The caret position is preserved when focus is lost.
[**Edit**: Added code for FireFox that I didn't have originally.]
[**Edit**: Added code to determine the most recent active text box.]
First, you can use each text box's onBlur event to set a variable to "this" so you always know the most recent active text box.
Then, there's an IE way to get the cursor position that also works in Opera, and an easier way in Firefox.
In IE the basic concept is to use the document.selection object and *put* some text *into* the selection. Then, using indexOf, you can get the position of the text you added.
In FireFox, there's a method called selectionStart that will give you the cursor position.
Once you have the cursor position, you overwrite the whole text.value with
text before the cursor position + the text you want to insert + the text after the cursor position
Here is an example with separate links for IE and FireFox. You can use you favorite browser detection method to figure out which code to run.
```
<html><head></head><body>
<script language="JavaScript">
<!--
var lasttext;
function doinsert_ie() {
var oldtext = lasttext.value;
var marker = "##MARKER##";
lasttext.focus();
var sel = document.selection.createRange();
sel.text = marker;
var tmptext = lasttext.value;
var curpos = tmptext.indexOf(marker);
pretext = oldtext.substring(0,curpos);
posttest = oldtext.substring(curpos,oldtext.length);
lasttext.value = pretext + "|" + posttest;
}
function doinsert_ff() {
var oldtext = lasttext.value;
var curpos = lasttext.selectionStart;
pretext = oldtext.substring(0,curpos);
posttest = oldtext.substring(curpos,oldtext.length);
lasttext.value = pretext + "|" + posttest;
}
-->
</script>
<form name="testform">
<input type="text" name="testtext1" onBlur="lasttext=this;">
<input type="text" name="testtext2" onBlur="lasttext=this;">
<input type="text" name="testtext3" onBlur="lasttext=this;">
</form>
<a href="#" onClick="doinsert_ie();">Insert IE</a>
<br>
<a href="#" onClick="doinsert_ff();">Insert FF</a>
</body></html>
```
This will also work with textareas. I don't know how to reposition the cursor so it stays at the insertion point. |
54,219 | <p>I'm working on an editor for files that are used by an important internal testing tool we use. The tool itself is large, complicated, and refactoring or rewriting would take more resources than we are able to devote to it for the forseeable future, so my hands are tied when it comes to large modifications. I must use a .NET language.</p>
<p>The files are XML serialized versions of four classes that are used by the tool (let's call them A, B, C, and D). The classes form a tree structure when all is well. Our editor works by loading a set of files, deserializing them, working out the relationships between them, and keeping track of any bad states it can find. The idea is for us to move away from hand-editing these files, which introduces tons of errors.</p>
<p>For a particular type of error, I'd like to maintain a collection of all files that have the problem. All four classes can have the problem, and I'd like to reduce duplication of code as much as possible. An important requirement is the user needs to be able to get the items in sets; for example, they need to get all A objects with an error, and telling them to iterate over the whole collection and pick out what they want is unacceptable compared to a <code>GetAs()</code> method. So, my first thought was to make a generic item that related the deserialized object and some metadata to indicate the error:</p>
<pre><code>public class ErrorItem<T>
{
public T Item { get; set; }
public Metadata Metadata { get; set; }
}
</code></pre>
<p>Then, I'd have a collection class that could hold all of the error items, with helper methods to extract the items of a specific class when the user needs them. This is where the trouble starts.</p>
<p>None of the classes inherit from a common ancestor (other than <code>Object</code>). This was probably a mistake of the initial design, but I've spent a few days thinking about it and the classes really don't have much in common other than a GUID property that uniquely identifies each item so I can see why the original designer did not relate them through inheritance. This means that the unified error collection would need to store <code>ErrorItem<Object></code> objects, since I don't have a base class or interface to restrict what comes in. However, this makes the idea of this unified collection a little sketchy to me:</p>
<pre><code>Public Class ErrorCollection
{
public ErrorItem<Object> AllItems { get; set; }
}
</code></pre>
<p>However, this has consequences on the public interface. What I really want is to return the appropriate <code>ErrorItem</code> generic type like this:</p>
<pre><code>public ErrorItem<A>[] GetA()
</code></pre>
<p>This is impossible because I can only store <code>ErrorItem<Object></code>! I've gone over some workarounds in my head; mostly they include creating a new <code>ErrorItem</code> of the appropriate type on-the-fly, but it just feels kind of ugly. Another thought has been using a <code>Dictionary</code> to keep items organized by type, but it still doesn't seem right.</p>
<p>Is there some kind of pattern that might help me here? I know the easiest way to solve this is to add a base class that A, B, C, and D derive from, but I'm trying to have as small an impact on the original tool as possible. Is the cost of any workaround great enough that I should push to change the initial tool?</p>
| [
{
"answer_id": 54258,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": true,
"text": "<p>If A, B, C and D have nothing in common then adding a base class won't really get you anything. It will just be an empty cl... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
] | I'm working on an editor for files that are used by an important internal testing tool we use. The tool itself is large, complicated, and refactoring or rewriting would take more resources than we are able to devote to it for the forseeable future, so my hands are tied when it comes to large modifications. I must use a .NET language.
The files are XML serialized versions of four classes that are used by the tool (let's call them A, B, C, and D). The classes form a tree structure when all is well. Our editor works by loading a set of files, deserializing them, working out the relationships between them, and keeping track of any bad states it can find. The idea is for us to move away from hand-editing these files, which introduces tons of errors.
For a particular type of error, I'd like to maintain a collection of all files that have the problem. All four classes can have the problem, and I'd like to reduce duplication of code as much as possible. An important requirement is the user needs to be able to get the items in sets; for example, they need to get all A objects with an error, and telling them to iterate over the whole collection and pick out what they want is unacceptable compared to a `GetAs()` method. So, my first thought was to make a generic item that related the deserialized object and some metadata to indicate the error:
```
public class ErrorItem<T>
{
public T Item { get; set; }
public Metadata Metadata { get; set; }
}
```
Then, I'd have a collection class that could hold all of the error items, with helper methods to extract the items of a specific class when the user needs them. This is where the trouble starts.
None of the classes inherit from a common ancestor (other than `Object`). This was probably a mistake of the initial design, but I've spent a few days thinking about it and the classes really don't have much in common other than a GUID property that uniquely identifies each item so I can see why the original designer did not relate them through inheritance. This means that the unified error collection would need to store `ErrorItem<Object>` objects, since I don't have a base class or interface to restrict what comes in. However, this makes the idea of this unified collection a little sketchy to me:
```
Public Class ErrorCollection
{
public ErrorItem<Object> AllItems { get; set; }
}
```
However, this has consequences on the public interface. What I really want is to return the appropriate `ErrorItem` generic type like this:
```
public ErrorItem<A>[] GetA()
```
This is impossible because I can only store `ErrorItem<Object>`! I've gone over some workarounds in my head; mostly they include creating a new `ErrorItem` of the appropriate type on-the-fly, but it just feels kind of ugly. Another thought has been using a `Dictionary` to keep items organized by type, but it still doesn't seem right.
Is there some kind of pattern that might help me here? I know the easiest way to solve this is to add a base class that A, B, C, and D derive from, but I'm trying to have as small an impact on the original tool as possible. Is the cost of any workaround great enough that I should push to change the initial tool? | If A, B, C and D have nothing in common then adding a base class won't really get you anything. It will just be an empty class and in effect will be the same as object.
I'd just create an ErrorItem class without the generics, make Item an object and do some casting when you want to use the objects referenced. If you want to use any of the properties or methods of the A, B, C or D class other than the Guid you would have had to cast them anyway. |
54,227 | <p>I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx". </p>
<p>Path.Combine didn't fix it. Is there a function to clean this path up? </p>
| [
{
"answer_id": 54273,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 3,
"selected": true,
"text": "<p>You could create a helper class which wrapped the UriBuilder class in System.Net</p>\n\n<pre><code>public static class... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5599/"
] | I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx".
Path.Combine didn't fix it. Is there a function to clean this path up? | You could create a helper class which wrapped the UriBuilder class in System.Net
```
public static class UriHelper
{
public static string NormalizeRelativePath(string path)
{
UriBuilder _builder = new UriBuilder("http://localhost");
builder.Path = path;
return builder.Uri.AbsolutePath;
}
}
```
which could then be used like this:
```
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
```
It is a bit hacky but it would work for the specific example you gave.
**EDIT: Updated to reflect Andrew's comments.** |
54,237 | <p>I want to link to bookmark on a page (mysite.com/mypage.htm#bookmark) AND visually highlight the item that was bookmarked (maybe having a red border). Naturally, there would be multiple items bookmarked. So that if someone clicked on #bookmark2 then <em>that</em> other area would be highlighted). </p>
<p>I can see how to do that with .asp or .aspx but I'd like to do it more simply than that. I thought maybe there was a clever way to do it with CSS.</p>
<p>WHY I'm interested:
- I want to have our programs link to a shopping page that lists all the programs on it. I'm using a bookmark so they're jumping to the particular program area (site.com/shoppingpage#Programx) but just to make it <em>obvious</em> I'd like to actually highlight the page being linked to.</p>
| [
{
"answer_id": 54257,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>I guess if you could store this information with JavaScript and cookies for the functionality of remembering the bookmark... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] | I want to link to bookmark on a page (mysite.com/mypage.htm#bookmark) AND visually highlight the item that was bookmarked (maybe having a red border). Naturally, there would be multiple items bookmarked. So that if someone clicked on #bookmark2 then *that* other area would be highlighted).
I can see how to do that with .asp or .aspx but I'd like to do it more simply than that. I thought maybe there was a clever way to do it with CSS.
WHY I'm interested:
- I want to have our programs link to a shopping page that lists all the programs on it. I'm using a bookmark so they're jumping to the particular program area (site.com/shoppingpage#Programx) but just to make it *obvious* I'd like to actually highlight the page being linked to. | In your css you need to define
```css
a.highlight {border:1px solid red;}
```
or something similar
Then using jQuery,
```
$(document).ready ( function () { //Work as soon as the DOM is ready for parsing
var id = location.hash.substr(1); //Get the word after the hash from the url
if (id) $('#'+id).addClass('highlight'); // add class highlight to element whose id is the word after the hash
});
```
To highlight the targets on mouse over also add:
```
$("a[href^='#']")
.mouseover(function() {
var id = $(this).attr('href').substr(1);
$('#'+id).addClass('highlight');
})
.mouseout(function() {
var id = $(this).attr('href').substr(1);
$('#'+id).removeClass('highlight');
});
``` |
54,255 | <p>Using Vim I often want to replace a block of code with a block that I just yanked.</p>
<p>But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.</p>
<p>So what is the slickest and quickest way to replace text in Vim?</p>
<ul>
<li>is there a way to delete text without putting it into the register?</li>
<li>is there a way to say e.g. "replace next word" or "replace up to next paragraph"</li>
<li>or is the best way to somehow use the multi-register feature?</li>
</ul>
| [
{
"answer_id": 54265,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 3,
"selected": false,
"text": "<p>Well, first do this command:</p>\n\n<pre><code>:h d\n</code></pre>\n\n<p>Then you will realize that you can delete into a ... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | Using Vim I often want to replace a block of code with a block that I just yanked.
But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.
So what is the slickest and quickest way to replace text in Vim?
* is there a way to delete text without putting it into the register?
* is there a way to say e.g. "replace next word" or "replace up to next paragraph"
* or is the best way to somehow use the multi-register feature? | To delete something without saving it in a register, you can use the "black hole register":
```
"_d
```
Of course you could also use any of the other registers that don't hold anything you are interested in. |
54,295 | <p>I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order? </p>
<pre><code>String propFile = "/path/to/file";
Properties props = new Properties();
/*set some properties here*/
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/*this comes out unsorted*/
props.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
</code></pre>
| [
{
"answer_id": 54303,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>java.util.Properties is based on Hashtable, which does not store its values in alphabetical order, but in order of the h... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5084/"
] | I'd like to store a properties file as XML. Is there a way to sort the keys when doing this so that the generated XML file will be in alphabetical order?
```
String propFile = "/path/to/file";
Properties props = new Properties();
/*set some properties here*/
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/*this comes out unsorted*/
props.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
``` | Here's a quick and dirty way to do it:
```
String propFile = "/path/to/file";
Properties props = new Properties();
/* Set some properties here */
Properties tmp = new Properties() {
@Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
};
tmp.putAll(props);
try {
FileOutputStream xmlStream = new FileOutputStream(propFile);
/* This comes out SORTED! */
tmp.storeToXML(xmlStream,"");
} catch (IOException e) {
e.printStackTrace();
}
```
Here are the caveats:
* The tmp Properties (an anonymous
subclass) doesn't fulfill the
contract of Properties.
For example, if you got its `keySet` and tried to remove an element from it, an exception would be raised. So, don't allow instances of this subclass to escape! In the snippet above, you are never passing it to another object or returning it to a caller who has a legitimate expectation that it fulfills the contract of Properties, so it is safe.
* The implementation of
Properties.storeToXML could change,
causing it to ignore the keySet
method.
For example, a future release, or OpenJDK, could use the `keys()` method of `Hashtable` instead of `keySet`. This is one of the reasons why classes should always document their "self-use" (Effective Java Item 15). However, in this case, the worst that would happen is that your output would revert to unsorted.
* Remember that the Properties storage
methods ignore any "default"
entries. |
54,334 | <p>The following SQL:</p>
<pre><code>SELECT notes + 'SomeText'
FROM NotesTable a
</code></pre>
<p>Give the error:</p>
<blockquote>
<p>The data types nvarchar and text are incompatible in the add operator.</p>
</blockquote>
| [
{
"answer_id": 54343,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 7,
"selected": true,
"text": "<p>The only way would be to convert your text field into an nvarchar field.</p>\n\n<pre><code>Select Cast(notes as nvarchar(4... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
] | The following SQL:
```
SELECT notes + 'SomeText'
FROM NotesTable a
```
Give the error:
>
> The data types nvarchar and text are incompatible in the add operator.
>
>
> | The only way would be to convert your text field into an nvarchar field.
```
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
```
Otherwise, I suggest doing the concatenation in your application. |
54,365 | <p>This is probably <a href="http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13320.html" rel="noreferrer">a complex solution</a>.</p>
<p>I am looking for a simple operator like ">>", but for prepending.</p>
<p>I am afraid it does not exist. I'll have to do something like </p>
<pre>
mv myfile tmp
cat myheader tmp > myfile
</pre>
<p>Anything smarter?</p>
| [
{
"answer_id": 54381,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 7,
"selected": false,
"text": "<p>This still uses a temp file, but at least it is on one line:</p>\n\n<pre><code>echo \"text\" | cat - yourfile >... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1277510/"
] | This is probably [a complex solution](http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13320.html).
I am looking for a simple operator like ">>", but for prepending.
I am afraid it does not exist. I'll have to do something like
```
mv myfile tmp
cat myheader tmp > myfile
```
Anything smarter? | The **hack** below was a quick off-the-cuff answer which worked and received lots of upvotes. Then, as the question became more popular and more time passed, people started reporting that it sorta worked but weird things could happen, or it just didn't work at all. Such fun.
I recommend [the 'sponge' solution posted by user222](https://stackoverflow.com/a/15721194/75033) as Sponge is part of 'moreutils' and probably on your system by default.
`(echo 'foo' && cat yourfile) | sponge yourfile`
The solution below exploits the exact implementation of file descriptors on your system and, because implementation varies significantly between nixes, it's success is entirely system dependent, definitively non-portable, and should not be relied upon for anything even vaguely important. Sponge uses the /tmp filesystem but condenses the task to a single command.
Now, with all that out of the way the original answer was:
---
Creating another file descriptor for the file (`exec 3<> yourfile`) thence writing to that (`>&3`) seems to overcome the read/write on same file dilemma. Works for me on 600K files with awk. However trying the same trick using 'cat' fails.
Passing the prependage as a variable to awk (`-v TEXT="$text"`) overcomes the literal quotes problem which prevents doing this trick with 'sed'.
```
#!/bin/bash
text="Hello world
What's up?"
exec 3<> yourfile && awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3
``` |
54,380 | <p>I am adding a ADO.Net Data Service lookup feature to an existing web page. Everything works great when running from visual studio, but when I roll it out to IIS, I get the following error:</p>
<blockquote>
<p><strong>Request Error</strong><br>The server encountered an error processing the request. See server logs for more details.</p>
</blockquote>
<p>I get this even when trying to display the default page, i.e.:</p>
<blockquote>
<p><a href="http://server/FFLookup.svc" rel="noreferrer">http://server/FFLookup.svc</a></p>
</blockquote>
<p>I have 3.5 SP1 installed on the server.</p>
<p>What am I missing, and which "Server Logs" is it refering to? I can't find any further error messages.</p>
<p>There is nothing in the Event Viewer logs (System or Application), and nothing in the IIS logs other than the GET:</p>
<blockquote>
<p>2008-09-10 15:20:19 10.7.131.71 GET /FFLookup.svc - 8082 - 10.7.131.86 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US)+AppleWebKit/525.13+(KHTML,+like+Gecko)+Chrome/0.2.149.29+Safari/525.13 401 2 2148074254</p>
</blockquote>
<p>There is no stack trace returned. The only response I get is the "Request Error" as noted above.</p>
<p>Thanks</p>
<p>Patrick</p>
| [
{
"answer_id": 55557,
"author": "Patrick Connelly",
"author_id": 5431,
"author_profile": "https://Stackoverflow.com/users/5431",
"pm_score": 4,
"selected": false,
"text": "<p>Well I found the \"Server Logs\" mentioned in the error above.</p>\n\n<p>You need to turn on tracing in the web.c... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5431/"
] | I am adding a ADO.Net Data Service lookup feature to an existing web page. Everything works great when running from visual studio, but when I roll it out to IIS, I get the following error:
>
> **Request Error**
> The server encountered an error processing the request. See server logs for more details.
>
>
>
I get this even when trying to display the default page, i.e.:
>
> <http://server/FFLookup.svc>
>
>
>
I have 3.5 SP1 installed on the server.
What am I missing, and which "Server Logs" is it refering to? I can't find any further error messages.
There is nothing in the Event Viewer logs (System or Application), and nothing in the IIS logs other than the GET:
>
> 2008-09-10 15:20:19 10.7.131.71 GET /FFLookup.svc - 8082 - 10.7.131.86 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US)+AppleWebKit/525.13+(KHTML,+like+Gecko)+Chrome/0.2.149.29+Safari/525.13 401 2 2148074254
>
>
>
There is no stack trace returned. The only response I get is the "Request Error" as noted above.
Thanks
Patrick | In order to verbosely display the errors resulting from your data service you can place the following tag above your dataservice definition:
```
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
```
This will then display the error in your browser window as well as a stack trace.
In addition to this dataservices throws all exceptions to the HandleException method so if you implement this method on your dataservice class you can put a break point on it and see the exception:
```
protected override void HandleException(HandleExceptionArgs e)
{
try
{
e.UseVerboseErrors = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
``` |
54,387 | <p>I have a set of calculation methods sitting in a .Net DLL. I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.</p>
<p>For example, my .net method:</p>
<pre><code>public double CalculateSomethingReallyComplex(double a, double b) {...}
</code></pre>
<p>I would like enable them to call this method just by typing a formula in a random cell:</p>
<pre><code>=CalculateSomethingReallyComplex(A1, B1)
</code></pre>
<p>What would be the best way to accomplish this?</p>
| [
{
"answer_id": 54429,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": true,
"text": "<p>There are two methods - you can used Visual Studio Tools for Office (VSTO):</p>\n\n<p><a href=\"http://blogs.msdn.com/pst... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324220/"
] | I have a set of calculation methods sitting in a .Net DLL. I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.
For example, my .net method:
```
public double CalculateSomethingReallyComplex(double a, double b) {...}
```
I would like enable them to call this method just by typing a formula in a random cell:
```
=CalculateSomethingReallyComplex(A1, B1)
```
What would be the best way to accomplish this? | There are two methods - you can used Visual Studio Tools for Office (VSTO):
<http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx>
or you can use COM:
<http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx>
I'm not sure if the VSTO method would work in older versions of Excel, but the COM method should work fine. |
54,401 | <p>As I develop more with vim, I find myself wanting to copy in blocks of useful code, similar to "templates" in Eclipse. </p>
<p>I was thinking of making a separate file for each code chunk and just reading them in with</p>
<pre><code>:r code-fornext
</code></pre>
<p>but that just seems kind of primitive. Googling around I find vim macros mentioned and something about "maps" but nothing that seems straightforward.</p>
<p>What I am looking for are e.g. something like Eclipse's "Templates" so I pop in a code chunk with the cursor sitting in the middle of it.
Or JEdit's "Macros" which I can record doing complicated deletes and renaming on one line, then I can play it again on 10 other lines so it does the same to them.</p>
<p>Does vim have anything like these two functionalities?</p>
| [
{
"answer_id": 54527,
"author": "brian newman",
"author_id": 3210,
"author_profile": "https://Stackoverflow.com/users/3210",
"pm_score": 4,
"selected": true,
"text": "<p>To record macros in Vim, in the command mode, hit the <code>q</code> key and another key you want to assign the macro ... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | As I develop more with vim, I find myself wanting to copy in blocks of useful code, similar to "templates" in Eclipse.
I was thinking of making a separate file for each code chunk and just reading them in with
```
:r code-fornext
```
but that just seems kind of primitive. Googling around I find vim macros mentioned and something about "maps" but nothing that seems straightforward.
What I am looking for are e.g. something like Eclipse's "Templates" so I pop in a code chunk with the cursor sitting in the middle of it.
Or JEdit's "Macros" which I can record doing complicated deletes and renaming on one line, then I can play it again on 10 other lines so it does the same to them.
Does vim have anything like these two functionalities? | To record macros in Vim, in the command mode, hit the `q` key and another key you want to assign the macro to. For quick throw away macros I usually just hit `qq` and assign the macro to the `q` key. Once you are in recording mode, run through your key strokes. When you are done make sure you are back in command mode and hit `q` again to stop recording. Then to replay the macro manually, you can type `@q`. To replay the previously run macro you can type `@@` or to run it 10 times you could type `10@q` or `20@q`, etc..
In summary:
```
+----------------------------------+-------------------------------------+
| start recording a macro | qX (X = key to assign macro to) |
+----------------------------------+-------------------------------------+
| stop recording a macro | q |
+----------------------------------+-------------------------------------+
| playback macro | @X (X = key macro was assigned to) |
+----------------------------------+-------------------------------------+
| replay previously played macro | @@ |
+----------------------------------+-------------------------------------+
```
In regards to code chunks, I have found and started using a Vim plug-in called snipMate, which mimics TextMate's snippets feature. You can get the plug-in here:
<http://www.vim.org/scripts/script.php?script_id=2540>
And a short article on using snipMate (along with a short screencast showing it in use):
<http://www.catonmat.net/blog/vim-plugins-snipmate-vim/>
Hope you find this helpful! |
54,418 | <p>I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.</p>
<p>So I'm thinking:</p>
<pre><code>UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
</code></pre>
<p>But my brain hurts going any farther than that.</p>
| [
{
"answer_id": 54430,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 10,
"selected": true,
"text": "<pre><code>SELECT DISTINCT a,b,c FROM t\n</code></pre>\n\n<p>is <em>roughly</em> equivalent to: </p>\n\n<pre><code>SEL... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915/"
] | I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.
So I'm thinking:
```
UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
FROM sales
HAVING count = 1)
```
But my brain hurts going any farther than that. | ```
SELECT DISTINCT a,b,c FROM t
```
is *roughly* equivalent to:
```
SELECT a,b,c FROM t GROUP BY a,b,c
```
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
```
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
``` |
54,419 | <p>I have a WCF application that has two Services that I am trying to host in a single Windows Service using net.tcp. I can run either of the services just fine, but as soon as I try to put them both in the Windows Service only the first one loads up. I have determined that the second services ctor is being called but the OnStart never fires. This tells me that WCF is finding something wrong with loading up that second service.</p>
<p>Using net.tcp I know I need to turn on port sharing and start the port sharing service on the server. This all seems to be working properly. I have tried putting the services on different tcp ports and still no success.</p>
<p>My service installer class looks like this:</p>
<pre><code> [RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller _process;
private ServiceInstaller _serviceAdmin;
private ServiceInstaller _servicePrint;
public ProjectInstaller()
{
_process = new ServiceProcessInstaller();
_process.Account = ServiceAccount.LocalSystem;
_servicePrint = new ServiceInstaller();
_servicePrint.ServiceName = "PrintingService";
_servicePrint.StartType = ServiceStartMode.Automatic;
_serviceAdmin = new ServiceInstaller();
_serviceAdmin.ServiceName = "PrintingAdminService";
_serviceAdmin.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] { _process, _servicePrint, _serviceAdmin });
}
}
</code></pre>
<p>and both services looking very similar</p>
<pre><code> class PrintService : ServiceBase
{
public ServiceHost _host = null;
public PrintService()
{
ServiceName = "PCTSPrintingService";
CanStop = true;
AutoLog = true;
}
protected override void OnStart(string[] args)
{
if (_host != null) _host.Close();
_host = new ServiceHost(typeof(Printing.ServiceImplementation.PrintingService));
_host.Faulted += host_Faulted;
_host.Open();
}
}
</code></pre>
| [
{
"answer_id": 54424,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>you probably just need 2 service hosts.</p>\n\n<p>_host1 and _host2.</p>\n"
},
{
"answer_id": 77401,
"author":... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5408/"
] | I have a WCF application that has two Services that I am trying to host in a single Windows Service using net.tcp. I can run either of the services just fine, but as soon as I try to put them both in the Windows Service only the first one loads up. I have determined that the second services ctor is being called but the OnStart never fires. This tells me that WCF is finding something wrong with loading up that second service.
Using net.tcp I know I need to turn on port sharing and start the port sharing service on the server. This all seems to be working properly. I have tried putting the services on different tcp ports and still no success.
My service installer class looks like this:
```
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller _process;
private ServiceInstaller _serviceAdmin;
private ServiceInstaller _servicePrint;
public ProjectInstaller()
{
_process = new ServiceProcessInstaller();
_process.Account = ServiceAccount.LocalSystem;
_servicePrint = new ServiceInstaller();
_servicePrint.ServiceName = "PrintingService";
_servicePrint.StartType = ServiceStartMode.Automatic;
_serviceAdmin = new ServiceInstaller();
_serviceAdmin.ServiceName = "PrintingAdminService";
_serviceAdmin.StartType = ServiceStartMode.Automatic;
Installers.AddRange(new Installer[] { _process, _servicePrint, _serviceAdmin });
}
}
```
and both services looking very similar
```
class PrintService : ServiceBase
{
public ServiceHost _host = null;
public PrintService()
{
ServiceName = "PCTSPrintingService";
CanStop = true;
AutoLog = true;
}
protected override void OnStart(string[] args)
{
if (_host != null) _host.Close();
_host = new ServiceHost(typeof(Printing.ServiceImplementation.PrintingService));
_host.Faulted += host_Faulted;
_host.Open();
}
}
``` | Base your service on this [MSDN article](http://msdn.microsoft.com/en-us/library/ms733069.aspx) and create two service hosts.
But instead of actually calling each service host directly, you can break it out to as many classes as you want which defines each service you want to run:
```
internal class MyWCFService1
{
internal static System.ServiceModel.ServiceHost serviceHost = null;
internal static void StartService()
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Instantiate new ServiceHost.
serviceHost = new System.ServiceModel.ServiceHost(typeof(MyService1));
// Open myServiceHost.
serviceHost.Open();
}
internal static void StopService()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
};
```
In the body of the windows service host, call the different classes:
```
// Start the Windows service.
protected override void OnStart( string[] args )
{
// Call all the set up WCF services...
MyWCFService1.StartService();
//MyWCFService2.StartService();
//MyWCFService3.StartService();
}
```
Then you can add as many WCF services as you like to one windows service host.
REMEBER to call the stop methods as well.... |
54,421 | <p>If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?</p>
<p>Consider:</p>
<pre><code>myprogram -f filename -d directory -r regex
</code></pre>
<p>How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)</p>
| [
{
"answer_id": 54457,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 5,
"selected": true,
"text": "<p>I don't know of any documented \"patterns\" for processing.</p>\n\n<p>I believe one of the oldest libraries/APIs for ... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] | If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?
Consider:
```
myprogram -f filename -d directory -r regex
```
How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer) | I don't know of any documented "patterns" for processing.
I believe one of the oldest libraries/APIs for handling arguments is getopt. Googling "getopt" shows lots of man pages and links to implementations.
Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with. Arguments are then translated into something in this service that the application than then query. This could be as simple as a dictionary of settings (like a string setting named "filename"). |
54,426 | <p>Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?</p>
<p>For example, I've been using </p>
<pre><code>javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
</code></pre>
<p>so far but wonder if there's something more sophisticated I could use or better practice.</p>
| [
{
"answer_id": 54446,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<pre><code>document.location = \"http://url_submitting_to.com?query_string_param=\" + window.location;\n</code></pre>\n"
... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5613/"
] | Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL. Suggestions?
For example, I've been using
```
javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))
```
so far but wonder if there's something more sophisticated I could use or better practice. | Do you want something exactly like the Delicious bookmarklet (as in, something the user actively clicks on to submit the URL)? If so, you could probably just copy their code and replace the target URL:
```
javascript:(function(){
location.href='http://example.com/your-script.php?url='+
encodeURIComponent(window.location.href)+
'&title='+encodeURIComponent(document.title)
})()
```
You may need to change the query string names, etc., to match what your script expects.
If you want to track a user through your website automatically, this probably won't be possible. You'd need to request the URL with AJAX, but the web browser won't allow Javascript to make a request outside of the originating domain. Maybe it's possible with `iframe` trickery.
**Edit:** John beat me to it. |
54,440 | <p>I want to add the selected item from the <code>TreeView</code> to the <code>ListBox</code> control using <code>DataBinding</code> (If it can work with <code>DataBinding</code>). </p>
<pre><code><TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
</code></pre>
<p><code>TreeView</code> is populated from the code behind page with some dummy data. </p>
| [
{
"answer_id": 54665,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure it is possible, since WPF is really flexible with data binding, but I haven't done that specific scenario yet... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] | I want to add the selected item from the `TreeView` to the `ListBox` control using `DataBinding` (If it can work with `DataBinding`).
```
<TreeView HorizontalAlignment="Left"
Margin="30,32,0,83"
Name="treeView1"
Width="133" >
</TreeView>
<ListBox VerticalAlignment="Top"
Margin="208,36,93,0"
Name="listBox1"
Height="196" >
</ListBox>
```
`TreeView` is populated from the code behind page with some dummy data. | You can bind to an element using ElementName, so if you wanted to bind the selected tree item to the ItemsSource of a ListBox:
```
ItemsSource="{Binding SelectedItem, ElementName=treeView1}"
``` |
54,475 | <p>I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.</p>
<p>Not until I force the browser to clear the cache do I see the changes.</p>
<p>Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the <a href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=FAQ_GWTApplicationFiles" rel="noreferrer">Google Web Toolkit</a> where they actually create a <strong>new</strong> JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.</p>
<p>Is there a list of best practices somewhere?</p>
| [
{
"answer_id": 54483,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>I am also of the method of just renaming things. It never fails, and is fairly easy to do.</p>\n"
},
{
"answer_i... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5079/"
] | I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.
Not until I force the browser to clear the cache do I see the changes.
Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the [Google Web Toolkit](http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=FAQ_GWTApplicationFiles) where they actually create a **new** JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.
Is there a list of best practices somewhere? | We append a product build number to the end of all Javascript (and CSS etc.) like so:
```
<script src="MyScript.js?4.0.8243">
```
Browsers ignore everything after the question mark but upgrades cause a new URL which means cache-reload.
This has the additional benefit that you can set HTTP headers that mean "never cache!" |
54,482 | <p>I need to enumerate all the user defined types created in a <code>SQL Server</code> database with <code>CREATE TYPE</code>, and/or find out whether they have already been defined.</p>
<p>With tables or stored procedures I'd do something like this:</p>
<pre><code>if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
drop table foobar
</code></pre>
<p>However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in <code>sysobjects</code>. </p>
<p>Can anyone enlighten me?</p>
| [
{
"answer_id": 54496,
"author": "jwolly2",
"author_id": 5202,
"author_profile": "https://Stackoverflow.com/users/5202",
"pm_score": 7,
"selected": true,
"text": "<p>Types and UDTs don't appear in sys.objects.\nYou should be able to get what you're looking for with the following:</p>\n\n<... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886/"
] | I need to enumerate all the user defined types created in a `SQL Server` database with `CREATE TYPE`, and/or find out whether they have already been defined.
With tables or stored procedures I'd do something like this:
```
if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
drop table foobar
```
However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in `sysobjects`.
Can anyone enlighten me? | Types and UDTs don't appear in sys.objects.
You should be able to get what you're looking for with the following:
```
select * from sys.types
where is_user_defined = 1
``` |
54,487 | <p>How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:</p>
<pre>
123.45 -> 123.45
99.0 -> 99
23.2 -> 23.2
45.0 -> 45
</pre>
<p>Edit: I forgot to mention - I'm still on Java 1.4 - sorry!</p>
| [
{
"answer_id": 54502,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 4,
"selected": true,
"text": "<p>If you use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html\" rel=\"nofollow noreferrer\">D... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:
```
123.45 -> 123.45
99.0 -> 99
23.2 -> 23.2
45.0 -> 45
```
Edit: I forgot to mention - I'm still on Java 1.4 - sorry! | If you use [DecimalFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html) and specify # in the pattern it only displays the value if it is not zero.
See my question [How do I format a number in java?](https://stackoverflow.com/questions/50532/how-do-i-format-a-number-in-java)
Sample Code
```
DecimalFormat format = new DecimalFormat("###.##");
double[] doubles = {123.45, 99.0, 23.2, 45.0};
for(int i=0;i<doubles.length;i++){
System.out.println(format.format(doubles[i]));
}
``` |
54,503 | <p>I'm working on a .net post-commit hook to feed data into OnTime via their Soap SDK. My hook works on Windows fine, but on our production RHEL4 subversion server, it won't work when called from a shell script.</p>
<pre>
#!/bin/sh
/usr/bin/mono $1/hooks/post-commit.exe "$@"
</pre>
<p>When I execute it with parameters from the command line, it works properly. When executed via the shell script, I get the following error: (looks like there is some problem with the process execution of SVN that I use to get the log data for the revision):</p>
<pre>
Unhandled Exception: System.InvalidOperationException: The process must exit before getting the requested information.
at System.Diagnostics.Process.get_ExitCode () [0x0003f] in /tmp/monobuild/build/BUILD/mono-1.9.1/mcs/class/System/System.Diagnostics/Process.cs:149
at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ExitCode ()
at SVNLib.SVN.Execute (System.String sCMD, System.String sParams, System.String sComment, System.String sUserPwd, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.Log (System.String sUrl, Int32 nRevLow, Int32 nRevHigh, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.LogAsString (System.String sUrl, Int32 nRevLow, Int32 nRevHigh) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
</pre>
<p>I've tried using <code>mkbundle</code> and <code>mkbundle2</code> to make a stand alone that could be named <code>post-commit</code>, but I get a different error message:</p>
<pre>
Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: Value cannot be null.
at System.Guid.CheckNull (System.Object o) [0x00000]
at System.Guid..ctor (System.String g) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
</pre>
<p>Any ideas why it might be failing from a shell script or what might be wrong with the bundled version?</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54537">@Herms</a>, I've already tried it with an echo, and it looks right. As for the <code>$1/hooks/post-commit.exe</code>, I've tried the script with and without a full path to the .net assembly with the same results.</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54545">@Leon</a>, I've tried both <code>$1 $2</code> and <code>"$@"</code> with the same results. It is a subversion post commit hook, and it takes two parameters, so those need to be passed along to the .net assembly. The <code>"$@"</code> was what was recommended at the mono site for calling a .net assembly from a shell script. The shell script <i>is</i> executing the .net assembly and with the correct parameters, but it is throwing an exception that does not get thrown when run directly from the command line.</p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54568">@Vinko</a>, I don't see any differences in the environment other than things like <code>BASH_LINENO</code> and <code>BASH_SOURCE</code></p>
<p><b>Edit:</b> <a href="https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54818">@Luke</a>, I tired it, but that makes no difference either. I first noticed the problem when testing from TortoiseSVN on my machine (when it runs as a sub-process of the subversion daemon), but also found that I get the same results when executing the script from the hooks directory (i.e. <code>./post-commit REPOS REV</code>, where <code>post-commit</code> is the above sh script. Doing <code>mono post-commit.exe REPOS REV</code> works fine. The main problem is that to execute, I need to have something of the name <code>post-commit</code> so that it will be called. But it does not work from a shell script, and as noted above, the <code>mkbundle</code> is not working with a different problem.</p>
| [
{
"answer_id": 54537,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>Just a random thought that might help with debugging. Try changing your shell script to:</p>\n\n<pre><code>#!/bin/sh\necho ... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1441/"
] | I'm working on a .net post-commit hook to feed data into OnTime via their Soap SDK. My hook works on Windows fine, but on our production RHEL4 subversion server, it won't work when called from a shell script.
```
#!/bin/sh
/usr/bin/mono $1/hooks/post-commit.exe "$@"
```
When I execute it with parameters from the command line, it works properly. When executed via the shell script, I get the following error: (looks like there is some problem with the process execution of SVN that I use to get the log data for the revision):
```
Unhandled Exception: System.InvalidOperationException: The process must exit before getting the requested information.
at System.Diagnostics.Process.get_ExitCode () [0x0003f] in /tmp/monobuild/build/BUILD/mono-1.9.1/mcs/class/System/System.Diagnostics/Process.cs:149
at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_ExitCode ()
at SVNLib.SVN.Execute (System.String sCMD, System.String sParams, System.String sComment, System.String sUserPwd, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.Log (System.String sUrl, Int32 nRevLow, Int32 nRevHigh, SVNLib.SVNCallback callback) [0x00000]
at SVNLib.SVN.LogAsString (System.String sUrl, Int32 nRevLow, Int32 nRevHigh) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
```
I've tried using `mkbundle` and `mkbundle2` to make a stand alone that could be named `post-commit`, but I get a different error message:
```
Unhandled Exception: System.ArgumentNullException: Argument cannot be null.
Parameter name: Value cannot be null.
at System.Guid.CheckNull (System.Object o) [0x00000]
at System.Guid..ctor (System.String g) [0x00000]
at SVNCommit2OnTime.Program.Main (System.String[] args) [0x00000]
```
Any ideas why it might be failing from a shell script or what might be wrong with the bundled version?
**Edit:** [@Herms](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54537), I've already tried it with an echo, and it looks right. As for the `$1/hooks/post-commit.exe`, I've tried the script with and without a full path to the .net assembly with the same results.
**Edit:** [@Leon](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54545), I've tried both `$1 $2` and `"$@"` with the same results. It is a subversion post commit hook, and it takes two parameters, so those need to be passed along to the .net assembly. The `"$@"` was what was recommended at the mono site for calling a .net assembly from a shell script. The shell script *is* executing the .net assembly and with the correct parameters, but it is throwing an exception that does not get thrown when run directly from the command line.
**Edit:** [@Vinko](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54568), I don't see any differences in the environment other than things like `BASH_LINENO` and `BASH_SOURCE`
**Edit:** [@Luke](https://stackoverflow.com/questions/54503/problem-with-net-app-under-linux-doesnt-work-from-shell-script#54818), I tired it, but that makes no difference either. I first noticed the problem when testing from TortoiseSVN on my machine (when it runs as a sub-process of the subversion daemon), but also found that I get the same results when executing the script from the hooks directory (i.e. `./post-commit REPOS REV`, where `post-commit` is the above sh script. Doing `mono post-commit.exe REPOS REV` works fine. The main problem is that to execute, I need to have something of the name `post-commit` so that it will be called. But it does not work from a shell script, and as noted above, the `mkbundle` is not working with a different problem. | It is normal for some processes to hang around for a while after they close their stdout (ie. you get an end-of-file reading from them). You need to call `proc.WaitForExit()` after reading all the data but before checking ExitCode. |
54,536 | <p>How do I create a windows application that does the following:</p>
<ul>
<li>it's a regular GUI app when invoked with no command line arguments</li>
<li>specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate</li>
<li>it must be a single executable. No cheating by making a console app exec a 2nd executable.</li>
<li>assume the main application code is written in C/C++</li>
<li>bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)</li>
</ul>
<p>In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.</p>
| [
{
"answer_id": 113032,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 5,
"selected": false,
"text": "<p>Microsoft designed console and GUI apps to be mutually exclusive.\nThis bit of short-sightedness means that there is... | 2008/09/10 | [
"https://Stackoverflow.com/questions/54536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5429/"
] | How do I create a windows application that does the following:
* it's a regular GUI app when invoked with no command line arguments
* specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate
* it must be a single executable. No cheating by making a console app exec a 2nd executable.
* assume the main application code is written in C/C++
* bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)
In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell. | Microsoft designed console and GUI apps to be mutually exclusive.
This bit of short-sightedness means that there is no perfect solution.
The most popular approach is to have two executables (eg. cscript / wscript,
java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating".
You've got two options - to make a "console executable" or a "gui executable",
and then use code to try to provide the other behaviour.
* GUI executable:
`cmd.exe` will assume that your program does no console I/O so won't wait for it to terminate
before continuing, which in interactive mode (ie not a batch) means displaying the next ("`C:\>`") prompt
and reading from the keyboard. So even if you use AttachConsole your output will be mixed
with `cmd`'s output, and the situation gets worse if you try to do input. This is basically a non-starter.
* Console executable:
Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.
The first is that if you run it from the command line with no arguments (so you want the GUI),
`cmd` will still wait for it to terminate before continuing, so that particular
console will be unusable for the duration. This can be overcome by launching
a second process of the same executable (do you consider this cheating?),
passing the DETACHED\_PROCESS flag to CreateProcess() and immediately exiting.
The new process can then detect that it has no console and display the GUI.
Here's C code to illustrate this approach:
```
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[])
{
if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process
{
MessageBox(0, "Hello GUI world!", "", 0);
}
else if (argc > 1) // we have command line args
{
printf("Hello console world!\n");
}
else // no command line args but a console - launch child process
{
DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;
STARTUPINFO startinfo;
PROCESS_INFORMATION procinfo;
ZeroMemory(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(startinfo);
if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo))
MessageBox(0, "CreateProcess() failed :(", "", 0);
}
exit(0);
}
```
I compiled it with cygwin's gcc - YMMV with MSVC.
The second problem is that when run from Explorer, your program will for a split second
display a console window. There's no programmatic way around this because the console is
created by Windows when the app is launched, before it starts executing. The only thing you can
do is, in your installer, make the shortcut to your program with a "show command" of
SW\_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO
in your program, so don't do that.
I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplish
it in your install program of choice is up to you.
The user can still of course run your program by finding the executable in Explorer and
double-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it. |