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
90,092
<p>I have a table in <code>MySQL</code> that has 3 fields and I want to enforce uniqueness among two of the fields. Here is the table <code>DDL</code>:</p> <pre><code>CREATE TABLE `CLIENT_NAMES` ( `ID` int(11) NOT NULL auto_increment, `CLIENT_NAME` varchar(500) NOT NULL, `OWNER_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>The <code>ID</code> field is a surrogate key (this table is being loaded with ETL). The <code>CLIENT_NAME</code> is a field that contains names of clients The <code>OWNER_ID</code> is an id indicates a clients owner.</p> <p>I thought I could enforce this with a unique index on <code>CLIENT_NAME</code> and <code>OWNER_ID</code>, </p> <pre><code>ALTER TABLE `DW`.`CLIENT_NAMES` ADD UNIQUE INDEX enforce_unique_idx(`CLIENT_NAME`, `OWNER_ID`); </code></pre> <p>but MySQL gives me an error: </p> <blockquote> <p>Error executing SQL commands to update table. Specified key was too long; max key length is 765 bytes (error 1071)</p> </blockquote> <p>Anyone else have any ideas?</p>
[ { "answer_id": 90111, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 0, "selected": false, "text": "<p>Have you looked at CONSTRAINT ... UNIQUE?</p>\n" }, { "answer_id": 90116, "author": "Gili", "author_i...
2008/09/18
[ "https://Stackoverflow.com/questions/90092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082/" ]
I have a table in `MySQL` that has 3 fields and I want to enforce uniqueness among two of the fields. Here is the table `DDL`: ``` CREATE TABLE `CLIENT_NAMES` ( `ID` int(11) NOT NULL auto_increment, `CLIENT_NAME` varchar(500) NOT NULL, `OWNER_ID` int(11) NOT NULL, PRIMARY KEY (`ID`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` The `ID` field is a surrogate key (this table is being loaded with ETL). The `CLIENT_NAME` is a field that contains names of clients The `OWNER_ID` is an id indicates a clients owner. I thought I could enforce this with a unique index on `CLIENT_NAME` and `OWNER_ID`, ``` ALTER TABLE `DW`.`CLIENT_NAMES` ADD UNIQUE INDEX enforce_unique_idx(`CLIENT_NAME`, `OWNER_ID`); ``` but MySQL gives me an error: > > Error executing SQL commands to update table. > Specified key was too long; max key length is 765 bytes (error 1071) > > > Anyone else have any ideas?
MySQL cannot enforce uniqueness on keys that are longer than 765 bytes (and apparently 500 UTF8 characters can surpass this limit). 1. Does CLIENT\_NAME really need to be 500 characters long? Seems a bit excessive. 2. Add a new (shorter) column that is hash(CLIENT\_NAME). Get MySQL to enforce uniqueness on that hash instead.
90,151
<p>Anyone got a working example of using ruby to post to a presigned URL on s3</p>
[ { "answer_id": 90708, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 0, "selected": false, "text": "<p>Does anything on the <a href=\"http://amazon.rubyforge.org/\" rel=\"nofollow noreferrer\">s3 library page</a> cover w...
2008/09/18
[ "https://Stackoverflow.com/questions/90151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17232/" ]
Anyone got a working example of using ruby to post to a presigned URL on s3
I have used aws-sdk and right\_aws both. Here is the code to do this. ``` require 'rubygems' require 'aws-sdk' require 'right_aws' require 'net/http' require 'uri' require 'rack' access_key_id = 'AAAAAAAAAAAAAAAAA' secret_access_key = 'ASDFASDFAS4646ASDFSAFASDFASDFSADF' s3 = AWS::S3.new( :access_key_id => access_key_id, :secret_access_key => secret_access_key) right_s3 = RightAws::S3Interface.new(access_key_id, secret_access_key, {:multi_thread => true, :logger => nil} ) bucket_name = 'your-bucket-name' key = "your-file-name.ext" right_url = right_s3.put_link(bucket_name, key) right_scan_command = "curl -I --upload-file #{key} '#{right_url.to_s}'" system(right_scan_command) bucket = s3.buckets[bucket_name] form = bucket.presigned_post(:key => key) uri = URI(form.url.to_s + '/' + key) uri.query = Rack::Utils.build_query(form.fields) scan_command = "curl -I --upload-file #{key} '#{uri.to_s}'" system(scan_command) ```
90,178
<p>I am working on a web application where I want the content to fill the height of the entire screen.</p> <p>The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom.</p> <p>I have a header <code>div</code> and a content <code>div</code>. At the moment I am using a table for the layout like so:</p> <p>CSS and HTML</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#page { height: 100%; width: 100% } #tdcontent { height: 100%; } #content { overflow: auto; /* or overflow: hidden; */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="page"&gt; &lt;tr&gt; &lt;td id="tdheader"&gt; &lt;div id="header"&gt;...&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="tdcontent"&gt; &lt;div id="content"&gt;...&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>The entire height of the page is filled, and no scrolling is required.</p> <p>For anything inside the content div, setting <code>top: 0;</code> will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting <code>header</code> inside <code>content</code> will not allow this to work.</p> <p>Is there a way to achieve the same effect without using the <code>table</code>?</p> <p><strong>Update:</strong></p> <p>Elements inside the content <code>div</code> will have heights set to percentages as well. So something at 100% inside the <code>div</code> will fill it to the bottom. As will two elements at 50%.</p> <p><strong>Update 2:</strong></p> <p>For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside <code>#content</code> would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.</p>
[ { "answer_id": 90414, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transit...
2008/09/18
[ "https://Stackoverflow.com/questions/90178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ]
I am working on a web application where I want the content to fill the height of the entire screen. The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom. I have a header `div` and a content `div`. At the moment I am using a table for the layout like so: CSS and HTML ```css #page { height: 100%; width: 100% } #tdcontent { height: 100%; } #content { overflow: auto; /* or overflow: hidden; */ } ``` ```html <table id="page"> <tr> <td id="tdheader"> <div id="header">...</div> </td> </tr> <tr> <td id="tdcontent"> <div id="content">...</div> </td> </tr> </table> ``` The entire height of the page is filled, and no scrolling is required. For anything inside the content div, setting `top: 0;` will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting `header` inside `content` will not allow this to work. Is there a way to achieve the same effect without using the `table`? **Update:** Elements inside the content `div` will have heights set to percentages as well. So something at 100% inside the `div` will fill it to the bottom. As will two elements at 50%. **Update 2:** For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside `#content` would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works.
### 2015 update: the flexbox approach There are two other answers briefly mentioning [flexbox](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes); however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. > > Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. > > > (taken from <https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes>) > > > All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: <http://caniuse.com/#feat=flexbox> ### Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. ```css html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; } ``` ```html <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div> ``` In the CSS above, the [flex](https://developer.mozilla.org/en/CSS/flex) property shorthands the [flex-grow](https://developer.mozilla.org/en/CSS/flex-grow), [flex-shrink](https://developer.mozilla.org/en/CSS/flex-shrink), and [flex-basis](https://developer.mozilla.org/en/CSS/flex-basis) properties to establish the flexibility of the flex items. Mozilla has a [good introduction to the flexible boxes model](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes).
90,181
<p>I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction.</p> <p>In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel.</p> <p>Can anyone suggest how to fix this?</p> <p>I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/&gt; &lt;script type="text/javascript" src="ext/ext-base.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="ext/ext-all-debug.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "-&gt;", {id: "continue", text: 'Continue'} ] }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 90414, "author": "Jerph", "author_id": 1701, "author_profile": "https://Stackoverflow.com/users/1701", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transit...
2008/09/18
[ "https://Stackoverflow.com/questions/90181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
I've just run into a display glitch in IE6 with the ExtJS framework. - Hopefully someone can point me in the right direction. In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel. Can anyone suggest how to fix this? I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/> <script type="text/javascript" src="ext/ext-base.js"></script> <script type="text/javascript" src="ext/ext-all-debug.js"></script> <script type="text/javascript"> Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "->", {id: "continue", text: 'Continue'} ] }); }); </script> </head> <body> <div id="content"></div> </body> </html> ```
### 2015 update: the flexbox approach There are two other answers briefly mentioning [flexbox](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes); however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. > > Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. > > > (taken from <https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes>) > > > All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: <http://caniuse.com/#feat=flexbox> ### Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. ```css html, body { height: 100%; margin: 0; } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 auto; } .box .row.footer { flex: 0 1 40px; } ``` ```html <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --> <div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div> </div> ``` In the CSS above, the [flex](https://developer.mozilla.org/en/CSS/flex) property shorthands the [flex-grow](https://developer.mozilla.org/en/CSS/flex-grow), [flex-shrink](https://developer.mozilla.org/en/CSS/flex-shrink), and [flex-basis](https://developer.mozilla.org/en/CSS/flex-basis) properties to establish the flexibility of the flex items. Mozilla has a [good introduction to the flexible boxes model](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes).
90,238
<p>As an example in pseudocode:</p> <pre><code>if ((a mod 2) == 0) { isEven = true; } else { isEven = false; } </code></pre>
[ { "answer_id": 90242, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 7, "selected": false, "text": "<p>Here is the representation of your pseudo-code in minimal Java code;</p>\n\n<pre><code>boolean isEven = a % 2 == 0;\n<...
2008/09/18
[ "https://Stackoverflow.com/questions/90238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17245/" ]
As an example in pseudocode: ``` if ((a mod 2) == 0) { isEven = true; } else { isEven = false; } ```
Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the *remainder* operator `%`. For your exact example: ``` if ((a % 2) == 0) { isEven = true; } else { isEven = false; } ``` This can be simplified to a one-liner: ``` isEven = (a % 2) == 0; ```
90,350
<p>I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc.</p> <p>Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.</p>
[ { "answer_id": 90372, "author": "JohnnyLambada", "author_id": 9648, "author_profile": "https://Stackoverflow.com/users/9648", "pm_score": 2, "selected": false, "text": "<p>I've used <a href=\"http://www.accesspdf.com/pdftk/\" rel=\"nofollow noreferrer\">pdftk</a> to great effect. It's a...
2008/09/18
[ "https://Stackoverflow.com/questions/90350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc. Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.
@J D OConal, thanks for the tip, the article you sent me was very outdated, but it did point me towards iText. I found this page that explains how to do exactly what I need: <http://java-x.blogspot.com/2006/11/merge-pdf-files-with-itext.html> Thanks for the other answers, but I don't really want to have to spawn other processes if I can avoid it, and our project already has itext.jar, so I'm not adding any external dependancies Here's the code I ended up writing: ``` public class PdfMergeHelper { /** * Merges the passed in PDFs, in the order that they are listed in the java.util.List. * Writes the resulting PDF out to the OutputStream provided. * * Sample Usage: * List<InputStream> pdfs = new ArrayList<InputStream>(); * pdfs.add(new FileInputStream("/location/of/pdf/OQS_FRSv1.5.pdf")); * pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Contract_Genericv0.5.pdf")); * pdfs.add(new FileInputStream("/location/of/pdf/PPFP-Quotev0.6.pdf")); * FileOutputStream output = new FileOutputStream("/location/to/write/to/merge.pdf"); * PdfMergeHelper.concatPDFs(pdfs, output, true); * * @param streamOfPDFFiles the list of files to merge, in the order that they should be merged * @param outputStream the output stream to write the merged PDF to * @param paginate true if you want page numbers to appear at the bottom of each page, false otherwise */ public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try { List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } } ```
90,360
<p>I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log_reuse_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. </p> <p>One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system.</p> <p>Are the settings in the log_reuse_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?</p>
[ { "answer_id": 91571, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": -1, "selected": false, "text": "<p>Hm, tricky. Could it be that the question it self to sys.databases is causing the ACTIVE_TRANSACTION? In that cas...
2008/09/18
[ "https://Stackoverflow.com/questions/90360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14947/" ]
I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log\_reuse\_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE\_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open\_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system. Are the settings in the log\_reuse\_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?
I still don't know why I was seeing the ACTIVE\_TRANSACTION in the sys.databases log\_reuse\_wait\_desc column - when there were no transactions running, but my subsequent experience indicates that the log\_reuse\_wait column for the tempdb changes for reasons that are not very clear, and for my purposes, not very relevant. Also, I found that running DBCC OPENTRAN, or the "select open\_tran from sysprocess" code, is a lot less informative than using the below statements when looking for transaction information: ``` select * from sys.dm_tran_active_transactions select * from sys.dm_tran_session_transactions select * from sys.dm_tran_locks ```
90,374
<p>Why doesn't this Google Chart API URL render both data sets on this XY scatter plot? </p> <pre><code>http://chart.apis.google.com/chart?cht=lxy&amp;chd=t:10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200|0.10,0.23,0.33,0.44,0.56,0.66,0.79,0.90,0.99,1.12,1.22,1.33,1.44,1.56,1.68,1.79,1.90,2.02,2.12,2.22|0.28,0.56,0.85,1.12,1.42,1.68,1.97,2.26,2.54,2.84,3.12,3.40,3.84,4.10,4.53,4.80,5.45,6.02,6.40,6.80&amp;chco=3072F3,ff0000,00aaaa&amp;chls=2,4,1&amp;chs=320x240&amp;chds=0,201,0,7&amp;chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5 </code></pre> <p>I've read the <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">documentation</a> over and over again, and I can't figure it out.</p>
[ { "answer_id": 90410, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": -1, "selected": true, "text": "<p>I think it actually does render both data sets, but you can only se one of them because there's only one scale o...
2008/09/18
[ "https://Stackoverflow.com/questions/90374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
Why doesn't this Google Chart API URL render both data sets on this XY scatter plot? ``` http://chart.apis.google.com/chart?cht=lxy&chd=t:10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200|0.10,0.23,0.33,0.44,0.56,0.66,0.79,0.90,0.99,1.12,1.22,1.33,1.44,1.56,1.68,1.79,1.90,2.02,2.12,2.22|0.28,0.56,0.85,1.12,1.42,1.68,1.97,2.26,2.54,2.84,3.12,3.40,3.84,4.10,4.53,4.80,5.45,6.02,6.40,6.80&chco=3072F3,ff0000,00aaaa&chls=2,4,1&chs=320x240&chds=0,201,0,7&chm=s,FF0000,0,-1,5|s,0000ff,1,-1,5|s,00aa00,2,-1,5 ``` I've read the [documentation](http://code.google.com/apis/chart/) over and over again, and I can't figure it out.
I think it actually does render both data sets, but you can only se one of them because there's only one scale on the y axis. (In other words, 0.10 is too small to show.) And, you should really be using percentages. 100 is the highest accepted value: > > Where chart data string consists of positive floating point numbers from zero (0.0) to one hundred (100.0) > > >
90,418
<p>I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?</p>
[ { "answer_id": 90434, "author": "Martin W", "author_id": 14199, "author_profile": "https://Stackoverflow.com/users/14199", "pm_score": 4, "selected": false, "text": "<p>In Bash this is easy. Just tie them together with <code>&amp;&amp;</code>:</p>\n<pre><code>command1 &amp;&amp; command2...
2008/09/18
[ "https://Stackoverflow.com/questions/90418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?
After each command, the exit code can be found in the `$?` variable so you would have something like: ``` ls -al file.ext rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi ``` You need to be careful of piped commands since the `$?` only gives you the return code of the last element in the pipe so, in the code: ``` ls -al file.ext | sed 's/^/xx: /" ``` will not return an error code if the file doesn't exist (since the `sed` part of the pipeline actually works, returning 0). The `bash` shell actually provides an array which can assist in that case, that being `PIPESTATUS`. This array has one element for each of the pipeline components, that you can access individually like `${PIPESTATUS[0]}`: ``` pax> false | true ; echo ${PIPESTATUS[0]} 1 ``` Note that this is getting you the result of the `false` command, not the entire pipeline. You can also get the entire list to process as you see fit: ``` pax> false | true | false; echo ${PIPESTATUS[*]} 1 0 1 ``` If you wanted to get the largest error code from a pipeline, you could use something like: ``` true | true | false | true | false rcs=${PIPESTATUS[*]}; rc=0; for i in ${rcs}; do rc=$(($i > $rc ? $i : $rc)); done echo $rc ``` This goes through each of the `PIPESTATUS` elements in turn, storing it in `rc` if it was greater than the previous `rc` value.
90,428
<p>I'm looking for an LDAP libracy in C or C++ that allows me to specify a list of LDAP hostnames instead of a single hostname. The library should then use the first one it can connect to in case one or more of the servers is/are down. I'm sure it'd be easy to wrap an existing library to create this, but why reinvent the wheel?</p>
[ { "answer_id": 90649, "author": "Kamil Kisiel", "author_id": 15061, "author_profile": "https://Stackoverflow.com/users/15061", "pm_score": -1, "selected": false, "text": "<p>I can't say I've ever heard of one. Furthermore, most LDAP-capable software I've used supported failover poorly or...
2008/09/18
[ "https://Stackoverflow.com/questions/90428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for an LDAP libracy in C or C++ that allows me to specify a list of LDAP hostnames instead of a single hostname. The library should then use the first one it can connect to in case one or more of the servers is/are down. I'm sure it'd be easy to wrap an existing library to create this, but why reinvent the wheel?
Use multiple A records, each with a different IP. ``` ldapserver.example.com. IN A 1.2.3.4 ldapserver.example.com. IN A 2.3.4.5 ``` The OpenLDAP client libs will try each host in turn. Failover is (unfortunately) as slow as your TCP connection timeout...
90,493
<p>How can I cast long to HWND (C++ visual studio 8)?</p> <pre><code>Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler; </code></pre> <p>But I got the following warning:</p> <blockquote> <p>warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size</p> </blockquote> <p>Thanks.</p>
[ { "answer_id": 90508, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": false, "text": "<p>As long as you're sure that the LONG you have is really an HWND, then it's as simple as:</p>\n\n<pre><code>HWND hW...
2008/09/18
[ "https://Stackoverflow.com/questions/90493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I cast long to HWND (C++ visual studio 8)? ``` Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler; ``` But I got the following warning: > > warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size > > > Thanks.
HWND is a handle to a window. This type is declared in WinDef.h as follows: > > typedef HANDLE HWND; > > > HANDLE is handle to an object. This type is declared in WinNT.h as follows: > > typedef PVOID HANDLE; > > > Finally, PVOID is a pointer to any type. This type is declared in WinNT.h as follows: > > typedef void \*PVOID; > > > So, HWND is actually a pointer to void. You can cast a long to a HWND like this: > > HWND h = (HWND)my\_long\_var; > > > but very careful of what information is stored in my\_long\_var. You have to make sure that you have a pointer in there. Later edit: The warning suggest that you've got 64-bit portability checks turned on. If you're building a 32 bit application you can ignore them.
90,517
<p>When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. </p> <p>It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie?</p> <p>Should I add <code>mysql_real_escape_string</code> (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?</p>
[ { "answer_id": 90526, "author": "Jeremy Privett", "author_id": 560, "author_profile": "https://Stackoverflow.com/users/560", "pm_score": 0, "selected": false, "text": "<p>You should mysql_real_escape_string <strong><em>anything</em></strong> that could be potentially harmful. Never trust...
2008/09/18
[ "https://Stackoverflow.com/questions/90517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie? Should I add `mysql_real_escape_string` (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?
What you *really* need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.: ``` define('COOKIE_SALT', 'secretblahblahlkdsfklj'); $cookie_value = sha1($username.$password.COOKIE_SALT); ``` Then you know the cookie value is always going to be a 40-character hexidecimal string, and can compare the value the user sends back with whatever's in the database to decide whether they're valid or not: ``` if ($user_cookie_value == sha1($username_from_db.$password_drom_db.COOKIE_SALT)) { # valid } else { #not valid } ``` `mysql_real_escape_string` makes an additional hit to the database, BTW (a lot of people don't realize it requires a DB connection and queries MySQL). The best way to do what you want if you can't change your app and insist on using hackable cookie values is to use [prepared statements with bound parameters](http://devzone.zend.com/node/view/id/686).
90,553
<p>I've kind of backed myself into a corner here.</p> <p>I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls.</p> <p>What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me <em>always</em> results in a bug).</p> <p>Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, <em>that's the point</em>. I <em>want</em> to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input.</p> <p>I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?</p>
[ { "answer_id": 90566, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>If your event is already defined in your parent class, you do not need to rewire it again in your child class. That will ...
2008/09/18
[ "https://Stackoverflow.com/questions/90553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
I've kind of backed myself into a corner here. I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls. What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me *always* results in a bug). Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, *that's the point*. I *want* to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input. I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?
Declare the parent method virtual, override it in the child classes and call ``` base.checkReadyness(sender, e); ``` (or derevation thereof) from within the child class. This allows for future design evolution say if you want to do some specific error checking code before calling the parent event handler. You might not need to write millions of event handlers like this for each control, you could just write one, hook all the controls to this event handler which in turn calls the parent's event handler. One thing that I have noted is that if all this code is being placed within a dll, then you might experience a performance hit trying to call an event handler from within a dll.
90,578
<p>I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. </p> <p>For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. </p> <p>The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools.</p> <p>So, any advice on how to blend in to Java-ME?</p>
[ { "answer_id": 90601, "author": "Noel Grandin", "author_id": 6591, "author_profile": "https://Stackoverflow.com/users/6591", "pm_score": 2, "selected": false, "text": "<p>The short answer is - it's going to be annoying, but not difficult.</p>\n\n<p>Java and C# have all the same underlyin...
2008/09/18
[ "https://Stackoverflow.com/questions/90578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools. So, any advice on how to blend in to Java-ME?
This [guy here](http://crfdesign.net/programming/top-10-differences-between-java-and-c) had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java: Gotcha #10 - Give me my standard output! ---------------------------------------- To print to the standard output in Java: ``` System.out.println("Hello"); ``` Gotcha #9 - Namespaces == Freedom --------------------------------- In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package *org.test* must be in the folder *org/test* Gotcha #8 - What happened to super? ----------------------------------- In Java to refer to the superclass you use the reserved word `super` instead of `base` Gotcha #7 - Chaining constructors to a base constructor ------------------------------------------------------- You don't have this in Java. You have to call the constructor by yourself Gotcha #6 - Dagnabit, how do I subclass an existing class? ---------------------------------------------------------- To subclass a class in Java do this: ``` public class A extends B { } ``` That means class `A` is a subclass of class `B`. In C# would be `class A : B` Gotcha #5 - Why don’t constants remain constant? ------------------------------------------------ To define a constant in Java use the keyword `final` instead of `const` Gotcha #4 - Where is `ArrayList`, `Vector` or `Hashtable`? ---------------------------------------------------------- The most used data structures in java are `HashSet`, `ArrayList` and `HashMap`. They implement `Set`, `List` and `Map`. Of course, there is a bunch more. Read more about collections [here](http://java.sun.com/docs/books/tutorial/collections/index.html) Gotcha #3 - Of Accessors and Mutators (Getters and Setters) ----------------------------------------------------------- You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically. Gotcha #2 - Can't I override!? ------------------------------ You don't have to declare a method `virtual` in Java. All methods - except those declared `final` - can be overridden in Java. And the #1 gotcha… ------------------ In Java the primitive types `int`, `float`, `double`, `char` and `long` are not `Object`s like in C#. All of them have a respective object representation, like `Integer`, `Float`, `Double`, etc. That's it. Don't forget to see [the original link](http://crfdesign.net/programming/top-10-differences-between-java-and-c), there's a more detailed discussion.
90,579
<p>How to center text over an image in a table cell using javascript, css, and/or html?</p> <p>I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.</p> <p>ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way</p>
[ { "answer_id": 90596, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<p>you could try putting the images in the background.</p>\n\n<pre><code>&lt;table&gt;\n &lt;tr&gt;\n &lt;td style=\"b...
2008/09/18
[ "https://Stackoverflow.com/questions/90579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
How to center text over an image in a table cell using javascript, css, and/or html? I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is. ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way
you could try putting the images in the background. ``` <table> <tr> <td style="background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center"> Here is my text </td> </tr> </table> ``` You'll just need to set the height and width on the cell and that should be it.
90,595
<p>How to implement a web page that scales when the browser window is resized?</p> <p>I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized</p> <p>i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way?</p> <ul> <li><p>thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread</p></li> <li><p>using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution</p></li> </ul> <p>EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling</p>
[ { "answer_id": 90603, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 5, "selected": true, "text": "<p>instead of using in css say \"width: 200px\", use stuff like \"width: 50%\"</p>\n\n<p>This makes it use 50% of whatever...
2008/09/18
[ "https://Stackoverflow.com/questions/90595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
How to implement a web page that scales when the browser window is resized? I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way? * thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread * using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling
instead of using in css say "width: 200px", use stuff like "width: 50%" This makes it use 50% of whatever it's in, so in the case of: ``` <body> <div style="width:50%"> <!--some stuff--> </div> </body> ``` The div will now always take up half the window horizontaly.
90,657
<p>I'm trying to find a way to fake the result of a method called from within another method.</p> <p>I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result).</p> <p>So I have code like this:</p> <pre><code>public class MyClass(){ public void LoadData(){ SomeProperty = Helper.GetSomeData(); } public object SomeProperty {get;set;} } </code></pre> <p>I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?</p> <p>*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.</p>
[ { "answer_id": 90670, "author": "Kevin Pang", "author_id": 1574, "author_profile": "https://Stackoverflow.com/users/1574", "pm_score": 0, "selected": false, "text": "<p>Yes, a mocking framework is exactly what you're looking for. You can record / arrange how you want certain mocked out ...
2008/09/18
[ "https://Stackoverflow.com/questions/90657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11388/" ]
I'm trying to find a way to fake the result of a method called from within another method. I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result). So I have code like this: ``` public class MyClass(){ public void LoadData(){ SomeProperty = Helper.GetSomeData(); } public object SomeProperty {get;set;} } ``` I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how? \*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.
As far as I know, you should create an interface or a base abstract class for the Helper object. With Rhino Mocks you can then return the value you want. Alternatively, you can add an overload for LoadData that accepts as parameters the data that you normally retrieve from the Helper object. This might even be easier.
90,682
<p>Is it possible to get a thread dump of a Java Web Start application? And if so, how?</p> <p>It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?</p> <p>In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.</p> <p>If answers require certain java versions, please say so.</p>
[ { "answer_id": 90711, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<pre><code>StackTraceElement[] stack = Thread.currentThread().getStackTrace();\n</code></pre>\n\n<p>Then yo...
2008/09/18
[ "https://Stackoverflow.com/questions/90682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15646/" ]
Is it possible to get a thread dump of a Java Web Start application? And if so, how? It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically? In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included. If answers require certain java versions, please say so.
In the console, press V rather than T: ``` t: dump thread list v: dump thread stack ``` This works under JDK6. Don't know about others. Alternative, under JDK5 (and possibly earlier) you can send a full stack trace of all threads to standard out: *Under Windows:* type ctrl-break in the Java console. *Under Unix:* `kill -3 <java_process_id>` (e.g. kill -3 5555). This will NOT kill your app. One other thing: As others say, you can get the stacks programatically via the `Thread` class but watch out for `Thread.getAllStackTraces()` prior to JDK6 as there's a memory leak. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434648> Regards, scotty
90,693
<p>I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m_moveListTree.GetSelectedItem(); CString s = m_moveListTree.GetItemText(h);</p> <p>However when I rightclick on any item in tree I do not get any TVN_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A.</p> <p>Please help in solving problem.</p> <p>-Praveen</p>
[ { "answer_id": 90773, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": true, "text": "<p>I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handle...
2008/09/18
[ "https://Stackoverflow.com/questions/90693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN\_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m\_moveListTree.GetSelectedItem(); CString s = m\_moveListTree.GetItemText(h); However when I rightclick on any item in tree I do not get any TVN\_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A. Please help in solving problem. -Praveen
I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handles that situation: ``` LRESULT xTreeCtrl::onRightClick(NMHDR *) { xPoint pt; //-- get the cursor at the time the mesage was posted DWORD dwPos = ::GetMessagePos(); pt.x = GET_X_LPARAM(dwPos); pt.y = GET_Y_LPARAM (dwPos); //-- now convert to window co-ordinates pt.toWindow(this); //-- check for a hit HTREEITEM hItem = this->hitTest(pt); //-- select any item that was hit if ((int)hItem != -1) this->select(hItem); //-- leave the rest to default processing return 0; } ``` I suspect if you do something similar in the MFC right click or right button down events that will fix the problem. NOTE: The onRightClick code above is nothing more than the handler for the **WM\_NOTIFY**, **NM\_RCLICK** message.
90,697
<p>How do I create a resource that I can reference and use in various parts of my program easily?</p> <p>My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. </p>
[ { "answer_id": 90699, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 9, "selected": true, "text": "<p>Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this pl...
2008/09/18
[ "https://Stackoverflow.com/questions/90697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
How do I create a resource that I can reference and use in various parts of my program easily? My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though. **How to create a resource:** In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though. * Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list. * Click the "Resources" tab. * The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options. * Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose. * At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective. **How to use a resource:** Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy. There is a static class called `Properties.Resources` that gives you access to all your resources, so my code ended up being as simple as: ``` paused = !paused; if (paused) notifyIcon.Icon = Properties.Resources.RedIcon; else notifyIcon.Icon = Properties.Resources.GreenIcon; ``` Done! Finished! Everything is simple when you know how, isn't it?
90,751
<p>Do C#/.NET floating point operations differ in precision between debug mode and release mode?</p>
[ { "answer_id": 90783, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 2, "selected": false, "text": "<p>In fact, they may differ if debug mode uses the x87 FPU and release mode uses SSE for float-ops.</p>\n" }, { ...
2008/09/18
[ "https://Stackoverflow.com/questions/90751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ]
Do C#/.NET floating point operations differ in precision between debug mode and release mode?
They can indeed be different. According to the CLR ECMA specification: > > Storage locations for floating-point > numbers (statics, array elements, and > fields of classes) are of fixed size. > The supported storage sizes are > float32 and float64. Everywhere else > (on the evaluation stack, as > arguments, as return types, and as > local variables) floating-point > numbers are represented using an > internal floating-point type. In each > such instance, the nominal type of the > variable or expression is either R4 or > R8, but its value can be represented > internally with additional range > and/or precision. The size of the > internal floating-point representation > is implementation-dependent, can vary, > and shall have precision at least as > great as that of the variable or > expression being represented. An > implicit widening conversion to the > internal representation from float32 > or float64 is performed when those > types are loaded from storage. The > internal representation is typically > the native size for the hardware, or > as required for efficient > implementation of an operation. > > > What this basically means is that the following comparison may or may not be equal: ``` class Foo { double _v = ...; void Bar() { double v = _v; if( v == _v ) { // Code may or may not execute here. // _v is 64-bit. // v could be either 64-bit (debug) or 80-bit (release) or something else (future?). } } } ``` Take-home message: never check floating values for equality.
90,755
<p>How do I get a list of the active IP-addresses, MAC-addresses and <a href="http://en.wikipedia.org/wiki/NetBIOS" rel="nofollow noreferrer">NetBIOS</a> names on the LAN?</p> <p>I'd like to get NetBIOS name, IP and <a href="http://en.wikipedia.org/wiki/MAC_address" rel="nofollow noreferrer">MAC addresses</a> for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself.</p> <p>How to do that with <a href="http://en.wikipedia.org/wiki/Windows_Script_Host" rel="nofollow noreferrer">Windows Script Host</a>/PowerShell/whatever?</p>
[ { "answer_id": 90806, "author": "Tubs", "author_id": 11924, "author_profile": "https://Stackoverflow.com/users/11924", "pm_score": 2, "selected": false, "text": "<p>If you're using DHCP then the server will give you a list of all that information.</p>\n\n<p>This website has a good tutori...
2008/09/18
[ "https://Stackoverflow.com/questions/90755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
How do I get a list of the active IP-addresses, MAC-addresses and [NetBIOS](http://en.wikipedia.org/wiki/NetBIOS) names on the LAN? I'd like to get NetBIOS name, IP and [MAC addresses](http://en.wikipedia.org/wiki/MAC_address) for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself. How to do that with [Windows Script Host](http://en.wikipedia.org/wiki/Windows_Script_Host)/PowerShell/whatever?
As Daren Thomas said, use nmap. ``` nmap -sP 192.168.1.1/24 ``` to scan the network 192.168.1.\* ``` nmap -O 192.168.1.1/24 ``` to get the operating system of the user. For more information, read the manpage ``` man nmap ``` regards
90,758
<p>I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow.</p> <p>Using the Imagick PHP library is even slower as it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type).</p> <p>Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension.</p> <p><strong>Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment</strong></p>
[ { "answer_id": 90768, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 3, "selected": false, "text": "<p>If you're using PHP with GD support, you can try <a href=\"http://www.php.net/manual/en/function.getimagesize.php\" r...
2008/09/18
[ "https://Stackoverflow.com/questions/90758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ]
I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow. Using the Imagick PHP library is even slower as it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type). Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension. **Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment**
Sorry I can't add this as a comment to a previous answer but I don't have the rep. Doing some quick and dirty testing I also found that exec("identify -ping... is about 20 times faster than without the -ping. But getimagesize() appears to be about 200 times faster still. So I would say getimagesize() is the faster method. I only tested on jpg and not on png. the test is just ``` $files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG'); foreach($files as $file){ $size2 = array(); $size3 = array(); $time1 = microtime(); $size = getimagesize($file); $time1 = microtime() - $time1; print "$time1 \n"; $time2 = microtime(); exec("identify -ping $file", $size2); $time2 = microtime() - $time2; print $time2/$time1 . "\n"; $time2 = microtime(); exec("identify $file", $size3); $time2 = microtime() - $time2; print $time2/$time1 . "\n"; print_r($size); print_r($size2); print_r($size3); } ```
90,775
<p>I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe:</p> <pre><code>windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... </code></pre> <p>I tried loading the icon using:</p> <pre><code>hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>But this produces an (very unspecific) error:<br> <strong>pywintypes.error: (0, 'LoadImage', 'No error message is available')</strong><br> <br> If I try specifying 0 as a string</p> <pre><code>hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>then I get the error:<br> <strong>pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')</strong><br> <br>So, what's the correct method/syntax to load the icon?<br> <em>Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.</em></p>
[ { "answer_id": 91245, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 0, "selected": false, "text": "<p>You should set the icon ID to something other than 0:</p>\n\n<pre><code>'icon_resources': [(42, 'my_icon.ico')]\n</code...
2008/09/18
[ "https://Stackoverflow.com/questions/90775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1531/" ]
I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe: ``` windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... ``` I tried loading the icon using: ``` hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) ``` But this produces an (very unspecific) error: **pywintypes.error: (0, 'LoadImage', 'No error message is available')** If I try specifying 0 as a string ``` hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) ``` then I get the error: **pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')** So, what's the correct method/syntax to load the icon? *Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.*
@efotinis: You're right. Here is a workaround until py2exe gets fixed and you don't want to include the same icon twice: ``` hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True) ``` Be aware that **1** is not the ID you gave the icon in setup.py (which is the icon group ID), but the resource ID *automatically* assigned by py2exe to each icon in each icon group. At least that's how I understand it. If you want to create an icon with a specified size (as CreateIconFromResource uses the system default icon size), you need to use CreateIconFromResourceEx, which isn't available via PyWin32: ``` icon_res = win32api.LoadResource(None, win32con.RT_ICON, 1) hicon = ctypes.windll.user32.CreateIconFromResourceEx(icon_res, len(icon_res), True, 0x00030000, 16, 16, win32con.LR_DEFAULTCOLOR) ```
90,885
<p>I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?<br> I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.</p> <p>In the following snippet, I need the command and model to be unique. pk is of course the primary key.</p> <pre><code>@Entity @Table(name = "dm_action_plan") public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } </code></pre>
[ { "answer_id": 90960, "author": "Michel", "author_id": 7198, "author_profile": "https://Stackoverflow.com/users/7198", "pm_score": 5, "selected": true, "text": "<p>You can use <a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/UniqueConstraint.html\" rel=\"nofollow norefer...
2008/09/18
[ "https://Stackoverflow.com/questions/90885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA? I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good. In the following snippet, I need the command and model to be unique. pk is of course the primary key. ``` @Entity @Table(name = "dm_action_plan") public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } ```
You can use [`@UniqueConstraint`](http://java.sun.com/javaee/5/docs/api/javax/persistence/UniqueConstraint.html) something like this : ``` @Entity @Table(name = "dm_action_plan", uniqueConstraints={ @UniqueConstraint(columnNames= "command","model") } ) public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } ``` This will allow your JPA implementation to generate the DDL for the unique constraint.
90,899
<p>How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:</p> <pre><code>CalendarItems = CalendarFolder.Items; CalendarItems.IncludeRecurrences = true; </code></pre> <p>I only get 1 item...</p> <p>Is there an easy way to get <strong>all</strong> items (main item + derived items) from a calendar? In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).</p> <p><strong>I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)</strong>.</p>
[ { "answer_id": 91652, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 5, "selected": true, "text": "<p>I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them....
2008/09/18
[ "https://Stackoverflow.com/questions/90899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this: ``` CalendarItems = CalendarFolder.Items; CalendarItems.IncludeRecurrences = true; ``` I only get 1 item... Is there an easy way to get **all** items (main item + derived items) from a calendar? In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves). **I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)**.
I believe that you must Restrict or Find in order to get recurring appointments, otherwise Outlook won't expand them. Also, you must Sort by Start *before* setting IncludeRecurrences.
90,940
<p>I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?</p>
[ { "answer_id": 91054, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": true, "text": "<p>You can use existing memory debugging tools for this, I found Memory Validator <a href=\"http://www.vmvalidator.com/cpp/memo...
2008/09/18
[ "https://Stackoverflow.com/questions/90940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11483/" ]
I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?
You can use existing memory debugging tools for this, I found Memory Validator [1](http://www.vmvalidator.com/cpp/memory/index.html "Memory Validator") quite useful, it is able to track both API level (heap, new...) and OS level (Virtual Memory) allocations and show virtual memory maps. The other option which I also found very usefull is to be able to dump a map of the whole virtual space based on VirtualQuery function. My code for this looks like this: ``` void PrintVMMap() { size_t start = 0; // TODO: make portable - not compatible with /3GB, 64b OS or 64b app size_t end = 1U<<31; // map 32b user space only - kernel space not accessible SYSTEM_INFO si; GetSystemInfo(&si); size_t pageSize = si.dwPageSize; size_t longestFreeApp = 0; int index=0; for (size_t addr = start; addr<end; ) { MEMORY_BASIC_INFORMATION buffer; SIZE_T retSize = VirtualQuery((void *)addr,&buffer,sizeof(buffer)); if (retSize==sizeof(buffer) && buffer.RegionSize>0) { // dump information about this region printf(.... some buffer information here ....); // track longest feee region - usefull fragmentation indicator if (buffer.State&MEM_FREE) { if (buffer.RegionSize>longestFreeApp) longestFreeApp = buffer.RegionSize; } addr += buffer.RegionSize; index+= buffer.RegionSize/pageSize; } else { // always proceed addr += pageSize; index++; } } printf("Longest free VM region: %d",longestFreeApp); } ```
90,949
<p>There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!</p>
[ { "answer_id": 100658, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 5, "selected": true, "text": "<p>The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a coup...
2008/09/18
[ "https://Stackoverflow.com/questions/90949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines. Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's `__('string')` wrapper function and `gettext` (there's some useful information about this [here](https://stackoverflow.com/questions/39562/how-do-you-build-a-multi-language-web-site#41379)) Assuming there's Contents that we want to translate with the following db table: ``` CREATE TABLE `contents` ( `id` int(11) unsigned NOT NULL auto_increment, `title` varchar(255) default NULL, `body` text, PRIMARY KEY (`id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` The content.php model then has: ``` var $actsAs = array('Translate' => array('title' => 'titleTranslation', 'body' => 'bodyTranslation' )); ``` in its definition. You then need to add the i18n table to the database thusly: ``` CREATE TABLE `i18n` ( `id` int(10) NOT NULL auto_increment, `locale` varchar(6) NOT NULL, `model` varchar(255) NOT NULL, `foreign_key` int(10) NOT NULL, `field` varchar(255) NOT NULL, `content` mediumtext, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish): ``` $this->Content->locale = 'pol'; $result = $this->Content->save($this->data); ``` This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like: ``` [Content] [id] [titleTranslation] [bodyTranslation] ``` We use the excellent [p28n component](http://bakery.cakephp.org/articles/view/p28n-the-top-to-bottom-persistent-internationalization-tutorial) to implement a language switching solution that works pretty well with the gettext and translate behaviours. It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.
90,971
<p>Let's say I have a class:</p> <pre><code>class Foo { public string Bar { get { ... } } public string this[int index] { get { ... } } } </code></pre> <p>I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine.</p> <p>Now let's say I want to implement INotifyPropertyChanged:</p> <pre><code>class Foo : INotifyPropertyChanged { public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?</p>
[ { "answer_id": 91020, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 2, "selected": false, "text": "<p>Don't know for sure if this'll work, but reflector shows that the get and set methods for an indexed property a...
2008/09/18
[ "https://Stackoverflow.com/questions/90971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6604/" ]
Let's say I have a class: ``` class Foo { public string Bar { get { ... } } public string this[int index] { get { ... } } } ``` I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine. Now let's say I want to implement INotifyPropertyChanged: ``` class Foo : INotifyPropertyChanged { public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged; } ``` What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?
Thanks to Cameron's suggestion, I've found the correct syntax, which is: ``` Item[] ``` Which updates everything (all index values) bound to that indexed property.
90,977
<p>Emacs Lisp has <code>replace-string</code> but has no <code>replace-char</code>. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:</p> <pre><code>(replace-string (make-string 1 ?\x53979) "'") </code></pre> <p>I think it would be better with <code>replace-char</code>. </p> <p>What is the best way to do this?</p>
[ { "answer_id": 91043, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>which would certainly be better with replace-char. Any way to improve my code?</p>\n</blockquote>\n\n<p>...
2008/09/18
[ "https://Stackoverflow.com/questions/90977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
Emacs Lisp has `replace-string` but has no `replace-char`. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with: ``` (replace-string (make-string 1 ?\x53979) "'") ``` I think it would be better with `replace-char`. What is the best way to do this?
Why not just use ``` (replace-string "\x53979" "'") ``` or ``` (while (search-forward "\x53979" nil t) (replace-match "'" nil t)) ``` as recommended in the documentation for replace-string?
90,982
<p>I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:</p> <p>Message<br> -- TextMessage<br> -------- InvitationTextMessage<br> -- EmailMessage<br> -------- InvitationEmailMessage </p> <p>The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. </p> <p>What's the most light-weight approach to solve the issue? </p> <p>Thanks!</p>
[ { "answer_id": 90991, "author": "danio", "author_id": 12663, "author_profile": "https://Stackoverflow.com/users/12663", "pm_score": 2, "selected": false, "text": "<p>It sounds like the <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">decorator patter...
2008/09/18
[ "https://Stackoverflow.com/questions/90982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy: Message -- TextMessage -------- InvitationTextMessage -- EmailMessage -------- InvitationEmailMessage The two types of Invitation\* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. What's the most light-weight approach to solve the issue? Thanks!
Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way: ``` $m = new Message(); $m->type = 'text/html'; $m->from = 'John Doe <jdoe@yahoo.com>'; $m->to = 'Random Hacker <rh@gmail.com>'; $m->subject = 'Invitation email'; $m->importBody('invitation.html'); $d = new MessageDispatcher(); $d->dispatch($m); ``` This way you can add some specialisation to Message class: ``` $htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor $textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor $d = new MessageDispatcher(); $d->dispatch($htmlIM); $d->dispatch($textIM); ``` Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on `type` property in Message object passed. ``` // in MessageDispatcher class public function dispatch(Message $m) { if ($m->type == 'text/plain') { $this->sendAsText($m); } elseif ($m->type == 'text/html') { $this->sendAsHTML($m); } else { throw new Exception("MIME type {$m->type} not supported"); } } ``` To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it [here](https://web.archive.org/web/20190613203216/https://www.dofactory.com/net/strategy-design-pattern).
90,988
<p>Using eclipse 3.3.2 with MyEclipse installed. For some reason if a file isn't called build.xml then it isnt' recognised as an ant file. The file association for *.xml includes ant and says "locked by 'Ant Buildfile' content type.</p> <p>The run-as menu is broken. Even if the editor association works run-as doesn't.</p> <p>The ant buildfiles in question are correctly formatted. They work fine if you call them build.xml or if you use them anywhere else. Eclipse just won't recognise and thus wont allow you to run them.</p>
[ { "answer_id": 91324, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 0, "selected": false, "text": "<p>If you open the \"File Associations\" page (Window -> Preferences -> General -> Editors -> File Associations) you ...
2008/09/18
[ "https://Stackoverflow.com/questions/90988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using eclipse 3.3.2 with MyEclipse installed. For some reason if a file isn't called build.xml then it isnt' recognised as an ant file. The file association for \*.xml includes ant and says "locked by 'Ant Buildfile' content type. The run-as menu is broken. Even if the editor association works run-as doesn't. The ant buildfiles in question are correctly formatted. They work fine if you call them build.xml or if you use them anywhere else. Eclipse just won't recognise and thus wont allow you to run them.
The environment inspects the file contents to determine if it is an Ant file (if it isn't called "build.xml"). Add the following to the XML file: ``` <?xml version="1.0" encoding="UTF-8"?> <project name="myproject" default="t1"> <target name="t1"></target> </project> ``` You should now see the "Ant Editor" in the "Open With >" menu when you right-click on the file.
90,996
<p>I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.</p> <p>What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..</p>
[ { "answer_id": 90998, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "<p>NewItems is my List here... This is a bit clunky though. </p>\n\n<pre><code>for(int iLooper = obEvtArgs.NewItems.Count-1; iL...
2008/09/18
[ "https://Stackoverflow.com/questions/90996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user. What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..
If you have .NET 3.5 you could use LINQ's Reverse? ``` foreach(var item in obEvtArgs.NewItems.Reverse()) { ... } ``` (Assuming you're talking about the generic IList)
91,108
<p>How do I get my C# program to sleep (pause execution) for 50 milliseconds?</p>
[ { "answer_id": 91119, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 10, "selected": true, "text": "<pre><code>System.Threading.Thread.Sleep(50);\n</code></pre>\n\n<p>Remember though, that doing this in the main GUI thread ...
2008/09/18
[ "https://Stackoverflow.com/questions/91108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
How do I get my C# program to sleep (pause execution) for 50 milliseconds?
``` System.Threading.Thread.Sleep(50); ``` Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish") Just remove the `;` to make it work for VB.net as well.
91,110
<p>How to match a single quote in sed if the expression is enclosed in single quotes:</p> <pre><code>sed -e '...' </code></pre> <p>For example need to match this text:</p> <pre><code>'foo' </code></pre>
[ { "answer_id": 91176, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 7, "selected": true, "text": "\n\n<p>You can either use:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>\"texta'textb\" (APOSTROPHE inside QUOTATIO...
2008/09/18
[ "https://Stackoverflow.com/questions/91110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
How to match a single quote in sed if the expression is enclosed in single quotes: ``` sed -e '...' ``` For example need to match this text: ``` 'foo' ```
You can either use: ```none "texta'textb" (APOSTROPHE inside QUOTATION MARKs) ``` or ```none 'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE) ``` I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash. In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.
91,116
<p>I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format:</p> <pre><code>6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% ))) </code></pre> <p>Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc.</p> <p>I'm writing this mostly as a note for myself, but improvements are always welcome. :)</p> <p>Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an <a href="http://en.wikipedia.org/wiki/Earth_radius" rel="nofollow noreferrer">appropriate alternative number</a> to use meters, miles etc.</p>
[ { "answer_id": 91144, "author": "Adam Hopkinson", "author_id": 12280, "author_profile": "https://Stackoverflow.com/users/12280", "pm_score": 2, "selected": false, "text": "<p>Am i right in thinking this is the Haversine formula?</p>\n" }, { "answer_id": 91481, "author": "Vale...
2008/09/18
[ "https://Stackoverflow.com/questions/91116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format: ``` 6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% ))) ``` Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc. I'm writing this mostly as a note for myself, but improvements are always welcome. :) Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an [appropriate alternative number](http://en.wikipedia.org/wiki/Earth_radius) to use meters, miles etc.
For databases (such as SQLite) that don't support trigonometric functions you can use the Pythagorean theorem. This is a faster method, even if your database does support trigonometric functions, with the following caveats: * you need to store coords in x,y grid instead of (or as well as) lat,lng; * the calculation assumes 'flat earth', but this is fine for relatively local searches. Here's an example from a Rails project I'm working on (the important bit is the SQL in the middle): ``` class User < ActiveRecord::Base ... # has integer x & y coordinates ... # Returns array of {:user => <User>, :distance => <distance>}, sorted by distance (in metres). # Distance is rounded to nearest integer. # point is a Geo::LatLng. # radius is in metres. # limit specifies the maximum number of records to return (default 100). def self.find_within_radius(point, radius, limit = 100) sql = <<-SQL select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d from users where #{(radius ** 2)} >= d order by d limit #{limit} SQL users = User.find_by_sql(sql) users.each {|user| user.d = Math.sqrt(user.d.to_f).round} return users end ```
91,124
<p>Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType?</p> <p>Could it handle the many different possible ways of writing the type in T-SQL, such as:</p> <pre><code>[nvarchar](50) nvarchar 50 </code></pre> <p>@Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer.</p>
[ { "answer_id": 91139, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 2, "selected": false, "text": "<p>In addition to yours I will put:</p>\n\n<ul>\n<li>Unit Test Strategy</li>\n<li>Integration Test Strategy</li>\n<l...
2008/09/18
[ "https://Stackoverflow.com/questions/91124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
Suppose I have a string 'nvarchar(50)', which is for example the T-SQL string segment used in creating a table of that type. How do I best convert that to an enum representation of System.Data.DbType? Could it handle the many different possible ways of writing the type in T-SQL, such as: ``` [nvarchar](50) nvarchar 50 ``` @Jorge Table: Yes, that's handy, but isn't there a prebaked converter? Otherwise good answer.
As a preliminary answer, check out the Joel test: <http://www.joelonsoftware.com/articles/fog0000000043.html> Just an appetizer: > > 1. Do you use source control? > 2. Can you make a build in one step? > 3. Do you make daily builds? > 4. Do you have a bug database? > 5. Do you fix bugs before writing new code? > 6. Do you have an up-to-date schedule? > 7. Do you have a spec? > 8. Do programmers have quiet working conditions? > 9. Do you use the best tools money can buy? > 10. Do you have testers? > 11. Do new candidates write code during their interview? > 12. Do you do hallway usability testing? > > >
91,127
<p>I want to verify a drag &amp; drop operation is allowed. A valid item can come from another one of our "controls", or internally from within the custom treeview. Currently I have this:</p> <pre><code>bool CanDrop(DragEventArgs e) { bool allow = false; Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); if (target != null) { if (CanWrite(target)) //user permissions { if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application { DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject)); DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection; if (data != null) { allow = true; } } else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this &amp; not a root node { if (TargetExistsInNode(tree.SelectedNode, target) == false) { if (e.Effect == DragDropEffects.Copy) { allow = true; } else if (e.Effect == DragDropEffects.Move) { allow = true; } } } } } return allow; } </code></pre> <p>I've moved all the checking code to this method to try to improve things, but to me this is still horrible!</p> <p>So much logic, and so much of it to do things that I'd expect the treeview would do itself (eg. "TargetExistsInNode" checks whether the dragged node is being dragged to one of its children).</p> <p>What is the best way to validate input to a control?</p>
[ { "answer_id": 91995, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": true, "text": "<p>I use the TreeNode.Tag property to store small \"controller\" objects that makes up the logic. E.g.:</p>\n\n<pre><code>c...
2008/09/18
[ "https://Stackoverflow.com/questions/91127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15608/" ]
I want to verify a drag & drop operation is allowed. A valid item can come from another one of our "controls", or internally from within the custom treeview. Currently I have this: ``` bool CanDrop(DragEventArgs e) { bool allow = false; Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); if (target != null) { if (CanWrite(target)) //user permissions { if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application { DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject)); DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection; if (data != null) { allow = true; } } else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this & not a root node { if (TargetExistsInNode(tree.SelectedNode, target) == false) { if (e.Effect == DragDropEffects.Copy) { allow = true; } else if (e.Effect == DragDropEffects.Move) { allow = true; } } } } } return allow; } ``` I've moved all the checking code to this method to try to improve things, but to me this is still horrible! So much logic, and so much of it to do things that I'd expect the treeview would do itself (eg. "TargetExistsInNode" checks whether the dragged node is being dragged to one of its children). What is the best way to validate input to a control?
I use the TreeNode.Tag property to store small "controller" objects that makes up the logic. E.g.: ``` class TreeNodeController { Entity data; virtual bool IsReadOnly { get; } virtual bool CanDrop(TreeNodeController source, DragDropEffects effect); virtual bool CanDrop(DataInfoObject info, DragDropEffects effect); virtual bool CanRename(); } class ParentNodeController : TreeNodeController { override bool IsReadOnly { get { return data.IsReadOnly; } } override bool CanDrop(TreeNodeController source, DragDropEffect effect) { return !IsReadOnly && !data.IsChildOf(source.data) && effect == DragDropEffect.Move; } virtual bool CanDrop(DataInfoObject info, DragDropEffects effect) { return info.DragDataCollection != null; } override bool CanRename() { return !data.IsReadOnly && data.HasName; } } class LeafNodeController : TreeNodeController { override bool CanDrop(TreeNodeController source, DragDropEffect effect) { return false; } } ``` Then my CanDrop would be something like: ``` bool CanDrop(DragDropEventArgs args) { Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); TreeNodeController targetController = target.Tag as TreeNodeController; DataInfoObject info = args.GetData(typeof(DataInfoObject)) as DataInfoObject; TreeNodeController sourceController = args.GetData(typeof(TreeNodeController)) as TreeNodeController; if (info != null) return targetController.CanDrop(info, e.Effect); if (sourceController != null) return targetController.CanDrop(sourceController, e.Effect); return false; } ``` Now for each class of objects that I add to the tree I can specialize the behaviour by choosing which TreeNodeController to put in the Tag object.
91,160
<p>How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values?</p> <p>For example:</p> <pre><code>DbType.StringFixedLength -&gt; System.String DbType.String -&gt; System.String DbType.Int32 -&gt; System.Int32 </code></pre> <p>I've only seen very "dirty" solutions but nothing really clean.</p> <p>(yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)</p>
[ { "answer_id": 91177, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "<p>AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping yo...
2008/09/18
[ "https://Stackoverflow.com/questions/91160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values? For example: ``` DbType.StringFixedLength -> System.String DbType.String -> System.String DbType.Int32 -> System.Int32 ``` I've only seen very "dirty" solutions but nothing really clean. (yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)
AFAIK there is no built-in converter in .NET for converting a SqlDbType to a System.Type. But knowing the mapping you can easily roll your own converter ranging from a simple dictionary to more advanced (XML based for extensability) solutions. The mapping can be found here: <http://www.carlprothman.net/Default.aspx?tabid=97>
91,169
<p>So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do:</p> <pre><code>pfiles `ls /proc` | less </code></pre> <p>and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up.</p> <p>Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on <strong>all</strong> processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.</p>
[ { "answer_id": 91188, "author": "Christoffer", "author_id": 15514, "author_profile": "https://Stackoverflow.com/users/15514", "pm_score": -1, "selected": false, "text": "<p>If you have access to <code>netstat</code>, that can do precisely that. </p>\n" }, { "answer_id": 91194, ...
2008/09/18
[ "https://Stackoverflow.com/questions/91169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do: ``` pfiles `ls /proc` | less ``` and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up. Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on **all** processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.
I found this script somewhere. I don't remember where, but it works for me: ``` #!/bin/ksh line='---------------------------------------------' pids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}') if [ $# -eq 0 ]; then read ans?"Enter port you would like to know pid for: " else ans=$1 fi for f in $pids do /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q "port: $ans" if [ $? -eq 0 ]; then echo $line echo "Port: $ans is being used by PID:\c" /usr/bin/ps -ef -o pid -o args | egrep -v "grep|pfiles" | grep $f fi done exit 0 ``` Edit: Here is the original source: [[Solaris] Which process is bound to a given port ?](http://blogs.oracle.com/JoachimAndres/entry/solaris_which_process_is_bound1)
91,223
<p>I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way).</p> <p>How can I do this with ASP?</p>
[ { "answer_id": 91334, "author": "Jordi", "author_id": 1893, "author_profile": "https://Stackoverflow.com/users/1893", "pm_score": 2, "selected": false, "text": "<p>You could try making a ping to the server and check the response.\nTake a look at this <a href=\"http://classicasp.aspfaq.co...
2008/09/18
[ "https://Stackoverflow.com/questions/91223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367/" ]
I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way). How can I do this with ASP?
All you need to do is have the code continue on error, then post to the other server and read the status from the post. Something like this: ``` PostURL = homelink & "CustID.aspx?SearchFlag=PO" set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.3.0") ``` **on error resume next** ``` xmlhttp.open "POST", PostURL, false xmlhttp.send "" ``` **status = xmlhttp.status** ``` if err.number <> 0 or status <> 200 then if status = 404 then Response.Write "ERROR: Page does not exist (404).<BR><BR>" elseif status >= 401 and status < 402 then Response.Write "ERROR: Access denied (401).<BR><BR>" elseif status >= 500 and status <= 600 then Response.Write "ERROR: 500 Internal Server Error on remote site.<BR><BR>" else Response.write "ERROR: Server is down or does not exist.<BR><BR>" end if else 'Response.Write "Server is up and URL is available.<BR><BR>" getcustomXML = xmlhttp.responseText end if set xmlhttp = nothing ```
91,263
<p>Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make.</p> <p>So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues.</p> <p>All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening.</p> <p>So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console.</p> <p>I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make. </p>
[ { "answer_id": 91273, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 4, "selected": true, "text": "<p>this should do the trick:</p>\n\n<p></p>\n\n<pre><code>if not ERRORLEVEL 0 pause\n</code></pre>\n\n<p>type <code>help i...
2008/09/18
[ "https://Stackoverflow.com/questions/91263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6063/" ]
Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make. So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues. All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening. So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console. I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make.
this should do the trick: ``` if not ERRORLEVEL 0 pause ``` type `help if` in DOS for more info on errorlevel usage.
91,275
<p>I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.</p> <p>I've found some information on the WebRequest class in C# (specifically from <a href="http://msdn.microsoft.com/en-us/library/debx8sh9.aspx" rel="noreferrer">here</a>) but before I start diving into it, I wondered if this was the right tool for the job.</p> <p>I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.</p>
[ { "answer_id": 91296, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 0, "selected": false, "text": "<p>I have used WebRequest for interacting with websites. It is the right 'tool'</p>\n\n<p>I can't comment on the JSON aspe...
2008/09/18
[ "https://Stackoverflow.com/questions/91275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started. I've found some information on the WebRequest class in C# (specifically from [here](http://msdn.microsoft.com/en-us/library/debx8sh9.aspx)) but before I start diving into it, I wondered if this was the right tool for the job. I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.
WebRequest and more specifically the HttpWebRequest class is a good starting point for what you want to achieve. To create the request you will use the WebRequest.Create and cast the created request to an HttpWebRequest to actually use it. You will then create your post data and send it to the stream like: ``` HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://mysite.com/index.php"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string postData = "var=value1&var2=value2"; req.ContentLength = postData.Length; StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(postData); stOut.Close(); ``` Similarly you can read the response back by using the GetResponse method which will allow you to read the resultant response stream and do whatever else you need to do. You can find more info on the class at: <http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx>
91,289
<p>I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is.</p> <p>Does anybody know how I can tell rails to look at the 'public' schema for this table?</p> <p>Example of SQL being executed: ~</p> <pre><code>CREATE SCHEMA new_schema; COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema'; -- various tables, triggers and functions created in new_schema </code></pre> <p>Error being thrown: ~</p> <pre><code>RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist L221 RRangeVarGetRelid: UPDATE schema_info SET version = ?? </code></pre> <p>Thanks for your help</p> <p>Chris Knight</p>
[ { "answer_id": 91449, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I understand what you're asking exactly, but, rake will be expecting to update the version of the Rails ...
2008/09/18
[ "https://Stackoverflow.com/questions/91289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557/" ]
I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema\_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is. Does anybody know how I can tell rails to look at the 'public' schema for this table? Example of SQL being executed: ~ ``` CREATE SCHEMA new_schema; COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema'; -- various tables, triggers and functions created in new_schema ``` Error being thrown: ~ ``` RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist L221 RRangeVarGetRelid: UPDATE schema_info SET version = ?? ``` Thanks for your help Chris Knight
Well that depends what your migration looks like, what your database.yml looks like and what exactly you are trying to attempt. Anyway more information is needed change the names if you have to and post an example database.yml and the migration. does the migration change the search\_path for the adapter for example ? But know that in general rails and postgresql schemas don't work well together (yet?). There are a few places which have problems. Try and build and app that uses only one pg database with 2 non-default schemas one for dev and one for test and tell me about it. (from thefollowing I can already tell you that you will get burned) Maybe it was fixed since the last time I played with it but when I see <http://rails.lighthouseapp.com/projects/8994/tickets/390-postgres-adapter-quotes-table-name-breaks-when-non-default-schema-is-used> or this <http://rails.lighthouseapp.com/projects/8994/tickets/918-postgresql-tables-not-generating-correct-schema-list> or this in postgresql\_adapter.rb ``` # Drops a PostgreSQL database # # Example: # drop_database 'matt_development' def drop_database(name) #:nodoc: execute "DROP DATABASE IF EXISTS #{name}" end ``` (yes this is wrong if you use the same database with different schemas for both dev and test, this would drop both databases each time you run the unit tests !) I actually started writing patches. the first one was for the indexes methods in the adapter which didn't care about the search\_path ending up with duplicated indexes in some conditions, then I started getting hurt by the rest and ended up abandonning the idea of using schemas: I wanted to get *my* app done and I didn't have the extra time needed to fix the problems I had using schemas.
91,305
<p>Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?</p> <p>The ideal would be something like:</p> <pre><code>var myXML: XML = ???; // ... load xml data into the XML object myXML.someAttribute = newValue; </code></pre>
[ { "answer_id": 91952, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 5, "selected": true, "text": "<p>Attributes are accessible in AS3 using the <code>@</code> prefix.</p>\n\n<p>For example:</p>\n\n<pre><code>var myXML:XM...
2008/09/18
[ "https://Stackoverflow.com/questions/91305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own? The ideal would be something like: ``` var myXML: XML = ???; // ... load xml data into the XML object myXML.someAttribute = newValue; ```
Attributes are accessible in AS3 using the `@` prefix. For example: ``` var myXML:XML = <test name="something"></test>; trace(myXML.@name); myXML.@name = "new"; trace(myXML.@name); ``` Output: ``` something new ```
91,355
<p>Environment: HP laptop with Windows XP SP2</p> <p>I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error:</p> <pre> C:\sureshr>gpg -a c:\sureshr\work\passwords.gpg gpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB" gpg: decryption failed: secret key not available C:\sureshr>gpg --list-keys C:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg -------------------------------------------------------------------- pub 1024D/80059241 2008-07-21 uid Suresh Ramaswamy (AAA) BBB sub 1024g/279AB302 2008-07-21 </pre> <p>AAA = gpg comment <br> BBB = my email address</p> <p>I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key?</p> <p>Thanks,</p> <p>Suresh</p>
[ { "answer_id": 91371, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.</p>\n\n<p>Do yo...
2008/09/18
[ "https://Stackoverflow.com/questions/91355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Environment: HP laptop with Windows XP SP2 I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error: ``` C:\sureshr>gpg -a c:\sureshr\work\passwords.gpg gpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB" gpg: decryption failed: secret key not available C:\sureshr>gpg --list-keys C:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg -------------------------------------------------------------------- pub 1024D/80059241 2008-07-21 uid Suresh Ramaswamy (AAA) BBB sub 1024g/279AB302 2008-07-21 ``` AAA = gpg comment BBB = my email address I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key? Thanks, Suresh
when reimporting your keys from the old keyring, you need to specify the command: ``` gpg --allow-secret-key-import --import <keyring> ``` otherwise it will only import the public keys, not the private keys.
91,357
<p>I want to log in to Stack Overflow with Techorati OpenID hosted at my site.</p> <p><a href="https://stackoverflow.com/users/login">https://stackoverflow.com/users/login</a> has some basic information.</p> <p>I understood that I should change</p> <pre><code>&lt;link rel="openid.delegate" href="http://yourname.x.com" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /&gt; </code></pre> <p>but if I change</p> <pre><code>&lt;link rel="openid.server" href="http://x.com/server" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/server" /&gt; </code></pre> <p>or</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/" /&gt; </code></pre> <p>it does not work.</p>
[ { "answer_id": 91371, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 3, "selected": false, "text": "<p>Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.</p>\n\n<p>Do yo...
2008/09/18
[ "https://Stackoverflow.com/questions/91357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ]
I want to log in to Stack Overflow with Techorati OpenID hosted at my site. <https://stackoverflow.com/users/login> has some basic information. I understood that I should change ``` <link rel="openid.delegate" href="http://yourname.x.com" /> ``` to ``` <link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /> ``` but if I change ``` <link rel="openid.server" href="http://x.com/server" /> ``` to ``` <link rel="openid.server" href="http://technorati.com/server" /> ``` or ``` <link rel="openid.server" href="http://technorati.com/" /> ``` it does not work.
when reimporting your keys from the old keyring, you need to specify the command: ``` gpg --allow-secret-key-import --import <keyring> ``` otherwise it will only import the public keys, not the private keys.
91,360
<p>I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc...</p> <p>The calculation happens once a month on a non production server, no worries about performance.</p> <p>What would the SQL look like to do it?</p> <p>If you're confused, don't worry, I am as well!</p> <p>User table:</p> <pre><code>ID ParentID Points 1 0 230 2 1 150 3 0 80 4 1 110 5 4 54 6 4 342 Tree: 0 |---\ 1 3 | \ 2 4--- \ \ 5 6 </code></pre> <p>Output should be:</p> <pre><code>ID Points Level1 Level2 1 230 150+110 150+110+54+342 2 150 3 80 4 110 54+342 5 54 6 342 </code></pre> <p>SQL Server Syntax and functions preferably...</p>
[ { "answer_id": 91372, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 1, "selected": false, "text": "<p>I would say: create a stored procedure, probably has the best performance.\nOr if you have a maximum number of le...
2008/09/18
[ "https://Stackoverflow.com/questions/91360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc... The calculation happens once a month on a non production server, no worries about performance. What would the SQL look like to do it? If you're confused, don't worry, I am as well! User table: ``` ID ParentID Points 1 0 230 2 1 150 3 0 80 4 1 110 5 4 54 6 4 342 Tree: 0 |---\ 1 3 | \ 2 4--- \ \ 5 6 ``` Output should be: ``` ID Points Level1 Level2 1 230 150+110 150+110+54+342 2 150 3 80 4 110 54+342 5 54 6 342 ``` SQL Server Syntax and functions preferably...
If you were using Oracle DBMS that would be pretty straightforward since Oracle supports tree queries with the **CONNECT BY/STARTS WITH** syntax. For SQL Server I think you might find [Common Table Expressions](http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1277481,00.html) useful
91,362
<p>How can brackets be escaped in using <code>string.Format</code>?</p> <p>For example:</p> <pre><code>String val = &quot;1,2,3&quot; String.Format(&quot; foo {{0}}&quot;, val); </code></pre> <p>This example doesn't throw an exception, but it outputs the string <code>foo {0}</code>.</p> <p>Is there a way to escape the brackets?</p>
[ { "answer_id": 91375, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 11, "selected": true, "text": "<p>For you to output <code> foo {1, 2, 3}</code> you have to do something like:</p>\n<pre><code>string t = &quot;1, 2,...
2008/09/18
[ "https://Stackoverflow.com/questions/91362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
How can brackets be escaped in using `string.Format`? For example: ``` String val = "1,2,3" String.Format(" foo {{0}}", val); ``` This example doesn't throw an exception, but it outputs the string `foo {0}`. Is there a way to escape the brackets?
For you to output `foo {1, 2, 3}` you have to do something like: ``` string t = "1, 2, 3"; string v = String.Format(" foo {{{0}}}", t); ``` To output a `{` you use `{{` and to output a `}` you use `}}`. **Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)** **Escaping brackets: String interpolation $("")**. It is new feature in C# 6.0. ``` var inVal = "1, 2, 3"; var outVal = $" foo {{{inVal}}}"; // The output will be: foo {1, 2, 3} ```
91,368
<p>From a shell script, how do I check if a directory contains files?</p> <p>Something similar to this</p> <pre class="lang-sh prettyprint-override"><code>if [ -e /some/dir/* ]; then echo "huzzah"; fi; </code></pre> <p>but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).</p>
[ { "answer_id": 91387, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>if [ ! -z `ls /some/dir/*` ]; then echo \"huzzah\"; fi\n</code></pre>\n" }, { "answer_id...
2008/09/18
[ "https://Stackoverflow.com/questions/91368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17491/" ]
From a shell script, how do I check if a directory contains files? Something similar to this ```sh if [ -e /some/dir/* ]; then echo "huzzah"; fi; ``` but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
The solutions so far use `ls`. Here's an all bash solution: ``` #!/bin/bash shopt -s nullglob dotglob # To include hidden files files=(/some/dir/*) if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi ```
91,420
<p>I have a static library written in C++ and I have a structure describing data format, i.e.<br></p> <pre><code>struct Format{ long fmtId; long dataChunkSize; long headerSize; Format(long, long, long); bool operator==(Format const &amp; other) const; }; </code></pre> <p>Some of data formats are widely used, like <code>{fmtId=0, dataChunkSize=128, headerSize=0}</code> and <code>{fmtId=0, dataChunkSize=256, headerSize=0}</code><br><br> Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global <code>Format</code> members <code>gFmt128, gFmt256</code> that I can pass by reference. I instantiate them in a .cpp file like </p> <p><code>Format gFmt128(0, 128, 0);</code></p> <p>and in .h there is</p> <p><code>extern Format gFmt128;</code></p> <p>also, I declare <code>Format const &amp; Format::Fmt128(){return gFmt128;}</code> and try to use it in the main module.</p> <p>But if I try and do it in the main module that uses the lib, the linker complains about unresolved external <code>gFmt128</code>.</p> <p>How can I make my library 'export' those global vars, so I can use them from other modules?</p>
[ { "answer_id": 91433, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 2, "selected": false, "text": "<p>Are they defined in .cpp file as well? Roughly, it should look like:</p>\n\n<pre><code>struct Format\n{\n [...]\n static...
2008/09/18
[ "https://Stackoverflow.com/questions/91420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481/" ]
I have a static library written in C++ and I have a structure describing data format, i.e. ``` struct Format{ long fmtId; long dataChunkSize; long headerSize; Format(long, long, long); bool operator==(Format const & other) const; }; ``` Some of data formats are widely used, like `{fmtId=0, dataChunkSize=128, headerSize=0}` and `{fmtId=0, dataChunkSize=256, headerSize=0}` Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global `Format` members `gFmt128, gFmt256` that I can pass by reference. I instantiate them in a .cpp file like `Format gFmt128(0, 128, 0);` and in .h there is `extern Format gFmt128;` also, I declare `Format const & Format::Fmt128(){return gFmt128;}` and try to use it in the main module. But if I try and do it in the main module that uses the lib, the linker complains about unresolved external `gFmt128`. How can I make my library 'export' those global vars, so I can use them from other modules?
Don't use the static keyword on global declarations. [Here is an article explain the visibility of variables with/without static](http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx). The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.
91,434
<p>I want to display an error message on my asp.net application. This message is a warning message, this is the way I did it:</p> <pre class="lang-js prettyprint-override"><code>CmdCalcInvoke.Attributes[&quot;onclick&quot;] = &quot;return confirm('Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change')&quot;; </code></pre> <p>The code above works fine. The <code>CmdCalcInvoke</code> is an <code>htmlInputButton</code>. This is the message that the message box displays;</p> <blockquote> <p><em>Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change</em></p> </blockquote> <p>What I want to do is to display this message, but wanted to highlight the WARNING word by making it bold, or displaying the word in red, can this be done???, can't remember seeing a message box with this characteristics, but I though i would ask in case</p> <p>Any suggestions will be welcome</p>
[ { "answer_id": 91461, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>you can if you dont use the default alert boxes. Try using a javascript modal window which is just normal div markup tha...
2008/09/18
[ "https://Stackoverflow.com/questions/91434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to display an error message on my asp.net application. This message is a warning message, this is the way I did it: ```js CmdCalcInvoke.Attributes["onclick"] = "return confirm('Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change')"; ``` The code above works fine. The `CmdCalcInvoke` is an `htmlInputButton`. This is the message that the message box displays; > > *Are you sure you want to calculate the certification? WARNING: If the quarter has not finished, all the partners status will change* > > > What I want to do is to display this message, but wanted to highlight the WARNING word by making it bold, or displaying the word in red, can this be done???, can't remember seeing a message box with this characteristics, but I though i would ask in case Any suggestions will be welcome
you can if you dont use the default alert boxes. Try using a javascript modal window which is just normal div markup that you can control the styling of. Look at blockui for jquery (there are loads of others)
91,479
<p>By default data extracted by the <code>GROUP BY</code> clause is ordered as ascending. How to change it to descending.</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Add <code>DESC</code> to the <code>GROUP BY</code> clause, e.g. :</p>\n\n<pre><code>GROUP BY myDate DESC\n</code></pre>\n" ...
2008/09/18
[ "https://Stackoverflow.com/questions/91479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
By default data extracted by the `GROUP BY` clause is ordered as ascending. How to change it to descending.
You should use the derived tables on your SQL. For example if you want to pick up the most recent row for an specific activity you're attempt to use: ``` select * from activities group by id_customer order by creation_date ``` but it doesn't work. Try instead: ``` SELECT * FROM ( select * from activities order by creation_date desc ) sorted_list GROUP BY id_customer ```
91,480
<p>I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "<p>Add <code>DESC</code> to the <code>GROUP BY</code> clause, e.g. :</p>\n\n<pre><code>GROUP BY myDate DESC\n</code></pre>\n" ...
2008/09/18
[ "https://Stackoverflow.com/questions/91480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17512/" ]
I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml
You should use the derived tables on your SQL. For example if you want to pick up the most recent row for an specific activity you're attempt to use: ``` select * from activities group by id_customer order by creation_date ``` but it doesn't work. Try instead: ``` SELECT * FROM ( select * from activities order by creation_date desc ) sorted_list GROUP BY id_customer ```
91,487
<p>I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (<a href="http://docs.codehaus.org/display/JETTY/KeepGenerated" rel="nofollow noreferrer">http://docs.codehaus.org/display/JETTY/KeepGenerated</a>) in webdefault.xml but it seems unclear how this works in embedded setups.</p>
[ { "answer_id": 92213, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 0, "selected": false, "text": "<p>It is dumped already.\nfor example if you have a file called <code>index.jsp</code>, a file will be created called <co...
2008/09/18
[ "https://Stackoverflow.com/questions/91487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17507/" ]
I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (<http://docs.codehaus.org/display/JETTY/KeepGenerated>) in webdefault.xml but it seems unclear how this works in embedded setups.
If you are using Jetty 6 you can use the following code: ``` String webApp = "./web/myapp"; // Location of the jsp files String contextPath = "/myapp"; WebAppContext webAppContext = new WebAppContext(webApp, contextPath); ServletHandler servletHandler = webAppContext.getServletHandler(); ServletHolder holder = new ServletHolder(JspServlet.class); servletHandler.addServletWithMapping(holder, "*.jsp"); holder.setInitOrder(0); holder.setInitParameter("compiler", "modern"); holder.setInitParameter("fork", "false"); File dir = new File("./web/compiled/" + webApp); dir.mkdirs(); holder.setInitParameter("scratchdir", dir.getAbsolutePath()); ```
91,511
<p>I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows). I currently do this: 1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer 2. Use memcpy to copy from my original buffer to this new buffer from step 1 3. Use BitBlt to let GDI perform the color conversion</p> <p>I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches:</p> <p>a. Wrap my original mem buf in a DC to perform BitBlt directly from it</p> <p>b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to.</p> <p>So how do I do either (a) or (b)?</p> <p>thanks!</p>
[ { "answer_id": 91575, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": true, "text": "<p>OK, to address the two parts of the problem.</p>\n\n<ol>\n<li><p>the following code shows how to get at the pixels inside...
2008/09/18
[ "https://Stackoverflow.com/questions/91511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows). I currently do this: 1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer 2. Use memcpy to copy from my original buffer to this new buffer from step 1 3. Use BitBlt to let GDI perform the color conversion I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches: a. Wrap my original mem buf in a DC to perform BitBlt directly from it b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to. So how do I do either (a) or (b)? thanks!
OK, to address the two parts of the problem. 1. the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap. You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data: ``` private void LockUnlockBitsExample(PaintEventArgs e) { // Create a new bitmap. Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg"); // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. for (int counter = 2; counter < rgbValues.Length; counter += 3) rgbValues[counter] = 255; // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); // Draw the modified image. e.Graphics.DrawImage(bmp, 0, 150); } ``` To convert the contents to 8bpp you'll want to use the System.Drawing.Imaging.ColorMatrix class. I don't have at hand the correct matrix values for half-tone, but this example grayscales and adjustment of the values should give you an idea of the effect: ``` Graphics g = e.Graphics; Bitmap bmp = new Bitmap("sample.jpg"); g.FillRectangle(Brushes.White, this.ClientRectangle); // Create a color matrix // The value 0.6 in row 4, column 4 specifies the alpha value float[][] matrixItems = { new float[] {1, 0, 0, 0, 0}, new float[] {0, 1, 0, 0, 0}, new float[] {0, 0, 1, 0, 0}, new float[] {0, 0, 0, 0.6f, 0}, new float[] {0, 0, 0, 0, 1}}; ColorMatrix colorMatrix = new ColorMatrix(matrixItems); // Create an ImageAttributes object and set its color matrix ImageAttributes imageAtt = new ImageAttributes(); imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // Now draw the semitransparent bitmap image. g.DrawImage(bmp, this.ClientRectangle, 0.0f, 0.0f, bmp.Width, bmp.Height, GraphicsUnit.Pixel, imageAtt); imageAtt.Dispose(); ``` I shall try and update later with the matrix values for half-tone, it's likely to be lots 0.5 or 0.333 values in there!
91,518
<p>Suppose I have a simple XHTML document that uses a custom namespace for attributes:</p> <pre><code>&lt;html xmlns="..." xmlns:custom="http://www.example.com/ns"&gt; ... &lt;div class="foo" custom:attr="bla"/&gt; ... &lt;/html&gt; </code></pre> <p>How do I match each element that has a certain custom attribute using jQuery? Using</p> <pre><code>$("div[custom:attr]") </code></pre> <p>does not work. (Tried with Firefox only, so far.)</p>
[ { "answer_id": 91607, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<p>You should use <code>$('div').attr('custom:attr')</code>.</p>\n" }, { "answer_id": 91807, "author": "Devon",...
2008/09/18
[ "https://Stackoverflow.com/questions/91518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779/" ]
Suppose I have a simple XHTML document that uses a custom namespace for attributes: ``` <html xmlns="..." xmlns:custom="http://www.example.com/ns"> ... <div class="foo" custom:attr="bla"/> ... </html> ``` How do I match each element that has a certain custom attribute using jQuery? Using ``` $("div[custom:attr]") ``` does not work. (Tried with Firefox only, so far.)
[jQuery](https://jquery.com/) does not support custom namespaces directly, but you can find the divs you are looking for by using filter function. ``` // find all divs that have custom:attr $('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() { // matched a div with custom::attr $(this).html('I was found.'); }); ```
91,563
<p>How can I make this work?</p> <pre><code>switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } </code></pre> <p>I don't want to use the name since string comparing for types is just awfull and can be subject to change.</p>
[ { "answer_id": 91590, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 0, "selected": false, "text": "<p>Do not worry about using strings within a switch because if you have several the compiler will automatically convert i...
2008/09/18
[ "https://Stackoverflow.com/questions/91563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
How can I make this work? ``` switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } ``` I don't want to use the name since string comparing for types is just awfull and can be subject to change.
``` System.Type propertyType = typeof(Boolean); System.TypeCode typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: //doStuff break; case TypeCode.String: //doOtherStuff break; default: break; } ``` You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.
91,576
<p>I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find <code>crti.o</code>. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this <code>crti.o</code>, wouldn't it use a library file, e.g. <code>libc.a</code>?</p> <p>I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? </p> <p><code>crti.o</code> is on one of the 'libraries' search path, but should it look for <code>.o</code> file on the library path? </p> <p>Is the search path the same for <code>gcc</code> and <code>ld</code>?</p>
[ { "answer_id": 91595, "author": "stsquad", "author_id": 17507, "author_profile": "https://Stackoverflow.com/users/17507", "pm_score": 6, "selected": true, "text": "<p><code>crti.o</code> is the bootstrap library, generally quite small. It's usually statically linked into your binary. It ...
2008/09/18
[ "https://Stackoverflow.com/questions/91576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find `crti.o`. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this `crti.o`, wouldn't it use a library file, e.g. `libc.a`? I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? `crti.o` is on one of the 'libraries' search path, but should it look for `.o` file on the library path? Is the search path the same for `gcc` and `ld`?
`crti.o` is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in `/usr/lib`. If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them. You're not cross-compiling are you? If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is `gcc -print-search-dirs` and see if crti.o is in any of those paths. The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on. ``` strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test ``` Open the log file and search for crti.o, as you can see my non-cross compiler: ``` 10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o" , "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu /"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_ 64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...], "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO LLECT_NO_DEMANGLE="]) = 0 10616 open("/etc/ld.so.cache", O_RDONLY) = 3 10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3 10616 open("/lib/libc.so.6", O_RDONLY) = 3 10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5 10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6 10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7 ``` If you see a bunch of attempts to `open(...crti.o) = -1 ENOENT`, `ld` is getting confused and you want to see where the path it's opening came from...
91,617
<p>I am looking for a tool that can take a unit test, like </p> <pre><code>IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); </code></pre> <p>and generate, automatically, the corresponding stub class and interface</p> <pre><code>interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } </code></pre> <p>I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?</p>
[ { "answer_id": 91665, "author": "Carlos Villela", "author_id": 16944, "author_profile": "https://Stackoverflow.com/users/16944", "pm_score": -1, "selected": false, "text": "<p>I find that whenever I need a code generation tool like this, I am probably writing code that could be made a li...
2008/09/18
[ "https://Stackoverflow.com/questions/91617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
I am looking for a tool that can take a unit test, like ``` IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); ``` and generate, automatically, the corresponding stub class and interface ``` interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } ``` I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?
What you appear to need is a parser for your language (Java), and a name and type resolver. ("Symbol table builder"). After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression has a valid type. Normally the name/type resolver complains when it can't find a definition. What you want it to do is to find the "undefined" thing that is causing the problem, and infer a type for it. For ``` IPerson p = new Person(); ``` the name resolver knows that "Person" and "IPerson" aren't defined. If it were ``` Foo p = new Bar(); ``` there would be no clue that you wanted an interface, just that Foo is some kind of abstract parent of Bar (e.g., a class or an interface). So the decision as which is it must be known to the tool ("whenever you find such a construct, assume Foo is an interface ..."). You could use a heuristic: IFoo and Foo means IFoo should be an interface, and somewhere somebody has to define Foo as a class realizing that interface. Once the tool has made this decision, it would need to update its symbol tables so that it can move on to other statements: For ``` p.Name = "Sklivvz"; ``` given that p must be an Interface (by the previous inference), then Name must be a field member, and it appears its type is String from the assignment. With that, the statement: ``` Assert.AreEqual("Sklivvz", p.Name); ``` names and types resolve without further issue. The content of the IFoo and Foo entities is sort of up to you; you didn't have to use get and set but that's personal taste. This won't work so well when you have multiple entities in the same statement: ``` x = p.a + p.b ; ``` We know a and b are likely fields, but you can't guess what numeric type if indeed they are numeric, or if they are strings (this is legal for strings in Java, dunno about C#). For C++ you don't even know what "+" means; it might be an operator on the Bar class. So what you have to do is collect *constraints*, e.g., "a is some indefinite number or string", etc. and as the tool collects evidence, it narrows the set of possible constraints. (This works like those word problems: "Joe has seven sons. Jeff is taller than Sam. Harry can't hide behind Sam. ... who is Jeff's twin?" where you have to collect the evidence and remove the impossibilities). You also have to worry about the case where you end up with a contradiction. You could rule out p.a+p.b case, but then you can't write your unit tests with impunity. There are standard constraint solvers out there if you want impunity. (What a concept). OK, we have the ideas, now, can this be done in a practical way? The first part of this requires a parser and a bendable name and type resolver. You need a constraint solver or at least a "defined value flows to undefined value" operation (trivial constraint solver). Our [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html) with its [Java Front End](http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html) could probably do this. DMS is a tool builder's tool, for people that want to build tools that process computer langauges in arbitrary ways. (Think of "computing with program fragments rather than numbers"). DMS provides general purpose parsing machinery, and can build an tree for whatever front end it is given (e.g., Java, and there's a C# front end). The reason I chose Java is that our Java front end has all that name and type resolution machinery, and it is provided in source form so it can be bent. If you stuck to the trivial constraint solver, you could probably bend the Java name resolver to figure out the types. DMS will let you assemble trees that correspond to code fragments, and coalesce them into larger ones; as your tool collected facts for the symbol table, it could build the primitive trees. Somewhere, you have to decide you are done. How many unit tests the tool have to see before it knows the entire interface? (I guess it eats all the ones you provide?). Once complete, it assembles the fragments for the various members and build an AST for an interface; DMS can use its prettyprinter to convert that AST back into source code like you've shown. I suggest Java here because our Java front end has name and type resolution. Our C# front end does not. This is a "mere" matter of ambition; somebody has to write one, but that's quite a lot of work (at least it was for Java and I can't imagine C# is really different). But the idea works fine in principle using DMS. You could do this with some other infrastructure that gave you access to a parser and an a bendable name and type resolver. That might not be so easy to get for C#; I suspect MS may give you a parser, and access to name and type resolution, but not any way to change that. Maybe Mono is the answer? You still need a was to generate code fragments and assemble them. You might try to do this by string hacking; my (long) experience with gluing program bits together is that if you do it with strings you eventually make a mess of it. You really want pieces that represent code fragments of known type, that can only be combined in ways the grammar allows; DMS does that thus no mess.
91,628
<p>I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id;</p> <p>I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.</p>
[ { "answer_id": 91684, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<p>You could use a trigger for this (if I've read you correctly and you want the value incremented each time you update the...
2008/09/18
[ "https://Stackoverflow.com/questions/91628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb\_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb\_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id; I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.
This trigger should do the trick: ``` create trigger update_increment for update as if not update(incrementID) UPDATE tb_users SET incrementID = incrementID + 1 from inserted WHERE tb_users.id = inserted.id ```
91,629
<p>I'm trying to match elements with a name that is <code>'container1$container2$chkChecked'</code>, using a regex of <code>'.+\$chkChecked'</code>, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?</p>
[ { "answer_id": 91647, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>try</p>\n\n<pre><code>string.match( /[$]chkChecked$/ ) \n</code></pre>\n\n<p>alternatively, you could try </p>\n\n<...
2008/09/18
[ "https://Stackoverflow.com/questions/91629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I'm trying to match elements with a name that is `'container1$container2$chkChecked'`, using a regex of `'.+\$chkChecked'`, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?
my guess, by your use of quotes, is you did something like ``` re = new RegExp('.+\$chkChecked'); ``` which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter instead you want ``` re = new RegExp('.+\\$chkChecked'); ```
91,635
<p>I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?</p>
[ { "answer_id": 91659, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 4, "selected": true, "text": "<p>I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so us...
2008/09/18
[ "https://Stackoverflow.com/questions/91635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6440/" ]
I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?
I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me. If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post Edit Ok, here's the basic Intercepter code, faily basic but it does everything I need. There are two intercepters, one logs everyhing and the other allows you to define method names to allow for more fine grained logging. This solution is faily dependant on Castle Windsor **Abstract Base class** ``` namespace Tools.CastleWindsor.Interceptors { using System; using System.Text; using Castle.Core.Interceptor; using Castle.Core.Logging; public abstract class AbstractLoggingInterceptor : IInterceptor { protected readonly ILoggerFactory logFactory; protected AbstractLoggingInterceptor(ILoggerFactory logFactory) { this.logFactory = logFactory; } public virtual void Intercept(IInvocation invocation) { ILogger logger = logFactory.Create(invocation.TargetType); try { StringBuilder sb = null; if (logger.IsDebugEnabled) { sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(".{0}(", invocation.Method); for (int i = 0; i < invocation.Arguments.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(invocation.Arguments[i]); } sb.Append(")"); logger.Debug(sb.ToString()); } invocation.Proceed(); if (logger.IsDebugEnabled && invocation.ReturnValue != null) { logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue); } } catch (Exception e) { logger.Error(string.Empty, e); throw; } } } } ``` **Full Logging Implemnetation** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Logging; public class LoggingInterceptor : AbstractLoggingInterceptor { public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory) { } } } ``` **Method logging** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Interceptor; using Castle.Core.Logging; using System.Linq; public class MethodLoggingInterceptor : AbstractLoggingInterceptor { private readonly string[] methodNames; public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory) { this.methodNames = methodNames; } public override void Intercept(IInvocation invocation) { if ( methodNames.Contains(invocation.Method.Name) ) base.Intercept(invocation); } } } ```
91,672
<p>In an application where users can belong to multiple groups, I'm currently storing their groups in a column called <code>groups</code> as a binary. Every four bytes is a 32 bit integer which is the <code>GroupID</code>. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group.</p> <p>Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge.</p> <p>Another method is to create a separate table, linking users to groups. One column called <code>UserID</code> and another called <code>GroupID</code>.</p> <p>Which of these ways would be the best to do it? Or is there a better way?</p>
[ { "answer_id": 91686, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>The more standard, usable and comprehensible way is the join table. It's easily supported by many ORMs, in additio...
2008/09/18
[ "https://Stackoverflow.com/questions/91672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ]
In an application where users can belong to multiple groups, I'm currently storing their groups in a column called `groups` as a binary. Every four bytes is a 32 bit integer which is the `GroupID`. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group. Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge. Another method is to create a separate table, linking users to groups. One column called `UserID` and another called `GroupID`. Which of these ways would be the best to do it? Or is there a better way?
You have a many-to-many relationship between users and groups. This calls for a separate table to combine users with groups: ``` User: (UserId[PrimaryKey], UserName etc.) Group: (GroupId[PrimaryKey], GroupName etc.) UserInGroup: (UserId[ForeignKey], GroupId[ForeignKey]) ``` To find all users in a given group, you just say: ``` select * from User join UserInGroup on UserId Where GroupId=<the GroupId you want> ``` Rule of thumb: If you feel like you need to encode multiple values in the same field, you probably need a foreign key to a separate table. Your tricks with byte-blocks or Unicode chars are just clever tricks to encode multiple values in one field. Database design should not use clever tricks - save that for application code ;-)
91,678
<p>My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a <code>URLConnection</code>. </p> <p>How can I specify this?</p>
[ { "answer_id": 91998, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "<p>The obvious portable way would be to set a Proxy in URL.openConnection. The proxy can be in local host, you ...
2008/09/18
[ "https://Stackoverflow.com/questions/91678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17542/" ]
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a `URLConnection`. How can I specify this?
This should do the trick: ``` URL url = new URL(yourUrlHere); Proxy proxy = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress( InetAddress.getByAddress( new byte[]{your, ip, interface, here}), yourTcpPortHere)); URLConnection conn = url.openConnection(proxy); ``` And you are done. Dont forget to handle exceptions nicely and off course change the values to suit your scenario. Ah and I omitted the import statements
91,692
<p>Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)?</p> <p>I would expect to be able to instantiate a an object of some sort, give it a template along the lines of</p> <pre><code>Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} </code></pre> <p>provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order').</p> <p>I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides </p> <p>For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as</p> <pre><code>Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} </code></pre> <p>and I can pass it an Object array, in my calling Java program</p> <pre><code>new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; </code></pre> <p>However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.</p>
[ { "answer_id": 91755, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 2, "selected": false, "text": "<p>I would recommend looking into <a href=\"http://velocity.apache.org/\" rel=\"nofollow noreferrer\">Apache Velocity</a>. It ...
2008/09/18
[ "https://Stackoverflow.com/questions/91692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]
Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)? I would expect to be able to instantiate a an object of some sort, give it a template along the lines of ``` Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} ``` provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order'). I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as ``` Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} ``` and I can pass it an Object array, in my calling Java program ``` new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; ``` However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.
You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper. This blog post describes how to do it: [Java: using EL outside J2EE](http://illegalargumentexception.blogspot.com/2008/04/java-using-el-outside-j2ee.html).
91,699
<p>Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP:</p> <pre><code>function mymodule_important_calculation() { $result = /* ... long and complex calculation ... */; return $resukt; } </code></pre> <p>This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable <code>resukt</code> is being used before it is assigned.</p> <p>So... is there a way to configure PHP to be stricter with variable assignments?</p>
[ { "answer_id": 91713, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>There is no way to make it fail as far as I know, but with E_NOTICE in error_reporting settings you can make it th...
2008/09/18
[ "https://Stackoverflow.com/questions/91699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8925/" ]
Python's convention is that variables are created by first assignment, and trying to read their value before one has been assigned raises an exception. PHP by contrast implicitly creates a variable when it is read, with a null value. This means it is easy to do this in PHP: ``` function mymodule_important_calculation() { $result = /* ... long and complex calculation ... */; return $resukt; } ``` This function always returns null, and if null is a valid value for the functuion then the bug might go undetected for some time. The Python equivalent would complain that the variable `resukt` is being used before it is assigned. So... is there a way to configure PHP to be stricter with variable assignments?
**PHP** doesn't do much forward checking of things at parse time. The best you can do is crank up the warning level to report your mistakes, but by the time you get an E\_NOTICE, its too late, and its not possible to force E\_NOTICES to occur in advance yet. A lot of people are toting the "error\_reporting E\_STRICT" flag, but its still retroactive warning, and won't protect you from bad code mistakes like you posted. This gem turned up on the php-dev mailing-list this week and I think its just the tool you want. Its more a lint-checker, but it adds scope to the current lint checking PHP does. [**PHP-Initialized Google Project**](http://code.google.com/p/php-initialized/wiki/Features) There's the hope that with a bit of attention we can get this behaviour implemented in PHP itself. So put your 2-cents on the PHP mailing list / bug system / feature requests and see if we can encourage its integration.
91,715
<p>I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char *'s, and there is no provision for STL lists.</p> <p>What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as:</p> <pre><code>char **registeredNames = new char*[numberOfNames]; </code></pre> <p>Then,</p> <pre><code>RegisterName(const * char const name, const int length) { //loop to see if name already registered snipped if(notFound) { registeredNames[lastIndex++] = name; } } </code></pre> <p>or, if it was C#...</p> <pre><code>if(!registeredNames.Contains(name)) { registeredNames.Add(name); } </code></pre> <p>and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!</p>
[ { "answer_id": 91749, "author": "Maximilian", "author_id": 1733, "author_profile": "https://Stackoverflow.com/users/1733", "pm_score": 1, "selected": false, "text": "<p>Edit: I guess I misunderstood your question. There is no constness problem in this code I'm aware of.</p>\n\n<p>I'm doi...
2008/09/18
[ "https://Stackoverflow.com/questions/91715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15667/" ]
I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char \*'s, and there is no provision for STL lists. What I'm currently trying to do is to create a list of strings, something which would take me no time at all using STL or in C#. Basically I want to have a function such as: ``` char **registeredNames = new char*[numberOfNames]; ``` Then, ``` RegisterName(const * char const name, const int length) { //loop to see if name already registered snipped if(notFound) { registeredNames[lastIndex++] = name; } } ``` or, if it was C#... ``` if(!registeredNames.Contains(name)) { registeredNames.Add(name); } ``` and I realize that it doesn't work. I know the const nature of the passed variables (a const pointer and a const string) makes it rather difficult, but my basic problem is that I've always avoided this situation in the past by using STL lists etc. so I've never had to work around it!
You'll probably need to use strcmp to see if the string is already stored: ``` for (int index=0; index<=lastIndex; index++) { if (strcmp(registeredNames[index], name) == 0) { return; // Already registered } } ``` Then if you really need to store a copy of the string, then you'll need to allocate a buffer and copy the characters over. ``` char* nameCopy = malloc(length+1); strcpy(nameCopy, name); registeredNames[lastIndex++] = nameCopy; ``` You didn't mention whether your input is NULL terminated - if not, then extra care is needed, and strcmp/strcpy won't be suitable.
91,734
<p>I'm a little blockheaded right now…</p> <p>I have a date string in european format <strong>dd.mm.yyyy</strong> and need to transform it to <strong>mm.dd.yyyy</strong> with classic ASP. Any quick ideas?</p>
[ { "answer_id": 91780, "author": "Anheledir", "author_id": 5703, "author_profile": "https://Stackoverflow.com/users/5703", "pm_score": 2, "selected": false, "text": "<p>OK, I just found a solution myself:</p>\n\n<pre><code>payment_date = MID(payment_date,4,3) &amp; LEFT(payment_date,3) &a...
2008/09/18
[ "https://Stackoverflow.com/questions/91734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5703/" ]
I'm a little blockheaded right now… I have a date string in european format **dd.mm.yyyy** and need to transform it to **mm.dd.yyyy** with classic ASP. Any quick ideas?
If its always in that format you could use split ``` d = split(".","dd.mm.yyyy") s = d(1) & "." & d(0) & "." & d(2) ``` this would allow for dates like 1.2.99 as well
91,745
<p>I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from.</p> <p>Is this possible?</p>
[ { "answer_id": 163247, "author": "WaterBoy", "author_id": 3270, "author_profile": "https://Stackoverflow.com/users/3270", "pm_score": 5, "selected": true, "text": "<p>Yes. This can be done using the DataGridViewComboBoxCell.</p>\n\n<p>Here is an example method to add the items to just on...
2008/09/18
[ "https://Stackoverflow.com/questions/91745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from. Is this possible?
Yes. This can be done using the DataGridViewComboBoxCell. Here is an example method to add the items to just one cell, rather than the whole column. ``` private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd) { DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex]; // You might pass a boolean to determine whether to clear or not. dgvcbc.Items.Clear(); foreach (object itemToAdd in itemsToAdd) { dgvcbc.Items.Add(itemToAdd); } } ```
91,747
<p>How can I set the background color of a specific item in a <em>System.Windows.Forms.ListBox</em>?</p> <p>I would like to be able to set multiple ones if possible.</p>
[ { "answer_id": 91758, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 7, "selected": true, "text": "<p>Probably the only way to accomplish that is to draw the items yourself.</p>\n<p>Set the <code>DrawMode</code> to <...
2008/09/18
[ "https://Stackoverflow.com/questions/91747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11137/" ]
How can I set the background color of a specific item in a *System.Windows.Forms.ListBox*? I would like to be able to set multiple ones if possible.
Probably the only way to accomplish that is to draw the items yourself. Set the `DrawMode` to `OwnerDrawFixed` and code something like this on the DrawItem event: ``` private void listBox_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Graphics g = e.Graphics; g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds); // Print text e.DrawFocusRectangle(); } ``` The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).
91,766
<p>I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)".</p> <p>I have tried </p> <pre><code>SortExpression="LEN(myField)" </code></pre> <p>but this throws an exception as it is not valid syntax. Any ideas?</p>
[ { "answer_id": 91788, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 3, "selected": true, "text": "<p>What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpress...
2008/09/18
[ "https://Stackoverflow.com/questions/91766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15393/" ]
I have a DataGrid where each column has a SortExpression. I would like the sort expression to be the equivalent of "ORDER BY LEN(myField)". I have tried ``` SortExpression="LEN(myField)" ``` but this throws an exception as it is not valid syntax. Any ideas?
What about returning the len by the query already, but don't show that column, only use it as your original column's sortexpression? I don't think that your idea is supported by default.
91,778
<p>To create a new event handler on a control you can do this</p> <pre><code>c.Click += new EventHandler(mainFormButton_Click); </code></pre> <p>or this</p> <pre><code>c.Click += mainFormButton_Click; </code></pre> <p>and to remove an event handler you can do this</p> <pre><code>c.Click -= mainFormButton_Click; </code></pre> <p>But how do you remove all event handlers from an event?</p>
[ { "answer_id": 91803, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "<p>From <em><a href=\"http://bytes.com/forum/thread274921.html\" rel=\"noreferrer\">Removing All Event Handlers</a></e...
2008/09/18
[ "https://Stackoverflow.com/questions/91778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7297/" ]
To create a new event handler on a control you can do this ``` c.Click += new EventHandler(mainFormButton_Click); ``` or this ``` c.Click += mainFormButton_Click; ``` and to remove an event handler you can do this ``` c.Click -= mainFormButton_Click; ``` But how do you remove all event handlers from an event?
I found a solution on the [MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/). The sample code below will remove all `Click` events from `button1`. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; button1.Click += button1_Click2; button2.Click += button2_Click; } private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello"); private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World"); private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1); private void RemoveClickEvent(Button b) { FieldInfo f1 = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic); object obj = f1.GetValue(b); PropertyInfo pi = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList list = (EventHandlerList)pi.GetValue(b, null); list.RemoveHandler(obj, list[obj]); } } ```
91,784
<p>I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?</p>
[ { "answer_id": 91792, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": false, "text": "<p>Add an identity column to act as a surrogate primary key, and use this to identify two of the three rows to be deleted....
2008/09/18
[ "https://Stackoverflow.com/questions/91784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?
I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. **EDIT:** now with code snippet! ``` INSERT INTO TABLE_2 SELECT DISTINCT * FROM TABLE_1 GO DELETE FROM TABLE_1 GO INSERT INTO TABLE_1 SELECT * FROM TABLE_2 GO ```
91,800
<p>I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns:</p> <pre><code>SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC </code></pre> <p>However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author.</p> <p>I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this?</p> <p><strong>Edit</strong>: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server.</p> <p>I tried to catch the query with SQL Profiler, but to no avail.</p> <p><strong>Edit 2</strong>: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.</p>
[ { "answer_id": 93524, "author": "Adam Hawkes", "author_id": 6703, "author_profile": "https://Stackoverflow.com/users/6703", "pm_score": 0, "selected": false, "text": "<p>I have no experience in SharePoint, but if it is the case where only one ORDER BY clause is being honored I would chan...
2008/09/18
[ "https://Stackoverflow.com/questions/91800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15682/" ]
I'm using a FullTextSqlQuery in SharePoint 2007 (MOSS) and need to order the results by two columns: ``` SELECT WorkId FROM SCOPE() ORDER BY Author ASC, Rank DESC ``` However it seems that only the first column from ORDER BY is taken into account when returning results. In this case the results are ordered correctly by Author, but not by Rank. If I change the order the results will be ordered by Rank, but not by Author. I had to resort to my own sorting of the results, which I don't like very much. Has anybody a solution to this? **Edit**: Unfortunately it also doesn't accept expressions in the ORDER BY clause (SharePoint throws an exception). My guess is that even if the query looks like legitimate SQL it is parsed somehow before being served to the SQL server. I tried to catch the query with SQL Profiler, but to no avail. **Edit 2**: In the end I used ordering by a single column (Author in my case, since it's the most important) and did the second ordering in code on the TOP N of the results. Works good enough for the project, but leaves a bad feeling of kludgy code.
Microsoft *finally* posted a knowledge base article about this issue. "When using RANK in the ORDER BY clause of a SharePoint Search query, no other properties should be used" <http://support.microsoft.com/kb/970830> Symptom: When using RANK in the ORDER BY clause of a SharePoint Search query only the first ORDER BY column is used in the results. Cause: RANK is a special property that is ranked in the full text index and hence cannot be used with other managed properties. Resolution: Do not use multiple properties in conjunction with the RANK property.
91,810
<p>Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.</p> <p>Is there something that will take any python object and display it in a more rational manner. e.g.</p> <pre><code>[0, 1, [a, b, c], 2, 3, 4] </code></pre> <p>instead of:</p> <pre><code>[0, 1, [a, b, c], 2, 3, 4] </code></pre> <p>I know that's not a very good example, but I think you get the idea.</p>
[ { "answer_id": 91818, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<pre><code>from pprint import pprint\na = [0, 1, ['a', 'b', 'c'], 2, 3, 4]\npprint(a)\n</code></pre>\n\n<p>Note that for a ...
2008/09/18
[ "https://Stackoverflow.com/questions/91810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there something that will take any python object and display it in a more rational manner. e.g. ``` [0, 1, [a, b, c], 2, 3, 4] ``` instead of: ``` [0, 1, [a, b, c], 2, 3, 4] ``` I know that's not a very good example, but I think you get the idea.
``` from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) ``` Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
91,817
<p>I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:</p> <pre><code>public ArrayList @params { get { return this.paramsField; } set { this.paramsField = value; } } </code></pre> <p>I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?</p>
[ { "answer_id": 91822, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 6, "selected": false, "text": "<p>It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).</p>\n" }...
2008/09/18
[ "https://Stackoverflow.com/questions/91817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13287/" ]
I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this: ``` public ArrayList @params { get { return this.paramsField; } set { this.paramsField = value; } } ``` I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '@' character in a variable/property name?
Straight from the [C# Language Specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/), [Identifiers (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers) : > > The prefix "@" enables the use of > keywords as identifiers, which is > useful when interfacing with other > programming languages. The character @ > is not actually part of the > identifier, so the identifier might be > seen in other languages as a normal > identifier, without the prefix. An > identifier with an @ prefix is called > a verbatim identifier. > > >
91,821
<p>I have a model class:</p> <pre><code>class Person(db.Model): first_name = db.StringProperty(required=True) last_name = db.StringProperty(required=True) </code></pre> <p>I have an instance of this class in <code>p</code>, and string <code>s</code> contains the value <code>'first_name'</code>. I would like to do something like:</p> <pre><code>print p[s] </code></pre> <p>and </p> <pre><code>p[s] = new_value </code></pre> <p>Both of which result in a <code>TypeError</code>.</p> <p>Does anybody know how I can achieve what I would like?</p>
[ { "answer_id": 91859, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n" }, { "answer_id": 91911, "author": "Jim", "a...
2008/09/18
[ "https://Stackoverflow.com/questions/91821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154/" ]
I have a model class: ``` class Person(db.Model): first_name = db.StringProperty(required=True) last_name = db.StringProperty(required=True) ``` I have an instance of this class in `p`, and string `s` contains the value `'first_name'`. I would like to do something like: ``` print p[s] ``` and ``` p[s] = new_value ``` Both of which result in a `TypeError`. Does anybody know how I can achieve what I would like?
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this. Try: ``` getattr(p, s) setattr(p, s, new_value) ``` There is also hasattr available.
91,826
<p>Is there a version of FitNesse that works on Delphi 2006/2007/2009?</p> <p>If so where can I find It?</p> <p>Are there any other programs like FitNesse that work on Delphi 2006?</p>
[ { "answer_id": 91859, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<pre><code>getattr(p, s)\nsetattr(p, s, new_value)\n</code></pre>\n" }, { "answer_id": 91911, "author": "Jim", "a...
2008/09/18
[ "https://Stackoverflow.com/questions/91826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
Is there a version of FitNesse that works on Delphi 2006/2007/2009? If so where can I find It? Are there any other programs like FitNesse that work on Delphi 2006?
If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this. Try: ``` getattr(p, s) setattr(p, s, new_value) ``` There is also hasattr available.
91,831
<p>Say I have the following web.config:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;authentication mode="Windows"&gt;&lt;/authentication&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?</p>
[ { "answer_id": 91836, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 3, "selected": true, "text": "<p>Try <code>Context.User.Identity.AuthenticationType</code></p>\n\n<p>Go for PB's answer folks</p>\n" }, { "answer_...
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
91,856
<p>Would the following SQL remove also the index - or does it have to be removed separately?</p> <pre><code>CREATE TABLE #Tbl (field int) CREATE NONCLUSTERED INDEX idx ON #Tbl (field) DROP TABLE #Tbl </code></pre>
[ { "answer_id": 91863, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 3, "selected": false, "text": "<p>It will be removed automatically, as there is nothing left to index. Think of it as a child object in this respect....
2008/09/18
[ "https://Stackoverflow.com/questions/91856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
Would the following SQL remove also the index - or does it have to be removed separately? ``` CREATE TABLE #Tbl (field int) CREATE NONCLUSTERED INDEX idx ON #Tbl (field) DROP TABLE #Tbl ```
Yes they are. You can search in MSSQL help for CREATE INDEX article it is said there: > > "Indexes can be created on a temporary > table. When the table is dropped or > the session ends, all indexes and > triggers are dropped." > > >
91,899
<p>I'm using grep to generate a list of files I need to move:</p> <pre><code>grep -L -r 'Subject: \[SPAM\]' . </code></pre> <p>How can I pass this list to the mv command and move the files somewhere else?</p>
[ { "answer_id": 91901, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": -1, "selected": false, "text": "<p>You can pass the result to the next command by using\ngrep ... | xargs mv {} destination</p>\n\n<p>Check man xargs fo...
2008/09/18
[ "https://Stackoverflow.com/questions/91899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17582/" ]
I'm using grep to generate a list of files I need to move: ``` grep -L -r 'Subject: \[SPAM\]' . ``` How can I pass this list to the mv command and move the files somewhere else?
If you want to find and move files that do not match your pattern (move files that don't contain `'Subject \[SPAM\]'` in this example) use: ``` grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR ``` The -Z means output with zeros (\0) after the filenames (so spaces are not used as delimeters). ``` xargs -0 ``` means interpret \0 to be delimiters. The -L means find files that do not match the pattern. Replace `-L` with `-l` if you want to move files that match your pattern. Then ``` -I{} mv {} DIR ``` means replace `{}` with the filenames, so you get `mv filenames DIR`.
91,905
<p>I want to add a mailto link on our web page. I want to add a urgent priority to this mail.</p>
[ { "answer_id": 91921, "author": "Robit", "author_id": 17026, "author_profile": "https://Stackoverflow.com/users/17026", "pm_score": 4, "selected": true, "text": "<p>mailto links just doesn't support this feature , sorry.</p>\n\n<p>however, you could use a specific subject and filter it i...
2008/09/18
[ "https://Stackoverflow.com/questions/91905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17584/" ]
I want to add a mailto link on our web page. I want to add a urgent priority to this mail.
mailto links just doesn't support this feature , sorry. however, you could use a specific subject and filter it in your inbox ``` <a href="mailto:webmaster@website.com?subject=Urgent">Send a email</a> ```
91,932
<p>How does it work, what is it used for and when should one use it?</p>
[ { "answer_id": 91961, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>Directly from the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy P...
2008/09/18
[ "https://Stackoverflow.com/questions/91932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695/" ]
How does it work, what is it used for and when should one use it?
Let's explain the strategy pattern the easy way: You have a class `Car()` with a method `run()`, so you use it this way in a pseudo language: ``` mycar = new Car() mycar.run() ``` Now, you may want to change the `run()` behavior on the fly, while the program is executing. For example, you might want to simulate a motor failure or the use of a "boost" button in a video game. There are several ways to do this simulation: using conditional statements and a flag variable is one way. The strategy pattern is another: it delegates the behavior of the `run()` method to another class: ``` Class Car() { this.motor = new Motor(this) // passing "this" is important for the motor so it knows what it is running method run() { this.motor.run() } method changeMotor(motor) { this.motor = motor } } ``` If you want to change the car's behavior, you can just change the motor. (Easier in a program than in real life, right? ;-) ) It's very useful if you have a lot of complex states: you can change and maintain them much more easily.
91,933
<p>I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a</p> <pre><code>List&lt;int&gt; </code></pre> <p>and </p> <pre><code>Dictionary&lt;int, bool&gt; </code></pre> <p>With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.</p>
[ { "answer_id": 91951, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "<p>They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than s...
2008/09/18
[ "https://Stackoverflow.com/questions/91933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ]
I've been working on a project where I need to iterate through a collection of data and remove entries where the "primary key" is duplicated. I have tried using a ``` List<int> ``` and ``` Dictionary<int, bool> ``` With the dictionary I found slightly better performance, even though I never need the Boolean tagged with each entry. My expectation is that this is because a List allows for indexed access and a Dictionary does not. What I was wondering is, is there a better solution to this problem. I do not need to access the entries again, I only need to track what "primary keys" I have seen and make sure I only perform addition work on entries that have a new primary key. I'm using C# and .NET 2.0. And I have no control over fixing the input data to remove the duplicates from the source (unfortunately!). And so you can have a feel for scaling, overall I'm checking for duplicates about 1,000,000 times in the application, but in subsets of no more than about 64,000 that need to be unique.
They have added the HashSet class in .NET 3.5. But I guess it will be on par with the Dictionary. If you have less than say a 100 elements a List will probably perform better.
91,957
<p>How do I use groovy to search+replace in XML?</p> <p>I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting.</p> <p>More specifically, how do I turn:</p> <pre><code>&lt;root&gt;&lt;data&gt;&lt;/data&gt;&lt;/root&gt; </code></pre> <p>into:</p> <pre><code>&lt;root&gt;&lt;data&gt;value&lt;/data&gt;&lt;/root&gt; </code></pre>
[ { "answer_id": 91976, "author": "Bob Dizzle", "author_id": 9581, "author_profile": "https://Stackoverflow.com/users/9581", "pm_score": -1, "selected": false, "text": "<p>check this:\n<a href=\"http://today.java.net/pub/a/today/2004/08/12/groovyxml.html?page=2\" rel=\"nofollow noreferrer\...
2008/09/18
[ "https://Stackoverflow.com/questions/91957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17554/" ]
How do I use groovy to search+replace in XML? I need something as short/easy as possible, since I'll be giving this code to the testers for their SoapUI scripting. More specifically, how do I turn: ``` <root><data></data></root> ``` into: ``` <root><data>value</data></root> ```
Some of the stuff you can do with an XSLT you can also do with some form of 'search & replace'. It all depends on how complex your problem is and how 'generic' you want to implement the solution. To make your own example slightly more generic: ``` xml.replaceFirst("<Mobiltlf>[^<]*</Mobiltlf>", '<Mobiltlf>32165487</Mobiltlf>') ``` The solution you choose is up to you. In my own experience (for very simple problems) using simple string lookups is faster than using regular expressions which is again faster than using a fullblown XSLT transformation (makes sense actually).
91,981
<p>Is there a way to mock object construction using JMock in Java? </p> <p>For example, if I have a method as such:</p> <pre class="lang-java prettyprint-override"><code>public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } </code></pre> <p>...is there a way to mock out the expectation of the object construction in a test method? </p> <p>I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example).</p> <p>So instead of:</p> <pre class="lang-java prettyprint-override"><code>assertTrue(a.createObject() instanceof Integer); </code></pre> <p>I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way.</p> <p>Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it.</p> <hr> <p>For a bit more background:</p> <p>I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them.</p> <p>Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? </p> <p>So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? </p> <p>My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)</p>
[ { "answer_id": 92064, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "<p>I hope there is none. \nMocks are supposed to mock interfaces, which have no constructors... just methods. </p>\n\n<p>Somet...
2008/09/18
[ "https://Stackoverflow.com/questions/91981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: ```java public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ``` ...is there a way to mock out the expectation of the object construction in a test method? I'd like to be able to place expectations that certain constructors are being called, rather than having an extra bit of code to check the type (as it won't always be as convoluted and simple as my example). So instead of: ```java assertTrue(a.createObject() instanceof Integer); ``` I could have an expectation of the certain constructor being called. Just to make it a bit cleaner, and express what is actually being tested in a more readable way. Please excuse the simple example, the actual problem I'm working on is a bit more complicated, but having the expectation would simplify it. --- For a bit more background: I have a simple factory method, which creates wrapper objects. The objects being wrapped can require parameters which are difficult to obtain in a test class (it's pre-existing code), so it is difficult to construct them. Perhaps closer to what I'm actually looking for is: is there a way to mock an entire class (using CGLib) in one fell swoop, without specifying every method to stub out? So the mock is being wrapped in a constructor, so obviously methods can be called on it, is JMock capable of dynamically mocking out each method? My guess is no, as that would be pretty complicated. But knowing I'm barking up the wrong tree is valuable too :-)
The only thing I can think of is to have the create method on at factory object, which you would than mock. But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together.
91,986
<p>I've got the following SQL:</p> <pre><code>select * from transaction_log where stoptime like '%2008%' </code></pre> <p>How do I write this in LINQ to SQL syntax?</p>
[ { "answer_id": 92009, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 6, "selected": true, "text": "<p>If you want to use the literal method, it's like this:</p>\n\n<pre><code>var query = from l in transaction_log\n ...
2008/09/18
[ "https://Stackoverflow.com/questions/91986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got the following SQL: ``` select * from transaction_log where stoptime like '%2008%' ``` How do I write this in LINQ to SQL syntax?
If you want to use the literal method, it's like this: ``` var query = from l in transaction_log where SqlMethods.Like(l.stoptime, "%2008%") select l; ``` Another option is: ``` var query = from l in transaction_log where l.stoptime.Contains("2008") select l; ``` If it's a DateTime: ``` var query = from l in transaction_log where l.stoptime.Year = 2008 select l; ``` That method is in the **System.Data.Linq.SqlClient** namespace
91,994
<p>This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.:</p> <pre><code>if (0 == someVariable) </code></pre> <p>As opposed to what I normally see/write:</p> <pre><code>if (someVariable == 0) </code></pre> <p>To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?</p>
[ { "answer_id": 91997, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 2, "selected": false, "text": "<p>Order does not matter, however, the former implies that it\ns the zero you're checking. Convention dictates the u...
2008/09/18
[ "https://Stackoverflow.com/questions/91994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9324/" ]
This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.: ``` if (0 == someVariable) ``` As opposed to what I normally see/write: ``` if (someVariable == 0) ``` To me, the second method seems more readable and intuitive, so I'm wondering if there's some reason I'm seeing the first method? Logically, both statements evaluate to the same result, so is it just a matter of personal preference how they're written?
I understand that this is personal preference. Although by putting the variable second you can ensure that you don't accidentally assign the constant to the variable which used to concearn c developers. This is probably why you are seeing it in c# as developers switch language.
92,008
<p>How do I programmatically set the record pointer in a C# DataGridView? </p> <p>I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.</p>
[ { "answer_id": 92105, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": true, "text": "<p>To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-...
2008/09/18
[ "https://Stackoverflow.com/questions/92008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148/" ]
How do I programmatically set the record pointer in a C# DataGridView? I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work. All it does is highlight that row within the grid; it doesn not move the record pointer to that row.
To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-disabled, non-header cell on the row that you have selected. You'd do this like: ``` dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow]; ``` Making sure that the cell matches the above criteria. Further information can be found at: <http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx>
92,027
<p>For a registration form I have something simple like:</p> <pre><code> &lt;tr:panelLabelAndMessage label="Zip/City" showRequired="true"&gt; &lt;tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /&gt; &lt;tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /&gt; &lt;/tr:panelLabelAndMessage&gt; &lt;tr:message for="zip" /&gt; &lt;tr:message for="city" /&gt; </code></pre> <p>When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. </p> <p>Is there a solution to show only one validation failed message somehow?</p> <p>Thanks a lot!</p>
[ { "answer_id": 107817, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I know this won't be ideal, but if you remove the <code>panelLabelAndMessage</code> tag and just use the label attribute on...
2008/09/18
[ "https://Stackoverflow.com/questions/92027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11705/" ]
For a registration form I have something simple like: ``` <tr:panelLabelAndMessage label="Zip/City" showRequired="true"> <tr:inputText id="zip" value="#{data['registration'].zipCode}" contentStyle="width:36px" simple="true" required="true" /> <tr:inputText id="city" value="#{data['registration'].city}" contentStyle="width:133px" simple="true" required="true" /> </tr:panelLabelAndMessage> <tr:message for="zip" /> <tr:message for="city" /> ``` When including the last two lines, I get two messages on validation error. When ommiting last to lines, a javascript alert shows up, which is not what I want. Is there a solution to show only one validation failed message somehow? Thanks a lot!
Problem is, the fields must layout horizontally. It's a no-go to put ZIP field and city not next to each other in one line. At least for me. A co-worker has pointed me to set a faclets variable inside the first tr:message and to put a rendered attribute at the second one that reacts on this variable. Havn't got the time to try nor found the right command for setting a varable yet. Will post results as soon as possible.
92,035
<p>I have a datagridview with a DataGridViewComboboxColumn column with 3 values:</p> <p>"Small", "Medium", "Large"</p> <p>I get back the users default which in this case is "Medium"</p> <p>I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.</p>
[ { "answer_id": 92186, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Are you retrieving the user data and attempting to set values in the DataGridView manually, or have you actually bound the D...
2008/09/18
[ "https://Stackoverflow.com/questions/92035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I have a datagridview with a DataGridViewComboboxColumn column with 3 values: "Small", "Medium", "Large" I get back the users default which in this case is "Medium" I want to show a dropdown cell in the datagridview but default the value to "Medium". i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.
When you get into the datagridview it is probably best to get into databinding. This will take care of all of the selected index stuff you are talking about. However, if you want to get in there by yourself, ``` DataGridView.Rows[rowindex].Cells[columnindex].Value ``` will let you get and set the value associated to the DataGridViewComboBoxColumn. Just make sure you supply the correct rowindex and columnindex along with setting the value to the correct type (the same type as the ValueMember property of the DataGridViewComboBoxColumn).
92,043
<p>I've tried the tools listed <a href="http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL" rel="noreferrer">here</a>, some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)</p>
[ { "answer_id": 92077, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"http://pgfoundry.org/\" rel=\"nofollow noreferrer\">PG Foundry</a>, extra utilities for Pos...
2008/09/18
[ "https://Stackoverflow.com/questions/92043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
I've tried the tools listed [here](http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL), some with more success than others, but none gave me valid postgres syntax I could use (tinyint errors etc.)
There's a `mysqldump` option which makes it output PostgreSQL code: ``` mysqldump --compatible=postgresql ... ``` But that doesn't work too well. Instead, please see the [mysql-to-postgres](https://github.com/maxlapshin/mysql2postgres) tool as [described in Linus Oleander's answer](https://stackoverflow.com/a/15670452/19163).
92,076
<p>I'm writing some xlst file which I want to use under linux and Windows. In this file I use node-set function which declared in different namespaces for MSXML and xsltproc ("urn:schemas-microsoft-com:xslt" and "<a href="http://exslt.org/common" rel="nofollow noreferrer">http://exslt.org/common</a>" respectively). Is there any platform independent way of using node-set?</p>
[ { "answer_id": 92119, "author": "Ben", "author_id": 15480, "author_profile": "https://Stackoverflow.com/users/15480", "pm_score": 1, "selected": false, "text": "<p>Firefox 3 implements node-set (as part of the EXSLT 2.0 namespace improvements) in it's client-side XSLT processing.</p>\n\n...
2008/09/18
[ "https://Stackoverflow.com/questions/92076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17569/" ]
I'm writing some xlst file which I want to use under linux and Windows. In this file I use node-set function which declared in different namespaces for MSXML and xsltproc ("urn:schemas-microsoft-com:xslt" and "<http://exslt.org/common>" respectively). Is there any platform independent way of using node-set?
You can use the function function-available() to determine which function you should use: ``` <xsl:choose> <xsl:when test="function-available('exslt:node-set')"> <xsl:apply-templates select="exslt:node-set($nodelist)" /> </xsl:when> <xsl:when test="function-available('msxsl:node-set')"> <xsl:apply-templates select="msxsl:node-set($nodelist)" /> </xsl:when> <!-- etc --> </xsl:choose> ``` You can even wrap this logic in a named template and call it with the nodeset as a parameter.
92,082
<p>How can I add a column with a default value to an existing table in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> / <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">SQL Server 2005</a>?</p>
[ { "answer_id": 92092, "author": "Benjamin Autin", "author_id": 1440933, "author_profile": "https://Stackoverflow.com/users/1440933", "pm_score": 6, "selected": false, "text": "<pre><code>ALTER TABLE ADD ColumnName {Column_Type} Constraint\n</code></pre>\n\n<p>The MSDN article <em><a href...
2008/09/18
[ "https://Stackoverflow.com/questions/92082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7241/" ]
How can I add a column with a default value to an existing table in [SQL Server 2000](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis) / [SQL Server 2005](http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005)?
Syntax: ------- ``` ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} WITH VALUES ``` Example: -------- ``` ALTER TABLE SomeTable ADD SomeCol Bit NULL --Or NOT NULL. CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated. DEFAULT (0)--Optional Default-Constraint. WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. ``` Notes: ------ **Optional Constraint Name:** If you leave out `CONSTRAINT D_SomeTable_SomeCol` then SQL Server will autogenerate     a Default-Contraint with a funny Name like: `DF__SomeTa__SomeC__4FB7FEF6` **Optional With-Values Statement:** The `WITH VALUES` is only needed when your Column is Nullable     and you want the Default Value used for Existing Records. If your Column is `NOT NULL`, then it will automatically use the Default Value     for all Existing Records, whether you specify `WITH VALUES` or not. **How Inserts work with a Default-Constraint:** If you insert a Record into `SomeTable` and do ***not*** Specify `SomeCol`'s value, then it will Default to `0`. If you insert a Record ***and*** Specify `SomeCol`'s value as `NULL` (and your column allows nulls),     then the Default-Constraint will ***not*** be used and `NULL` will be inserted as the Value. Notes were based on everyone's great feedback below. Special Thanks to:     @Yatrix, @WalterStabosz, @YahooSerious, and @StackMan for their Comments.
92,093
<p>I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple <code>VARCHAR(10)</code> field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.</p> <p>Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an <code>RTRIM</code> function, but this seems only to remove spaces. </p>
[ { "answer_id": 92363, "author": "Ian Horwill", "author_id": 5816, "author_profile": "https://Stackoverflow.com/users/5816", "pm_score": 8, "selected": true, "text": "<pre><code>select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)\n</code></pre>\n" }, { "answer_id": 450...
2008/09/18
[ "https://Stackoverflow.com/questions/92093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple `VARCHAR(10)` field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'. Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an `RTRIM` function, but this seems only to remove spaces.
``` select substring(ColumnName, patindex('%[^0]%',ColumnName), 10) ```
92,100
<p>Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.</p>
[ { "answer_id": 92205, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "<p>XAML is for constructing object graphs not containing code.<br>\nA Data template is used to indicate how a custom user-obje...
2008/09/18
[ "https://Stackoverflow.com/questions/92100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204/" ]
Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button click is done in the code file behind the control. If I was to create a data template with a button how can I write the event handler code for it's button click within the resource dictionary.
I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window: Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyCompany.MyProject.MyResourceDictionary" x:ClassModifier="public"> ``` Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration: ``` namespace MyCompany.MyProject { partial class MyResourceDictionary : ResourceDictionary { public MyResourceDictionary() { InitializeComponent(); } ... // event handlers ahead.. } } ``` And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers. **== Update for Windows 10 apps ==** And just in case you are playing with **UWP** there is one more thing to be aware of: ``` <Application x:Class="SampleProject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:rd="using:MyCompany.MyProject"> <!-- no need in x:ClassModifier="public" in the header above --> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- This will NOT work --> <!-- <ResourceDictionary Source="/MyResourceDictionary.xaml" />--> <!-- Create instance of your custom dictionary instead of the above source reference --> <rd:MyResourceDictionary /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> ```
92,103
<p>What do you find is the optimal setting for mysql slow query log parameter, and why?</p>
[ { "answer_id": 92140, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 2, "selected": false, "text": "<p>Whatever time /you/ feel is unacceptably slow for a query on your systems.</p>\n\n<p>It depends on the kind of quer...
2008/09/18
[ "https://Stackoverflow.com/questions/92103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
What do you find is the optimal setting for mysql slow query log parameter, and why?
I recommend these three lines ``` log_slow_queries set-variable = long_query_time=1 log-queries-not-using-indexes ``` The first and second will log any query over a second. As others have pointed out a one second query is pretty far gone if you are a shooting for a high transaction rate on your website, but I find that it turns up some real WTFs; queries that *should* be fast, but for whatever combination of data it was run against was not. The last will log any query that does not use an index. Unless your doing data warehousing any common query should have the best index you can find so pay attention to its output. Although its certainly not for production, this last option ``` log = /var/log/mysql/mysql.log ``` will log all queries, which can be useful if you are trying to tune a specific page or action.
92,114
<p>There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class.</p> <p>Here is the error that you get:</p> <blockquote> <p>Cannot copy [filename]: Insufficient system resources exist to complete the requested service.</p> </blockquote> <p>The is a <a href="http://support.microsoft.com/default.aspx/kb/259837" rel="noreferrer">knowledge base article</a> on the subject, but it pertains to NT4 and 2000.</p> <p>There is also a suggestion to <a href="http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx" rel="noreferrer">use ESEUTIL</a> from an Exchange installation, but I haven't had any luck getting that to work.</p> <p>Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested.</p> <p><strong>[Edit]</strong> I provided working C# code to accompany the accepted answer.</p>
[ { "answer_id": 92165, "author": "jabial", "author_id": 16995, "author_profile": "https://Stackoverflow.com/users/16995", "pm_score": 5, "selected": true, "text": "<p>The best option is to just open the original file for reading, the destination file for writing and then loop copying it b...
2008/09/18
[ "https://Stackoverflow.com/questions/92114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
There is a limitation on Windows Server 2003 that prevents you from copying extremely large files, in proportion to the amount of RAM you have. The limitation is in the CopyFile and CopyFileEx functions, which are used by xcopy, Explorer, Robocopy, and the .NET FileInfo class. Here is the error that you get: > > Cannot copy [filename]: Insufficient system resources exist to complete the requested service. > > > The is a [knowledge base article](http://support.microsoft.com/default.aspx/kb/259837) on the subject, but it pertains to NT4 and 2000. There is also a suggestion to [use ESEUTIL](http://blogs.technet.com/askperf/archive/2007/05/08/slow-large-file-copy-issues.aspx) from an Exchange installation, but I haven't had any luck getting that to work. Does anybody know of a quick, easy way to handle this? I'm talking about >50Gb on a machine with 2Gb of RAM. I plan to fire up Visual Studio and just write something to do it for me, but it would be nice to have something that was already out there, stable and well-tested. **[Edit]** I provided working C# code to accompany the accepted answer.
The best option is to just open the original file for reading, the destination file for writing and then loop copying it block by block. In pseudocode : ``` f1 = open(filename1); f2 = open(filename2, "w"); while( !f1.eof() ) { buffer = f1.read(buffersize); err = f2.write(buffer, buffersize); if err != NO_ERROR_CODE break; } f1.close(); f2.close(); ``` **[Edit by Asker]** Ok, this is how it looks in C# (it's slow but it seems to work Ok, and it gives progress): ``` using System; using System.Collections.Generic; using System.IO; using System.Text; namespace LoopCopy { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine( "Usage: LoopCopy.exe SourceFile DestFile"); return; } string srcName = args[0]; string destName = args[1]; FileInfo sourceFile = new FileInfo(srcName); if (!sourceFile.Exists) { Console.WriteLine("Source file {0} does not exist", srcName); return; } long fileLen = sourceFile.Length; FileInfo destFile = new FileInfo(destName); if (destFile.Exists) { Console.WriteLine("Destination file {0} already exists", destName); return; } int buflen = 1024; byte[] buf = new byte[buflen]; long totalBytesRead = 0; double pctDone = 0; string msg = ""; int numReads = 0; Console.Write("Progress: "); using (FileStream sourceStream = new FileStream(srcName, FileMode.Open)) { using (FileStream destStream = new FileStream(destName, FileMode.CreateNew)) { while (true) { numReads++; int bytesRead = sourceStream.Read(buf, 0, buflen); if (bytesRead == 0) break; destStream.Write(buf, 0, bytesRead); totalBytesRead += bytesRead; if (numReads % 10 == 0) { for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } pctDone = (double) ((double)totalBytesRead / (double)fileLen); msg = string.Format("{0}%", (int)(pctDone * 100)); Console.Write(msg); } if (bytesRead < buflen) break; } } } for (int i = 0; i < msg.Length; i++) { Console.Write("\b \b"); } Console.WriteLine("100%"); Console.WriteLine("Done"); } } } ```
92,239
<p>If you have several <code>div</code>s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first <code>div</code> will show near the top of the page and the last <code>div</code> will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you?</p> <p>I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the <code>div</code>s in the same order!</p> <p>(P.S. I am sure no one uses <code>position:absolute</code> on every element on a page.)</p>
[ { "answer_id": 92264, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>You don't need position:absolute on every element to do what you want.</p>\n\n<p>You just use it on a few key items and...
2008/09/18
[ "https://Stackoverflow.com/questions/92239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11461/" ]
If you have several `div`s on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first `div` will show near the top of the page and the last `div` will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you? I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the `div`s in the same order! (P.S. I am sure no one uses `position:absolute` on every element on a page.)
With Floating, and with position absolute, you can pull some pretty good positioning magic to change some of the order of the page. For instance, with StackOverflow, if the markup was setup right, the title, and main body content could be the first 2 things in the markup, and then the navigation/search, and finally the right hand sidebar. This would be done by having a content container with a top margin big enough to hold the navigation and a right margin big enough to hold the sidebars. Then both could be absolutely positioned in place. The markup might look like: ```css h1 { position: absolute; top: 0; left: 0; } #content { margin-top: 100px; margin-right: 250px; } #nav { position: absolute; top: 0; left: 300px; } #side { position: absolute; right: 0; top: 100px; } ``` ```html <h1> Stack Overflow </h1> <div id="content"> <h2> Can Css truly blah blah? </h2> ... </div> <div id="nav"> <ul class="main"> <li>quiestions</li> ... </ul> .... </div> <div id="side"> <div class="box"> <h3> Sponsored By </h3> <h4> New Zelands fish market </h4> .... </div> </div> ``` The important thing here is that the markup has to be done with this kind of positioning magic in mind. Changing things so that the navbar is on the left and the sidebar below the nav be too hard.