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
271,938
<p>Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick.</p> <p>How do I install a debian package on the computer locally?</p>
[ { "answer_id": 271952, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": true, "text": "<p>Once you have the USB stick mounted:</p>\n\n<pre><code>dpkg --install /path/to/foo_VVV-RRR.deb\n</code></pre>\n\n<p>(where fooVVV-RRR.deb is the package's file name)</p>\n\n<p>You can find more commands at the <a href=\"http://www.debian.org/doc/FAQ/ch-pkgtools.en.html\" rel=\"nofollow noreferrer\">Debian GNU/Linux FAQ</a>.</p>\n\n<p>Side note: this is from the command line. I'm not sure how to get synaptic to do it.</p>\n" }, { "answer_id": 271989, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 2, "selected": false, "text": "<p>If you're not a command line fan, double-clicking on the .deb files in the file manager should launch a package installer. Has exactly the same effect as <code>dpkg -i</code> of course.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3713/" ]
Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick. How do I install a debian package on the computer locally?
Once you have the USB stick mounted: ``` dpkg --install /path/to/foo_VVV-RRR.deb ``` (where fooVVV-RRR.deb is the package's file name) You can find more commands at the [Debian GNU/Linux FAQ](http://www.debian.org/doc/FAQ/ch-pkgtools.en.html). Side note: this is from the command line. I'm not sure how to get synaptic to do it.
271,939
<p>This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first:</p> <pre><code>// Singleton class which contains data class MyData { static MyData* sMyData ; int mData1[1024]; int mData2[1024]; int mData3[1024]; MyData* getInstance() { // sMyData is created in the very beginning. return sMyData ; } void getValues(int idx, int&amp; data1,int&amp; data2,int&amp; data3) { data1 = mData1[idx]; data2 = mData2[idx]; data3 = mData3[idx]; } int* getData1() { return &amp;mData1[0]; } } class MyThread { void workerMethod() { MyData* md = MyData::getInstance(); int d1,d2,d3; md-&gt;getValue( 12, d1,d2,d3 ); int* data1 = md-&gt;getData1(); d1 = data1[34]; } } </code></pre> <p>Now as you see I have some getter methods (all read-only), MyData::getInstance(), MyData::getValue() and MyData::getData1(). The 1st question is how thread-safe these methods are ?</p> <p>Since they are often-called methods, protecting those methods with mutex is something I am trying to avoid. </p> <p>The 2nd question is: what is the suggested way of reading data from central sources in a multi-thread application, especially in worker methods.</p> <p>Thanks !</p> <p>Paul</p>
[ { "answer_id": 271958, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 4, "selected": true, "text": "<p>Provided that no other thread will try to write to the data in your singleton object, you don't need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program's initialization code sets up a singleton, which is then only read from by worker threads.</p>\n\n<p>However, if <em>any</em> thread <em>ever</em> writes to this data while others are reading from it, you must protect it in some way. If you have lots of readers and only the occasional writer, it is worth considering some sort of \"read-write\" lock, which allows multiple readers in the absence of any writers.</p>\n" }, { "answer_id": 271968, "author": "Clay", "author_id": 16429, "author_profile": "https://Stackoverflow.com/users/16429", "pm_score": 1, "selected": false, "text": "<p>Your methods are okay, but you have two major problems.</p>\n\n<p>First, MyData::getInstance() should be static and does not create an instance. In order to minimize mutex usage, you should check out the <a href=\"http://en.wikipedia.org/wiki/Double_checked_locking_pattern\" rel=\"nofollow noreferrer\" title=\"double checked lock\">double checked lock</a>.</p>\n\n<p>Second, thread safety is up to callers of the getter methods not the MyData class. If that is what you're looking for, then great. If not, then you are going to have to come up with some sort of access control in MyClass. Also, since your contained data type is just an basic type (int), chances are good that you'll never see any synchronization problems until after your code is in production.</p>\n" }, { "answer_id": 271969, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 2, "selected": false, "text": "<p>It is not possible to tell if this could is threadsafe. If the data is initialized during object creation and never changes than this will run correctly. If you are mutating the underlying data through other methods then the readers will have to perform some sort of synchronization against the writers, there is no way around that.</p>\n\n<p>Depending on exactly what you are doing you might be able to use something lighter weight than a mutex, such as atomic updates synchronize commands, or using reader-writer locks, but without knowing more about what you are doing it is impossible to tell.</p>\n" }, { "answer_id": 272318, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "<p>First go back and read this question to get a better version of singelton:<br>\n<a href=\"https://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c\">Can any one provide me a sample of Singleton in c++?</a></p>\n\n<p>Also note: Do <b>NOT</b> use a singleton as a glorified global variable.<br>\nIt just adds complexity to a bad design. Just use a global variable.</p>\n\n<p>As long as you are only reading from the singleton it is thread safe when being used.</p>\n\n<p>The only point that is not thread safe (not guaranteed by the language) is during creation. So technically you should add locks around the part that creates the instance to guarantee that singleton has been fully created before anybody can use it.</p>\n\n<p>Note: Do not be lured by the use of double checked locking to optimize your locking strategy. It can <b>NOT</b> be made to work correctly in C++. Read this <a href=\"http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf\" rel=\"nofollow noreferrer\">DDJ article</a>.</p>\n\n<p>If you can guarantee that the singleton is instantiated (probably the first call too getInstance()) within a single threaded environment (before any threads are created) then you can dispense with the need for locks during instantiation.</p>\n\n<p>If you alter your code so that other threads can write to the singleton then you need to think about locking and consistency. You only need locking if your writes are not atomic. If your write is just updating one integer it is already atomic no change required. If your code is not atomic:</p>\n\n<ul>\n<li>Writing multiple integers within a method</li>\n<li>Performing a read and then write</li>\n</ul>\n\n<p>Then you will need to lock the object until all writes are complete and consequently also have locks on the methods that have read access to stop them reading from the object while another method updates the object.</p>\n\n<p>Consequently this is another reason why member variables should only be accessed by member methods.</p>\n" }, { "answer_id": 272323, "author": "Sean Johnston", "author_id": 665917, "author_profile": "https://Stackoverflow.com/users/665917", "pm_score": 0, "selected": false, "text": "<p>For thread safety you need to look at the class as a whole. As written your class would not be thread safe. Whilst your getValues method is okay, the getData1 method has problems.</p>\n\n<p>You say they are (read-only) getter methods. However, neither are declared as const methods. The getData1 would not be valid as a const method as it returns a non const pointer. In addition, returning a pointer to private class data is bad as you are exposing your implementation.</p>\n\n<p>If this is a singleton class to hold some essentially static data set on initialistion before your threading kicks off then all your accessors should be const methods. The getInstance should also return a const pointer to the class (and be a static method as mentioned by another answer).</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23000/" ]
This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first: ``` // Singleton class which contains data class MyData { static MyData* sMyData ; int mData1[1024]; int mData2[1024]; int mData3[1024]; MyData* getInstance() { // sMyData is created in the very beginning. return sMyData ; } void getValues(int idx, int& data1,int& data2,int& data3) { data1 = mData1[idx]; data2 = mData2[idx]; data3 = mData3[idx]; } int* getData1() { return &mData1[0]; } } class MyThread { void workerMethod() { MyData* md = MyData::getInstance(); int d1,d2,d3; md->getValue( 12, d1,d2,d3 ); int* data1 = md->getData1(); d1 = data1[34]; } } ``` Now as you see I have some getter methods (all read-only), MyData::getInstance(), MyData::getValue() and MyData::getData1(). The 1st question is how thread-safe these methods are ? Since they are often-called methods, protecting those methods with mutex is something I am trying to avoid. The 2nd question is: what is the suggested way of reading data from central sources in a multi-thread application, especially in worker methods. Thanks ! Paul
Provided that no other thread will try to write to the data in your singleton object, you don't need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program's initialization code sets up a singleton, which is then only read from by worker threads. However, if *any* thread *ever* writes to this data while others are reading from it, you must protect it in some way. If you have lots of readers and only the occasional writer, it is worth considering some sort of "read-write" lock, which allows multiple readers in the absence of any writers.
271,944
<p>I have a scenario where users of my ASP.NET web application submit testimonials consisting of text info and images. The submit process has the following steps:</p> <ul> <li>First the user inputs the content and chooses a path to an image</li> <li>When he clicks preview, the info is once again shown so that he can confirm</li> <li>Once confirmed the info is persisted in the database</li> </ul> <p>The problem with this is that I don't want to store uploaded images in the DB before the user actually confirms. Instead I store them as temporary files and put them in DB only after final confirmation.</p> <p>Since I also want my application to run in medium trust, I have write permissions only to the application directory and nowhere outside. I even want to limit write permissions for the ASPNET / NETWORK SERVICE user to the ~/App_Data folder. The problem with my scenario is that once a temporary file is created in this folder, the application pool is recycled and I don't want that on every testimonial submit.</p> <p>How do you advise I keep these temp files instead? The pool is not restarted if I update a file - only on create or rename. But I don't think I can store whole images in a single file for all users. What do you think?</p> <p><b>UPDATE</b>: I should note that I'm using a third party control for upload. It gives me programmatic access to the binary stream of the file contents after upload, but I cannot keep this after a second postback (the first step and postback actually does the upload).</p>
[ { "answer_id": 271967, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>You can still use the normal <a href=\"https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx\" rel=\"nofollow noreferrer\">Path.GetTempFilename</a>() method to get a temporary file in ASP.NET scenarios.</p>\n\n<p>It should give you a temp file path that is writable by NETWORK_SERVICE but also lives in one of the actual Windows' temp folders, not your application folder.</p>\n\n<p>If your host configured his server correctly, that should works fine.</p>\n" }, { "answer_id": 271994, "author": "Seb Nilsson", "author_id": 2429, "author_profile": "https://Stackoverflow.com/users/2429", "pm_score": 4, "selected": true, "text": "<p>I would recommend <a href=\"http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx\" rel=\"noreferrer\">IsolatedStorage</a>. It's a kind of virtual folder.</p>\n\n<p>Here is an excerpt from <a href=\"http://www.codeproject.com/KB/dotnet/IsolatedStorage.aspx\" rel=\"noreferrer\">an example on CodeProject</a>:</p>\n\n<pre><code>IsolatedStorageFileStream stream = \n new IsolatedStorageFileStream(ISOLATED_FILE_NAME, \n FileMode.Create, isoStore);\n\nStreamWriter writer = new StreamWriter( stream );\nwriter.WriteLine( \"This is my first line in the isolated storage file.\" );\nwriter.WriteLine( \"This is second line.\" );\nwriter.Close();\n</code></pre>\n\n<p><strong>UPDATE</strong>: To clean up your file just do this:</p>\n\n<pre><code>string fileName = \"isolatestorage.txt\";\n\nIsolatedStorageFile storage = IsolatedStorageFile.GetStore(\n IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);\n\nstring[] files = storage.GetFileNames(fileName);\nforeach(string file in files) {\n if(file == fileName) {\n storage.DeleteFile(file);\n break;\n }\n}\n</code></pre>\n" }, { "answer_id": 272008, "author": "Slavo", "author_id": 1801, "author_profile": "https://Stackoverflow.com/users/1801", "pm_score": 0, "selected": false, "text": "<p>This is a reply to Leppie who commented on my question (to avoid the char limit)</p>\n\n<p>From: <a href=\"http://blogs.msdn.com/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx</a></p>\n\n<blockquote>\n <p>...sometimes your application pool inexplicably recycles for no obvious reason. This is usually a configuration issue or due to the fact that you're performing file system operations in the application directory.</p>\n</blockquote>\n\n<p>Are you sure it's not supposed to recycle?</p>\n" }, { "answer_id": 275563, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": "<p>The default web_mediumtrust.config file that Microsoft ships is notoriously impractical.</p>\n\n<p>Here is a snippet from the default web_mediumtrust.config file. By default, you cannot use System.IO to discover or write to the temp folder.</p>\n\n<pre><code> &lt;IPermission\n class=\"FileIOPermission\"\n version=\"1\"\n Read=\"$AppDir$\"\n Write=\"$AppDir$\"\n Append=\"$AppDir$\"\n PathDiscovery=\"$AppDir$\"\n /&gt;\n</code></pre>\n\n<p>Although I haven't experirement with Isolated Storage as mentioned by @Seb, it seems to be permitted by the default config file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801/" ]
I have a scenario where users of my ASP.NET web application submit testimonials consisting of text info and images. The submit process has the following steps: * First the user inputs the content and chooses a path to an image * When he clicks preview, the info is once again shown so that he can confirm * Once confirmed the info is persisted in the database The problem with this is that I don't want to store uploaded images in the DB before the user actually confirms. Instead I store them as temporary files and put them in DB only after final confirmation. Since I also want my application to run in medium trust, I have write permissions only to the application directory and nowhere outside. I even want to limit write permissions for the ASPNET / NETWORK SERVICE user to the ~/App\_Data folder. The problem with my scenario is that once a temporary file is created in this folder, the application pool is recycled and I don't want that on every testimonial submit. How do you advise I keep these temp files instead? The pool is not restarted if I update a file - only on create or rename. But I don't think I can store whole images in a single file for all users. What do you think? **UPDATE**: I should note that I'm using a third party control for upload. It gives me programmatic access to the binary stream of the file contents after upload, but I cannot keep this after a second postback (the first step and postback actually does the upload).
I would recommend [IsolatedStorage](http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx). It's a kind of virtual folder. Here is an excerpt from [an example on CodeProject](http://www.codeproject.com/KB/dotnet/IsolatedStorage.aspx): ``` IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ISOLATED_FILE_NAME, FileMode.Create, isoStore); StreamWriter writer = new StreamWriter( stream ); writer.WriteLine( "This is my first line in the isolated storage file." ); writer.WriteLine( "This is second line." ); writer.Close(); ``` **UPDATE**: To clean up your file just do this: ``` string fileName = "isolatestorage.txt"; IsolatedStorageFile storage = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); string[] files = storage.GetFileNames(fileName); foreach(string file in files) { if(file == fileName) { storage.DeleteFile(file); break; } } ```
271,953
<p>Got into a situation where in a schema i have a table, say table ACTION , while i got a synonym called ACTION as well which refers to another table to another schema.</p> <p>Now, when i run the query</p> <p>select * from ACTION</p> <p>it will select the records from the table, but not the synonym.</p> <p>Anyway for me to select from the synonym AND the table both together?</p> <p>Thanx</p>
[ { "answer_id": 271997, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 2, "selected": false, "text": "<p>Well, your underlying ACTION table should be renamed, let's say do LOCAL_ACTION.</p>\n\n<p>Let's pretend your ACTION synonym is on otheruser.LOCAL_ACTION table...</p>\n\n<p>Then you can redefine the ACTION synonym to be:</p>\n\n<pre><code>SELECT * from LOCAL_ACTION\nUNION\nSELECT * from otheruser.LOCAL_ACTION\n</code></pre>\n\n<p>Then in the end, select * from ACTION will give you a combined list of both tables.</p>\n" }, { "answer_id": 272051, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 3, "selected": false, "text": "<p>I don't think that your ACTION synonym resides in the same schema as your ACTION table, as that isn't allowed in Oracle. Most likely your ACTION synonym resides in other schema, perhaps it's a PUBLIC synonym. If that's the case you can use </p>\n\n<pre><code>select * from ACTION\nunion \nselect * from public.ACTION\n</code></pre>\n" }, { "answer_id": 277877, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>Tables and private synonyms do indeed share the same name space, so that is a public synonym: <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements008.htm#sthref723\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements008.htm#sthref723</a></p>\n\n<p>Be aware that UNION is an implicit distinct on the result set. Waht you need is UNION ALL.</p>\n\n<pre><code>select * from ACTION\nunion all\nselect * from public.ACTION\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Got into a situation where in a schema i have a table, say table ACTION , while i got a synonym called ACTION as well which refers to another table to another schema. Now, when i run the query select \* from ACTION it will select the records from the table, but not the synonym. Anyway for me to select from the synonym AND the table both together? Thanx
I don't think that your ACTION synonym resides in the same schema as your ACTION table, as that isn't allowed in Oracle. Most likely your ACTION synonym resides in other schema, perhaps it's a PUBLIC synonym. If that's the case you can use ``` select * from ACTION union select * from public.ACTION ```
271,966
<p>There are no builtin matrix functions in C#, but there are in the F# powerpack.</p> <p>Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#. </p> <p>Wondered if anybody has already thought of this, or tried it, and whether it's a good idea.</p> <p>Should I expose it as a class, or a load of static functions?</p> <p>Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output?</p> <p>Any thoughts?</p> <p>Answer thanks to <a href="https://stackoverflow.com/questions/271966/about-using-f-to-create-a-matrix-assembly-usable-from-c#272250">Hath</a> below: you can use the F# library directly in C# (operators as well!):</p> <pre><code>using System; using System.Text; using Microsoft.FSharp.Math; namespace CSharp { class Program { static void Main(string[] args) { double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } }; double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } }; Matrix&lt;double&gt; m1 = MatrixModule.of_array2(x); Matrix&lt;double&gt; m2 = MatrixModule.of_array2(y); var mp = m1 * m2; var output = mp.ToArray2(); Console.WriteLine(output.StringIt()); Console.ReadKey(); } } public static class Extensions { public static string StringIt(this double[,] array) { var sb = new StringBuilder(); for (int r = 0; r &lt; array.Length / array.Rank; r++) { for (int c = 0; c &lt; array.Rank; c++) { if (c &gt; 0) sb.Append("\t"); sb.Append(array[r, c].ToString()); } sb.AppendLine(); } return sb.ToString(); } } } </code></pre>
[ { "answer_id": 272067, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 0, "selected": false, "text": "<p>There are very good Matrix classes in the XNA Framework. I'd either reference that dll, or most likely use reflector and copy and paste the code into my own solution. I know it doesn't answer your question directly, but just another idea....</p>\n" }, { "answer_id": 272250, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 4, "selected": true, "text": "<p>can you not just reference the f# library you need in c# and use it directly?</p>\n\n<p>I've done a similar thing to reference the FSharp.Core.dll to get at the </p>\n\n<pre><code>Microsoft.FSharp.Math.BigInt class.\n</code></pre>\n\n<p>So you can probably just reference the FSharp.PowerPack.dll to get at the </p>\n\n<pre><code>Microsoft.FSharp.Math.Matrix&lt;A&gt; class\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
There are no builtin matrix functions in C#, but there are in the F# powerpack. Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#. Wondered if anybody has already thought of this, or tried it, and whether it's a good idea. Should I expose it as a class, or a load of static functions? Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output? Any thoughts? Answer thanks to [Hath](https://stackoverflow.com/questions/271966/about-using-f-to-create-a-matrix-assembly-usable-from-c#272250) below: you can use the F# library directly in C# (operators as well!): ``` using System; using System.Text; using Microsoft.FSharp.Math; namespace CSharp { class Program { static void Main(string[] args) { double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } }; double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } }; Matrix<double> m1 = MatrixModule.of_array2(x); Matrix<double> m2 = MatrixModule.of_array2(y); var mp = m1 * m2; var output = mp.ToArray2(); Console.WriteLine(output.StringIt()); Console.ReadKey(); } } public static class Extensions { public static string StringIt(this double[,] array) { var sb = new StringBuilder(); for (int r = 0; r < array.Length / array.Rank; r++) { for (int c = 0; c < array.Rank; c++) { if (c > 0) sb.Append("\t"); sb.Append(array[r, c].ToString()); } sb.AppendLine(); } return sb.ToString(); } } } ```
can you not just reference the f# library you need in c# and use it directly? I've done a similar thing to reference the FSharp.Core.dll to get at the ``` Microsoft.FSharp.Math.BigInt class. ``` So you can probably just reference the FSharp.PowerPack.dll to get at the ``` Microsoft.FSharp.Math.Matrix<A> class ```
271,971
<p>Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields?</p> <pre><code>SYSTEMTIME sysTime; GetLocalTime( &amp;sysTime ); char buf[80]; for (int i = 0; i &lt; 100000; i++) { sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); } </code></pre> <hr> <p>Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed <code>sprintf()</code> as the offender.</p>
[ { "answer_id": 271986, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 0, "selected": false, "text": "<p>StringStream is the suggestion that I got from Google.</p>\n\n<p><a href=\"http://bytes.com/forum/thread132583.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread132583.html</a></p>\n" }, { "answer_id": 271993, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 3, "selected": false, "text": "<p>You could try filling each char in the output in turn. </p>\n\n<pre><code>buf[0] = (sysTime.wYear / 1000) % 10 + '0' ;\nbuf[1] = (sysTime.wYear / 100) % 10 + '0';\nbuf[2] = (sysTime.wYear / 10) % 10 + '0';\nbuf[3] = sysTime.wYear % 10 + '0';\nbuf[4] = '-';\n</code></pre>\n\n<p>... etc...</p>\n\n<p>Not pretty, but you get the picture. If nothing else, it may help explain why sprintf isn't going to be that fast.</p>\n\n<p>OTOH, maybe you could cache the last result. That way you'd only need to generate one every second.</p>\n" }, { "answer_id": 271995, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 3, "selected": false, "text": "<p>Printf needs to deal with a lot of different formats.\nYou certainly could grab the <a href=\"http://www.menie.org/georges/embedded/printf.c\" rel=\"nofollow noreferrer\">source for printf</a> and use it as a basis to roll your own version that deals specifically with the <strong>sysTime</strong> structure. That way you pass in one argument, and it does just exactly the work that needs to be done and nothing more.</p>\n" }, { "answer_id": 272006, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 1, "selected": false, "text": "<p>You would probably get w perf increase by hand rolling a routine that lays out the digits in the return buf, since you could avoid repeatedly parsing a format string and would not have to deal with a lot of the more complex cases sprintf handles. I am loathe to actually recommend doing that though.</p>\n\n<p>I would recommend trying to figure out if you can somehow reduce the amount you need to generate these strings, are they optional somegtimes, can they be cached, etc.</p>\n" }, { "answer_id": 272011, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 0, "selected": false, "text": "<p>It's hard to imagine that you're going to beat sprintf at formatting integers. Are you sure sprintf is your problem?</p>\n" }, { "answer_id": 272016, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 2, "selected": false, "text": "<p>What do you mean by a \"long\" time -- since the <code>sprintf()</code> is the only statement in your loop and the \"plumbing\" of the loop (increment, comparison) is negligible, the <code>sprintf()</code> <em>has</em> to consume the most time.</p>\n\n<p>Remember the old joke about the man who lost his wedding ring on 3rd Street one night, but looked for it on 5th because the light was brighter there? You've built an example that's designed to \"prove\" your assumption that <code>sprintf()</code> is ineffecient.</p>\n\n<p>Your results will be more accurate if you profile \"actual\" code that contains <code>sprintf()</code> in addition to all the other functions and algorithms you use. Alternatively, try writing your own version that addresses the specific zero-padded numeric conversion that you require.</p>\n\n<p>You may be surprised at the results.</p>\n" }, { "answer_id": 272021, "author": "Jaywalker", "author_id": 382974, "author_profile": "https://Stackoverflow.com/users/382974", "pm_score": 2, "selected": false, "text": "<p>How about caching the results? Isn't that a possibility? Considering that this particular sprintf() call is made too often in your code, I'm assuming that between most of these consecutive calls, the year, month and day do not change.</p>\n\n<p>Thus, we can implement something like the following. Declare an old and a current SYSTEMTIME structure:</p>\n\n<pre><code>SYSTEMTIME sysTime, oldSysTime;\n</code></pre>\n\n<p>Also, declare separate parts to hold the date and the time:</p>\n\n<pre><code>char datePart[80];\nchar timePart[80];\n</code></pre>\n\n<p>For, the first time, you'll have to fill in both sysTime, oldSysTime as well as datePart and timePart. But subsequent sprintf()'s can be made quite faster as given below:</p>\n\n<pre>sprintf (timePart, \"%02d:%02d:%02d\", sysTime.wHour, sysTime.wMinute, sysTime.wSecond);\nif (oldSysTime.wYear == sysTime.wYear && \n oldSysTime.wMonth == sysTime.wMonth &&\n oldSysTime.wDay == sysTime.wDay) \n {\n // we can reuse the date part\n strcpy (buff, datePart);\n strcat (buff, timePart);\n }\nelse {\n // we need to regenerate the date part as well\n sprintf (datePart, \"%4d-%02d-%02d\", sysTime.wYear, sysTime.wMonth, sysTime.wDay);\n strcpy (buff, datePart);\n strcat (buff, timePart);\n}\n\nmemcpy (&oldSysTime, &sysTime, sizeof (SYSTEMTIME));\n</pre>\n\n<p>Above code has some redundancy to make the code easier to understand. You can factor out easily. You can further speed up if you know that even hour and minutes won't change faster than your call to the routine.</p>\n" }, { "answer_id": 272024, "author": "John Carter", "author_id": 8331, "author_profile": "https://Stackoverflow.com/users/8331", "pm_score": 5, "selected": true, "text": "<p>If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year.</p>\n\n<p>edit: Note that to cope with leap seconds (and to match <a href=\"http://en.cppreference.com/w/c/chrono/strftime\" rel=\"nofollow noreferrer\"><code>strftime()</code></a>) you should be able to print seconds values of 60 and 61.</p>\n\n<pre><code>char LeadingZeroIntegerValues[62][] = { \"00\", \"01\", \"02\", ... \"59\", \"60\", \"61\" };\n</code></pre>\n\n<p>Alternatively, how about <a href=\"http://en.cppreference.com/w/c/chrono/strftime\" rel=\"nofollow noreferrer\"><code>strftime()</code></a>? I've no idea how the performance compares (it could well just be calling sprintf()), but it's worth looking at (and it could be doing the above lookup itself).</p>\n" }, { "answer_id": 272113, "author": "Tom Barta", "author_id": 29839, "author_profile": "https://Stackoverflow.com/users/29839", "pm_score": 2, "selected": false, "text": "<p>I would do a few things...</p>\n\n<ul>\n<li>cache the current time so you don't have to regenerate the timestamp every time</li>\n<li>do the time conversion manually. The slowest part of the <code>printf</code>-family functions is the format-string parsing, and it's silly to be devoting cycles to that parsing on every loop execution.</li>\n<li>try using 2-byte lookup tables for all conversions (<code>{ \"00\", \"01\", \"02\", ..., \"99\" }</code>). This is because you want to avoid moduluar arithmetic, and a 2-byte table means you only have to use one modulo, for the year.</li>\n</ul>\n" }, { "answer_id": 272146, "author": "shank", "author_id": 24697, "author_profile": "https://Stackoverflow.com/users/24697", "pm_score": 2, "selected": false, "text": "<p>Looks like Jaywalker is suggesting a very similar method (beat me by less than an hour).</p>\n\n<p>In addition to the already suggested lookup table method (n2s[] array below), how about generating your format buffer so that the usual sprintf is less intensive? The code below will only have to fill in the minute and second every time through the loop unless the year/month/day/hour have changed. Obviously, if any of those have changed you do take another sprintf hit but overall it may not be more than what you are currently witnessing (when combined with the array lookup).</p>\n\n<pre><code>\nstatic char fbuf[80];\nstatic SYSTEMTIME lastSysTime = {0, ..., 0}; // initialize to all zeros.\n\nfor (int i = 0; i &lt; 100000; i++)\n{\n if ((lastSysTime.wHour != sysTime.wHour)\n || (lastSysTime.wDay != sysTime.wDay)\n || (lastSysTime.wMonth != sysTime.wMonth)\n || (lastSysTime.wYear != sysTime.wYear))\n {\n sprintf(fbuf, \"%4d-%02s-%02s %02s:%%02s:%%02s\",\n sysTime.wYear, n2s[sysTime.wMonth],\n n2s[sysTime.wDay], n2s[sysTime.wHour]);\n\n lastSysTime.wHour = sysTime.wHour;\n lastSysTime.wDay = sysTime.wDay;\n lastSysTime.wMonth = sysTime.wMonth;\n lastSysTime.wYear = sysTime.wYear;\n }\n\n sprintf(buf, fbuf, n2s[sysTime.wMinute], n2s[sysTime.wSecond]);\n\n}\n</code></pre>\n" }, { "answer_id": 814222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I'm working on a similar problem at the moment.</p>\n\n<p>I need to log debug statements with timestamp, filename, line number etc on an embedded system. We already have a logger in place but when I turn the knob to 'full logging', it eats all our proc cycles and puts our system in dire states, states that no computing device should ever have to experience.</p>\n\n<p>Someone did say \"You cannot measure/observe something without changing that which you are measuring/observing.\"</p>\n\n<p>So I'm changing things to improve performance. The current state of things is that Im 2x faster than the original <em>function call</em> (the bottleneck in that logging system is not in the function call but in the log reader which is a separate executable, which I can discard if I write my own logging stack).</p>\n\n<p>The interface I need to provide is something like- <code>void log(int channel, char *filename, int lineno, format, ...)</code>. I need to append the channel name (which currently does a <em>linear search</em> within a list! For every single debug statement!) and timestamp including millisecond counter. Here are some of the things Im doing to make this faster-</p>\n\n<ul>\n<li>Stringify channel name so I can <code>strcpy</code> rather than search the list. define macro <code>LOG(channel, ...etc)</code> as <code>log(#channel, ...etc)</code>. You can use <code>memcpy</code> if you fix the length of the string by defining <code>LOG(channel, ...)</code> <code>log(\"....\"#channel - sizeof(\"....\"#channel) + *11*)</code> to get fixed <em>10</em> byte channel lengths</li>\n<li>Generate timestamp string a couple of times a second. You can use asctime or something. Then memcpy the fixed length string to every debug statement.</li>\n<li>If you want to generate the timestamp string in real time then a look up table with assignment (not memcpy!) is perfect. But that works only for 2 digit numbers and maybe for the year.</li>\n<li><p>What about three digits (milliseconds) and five digits (lineno)? I dont like itoa and I dont like the custom itoa (<code>digit = ((value /= value) % 10)</code>) either because divs and mods are <em>slow</em>. I wrote the functions below and later discovered that something similar is in the AMD optimization manual (in assembly) which gives me confidence that these are about the fastest C implementations.</p>\n\n<pre><code>void itoa03(char *string, unsigned int value)\n{\n *string++ = '0' + ((value = value * 2684355) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = ' ';/* null terminate here if thats what you need */\n}\n</code></pre>\n\n<p>Similarly, for the line numbers,</p>\n\n<pre><code>void itoa05(char *string, unsigned int value)\n{\n *string++ = ' ';\n *string++ = '0' + ((value = value * 26844 + 12) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = '0' + ((value = ((value &amp; 0x0FFFFFFF)) * 10) &gt;&gt; 28);\n *string++ = ' ';/* null terminate here if thats what you need */\n}\n</code></pre></li>\n</ul>\n\n<p>Overall, my code is pretty fast now. The <code>vsnprintf()</code> I need to use takes about 91% of the time and the rest of my code takes only 9% (whereas the rest of the code i.e. except <code>vsprintf()</code> used to take 54% earlier)</p>\n" }, { "answer_id": 50260393, "author": "rustyx", "author_id": 485343, "author_profile": "https://Stackoverflow.com/users/485343", "pm_score": 1, "selected": false, "text": "<p>The two fast formatters I've tested are <a href=\"http://www.fastformat.org/\" rel=\"nofollow noreferrer\"><strong>FastFormat</strong></a> and <strong>Karma::generate</strong> (part of <a href=\"https://www.boost.org/doc/libs/1_67_0/libs/spirit/doc/html/spirit/karma.html\" rel=\"nofollow noreferrer\">Boost Spirit</a>).</p>\n\n<p>You might also find it useful to benchmark it or at least look for existing benchmarks.</p>\n\n<p>For example <a href=\"http://www.zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html\" rel=\"nofollow noreferrer\">this one</a> (though it's missing FastFormat):</p>\n\n<p><a href=\"https://i.stack.imgur.com/FBjiB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FBjiB.png\" alt=\"Fast integer to string conversion in C++\"></a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/271971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields? ``` SYSTEMTIME sysTime; GetLocalTime( &sysTime ); char buf[80]; for (int i = 0; i < 100000; i++) { sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); } ``` --- Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed `sprintf()` as the offender.
If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year. edit: Note that to cope with leap seconds (and to match [`strftime()`](http://en.cppreference.com/w/c/chrono/strftime)) you should be able to print seconds values of 60 and 61. ``` char LeadingZeroIntegerValues[62][] = { "00", "01", "02", ... "59", "60", "61" }; ``` Alternatively, how about [`strftime()`](http://en.cppreference.com/w/c/chrono/strftime)? I've no idea how the performance compares (it could well just be calling sprintf()), but it's worth looking at (and it could be doing the above lookup itself).
272,007
<p>I am using jQuery to try and trigger a method when an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> (2.0) dropdown list's change event is handled by jQuery. The problem is that the drop down list is located inside a gridview and even then only when a user has decided to edit a row within that gridview.</p> <p>I think I have it picking up the object using an ASP code block, but the problem with that is that when the page first loads the edit index of the row does not exist and it throws an error. Putting the block inside a <code>IF</code> statement also does not work.</p> <pre><code>$(document).ready(function() //when DOM is ready, run containing code { &lt;% if (grvTimeSheets.EditIndex &gt; -1) {%&gt; $(#&lt;%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %&gt;).change(function() { $(#&lt;%= grvTimeSheets.ClientID %&gt;).block({ message: null } }); } ); &lt;% } %&gt; </code></pre> <p>It is one attempt I made, and I also tried putting the IF statement ASP code outside the JavaScript block. It doesn't work either.</p> <p>How could I apply the jQuery event to the drop drop box? Ideally as concise as possible.</p> <hr> <p>Thanks for the answer but nope, it doesn't work :(. The JavaScript code seems not to be outputted... Confusing...</p> <pre><code>&lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.tablesorter.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.blockUI.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() //When DOM is ready, run the containing code { } ); &lt;/script&gt; </code></pre> <p>Is the output. Even though this is the code:</p> <pre><code>&lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.tablesorter.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.blockUI.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() //when DOM is ready, run containing code {&lt;% if (grvTimeSheets.EditIndex &gt; -1) {%&gt; var id = '#&lt;%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %&gt;'; $(id).change(function() { $(id).block({ message: null } }); &lt;% } %&gt; } ); &lt;/script&gt; </code></pre> <p>It was doing that before as well, driving me CRAZY.</p> <hr> <p>Sorry, could you make that slightly clearer. I tried defining the entire thing in code behind like so:</p> <pre><code>DropDownList ddl (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients"); if (ddl != null) { ClientScriptManager csm = Page.ClientScript; Type cstype = this.GetType(); String csname1 = "PopupScript"; string script = @" &lt;script language='javascript' type='text/javascript'&gt; $(#" + ddl.ClientID + ").change(function() { $(" + grvTimeSheets.ClientID + ").blockUI({ message: null }});} &lt;/script&gt;"; csm.RegisterStartupScript(cstype, csname1, script, true); } </code></pre> <p>Is that what you meant?</p> <p>BTW, the above didn't work. No errors, just no events worked.</p>
[ { "answer_id": 272311, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 3, "selected": true, "text": "<p>A couple of things here.</p>\n\n<ol>\n<li>You need to wrap your selectors in quotes when you pass them to the <code>$()</code> function. The code snippet above generates something like <code>$(#some-generated-id)</code>, which won't work.</li>\n<li>The closing curly brace for your server side if statement was outside the onready function. It needs to be nested at the same level as the opening if.</li>\n</ol>\n\n<p>Try this one:</p>\n\n<pre><code>$(document).ready(function() //when DOM is ready, run containing code\n{\n &lt;% if (grvTimeSheets.EditIndex &gt; -1) {%&gt;\n var id = '#&lt;%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl(\"ddlClients\").ClientID %&gt;';\n $(id).change(function() { \n $(id).block({ message: null }\n }); \n &lt;% } %&gt;\n}\n);\n</code></pre>\n\n<p>If it doesn't work, go ahead and paste the generated javascript as well.</p>\n" }, { "answer_id": 272752, "author": "OutOFTouch", "author_id": 35166, "author_profile": "https://Stackoverflow.com/users/35166", "pm_score": 1, "selected": false, "text": "<p>I used the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.page.clientscript.aspx\" rel=\"nofollow noreferrer\">Page.ClientScript</a> property to register a script block to contain any id's I need to access with jQuery.</p>\n\n<p>Here is an example of my JavaScript in an external file:</p>\n\n<pre><code>var myFancySelector = '#' + myControlId;\nselectedValue = $(myFancySelector).val();\n</code></pre>\n\n<p>myControlId is defined from the code behind and registerd in the ClientScriptBlock.</p>\n" }, { "answer_id": 272788, "author": "OutOFTouch", "author_id": 35166, "author_profile": "https://Stackoverflow.com/users/35166", "pm_score": 1, "selected": false, "text": "<p>Use this: </p>\n\n<pre><code>cs.RegisterClientScriptBlock(cstype, csname, cstext2.ToString(), False)\n</code></pre>\n\n<p>It is false to not create the script tags since you are including them. The MSDN documentation is wrong in how it explains the flag.</p>\n\n<p>Also, just put the client id's of your controls into separate variables from the code behind, not the <a href=\"http://en.wikipedia.org/wiki/JQuery\" rel=\"nofollow noreferrer\">jQuery</a> code.</p>\n\n<p>Then use the variables that contain the ids instead in jQuery code.</p>\n" }, { "answer_id": 272832, "author": "OutOFTouch", "author_id": 35166, "author_profile": "https://Stackoverflow.com/users/35166", "pm_score": 0, "selected": false, "text": "<p>The key can be anything you want, it should be unique though.</p>\n" }, { "answer_id": 272853, "author": "Damien", "author_id": 35454, "author_profile": "https://Stackoverflow.com/users/35454", "pm_score": 0, "selected": false, "text": "<p>I'll try more after the weekend. This was the code, though:</p>\n\n<pre><code>DropDownList ddl = (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl(\"ddlClients\");\nif (ddl != null)\n{\n ClientScriptManager csm = Page.ClientScript;\n Type cstype = this.GetType();\n String csname1 = \"PopupScript\";\n\n string script = @\"\n &lt;script language='javascript' type='text/javascript'&gt;\n jQuery(#\" + ddl.ClientID + \").change(function() { $(\" + grvTimeSheets.ClientID + \").blockUI({ message: null }});} &lt;/script&gt;\";\n csm.RegisterStartupScript(cstype, csname1, script, false);\n</code></pre>\n" }, { "answer_id": 272871, "author": "OutOFTouch", "author_id": 35166, "author_profile": "https://Stackoverflow.com/users/35166", "pm_score": 1, "selected": false, "text": "<p>Inside your script block that you create in the code behind:</p>\n\n<pre><code>string script = @\"&lt;script type=text/javascript&gt; var myControlId = '\" + ddl.ClientId \"';\") + \"&lt;/script&gt;\"\n</code></pre>\n\n<p>I didn't verify this syntax, but it should be close. You can add the additional syntax for <code>grvTimeSheets.ClientID</code> yourself. If you get this working then you might want to change it to build a JavaScript array and store the ClientId's that way, and then you only have one global JavaScript variable that you need to work with.</p>\n" }, { "answer_id": 272883, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>Another option is to just give the element you're looking for a class name that describes its behavior. Then your jQuery code becomes really clear:</p>\n\n<pre><code>$(function() {\n $(\"select.yourMarkerClass\").change(....);\n});\n</code></pre>\n\n<p>If there is no edit row, then this code does nothing. If there is an element that matches the selector, you'll get the new behavior added.</p>\n" }, { "answer_id": 272884, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 1, "selected": false, "text": "<p>If you're not using the same ID elsewhere on the page, you can thwart <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"nofollow noreferrer\">ASP.NET</a>'s UniqueID with one of jQuery's advanced selectors:</p>\n\n<pre><code>$('[id$=ddlClients]')\n</code></pre>\n\n<p>This matches only the end of the id string rather than the whole. Bear in mind, if the control is present multiple times within different rows, this will match all instances.</p>\n\n<p>See <em><a href=\"http://docs.jquery.com/Selectors\" rel=\"nofollow noreferrer\">Selectors</a></em> for more examples.</p>\n" }, { "answer_id": 272994, "author": "OutOFTouch", "author_id": 35166, "author_profile": "https://Stackoverflow.com/users/35166", "pm_score": 0, "selected": false, "text": "<p>Because you have a dropdown in each row. Each dropdown will have a Unique ClientId, so I suggest doing what Ben suggested and use the class selector since it is the simplest solution.</p>\n\n<p>Or you could create a JavaScript function on your edit click and then get the unique client id of your dropdown in that row that is being edited.</p>\n\n<p>Sorry, I should have read your code closer.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35454/" ]
I am using jQuery to try and trigger a method when an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) (2.0) dropdown list's change event is handled by jQuery. The problem is that the drop down list is located inside a gridview and even then only when a user has decided to edit a row within that gridview. I think I have it picking up the object using an ASP code block, but the problem with that is that when the page first loads the edit index of the row does not exist and it throws an error. Putting the block inside a `IF` statement also does not work. ``` $(document).ready(function() //when DOM is ready, run containing code { <% if (grvTimeSheets.EditIndex > -1) {%> $(#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>).change(function() { $(#<%= grvTimeSheets.ClientID %>).block({ message: null } }); } ); <% } %> ``` It is one attempt I made, and I also tried putting the IF statement ASP code outside the JavaScript block. It doesn't work either. How could I apply the jQuery event to the drop drop box? Ideally as concise as possible. --- Thanks for the answer but nope, it doesn't work :(. The JavaScript code seems not to be outputted... Confusing... ``` <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.tablesorter.js"></script> <script type="text/javascript" src="jquery.blockUI.js"></script> <script type="text/javascript"> $(document).ready(function() //When DOM is ready, run the containing code { } ); </script> ``` Is the output. Even though this is the code: ``` <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.tablesorter.js"></script> <script type="text/javascript" src="jquery.blockUI.js"></script> <script type="text/javascript"> $(document).ready(function() //when DOM is ready, run containing code {<% if (grvTimeSheets.EditIndex > -1) {%> var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>'; $(id).change(function() { $(id).block({ message: null } }); <% } %> } ); </script> ``` It was doing that before as well, driving me CRAZY. --- Sorry, could you make that slightly clearer. I tried defining the entire thing in code behind like so: ``` DropDownList ddl (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients"); if (ddl != null) { ClientScriptManager csm = Page.ClientScript; Type cstype = this.GetType(); String csname1 = "PopupScript"; string script = @" <script language='javascript' type='text/javascript'> $(#" + ddl.ClientID + ").change(function() { $(" + grvTimeSheets.ClientID + ").blockUI({ message: null }});} </script>"; csm.RegisterStartupScript(cstype, csname1, script, true); } ``` Is that what you meant? BTW, the above didn't work. No errors, just no events worked.
A couple of things here. 1. You need to wrap your selectors in quotes when you pass them to the `$()` function. The code snippet above generates something like `$(#some-generated-id)`, which won't work. 2. The closing curly brace for your server side if statement was outside the onready function. It needs to be nested at the same level as the opening if. Try this one: ``` $(document).ready(function() //when DOM is ready, run containing code { <% if (grvTimeSheets.EditIndex > -1) {%> var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>'; $(id).change(function() { $(id).block({ message: null } }); <% } %> } ); ``` If it doesn't work, go ahead and paste the generated javascript as well.
272,035
<p>I have a form that displays file information in a TabControl, and I'd like the pages to have the file's icon in their tab. How do I get the icon associated with a file type?</p> <p>I'd prefer solutions that don't involve looking things up in the registry, but if that's the only way then so be it.</p>
[ { "answer_id": 272044, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.codeproject.com/KB/dotnet/System_File_Association.aspx\" rel=\"nofollow noreferrer\">CodeProject</a> has some classes you can download.</p>\n\n<p>First get the <code>FileAssociationInfo</code>, and from that get the <code>ProgramAssociationInfo</code>. The <code>pai</code> object can give you the icon.</p>\n\n<pre><code>FileAssociationInfo fai = new FileAssociationInfo(\".bob\");\nProgramAssociationInfo pai = new ProgramAssociationInfo(fai.ProgID);\nProgramIcon icon = pai.DefaultIcon;\n</code></pre>\n" }, { "answer_id": 272058, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx\" rel=\"noreferrer\">System.Drawing.Icon.ExtractAssociatedIcon(string filePath)</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I have a form that displays file information in a TabControl, and I'd like the pages to have the file's icon in their tab. How do I get the icon associated with a file type? I'd prefer solutions that don't involve looking things up in the registry, but if that's the only way then so be it.
[CodeProject](http://www.codeproject.com/KB/dotnet/System_File_Association.aspx) has some classes you can download. First get the `FileAssociationInfo`, and from that get the `ProgramAssociationInfo`. The `pai` object can give you the icon. ``` FileAssociationInfo fai = new FileAssociationInfo(".bob"); ProgramAssociationInfo pai = new ProgramAssociationInfo(fai.ProgID); ProgramIcon icon = pai.DefaultIcon; ```
272,036
<p>I've accidentally removed Win2K compatibility from an application by using <a href="http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx" rel="nofollow noreferrer">GetProcessID</a>.</p> <p>I use it like this, to get the main HWND for the launched application.</p> <pre><code>ShellExecuteEx(&amp;info); // Launch application HANDLE han = info.hProcess; // Get process cbinfo.han = han; //Call EnumWindows to enumerate windows.... //with this as the callback static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam) { DWORD id; GetWIndowThreadProcessID(hwnd, &amp;id); if (id == GetProcessID(cbinfo.han)) setResult(hwnd) ... } </code></pre> <p>Any ideas how the same function could be acheived on Win2K?</p>
[ { "answer_id": 272070, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 4, "selected": true, "text": "<p>There is an 'sort-of-unsupported' function: ZwQueryInformationProcess(): see</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms687420.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms687420.aspx</a></p>\n\n<p>This will give you the process id (amongst other things), given the handle. This isn't guaranteed to work with future Windows versions, so I'd suggest having a helper function that tests the OS version and then uses GetProcAddress() to call either GetProcessId() for XP and above, and ZwQueryInformationProcess() for Win2K only.</p>\n" }, { "answer_id": 272723, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>No, it's not ZwQueryInformationProcess() \nIt's NtQIP and of course it works for all versions since NT 3.5 and you don't need to test OS at all</p>\n" }, { "answer_id": 277202, "author": "Larry Osterman", "author_id": 761503, "author_profile": "https://Stackoverflow.com/users/761503", "pm_score": 3, "selected": false, "text": "<p>DavidK's right. Please see the comment in the ZwQueryInformationProcess documentation:</p>\n\n<blockquote>\n <p>[ZwQueryInformationProcess may be\n altered or unavailable in future\n versions of Windows. Applications\n should use the alternate functions\n listed in this topic.]</p>\n</blockquote>\n\n<p>That means that Microsoft can choose to remove this at any time in the future, thus breaking your application. I strongly consider you follow DavidK's advice and use ZwQueryInformationProcess on OS's that don't support GetProcessID and use GetProcessID on OS's that support it (XP SP1 and above).</p>\n" }, { "answer_id": 280533, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>Thanks to DavidK and Larry - Here's my final solution. Full error handling is left as an exercise for the reader.</p>\n\n<p>Note that rather than specifically checking the OS version, I attempt to dynamically link to the functions. Static linking would mean that the application would simply fail to load if the procedure wasn't available. </p>\n\n<p>This has been tried successfully on Win2K and Vista:</p>\n\n<pre><code>#include \"Winternl.h\"\n\ntypedef DWORD (WINAPI* pfnGetProcID)(HANDLE h);\n\ntypedef NTSTATUS (WINAPI* pfnQueryInformationProcess)(\n HANDLE ProcessHandle,\n PROCESSINFOCLASS ProcessInformationClass,\n PVOID ProcessInformation,\n ULONG ProcessInformationLength,\n PULONG ReturnLength);\n\nDWORD MyGetProcessId(HANDLE h)\n{\n static pfnQueryInformationProcess ntQIP = (pfnQueryInformationProcess) GetProcAddress(GetModuleHandle(\"NTDLL.DLL\"),\"NtQueryInformationProcess\");\n static pfnGetProcID getPId = (pfnGetProcID) GetProcAddress(GetModuleHandle(\"KERNEL32.DLL\"),\"GetProcessId\");\n\n if ((ntQIP == NULL) &amp;&amp; (getPId == NULL))\n throw Exception(\"Can't retrieve process ID : GetProcessID not supported\");\n\n if (getPId != NULL)\n return getPId(h);\n else\n {\n PROCESS_BASIC_INFORMATION info;\n ULONG returnSize;\n ntQIP(h, ProcessBasicInformation, &amp;info, sizeof(info), &amp;returnSize); // Get basic information.\n return info.UniqueProcessId;\n }\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
I've accidentally removed Win2K compatibility from an application by using [GetProcessID](http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx). I use it like this, to get the main HWND for the launched application. ``` ShellExecuteEx(&info); // Launch application HANDLE han = info.hProcess; // Get process cbinfo.han = han; //Call EnumWindows to enumerate windows.... //with this as the callback static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam) { DWORD id; GetWIndowThreadProcessID(hwnd, &id); if (id == GetProcessID(cbinfo.han)) setResult(hwnd) ... } ``` Any ideas how the same function could be acheived on Win2K?
There is an 'sort-of-unsupported' function: ZwQueryInformationProcess(): see <http://msdn.microsoft.com/en-us/library/ms687420.aspx> This will give you the process id (amongst other things), given the handle. This isn't guaranteed to work with future Windows versions, so I'd suggest having a helper function that tests the OS version and then uses GetProcAddress() to call either GetProcessId() for XP and above, and ZwQueryInformationProcess() for Win2K only.
272,038
<p>In my Seam application, I have a Seam component that returns a (<code>@Datamodel</code>) list of items I want to transform into a set of <code>&lt;li&gt;</code> HTML elements. I have this working without a problem. </p> <p>But now, I want to split up the list according to an EL expression. So the EL expression determines if a new <code>&lt;ul&gt;</code> element should be started. I tried the following:</p> <pre><code>&lt;s:fragment rendered="#{action.isNewList(index)}"&gt; &lt;ul&gt; &lt;/s:fragment&gt; &lt;!-- stuff that does the &lt;li&gt;'s goes here --&gt; &lt;s:fragment rendered="#{action.isNewList(index)}"&gt; &lt;/ul&gt; &lt;/s:fragment&gt; </code></pre> <p>But that's invalid, because the nesting for <code>&lt;ul&gt;</code> is wrong.</p> <p>How should I do this?</p>
[ { "answer_id": 483930, "author": "phloopy", "author_id": 8507, "author_profile": "https://Stackoverflow.com/users/8507", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with the Seam Framework, but if I understand the problem correctly something like this might work.</p>\n\n<pre><code>&lt;!-- before your loop, open your first &lt;ul&gt; if the (@Datamodel) is not empty --&gt;\n\n&lt;s:fragment rendered=\"#{action.isNewList(index)}\"&gt;\n &lt;/ul&gt;\n &lt;ul&gt;\n&lt;/s:fragment&gt;\n&lt;!-- stuff that does the &lt;li&gt;'s goes here --&gt;\n\n&lt;!-- after your loop, close your last &lt;/ul&gt; if the (@Datamodel) is not empty --&gt;\n</code></pre>\n" }, { "answer_id": 483957, "author": "Mike Griffith", "author_id": 1469605, "author_profile": "https://Stackoverflow.com/users/1469605", "pm_score": 0, "selected": false, "text": "<p>I'm not familiar with Seam specifically, but I've seen this same problem come up when working with XSLT and other XML-based frameworks.</p>\n\n<p>There are generally two solutions:</p>\n\n<ol>\n<li>Rethink your page and data architecture so that the entire list written depending on a single condition. This may require a loop inside the s:fragment.</li>\n<li>Wrap the offending non-valid fragment html in a &lt;![CDATA[ ... ]]&gt;</li>\n</ol>\n" }, { "answer_id": 485578, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 0, "selected": false, "text": "<p>You should have something like this (i will use pseudo code):</p>\n\n<pre><code>&lt;ul&gt;\n &lt;s:for items=\"itemList\" ...&gt;\n\n &lt;s:fragment rendered=\"#{action.isNewList(index) &amp;&amp; index &gt; 0}\"&gt;\n &lt;/ul&gt;\n &lt;ul&gt;\n &lt;/s:fragment&gt;\n &lt;li&gt;\n &lt;!-- stuff that does the &lt;li&gt;'s goes here --&gt;\n &lt;/li&gt;\n\n &lt;/s:for&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 487676, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 2, "selected": true, "text": "<p>You can do this using the JSF <code>&lt;f:verbatim&gt;</code> tag, which isn't pretty but works:</p>\n\n<pre><code>&lt;f:verbatim rendered=\"#{action.isNewList(index)}\"&gt;\n &amp;lt;ul&amp;gt;\n&lt;/f:verbatim&gt;\n&lt;!-- stuff that does the &lt;li&gt;'s goes here --&gt;\n&lt;f:verbatim rendered=\"#{action.isNewList(index)}\"&gt;\n &amp;lt;/ul&amp;gt;\n&lt;/f:verbatim&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6400/" ]
In my Seam application, I have a Seam component that returns a (`@Datamodel`) list of items I want to transform into a set of `<li>` HTML elements. I have this working without a problem. But now, I want to split up the list according to an EL expression. So the EL expression determines if a new `<ul>` element should be started. I tried the following: ``` <s:fragment rendered="#{action.isNewList(index)}"> <ul> </s:fragment> <!-- stuff that does the <li>'s goes here --> <s:fragment rendered="#{action.isNewList(index)}"> </ul> </s:fragment> ``` But that's invalid, because the nesting for `<ul>` is wrong. How should I do this?
You can do this using the JSF `<f:verbatim>` tag, which isn't pretty but works: ``` <f:verbatim rendered="#{action.isNewList(index)}"> &lt;ul&gt; </f:verbatim> <!-- stuff that does the <li>'s goes here --> <f:verbatim rendered="#{action.isNewList(index)}"> &lt;/ul&gt; </f:verbatim> ```
272,045
<p>I have two tables A and B. I would like to delete all the records from table A that are returned in the following query:</p> <pre><code>SELECT A.* FROM A , B WHERE A.id = B.a_id AND b.date &lt; '2008-10-10' </code></pre> <p>I have tried:</p> <pre><code>DELETE A WHERE id in ( SELECT a_id FROM B WHERE date &lt; '2008-10-10') </code></pre> <p>but that only works if the inner select actually returns a value (not if the result set is empty)</p> <p><strong>NB:</strong> this has to work on <strong>both SQLServer AND MySQL</strong></p> <p>EDIT: More information</p> <p>The above delete works 100% on SQLServer</p> <p>When running it on MySQL I get an "error in you SQL syntax" message which points to the start of the SELECT as the problem. if I substitute the inner select with (1,2) then it works. </p> <p><em>@Kibbee You are right it actually makes no difference if the inner select returns rows or not.</em></p> <p><em>@Fred I get a "not unique table.alias: a" message</em></p>
[ { "answer_id": 272056, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "<p>You were not so far from the answer!</p>\n\n<p>Post Edited: Remove alias on table A and B</p>\n\n<pre><code>DELETE FROM A\nWHERE A.id in (\n SELECT B.a_id \n FROM B\n WHERE B.date &lt; '2008-10-10');\n</code></pre>\n" }, { "answer_id": 272063, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>I'm not sure why your method is failing. If the inner query returns an empty set, then the first query should also return an empty set. I don't think @Fred's solution is right, as he seems to be joining on the wrong column.</p>\n" }, { "answer_id": 272083, "author": "lmop", "author_id": 22260, "author_profile": "https://Stackoverflow.com/users/22260", "pm_score": 4, "selected": true, "text": "<p>I think this should work (works on MySQL anyway):</p>\n\n<pre><code>DELETE a.* FROM A a JOIN B b ON b.id = a.id WHERE b.date &lt; '2008-10-10';\n</code></pre>\n\n<p>Without aliases:</p>\n\n<pre><code>DELETE A.* FROM A JOIN B ON B.id = A.id WHERE B.date &lt; '2008-10-10';\n</code></pre>\n" }, { "answer_id": 272102, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": -1, "selected": false, "text": "<p>According to your description to your DELETE-statement, you want to delete empty orphants in table A aswell?</p>\n\n<pre>\nDELETE A.*\nFROM A \nLEFT JOIN B ON A.id = B.a_id AND b.date > '2008-10-10'\nWHERE b.id IS NULL\n</pre>\n\n<p>(please note the inverted way of joining in B)</p>\n\n<p>Should do the trick in that case. I'm not sure how MSSQL deals with join-deletes, but I guess that it should work the same way. </p>\n" }, { "answer_id": 272144, "author": "anonym0use", "author_id": 35441, "author_profile": "https://Stackoverflow.com/users/35441", "pm_score": 1, "selected": false, "text": "<p>You could also use ON CASCADE in your child table so that when a row is deleted in your parent table it automatically deletes child rows in the child table. In that way you need not worry about referential integrity when a parent row is deleted.</p>\n" }, { "answer_id": 272156, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 0, "selected": false, "text": "<pre><code>delete from a inner join b on a.id = b.a_id and b.date &lt; '2008-10-10'\n</code></pre>\n" }, { "answer_id": 272221, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "<p>Or you could switch to an exists syntax with a correlated subquery ... </p>\n\n<pre><code>Delete A \nFrom A\nWhere Exists \n (Select * From B \n Where B.Id = A.Id\n And B.date &lt; '2008-10-10');\n</code></pre>\n\n<p>Depending on how smart the query optimizer is, (and how many records in Table B would be returned by the subquery) this could be faster, as an exists doesn't need to completely generate the full resultset... It can stop as soon as it finds one record... </p>\n" }, { "answer_id": 277377, "author": "EJ.", "author_id": 35109, "author_profile": "https://Stackoverflow.com/users/35109", "pm_score": 0, "selected": false, "text": "<p>Another option in MYSQL and MSSQL, but its long way round of doing it: </p>\n\n<pre><code>select b.ID\ninto #T\nfrom \n [Table b] with (nolock) \nwhere \n b.date &gt; '2008-10-10'\n\nif exists (select * from #T with (nolock))\n delete from [Table a] where a.id in (select id from #T with (nolock))\n drop table #T\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
I have two tables A and B. I would like to delete all the records from table A that are returned in the following query: ``` SELECT A.* FROM A , B WHERE A.id = B.a_id AND b.date < '2008-10-10' ``` I have tried: ``` DELETE A WHERE id in ( SELECT a_id FROM B WHERE date < '2008-10-10') ``` but that only works if the inner select actually returns a value (not if the result set is empty) **NB:** this has to work on **both SQLServer AND MySQL** EDIT: More information The above delete works 100% on SQLServer When running it on MySQL I get an "error in you SQL syntax" message which points to the start of the SELECT as the problem. if I substitute the inner select with (1,2) then it works. *@Kibbee You are right it actually makes no difference if the inner select returns rows or not.* *@Fred I get a "not unique table.alias: a" message*
I think this should work (works on MySQL anyway): ``` DELETE a.* FROM A a JOIN B b ON b.id = a.id WHERE b.date < '2008-10-10'; ``` Without aliases: ``` DELETE A.* FROM A JOIN B ON B.id = A.id WHERE B.date < '2008-10-10'; ```
272,097
<p>How do I dynamically reload the app.config in a .net Windows application? I need to turn logging on and off dynamically and not just based upon the value at application start.</p> <p>ConfigurationManager.RefreshSection("appSettings") does not work and I've also tried explicitly opening the config file using OpenExeConfiguration but I always get the cached value at application startup and not the current value. </p> <p>I've accepted the answer of creating a custom configuration section. As a side note and foolish mistake - if you're running from the IDE there's no point in updating the app.config file and expecting changes. Yuo have to modify the .exe.config file in the bin\debug folder. Doh!</p>
[ { "answer_id": 272103, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>I don't think there's any way to do this, unless you write your own config file reader using XML. Why not just turn logging on or off at the start of your app based on the config file setting, and then just turn it on or off dynamically while the program is running?</p>\n" }, { "answer_id": 272104, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 0, "selected": false, "text": "<p>I think I read in the log4net documentation that this is not possible.</p>\n\n<p>Try having the logging in an external logfile that can be watched with a filesystemwatcher</p>\n\n<p>Update: Found it again.. \n<a href=\"http://logging.apache.org/log4net/release/manual/configuration.html#.config%20Files\" rel=\"nofollow noreferrer\">http://logging.apache.org/log4net/release/manual/configuration.html#.config%20Files</a></p>\n\n<p>There is no way to reload the app.config during runtime.</p>\n" }, { "answer_id": 272107, "author": "eduesing", "author_id": 322538, "author_profile": "https://Stackoverflow.com/users/322538", "pm_score": 0, "selected": false, "text": "<p>I would recommend using another XML file and not app.config. You could even watch the file for changes and automatically reload it when it changes.</p>\n" }, { "answer_id": 272114, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 6, "selected": true, "text": "<p>You can refresh <strong>your own</strong> section the way you say:</p>\n\n<pre><code>ConfigurationManager.RefreshSection(\"yoursection/subsection\");\n</code></pre>\n\n<p>Just move a logging true/false into a section and you'll be fine.</p>\n" }, { "answer_id": 272120, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>If you are using log4Net, you can do what you asked:</p>\n\n<p>Although it is possible to add your log4net configuration settings to your project’s <code>app.config</code> or <code>web.config</code> file, it is preferable to place them in a separate configuration file. Aside from the obvious benefit of maintainability, it has the added benefit that log4net can place a <code>FileSystemWatcher</code> object on your config file to monitor when it changes and update its settings dynamically.</p>\n\n<p>To use a separate config file, add a file named Log4Net.config to your project and add the following attribute to your AssemblyInfo.cs file: </p>\n\n<pre><code>[assembly: log4net.Config.XmlConfigurator(ConfigFile=\"Log4Net.config\", Watch = true)]\n</code></pre>\n\n<p>Note: for web applications, this assumes <code>Log4Net.config</code> resides in the web root. Ensure the <code>log4net.config</code> file is marked as “Copy To Output” -> “Copy Always” in Properties.</p>\n" }, { "answer_id": 748467, "author": "foson", "author_id": 22539, "author_profile": "https://Stackoverflow.com/users/22539", "pm_score": 2, "selected": false, "text": "<p>Just a note, in WinForms, you can make programmatic changes to your app.config before your application loads (before <code>Application.Start(new Form1())</code>), as long as you use <code>System.Xml</code> instead of <code>System.Configuration.ConfigurationManager</code></p>\n\n<pre><code>string configFile = Application.ExecutablePath + \".config\"; //c:\\path\\exename.exe.config\nXmlDocument xdoc = new XmlDocument();\nxdoc.Load(configFile);\nXmlNode node = xdoc.SelectSingleNode(\"/configuration/appSettings/add[@key='nodeToChange']/@value\");\nnode.Value = \"new value\";\nFile.WriteAllText(setFile, xdoc.InnerXml);\n</code></pre>\n" }, { "answer_id": 1198660, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Actually using an:</p>\n\n<p>Application.restart();</p>\n\n<p>Has worked pretty good for me.</p>\n\n<p>Regards</p>\n\n<p>Jorge</p>\n" }, { "answer_id": 3607822, "author": "Ruchir", "author_id": 435781, "author_profile": "https://Stackoverflow.com/users/435781", "pm_score": 3, "selected": false, "text": "<p>Following is the hack which you can put this will make config to read from disk.</p>\n\n<p>You just need to save the config file in Modified Mode and then refresh this will make application to read the file agian from the disk.</p>\n\n<pre><code>ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n</code></pre>\n" }, { "answer_id": 6841134, "author": "froeschli", "author_id": 431657, "author_profile": "https://Stackoverflow.com/users/431657", "pm_score": 1, "selected": false, "text": "<p>I wrote this implementation to change the log level at runtime and persist the new treshold back to the app.config (actually the Application.exe.config).</p>\n\n<p>The interface:</p>\n\n<pre><code>internal interface ILoggingConfiguration\n{\n void SetLogLevel(string level);\n\n string GetLogLevel();\n}\n</code></pre>\n\n<p>The implementation:</p>\n\n<pre><code>internal sealed class LoggingConfigurationImpl : ILoggingConfiguration\n{\n #region Members\n\n private static readonly ILog _logger = \n ObjectManager.Common.Logger.GetLogger();\n private const string DEFAULT_NAME_SPACE = \"Default.Name.Space\";\n\n #endregion\n\n #region Implementation of ILoggingConfiguration\n\n public void SetLogLevel(string level)\n {\n Level threshold = Log4NetUtils.ConvertToLevel(level);\n ILoggerRepository[] repositories = LogManager.GetAllRepositories();\n\n foreach (ILoggerRepository repository in repositories)\n {\n try\n {\n SetLogLevelOnRepository(repository, threshold);\n }\n catch (Exception ex)\n {\n _logger.ErrorFormat(\"Exception while changing log-level: {0}\", ex);\n }\n }\n PersistLogLevel(level);\n }\n\n public string GetLogLevel()\n {\n ILoggerRepository repository = LogManager.GetRepository();\n Hierarchy hierarchy = (Hierarchy) repository;\n ILogger logger = hierarchy.GetLogger(DEFAULT_NAME_SPACE);\n return ((Logger) logger).Level.DisplayName;\n }\n\n private void SetLogLevelOnRepository(ILoggerRepository repository,\n Level threshold)\n {\n repository.Threshold = threshold;\n Hierarchy hierarchy = (Hierarchy)repository;\n ILogger[] loggers = hierarchy.GetCurrentLoggers();\n foreach (ILogger logger in loggers)\n {\n try\n {\n SetLogLevelOnLogger(threshold, logger);\n }\n catch (Exception ex)\n {\n _logger.ErrorFormat(\"Exception while changing log-level for \n logger: {0}{1}{2}\", logger, Environment.NewLine, ex);\n }\n }\n }\n\n private void SetLogLevelOnLogger(Level threshold, ILogger logger)\n {\n ((Logger)logger).Level = threshold;\n }\n\n private void PersistLogLevel(string level)\n {\n XmlDocument config = new XmlDocument();\n config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n string xpath =\n String.Format(\"configuration/log4net/logger[@name='{0}']/level\",\n DEFAULT_NAME_SPACE);\n XmlNode rootLoggerNode = config.SelectSingleNode(xpath);\n\n try\n {\n rootLoggerNode.Attributes[\"value\"].Value = level;\n config.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);\n\n ConfigurationManager.RefreshSection(\"log4net\");\n }\n catch(Exception ex)\n {\n _logger.ErrorFormat(\"error while persisting new log-level: {0}\", ex);\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>The helper class Log4NetUtils:</p>\n\n<pre><code>public sealed class Log4NetUtils\n{\n private static readonly ILoggerRepository _loggerRepository =\n LoggerManager.GetAllRepositories().First();\n\n public static Level ConvertToLevel(string level)\n {\n return _loggerRepository.LevelMap[level];\n }\n}\n</code></pre>\n\n<p>The XAML code:</p>\n\n<pre><code>&lt;ComboBox Name=\"cbxLogLevel\" Text=\"{Binding LogLevel}\"&gt;\n &lt;ComboBoxItem Content=\"DEBUG\" /&gt;\n &lt;ComboBoxItem Content=\"INFO\" /&gt;\n &lt;ComboBoxItem Content=\"WARN\" /&gt;\n &lt;ComboBoxItem Content=\"ERROR\" /&gt;\n&lt;/ComboBox&gt;\n&lt;Button Name=\"btnChangeLogLevel\" \n Command=\"{Binding SetLogLevelCommand}\"\n CommandParameter=\"{Binding ElementName=cbxLogLevel, Path=Text}\" &gt;\n Change log level\n&lt;/Button&gt;\n</code></pre>\n" }, { "answer_id": 11425940, "author": "Sudhanshu Mishra", "author_id": 190476, "author_profile": "https://Stackoverflow.com/users/190476", "pm_score": 0, "selected": false, "text": "<p>I have tried using the RefreshSection method and got it to work using the following code sample:</p>\n\n<pre><code>class Program\n {\n static void Main(string[] args)\n {\n string value = string.Empty, key = \"mySetting\";\n Program program = new Program();\n\n program.GetValue(program, key);\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadLine();\n }\n\n /// &lt;summary&gt;\n /// Gets the value of the specified key from app.config file.\n /// &lt;/summary&gt;\n /// &lt;param name=\"program\"&gt;The instance of the program.&lt;/param&gt;\n /// &lt;param name=\"key\"&gt;The key.&lt;/param&gt;\n private void GetValue(Program program, string key)\n {\n string value;\n if (ConfigurationManager.AppSettings.AllKeys.Contains(key))\n {\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Key found, evaluating value...\");\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"Value read from app.confg for Key = {0} is {1}\", key, value);\n Console.WriteLine(\"--------------------------------------------------------------\");\n\n //// Update the value\n program.UpdateAppSettings(key, \"newValue\");\n //// Re-read from config file\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"New Value read from app.confg for Key = {0} is {1}\", key, value);\n }\n else\n {\n Console.WriteLine(\"Specified key not found in app.config\");\n }\n }\n\n /// &lt;summary&gt;\n /// Updates the app settings.\n /// &lt;/summary&gt;\n /// &lt;param name=\"key\"&gt;The key.&lt;/param&gt;\n /// &lt;param name=\"value\"&gt;The value.&lt;/param&gt;\n public void UpdateAppSettings(string key, string value)\n {\n Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\n if (configuration.AppSettings.Settings.AllKeys.Contains(key))\n {\n configuration.AppSettings.Settings[key].Value = value;\n }\n\n configuration.Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I dynamically reload the app.config in a .net Windows application? I need to turn logging on and off dynamically and not just based upon the value at application start. ConfigurationManager.RefreshSection("appSettings") does not work and I've also tried explicitly opening the config file using OpenExeConfiguration but I always get the cached value at application startup and not the current value. I've accepted the answer of creating a custom configuration section. As a side note and foolish mistake - if you're running from the IDE there's no point in updating the app.config file and expecting changes. Yuo have to modify the .exe.config file in the bin\debug folder. Doh!
You can refresh **your own** section the way you say: ``` ConfigurationManager.RefreshSection("yoursection/subsection"); ``` Just move a logging true/false into a section and you'll be fine.
272,109
<p>I have a csv file of the format:</p> <pre><code>270291014011 ED HARDY - TRUE TO MY LOVE - Cap NEU 2008 NEU 0,00 € 0,00 € 0 1 0 22.10.2008 03:37:10 21.11.2008 02:37:10 21.11.2008 02:42:10 50 0 0 0 39,99 € http://i7.ebayimg.com/02/i/001/16/0d/68af_1.JPG?set_id=800005007 0 2 8.10.2008 13:40:20 8.10.2008 13:40:20 80587 0 &lt;table bordercolordark="#999900" bordercolorlight="#666666" bgcolor="#ffffff" border="10" bordercolor="#666666" width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;blockquote&gt; &lt;div align="center"&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h1&gt;&lt;font size="6"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;100% ORGINAL MARKENWARE AUS DEN USA&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/h1&gt; &lt;p style="color: rgb(0, 0, 0);"&gt;&lt;font size="6"&gt;&lt;b&gt;&lt;font face="arial"&gt;ED HARDY&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/p&gt;&lt;p style="color: rgb(0, 0, 0);"&gt;&lt;b&gt;&lt;font face="arial" size="5"&gt;CAP&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;/div&gt;&lt;div style="text-align: center;"&gt;&lt;font size="5"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Style: TRUE ROSE&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Die Kollektion von der trend Marke Ed Hardy kreiert sportlich, hipe Mode die bei den Stars in Hollywood der absolute Renner ist. In diesem super Trucker Cap fallen Sie auf !!&amp;nbsp; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Dieses Cap ist nagelneu mit Etikett und&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt; 100% orginal.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;&lt;br&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Wir tragen die ebay Kosten und der Kaeufer die Versandkosten.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Versandkosten nach Europa sind folgend:&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;fuer unversicherten Versand 6,00 Euro&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;fuer versicherten Versand 12,00 Euro&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;br&gt; &lt;font size="5"&gt;&lt;span style="font-family: arial;"&gt;&lt;span style="font-weight: bold;"&gt;Bei paypal Bezahlungen akzeptieren wir nur noch versicherten Versand!&lt;/span&gt;&lt;/span&gt;&lt;/font&gt;&lt;br&gt;&lt;font size="5"&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Auf Ihren Wunsch versenden wir die Ware auch versichert. Ansonsten trägt das Risiko beim Versand der Käufer. &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial"&gt;Wir bitten um Ihre Zahlung innerhalb 10 Tage nach Auktionsende.&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;/font&gt;&lt;/div&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;div align="center"&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="#ff0000"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;marquee width="70%" bgcolor="#ffffff"&gt; &lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="#ff0000"&gt;Schauen Sie unbedingt bei unserem Shop "cheap-and-hip" vorbei!!!&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;/marquee&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;&lt;br&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;blockquote&gt; &lt;div align="center"&gt; &lt;center&gt; &lt;h1&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;Abwicklung Ihres Einkaufs bei uns&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h1&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="black" face="arial" size="5"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/center&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/div&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Jeder Käufer erhält innerhalb von 24 Stunden nach Auktionsende eine e-mail mit allen für die Kaufabwicklung relevanten Informationen. Sollten Sie nach 24 Stunden noch keine e-mail erhalten haben, setzen Sie sich bitte mit uns per e-mail in Verbindung. &lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Kauf von mehreren Artikeln&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Da das Porto aus den USA nach Gewicht berechnet wird, werden die Versandkosten beim Einkauf von mehreren Artikeln neu berechnet. Bitte teilen Sie uns per e-mail mit, wenn Sie mehrere Artikel ersteigert/gekauft haben, bzw. noch ersteigern/kaufen moechten, Sie erhalten von uns dann die kompletten Versandkosten. Die Kosten fuer den Versand werden von dem Kaeufer getragen. Die Versanddauer betraegt bei Luftversand zirka 5-10 Tage.&lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Versand&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Der Versand erfolgt innerhalb von 2-3 Werktagen nach Zahlungseingang (Gutschrift der Überweisung auf unserem Konto bei der Postbank oder bei paypal). Bitte beachten Sie, dass es je nach Kreditinstitut 2-4 Werktage dauern kann, bis Ihre Überweisung auf unserem Konto gutgeschrieben wird. Kreditkarten Gutbuchung ueber paypal erfolgt noch am gleichen Tag.&lt;br&gt;Als Betreff einer Ueberweisung muß unbedingt die eBay-Artikelnummer der Auktion angegeben werden. Ohne diese Information ist eine Zuordnung der Überweisung leider fast nicht möglich! &lt;br&gt;ZOLL: Bitte beachten Sie das Zollgebuehren anfallen koennen auch wenn es nur selten vorkommt sollten Sie sich mit den Einfuhrbestimmungen Ihres Landes vertraut machen. &lt;br&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;br&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Umtausch&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Wir tauschen gerne Ihren Artikel um sofern Sie die Ware innerhalb von 14 Tagen nach erhalt den Artikel uns wieder zuschicken. Wir nehmen nur ungetragene Ware zurueck und alle Etiketten muessen noch an dem Artikel befestigt sein&lt;br&gt;&lt;br&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Falls Sie Reklamationen haben&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/h2&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;Wir bitten bei Beanstandungen der Ware sich erst mit uns in Verbindung zu setzten. Wir pruefen unsere Ware immer auf Defekte aber es kann vorkommen das uns etwas entgeht und bevor Sie eine "negative Bewertung" abgeben moechten wir die Chance bekommen Sie zufrieden zustellen. &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;p&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt; &lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;center&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt;Vielen Dank fuer Ihr Intresse!&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/center&gt;&lt;p&gt;&lt;b&gt;&lt;font color="#990000" face="arial" size="5"&gt;&lt;font color="#ff0000"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;font color="black" face="arial" size="3"&gt;&lt;b&gt;&lt;font color="#ff0000" face="arial" size="5"&gt;&lt;br&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/font&gt;&lt;/b&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;/div&gt;&lt;/blockquote&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;br&gt;&lt;br&gt; 1 Baltimore 1 0 1 0 0 0,10 € 0,00 € 0,00 € 0 0 1 77 </code></pre> <p>I would like to know if there is an easy way with sed or awk to remove the HTML tags except for <code>&lt;p&gt;</code> tags. I would also like to know if it is possible for any link html embedding a Flash SWF file, to change the HTML automatically to link to this file.</p> <p>So, in essence, to replace any code such as</p> <pre><code>&lt;embed src="http://backend.supremeauction.com/app/gallery/loader.swf"&gt; </code></pre> <p>with something like <code>&lt;a href="http://backend.supremeauction.com/app/gallery/loader.swf"&gt;Click here for external description&lt;/a&gt;</code> and then remove all other HTML tags except for <code>&lt;p&gt;</code></p> <p>Is this even possible?</p>
[ { "answer_id": 272353, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": true, "text": "<p>Here's the Perl for removing the non-p tags--it won't work across lines though</p>\n\n<pre><code>perl -pe 's/&lt;\\/?(?&gt;[^p]|p\\w+)[^&gt;]*&gt;//ig'\n</code></pre>\n\n<p>That will print it out to standard out and you can redirect it from there. </p>\n\n<p>If you have only one link, you could do this:</p>\n\n<pre><code>perl -pe 's/&lt;embed\\s+src=\"(.*?\\.swf)\"\\/?&gt;/&lt;a href=\"$1\"&gt;Click here for external description&lt;\\/a&gt;/i;s/&lt;\\/?(?&gt;[^ap]|[ap]\\w+)[^&gt;]*&gt;//ig'\n</code></pre>\n" }, { "answer_id": 272376, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 1, "selected": false, "text": "<p>I came up with this, for sed:</p>\n\n<pre><code>sed -e 's/[&lt;][/][^Pp][^&gt;]*[&gt;]//g' -e 's/[&lt;][^/Pp][^&gt;]*[&gt;]//g' file\n</code></pre>\n" }, { "answer_id": 272478, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 0, "selected": false, "text": "<p>Use <A HREF=\"http://xmlstar.sf.net/\" rel=\"nofollow noreferrer\">xmlstarlet</A> to filter out the tags you want; as it knows XML syntax (which is considerably more complex than can be correctly captured in a regex), it isn't prone to failure in corner cases like nested tags, and can decode <code>&amp;amp;</code> and kin within elements correctly. The <code>select</code> subcommand will take XPath, so a trivial expression to find <code>A</code> elements will do what you want.</p>\n\n<p>The <code>format</code> subcommand has an option to take HTML as input, so you'll want to do an initial processing stage with that if your content isn't valid XHTML.</p>\n" }, { "answer_id": 273568, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 0, "selected": false, "text": "<p>If you want to do this in Perl, there are many HTML utility modules that can help you transform and filter HTML. Other languages probably have similar libraries. See, for instance, <a href=\"http://search.cpan.org/dist/HTML-Parser\" rel=\"nofollow noreferrer\">HTML::Parser</a>. You define handlers for the parts you want to affect. Once you get control of that part, you can transform it and decide how to output it. </p>\n\n<p>If you have very regular output that is generated by another program, you might be able to get away with a regex. However, whenever I've done that the regex starts to get pretty nasty as I find the special cases and exceptions.</p>\n\n<p>It sounds like you may be able to turn this problem around though. Are you really just trying to extract URLs and link to them? Instead of messing with the parsers, can you just pull out the URLs and write a completely new document without caring about the old one? Or maybe just completely replace a region with the larger document? </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
I have a csv file of the format: ``` 270291014011 ED HARDY - TRUE TO MY LOVE - Cap NEU 2008 NEU 0,00 € 0,00 € 0 1 0 22.10.2008 03:37:10 21.11.2008 02:37:10 21.11.2008 02:42:10 50 0 0 0 39,99 € http://i7.ebayimg.com/02/i/001/16/0d/68af_1.JPG?set_id=800005007 0 2 8.10.2008 13:40:20 8.10.2008 13:40:20 80587 0 <table bordercolordark="#999900" bordercolorlight="#666666" bgcolor="#ffffff" border="10" bordercolor="#666666" width="100%"> <tbody> <tr> <td><b><font color="#990000" face="arial" size="5"><br> </font></b><blockquote> <div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000"> </font></font></b><h1><font size="6"><b><font color="#990000" face="arial"><font color="#ff0000">100% ORGINAL MARKENWARE AUS DEN USA</font></font></b></font></h1> <p style="color: rgb(0, 0, 0);"><font size="6"><b><font face="arial">ED HARDY</font></b></font></p><p style="color: rgb(0, 0, 0);"><b><font face="arial" size="5">CAP<br></font></b></p></div><div style="text-align: center;"><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Style: TRUE ROSE<br></font></b></font></font></b><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Die Kollektion von der trend Marke Ed Hardy kreiert sportlich, hipe Mode die bei den Stars in Hollywood der absolute Renner ist. In diesem super Trucker Cap fallen Sie auf !!&nbsp; </font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Dieses Cap ist nagelneu mit Etikett und</font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"> 100% orginal.</font></b></font></font></b></font><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br><br></font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir tragen die ebay Kosten und der Kaeufer die Versandkosten.</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Versandkosten nach Europa sind folgend:</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer unversicherten Versand 6,00 Euro<br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer versicherten Versand 12,00 Euro</font></b></font></font></b></font><br> <font size="5"><span style="font-family: arial;"><span style="font-weight: bold;">Bei paypal Bezahlungen akzeptieren wir nur noch versicherten Versand!</span></span></font><br><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Auf Ihren Wunsch versenden wir die Ware auch versichert. Ansonsten trägt das Risiko beim Versand der Käufer. </font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir bitten um Ihre Zahlung innerhalb 10 Tage nach Auktionsende.</font></b></font></font></b><br></font></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><br> </font></b></font></font></b><div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000"> </font></font></b></font></font></b><marquee width="70%" bgcolor="#ffffff"> <h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000">Schauen Sie unbedingt bei unserem Shop "cheap-and-hip" vorbei!!!</font></font></b></font></font></b></h2></marquee><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br><b><font color="black" face="arial" size="5"><br> </font></b></font></font></font></b><blockquote> <div align="center"> <center> <h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5">Abwicklung Ihres Einkaufs bei uns</font></b></font></font></font></b></h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5"><br></font></b></font></font></font></b></center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br></font></font></font></b></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Jeder Käufer erhält innerhalb von 24 Stunden nach Auktionsende eine e-mail mit allen für die Kaufabwicklung relevanten Informationen. Sollten Sie nach 24 Stunden noch keine e-mail erhalten haben, setzen Sie sich bitte mit uns per e-mail in Verbindung. <br><br> </font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Kauf von mehreren Artikeln</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Da das Porto aus den USA nach Gewicht berechnet wird, werden die Versandkosten beim Einkauf von mehreren Artikeln neu berechnet. Bitte teilen Sie uns per e-mail mit, wenn Sie mehrere Artikel ersteigert/gekauft haben, bzw. noch ersteigern/kaufen moechten, Sie erhalten von uns dann die kompletten Versandkosten. Die Kosten fuer den Versand werden von dem Kaeufer getragen. Die Versanddauer betraegt bei Luftversand zirka 5-10 Tage.<br><br> </font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Versand</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Der Versand erfolgt innerhalb von 2-3 Werktagen nach Zahlungseingang (Gutschrift der Überweisung auf unserem Konto bei der Postbank oder bei paypal). Bitte beachten Sie, dass es je nach Kreditinstitut 2-4 Werktage dauern kann, bis Ihre Überweisung auf unserem Konto gutgeschrieben wird. Kreditkarten Gutbuchung ueber paypal erfolgt noch am gleichen Tag.<br>Als Betreff einer Ueberweisung muß unbedingt die eBay-Artikelnummer der Auktion angegeben werden. Ohne diese Information ist eine Zuordnung der Überweisung leider fast nicht möglich! <br>ZOLL: Bitte beachten Sie das Zollgebuehren anfallen koennen auch wenn es nur selten vorkommt sollten Sie sich mit den Einfuhrbestimmungen Ihres Landes vertraut machen. <br></font></font></font></font></b><br><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><br> </font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Umtausch</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir tauschen gerne Ihren Artikel um sofern Sie die Ware innerhalb von 14 Tagen nach erhalt den Artikel uns wieder zuschicken. Wir nehmen nur ungetragene Ware zurueck und alle Etiketten muessen noch an dem Artikel befestigt sein<br><br> </font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Falls Sie Reklamationen haben</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir bitten bei Beanstandungen der Ware sich erst mit uns in Verbindung zu setzten. Wir pruefen unsere Ware immer auf Defekte aber es kann vorkommen das uns etwas entgeht und bevor Sie eine "negative Bewertung" abgeben moechten wir die Chance bekommen Sie zufrieden zustellen. </font></font></font></font></b><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5"> </font></b></font></font></font></font></b></p><center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5">Vielen Dank fuer Ihr Intresse!</font></b></font></font></font></font></b></center><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5"><br></font></b></font></font></font></font></b></p></blockquote></div></blockquote></td></tr></tbody></table><br><br> 1 Baltimore 1 0 1 0 0 0,10 € 0,00 € 0,00 € 0 0 1 77 ``` I would like to know if there is an easy way with sed or awk to remove the HTML tags except for `<p>` tags. I would also like to know if it is possible for any link html embedding a Flash SWF file, to change the HTML automatically to link to this file. So, in essence, to replace any code such as ``` <embed src="http://backend.supremeauction.com/app/gallery/loader.swf"> ``` with something like `<a href="http://backend.supremeauction.com/app/gallery/loader.swf">Click here for external description</a>` and then remove all other HTML tags except for `<p>` Is this even possible?
Here's the Perl for removing the non-p tags--it won't work across lines though ``` perl -pe 's/<\/?(?>[^p]|p\w+)[^>]*>//ig' ``` That will print it out to standard out and you can redirect it from there. If you have only one link, you could do this: ``` perl -pe 's/<embed\s+src="(.*?\.swf)"\/?>/<a href="$1">Click here for external description<\/a>/i;s/<\/?(?>[^ap]|[ap]\w+)[^>]*>//ig' ```
272,124
<p>since JTree &amp; TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?</p> <p>Edit: (Answering my own question afterwards.) </p> <p>@Zarkonnen: Thanks for the getTooltipText idea. </p> <p>I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it:</p> <pre><code>public class JTreeWithToolTips { private static class OwnRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { setToolTipText("foobar" + row); return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } } public static void main(String[] args) { JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" }); tree.setCellRenderer(new OwnRenderer()); ToolTipManager.sharedInstance().registerComponent(tree); JFrame frame = new JFrame(); frame.getContentPane().add(tree); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } </code></pre>
[ { "answer_id": 272181, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 5, "selected": true, "text": "<p>See <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/swing/JTree.html#getToolTipText(java.awt.event.MouseEvent)\" rel=\"nofollow noreferrer\">getTooltipText</a> on JTree. This should allow you to show tooltips depending on what in the tree is being hovered over. (Do read the docs though, you need to register the JTree with the ToolTipManager.)</p>\n" }, { "answer_id": 1774609, "author": "Agustin", "author_id": 215965, "author_profile": "https://Stackoverflow.com/users/215965", "pm_score": 1, "selected": false, "text": "<p>Yeah, you can use <code>onMouseMoved</code> and then use a method (I don't remember the name) that tells you in which node you are over. If you get null, obviously then you are not over a node.</p>\n" }, { "answer_id": 46084789, "author": "Matthieu", "author_id": 1098603, "author_profile": "https://Stackoverflow.com/users/1098603", "pm_score": 1, "selected": false, "text": "<p>When dealing with specific <code>TreeNode</code> subclasses, based on your own answer and comments, I came up with an interface for my <code>TreeNode</code> to implement.</p>\n\n<p>Notice how we check if the <code>value</code> is an intance of <code>Tooltipable</code> in the <code>TreeCellRenderer</code>:</p>\n\n<pre><code>public static interface Tooltipable {\n public String getToolTip();\n}\n\npublic static class TheNode extends DefaultMutableTreeNode implements Tooltipable {\n\n private String shortDesc, longDesc;\n\n public TheNode(String shortDesc, String longDesc) {\n super();\n this.shortDesc = shortDesc;\n this.longDesc = longDesc;\n }\n\n @Override\n public String getToolTip() {\n return longDesc;\n }\n\n @Override\n public String toString() {\n return shortDesc;\n }\n}\n\npublic static class TheModel extends DefaultTreeModel {\n public TheModel() {\n super(new TheNode(\"Root\", \"The base of everything\"));\n TheNode root = (TheNode)getRoot();\n root.add(new TheNode(\"Second\", \"I am a number two\"));\n TheNode node = new TheNode(\"Third\", \"Another one bites the dust\");\n root.add(node);\n node.add(new TheNode(\"Last\", null)); // No tooltip for this one\n }\n}\n\npublic static class TreeTooltipRenderer extends DefaultTreeCellRenderer {\n @Override\n public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {\n if (value instanceof Tooltipable)\n setToolTipText(((Tooltipable)value).getToolTip());\n return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);\n }\n}\n\npublic static void main(String[] args) {\n JFrame frame = new JFrame();\n frame.setBounds(100, 100, 300, 300);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JTree tree = new JTree(new TheModel());\n ToolTipManager.sharedInstance().registerComponent(tree);\n tree.setCellRenderer(new TreeTooltipRenderer());\n frame.add(new JScrollPane(tree), BorderLayout.CENTER);\n frame.setVisible(true);\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28482/" ]
since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree? Edit: (Answering my own question afterwards.) @Zarkonnen: Thanks for the getTooltipText idea. I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it: ``` public class JTreeWithToolTips { private static class OwnRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { setToolTipText("foobar" + row); return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } } public static void main(String[] args) { JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" }); tree.setCellRenderer(new OwnRenderer()); ToolTipManager.sharedInstance().registerComponent(tree); JFrame frame = new JFrame(); frame.getContentPane().add(tree); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } ```
See [getTooltipText](http://docs.oracle.com/javase/7/docs/api/javax/swing/JTree.html#getToolTipText(java.awt.event.MouseEvent)) on JTree. This should allow you to show tooltips depending on what in the tree is being hovered over. (Do read the docs though, you need to register the JTree with the ToolTipManager.)
272,131
<h2>Setup</h2> <p>I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other.</p> <p>However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen.</p> <h2>Desire</h2> <p>What I'd like to be able to do, but have not figured out a way yet, is to put all the feeds linearly into the page, and have:</p> <ul> <li>a 'pre-built' multicolumn view where the feeds would "balance" themselves into the columns</li> </ul> <p>which leads me to:</p> <ul> <li>the number of columns change depending on how wide the screen is currently\</li> </ul> <p>This is akin to how word processing applications handle columnar layouts.</p> <h2>Question</h2> <p>I presume that I will need to implement some form of AJAXy happiness, but currently know very little about Javascript.</p> <p>Is there a way to do this with <strong><em>just</em></strong> CSS/HTML/PHP?</p> <p>If not, how should I go about solving this?</p> <p><br/></p> <h3>final solution:</h3> <p>(based on <a href="https://stackoverflow.com/a/272183/4418">@warpr</a>'s and <a href="https://stackoverflow.com/a/272229/4418">@joh6nn</a>'s answers)</p> <pre><code>#rss {min-width: 10em; max-width: 25em; min-height: 15em; max-height: 25em; font-size: .97em; float: left; } </code></pre>
[ { "answer_id": 272183, "author": "warp", "author_id": 7700, "author_profile": "https://Stackoverflow.com/users/7700", "pm_score": 3, "selected": true, "text": "<p>You probably cannot get what you want with just CSS/HTML, but you can get somewhat close.</p>\n\n<p>A trick I used for a photo album is this:</p>\n\n<ol>\n<li>Make sure each feed has a fixed width, I would recommend something like '20em';</li>\n<li>Make sure each feed has the same height.</li>\n<li>Float everything left.</li>\n</ol>\n\n<p>Because each div has the same dimensions, when they're floated left they will form a grid with exactly the number of columns that will fit in your browser.</p>\n\n<p>Unless you actually fix the height of the divs and use CSS to clip the content, you will need javascript for step 2, what I did was:</p>\n\n<ol>\n<li>Iterate over each feed div, finding the tallest div.</li>\n<li>Iterate over each div again, changing the height to match the div found in the first step.</li>\n</ol>\n\n<p>This is fairly easy to implement, but is obviously not optimal. I look forward to reading any better solutions posted here :)</p>\n" }, { "answer_id": 272229, "author": "joh6nn", "author_id": 21837, "author_profile": "https://Stackoverflow.com/users/21837", "pm_score": 1, "selected": false, "text": "<p>you might be able to do this with lists; i've never tried it, so i'm not sure.</p>\n\n<p>if you make list items display:inline, the list becomes horizontal instead of vertical. from there, if you stuff the list into a containing element and fiddle with the padding and margins, you may be able to get the list to line-warp, like text: again, i've never tried that, so i don't know.</p>\n\n<p>if this technique works, i'd be very interested to hear about it.</p>\n" }, { "answer_id": 272351, "author": "Raithlin", "author_id": 6528, "author_profile": "https://Stackoverflow.com/users/6528", "pm_score": 0, "selected": false, "text": "<p>The only way I can think of is a mixture of dynamic CSS and javascript. Every time a column (feed) is added, use the javascript to rewrite the width (in percentage) of each div. </p>\n\n<p>jQuery would come in handy here.</p>\n\n<pre><code>var columns = $(\".feed\").size();\nvar size = 100/columns;\n$(\".feed\").css(\"width\",size+\"%\");\n</code></pre>\n\n<p>Someone feel free to correct me if I'm wrong. My jQuery is a little wobbly.</p>\n\n<p>Of course, if you're not using AJAX, you could implement the same solution entirely in PHP.</p>\n" }, { "answer_id": 274595, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 0, "selected": false, "text": "<p>You could also use this jQuery javascript (you will need the jQuery library).</p>\n\n<pre><code>var docwidth = $(document).width();\nvar numOfCollums = $('.feed').length;\nvar colWidth = docwidth/numOfCollums;\n$('.feed').each( function() {\n $(this).width(colWidth);\n});\n</code></pre>\n\n<p>Which would set the column width dynamically.</p>\n\n<p>For this to work your columns should have the class 'feed'</p>\n\n<p>EDIT:</p>\n\n<p>You should style your divs something like this:</p>\n\n<pre><code>.feed{\n float:left;\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4418/" ]
Setup ----- I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other. However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen. Desire ------ What I'd like to be able to do, but have not figured out a way yet, is to put all the feeds linearly into the page, and have: * a 'pre-built' multicolumn view where the feeds would "balance" themselves into the columns which leads me to: * the number of columns change depending on how wide the screen is currently\ This is akin to how word processing applications handle columnar layouts. Question -------- I presume that I will need to implement some form of AJAXy happiness, but currently know very little about Javascript. Is there a way to do this with ***just*** CSS/HTML/PHP? If not, how should I go about solving this? ### final solution: (based on [@warpr](https://stackoverflow.com/a/272183/4418)'s and [@joh6nn](https://stackoverflow.com/a/272229/4418)'s answers) ``` #rss {min-width: 10em; max-width: 25em; min-height: 15em; max-height: 25em; font-size: .97em; float: left; } ```
You probably cannot get what you want with just CSS/HTML, but you can get somewhat close. A trick I used for a photo album is this: 1. Make sure each feed has a fixed width, I would recommend something like '20em'; 2. Make sure each feed has the same height. 3. Float everything left. Because each div has the same dimensions, when they're floated left they will form a grid with exactly the number of columns that will fit in your browser. Unless you actually fix the height of the divs and use CSS to clip the content, you will need javascript for step 2, what I did was: 1. Iterate over each feed div, finding the tallest div. 2. Iterate over each div again, changing the height to match the div found in the first step. This is fairly easy to implement, but is obviously not optimal. I look forward to reading any better solutions posted here :)
272,153
<p>If I define a struct in C# using automatic properties like this:</p> <pre><code>public struct Address { public Address(string line1, string line2, string city, string state, string zip) { Line1 = line1; Line2 = line2; City = city; State = state; Zip = zip; } public string Line1 { get; protected set; } public string Line2 { get; protected set; } public string City { get; protected set; } public string State { get; protected set; } public string Zip { get; protected set; } } </code></pre> <p>When I attempt to build the file, I get a compilation error saying <code>The 'this' object cannot be used before all of its fields are assigned to</code>. This can be solved by changing the constructor to make a chained call to the default constructor like this:</p> <pre><code>public Address(string line1, string line2, string city, string state, string zip): this() { Line1 = line1; Line2 = line2; City = city; State = state; Zip = zip; } </code></pre> <p>My question is, why does this work, and what is happening? I have a guess, and I tried to prove it by looking at IL, but I'm only kidding myself if I think I can break down IL. But my guess is, auto properties work by having the compiler generate fields for your properties behind the scenes. Those fields cannot be accessed through code, all setting and getting must be done through the properties. When creating a struct, a default constructor cannot be explicitly defined. So behind the scenes, the compiler must be generating a default constructor that sets the values of the fields that the developer can't see.</p> <p>Any and all IL wizards are welcome to prove or disprove my theory.</p>
[ { "answer_id": 272164, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p><strong>Note: as of C# 6, this isn't required - but you should be using read-only automatically-implemented properties with C# 6 anyway...</strong></p>\n\n<p><code>this()</code> makes sure that the fields are definitely assigned as far as the compiler is concerned - it sets all fields to their default values. You have to have a fully constructed struct before you can start accessing <em>any</em> properties.</p>\n\n<p>It's annoying, but that's the way it is. Are you sure you really want this to be a struct though? And why use a protected setter on a struct (which can't be derived from)?</p>\n" }, { "answer_id": 12676594, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "<p>A property is nothing more than an encapsulation of a <code>Get</code> method and/or a <code>Set</code> method. The CLR has metadata which indicates that particular methods should be regarded as being a properties, meaning compilers should allow some constructs which it would not allow with methods. For example, if <code>X</code> is a read-write property of <code>Foo</code>, a compiler will translate <code>Foo.X += 5</code> into <code>Foo.SET_X_METHOD(Foo.GET_X_METHOD() + 5)</code> (though the methods are named differently, and are not generally accessible by name).</p>\n\n<p>Although an autoproperty implements a pair of get/set methods which access a private field in such a way as to behave more or less like a field, from the point of view of any code outside the property, an autoproperty is a pair of get/set methods just like any other property. Consequently, a statement like <code>Foo.X = 5;</code> is translated as <code>Foo.SET_X_METHOD(5)</code>. Since the C# compiler just sees that as a method call, and since methods do not include any metadata to indicate what fields they read or write, the compiler will forbid the method call unless it knows every field of <code>Foo</code> has been written.</p>\n\n<p>Personally, my advice would be to avoid the use of autoproperties with structure types. Autoproperties make sense with classes, since it's possible for class properties to support features like update notifications. Even if early versions of a class do not support update notifications, having those versions use an autoproperty rather than a field will mean that future versions can add update-notification features without requiring consumers of the class to be reworked. Structures, however, cannot meaningfully support most of the types of features that one might wish to add to field-like properties.</p>\n\n<p>Further, the performance differences between fields and properties is much greater with large structures than it is with class types. Indeed, much of the recommendation to avoid large structures is a consequence of this difference. Large structures can actually be very efficient, if one avoids copying them unnecessarily. Even if one had an enormous structure <code>HexDecet&lt;HexDecet&lt;HexDecet&lt;Integer&gt;&gt;&gt;</code>, where <code>HexDecet&lt;T&gt;</code> contained exposed fields <code>F0</code>..<code>F15</code> of type <code>T</code>, a statement like <code>Foo = MyThing.F3.F6.F9;</code> would simply require reading one integer from <code>MyThing</code> and storing it to <code>Foo</code>, even though <code>MyThing</code> would by huge by struct standards (4096 integers occupying 16K). Additionally, one could update that element very easily, e.g. <code>MyThing.F3.F6.F9 += 26;</code>. By contrast, if <code>F0</code>..<code>F15</code> were auto-properties, the statement <code>Foo = MyThing.F3.F6.F9</code> would require copying 1K of data from <code>MyThing.F3</code> to a temporary (call it <code>temp1</code>, then 64 bytes of data from <code>temp1.F6</code> to <code>temp2</code>) before finally getting around to reading 4 bytes of data from <code>temp2.F9</code>. Ick. Worse, trying to add 26 to the value in <code>MyThing.F3.F6.F9</code> would require something like <code>var t1 = MyThing.F3; var t2 = t1.F6; t2.F9 += 26; t1.F6 = f2; MyThing.F3 = t1;</code>.</p>\n\n<p>Many of the long-standing complaints about \"mutable structure types\" are really complaints about structure types with read/write properties. Simply replace properties with fields and the problems go away.</p>\n\n<p>PS: There are times it can be useful to have a structure whose properties access a class object to which it holds a reference. For example, it would be nice to have a version of an <code>ArraySegment&lt;T&gt;</code> class which allowed one to say <code>Var foo[] = new int[100]; Var MyArrSeg = New ArraySegment&lt;int&gt;(foo, 25, 25); MyArrSeg[6] += 9;</code>, and have the last statement add nine to element (25+6) of <code>foo</code>. In older versions of C# one could do that. Unfortunately, the frequent use of autoproperties in the Framework where fields would have been more appropriate led to widespread complaints about the compiler allowing property setters to be called uselessly on read-only structures; consequently, calling any property setter on a read-only structure is now forbidden, whether or not the property setter would actually modify any fields of the struct. If people had simply refrained from making structs mutable via property setters (making fields directly accessible when mutability was appropriate) compilers would never have had to implement that restriction.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6146/" ]
If I define a struct in C# using automatic properties like this: ``` public struct Address { public Address(string line1, string line2, string city, string state, string zip) { Line1 = line1; Line2 = line2; City = city; State = state; Zip = zip; } public string Line1 { get; protected set; } public string Line2 { get; protected set; } public string City { get; protected set; } public string State { get; protected set; } public string Zip { get; protected set; } } ``` When I attempt to build the file, I get a compilation error saying `The 'this' object cannot be used before all of its fields are assigned to`. This can be solved by changing the constructor to make a chained call to the default constructor like this: ``` public Address(string line1, string line2, string city, string state, string zip): this() { Line1 = line1; Line2 = line2; City = city; State = state; Zip = zip; } ``` My question is, why does this work, and what is happening? I have a guess, and I tried to prove it by looking at IL, but I'm only kidding myself if I think I can break down IL. But my guess is, auto properties work by having the compiler generate fields for your properties behind the scenes. Those fields cannot be accessed through code, all setting and getting must be done through the properties. When creating a struct, a default constructor cannot be explicitly defined. So behind the scenes, the compiler must be generating a default constructor that sets the values of the fields that the developer can't see. Any and all IL wizards are welcome to prove or disprove my theory.
**Note: as of C# 6, this isn't required - but you should be using read-only automatically-implemented properties with C# 6 anyway...** `this()` makes sure that the fields are definitely assigned as far as the compiler is concerned - it sets all fields to their default values. You have to have a fully constructed struct before you can start accessing *any* properties. It's annoying, but that's the way it is. Are you sure you really want this to be a struct though? And why use a protected setter on a struct (which can't be derived from)?
272,157
<p>I have a triangle mesh that has no texture, but a set color (sort of blue) and alpha (0.7f). This mesh is run time generated and the normals are correct. I find that with lighting on, the color of my object changes as it moves around the level. Also, the lighting doesn't look right. When I draw this object, this is the code:</p> <pre><code>glEnable( GL_COLOR_MATERIAL ); float matColor[] = { cur-&gt;GetRed(), cur-&gt;GetGreen(), cur-&gt;GetBlue(), cur-&gt;GetAlpha() }; float white[] = { 0.3f, 0.3f, 0.3f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matColor); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white); </code></pre> <p>Another odd thing I noticed is that the lighting fails, when I disable <code>GL_FRONT_AND_BACK</code> and use just <code>GL_FRONT</code> or <code>GL_BACK</code>. Here is my lighting setup (done once at beginning of renderer):</p> <pre><code>m_lightAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f }; m_lightSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; m_lightPosition[] = { 0.0f, 1200.0f, 0.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient); glLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular); glLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition); </code></pre> <p>EDIT: I've done a lot to make the normals "more" correct (since I am generating the surface myself), but the objects color still changes depending where it is. Why is this? Does openGL have some special environment blending I don't know about?</p> <p>EDIT: Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, <code>glMaterialfv</code> was blending with it.</p>
[ { "answer_id": 272171, "author": "mwahab", "author_id": 35485, "author_profile": "https://Stackoverflow.com/users/35485", "pm_score": 1, "selected": false, "text": "<p>If your lighting fails when GL_FRONT_AND_BACK is disabled it's possible that your normals are flipped. </p>\n" }, { "answer_id": 272258, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 0, "selected": false, "text": "<p>If your triangles are alpha-blended, won't you have to sort your faces by z-order from the camera? Otherwise you could be rendering a face at the back of the object on top of a face at the front.</p>\n" }, { "answer_id": 272786, "author": "Sebastian", "author_id": 29909, "author_profile": "https://Stackoverflow.com/users/29909", "pm_score": 1, "selected": false, "text": "<p>Could you post the code that initializes OpenGL? You're saying that all other meshes are drawn perfectly? Are you rendering them simultanously?</p>\n" }, { "answer_id": 277381, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": 0, "selected": false, "text": "<p>@sebastion:\nmultiple draw calls, each object gets a glDrawArrays. some are textured, some colored, all with normals. gl init code is:\n glMatrixMode(GL_MODELVIEW);</p>\n\n<pre><code>// Vertices!\nglEnableClientState(GL_VERTEX_ARRAY);\n\n// Depth func\nglEnable(GL_DEPTH_TEST);\nglDepthFunc( GL_LESS );\n\n// Enable alpha blending\nglEnable(GL_BLEND);\nglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n// Lighting\nglEnable(GL_LIGHTING);\nglEnable(GL_LIGHT0);\nglLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient);\nglLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular);\nglLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition);\n\n// Culling\nglDisable( GL_CULL_FACE );\n// Smooth Shading\nglShadeModel(GL_SMOOTH);\n\nm_glSetupDone = true;\n</code></pre>\n\n<p>after this i have some camera set up, but thats completely standard, projection mode, frustum, modelview, look at, translate.</p>\n" }, { "answer_id": 277421, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 1, "selected": false, "text": "<p>@response to stusmith:</p>\n\n<p>Z-testing won't help you with transparent triangles, you'll need per-triangle alpha sorting too. If you have an object that at any time could have overlapping triangles facing the camera (a concave object) you must draw the farthest triangles first to ensure blending is performed correctly, since Z-testing doesn't take transparency into account.\nConsider these two overlapping (and transparent) triangles and think about what happens when that little overlapped region is drawn, with or without Z-testing. You'll probably reach the conclusion that the drawing order does, in fact, matter. Transparency sucks :P</p>\n\n<pre><code> /\\ /\\\n / \\ / \\\n / \\/ \\\n / /\\ \\\n/_____/__\\_____\\\n</code></pre>\n\n<p>I'm not convinced that this is your problem, but alpha sorting is something you need to take into account when dealing with partly transparent objects.</p>\n" }, { "answer_id": 413184, "author": "Manuel", "author_id": 50770, "author_profile": "https://Stackoverflow.com/users/50770", "pm_score": 0, "selected": false, "text": "<p>Are you sure your normals are <strong>normalized</strong>?\nIf not and you are specifying normals via glNormal calls, you could try to let OpenGL do the normalization for you, keep in mind that this should be avoided, but you can test it out:</p>\n\n<pre><code>glEnable(GL_NORMALIZE);\n</code></pre>\n\n<p>This way you are telling OpenGL to rescale all the normal vectors supplied via glNormal.</p>\n" }, { "answer_id": 58925641, "author": "Alex", "author_id": 12394900, "author_profile": "https://Stackoverflow.com/users/12394900", "pm_score": 0, "selected": false, "text": "<p>I had a transparency issue on my terrain display, slopes would seem transparent when looked from a certain angle. It only happened when lighting was enabled in the shader. Turns out that I had not turned on depth testing, and from a certain angle the terrain was overwritten by other terrain and displaying semi-transparent. </p>\n\n<p>TLDR; check if you have depth testing enabled, having it off may give transparency-like effects when lighting is involved.\n<a href=\"https://learnopengl.com/Advanced-OpenGL/Depth-testing\" rel=\"nofollow noreferrer\">https://learnopengl.com/Advanced-OpenGL/Depth-testing</a></p>\n" }, { "answer_id": 58948174, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": 2, "selected": true, "text": "<p>Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, glMaterialfv was blending with it.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25893/" ]
I have a triangle mesh that has no texture, but a set color (sort of blue) and alpha (0.7f). This mesh is run time generated and the normals are correct. I find that with lighting on, the color of my object changes as it moves around the level. Also, the lighting doesn't look right. When I draw this object, this is the code: ``` glEnable( GL_COLOR_MATERIAL ); float matColor[] = { cur->GetRed(), cur->GetGreen(), cur->GetBlue(), cur->GetAlpha() }; float white[] = { 0.3f, 0.3f, 0.3f, 1.0f }; glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matColor); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white); ``` Another odd thing I noticed is that the lighting fails, when I disable `GL_FRONT_AND_BACK` and use just `GL_FRONT` or `GL_BACK`. Here is my lighting setup (done once at beginning of renderer): ``` m_lightAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f }; m_lightSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; m_lightPosition[] = { 0.0f, 1200.0f, 0.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient); glLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular); glLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition); ``` EDIT: I've done a lot to make the normals "more" correct (since I am generating the surface myself), but the objects color still changes depending where it is. Why is this? Does openGL have some special environment blending I don't know about? EDIT: Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, `glMaterialfv` was blending with it.
Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, glMaterialfv was blending with it.
272,159
<p>I have the following one route, registered in my global.asax.</p> <pre><code>routes.MapRoute( "Home", // Unique name "", // Root url new { controller = "Home", action = "Index", tag = string.Empty, page = 1 } ); </code></pre> <p>kewl. when I start the site, it correctly picks up this route.</p> <p>Now, when I try to programmatically do the following, it returns NULL.</p> <pre><code>var pageLinkValueDictionary = new RouteValueDictionar(linkWithoutPageValuesDictionary) {{"page", 2}}; VirtualPathData virtualPathData = RouteTable.Routes.GetVirtualPath(viewContext, "Home" pageLinkValueDictionary); // NOTE: pageLinkValueDictionary == // Key: Action, Value: Index; Key: page, Value: 2 </code></pre> <p>Why would this be happening?</p> <p>I was under the impression that it would find the Home route but append any values not found as query string items?</p> <h2>Update</h2> <p>Still no luck with this. Also, using the <a href="https://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6&amp;displaylang=en" rel="nofollow noreferrer">MVC RC</a>, I now need to change the viewContext to veiwContext.RequestContext .. which compiles but I'm still getting a null result.</p> <h2>Update 2</h2> <p>When I have the route without the <code>page=1</code> default item, the route <em>IS FOUND</em>. eg.</p> <pre><code>routes.MapRoute( "Home", "", new { controller = "Post", action = "Index", tags = string.Empty } ); </code></pre> <p>.. and <code>RouteTable.Routes.GetVirtualPath</code> returns a <code>VirtualPathData</code> instance. When I add the <code>page=1</code> (default value) back in, the <code>VirtualPathData</code> instance returned is null?</p>
[ { "answer_id": 272527, "author": "Torkel", "author_id": 24425, "author_profile": "https://Stackoverflow.com/users/24425", "pm_score": 2, "selected": true, "text": "<p>Well the reason it returns null is because there is no route with a \"page\" route data. </p>\n\n<p>Could you expand a little bit on what you are trying to achieve? If you want to redirect to a page with the url /page/2 or /?page=2 , then you should be using RedirectToRoute or RedirectToAction: </p>\n\n<pre><code>return RedirectToRoute(\"IndexDefault\", new {page = \"2\"}); \n</code></pre>\n" }, { "answer_id": 272917, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>I think your route should be like this:</p>\n\n<pre><code>route.MapRoute(\"theRoute\", \"{controller}/{action}/{tag}/{page}\",\n new { controller=\"Post\", action=\"Index\", tag=\"\", page=1 });\n</code></pre>\n\n<p>or (depending on what the full URL should look like)...</p>\n\n<pre><code>route.MapRoute(\"theRoute\", \"/{tag}/{page}\",\n new { controller=\"Post\", action=\"Index\", tag=\"\", page=1 });\n</code></pre>\n\n<p>This will still match a request to <a href=\"http://mysite.com/\" rel=\"nofollow noreferrer\">http://mysite.com/</a> and go to your default route values defined above. But now when you specify a tag or page, you'll get the url you wanted.</p>\n" }, { "answer_id": 274396, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 0, "selected": false, "text": "<p>You should check out Phil's Route Tester:</p>\n\n<p><a href=\"http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx\" rel=\"nofollow noreferrer\">ASP.NET Routing Debugger</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
I have the following one route, registered in my global.asax. ``` routes.MapRoute( "Home", // Unique name "", // Root url new { controller = "Home", action = "Index", tag = string.Empty, page = 1 } ); ``` kewl. when I start the site, it correctly picks up this route. Now, when I try to programmatically do the following, it returns NULL. ``` var pageLinkValueDictionary = new RouteValueDictionar(linkWithoutPageValuesDictionary) {{"page", 2}}; VirtualPathData virtualPathData = RouteTable.Routes.GetVirtualPath(viewContext, "Home" pageLinkValueDictionary); // NOTE: pageLinkValueDictionary == // Key: Action, Value: Index; Key: page, Value: 2 ``` Why would this be happening? I was under the impression that it would find the Home route but append any values not found as query string items? Update ------ Still no luck with this. Also, using the [MVC RC](https://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6&displaylang=en), I now need to change the viewContext to veiwContext.RequestContext .. which compiles but I'm still getting a null result. Update 2 -------- When I have the route without the `page=1` default item, the route *IS FOUND*. eg. ``` routes.MapRoute( "Home", "", new { controller = "Post", action = "Index", tags = string.Empty } ); ``` .. and `RouteTable.Routes.GetVirtualPath` returns a `VirtualPathData` instance. When I add the `page=1` (default value) back in, the `VirtualPathData` instance returned is null?
Well the reason it returns null is because there is no route with a "page" route data. Could you expand a little bit on what you are trying to achieve? If you want to redirect to a page with the url /page/2 or /?page=2 , then you should be using RedirectToRoute or RedirectToAction: ``` return RedirectToRoute("IndexDefault", new {page = "2"}); ```
272,161
<p>When I write code like this in VS 2008:<br><br></p> <pre><code>.h struct Patterns { string ptCreate; string ptDelete; string ptDrop; string ptUpdate; string ptInsert; string ptSelect; }; class QueryValidate { string query; string pattern; static Patterns pts; public: friend class Query; QueryValidate(const string&amp; qr, const string&amp; ptn): query(qr), pattern(ptn) {} bool validate() { boost::regex rg(pattern); return boost::regex_match(query, rg); } virtual ~QueryValidate() {} }; </code></pre> <p>I then initialize my structure like this: </p> <pre><code>.cpp string QueryValidate::pts::ptCreate = "something"; string QueryValidate::pts::ptDelete = "something"; //... </code></pre> <p>The compiler gives the following errors: </p> <blockquote> <p>'Patterns': the symbol to the left of a '::' must be a type 'ptSelect' : is not a member of 'QueryValidate'</p> </blockquote> <p>What am I doing wrong? Is this a problem with Visual Studio or with my code? I know that static members except for const ones must be defined outside the class they were declared in.</p>
[ { "answer_id": 272240, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 4, "selected": true, "text": "<p>You're trying to create a non-static member (ptCreate) of a static member (pts). This won't work like this.</p>\n\n<p>You got two options, either use a struct initializer list for the Patterns class.</p>\n\n<pre><code>Patterns QueryValidate::pts = {\"CREATE\", \"DELETE\"}; // etc. for every string\n</code></pre>\n\n<p>Or, much safer (and better in my opinion), provide a constructor in Patterns and call that one.</p>\n\n<pre><code>struct Patterns {\n Patterns() { /*...*/ }\n /* ... */\n}\n</code></pre>\n\n<p>On a side not, your code wouldn't work in any C++ compiler, it's not a conflict with Visual Studio things.</p>\n" }, { "answer_id": 272247, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 1, "selected": false, "text": "<p>This isn't valid C++. In the cpp file you're declaring parts of the static structure \"QueryValidate::pts\", but that's not allowed: you've got to declare the whole structure, like so:</p>\n\n<p>Patterns QueryValidate::pts;</p>\n\n<p>if you want members to be initialized, you either initialize them in another method, or add a constructor to Patterns that takes whatever initialization arguments you want.</p>\n" }, { "answer_id": 272295, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 2, "selected": false, "text": "<p>You can only initialize the structure as a whole, as in:</p>\n\n<pre><code>Patterns QueryValidate::pts = { \"something\", \"something\", ... };\n</code></pre>\n" }, { "answer_id": 272336, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 0, "selected": false, "text": "<p>I'm not real sure what you are trying to do here. It looks kind of like you are trying to declare and initialize each field in pts separately, rather than declare pts once as a single object. I'm really surprised VS lets you do that.</p>\n\n<p>What worked for me in gcc was the following:</p>\n\n<pre><code>Patterns QueryValidate::pts;\n\nvoid foo () {\n QueryValidate::pts.ptCreate = \"something\";\n QueryValidate::pts.ptDelete = \"something\";\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
When I write code like this in VS 2008: ``` .h struct Patterns { string ptCreate; string ptDelete; string ptDrop; string ptUpdate; string ptInsert; string ptSelect; }; class QueryValidate { string query; string pattern; static Patterns pts; public: friend class Query; QueryValidate(const string& qr, const string& ptn): query(qr), pattern(ptn) {} bool validate() { boost::regex rg(pattern); return boost::regex_match(query, rg); } virtual ~QueryValidate() {} }; ``` I then initialize my structure like this: ``` .cpp string QueryValidate::pts::ptCreate = "something"; string QueryValidate::pts::ptDelete = "something"; //... ``` The compiler gives the following errors: > > 'Patterns': the symbol to the left of a '::' must be a type 'ptSelect' > : is not a member of 'QueryValidate' > > > What am I doing wrong? Is this a problem with Visual Studio or with my code? I know that static members except for const ones must be defined outside the class they were declared in.
You're trying to create a non-static member (ptCreate) of a static member (pts). This won't work like this. You got two options, either use a struct initializer list for the Patterns class. ``` Patterns QueryValidate::pts = {"CREATE", "DELETE"}; // etc. for every string ``` Or, much safer (and better in my opinion), provide a constructor in Patterns and call that one. ``` struct Patterns { Patterns() { /*...*/ } /* ... */ } ``` On a side not, your code wouldn't work in any C++ compiler, it's not a conflict with Visual Studio things.
272,190
<p>I basically created some tables to play around with: I have Two main tables, and a Many-Many join table. Here is the DDL: (I am using HSQLDB)</p> <pre><code>CREATE TABLE PERSON ( PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, NAME VARCHAR(50), MAIN_PERSON_ID INTEGER ) CREATE TABLE JOB ( JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, NAME VARCHAR(50) ) CREATE TABLE JOB_PERSON ( PERSON_ID INTEGER, JOB_ID INTEGER ) ALTER TABLE JOB_PERSON ADD CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID) REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE ALTER TABLE JOB_PERSON ADD CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID) REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE ALTER TABLE PERSON ADD CONSTRAINT FK_PERSON_PERSON FOREIGN KEY(MAIN_PERSON_ID) REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE insert into person values(null,'Arthur', null); insert into person values(null,'James',0); insert into job values(null, 'Programmer') insert into job values(null, 'Manager') insert into job_person values(0,0); insert into job_person values(0,1); insert into job_person values(1,1); </code></pre> <p>I want to create a delete statement that deletes orphans from JOB (if there exists only one entry in the join table for a specific job) based on the PERSON.PERSON_ID. </p> <p>In pseudo language: </p> <pre><code>delete from job where job_person.job_id=job.job_id AND count(job_person.job_id)=1 AND job_person.person_id=X </code></pre> <p>Where X is some person_id. I have tried a lot of different ways; I think it is the "COUNT" part that is causing problems. I am an SQL rookie, so any help would be much appreciated.</p>
[ { "answer_id": 272243, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "<p>I'm not following.</p>\n\n<p>You cannot delete <code>JOB</code> rows which have <code>JOB_PERSON</code> rows (even one) because of your FK contraints. Thus there is no way to delete <code>JOB</code> rows based on <code>PERSON</code> rows.</p>\n\n<p><code>JOB_PERSON</code> rows have to be deleted before either a <code>JOB</code> or <code>PERSON</code> can be deleted.</p>\n\n<p>If you want to delete all <code>JOB</code> rows with no <code>JOB_PERSON</code>, then one way is:</p>\n\n<pre><code>DELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n</code></pre>\n\n<p>If you want to delete all <code>JOB_PERSON</code> rows for a particular person and then all orphans, do it in two steps:</p>\n\n<pre><code>DELETE FROM JOB_PERSON\nWHERE PERSON_ID = X\n\nDELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n</code></pre>\n\n<p>If you want to delete only the orphan <code>JOB</code>s previously linked to X, you will need to hold those in a temporary table before the first delete.</p>\n\n<pre><code>INSERT INTO TEMP_TABLE\nSELECT JOB.JOB_ID\nFROM JOB\nINNER JOIN JOB_PERSON\n ON JOB_PERSON.JOB_ID = JOB.JOB_ID\nWHERE JOB_PERSON.PERSON_ID = X\n\nDELETE FROM PERSON\nWHERE PERSON_ID = X\n\n-- YOUR CASCADING DELETE DOES THIS:\n/*\nDELETE FROM JOB_PERSON\nWHERE PERSON_ID = X\n*/\n\n-- Now clean up (only) new orphans on the other side\nDELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\nAND JOB_ID IN (\n SELECT JOB_ID\n FROM TEMP_TABLE\n)\n</code></pre>\n" }, { "answer_id": 272251, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "<p>This will delete from your table JOB entries which have no entry in the table JOB_PERSON (Orpheans).</p>\n\n<pre><code>DELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n</code></pre>\n\n<p>You can't delete rows which are linked by a foreign on an other table...</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33863/" ]
I basically created some tables to play around with: I have Two main tables, and a Many-Many join table. Here is the DDL: (I am using HSQLDB) ``` CREATE TABLE PERSON ( PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, NAME VARCHAR(50), MAIN_PERSON_ID INTEGER ) CREATE TABLE JOB ( JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, NAME VARCHAR(50) ) CREATE TABLE JOB_PERSON ( PERSON_ID INTEGER, JOB_ID INTEGER ) ALTER TABLE JOB_PERSON ADD CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID) REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE ALTER TABLE JOB_PERSON ADD CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID) REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE ALTER TABLE PERSON ADD CONSTRAINT FK_PERSON_PERSON FOREIGN KEY(MAIN_PERSON_ID) REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE insert into person values(null,'Arthur', null); insert into person values(null,'James',0); insert into job values(null, 'Programmer') insert into job values(null, 'Manager') insert into job_person values(0,0); insert into job_person values(0,1); insert into job_person values(1,1); ``` I want to create a delete statement that deletes orphans from JOB (if there exists only one entry in the join table for a specific job) based on the PERSON.PERSON\_ID. In pseudo language: ``` delete from job where job_person.job_id=job.job_id AND count(job_person.job_id)=1 AND job_person.person_id=X ``` Where X is some person\_id. I have tried a lot of different ways; I think it is the "COUNT" part that is causing problems. I am an SQL rookie, so any help would be much appreciated.
I'm not following. You cannot delete `JOB` rows which have `JOB_PERSON` rows (even one) because of your FK contraints. Thus there is no way to delete `JOB` rows based on `PERSON` rows. `JOB_PERSON` rows have to be deleted before either a `JOB` or `PERSON` can be deleted. If you want to delete all `JOB` rows with no `JOB_PERSON`, then one way is: ``` DELETE FROM JOB WHERE JOB_ID NOT IN ( SELECT JOB_ID FROM JOB_PERSON ) ``` If you want to delete all `JOB_PERSON` rows for a particular person and then all orphans, do it in two steps: ``` DELETE FROM JOB_PERSON WHERE PERSON_ID = X DELETE FROM JOB WHERE JOB_ID NOT IN ( SELECT JOB_ID FROM JOB_PERSON ) ``` If you want to delete only the orphan `JOB`s previously linked to X, you will need to hold those in a temporary table before the first delete. ``` INSERT INTO TEMP_TABLE SELECT JOB.JOB_ID FROM JOB INNER JOIN JOB_PERSON ON JOB_PERSON.JOB_ID = JOB.JOB_ID WHERE JOB_PERSON.PERSON_ID = X DELETE FROM PERSON WHERE PERSON_ID = X -- YOUR CASCADING DELETE DOES THIS: /* DELETE FROM JOB_PERSON WHERE PERSON_ID = X */ -- Now clean up (only) new orphans on the other side DELETE FROM JOB WHERE JOB_ID NOT IN ( SELECT JOB_ID FROM JOB_PERSON ) AND JOB_ID IN ( SELECT JOB_ID FROM TEMP_TABLE ) ```
272,199
<p>I have a solution which contains many class libraries and an ASP .NET website which references those assemblies.</p> <p>When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great!</p> <p>When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why?</p> <p>My command line is simply:</p> <pre><code>msbuild.exe d:\myproject\mysolution.sln </code></pre>
[ { "answer_id": 272296, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 0, "selected": false, "text": "<p>Which msbuild are you referencing? Is it the right one?</p>\n\n<p>I generally call like this (from a batch file):</p>\n\n<blockquote>\n <p>%WINDIR%\\Microsoft.NET\\Framework\\v3.5\\msbuild.exe deploy.proj /v:n</p>\n</blockquote>\n\n<p>In this example, deploy.proj is just a regular msbuild file that does some other stuff before and after calling msbuild on the .sln file.</p>\n" }, { "answer_id": 272312, "author": "El Padrino", "author_id": 30339, "author_profile": "https://Stackoverflow.com/users/30339", "pm_score": 0, "selected": false, "text": "<p>I think this problem only occurs when your bin directory is not the framework's default for a solution. </p>\n\n<p>I understand that msbuild uses each project set up to build it. If this is so, please go to each projects properties page and check the post build event command line arguments. </p>\n" }, { "answer_id": 272331, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": -1, "selected": false, "text": "<p>If I recall, MSBuild dosen't copy the referenced assemblies.\nI've posted a \"solution\" a while ago:\n<a href=\"http://www.brunofigueiredo.com/post/Issue-Tracker-part-IV-The-Build-Enviroment-using-MSBuild-(or-NAnt).aspx\" rel=\"nofollow noreferrer\">http://www.brunofigueiredo.com/post/Issue-Tracker-part-IV-The-Build-Enviroment-using-MSBuild-(or-NAnt).aspx</a></p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 287666, "author": "Andrew Van Slaars", "author_id": 8087, "author_profile": "https://Stackoverflow.com/users/8087", "pm_score": 0, "selected": false, "text": "<p>You could always use a copy task in MSBuild to pull your assemblies into the proper directory. I asked a question not to long ago and ended up answering it myself. It shows how you can setup your Copy task to grab output from another project and pull it into your target project:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/266888/msbuild-copy-output-from-another-project-into-the-output-of-the-current-project\">MSBuild copy output from another project into the output of the current project</a></p>\n" }, { "answer_id": 287900, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>I haven't been using msbuild for ASP.NET, but aspnet_compiler. Though...I don't remember why. Sorry.</p>\n\n<pre><code>%windir%\\Microsoft.Net\\framework\\v2.0.50727\\aspnet_compiler -v \\%~n1 -f -p .\\%1 .\\Website\n</code></pre>\n" }, { "answer_id": 303407, "author": "George Sealy", "author_id": 10086, "author_profile": "https://Stackoverflow.com/users/10086", "pm_score": 1, "selected": false, "text": "<p>I have found various references to this problem scattered around the Net - and I've just come across it myself. Apparently MSBuild on the command line isn't as good at tracing chains of dependencies as the IDE is.</p>\n\n<p>So as I understand it, if A depends on B which depends on C, The command line may not realize that A depends on C. </p>\n\n<p>The only solution I've found is to ensure that you manually set the project dependencies so that the ASP project references everything it depends on - don't expect it to be able to figure them all out on the command line. This has worked for me, although I only have 5 projects so it's not a bind to get going.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 2315626, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 0, "selected": false, "text": "<p>You could make use of the Post-Build steps in project properties to copy the output for the project to a particular location.</p>\n\n<p>This copies to an Assemblies directory in the same directory as the Sln file. I have this in the post-build step of all my projects.</p>\n\n<pre><code>md \"$(SolutionDir)Assemblies\"\ndel \"$(SolutionDir)Assemblies\\$(TargetFileName)\"\ncopy \"$(TargetPath)\" \"$(SolutionDir)Assemblies\" /y\n</code></pre>\n" }, { "answer_id": 11551469, "author": "vangorra", "author_id": 1267536, "author_profile": "https://Stackoverflow.com/users/1267536", "pm_score": 1, "selected": false, "text": "<p>The issue I was facing was I have a project that is dependent on a library project. In order to build I was following these steps:</p>\n\n<pre><code>msbuild.exe myproject.vbproj /T:Rebuild\nmsbuild.exe myproject.vbproj /T:Package\n</code></pre>\n\n<p>That of course meant I was missing my library's dll files in bin and most importantly in the package zip file. I found this works perfectly:</p>\n\n<pre><code>msbuild.exe myproject.vbproj /T:Rebuild;Package\n</code></pre>\n\n<p>I have no idea why this work or why it didn't in the first place. But hope that helps.</p>\n" }, { "answer_id": 21729974, "author": "Henry Aloni", "author_id": 938982, "author_profile": "https://Stackoverflow.com/users/938982", "pm_score": 0, "selected": false, "text": "<p>Known problem ffor MSBuild 3.5 and msbuild 4.5. I am using Msbuild 4 found at </p>\n\n<pre><code> c:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe &lt;yourSolutionFile&gt;.sln\n</code></pre>\n\n<p>It seems to solve the problem.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449/" ]
I have a solution which contains many class libraries and an ASP .NET website which references those assemblies. When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great! When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why? My command line is simply: ``` msbuild.exe d:\myproject\mysolution.sln ```
I have found various references to this problem scattered around the Net - and I've just come across it myself. Apparently MSBuild on the command line isn't as good at tracing chains of dependencies as the IDE is. So as I understand it, if A depends on B which depends on C, The command line may not realize that A depends on C. The only solution I've found is to ensure that you manually set the project dependencies so that the ASP project references everything it depends on - don't expect it to be able to figure them all out on the command line. This has worked for me, although I only have 5 projects so it's not a bind to get going. I hope this helps.
272,203
<p>I'm thinking of using PDO in all of my future webapp. Currently (using what I've learned from SO so far), what I have in my site to handle database connection is a Singleton class like this :</p> <pre><code>class DB { private static $instance = NULL; private static $dsn = "mysql:host=localhost;dbname=mydatabase;"; private static $db_user = 'root'; private static $db_pass = '0O0ooIl1'; private function __construct() { } private function __clone() { } public static function getInstance() { if (!self::$instance) { self::$instance = new PDO(self::$dsn, self::$db_user, self::$db_pass); self::$instance-&gt; setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return self::$instance; } } </code></pre> <p>and another file (functions.php) with content-specific functions looking exactly like this one :</p> <pre><code>function get_recent_activities () { try { $db = DB::getInstance(); // --prepare and execute query here, fetch the result-- return $my_list_of_recent_activities; } catch (PDOException $e) { return "some fail-messages"; } } ... </code></pre> <p>meaning that I have to repeat the <code>try .. catch</code> part in all of the functions.</p> <p>My questions are :</p> <ol> <li>How should I make that more efficient ? (eg. not having to repeat <code>try..catch</code> in all functions, and yet still able to return different "fail-message" on each one)</li> <li>Is this already a good practice ? I'm still new at PDO and OOP (still a lot more to learn), so (as of now), I can't really see any disadvantages or things that can be improved in there.</li> </ol> <p>I'm sorry if that seems unclear or too long. Thanks in advance.</p>
[ { "answer_id": 272274, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>A couple of caveats here are:</p>\n\n<ul>\n<li>This code is written to take several legacy issues into account such as the database logging and database configuration management. </li>\n<li>I would strongly recommend that you look at an existing solution before building your own. A lot of people think to themselves when they start out that they don't want to use an existing framework or library because they're too big, require too much time to learn, etc., but after having been one of these people I can't state emphatically enough that I am leaving my custom framework and wrapper classes to move to a framework. I am looking to move to Zend but there are a number of excellent choices available.</li>\n</ul>\n\n<p>Oh, I should point out that this point illustrates how one could wrap a single function to handle all of the exception handling for your queries. I don't write try catch blocks almost anywhere else now because the stack trace from the query gives me all of the information that I need to debug the problem and fix it.</p>\n\n<p>Here is my current PDO wrapper class implementation: </p>\n\n<pre><code>class DB extends PDO \n{\n // Allows implementation of the singleton pattern -- ndg 5/24/2008\n private static $instance;\n\n // Public static variables for configuring the DB class for a particular database -- ndg 6/16/2008\n public static $error_table;\n public static $host_name;\n public static $db_name;\n public static $username;\n public static $password;\n public static $driver_options;\n public static $db_config_path;\n\n\n\n function __construct($dsn=\"\", $username=\"\", $password=\"\", $driver_options=array()) \n {\n if(isset(self::$db_config_path))\n {\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e-&gt;emailAdmin();\n }\n }\n elseif(isset($_ENV['DB']))\n {\n self::$db_config_path = 'config.db.php';\n\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e-&gt;emailAdmin();\n }\n }\n\n parent::__construct(\"mysql:host=\" . self::$host_name . \";dbname=\" .self::$db_name, self::$username, self::$password, self::$driver_options);\n $this-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $this-&gt;setAttribute(PDO::ATTR_STATEMENT_CLASS, array('QueryStatement', array($this)));\n\n if(!isset(self::$error_table))\n {\n self::$error_table = 'errorlog_rtab';\n }\n }\n\n /**\n * Return a DB Connection Object\n *\n * @return DB\n */\n public static function connect()\n {\n\n // New PDO Connection to be used in NEW development and MAINTENANCE development\n try \n {\n if(!isset(self::$instance))\n { \n if(!self::$instance = new DB())\n {\n throw new error('PDO DB Connection failed with error: ' . self::errorInfo());\n }\n }\n\n return self::$instance;\n }\n catch(error $e)\n {\n $e-&gt;printErrMsg();\n }\n }\n\n /**\n * Returns a QueryBuilder object which can be used to build dynamic queries\n *\n * @return QueryBuilder\n * \n */\n public function createQuery()\n {\n return new QueryBuilder();\n }\n\n public function executeStatement($statement, $params = null, $FETCH_MODE = null)\n {\n if($FETCH_MODE == 'scalar')\n {\n return $this-&gt;executeScalar($statement, $params); \n }\n\n\n try {\n try {\n if(!empty($params))\n {\n $stmt = $this-&gt;prepare($statement);\n $stmt-&gt;execute($params);\n }\n else \n {\n $stmt = $this-&gt;query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error-&gt;getMessage());\n }\n }\n catch(error $e)\n {\n $this-&gt;logDBError($e);\n $e-&gt;emailAdmin();\n return false;\n }\n\n try \n {\n if($FETCH_MODE == 'all')\n {\n $tmp = $stmt-&gt;fetchAll();\n }\n elseif($FETCH_MODE == 'column')\n {\n $arr = $stmt-&gt;fetchAll();\n\n foreach($arr as $key =&gt; $val)\n {\n foreach($val as $var =&gt; $value)\n {\n $tmp[] = $value;\n }\n } \n }\n elseif($FETCH_MODE == 'row') \n {\n $tmp = $stmt-&gt;fetch();\n }\n elseif(empty($FETCH_MODE))\n {\n return true;\n }\n }\n catch(PDOException $pdoError)\n {\n return true;\n }\n\n $stmt-&gt;closeCursor();\n\n return $tmp;\n\n }\n\n public function executeScalar($statement, $params = null)\n {\n $stmt = $this-&gt;prepare($statement);\n\n if(!empty($this-&gt;bound_params) &amp;&amp; empty($params))\n {\n $params = $this-&gt;bound_params;\n }\n\n try {\n try {\n if(!empty($params))\n {\n $stmt-&gt;execute($params);\n }\n else \n {\n $stmt = $this-&gt;query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error-&gt;getMessage());\n }\n }\n catch(error $e)\n {\n $this-&gt;logDBError($e);\n $e-&gt;emailAdmin();\n }\n\n $count = $stmt-&gt;fetchColumn();\n\n $stmt-&gt;closeCursor();\n\n //echo $count;\n return $count; \n }\n\n protected function logDBError($e)\n {\n $error = $e-&gt;getErrorReport();\n\n $sql = \"\n INSERT INTO \" . self::$error_table . \" (message, time_date) \n VALUES (:error, NOW())\";\n\n $this-&gt;executeStatement($sql, array(':error' =&gt; $error));\n }\n}\n\nclass QueryStatement extends PDOStatement \n{\n public $conn;\n\n protected function __construct() \n {\n $this-&gt;conn = DB::connect();\n $this-&gt;setFetchMode(PDO::FETCH_ASSOC);\n }\n\n public function execute($bound_params = null)\n {\n return parent::execute($bound_params); \n }\n}\n</code></pre>\n" }, { "answer_id": 273090, "author": "pd.", "author_id": 19066, "author_profile": "https://Stackoverflow.com/users/19066", "pm_score": 7, "selected": true, "text": "<p>Your implementation is just fine, and it'll work perfectly well for most purposes.</p>\n\n<p>It's not necessary to put every query inside a try/catch block, and in fact in most cases you actually don't want to. The reason for this is that if a query generates an exception, it's the result of a fatal problem like a syntax error or a database issue, and those are not issues that you should be accounting for with every query that you do.</p>\n\n<p>For example:</p>\n\n<pre><code>try {\n $rs = $db-&gt;prepare('SELECT * FROM foo');\n $rs-&gt;execute();\n $foo = $rs-&gt;fetchAll();\n} catch (Exception $e) {\n die(\"Oh noes! There's an error in the query!\");\n}\n</code></pre>\n\n<p>The query here will either work properly or not work at all. The circumstances where it wouldn't work at all should not ever occur with any regularity on a production system, so they're not conditions that you should check for here. Doing so is actually counterproductive, because your users get an error that will never change, and you don't get an exception message that would alert you to the problem.</p>\n\n<p>Instead, just write this:</p>\n\n<pre><code>$rs = $db-&gt;prepare('SELECT * FROM foo');\n$rs-&gt;execute();\n$foo = $rs-&gt;fetchAll();\n</code></pre>\n\n<p>In general, the only time that you'll want to catch and handle a query exception is when you want to do something else if the query fails. For example:</p>\n\n<pre><code>// We're handling a file upload here.\ntry {\n $rs = $db-&gt;prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)');\n $rs-&gt;execute(array(1234, '/var/tmp/file1234.txt'));\n} catch (Exception $e) {\n unlink('/var/tmp/file1234.txt');\n throw $e;\n}\n</code></pre>\n\n<p>You'll want to write a simple exception handler that logs or notifies you of database errors that occur in your production environment and displays a friendly error message to your users instead of the exception trace. See <a href=\"http://www.php.net/set-exception-handler\" rel=\"noreferrer\">http://www.php.net/set-exception-handler</a> for information on how to do that.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26721/" ]
I'm thinking of using PDO in all of my future webapp. Currently (using what I've learned from SO so far), what I have in my site to handle database connection is a Singleton class like this : ``` class DB { private static $instance = NULL; private static $dsn = "mysql:host=localhost;dbname=mydatabase;"; private static $db_user = 'root'; private static $db_pass = '0O0ooIl1'; private function __construct() { } private function __clone() { } public static function getInstance() { if (!self::$instance) { self::$instance = new PDO(self::$dsn, self::$db_user, self::$db_pass); self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return self::$instance; } } ``` and another file (functions.php) with content-specific functions looking exactly like this one : ``` function get_recent_activities () { try { $db = DB::getInstance(); // --prepare and execute query here, fetch the result-- return $my_list_of_recent_activities; } catch (PDOException $e) { return "some fail-messages"; } } ... ``` meaning that I have to repeat the `try .. catch` part in all of the functions. My questions are : 1. How should I make that more efficient ? (eg. not having to repeat `try..catch` in all functions, and yet still able to return different "fail-message" on each one) 2. Is this already a good practice ? I'm still new at PDO and OOP (still a lot more to learn), so (as of now), I can't really see any disadvantages or things that can be improved in there. I'm sorry if that seems unclear or too long. Thanks in advance.
Your implementation is just fine, and it'll work perfectly well for most purposes. It's not necessary to put every query inside a try/catch block, and in fact in most cases you actually don't want to. The reason for this is that if a query generates an exception, it's the result of a fatal problem like a syntax error or a database issue, and those are not issues that you should be accounting for with every query that you do. For example: ``` try { $rs = $db->prepare('SELECT * FROM foo'); $rs->execute(); $foo = $rs->fetchAll(); } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } ``` The query here will either work properly or not work at all. The circumstances where it wouldn't work at all should not ever occur with any regularity on a production system, so they're not conditions that you should check for here. Doing so is actually counterproductive, because your users get an error that will never change, and you don't get an exception message that would alert you to the problem. Instead, just write this: ``` $rs = $db->prepare('SELECT * FROM foo'); $rs->execute(); $foo = $rs->fetchAll(); ``` In general, the only time that you'll want to catch and handle a query exception is when you want to do something else if the query fails. For example: ``` // We're handling a file upload here. try { $rs = $db->prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)'); $rs->execute(array(1234, '/var/tmp/file1234.txt')); } catch (Exception $e) { unlink('/var/tmp/file1234.txt'); throw $e; } ``` You'll want to write a simple exception handler that logs or notifies you of database errors that occur in your production environment and displays a friendly error message to your users instead of the exception trace. See <http://www.php.net/set-exception-handler> for information on how to do that.
272,210
<p>What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement:</p> <pre><code>SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) </code></pre> <p>How should this be indented? Many thanks.</p>
[ { "answer_id": 272227, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 4, "selected": false, "text": "<p>This is my personal method. Depending on the length of the join condition I sometimes indent it on the line below.</p>\n\n<pre><code>SELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n\n\nSELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1 -- for long ones\n )\n</code></pre>\n" }, { "answer_id": 272228, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<pre><code>SELECT column1, column2\nFROM table\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n)\n</code></pre>\n\n<p>This is pretty short and easy to read. I'd make adjustments if there were more columns selected or more join conditions.</p>\n" }, { "answer_id": 272231, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 5, "selected": false, "text": "<p>Not sure there is an accepted practice, but here's now how I'd do it:</p>\n\n<pre><code>SELECT \n column1, \n column2 \nFROM \n table1 \nWHERE \n column3 IN \n ( \n SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN \n table3 \n ON table2.column1 = table3.column1 \n )\n</code></pre>\n" }, { "answer_id": 272232, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": "<pre><code>SELECT column1\n , column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n</code></pre>\n\n<p>I like to have all <strong>\",\" in front</strong>, this way I never search them when an error at line X from the SQL editor.</p>\n\n<p><hr/></p>\n\n<h3>This is an example for those who do not use this type of writting SQL statement. Both contain an error of a missing comma.</h3>\n\n<pre><code>SELECT sdcolumn123\n , dscolumn234\n , sdcolumn343\n , ffcolumn434\n , sdcolumn543\n , bvcolumn645\n vccolumn754\n , cccolumn834\n , vvcolumn954\n , cvcolumn104\nFROM table1\nWHERE column3 IN\n(\n ...\n)\n\nSELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054\nFROM table1\nWHERE column3 IN\n(\n ...\n)\n</code></pre>\n\n<p>I found easier and more quick at the first example. Hope this example show you more my point of view.</p>\n" }, { "answer_id": 272236, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What I usually do is,</p>\n\n<pre><code>print(\"SELECT column1, column2\n FROM table1\n WHERE column3 IN (SELECT TOP(1) column4\n FROM table2 INNER JOIN \n table3 ON table2.column1 = table3.column1)\");\n</code></pre>\n" }, { "answer_id": 272238, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": 2, "selected": false, "text": "<p>Of course, this comes down to personal preference. And if in a team setting, it's something that should be agreed upon among the members for consistency's sake. But this would be my preference:</p>\n\n<pre><code>SELECT column1, column2\nFROM table1\nWHERE column3 IN(SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON\n table2.column1 = table3.column1\n )\n</code></pre>\n" }, { "answer_id": 272242, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>I would format like this:</p>\n\n<pre><code>SELECT\n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN (SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN table3 ON table2.column1 = table3.column1)\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>SELECT\n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN (SELECT TOP(1) column4 \n FROM table2 \n INNER JOIN table3 ON table2.column1 = table3.column1)\n</code></pre>\n" }, { "answer_id": 272245, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 1, "selected": false, "text": "<p>I don't know if there's a standard but I like to do it this way;</p>\n\n<pre><code>SELECT column1, column2\n FROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n</code></pre>\n\n<p>because I can read and analyze the SQL better.</p>\n" }, { "answer_id": 272264, "author": "jalbert", "author_id": 1360388, "author_profile": "https://Stackoverflow.com/users/1360388", "pm_score": 4, "selected": false, "text": "<p>I like to have \"rivers\" of white space in the code. It makes it a little easier to scan.</p>\n\n<pre><code>SELECT column1,\n column2\n FROM table1\n WHERE column3 IN (SELECT column4\n FROM table2\n JOIN table3\n ON table2.column1 = table3.column1);\n</code></pre>\n" }, { "answer_id": 272267, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>This is my normal preference:</p>\n\n<pre><code> SELECT column1\n ,column2\n FROM table1\n WHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n</code></pre>\n" }, { "answer_id": 272278, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>This is a matter of taste.</p>\n\n<p>This is my preference.</p>\n\n<pre><code>SELECT \n column1\n ,column2\nFROM\n table1\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM \n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n</code></pre>\n" }, { "answer_id": 272282, "author": "Jack Ryan", "author_id": 28882, "author_profile": "https://Stackoverflow.com/users/28882", "pm_score": 3, "selected": false, "text": "<p>I like to have the different parts of my query line up vertically. I tend to use a tab size of 8 spaces for SQL which seems to work well.</p>\n\n<pre><code>SELECT column1, \n column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n</code></pre>\n" }, { "answer_id": 272284, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Well, of course it depends on the query. </p>\n\n<p>For simple queries, a highly formal indentation scheme is just more trouble than it's worth and can actually make the code <em>less</em> readable, not more. But as complexity grows you need to start being more careful with how you structure the statement, to make sure it will be readable again later.</p>\n" }, { "answer_id": 272305, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>Yeah, this is pretty subjective...But here's my 2 cents:</p>\n\n<pre><code>SELECT\n Column1,\n Column2\nFROM Table1\nWHERE \n Column3 IN (\n SELECT Column4\n FROM Table2\n JOIN Table3 ON\n Table2.Column1 = Table3.Column1\n )\n</code></pre>\n\n<p>But, really, I'd probably rewrite it without the IN:</p>\n\n<pre><code>SELECT\n Column1,\n Column2\nFROM Table1\nJOIN Table2 ON\n Table1.Column3 = Table2.Column4\nJOIN Table3 ON\n Table2.Column1 = Table3.Column1\n</code></pre>\n\n<p>Basically, my rules are:</p>\n\n<ul>\n<li>Capitalize Keywords</li>\n<li>Columns go on individual lines, but SELECT modifiers (SELECT TOP 100, SELECT DISTINCT, etc.) or single columns (SELECT 1, SELECT Id, SELECT *, etc.) go on same line</li>\n<li>Join conditions indented underneath JOIN clause</li>\n<li>Use JOIN for INNER JOIN (since it's the common one), and fully specify others (LEFT OUTER JOIN, FULL OUTER JOIN, etc.)</li>\n<li>Open parens on same line, close paren on separate line. If you have an alias, the alias goes with close paren.</li>\n</ul>\n" }, { "answer_id": 272339, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 3, "selected": false, "text": "<p>SQL formatting is an area where there is a great deal of variance and disagreement... But fwiw, I like to focus on readability and think that whatever you do, consistently conforming to any rules that reduce readability is, as the old cliche goes, a \"foolish consistency\" ( \"Foolish consistency is a hobgoblin for simple minds\" ) </p>\n\n<p>So, instead of calling them rules, here are some guidelines.\nFor each Major clause in a SQL statement (Select, Insert, Delete, From, Where, Having, Group BY, Order By, ... I may be missing a few) should be EASILY identifiable. So I generally indent them at the highest level, all even with each other. Then within each clause, I indent the next logical sub structure evenly... and so on.. But I feel free to (and often do) change the pattern if in any individual case it would be more readable to do so... Complex Case statements are a good example. Because anything that requires horizontal scrolling reduces readability enormously, I often write complex (nested) Case expressions on multiple lines. When I do, I try to keep the beginning of such a statement hanging indent based on it's logical place in the SQL statement, and indent the rest of the statement lines a few characters furthur... </p>\n\n<p>SQL Database code has been around for a long time, since before computers had lower case, so there is a historical preference for upper casing keywords, but I prefer readability over tradition... (and every tool I use color codes the key words now anyway)</p>\n\n<p>I also would use Table aliases to reduce the amount of text the eye has to scan in order to grok the structure of the query, as long as the aliases do not create confusion. In a query with less than 3 or 4 tables, Single character aliases are fine, I often use first letter of the table if all ther tables start with a different letter... again, whatever most contributes to readability. Finally, if your database supports it, many of the keywords are optional, (like \"Inner\", \"Outer\", \"As\" for aliases, etc.) \"Into\" (from Insert Into) is optional on Sql Server - but not on Oracle) So be careful about using this if your code needs to be platform independant... </p>\n\n<p>Your example, I would write as:</p>\n\n<pre><code>Select column1, column2\nFrom table1 T1\nWhere column3 In (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>Select column1, column2\nFrom table1 T1\nWhere column3 In \n (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n</code></pre>\n\n<p>If there many more columns on the select clause, I would indent the second and subsequent lines... I generally do NOT adhere to any strict (one column per row) kind of rule as scrolling veritcally is almost as bad for readability as scrolling horizontally is, especially if only the first ten columns of the screen have any text in them)</p>\n\n<pre><code>Select column1, column2, Col3, Col4, column5,\n column6, Column7, isNull(Column8, 'FedEx') Shipper,\n Case Upper(Column9) \n When 'EAST' Then 'JFK'\n When 'SOUTH' Then 'ATL'\n When 'WEST' Then 'LAX'\n When 'NORTH' Then 'CHI' End HubPoint\nFrom table1 T1\nWhere column3 In \n (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n</code></pre>\n\n<p>Format the code in whatever manner makes it the most readable... </p>\n" }, { "answer_id": 272344, "author": "Slapout", "author_id": 19072, "author_profile": "https://Stackoverflow.com/users/19072", "pm_score": 4, "selected": false, "text": "<p>I like jalbert's form of lining up the keywords on their right. I'd also add that I like the ANDs and ORs on the left (some people put them on the right.) In addition, I like to line up my equals signs when possible.</p>\n\n<pre><code>\nSELECT column1, \n column2 \n FROM table1, table2 \n WHERE table1.column1 = table2.column4 \n AND table1.col5 = \"hi\" \n OR table2.myfield = 678 \n</code></pre>\n" }, { "answer_id": 272391, "author": "Mike Burton", "author_id": 22225, "author_profile": "https://Stackoverflow.com/users/22225", "pm_score": 3, "selected": false, "text": "<p>I've written a code standard for our shop that is biased in the extreme towards readability/\"discoverability\" (the latter being primarily useful in insert-select statements):</p>\n\n<pre><code>SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n</code></pre>\n\n<p>On more complex queries it becomes more obvious how this is useful:</p>\n\n<pre><code>SELECT\n Column1,\n Column2,\n Function1\n (\n Column1,\n Column2\n ) as Function1,\n CASE\n WHEN Column1 = 1 THEN\n a\n ELSE\n B\n END as Case1 \nFROM\n Table1 t1\n INNER JOIN Table2 t2 ON t1.column12 = t2.column21\nWHERE\n (\n FilterClause1\n AND FilterClause2\n )\n OR\n (\n FilterClause3\n AND FilterClause4\n )\n</code></pre>\n\n<p>Once you move to systems with more than a single join in most of your queries, it has been my experience that using vertical space liberally is your best friend with complex SQL.</p>\n" }, { "answer_id": 272434, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 3, "selected": false, "text": "<p>If you have a lengthy SQL statement that you'd like to reformat without all the typing and tabbing, you can slap it into <a href=\"http://www.orafaq.com/cgi-bin/sqlformat/pp/utilities/sqlformatter.tpl\" rel=\"nofollow noreferrer\">this website</a> and get a nicely formatted result. You can experiment with various formats to see which makes your text the most readable.</p>\n\n<p>Edit: I believe that <a href=\"http://sqlformat.org/\" rel=\"nofollow noreferrer\">this</a> is the 2014 location of the SQL formatter.</p>\n" }, { "answer_id": 272655, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've just put it through my SQL prettifier and it came out like this....</p>\n\n<pre><code>SELECT column1, column2\nFROM table1\nWHERE column3 IN\n(\nSELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n</code></pre>\n\n<p><a href=\"http://extras.sqlservercentral.com/prettifier/prettifier.aspx\" rel=\"nofollow noreferrer\">http://extras.sqlservercentral.com/prettifier/prettifier.aspx</a></p>\n\n<p>.....But I haven't worked out a way of getting colours into StackOverflow.</p>\n" }, { "answer_id": 3535810, "author": "José Américo Antoine Jr", "author_id": 426870, "author_profile": "https://Stackoverflow.com/users/426870", "pm_score": 3, "selected": false, "text": "<p>Example indenting a very very very complex SQL:</p>\n\n<pre><code>SELECT \n produtos_cesta.cod_produtos_cesta, \n produtos.nome_pequeno,\n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r AS sku_kit, \n sku_final = CASE\n WHEN produtos_kits.sku_r IS NOT NULL THEN produtos_kits.sku_r\n ELSE produtos_cesta.sku\n END,\n estoque = CASE\n WHEN produtos2.estoque IS NOT NULL THEN produtos2.estoque\n ELSE produtos.estoque\n END,\n produtos_cesta.unidades as unidades1, \n unidades_x_quantidade = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN CAST(produtos_cesta.quantidade * (produtos_cesta.unidades / tab_contagem.cont) * produtos_kits.quantidade AS int)\n ELSE CAST(produtos_cesta.quantidade * produtos_cesta.unidades AS int)\n END,\n unidades = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN produtos_cesta.unidades / tab_contagem.cont * produtos_kits.quantidade\n ELSE produtos_cesta.unidades\n END,\n unidades_parent = produtos_cesta.unidades,\n produtos_cesta.quantidade,\n produtos.controla_estoque, \n produtos.status\nFROM \n produtos_cesta \nINNER JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \nINNER JOIN produtos_pacotes \n ON (produtos_cesta.sku = produtos_pacotes.sku) \nINNER JOIN (\n SELECT \n produtos_cesta.cod_produtos_cesta,\n cont = SUM(\n CASE\n WHEN produtos_kits.quantidade IS NOT NULL THEN produtos_kits.quantidade\n ELSE 1\n END\n )\n FROM \n produtos_cesta \n LEFT JOIN produtos_kits \n ON (produtos_cesta.sku = produtos_kits.sku) \n LEFT JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \n WHERE \n shopper_id = '\" + mscsShopperId + @\"' \n GROUP BY \n produtos_cesta.cod_produtos_cesta, \n produtos_cesta.sku, \n produtos_cesta.unidades \n) \nAS tab_contagem\n ON (produtos_cesta.cod_produtos_cesta = tab_contagem.cod_produtos_cesta)\nLEFT JOIN produtos_kits \n ON (produtos.sku = produtos_kits.sku) \nLEFT JOIN produtos as produtos2\n ON (produtos_kits.sku_r = produtos2.sku) \nWHERE \n shopper_id = '\" + mscsShopperId + @\"' \nGROUP BY \n produtos_cesta.cod_produtos_cesta, \n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r, \n produtos.cod_produtos_kits_tipo, \n produtos2.estoque,\n produtos.controla_estoque, \n produtos.estoque, \n produtos.status, \n produtos.nome_pequeno, \n produtos_cesta.unidades, \n produtos_cesta.quantidade,\n produtos_kits.quantidade\nORDER BY \n produtos_cesta.sku, \n produtos_cesta.unidades DESC\n</code></pre>\n" }, { "answer_id": 4582352, "author": "S. Goldberg", "author_id": 560893, "author_profile": "https://Stackoverflow.com/users/560893", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT\n Column1,\n Column2\nFROM\n Table1\nWHERE\n Column3 IN\n (\n SELECT TOP (1)\n Column4\n FROM \n Table2\n INNER JOIN \n Table3\n ON\n Table2.Column1 = Table3.Column1\n )\n</code></pre>\n" }, { "answer_id": 9910379, "author": "Jens Frandsen", "author_id": 1298535, "author_profile": "https://Stackoverflow.com/users/1298535", "pm_score": 3, "selected": false, "text": "<p>As most above have lined up the return column names, I find lining up tables names and conditions helps readability a lot.</p>\n\n<pre><code>SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2 INNER JOIN \n table3 ON table2.column1 = table3.column1\n )\n</code></pre>\n\n<p>And for when join conditions get long.</p>\n\n<pre><code>SELECT\n Column1,\n Column2\nFROM \n Table1 JOIN \n Table2 ON \n Table1.Column3 = Table2.Column4 JOIN \n Table3 ON \n Table2.Column1 = Table3.Column1 and\n Table2.ColumnX = @x and\n Table3.ColumnY = @y\nWHERE\n Condition1=xxx and\n Condition2=yyy and\n (\n Condition3=aaa or\n Condition4=bbb\n )\n</code></pre>\n" }, { "answer_id": 17877162, "author": "cdw", "author_id": 2622045, "author_profile": "https://Stackoverflow.com/users/2622045", "pm_score": -1, "selected": false, "text": "<p>That's how we would do it here:</p>\n\n<pre>\nselect\n COLUMN1,\n COLUMN2,\n case when COLUMN5 = 'X'\n and\n COLUMN6 = 'Y'\n then 'one'\n when COLUMN5 in (\n 'AAA',\n 'BBB'\n )\n then 'two'\n else 'three'\n end as COLUMN7\nfrom\n TABLE1\nwhere\n COLUMN2 in (\n select top(1)\n COLUMN4\n from\n TABLE2\n inner join\n TABLE3\n on\n TABLE2.COLUMN1 = TABLE3.COLUMN1\n and\n TABLE2.COLUMN2\n between\n TABLE3.COLUMN2\n and\n TABLE3.COLUMN3\n )\n</pre>\n\n<p>Our idea is: keep sql keywords in lower case and put all changing (and therefore \"more interesting\") things like table or column names in upper case.\nThe code might look a bit \"blown up\" here, but it increases readability if you have complex queries with longer names (incl. schema etc.) much longer than in this example.\nAnd: indent all objects according to their \"level\".</p>\n" }, { "answer_id": 18098922, "author": "John Doe", "author_id": 2659987, "author_profile": "https://Stackoverflow.com/users/2659987", "pm_score": 3, "selected": false, "text": "<p>Here's my poke at this:</p>\n\n<pre><code>select column1, column2\n from table1\n where (column3 in (\n select top(1) column4\n from table2\n inner join table3\n on (table2.column1 = table3.column1)\n ))\n;\n</code></pre>\n\n<ul>\n<li>Everything lowercase because it's easier to read lowercase characters (and we have code highlighting to emphasize keywords) also easier to type</li>\n<li>Every restriction or option on a keyword (like the from on the select or the on on the join) is indented to show their dependance on the outward keyword</li>\n<li>The closing bracket is at the same indenting level as the opening where</li>\n<li>Use brackets for where- and on-clauses to increase readability</li>\n<li>Have the semicolon closing the select-statement at the same indenting so multiple statements can be distinguished better (if you need a semicolon in your language like SAS PROC SQL does)</li>\n<li>It's still quite compact and does not stretch all over the page</li>\n</ul>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35483/" ]
What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement: ``` SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` How should this be indented? Many thanks.
``` SELECT column1 , column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` I like to have all **"," in front**, this way I never search them when an error at line X from the SQL editor. --- ### This is an example for those who do not use this type of writting SQL statement. Both contain an error of a missing comma. ``` SELECT sdcolumn123 , dscolumn234 , sdcolumn343 , ffcolumn434 , sdcolumn543 , bvcolumn645 vccolumn754 , cccolumn834 , vvcolumn954 , cvcolumn104 FROM table1 WHERE column3 IN ( ... ) SELECT sdcolumn123, dscolumn234, asdcolumn345, dscolumn456, ascolumn554, gfcolumn645 sdcolumn754, fdcolumn845, sdcolumn954, fdcolumn1054 FROM table1 WHERE column3 IN ( ... ) ``` I found easier and more quick at the first example. Hope this example show you more my point of view.
272,254
<p>This piece of T-SQL is deprecated in 2005:</p> <pre><code>BACKUP LOG [DB_NAME] WITH TRUNCATE_ONLY </code></pre> <p>I don't need to keep a backup the log for my db - but I do not want the piece of code to stop working if we port to SQL2008 or successive versions in future.</p> <p>Cheers</p>
[ { "answer_id": 272276, "author": "Greg Smalter", "author_id": 34290, "author_profile": "https://Stackoverflow.com/users/34290", "pm_score": 1, "selected": false, "text": "<p>If you change the recovery model of the database to Simple, I think it will stop forcing you to backup/truncate the log.</p>\n" }, { "answer_id": 272280, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "<p>Switch the database recovery mode to SIMPLE, and then use DBCC SHRINKFILE. Then restore your original recovery mode. If your LOG file does not shrink, you might have uncommitted transactions. For more details, see Tibor's Karaszi's article on <a href=\"http://www.karaszi.com/SQLServer/info_dont_shrink.asp\" rel=\"nofollow noreferrer\">shrinking</a>.</p>\n" }, { "answer_id": 272298, "author": "Andy Jones", "author_id": 5096, "author_profile": "https://Stackoverflow.com/users/5096", "pm_score": 1, "selected": false, "text": "<p>Change your database to use the simple recovery model. This means you do not have point in time recovery (you won't have that anyway if you are truncating your log), but the log file is automatically cycled and won't grow too large.</p>\n\n<p>A log file is mandatory and you have no option but to keep it, what you don't want is for it to grow out of control and fill your disk.</p>\n" }, { "answer_id": 272343, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 0, "selected": false, "text": "<p>As Andy Jones answered, the log file is mandatory. It is not simply a log of events for your sake, but a vital part of the way the database handles transaction rollbacks as well as memory commits.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
This piece of T-SQL is deprecated in 2005: ``` BACKUP LOG [DB_NAME] WITH TRUNCATE_ONLY ``` I don't need to keep a backup the log for my db - but I do not want the piece of code to stop working if we port to SQL2008 or successive versions in future. Cheers
Switch the database recovery mode to SIMPLE, and then use DBCC SHRINKFILE. Then restore your original recovery mode. If your LOG file does not shrink, you might have uncommitted transactions. For more details, see Tibor's Karaszi's article on [shrinking](http://www.karaszi.com/SQLServer/info_dont_shrink.asp).
272,270
<pre><code> &lt;object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"&gt; &lt;param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/&gt; &lt;param value="high" name="quality"/&gt; &lt;param value="#FFFFFF" name="bgcolor"/&gt; &lt;param value="opaque" name="wmode"/&gt; &lt;embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/&gt; &lt;/object&gt; </code></pre> <p>I am having to insert this legacy markup into a new site that I'm building. Problem is its using an <code>&lt;embed&gt;</code> tag. </p> <p>Would I just do away with the <code>&lt;embed&gt;</code> and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.</p>
[ { "answer_id": 272306, "author": "pbrodka", "author_id": 33093, "author_profile": "https://Stackoverflow.com/users/33093", "pm_score": 1, "selected": false, "text": "<p>I use function AC_FL_RunContent for embedding flash objects - it's good because it supports all browsers and is recommended by Adobe.</p>\n<p>More is <a href=\"http://www.adobe.com/devnet/activecontent/articles/devletter.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n<p>They also suggest using &lt;object&gt; tag instead of &lt;embed&gt;</p>\n" }, { "answer_id": 272308, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 2, "selected": false, "text": "<p>You can nest object elements to display alternatives. The W3C explains it <a href=\"http://www.w3.org/TR/html401/struct/objects.html#h-13.3\" rel=\"nofollow noreferrer\">here</a>. I copied a snippet below:</p>\n<blockquote>\n<p>One significant consequence of the OBJECT element's design is that it offers a mechanism for specifying alternate object renderings; each embedded OBJECT declaration may specify alternate content types. If a user agent cannot render the outermost OBJECT, it tries to render the contents, which may be another OBJECT element, etc.</p>\n<p>In the following example, we embed several OBJECT declarations to illustrate how alternate renderings work. A user agent will attempt to render the first OBJECT element it can, in the following order: (1) an Earth applet written in the Python language, (2) an MPEG animation of the Earth, (3) a GIF image of the Earth, (4) alternate text.</p>\n</blockquote>\n<pre><code>&lt;P&gt; &lt;!-- First, try the Python applet --&gt;\n&lt;OBJECT title=&quot;The Earth as seen from space&quot; \n classid=&quot;http://www.observer.mars/TheEarth.py&quot;&gt;\n &lt;!-- Else, try the MPEG video --&gt;\n &lt;OBJECT data=&quot;TheEarth.mpeg&quot; type=&quot;application/mpeg&quot;&gt;\n &lt;!-- Else, try the GIF image --&gt;\n &lt;OBJECT data=&quot;TheEarth.gif&quot; type=&quot;image/gif&quot;&gt;\n &lt;!-- Else render the text --&gt;\n The &lt;STRONG&gt;Earth&lt;/STRONG&gt; as seen from space.\n &lt;/OBJECT&gt;\n &lt;/OBJECT&gt;\n&lt;/OBJECT&gt;\n</code></pre>\n" }, { "answer_id": 272314, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>Basically, you should keep embed, because it is a fallback for some old browsers. It might hurt validation of page, but as long as you know why it is there, it is OK.</p>\n\n<p>At least that's the way Adobe officially recommends: <a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_4150\" rel=\"nofollow noreferrer\" title=\"Macromedia Flash OBJECT and EMBED tag syntax\">Macromedia Flash OBJECT and EMBED tag syntax</a></p>\n\n<p>You are right to want to do code for XXIth century, but we have to deal with browser from previous millennium... :-)</p>\n" }, { "answer_id": 272328, "author": "Raithlin", "author_id": 6528, "author_profile": "https://Stackoverflow.com/users/6528", "pm_score": 1, "selected": false, "text": "<p>I found this code on the web (from a usability site) which caters for IE and others, and I use it on my flash pages (I've changed it to your code):</p>\n\n<pre><code>&lt;!--[if !IE]&gt; --&gt;\n&lt;object type=\"application/x-shockwave-flash\" data=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" width=\"75\" height=\"25\"&gt;\n&lt;!-- &lt;![endif]--&gt;\n\n&lt;!--[if IE]&gt;\n&lt;object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"75\" height=\"25\"&gt;\n &lt;param name=\"movie\" value=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" /&gt;\n&lt;!--&gt;&lt;!--dgx--&gt;\n &lt;param name=\"loop\" value=\"false\"&gt;\n &lt;param name=\"menu\" value=\"false\"&gt;\n &lt;param name=\"quality\" value=\"high\"&gt;\n&lt;/object&gt;\n&lt;!-- &lt;![endif]--&gt;\n</code></pre>\n" }, { "answer_id": 272362, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 2, "selected": false, "text": "<p>I recommend that you use <strong>swfobject</strong> which is a cross platform, open source library to display flash on your pages.</p>\n\n<p><a href=\"http://code.google.com/p/swfobject/\" rel=\"nofollow noreferrer\">http://code.google.com/p/swfobject/</a></p>\n\n<p>There are a variety of ways to load the flash and the alternative (non-flash) content. For example the following code could replace your code:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"swfobject.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n swfobject.embedSWF(\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\", \n \"myContent\", \"25\", \"75\", \"9.0.0\");\n&lt;/script&gt;\n&lt;div id=\"myContent\"&gt;\n &lt;p&gt;Alternative content&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
``` <object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/> <param value="high" name="quality"/> <param value="#FFFFFF" name="bgcolor"/> <param value="opaque" name="wmode"/> <embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/> </object> ``` I am having to insert this legacy markup into a new site that I'm building. Problem is its using an `<embed>` tag. Would I just do away with the `<embed>` and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.
You can nest object elements to display alternatives. The W3C explains it [here](http://www.w3.org/TR/html401/struct/objects.html#h-13.3). I copied a snippet below: > > One significant consequence of the OBJECT element's design is that it offers a mechanism for specifying alternate object renderings; each embedded OBJECT declaration may specify alternate content types. If a user agent cannot render the outermost OBJECT, it tries to render the contents, which may be another OBJECT element, etc. > > > In the following example, we embed several OBJECT declarations to illustrate how alternate renderings work. A user agent will attempt to render the first OBJECT element it can, in the following order: (1) an Earth applet written in the Python language, (2) an MPEG animation of the Earth, (3) a GIF image of the Earth, (4) alternate text. > > > ``` <P> <!-- First, try the Python applet --> <OBJECT title="The Earth as seen from space" classid="http://www.observer.mars/TheEarth.py"> <!-- Else, try the MPEG video --> <OBJECT data="TheEarth.mpeg" type="application/mpeg"> <!-- Else, try the GIF image --> <OBJECT data="TheEarth.gif" type="image/gif"> <!-- Else render the text --> The <STRONG>Earth</STRONG> as seen from space. </OBJECT> </OBJECT> </OBJECT> ```
272,313
<p>I have the requirement to support different Master pages on my application (ASP.NET MVC). What is the recommended way to:</p> <ol> <li>Pass the master page name to the view from.</li> <li>Store the master page (in session, or something) so it sticks during a user's visit.</li> </ol>
[ { "answer_id": 272369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you could throw the master page name into the session, but sessions are unreliable. i'd recommend throwing it in a db instead.</p>\n\n<p>once you're in the page, you can change/set the master page by accessing page.masterpagefile. it's a string; just pass the .master name in.</p>\n" }, { "answer_id": 272400, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": -1, "selected": false, "text": "<p>Why not keep the Master Page on the user profile?\nThen just change it on the PreLoad event.</p>\n\n<p><a href=\"http://www.odetocode.com/articles/440.aspx\" rel=\"nofollow noreferrer\">http://www.odetocode.com/articles/440.aspx</a></p>\n" }, { "answer_id": 460828, "author": "Slee", "author_id": 34548, "author_profile": "https://Stackoverflow.com/users/34548", "pm_score": 4, "selected": true, "text": "<p>Use a custom base controller and inherit from it instead:</p>\n\n<pre><code>Public Class CustomBaseController\n Inherits System.Web.Mvc.Controller\n\n Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult\n\n Return MyBase.View(viewName, Session(\"MasterPage\"), model)\n\n End Function\n\nEnd Class\n</code></pre>\n\n<p>I set my Session variable in the global.asax Session_Start:</p>\n\n<pre><code>Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)\n\n//programming to figure out your session\nSession(\"MasterPage\")=\"MyMasterPage\"\n\nEnd Sub\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7277/" ]
I have the requirement to support different Master pages on my application (ASP.NET MVC). What is the recommended way to: 1. Pass the master page name to the view from. 2. Store the master page (in session, or something) so it sticks during a user's visit.
Use a custom base controller and inherit from it instead: ``` Public Class CustomBaseController Inherits System.Web.Mvc.Controller Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult Return MyBase.View(viewName, Session("MasterPage"), model) End Function End Class ``` I set my Session variable in the global.asax Session\_Start: ``` Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) //programming to figure out your session Session("MasterPage")="MyMasterPage" End Sub ```
272,338
<p>I am developing a small ASP.NET website for online shopping, when testing it out in Visual Studio, everything works fine, however that is no longer the case when I deploy it to IIS.</p> <p>The problem seems to be in a DLL file that I reference, this DLL file contains the Classes I need to initialize and send query requests to another server that has all the product information. This DLL was originally a Jar file which I converted to DLL using IKVM.</p> <p>When I deploy the app to IIS, any page that attempts to instantiate an object defined in that DLL fails with a null reference, for example:</p> <pre><code>Fulfiller fulfiller = new Fulfiller(); string result = fulfiller.initialize("host", port, "user", "pass"); </code></pre> <p>returns this error:</p> <blockquote> <p><code>System.NullReferenceException</code>: Object reference not set to an instance of an object. at <code>Fulfiller.toLog(String )</code> at <code>Fulfiller.initialize(String str1, Int32 i, String str2, String str3)</code> at <code>Orders.createDataSource()</code></p> </blockquote> <p>Now again, this works perfectly on the VS development server but breaks in IIS and I don't know why. Is it some sort of coding problem where the DLL is not loaded properly when running on IIS? or is it a problem with IIS maybe blocking the DLL from executing or sending out requests, I'm very desperate to solve this problem</p> <p>thanks</p>
[ { "answer_id": 272347, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 0, "selected": false, "text": "<p>What is fulfiller.Initialize() doing? Can you post that code?</p>\n\n<p>Clearly you have a fulfiller reference, because you can't pass the constructor without error and then have a null-ref.</p>\n" }, { "answer_id": 272366, "author": "Loris", "author_id": 23824, "author_profile": "https://Stackoverflow.com/users/23824", "pm_score": 2, "selected": false, "text": "<p>Usually, when something that works on the dev sever doesn't work on IIS, the problem is authorizations (the VS server runs under your credentials, but IIS runs as \"Network Service\" or another system user).</p>\n\n<p>For example, I see your code breaks on fulfiller.toLog().</p>\n\n<p>Could it be that the toLog() function is trying to open a log file and that the user impersonated by IIS is not authorized to read or write it?</p>\n" }, { "answer_id": 272411, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "<p>I second Loris' answer. </p>\n\n<p>The dev server has your permissions. Assuming you are deploying to Windows Server, or any machine running Active Directory, you should be able to right-click on the directory where the log files are stored and select properties. In the dialog box, there will be a tab labeled Security. If the Network Service user (or IUSR_machinename) is not visible, you will have to add them to the list. Select the user and assign them read and write permissions.</p>\n\n<p>Do not give the IIS user full permissions to your entire application directory. It is a huge security vulnerability, hence the default deployment not giving you the permissions that you currently need.</p>\n" }, { "answer_id": 272669, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have not used IKVM, but I am sure that some IKVM runtime must be installed on the server. Have you checked IKVM on the server? </p>\n\n<p>Hope this helps.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am developing a small ASP.NET website for online shopping, when testing it out in Visual Studio, everything works fine, however that is no longer the case when I deploy it to IIS. The problem seems to be in a DLL file that I reference, this DLL file contains the Classes I need to initialize and send query requests to another server that has all the product information. This DLL was originally a Jar file which I converted to DLL using IKVM. When I deploy the app to IIS, any page that attempts to instantiate an object defined in that DLL fails with a null reference, for example: ``` Fulfiller fulfiller = new Fulfiller(); string result = fulfiller.initialize("host", port, "user", "pass"); ``` returns this error: > > `System.NullReferenceException`: Object reference not set to an instance > of an object. at `Fulfiller.toLog(String )` at > `Fulfiller.initialize(String str1, Int32 i, String str2, String str3)` > at `Orders.createDataSource()` > > > Now again, this works perfectly on the VS development server but breaks in IIS and I don't know why. Is it some sort of coding problem where the DLL is not loaded properly when running on IIS? or is it a problem with IIS maybe blocking the DLL from executing or sending out requests, I'm very desperate to solve this problem thanks
Usually, when something that works on the dev sever doesn't work on IIS, the problem is authorizations (the VS server runs under your credentials, but IIS runs as "Network Service" or another system user). For example, I see your code breaks on fulfiller.toLog(). Could it be that the toLog() function is trying to open a log file and that the user impersonated by IIS is not authorized to read or write it?
272,360
<p>If so, does it effectively deprecate the <code>visibility</code> property?</p> <p>(I realize that Internet Explorer does not yet support this CSS2 property.) <br/> <a href="http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties" rel="noreferrer">Comparisons of layout engines</a></p> <p><a href="https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone">See also: What is the difference between visibility:hidden and display:none</a></p>
[ { "answer_id": 272371, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 3, "selected": false, "text": "<p>I'm not entirely sure of this, but I think screen readers don't read things that are set to visibility hidden, but they may read things regardless of their opacity.</p>\n\n<p>That's the only difference I can think of.</p>\n" }, { "answer_id": 272380, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>Im not sure entirely, but this is how i do cross browser transparency:</p>\n\n<pre><code>opacity: 0.6;\n-moz-opacity: 0.6;\nfilter: alpha(opacity=60);\n</code></pre>\n\n<p>objects with Visibility:hidden still have shape, they just arent visible. opacity zero elements can still be clicked and react to other events.</p>\n" }, { "answer_id": 272381, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>What Phil says is true.</p>\n\n<p>IE supports opacity though:</p>\n\n<pre><code>filter:alpha(opacity=0);\n</code></pre>\n" }, { "answer_id": 273076, "author": "Chris Noe", "author_id": 14749, "author_profile": "https://Stackoverflow.com/users/14749", "pm_score": 9, "selected": true, "text": "<p>Here is a compilation of verified information from the various answers.</p>\n\n<p>Each of these CSS properties is unique. In addition to rendering an element not visible, they have the following additional effect(s):</p>\n\n<ol>\n<li><strong>Collapses</strong> the space that the element would normally occupy</li>\n<li>Responds to <strong>events</strong> (e.g., click, keypress)</li>\n<li>Participates in the <strong>taborder</strong></li>\n</ol>\n\n<pre>\n collapse events taborder\nopacity: 0 No Yes Yes\nvisibility: hidden No No No\nvisibility: collapse Yes* No No\ndisplay: none Yes No No\n\n* Yes inside a table element, otherwise No.\n</pre>\n" }, { "answer_id": 273105, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 0, "selected": false, "text": "<p>The properties have different <em>semantic</em> meanings. While semantic CSS sounds like it may be silly, as other users have mentioned it has an impact on devices like screen readers -- where semantics impact the accessibility of a page.</p>\n" }, { "answer_id": 742324, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<p>No.</p>\n\n<p>Elements with opacity create new stacking context. </p>\n\n<p>Also, CSS spec doesn't define this, but elements with <code>opacity:0</code> are clickable, and elements with <code>visibility:hidden</code> are not.</p>\n" }, { "answer_id": 34529543, "author": "Nishant", "author_id": 1065020, "author_profile": "https://Stackoverflow.com/users/1065020", "pm_score": 4, "selected": false, "text": "<p>No it does not. There is a big difference. \nThey are similar because you can see through the element if visibility is hidden or opacity is 0, however</p>\n\n<p><strong>opacity: 0</strong> : <strong>you can not click</strong> on elements behind it.</p>\n\n<p><strong>visibility: hidden</strong> : <strong>you can click</strong> on elements behind it.</p>\n" }, { "answer_id": 43482222, "author": "MalcolmOcean", "author_id": 985026, "author_profile": "https://Stackoverflow.com/users/985026", "pm_score": 2, "selected": false, "text": "<p>While making a userstyle that affects elements in a <code>contenteditable</code>, I noticed that if you set something to <code>visibility: hidden</code>, then the input caret doesn't really want to interact with it. Eg if you have </p>\n\n<pre><code>&lt;div contenteditable&gt;&lt;span style='visibility: hidden;'&gt;&lt;/span&gt;&lt;/div&gt;\n</code></pre>\n\n<p>...then it seems if you focus that div/span, you can't actually type in it. Whereas with <code>opacity: 0</code> it seems you can. I haven't tested this extensively, but figured it was worth mentioning this here as nobody else on this page has talked about the effects on text input. This seems possibly related to the <strong>events</strong> stuff mentioned above though.</p>\n" }, { "answer_id": 50027026, "author": "Mr Lister", "author_id": 1016716, "author_profile": "https://Stackoverflow.com/users/1016716", "pm_score": 3, "selected": false, "text": "<p>There are many differences between <code>visibility</code> and <code>opacity</code>. Most of the answers mention some differences, but here is a complete list.</p>\n\n<ol>\n<li><p>opacity does not inherit, while visibility does</p></li>\n<li><p>opacity is animatable while visibility is not.<br>\n(Well, <em>technically</em> it is, but there is simply no behaviour defined for, say, \"37% collapsed and 63% hidden\", so you can consider this as non-animatable.)</p></li>\n<li><p>Using opacity, you can not make a child element more opaque than its parent. E.G. if you have a p with color:black and opacity:0.5, you can not make any of its children fully black. Valid values for opacity are between 0 and 1, and this example would require 2!<br>\nConsequently, according to <a href=\"https://stackoverflow.com/questions/272360/does-opacity0-have-exactly-the-same-effect-as-visibilityhidden#comment57887943_273076\">Martin's comment</a>, you can have a visible child (with visibility:visible) in an invisible parent (with visibility:hidden). This is impossible with opacity; if a parent has opacity:0; its children are always invisible.</p></li>\n<li><p><a href=\"https://stackoverflow.com/a/742324/1016716\">Kornel's answer</a> mentions that opacity values less than 1 create their own stacking context; no value for visibility does.<br>\n(I wish I could think of a way to demonstrate this, but I can't think of any means to show the stacking context of a visibility:hidden element.)</p></li>\n<li><p>According to <a href=\"https://stackoverflow.com/a/272371/1016716\">philnash's answer</a>, elements with opacity:0 are still read by screen readers, while visible:hidden elements are not.</p></li>\n<li><p>According to <a href=\"https://stackoverflow.com/a/273076/1016716\">Chris Noe's answer</a>, visibility has more options (such as collapse) and elements that are not visible no longer respond to clicks and cannot be tabbed to.</p></li>\n</ol>\n\n<p>(Making this a community wiki, since borrowing from the existing answers wouldn't be fair otherwise.)</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
If so, does it effectively deprecate the `visibility` property? (I realize that Internet Explorer does not yet support this CSS2 property.) [Comparisons of layout engines](http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties) [See also: What is the difference between visibility:hidden and display:none](https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone)
Here is a compilation of verified information from the various answers. Each of these CSS properties is unique. In addition to rendering an element not visible, they have the following additional effect(s): 1. **Collapses** the space that the element would normally occupy 2. Responds to **events** (e.g., click, keypress) 3. Participates in the **taborder** ``` collapse events taborder opacity: 0 No Yes Yes visibility: hidden No No No visibility: collapse Yes* No No display: none Yes No No * Yes inside a table element, otherwise No. ```
272,361
<p>I wrote a PHP code like this</p> <pre><code>$site="http://www.google.com"; $content = file_get_content($site); echo $content; </code></pre> <p>But when I remove "http://" from <code>$site</code> I get the following warning:</p> <blockquote> <p>Warning: file_get_contents(www.google.com) [function.file-get-contents]: failed to open stream:</p> </blockquote> <p>I tried <code>try</code> and <code>catch</code> but it didn't work.</p>
[ { "answer_id": 272373, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "<p>You can prepend an @:\n<code>$content = @file_get_contents($site);</code></p>\n\n<p>This will supress any warning - <b>use sparingly!</b>. See <a href=\"http://www.php.net/@\" rel=\"noreferrer\">Error Control Operators</a></p>\n\n<p>Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called \"www.google.....\"</p>\n" }, { "answer_id": 272377, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 10, "selected": true, "text": "<p>Step 1: check the return code: <code>if($content === FALSE) { // handle error here... }</code></p>\n\n<p>Step 2: suppress the warning by putting an <a href=\"http://php.net/manual/en/language.operators.errorcontrol.php\" rel=\"noreferrer\">error control operator</a> (i.e. <code>@</code>) in front of the call to <em>file_get_contents()</em>:\n<code>$content = @file_get_contents($site);</code></p>\n" }, { "answer_id": 272724, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones.\n<a href=\"http://www.php.net/set_error_handler\" rel=\"noreferrer\">http://www.php.net/set_error_handler</a></p>\n" }, { "answer_id": 617721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!</p>\n\n<pre><code>$content = @file_get_contents(\"http://www.google.com\");\nif (strpos($http_response_header[0], \"200\")) { \n echo \"SUCCESS\";\n} else { \n echo \"FAILED\";\n} \n</code></pre>\n" }, { "answer_id": 3406181, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 7, "selected": false, "text": "<p>You can also <a href=\"http://us2.php.net/set_error_handler\" rel=\"noreferrer\">set your error handler</a> as an <a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"noreferrer\">anonymous function</a> that calls an <a href=\"http://us.php.net/manual/en/class.errorexception.php\" rel=\"noreferrer\">Exception</a> and use a try / catch on that exception.</p>\n\n<pre><code>set_error_handler(\n function ($severity, $message, $file, $line) {\n throw new ErrorException($message, $severity, $severity, $file, $line);\n }\n);\n\ntry {\n file_get_contents('www.google.com');\n}\ncatch (Exception $e) {\n echo $e-&gt;getMessage();\n}\n\nrestore_error_handler();\n</code></pre>\n\n<p>Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.</p>\n" }, { "answer_id": 6463291, "author": "Aram Kocharyan", "author_id": 549848, "author_profile": "https://Stackoverflow.com/users/549848", "pm_score": 5, "selected": false, "text": "<p>One alternative is to suppress the error and also throw an exception which you can catch later. This is especially useful if there are multiple calls to file_get_contents() in your code, since you don't need to suppress and handle all of them manually. Instead, several calls can be made to this function in a single try/catch block.</p>\n\n<pre><code>// Returns the contents of a file\nfunction file_contents($path) {\n $str = @file_get_contents($path);\n if ($str === FALSE) {\n throw new Exception(\"Cannot access '$path' to read contents.\");\n } else {\n return $str;\n }\n}\n\n// Example\ntry {\n file_contents(\"a\");\n file_contents(\"b\");\n file_contents(\"c\");\n} catch (Exception $e) {\n // Deal with it.\n echo \"Error: \" , $e-&gt;getMessage();\n}\n</code></pre>\n" }, { "answer_id": 9461675, "author": "ogie", "author_id": 1235083, "author_profile": "https://Stackoverflow.com/users/1235083", "pm_score": -1, "selected": false, "text": "<p>You could use this script</p>\n\n<pre><code>$url = @file_get_contents(\"http://www.itreb.info\");\nif ($url) {\n // if url is true execute this \n echo $url;\n} else {\n // if not exceute this \n echo \"connection error\";\n}\n</code></pre>\n" }, { "answer_id": 13365281, "author": "Laurie", "author_id": 1603948, "author_profile": "https://Stackoverflow.com/users/1603948", "pm_score": 7, "selected": false, "text": "<p>My favorite way to do this is fairly simple:</p>\n<pre><code>if (($data = @file_get_contents(&quot;http://www.google.com&quot;)) === false) {\n $error = error_get_last();\n echo &quot;HTTP request failed. Error was: &quot; . $error['message'];\n} else {\n echo &quot;Everything went better than expected&quot;;\n}\n</code></pre>\n<p>I found this after experimenting with the <code>try/catch</code> from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use <code>error_get_last</code> to get the text of the last error, and <code>file_get_contents</code> returns false on failure, so a simple &quot;if&quot; can catch that.</p>\n" }, { "answer_id": 21976530, "author": "Jrm", "author_id": 3344672, "author_profile": "https://Stackoverflow.com/users/3344672", "pm_score": 3, "selected": false, "text": "<p>Here's how I handle that:</p>\n\n<pre><code>$this-&gt;response_body = @file_get_contents($this-&gt;url, false, $context);\nif ($this-&gt;response_body === false) {\n $error = error_get_last();\n $error = explode(': ', $error['message']);\n $error = trim($error[2]) . PHP_EOL;\n fprintf(STDERR, 'Error: '. $error);\n die();\n}\n</code></pre>\n" }, { "answer_id": 21976746, "author": "RafaSashi", "author_id": 2456038, "author_profile": "https://Stackoverflow.com/users/2456038", "pm_score": 4, "selected": false, "text": "<pre><code>function custom_file_get_contents($url) {\n return file_get_contents(\n $url,\n false,\n stream_context_create(\n array(\n 'http' =&gt; array(\n 'ignore_errors' =&gt; true\n )\n )\n )\n );\n}\n\n$content=FALSE;\n\nif($content=custom_file_get_contents($url)) {\n //play with the result\n} else {\n //handle the error\n}\n</code></pre>\n" }, { "answer_id": 24831155, "author": "Bob Stein", "author_id": 673991, "author_profile": "https://Stackoverflow.com/users/673991", "pm_score": 0, "selected": false, "text": "<p>Since PHP 4 use <a href=\"http://php.net/function.error_reporting\" rel=\"nofollow\">error_reporting()</a>:</p>\n\n<pre><code>$site=\"http://www.google.com\";\n$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);\n$content = file_get_content($site);\nerror_reporting($old_error_reporting);\nif ($content === FALSE) {\n echo \"Error getting '$site'\";\n} else {\n echo $content;\n}\n</code></pre>\n" }, { "answer_id": 38642120, "author": "Brad", "author_id": 26130, "author_profile": "https://Stackoverflow.com/users/26130", "pm_score": -1, "selected": false, "text": "<p>This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.</p>\n\n<pre><code>try {\n $content = file_get_contents($site);\n} catch(\\Exception $e) {\n return 'The file was not found';\n}\n</code></pre>\n" }, { "answer_id": 39837955, "author": "Jesús Díaz", "author_id": 1679158, "author_profile": "https://Stackoverflow.com/users/1679158", "pm_score": -1, "selected": false, "text": "<p>You should use file_exists() function before to use file_get_contents().\nWith this way you'll avoid the php warning.</p>\n\n<pre><code>$file = \"path/to/file\";\n\nif(file_exists($file)){\n $content = file_get_contents($file);\n}\n</code></pre>\n" }, { "answer_id": 54588076, "author": "Muhammad Adeel Malik", "author_id": 8307587, "author_profile": "https://Stackoverflow.com/users/8307587", "pm_score": -1, "selected": false, "text": "<p>Simplest way to do this is just prepend an @ before file_get_contents,\ni.&nbsp;e.:</p>\n\n<pre><code>$content = @file_get_contents($site); \n</code></pre>\n" }, { "answer_id": 55815800, "author": "Michael de Oz", "author_id": 4215940, "author_profile": "https://Stackoverflow.com/users/4215940", "pm_score": -1, "selected": false, "text": "<p>something like this:</p>\n\n<pre><code>public function get($curl,$options){\n $context = stream_context_create($options);\n $file = @file_get_contents($curl, false, $context);\n $str1=$str2=$status=null;\n sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);\n if($status==200)\n return $file \n else \n throw new \\Exception($http_response_header[0]);\n}\n</code></pre>\n" }, { "answer_id": 60255497, "author": "Frank Rich", "author_id": 9986479, "author_profile": "https://Stackoverflow.com/users/9986479", "pm_score": -1, "selected": false, "text": "<pre><code>if (!file_get_contents($data)) {\n exit('&lt;h1&gt;ERROR MESSAGE&lt;/h1&gt;');\n} else {\n return file_get_contents($data);\n}\n</code></pre>\n" }, { "answer_id": 69505316, "author": "Công Thịnh", "author_id": 16816194, "author_profile": "https://Stackoverflow.com/users/16816194", "pm_score": -1, "selected": false, "text": "<p>I was resolve all problem, it's work all links</p>\n<pre><code>public function getTitle($url)\n {\n try {\n if (strpos($url, 'www.youtube.com/watch') !== false) {\n $apikey = 'AIzaSyCPeA3MlMPeT1CU18NHfJawWAx18VoowOY';\n $videoId = explode('&amp;', explode(&quot;=&quot;, $url)[1])[0];\n $url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $videoId . '&amp;key=' . $apikey . '&amp;part=snippet';\n\n $ch = curl_init();\n\n curl_setopt($ch, CURLOPT_HEADER, 0);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);\n curl_setopt($ch, CURLOPT_VERBOSE, 0);\n curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);\n $response = curl_exec($ch);\n curl_close($ch);\n\n $data = json_decode($response);\n $value = json_decode(json_encode($data), true);\n\n $title = $value['items'][0]['snippet']['title'];\n } else {\n set_error_handler(\n function () {\n return false;\n }\n );\n if (($str = file_get_contents($url)) === false) {\n $title = $url;\n } else {\n preg_match(&quot;/\\&lt;title\\&gt;(.*)\\&lt;\\/title\\&gt;/i&quot;, $str, $title);\n $title = $title[1];\n if (preg_replace('/[\\x00-\\x1F\\x7F-\\xFF]/', '', $title))\n $title = utf8_encode($title);\n $title = html_entity_decode($title);\n }\n restore_error_handler();\n }\n } catch (Exception $e) {\n $title = $url;\n }\n return $title;\n }\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
I wrote a PHP code like this ``` $site="http://www.google.com"; $content = file_get_content($site); echo $content; ``` But when I remove "http://" from `$site` I get the following warning: > > Warning: > file\_get\_contents(www.google.com) > [function.file-get-contents]: failed > to open stream: > > > I tried `try` and `catch` but it didn't work.
Step 1: check the return code: `if($content === FALSE) { // handle error here... }` Step 2: suppress the warning by putting an [error control operator](http://php.net/manual/en/language.operators.errorcontrol.php) (i.e. `@`) in front of the call to *file\_get\_contents()*: `$content = @file_get_contents($site);`
272,368
<p>If I have a method with a parameter that's an interface, whats the fasts way to see if the interface's reference is of a specific generic type?</p> <p>More specifically, if I have:</p> <pre><code>interface IVehicle{} class Car&lt;T&gt; : IVehicle {} CheckType(IVehicle param) { // How do I check that param is Car&lt;int&gt;? } </code></pre> <p>I'm also going to have to cast after the check. So if there is a way to kill 2 birds with one stone on this one let me know.</p>
[ { "answer_id": 272393, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>To check if param is a <code>Car&lt;int&gt;</code> you can use \"is\" and \"as\" as normal:</p>\n\n<pre><code>CheckType(IVehicle param)\n{\n Car&lt;int&gt; car = param as Car&lt;int&gt;;\n if (car != null)\n {\n ...\n }\n}\n</code></pre>\n" }, { "answer_id": 272396, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>I often find that if my code requires me to write checks for specific types, I'm probably doing something wrong. You didn't give us enough context for us to give advice on this, though.</p>\n\n<p>Does this meet your needs?</p>\n\n<pre><code>Car&lt;int&gt; carOfInt = param as Car&lt;int&gt;;\nif (carOfInt != null)\n{\n // .. yes, it's a Car&lt;int&gt;\n}\n</code></pre>\n" }, { "answer_id": 272402, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 0, "selected": false, "text": "<p>Use the \"as\" operator to do it all in one shot. \"as\" will return either an object of the type you want, or null if what you're checking against doesn't match. This will only work for reference types, though.</p>\n\n<pre><code>interface IVehicle { }\nclass Car&lt;T&gt; : IVehicle \n{\n static Car&lt;int&gt; CheckType(IVehicle v)\n {\n return v as Car&lt;int&gt;;\n }\n}\n</code></pre>\n\n<p>The \"is\" operator will let you test to see if <code>v</code> is an instance of <code>Car&lt;int&gt;</code>.</p>\n" }, { "answer_id": 272405, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 2, "selected": false, "text": "<p>Or, you can just do:</p>\n\n<pre><code>if(param is Car&lt;int&gt;)\n{\n // Hey, I'm a Car&lt;int&gt;!\n}\n</code></pre>\n" }, { "answer_id": 272444, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 1, "selected": false, "text": "<p>Why not make this generic?</p>\n\n<pre><code>interface IVehicle{}\n\nclass Car&lt;T&gt; : IVehicle {\n\n public static bool CheckType(IVehicle param)\n {\n return param is Car&lt;T&gt;;\n }\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>Car&lt;string&gt; c1 = new Car&lt;string&gt;();\nCar&lt;int&gt; c2 = new Car&lt;int&gt;();\nConsole.WriteLine(Car&lt;int&gt;.CheckType(c1));\nConsole.WriteLine(Car&lt;int&gt;.CheckType(c2));\n</code></pre>\n" }, { "answer_id": 273075, "author": "Robert Giesecke", "author_id": 35443, "author_profile": "https://Stackoverflow.com/users/35443", "pm_score": 1, "selected": false, "text": "<p>The code differs quite dramatically depending on whether you want to know, if the reference is based on a generic type prototype, or a specialized one.</p>\n\n<p>The specialized one is easy, you can just use <code>is</code>:</p>\n\n<pre><code>CheckType(IVehicle param)\n{\n var isofYourType = param is Car&lt;int&gt;;\n ...\n}\n</code></pre>\n\n<p>or a safe cast, as shown before:</p>\n\n<pre><code>CheckType(IVehicle param)\n{\n var value = param as Car&lt;int&gt;;\n if(value != null) \n ...\n}\n</code></pre>\n\n<p>In case you wanted to know whether yur var is just some specialization of <code>Car&lt;T&gt;</code>, things get really <strong>ugly</strong>.\nAnd the last you should thing to worry about is speed in this case, because that's gonna be even uglier than the code <em>g</em>:</p>\n\n<pre><code>class Car&lt;T&gt;\n{ }\n\ninterface IVehicle { }\n\nclass YourCar : Car&lt;int&gt;, IVehicle\n{ }\n\nstatic bool IsOfType(IVehicle param)\n{\n Type typeRef = param.GetType();\n while (typeRef != null)\n {\n if (typeRef.IsGenericType &amp;&amp;\n typeRef.GetGenericTypeDefinition() == typeof(Car&lt;&gt;))\n {\n return true;\n }\n typeRef = typeRef.BaseType;\n }\n return false;\n}\n\nstatic void Main(string[] args)\n{\n IVehicle test = new YourCar();\n bool x = IsOfType(test);\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
If I have a method with a parameter that's an interface, whats the fasts way to see if the interface's reference is of a specific generic type? More specifically, if I have: ``` interface IVehicle{} class Car<T> : IVehicle {} CheckType(IVehicle param) { // How do I check that param is Car<int>? } ``` I'm also going to have to cast after the check. So if there is a way to kill 2 birds with one stone on this one let me know.
To check if param is a `Car<int>` you can use "is" and "as" as normal: ``` CheckType(IVehicle param) { Car<int> car = param as Car<int>; if (car != null) { ... } } ```
272,387
<p>In SQL Server 2005, I want to print out a blank line with the PRINT statement, however, when I run</p> <pre><code>PRINT '' </code></pre> <p>it actually prints a line with a single space.</p> <p>Does anyone know if it's possible to just print a blank line without the space?</p> <p>If I print a new line character, it doesn't print a space, but I end up with two new lines.</p>
[ { "answer_id": 272404, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>AFAIK there is no way around this, it is the way the print statement works</p>\n" }, { "answer_id": 272430, "author": "Loris", "author_id": 23824, "author_profile": "https://Stackoverflow.com/users/23824", "pm_score": 3, "selected": false, "text": "<p>You could just add a newline on your previous print statement, if you have one.</p>\n\n<p>Instead of:</p>\n\n<pre><code>PRINT 'BLABLABLA'\nPRINT ''\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>PRINT 'BLABLABLA\n' &lt;- the string finishes here!\n</code></pre>\n" }, { "answer_id": 272467, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 1, "selected": false, "text": "<p>Can you encode the BACKSPACE character and PRINT that out?</p>\n\n<p>UPDATE: PRINT '' + CHAR(8) doesn't seem to go down particularly well :(</p>\n" }, { "answer_id": 272691, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This suggests that you want to print a blank message. Are you sure that this is your intention? The Print statement actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. </p>\n" }, { "answer_id": 273013, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 3, "selected": false, "text": "<p>Very similar to the other suggestion here, this seems to work:</p>\n\n<pre><code>print '\n'</code></pre>\n" }, { "answer_id": 1718073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>-- Search the web for: SQL PRINT NewLine\n-- What you'll end up finding:\n\nDECLARE @CR AS CHAR(1) -- Carriage Return (CR)\nDECLARE @LF AS CHAR(1) -- Line Feed (LF)\nDECLARE @CrLf AS CHAR(2) -- Carriage Return / Line Feed\n\nSET @CR = CHAR(10)\nSET @LF = CHAR(13)\nSET @CrLf = @CR + @LF\n\nPRINT '--==--==--==--==--=='\nPRINT @CrLf + 'Use variables as you see fit' + @CrLf\nPRINT '--==--==--==--==--=='\n\n-- AntGut\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In SQL Server 2005, I want to print out a blank line with the PRINT statement, however, when I run ``` PRINT '' ``` it actually prints a line with a single space. Does anyone know if it's possible to just print a blank line without the space? If I print a new line character, it doesn't print a space, but I end up with two new lines.
You could just add a newline on your previous print statement, if you have one. Instead of: ``` PRINT 'BLABLABLA' PRINT '' ``` You could write: ``` PRINT 'BLABLABLA ' <- the string finishes here! ```
272,412
<p>i want something like this</p> <ol> <li><p>the user enter a website link</p></li> <li><p>i need check the link if the link doesn't start with 'http://' I want to append 'http://' to the link .</p></li> </ol> <p>how can I do that in PHP ? </p>
[ { "answer_id": 272421, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 5, "selected": true, "text": "<pre><code>if (stripos($url, 'http://') !== 0) {\n $url = 'http://' . $url;\n}\n</code></pre>\n" }, { "answer_id": 272432, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "<p>I'll recommend a slight improvement over tom's</p>\n\n<blockquote>\n<pre><code>if (0 !== stripos($url, 'http://') &amp;&amp; 0 !== stripos($url, 'https://')) {\n $url = 'http://' . $url;\n}\n</code></pre>\n</blockquote>\n\n<p>However, this will mess up links that use other protocols (ftp:// svn:// gopher:// etc)</p>\n" }, { "answer_id": 272437, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 2, "selected": false, "text": "<pre><code>if (!preg_match(\"/^http:\\/{2}/\",$url)){\n $url = 'http://' . $url;\n}\n</code></pre>\n" }, { "answer_id": 275161, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 2, "selected": false, "text": "<p>I would check for the some letters followed by a colon. According to the URI specifications a colon is used to separate the \"schema\" (http, ftp etc.) from the \"schema specific part\". This way if somebody enters (for example) mailto links these are handled correctly. </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
i want something like this 1. the user enter a website link 2. i need check the link if the link doesn't start with 'http://' I want to append 'http://' to the link . how can I do that in PHP ?
``` if (stripos($url, 'http://') !== 0) { $url = 'http://' . $url; } ```
272,429
<p>I have 4 different named instances of SQL Server 2005 on a single server (for testing purposes). There is no default instance on the server.</p> <p>Because I will eventually need to allow communication to these instances across the firewall, I have set the ports of each instance statically listening on all IPs for the server.</p> <p><strong>Edit</strong>: TCP/IP, Shared Memory, and Named Pipes are all enabled. VIA is disabled. The ports are statically set for All IPs on the TCP/IP protocol, and each named instance is using a separate port.</p> <p>I also have SQLBrowser service running, and all instances are configured to allow remote connections.</p> <p>One instance is set to the default port (1433), and it works fine.</p> <p>The other instances, however, exhibit very strange behavior. When I connect to them using the Sql Server Management Studio within the network (so I'm not even crossing the firewall yet), the studio connects without complaining. However, as soon as I try to expand the Database list for the instance, or refresh the instance, or pretty much anything else, I get the following error:</p> <p>TITLE: Microsoft SQL Server Management Studio</p> <hr> <p>Failed to retrieve data for this request. (Microsoft.SqlServer.SmoEnum)</p> <p>For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;LinkId=20476" rel="nofollow noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;LinkId=20476</a></p> <hr> <p>ADDITIONAL INFORMATION:</p> <p>Failed to connect to server . (Microsoft.SqlServer.ConnectionInfo)</p> <hr> <p>A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)</p> <p>For help, click: <a href="http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=233&amp;LinkId=20476" rel="nofollow noreferrer">http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&amp;EvtSrc=MSSQLServer&amp;EvtID=233&amp;LinkId=20476</a></p> <hr>
[ { "answer_id": 272449, "author": "DCNYAM", "author_id": 30419, "author_profile": "https://Stackoverflow.com/users/30419", "pm_score": 0, "selected": false, "text": "<p>Try enabling TCP/IP communication to the SQL server instances. If you are eventually going to be traversing a firewall, you'll probably want to use TCP/IP instead of named pipes anyway. </p>\n" }, { "answer_id": 272488, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 1, "selected": false, "text": "<p>Try using different TCP/IP ports for each instance on the server. You will need to go into the SQL Server Configuration Manager to change these settings. Under TCP/IP you can change the port numbers and then use these in your connection string or in SQL Management Studio when connecting.</p>\n\n<p>Out of curiosity, why do you have for instances o the server? Can you use one instance and have multiple databases instead? If you are using other instances for development or testing you might want to consider moving those to another box.</p>\n" }, { "answer_id": 272567, "author": "andyhky", "author_id": 2764, "author_profile": "https://Stackoverflow.com/users/2764", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>The first thing to do would be to try\n adding the prefix np: or tcp: (for\n either Named Pipes or TCP/IP) before\n the name of the server. For tcp/ip,\n you can also try adding the port\n number (,1433) after the name of the\n server. If this is not the default\n instance, you must add the name of the\n instance after the name of the server;\n for example:</p>\n</blockquote>\n\n<pre><code>&gt; sqlcmd -S\n&gt; tcp:NameOfTheServer\\sqlexpress,1433\n</code></pre>\n\n<p>EDIT: removed source link, as it is now a dead link</p>\n" }, { "answer_id": 273773, "author": "Nathan", "author_id": 24954, "author_profile": "https://Stackoverflow.com/users/24954", "pm_score": 2, "selected": false, "text": "<p>Bofe's answer worked, so that gave an indication that something was askew with the ports.</p>\n\n<p>It turns out that in the TCP/IP settings for the named instances, I had listen All set on the protocol, and then had a static port set for IPAll, but dynamic port set for IP1. I had assumed that since IP1 was disabled, I didn't need to worry about it, but apparently if you have Listen All set, then the enabled property for IP1 is ignored. So, having only one ip address on the server, and configuring IP1 dynamic ports, and IPAll static ports caused some sort of weird conflict.</p>\n\n<p>To fix the problem, I just set IP1 to use the same static port as IPAll, enabled IP1, rebooted the server, and things worked like they were supposed to, without having to explicitly set the port in the connection string.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24954/" ]
I have 4 different named instances of SQL Server 2005 on a single server (for testing purposes). There is no default instance on the server. Because I will eventually need to allow communication to these instances across the firewall, I have set the ports of each instance statically listening on all IPs for the server. **Edit**: TCP/IP, Shared Memory, and Named Pipes are all enabled. VIA is disabled. The ports are statically set for All IPs on the TCP/IP protocol, and each named instance is using a separate port. I also have SQLBrowser service running, and all instances are configured to allow remote connections. One instance is set to the default port (1433), and it works fine. The other instances, however, exhibit very strange behavior. When I connect to them using the Sql Server Management Studio within the network (so I'm not even crossing the firewall yet), the studio connects without complaining. However, as soon as I try to expand the Database list for the instance, or refresh the instance, or pretty much anything else, I get the following error: TITLE: Microsoft SQL Server Management Studio --- Failed to retrieve data for this request. (Microsoft.SqlServer.SmoEnum) For help, click: <http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476> --- ADDITIONAL INFORMATION: Failed to connect to server . (Microsoft.SqlServer.ConnectionInfo) --- A connection was successfully established with the server, but then an error occurred during the login process. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233) For help, click: <http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476> ---
> > The first thing to do would be to try > adding the prefix np: or tcp: (for > either Named Pipes or TCP/IP) before > the name of the server. For tcp/ip, > you can also try adding the port > number (,1433) after the name of the > server. If this is not the default > instance, you must add the name of the > instance after the name of the server; > for example: > > > ``` > sqlcmd -S > tcp:NameOfTheServer\sqlexpress,1433 ``` EDIT: removed source link, as it is now a dead link
272,433
<p>Some programs read the company name that you entered when Windows was installed and display it in the program. How is this done? Are they simply reading the name from the registry?</p>
[ { "answer_id": 272496, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "<p>Check the API SystemParametersInfo and a constant named SPI_GETOEMINFO </p>\n\n<pre><code>int details = SystemParametersInfo(SPI_GETOEMINFO, OEMInfo.Capacity, OEMInfo, 0);\n if (details != 0)\n {\n MessageBox.Show(OEMInfo.ToString());\n }\n</code></pre>\n\n<p>That will return the companyname for the OEM. I dont think you have to enter company name when installing windows, only computer name ( I can be wrong here)</p>\n\n<p>You can see all the constants and examples here:<br>\n<a href=\"http://pinvoke.net/default.aspx/Enums.SystemMetric\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/Enums.SystemMetric</a></p>\n" }, { "answer_id": 272500, "author": "Xiaofu", "author_id": 31967, "author_profile": "https://Stackoverflow.com/users/31967", "pm_score": 4, "selected": false, "text": "<p>If you want the registered company name as entered in the registry, you can get it from:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n</code></pre>\n\n<p>Using the Registry class you can do something along these lines:</p>\n\n<pre><code>string org = (string)Microsoft.Win32.Registry.GetValue(@\"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\", \"RegisteredOrganization\", \"\");\n</code></pre>\n" }, { "answer_id": 272501, "author": "GeneQ", "author_id": 22556, "author_profile": "https://Stackoverflow.com/users/22556", "pm_score": 2, "selected": false, "text": "<p>Windows stores the registered company name in the registry at :</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n</code></pre>\n\n<p>Import the following :</p>\n\n<pre><code>using Microsoft.Win32;\n</code></pre>\n\n<p>Read the value of the registry key required, like so:</p>\n\n<pre><code>RegistryKey hklm = Registry.LocalMachine;\nhklm = hklm.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\");\nObject obp = hklm.GetValue(\"RegisteredOrganization\");`\nConsole.WriteLine(\"RegisteredOrganization :{0}\",obp);`\n</code></pre>\n\n<p>Or a one liner, as suggested by <a href=\"https://stackoverflow.com/users/31967/xiaofu\">Xiaofu</a>.</p>\n\n<p><em>However, the correct way is to use a double backslash. This is because the backslash is the C# escape character - that is, you can insert a newline character using \\n, or tab using \\t therefore to let C# know that we want a plain backslash and not some escaped character, we have to use two backslashes (\\) or use @ in front of the string like (@\"\\somestring\") :</em></p>\n\n<pre><code>string org = (string)Microsoft.Win32.Registry.GetValue(\"HKEY_LOCAL_MACHINE\\\\\\Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", \"RegisteredOrganization\", \"\");\n</code></pre>\n\n<p><strong>Note:</strong> The RegisteredOrganization key is not guaranteed to contain a value, as it may not have been filled in during the OS installation. So always use a try/catch block or check the returned value.</p>\n" }, { "answer_id": 272508, "author": "Ken Pespisa", "author_id": 30812, "author_profile": "https://Stackoverflow.com/users/30812", "pm_score": 0, "selected": false, "text": "<p>I couldn't find a method or property in .NET that gets you the information, but I found a technote that tells what registry key contains the info:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\RegisteredOrganization\n</code></pre>\n\n<p><a href=\"http://support.microsoft.com/kb/310441\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/310441</a></p>\n" }, { "answer_id": 272603, "author": "Murph", "author_id": 1070, "author_profile": "https://Stackoverflow.com/users/1070", "pm_score": 2, "selected": false, "text": "<p>You can read this Using WMI, it looks to me like you're after the Win32_OperatingSystem class and the Organization element of that class holds the company name.</p>\n\n<p>The code below is a console app that shows the registered user and organization. To get it to run you'll need to add a reference to System.Management.dll to the project. There should only be one management object so the foreach is probably redundant, not quite sure what best practice for that would be:</p>\n\n<pre><code>using System;\nusing System.Management;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n ManagementClass c = new ManagementClass(\"Win32_OperatingSystem\");\n\n foreach (ManagementObject o in c.GetInstances())\n {\n Console.WriteLine(\"Registered User: {0}, Organization: {1}\", o[\"RegisteredUser\"], o[\"Organization\"]);\n }\n Console.WriteLine(\"Finis!\");\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 272642, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": -1, "selected": false, "text": "<p>I don't like to have text-y registry calls in my business code, and I'm not a fan of utility classes, so I wrote an extension method that gets the company name from the registry.</p>\n\n<pre><code>using Microsoft.Win32;\n\nnamespace Extensions\n{\n public static class MyExtensions\n {\n public static string CompanyName(this RegistryKey key)\n {\n // this string goes in my resources file usually\n return (string)key.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\").GetValue(\"RegisteredOrganization\");\n }\n }\n}\n</code></pre>\n\n<p>Then I can easily get that value:</p>\n\n<pre><code>RegistryKey key = Registry.LocalMachine;\nreturn key.CompanyName();\n</code></pre>\n\n<p>It's nothing fancy, just a prettier way of dealing with oft-retrieved registry values.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Some programs read the company name that you entered when Windows was installed and display it in the program. How is this done? Are they simply reading the name from the registry?
If you want the registered company name as entered in the registry, you can get it from: ``` HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization ``` Using the Registry class you can do something along these lines: ``` string org = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization", ""); ```
272,438
<p>Suppose I create a table in Postgresql with a comment on a column:</p> <pre><code>create table t1 ( c1 varchar(10) ); comment on column t1.c1 is 'foo'; </code></pre> <p>Some time later, I decide to add another column:</p> <pre><code>alter table t1 add column c2 varchar(20); </code></pre> <p>I want to look up the comment contents of the first column, and associate with the new column:</p> <pre><code>select comment_text from (what?) where table_name = 't1' and column_name = 'c1' </code></pre> <p>The (what?) is going to be a system table, but after having looked around in pgAdmin and searching on the web I haven't learnt its name.</p> <p>Ideally I'd like to be able to:</p> <pre><code>comment on column t1.c1 is (select ...); </code></pre> <p>but I have a feeling that's stretching things a bit far. Thanks for any ideas.</p> <p>Update: based on the suggestions I received here, I wound up writing a program to automate the task of transferring comments, as part of a larger process of changing the datatype of a Postgresql column. You can read about that <a href="http://wirespeed.wordpress.com/2008/11/07/alter-column-type-postgres/" rel="nofollow noreferrer">on my blog</a>.</p>
[ { "answer_id": 272525, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 1, "selected": false, "text": "<p>You can retrieve comments on columns using the system function col_description(table_oid, column_number). See <a href=\"http://www.postgresql.org/docs/8.2/static/functions-info.html#FUNCTIONS-INFO-COMMENT-TABLE\" rel=\"nofollow noreferrer\">this page</a> for further details.</p>\n" }, { "answer_id": 272539, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<p>The next thing to know is how to obtain the table oid. I think that using this as part of comment on will not work, as you suspect.</p>\n\n<pre>\n postgres=# create table comtest1 (id int, val varchar);\n CREATE TABLE\n postgres=# insert into comtest1 values (1,'a');\n INSERT 0 1\n postgres=# select distinct tableoid from comtest1;\n tableoid\n ----------\n 32792\n (1 row)\n\n postgres=# comment on column comtest1.id is 'Identifier Number One';\n COMMENT\n postgres=# select col_description(32792,1);\n col_description\n -----------------------\n Identifier Number One\n (1 row)\n</pre>\n\n<p>Anyhow, I whipped up a quick plpgsql function to copy comments from one table/column pair to another. You have to createlang plpgsql on the database and use it like this:</p>\n\n<pre>\n Copy the comment on the first column of table comtest1 to the id \n column of the table comtest2. Yes, it should be improved but \n that's left as work for the reader.\n\n postgres=# select copy_comment('comtest1',1,'comtest2','id');\n copy_comment\n --------------\n 1\n (1 row)\n</pre>\n\n<pre><code>CREATE OR REPLACE FUNCTION copy_comment(varchar,int,varchar,varchar) RETURNS int AS $PROC$\nDECLARE\n src_tbl ALIAS FOR $1;\n src_col ALIAS FOR $2;\n dst_tbl ALIAS FOR $3;\n dst_col ALIAS FOR $4;\n row RECORD;\n oid INT;\n comment VARCHAR;\nBEGIN\n FOR row IN EXECUTE 'SELECT DISTINCT tableoid FROM ' || quote_ident(src_tbl) LOOP\n oid := row.tableoid;\n END LOOP;\n\n FOR row IN EXECUTE 'SELECT col_description(' || quote_literal(oid) || ',' || quote_literal(src_col) || ')' LOOP\n comment := row.col_description;\n END LOOP;\n\n EXECUTE 'COMMENT ON COLUMN ' || quote_ident(dst_tbl) || '.' || quote_ident(dst_col) || ' IS ' || quote_literal(comment);\n\n RETURN 1;\nEND;\n$PROC$ LANGUAGE plpgsql;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18625/" ]
Suppose I create a table in Postgresql with a comment on a column: ``` create table t1 ( c1 varchar(10) ); comment on column t1.c1 is 'foo'; ``` Some time later, I decide to add another column: ``` alter table t1 add column c2 varchar(20); ``` I want to look up the comment contents of the first column, and associate with the new column: ``` select comment_text from (what?) where table_name = 't1' and column_name = 'c1' ``` The (what?) is going to be a system table, but after having looked around in pgAdmin and searching on the web I haven't learnt its name. Ideally I'd like to be able to: ``` comment on column t1.c1 is (select ...); ``` but I have a feeling that's stretching things a bit far. Thanks for any ideas. Update: based on the suggestions I received here, I wound up writing a program to automate the task of transferring comments, as part of a larger process of changing the datatype of a Postgresql column. You can read about that [on my blog](http://wirespeed.wordpress.com/2008/11/07/alter-column-type-postgres/).
The next thing to know is how to obtain the table oid. I think that using this as part of comment on will not work, as you suspect. ``` postgres=# create table comtest1 (id int, val varchar); CREATE TABLE postgres=# insert into comtest1 values (1,'a'); INSERT 0 1 postgres=# select distinct tableoid from comtest1; tableoid ---------- 32792 (1 row) postgres=# comment on column comtest1.id is 'Identifier Number One'; COMMENT postgres=# select col_description(32792,1); col_description ----------------------- Identifier Number One (1 row) ``` Anyhow, I whipped up a quick plpgsql function to copy comments from one table/column pair to another. You have to createlang plpgsql on the database and use it like this: ``` Copy the comment on the first column of table comtest1 to the id column of the table comtest2. Yes, it should be improved but that's left as work for the reader. postgres=# select copy_comment('comtest1',1,'comtest2','id'); copy_comment -------------- 1 (1 row) ``` ``` CREATE OR REPLACE FUNCTION copy_comment(varchar,int,varchar,varchar) RETURNS int AS $PROC$ DECLARE src_tbl ALIAS FOR $1; src_col ALIAS FOR $2; dst_tbl ALIAS FOR $3; dst_col ALIAS FOR $4; row RECORD; oid INT; comment VARCHAR; BEGIN FOR row IN EXECUTE 'SELECT DISTINCT tableoid FROM ' || quote_ident(src_tbl) LOOP oid := row.tableoid; END LOOP; FOR row IN EXECUTE 'SELECT col_description(' || quote_literal(oid) || ',' || quote_literal(src_col) || ')' LOOP comment := row.col_description; END LOOP; EXECUTE 'COMMENT ON COLUMN ' || quote_ident(dst_tbl) || '.' || quote_ident(dst_col) || ' IS ' || quote_literal(comment); RETURN 1; END; $PROC$ LANGUAGE plpgsql; ```
272,454
<p><a href="http://localhost:50034/Admin/Delete/723" rel="nofollow noreferrer">http://localhost:50034/Admin/Delete/723</a></p> <p>Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything?</p> <p>Thanks.</p>
[ { "answer_id": 272472, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>public ActionResult Details(int? Id)\n{\n if (Id == null)\n return RedirectToAction(\"Index\");\n return View();\n}\n</code></pre>\n" }, { "answer_id": 272482, "author": "Torkel", "author_id": 24425, "author_profile": "https://Stackoverflow.com/users/24425", "pm_score": 4, "selected": true, "text": "<p>I am not sure what you mean, do you mean that the url <a href=\"http://localhost:50034/Admin/Delete/\" rel=\"noreferrer\">http://localhost:50034/Admin/Delete/</a> is generating an exception? </p>\n\n<p>Try setting the id parameter as nullable, like this:</p>\n\n<pre><code>public class MyController : Controller\n{\n public void Delete(int? id)\n {\n if (!id.HasValue)\n {\n return RedirectToAction(\"Index\", \"Home\");\n }\n\n ///\n }\n}\n</code></pre>\n" }, { "answer_id": 272515, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 1, "selected": false, "text": "<p>Assuming that you are using the default routing rules:</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\n<p>then create your Delete method with a nullable int (int?) for the id parameter similar to</p>\n\n<pre><code>public ActionResult Delete(int? id)\n{\n if (id.HasValue)\n {\n // do your normal stuff \n // to delete\n return View(\"afterDeleteView\");\n }\n else\n {\n // no id value passed\n return View(\"noParameterView\");\n }\n</code></pre>\n\n<p>}</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
<http://localhost:50034/Admin/Delete/723> Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything? Thanks.
I am not sure what you mean, do you mean that the url <http://localhost:50034/Admin/Delete/> is generating an exception? Try setting the id parameter as nullable, like this: ``` public class MyController : Controller { public void Delete(int? id) { if (!id.HasValue) { return RedirectToAction("Index", "Home"); } /// } } ```
272,457
<p>I'm looking into tightening up our ad code by moving it to an external jQuery script, but I obviously still need some HTML to target the ad to. So I was wondering if I can target a noscript element (or within a noscript element) since I'm going to have to leave that on the page anyway, or if I need to have some other element for the JavaScript to target?</p> <pre><code>&lt;noscript&gt; &lt;div class="ad"&gt;&lt;a href="foo"&gt;&lt;img src="bar" alt="ad" /&gt;&lt;/a&gt;&lt;/div&gt; &lt;/noscript&gt; </code></pre> <p>My intention would be to change or strip the noscript element.</p>
[ { "answer_id": 272460, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>If the browser has javascript enabled, the content inside the no-script element is NOT displayed.</p>\n\n<p>You would need to put it outside of that for the javascript targeting, and use the NoScript section for what its purpose is, users without JavaScript enabled.</p>\n" }, { "answer_id": 272461, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 0, "selected": false, "text": "<p>You could always use the JS to hide that ad using CSS, if nothing else.</p>\n" }, { "answer_id": 272471, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 2, "selected": false, "text": "<p>Why do you need the noscript element? If you are just going to remove or replace it with different elements when the javascript runs, then the div is acting as like a noscript element would anyway.</p>\n" }, { "answer_id": 272473, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 1, "selected": false, "text": "<p>Most browsers will not let you target the noscript element, even if you (incorrectly) give it an id. You might try something like <a href=\"http://dev.opera.com/articles/view/replacing-noscript-with-accessible-un/\" rel=\"nofollow noreferrer\">http://dev.opera.com/articles/view/replacing-noscript-with-accessible-un/</a> - it is a standard compliant method for achieving the same end, but without a noscript tag.</p>\n" }, { "answer_id": 272474, "author": "Lasar", "author_id": 9438, "author_profile": "https://Stackoverflow.com/users/9438", "pm_score": 4, "selected": true, "text": "<p><code>&lt;noscript&gt;</code> content is not only not displayed when JS is active, it apparently is also not in the DOM. I tried accessing content inside a <code>&lt;noscript&gt;</code> area (hoping you could <code>clone()</code> it with jQuery and insert it somewhere else) but got back nothing.</p>\n" }, { "answer_id": 272545, "author": "James Hughes", "author_id": 34671, "author_profile": "https://Stackoverflow.com/users/34671", "pm_score": 2, "selected": false, "text": "<p>You can target noscript elemements.</p>\n\n<pre><code> &lt;noscript&gt;asdfasFSD&lt;/noscript&gt;\n\n &lt;script&gt;\n alert(document.getElementsByTagName(\"noscript\")[0].innerHTML);\n &lt;/script&gt;\n</code></pre>\n\n<p>This works in FF3, IE6 and Google Chrome. It will alert asdfasFSD for me.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
I'm looking into tightening up our ad code by moving it to an external jQuery script, but I obviously still need some HTML to target the ad to. So I was wondering if I can target a noscript element (or within a noscript element) since I'm going to have to leave that on the page anyway, or if I need to have some other element for the JavaScript to target? ``` <noscript> <div class="ad"><a href="foo"><img src="bar" alt="ad" /></a></div> </noscript> ``` My intention would be to change or strip the noscript element.
`<noscript>` content is not only not displayed when JS is active, it apparently is also not in the DOM. I tried accessing content inside a `<noscript>` area (hoping you could `clone()` it with jQuery and insert it somewhere else) but got back nothing.
272,458
<p>I want my validation.xml to only check for a null if certain options are selected from a dropdown. So far I have</p> <pre><code>&lt;field property="empFDServiceStartDate" depends="requiredif, date"&gt; &lt;arg0 key="Service Start date" resource="false"/&gt; &lt;var&gt; &lt;var-name&gt;field[0]&lt;/var-name&gt; &lt;var-value&gt;moverChangeType&lt;/var-value&gt; &lt;/var&gt; &lt;var&gt; &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt; &lt;var-value&gt;EQUALS&lt;/var-value&gt; &lt;/var&gt; &lt;var&gt; &lt;var-name&gt;fieldValue[0]&lt;/var-name&gt; &lt;var-value&gt;Conversion&lt;/var-value&gt; &lt;/var&gt; &lt;/field&gt; </code></pre> <p>When the value "Conversion" is selected from the moverChangeType dropdown, I was hoping that the empFDServiceStartDate field would be checked for nulls before being saved. At the moment this doesn't work and it allows me to save nulls.</p> <p>Any idea?</p> <p>I am tied to struts 1.1 and therefore can't use newer commands.</p> <p>M</p>
[ { "answer_id": 272495, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 0, "selected": false, "text": "<p>If you want to check the field if moverChangeType equals \"Conversion\" try this...</p>\n\n<pre><code>&lt;field property=\"empFDServiceStartDate\" depends=\"requiredif, date\"&gt;\n &lt;arg0 key=\"Service Start date\" resource=\"false\"/&gt;\n &lt;var&gt;\n &lt;var-name&gt;test&lt;/var-name&gt;\n &lt;var-value&gt;(moverChangeType == \"Conversion\")&lt;/var-value&gt;\n &lt;/var&gt;\n&lt;/field&gt;\n</code></pre>\n" }, { "answer_id": 277365, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "<p>You can do this multiple test in the same test, like this:</p>\n\n<pre><code>&lt;field property=\"empFDServiceStartDate\" depends=\"requiredif, date\"&gt;\n &lt;arg0 key=\"Service Start date\" resource=\"false\"/&gt;\n &lt;var&gt;\n &lt;var-name&gt;test&lt;/var-name&gt;\n &lt;var-value&gt;((moverChangeType == \"Conversion\") or (moverChangeType == \"SomethingElse\"))&lt;/var-value&gt;\n &lt;/var&gt; \n&lt;/field&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want my validation.xml to only check for a null if certain options are selected from a dropdown. So far I have ``` <field property="empFDServiceStartDate" depends="requiredif, date"> <arg0 key="Service Start date" resource="false"/> <var> <var-name>field[0]</var-name> <var-value>moverChangeType</var-value> </var> <var> <var-name>fieldTest[0]</var-name> <var-value>EQUALS</var-value> </var> <var> <var-name>fieldValue[0]</var-name> <var-value>Conversion</var-value> </var> </field> ``` When the value "Conversion" is selected from the moverChangeType dropdown, I was hoping that the empFDServiceStartDate field would be checked for nulls before being saved. At the moment this doesn't work and it allows me to save nulls. Any idea? I am tied to struts 1.1 and therefore can't use newer commands. M
You can do this multiple test in the same test, like this: ``` <field property="empFDServiceStartDate" depends="requiredif, date"> <arg0 key="Service Start date" resource="false"/> <var> <var-name>test</var-name> <var-value>((moverChangeType == "Conversion") or (moverChangeType == "SomethingElse"))</var-value> </var> </field> ```
272,459
<p>I wonder if there is a way to set the value of #define in run time.</p> <p>I assume that there is a query for Oracle specific and Sql Server specific at the code below.</p> <pre><code>#define oracle // ... #if oracle // some code #else // some different code. #endif </code></pre>
[ { "answer_id": 272475, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 5, "selected": true, "text": "<p>Absolutely not, #defines are compiled out by the preprocessor before the compiler even sees it - so the token 'oracle' isn't even in your code, just '1' or '0'. Change the #define to a global variable or (better) a function that returns the correct value.</p>\n" }, { "answer_id": 272476, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p><code>#if</code> is compile-time. You could specify this in your build process (via switches to msbuild/csc), but not really at runtime. The excluded code <em>doesn't exist</em>. You might be better advised to (1 of):</p>\n\n<ul>\n<li>Have separate DAL stacks for each back-end, using Dependency Injection / IoC</li>\n<li>Use an ORM tool that supports either</li>\n<li>Branch the code based n the provider (in a single DAL)</li>\n</ul>\n" }, { "answer_id": 272481, "author": "Louis Gerbarg", "author_id": 30506, "author_profile": "https://Stackoverflow.com/users/30506", "pm_score": 0, "selected": false, "text": "<p>No, the preprocessor runs before compile and can alter code at that time, that is its purpose, if you want to switch behavior based on something at runtime use a variable and normal conditional logic.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
I wonder if there is a way to set the value of #define in run time. I assume that there is a query for Oracle specific and Sql Server specific at the code below. ``` #define oracle // ... #if oracle // some code #else // some different code. #endif ```
Absolutely not, #defines are compiled out by the preprocessor before the compiler even sees it - so the token 'oracle' isn't even in your code, just '1' or '0'. Change the #define to a global variable or (better) a function that returns the correct value.
272,469
<p>I have the following database table created thus:</p> <pre><code>CREATE TABLE AUCTIONS ( ARTICLE_NO VARCHAR(20), ARTICLE_NAME VARCHAR(100), SUBTITLE VARCHAR(20), CURRENT_BID DECIMAL(5,2), START_PRICE DECIMAL(5,2), BID_COUNT VARCHAR(20), QUANT_TOTAL VARCHAR(20), QUANT_SOLD VARCHAR(20), ACCESSSTARTS VARCHAR(20), ACCESSENDS VARCHAR(20), ACCESSORIGIN_END VARCHAR(20), SELLER_ID VARCHAR(20), BEST_BIDDER_ID VARCHAR(20), FINISHED TINYINT, WATCH TINYINT, BUYITNOW_PRICE DECIMAL(5,2), PIC_URL VARCHAR(20), PRIVATE_AUCTION TINYINT, AUCTION_TYPE VARCHAR(20), ACCESSINSERT_DATE VARCHAR(20), ACCESSUPDATE_DATE VARCHAR(20), CAT_1_ID VARCHAR(20), CAT_2_ID VARCHAR(20), ARTICLE_DESC TEXT, COUNTRYCODE VARCHAR(20), LOCATION VARCHAR(20), CONDITIONS VARCHAR(20), REVISED TINYINT, PAYPAL_ACCEPT TINYINT, PRE_TERMINATED TINYINT, SHIPPING_TO VARCHAR(20), FEE_INSERTION DECIMAL(5,2), FEE_FINAL DECIMAL(5,2), FEE_LISTING DECIMAL(5,2), PIC_XXL TINYINT, PIC_DIASHOW TINYINT, PIC_COUNT VARCHAR(20), ITEM_SITE_ID VARCHAR(20), STARTS DATETIME, ENDS DATETIME, ORIGIN_END DATETIME, PRIMARY KEY ( `ARTICLE_NO` )); </code></pre> <p>Which is fine.</p> <p>However when trying to input this row:</p> <pre><code>5555555 This is the best ARticle in the world!!!!!! True 55.55 3232.2 6 5 5 8.7.2008 17:18:37 8.7.2008 17:18:37 8.7.2008 17:18:37 5454 7877 1 1 46.44 http//www.x.com 1 good 8.7.2008 17:18:37 8.7.2008 17:18:37 22 44 ANZTHINGcanogoherehihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 77 germanz none 1 1 1 446 everzwhere australia 22.2 22.2 22.2 1 1 5 1 </code></pre> <p>As a tab delimited text file, there seems to be a problem around buy_it_nowprice</p> <p>buy_it_nowprice shows correctly as 46.44 when doing select buy_it_nowprice from Auctions, but select pic_url from Auctions shows returns 1 instead of the website, and as a result all the subsequent records are out of place.</p> <p>I am sure I have missed a field or something, but I can not work out what it is.</p>
[ { "answer_id": 272487, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": true, "text": "<p>You have a space after 46.44, not a tab,</p>\n" }, { "answer_id": 272494, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 0, "selected": false, "text": "<p>There is a space after the number. If you have the option of using another field delimiter from the application that creates the text file for you, that will probably make these kinds of problems easier to spot.</p>\n" }, { "answer_id": 272498, "author": "Alan", "author_id": 34019, "author_profile": "https://Stackoverflow.com/users/34019", "pm_score": 0, "selected": false, "text": "<p>Check that the buyitnow_price and pic_url data fields are actually tab separated, it looks as though it might be a space, not a tab</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
I have the following database table created thus: ``` CREATE TABLE AUCTIONS ( ARTICLE_NO VARCHAR(20), ARTICLE_NAME VARCHAR(100), SUBTITLE VARCHAR(20), CURRENT_BID DECIMAL(5,2), START_PRICE DECIMAL(5,2), BID_COUNT VARCHAR(20), QUANT_TOTAL VARCHAR(20), QUANT_SOLD VARCHAR(20), ACCESSSTARTS VARCHAR(20), ACCESSENDS VARCHAR(20), ACCESSORIGIN_END VARCHAR(20), SELLER_ID VARCHAR(20), BEST_BIDDER_ID VARCHAR(20), FINISHED TINYINT, WATCH TINYINT, BUYITNOW_PRICE DECIMAL(5,2), PIC_URL VARCHAR(20), PRIVATE_AUCTION TINYINT, AUCTION_TYPE VARCHAR(20), ACCESSINSERT_DATE VARCHAR(20), ACCESSUPDATE_DATE VARCHAR(20), CAT_1_ID VARCHAR(20), CAT_2_ID VARCHAR(20), ARTICLE_DESC TEXT, COUNTRYCODE VARCHAR(20), LOCATION VARCHAR(20), CONDITIONS VARCHAR(20), REVISED TINYINT, PAYPAL_ACCEPT TINYINT, PRE_TERMINATED TINYINT, SHIPPING_TO VARCHAR(20), FEE_INSERTION DECIMAL(5,2), FEE_FINAL DECIMAL(5,2), FEE_LISTING DECIMAL(5,2), PIC_XXL TINYINT, PIC_DIASHOW TINYINT, PIC_COUNT VARCHAR(20), ITEM_SITE_ID VARCHAR(20), STARTS DATETIME, ENDS DATETIME, ORIGIN_END DATETIME, PRIMARY KEY ( `ARTICLE_NO` )); ``` Which is fine. However when trying to input this row: ``` 5555555 This is the best ARticle in the world!!!!!! True 55.55 3232.2 6 5 5 8.7.2008 17:18:37 8.7.2008 17:18:37 8.7.2008 17:18:37 5454 7877 1 1 46.44 http//www.x.com 1 good 8.7.2008 17:18:37 8.7.2008 17:18:37 22 44 ANZTHINGcanogoherehihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 77 germanz none 1 1 1 446 everzwhere australia 22.2 22.2 22.2 1 1 5 1 ``` As a tab delimited text file, there seems to be a problem around buy\_it\_nowprice buy\_it\_nowprice shows correctly as 46.44 when doing select buy\_it\_nowprice from Auctions, but select pic\_url from Auctions shows returns 1 instead of the website, and as a result all the subsequent records are out of place. I am sure I have missed a field or something, but I can not work out what it is.
You have a space after 46.44, not a tab,
272,504
<p>I am using the following code fragment in a php script to safely update a shared resource. </p> <pre><code>$lock_id = sem_get( ftok( 'tmp/this.lock', 'r')); sem_acquire($lock_id) //do something sem_release($lock_id) </code></pre> <p>When I stress test this code with large number of requests I get an error:</p> <pre><code>Warning: semop() failed acquiring SYSVSEM_SETVAL for key 0x1e: No space left on device in blahblah.php on line 1293 </code></pre> <p>php sources show the following code for failed acquiring SYSVSEM_SETVAL</p> <pre><code>while (semop(semid, sop, 3) == -1) { if (errno != EINTR) { php3_error(E_WARNING, "semop() failed acquiring SYSVSEM_SETVAL for key 0x%x: %s", key, strerror(errno)); break; } } </code></pre> <p>which means semop fails with EINTR. man page reveals that the semop() system call was interrupted by a signal. </p> <p>My question is can I safely ignore this error and retry sem_acquire? </p> <p><strong>Edit</strong>: I have misunderstood this problem, Pl see the clarification I have posted below.</p> <p>raj</p>
[ { "answer_id": 272616, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 2, "selected": true, "text": "<p>I wouldn't ignore the ENOSPC (you're getting something other than EINTR, as the code shows). You may end up in a busy loop waiting for a resource that you have earlier exhausted. If you're out of some space somewhere, you want to make sure that you deal with that issue. ENOSPC generally means you are out of...something.</p>\n\n<p>A couple of random ideas:</p>\n\n<p>I am not an expert on the PHP implementation, but I'd try to avoid calling <code>sem_get()</code> each time you want the semaphore. Store the handle instead. It may be that some resource is associated with each call to sem_get, and that is where you're running out of space.</p>\n\n<p>I'd make sure to check your error returns on <code>sem_get()</code>. It's a code snippet, but if you were to fail to get the sema4, you would get inconsistent results when trying to <code>sem_op()</code> it (perhaps EINTR makes sense)</p>\n" }, { "answer_id": 272870, "author": "Rajkumar S", "author_id": 25453, "author_profile": "https://Stackoverflow.com/users/25453", "pm_score": 0, "selected": false, "text": "<p>After posting this question I noticed that I misread the code as <code>errno</code> <strong><code>==</code></strong> <code>EINTR</code> and jumped into conclusion. So as bog has pointed out, the error is <code>ENOSPC</code> and not <code>EINTR</code>. After some digging I located the reason for <code>ENOSPC</code>. The number of undo buffers were getting exhausted. I have increased the number of <code>semmnu</code> and now the code is running with out issues. I have used <code>semmni*semms</code>l as the value of <code>semmnu</code></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25453/" ]
I am using the following code fragment in a php script to safely update a shared resource. ``` $lock_id = sem_get( ftok( 'tmp/this.lock', 'r')); sem_acquire($lock_id) //do something sem_release($lock_id) ``` When I stress test this code with large number of requests I get an error: ``` Warning: semop() failed acquiring SYSVSEM_SETVAL for key 0x1e: No space left on device in blahblah.php on line 1293 ``` php sources show the following code for failed acquiring SYSVSEM\_SETVAL ``` while (semop(semid, sop, 3) == -1) { if (errno != EINTR) { php3_error(E_WARNING, "semop() failed acquiring SYSVSEM_SETVAL for key 0x%x: %s", key, strerror(errno)); break; } } ``` which means semop fails with EINTR. man page reveals that the semop() system call was interrupted by a signal. My question is can I safely ignore this error and retry sem\_acquire? **Edit**: I have misunderstood this problem, Pl see the clarification I have posted below. raj
I wouldn't ignore the ENOSPC (you're getting something other than EINTR, as the code shows). You may end up in a busy loop waiting for a resource that you have earlier exhausted. If you're out of some space somewhere, you want to make sure that you deal with that issue. ENOSPC generally means you are out of...something. A couple of random ideas: I am not an expert on the PHP implementation, but I'd try to avoid calling `sem_get()` each time you want the semaphore. Store the handle instead. It may be that some resource is associated with each call to sem\_get, and that is where you're running out of space. I'd make sure to check your error returns on `sem_get()`. It's a code snippet, but if you were to fail to get the sema4, you would get inconsistent results when trying to `sem_op()` it (perhaps EINTR makes sense)
272,509
<p>I want to explicitly call a view from my controller.</p> <p>Right now I have:</p> <pre><code>def some_action .. do something ... respond_to do |format| format.xml end end </code></pre> <p>... then it calls my some_action.xml.builder view. How can I call some other view? Is there a parameter in respond_to I'm missing?</p> <p>Thanks,</p> <p>JP</p>
[ { "answer_id": 272559, "author": "Gabe Hollombe", "author_id": 30632, "author_profile": "https://Stackoverflow.com/users/30632", "pm_score": 4, "selected": false, "text": "<p>See the <a href=\"http://api.rubyonrails.org/classes/ActionController/Base.html#M000474\" rel=\"noreferrer\">Rendering section of the ActionController::Base documentation</a> for the different ways you can control what to render.</p>\n\n<p>You can tell Rails to render a specific view (template) like this:</p>\n\n<pre><code># Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.erb)\n render :template =&gt; \"weblog/show\"\n\n# Renders the template with a local variable\n render :template =&gt; \"weblog/show\", :locals =&gt; {:customer =&gt; Customer.new}\n</code></pre>\n" }, { "answer_id": 272572, "author": "Kevin Kaske", "author_id": 2737, "author_profile": "https://Stackoverflow.com/users/2737", "pm_score": 6, "selected": true, "text": "<p>You could do something like the following using render:</p>\n\n<pre><code>respond_to do |format|\n format.html { render :template =&gt; \"weblog/show\" }\nend\n</code></pre>\n" }, { "answer_id": 272583, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 3, "selected": false, "text": "<p>You can also pass :action, or :controller if that's more convenient.</p>\n\n<pre><code>respond_to do |format|\n format.html { render :action =&gt; 'show' }\nend\n</code></pre>\n" }, { "answer_id": 276008, "author": "edthix", "author_id": 33552, "author_profile": "https://Stackoverflow.com/users/33552", "pm_score": 0, "selected": false, "text": "<p>Use render</p>\n\n<p><a href=\"http://api.rubyonrails.com/classes/ActionController/Base.html#M000474\" rel=\"nofollow noreferrer\">http://api.rubyonrails.com/classes/ActionController/Base.html#M000474</a></p>\n" }, { "answer_id": 16300605, "author": "Fellow Stranger", "author_id": 1417223, "author_profile": "https://Stackoverflow.com/users/1417223", "pm_score": 3, "selected": false, "text": "<p>Or even simpler since <a href=\"http://guides.rubyonrails.org/layouts_and_rendering.html#rendering-an-action-s-view\" rel=\"noreferrer\">Rails > 3.0</a>:</p>\n\n<pre><code>render \"edit\"\n</code></pre>\n" }, { "answer_id": 25024461, "author": "Nate", "author_id": 761771, "author_profile": "https://Stackoverflow.com/users/761771", "pm_score": 2, "selected": false, "text": "<p>You can modify the internal <code>lookup_context</code> of the controller by doing this in your controller</p>\n\n<pre><code>before_filter do\n lookup_context.prefixes &lt;&lt; 'view_prefix'\nend\n</code></pre>\n\n<p>and the controller will try to load <code>view/view_prefix/show.html</code> when responding to an <code>show</code> request after looking for all the other view prefixes in the list. The default list is typically <code>application</code> and the name of the current controller.</p>\n\n<pre><code>class MagicController\n before_filter do\n lookup_context.prefixes &lt;&lt; 'secondary'\n end\n\n def show\n # ...\n end\nend\n\napp.get '/magic/1`\n</code></pre>\n\n<p>This <code>GET</code> request will look for a view in the following order:</p>\n\n<ul>\n<li><code>view/application/show.erb</code></li>\n<li><code>view/magic/show.erb</code></li>\n<li><code>view/secondary/show.erb</code></li>\n</ul>\n\n<p>and use the first found view.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I want to explicitly call a view from my controller. Right now I have: ``` def some_action .. do something ... respond_to do |format| format.xml end end ``` ... then it calls my some\_action.xml.builder view. How can I call some other view? Is there a parameter in respond\_to I'm missing? Thanks, JP
You could do something like the following using render: ``` respond_to do |format| format.html { render :template => "weblog/show" } end ```
272,511
<p>Is it possible to write a GUI from inside a function?</p> <p>The problem is that the callback of all GUI-functions are evaluated in the global workspace. But functions have their own workspace and can not access variables in the global workspace. Is it possible to make the GUI-functions use the workspace of the function? For example:</p> <pre><code>function myvar = myfunc() myvar = true; h_fig = figure; % create a useless button uicontrol( h_fig, 'style', 'pushbutton', ... 'string', 'clickme', ... 'callback', 'myvar = false' ); % wait for the button to be pressed while myvar pause( 0.2 ); end close( h_fig ); disp( 'this will never be displayed' ); end </code></pre> <p>This event-loop will run indefinitely, since the callback will not modify <code>myvar</code> in the function. Instead it will create a new <code>myvar</code> in the global workspace.</p>
[ { "answer_id": 272579, "author": "Ian Hopkinson", "author_id": 19172, "author_profile": "https://Stackoverflow.com/users/19172", "pm_score": 1, "selected": false, "text": "<p>You can declare a variable global in your function and global in the GUI code, certainly if the callback is in a separate function rather than inline. I've done this in a little skeleton GUI I use to make quick menu system.</p>\n\n<p>In your code above you may be able to add the global keyword to your initial declaration and also to your inline callback i.e. 'global myvar = false'</p>\n" }, { "answer_id": 277818, "author": "bastibe", "author_id": 1034, "author_profile": "https://Stackoverflow.com/users/1034", "pm_score": 1, "selected": false, "text": "<p>I found a solution to the problem. The callback-function has to modify the handle-structure of the GUI. This structure can be accessed both from within the callback and from the function without introducing new variables to the global workspace:</p>\n\n<pre><code>function myfunc()\n h_fig = figure;\n\n % add continue_loop to the GUI-handles structure\n fig_handles = guihandles( h_fig );\n fig_handles.continue_loop = true;\n guidata( h_fig, fig_handles );\n\n % create a useless button\n uicontrol( h_fig, 'style', 'pushbutton', ...\n 'string', 'clickme', ...\n 'callback', @gui_callback );\n\n % wait for the button to be pressed\n while fig_handles.continue_loop\n fig_handles = guidata( h_fig ); % update handles\n pause( 0.2 );\n end\n\n close( h_fig );\n disp( 'callback ran successfully' );\nend\n\n% The arguments are the Matlab-defaults for GUI-callbacks.\nfunction gui_callback( hObject, eventdata, handles )\n % modify and save handles-Structure\n handles.continue_loop = false;\n guidata( hObject, handles );\nend\n</code></pre>\n\n<p>note that since the while-loop will only update fig_handles when it is run, you will always have at least 0.2 seconds delay until the loop catches the modification of <code>fig_handles.continue_loop</code></p>\n" }, { "answer_id": 425347, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 4, "selected": true, "text": "<p>There are a number of ways to <a href=\"https://www.mathworks.com/help/matlab/creating_guis/ways-to-build-matlab-guis.html\" rel=\"nofollow noreferrer\">build a GUI</a>, such as using the App Designer, GUIDE, or creating it programmatically (I'll illustrate this option below). It's also important to be aware of the <a href=\"https://www.mathworks.com/help/matlab/creating_guis/write-callbacks-using-the-programmatic-workflow.html\" rel=\"nofollow noreferrer\">different ways to define callback functions</a> for your GUI components and the <a href=\"https://www.mathworks.com/help/matlab/creating_guis/share-data-among-callbacks.html\" rel=\"nofollow noreferrer\">options available for sharing data between components</a>.</p>\n\n<p>The approach I'm partial to is using <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html\" rel=\"nofollow noreferrer\">nested functions</a> as callbacks. Here's a simple GUI as an example:</p>\n\n<pre><code>function make_useless_button()\n\n % Initialize variables and graphics:\n iCounter = 0;\n hFigure = figure;\n hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ...\n 'String', 'Blah', 'Callback', @increment);\n\n % Nested callback function:\n function increment(~, ~)\n iCounter = iCounter+1;\n disp(iCounter);\n end\n\nend\n</code></pre>\n\n<p>When you run this code, the counter displayed should increment by one every time you press the button, because the nested function <code>increment</code> has access to the workspace of <code>make_useless_button</code> and thus can modify <code>iCounter</code>. Note that the button callback is set to a <a href=\"https://www.mathworks.com/help/matlab/creating_guis/write-callbacks-using-the-programmatic-workflow.html#br7qvh9\" rel=\"nofollow noreferrer\">function handle</a> to <code>increment</code>, and that this function must accept two arguments by default: a graphics handle for the UI component that triggered the callback, and a structure of associated event data. We <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/ignore-function-inputs.html\" rel=\"nofollow noreferrer\">ignore them with the <code>~</code></a> in this case since we aren't using them.</p>\n\n<p>Extending the above approach to your particular problem, you could add your loop and change the callback so it sets your flag variable to false:</p>\n\n<pre><code>function make_stop_button()\n\n % Initialize variables and graphics:\n keepLooping = true;\n hFigure = figure;\n hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ...\n 'String', 'Stop', 'Callback', @stop_fcn);\n\n % Keep looping until the button is pressed:\n while keepLooping,\n drawnow;\n end\n\n % Delete the figure:\n delete(hFigure);\n\n % Nested callback function:\n function stop_fcn(~, ~)\n keepLooping = false;\n end\n\nend\n</code></pre>\n\n<p>The <a href=\"https://www.mathworks.com/help/matlab/ref/drawnow.html\" rel=\"nofollow noreferrer\"><code>drawnow</code></a> is needed here to give the button callback a chance to interrupt the program flow within the loop and modify the value of <code>keepLooping</code>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1034/" ]
Is it possible to write a GUI from inside a function? The problem is that the callback of all GUI-functions are evaluated in the global workspace. But functions have their own workspace and can not access variables in the global workspace. Is it possible to make the GUI-functions use the workspace of the function? For example: ``` function myvar = myfunc() myvar = true; h_fig = figure; % create a useless button uicontrol( h_fig, 'style', 'pushbutton', ... 'string', 'clickme', ... 'callback', 'myvar = false' ); % wait for the button to be pressed while myvar pause( 0.2 ); end close( h_fig ); disp( 'this will never be displayed' ); end ``` This event-loop will run indefinitely, since the callback will not modify `myvar` in the function. Instead it will create a new `myvar` in the global workspace.
There are a number of ways to [build a GUI](https://www.mathworks.com/help/matlab/creating_guis/ways-to-build-matlab-guis.html), such as using the App Designer, GUIDE, or creating it programmatically (I'll illustrate this option below). It's also important to be aware of the [different ways to define callback functions](https://www.mathworks.com/help/matlab/creating_guis/write-callbacks-using-the-programmatic-workflow.html) for your GUI components and the [options available for sharing data between components](https://www.mathworks.com/help/matlab/creating_guis/share-data-among-callbacks.html). The approach I'm partial to is using [nested functions](https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html) as callbacks. Here's a simple GUI as an example: ``` function make_useless_button() % Initialize variables and graphics: iCounter = 0; hFigure = figure; hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ... 'String', 'Blah', 'Callback', @increment); % Nested callback function: function increment(~, ~) iCounter = iCounter+1; disp(iCounter); end end ``` When you run this code, the counter displayed should increment by one every time you press the button, because the nested function `increment` has access to the workspace of `make_useless_button` and thus can modify `iCounter`. Note that the button callback is set to a [function handle](https://www.mathworks.com/help/matlab/creating_guis/write-callbacks-using-the-programmatic-workflow.html#br7qvh9) to `increment`, and that this function must accept two arguments by default: a graphics handle for the UI component that triggered the callback, and a structure of associated event data. We [ignore them with the `~`](https://www.mathworks.com/help/matlab/matlab_prog/ignore-function-inputs.html) in this case since we aren't using them. Extending the above approach to your particular problem, you could add your loop and change the callback so it sets your flag variable to false: ``` function make_stop_button() % Initialize variables and graphics: keepLooping = true; hFigure = figure; hButton = uicontrol('Style', 'pushbutton', 'Parent', hFigure, ... 'String', 'Stop', 'Callback', @stop_fcn); % Keep looping until the button is pressed: while keepLooping, drawnow; end % Delete the figure: delete(hFigure); % Nested callback function: function stop_fcn(~, ~) keepLooping = false; end end ``` The [`drawnow`](https://www.mathworks.com/help/matlab/ref/drawnow.html) is needed here to give the button callback a chance to interrupt the program flow within the loop and modify the value of `keepLooping`.
272,518
<p>When I do a ReadLinesFromFile on a file in MSBUILD and go to output that file again, I get all the text on one line. All the Carriage returns and LineFeeds are stripped out.</p> <pre><code>&lt;Project DefaultTargets = "Deploy" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" &gt; &lt;Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/&gt; &lt;ItemGroup&gt; &lt;MyTextFile Include="$(ReleaseNotesDir)$(NewBuildNumber).txt"/&gt; &lt;/ItemGroup&gt; &lt;Target Name="ReadReleaseNotes"&gt; &lt;ReadLinesFromFile File="@(MyTextFile)" &gt; &lt;Output TaskParameter="Lines" ItemName="ReleaseNoteItems"/&gt; &lt;/ReadLinesFromFile&gt; &lt;/Target&gt; &lt;Target Name="MailUsers" DependsOnTargets="ReadReleaseNotes" &gt; &lt;Mail SmtpServer="$(MailServer)" To="$(MyEMail)" From="$(MyEMail)" Subject="Test Mail Task" Body="@(ReleaseNoteItems)" /&gt; &lt;/Target&gt; &lt;Target Name="Deploy"&gt; &lt;CallTarget Targets="MailUsers" /&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre> <p>I get the text from the file which normally looks like this</p> <blockquote> <pre><code>- New Deployment Tool for BLAH - Random other stuff()"" </code></pre> </blockquote> <p>Coming out like this</p> <blockquote> <pre><code>- New Deployment Tool for BLAH;- Random other stuff()"" </code></pre> </blockquote> <p>I know that the code for ReadLinesFromFile will pull the data in one line at a time and strip out the carriage returns.</p> <p>Is there a way to put them back in? So my e-mail looks all nicely formatted?</p> <p>Thanks </p>
[ { "answer_id": 274720, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 6, "selected": true, "text": "<p>The problem here is you are using the <code>ReadLinesFromFile</code> task in a manner it wasn't intended.</p>\n\n<blockquote>\n <p><strong>ReadLinesFromFile Task</strong><br>\n Reads a list of <em>items</em> from a text file.</p>\n</blockquote>\n\n<p>So it's not just reading all the text from a file, it's reading individual items from a file and returning an item group of ITaskItems. Whenever you output a list of items using the <code>@()</code> syntax you will get a separated list, the default of which is a semicolon. This example illustrates this behavior:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\"&gt;\n\n &lt;ItemGroup&gt;\n &lt;Color Include=\"Red\" /&gt;\n &lt;Color Include=\"Blue\" /&gt;\n &lt;Color Include=\"Green\" /&gt;\n&lt;/ItemGroup&gt;\n\n&lt;Target Name=\"Build\"&gt;\n &lt;Message Text=\"ItemGroup Color: @(Color)\" /&gt;\n&lt;/Target&gt;\n\n&lt;/Project&gt;\n</code></pre>\n\n<p>And the output looks like this:</p>\n\n<pre><code> ItemGroup Color: Red;Blue;Green\n</code></pre>\n\n<p>So while the best solution to your problem is to write an MSBuild task that reads a file into a <em>property</em> as a string an not a list of items, that's really not what you asked for. You asked if there was a <em>way</em> to put them back, and there is using <a href=\"http://msdn.microsoft.com/en-us/library/ms171476.aspx\" rel=\"noreferrer\">MSBuild Transforms</a>.</p>\n\n<p>Transforms are used to create one list from another and also have the ability to transform using a custom separator. So the answer is to transform your list read in using <code>ReadItemsFromFile</code> into another list with newlines. Here is an example that does just that:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\"&gt;\n\n &lt;ItemGroup&gt;\n &lt;File Include=\"$(MSBuildProjectDirectory)\\Test.txt\" /&gt;\n &lt;/ItemGroup&gt;\n\n &lt;Target Name=\"Build\"&gt;\n &lt;ReadLinesFromFile File=\"@(File)\"&gt;\n &lt;Output TaskParameter=\"Lines\" ItemName=\"FileContents\" /&gt;\n &lt;/ReadLinesFromFile&gt;\n\n &lt;Message Text=\"FileContents: @(FileContents)\" /&gt;\n &lt;Message Text=\"FileContents Transformed: @(FileContents-&gt;'%(Identity)', '%0a%0d')\" /&gt;\n &lt;/Target&gt;\n\n&lt;/Project&gt;\n</code></pre>\n\n<p>Test.text looks like:</p>\n\n<pre><code>Red\nGreen\nBlue\n</code></pre>\n\n<p>And the output looks like this:</p>\n\n<pre><code>[C:\\temp]:: msbuild test.proj\nMicrosoft (R) Build Engine Version 3.5.21022.8\n[Microsoft .NET Framework, Version 2.0.50727.1433]\nCopyright (C) Microsoft Corporation 2007. All rights reserved.\n\nBuild started 11/8/2008 8:16:59 AM.\nProject \"C:\\temp\\test.proj\" on node 0 (default targets).\n FileContents: Red;Green;Blue\n FileContents Transformed: Red\nGreen\nBlue\nDone Building Project \"C:\\temp\\test.proj\" (default targets).\n\n\nBuild succeeded.\n 0 Warning(s)\n 0 Error(s)\n\nTime Elapsed 00:00:00.03\n</code></pre>\n\n<p>What's going on here is two things.</p>\n\n<pre><code>@(FileContents-&gt;'%(Identity)', '%0a%0d') \n</code></pre>\n\n<ul>\n<li>We are transforming the list from one type to another using the same values (<code>Identity</code>) but a custom separator <code>'%0a%0d'</code></li>\n<li>We are using <a href=\"http://msdn.microsoft.com/en-us/library/ms228186.aspx\" rel=\"noreferrer\">MSBuild Escaping</a> to escape the line feed (<code>%0a</code>) and carriage return (<code>%0d</code>)</li>\n</ul>\n" }, { "answer_id": 1414744, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Instead of @(FileContents->'%(Identity)', '%0a%0d') I believe you can do @(FileContents, '%0a%0d')</p>\n" }, { "answer_id": 9335100, "author": "user75810", "author_id": 75810, "author_profile": "https://Stackoverflow.com/users/75810", "pm_score": 5, "selected": false, "text": "<p>If you are using MSBuild 4.0, you can do the following instead, to get the contents of a file:</p>\n\n<pre><code>$([System.IO.File]::ReadAllText($FilePath))\n</code></pre>\n" }, { "answer_id": 35156845, "author": "romi ares", "author_id": 2381476, "author_profile": "https://Stackoverflow.com/users/2381476", "pm_score": 1, "selected": false, "text": "<p>You can use WriteLinesToFile combined with </p>\n\n<pre><code>$([System.IO.File]::ReadAllText($(SourceFilePath))):\n\n&lt; WriteLinesToFile File=\"$(DestinationFilePath)\" Lines=\"$([System.IO.File]::ReadAllText($(SourceFilePath)))\"\n Overwrite=\"true\" \n /&gt;\n</code></pre>\n\n<p>This will copy your file exactly at it is.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2806/" ]
When I do a ReadLinesFromFile on a file in MSBUILD and go to output that file again, I get all the text on one line. All the Carriage returns and LineFeeds are stripped out. ``` <Project DefaultTargets = "Deploy" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" > <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/> <ItemGroup> <MyTextFile Include="$(ReleaseNotesDir)$(NewBuildNumber).txt"/> </ItemGroup> <Target Name="ReadReleaseNotes"> <ReadLinesFromFile File="@(MyTextFile)" > <Output TaskParameter="Lines" ItemName="ReleaseNoteItems"/> </ReadLinesFromFile> </Target> <Target Name="MailUsers" DependsOnTargets="ReadReleaseNotes" > <Mail SmtpServer="$(MailServer)" To="$(MyEMail)" From="$(MyEMail)" Subject="Test Mail Task" Body="@(ReleaseNoteItems)" /> </Target> <Target Name="Deploy"> <CallTarget Targets="MailUsers" /> </Target> </Project> ``` I get the text from the file which normally looks like this > > > ``` > - New Deployment Tool for BLAH > > - Random other stuff()"" > > ``` > > Coming out like this > > > ``` > - New Deployment Tool for BLAH;- Random other stuff()"" > > ``` > > I know that the code for ReadLinesFromFile will pull the data in one line at a time and strip out the carriage returns. Is there a way to put them back in? So my e-mail looks all nicely formatted? Thanks
The problem here is you are using the `ReadLinesFromFile` task in a manner it wasn't intended. > > **ReadLinesFromFile Task** > > Reads a list of *items* from a text file. > > > So it's not just reading all the text from a file, it's reading individual items from a file and returning an item group of ITaskItems. Whenever you output a list of items using the `@()` syntax you will get a separated list, the default of which is a semicolon. This example illustrates this behavior: ``` <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <ItemGroup> <Color Include="Red" /> <Color Include="Blue" /> <Color Include="Green" /> </ItemGroup> <Target Name="Build"> <Message Text="ItemGroup Color: @(Color)" /> </Target> </Project> ``` And the output looks like this: ``` ItemGroup Color: Red;Blue;Green ``` So while the best solution to your problem is to write an MSBuild task that reads a file into a *property* as a string an not a list of items, that's really not what you asked for. You asked if there was a *way* to put them back, and there is using [MSBuild Transforms](http://msdn.microsoft.com/en-us/library/ms171476.aspx). Transforms are used to create one list from another and also have the ability to transform using a custom separator. So the answer is to transform your list read in using `ReadItemsFromFile` into another list with newlines. Here is an example that does just that: ``` <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <ItemGroup> <File Include="$(MSBuildProjectDirectory)\Test.txt" /> </ItemGroup> <Target Name="Build"> <ReadLinesFromFile File="@(File)"> <Output TaskParameter="Lines" ItemName="FileContents" /> </ReadLinesFromFile> <Message Text="FileContents: @(FileContents)" /> <Message Text="FileContents Transformed: @(FileContents->'%(Identity)', '%0a%0d')" /> </Target> </Project> ``` Test.text looks like: ``` Red Green Blue ``` And the output looks like this: ``` [C:\temp]:: msbuild test.proj Microsoft (R) Build Engine Version 3.5.21022.8 [Microsoft .NET Framework, Version 2.0.50727.1433] Copyright (C) Microsoft Corporation 2007. All rights reserved. Build started 11/8/2008 8:16:59 AM. Project "C:\temp\test.proj" on node 0 (default targets). FileContents: Red;Green;Blue FileContents Transformed: Red Green Blue Done Building Project "C:\temp\test.proj" (default targets). Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:00.03 ``` What's going on here is two things. ``` @(FileContents->'%(Identity)', '%0a%0d') ``` * We are transforming the list from one type to another using the same values (`Identity`) but a custom separator `'%0a%0d'` * We are using [MSBuild Escaping](http://msdn.microsoft.com/en-us/library/ms228186.aspx) to escape the line feed (`%0a`) and carriage return (`%0d`)
272,523
<p>I am using winsock and C++ to set up a server application. The problem I'm having is that the call to <code>listen</code> results in a first chance exception. I guess normally these can be ignored (?) but I've found others having the same issue I am where it causes the application to hang every once in a while. Any help would be greatly appreciated.</p> <p>The first chance exception is:</p> <blockquote> <p>First-chance exception at 0x*12345678* in <em>MyApp</em>.exe: 0x000006D9: There are no more endpoints available from the endpoint mapper.</p> </blockquote> <p>I've found some evidence that this could be cause by the socket And the code that I'm working with is as follows. The exception occurs on the call to <code>listen</code> in the fifth line from the bottom.</p> <pre><code> m_accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (m_accept_fd == INVALID_SOCKET) { return false; } int optval = 1; if (setsockopt (m_accept_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&amp;optval, sizeof(optval))) { closesocket(m_accept_fd); m_accept_fd = INVALID_SOCKET; return false; } struct sockaddr_in local_addr; local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = INADDR_ANY; local_addr.sin_port = htons(m_port); if (bind(m_accept_fd, (struct sockaddr *)&amp;local_addr, sizeof(struct sockaddr_in)) == SOCKET_ERROR) { closesocket(m_accept_fd); return false; } if (listen (m_accept_fd, 5) == SOCKET_ERROR) { closesocket(m_accept_fd); return false; } </code></pre>
[ { "answer_id": 272668, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 0, "selected": false, "text": "<p>This won't answer your question directly, but since you're using C++, I would recommend using something like <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html\" rel=\"nofollow noreferrer\">Boost::Asio</a> to handle your socket code. This gives you a nice abstraction over the winsock API, and should allow you to more easily diagnose error conditions.</p>\n" }, { "answer_id": 272682, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 1, "selected": false, "text": "<p>Uhh, maybe it's because you're limiting greatly the maximum number of incoming connections?</p>\n\n<pre><code>listen (m_accept_fd, 5)\n// Limit here ^^^\n</code></pre>\n\n<p>If you allow a greater backlog, you should be able to handle your problem. Use something like SOMAXCONN instead of 5.</p>\n\n<p>Also, if your problem is only on server startup, you might want to turn off LINGER (SO_LINGER) to prevent connections from hanging around and blocking the socket...</p>\n" }, { "answer_id": 274166, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 2, "selected": false, "text": "<p>Are you actually seeing a problem, e.g., does the program end because of an unhandled exception?</p>\n\n<p>The debugger may print the message even when there isn't a problem, for example, see <a href=\"http://blogs.msdn.com/davidklinems/archive/2005/07/12/438061.aspx\" rel=\"nofollow noreferrer\">here</a>. </p>\n" }, { "answer_id": 274370, "author": "Darian Miller", "author_id": 35696, "author_profile": "https://Stackoverflow.com/users/35696", "pm_score": 4, "selected": true, "text": "<p>On a very busy server, you may be running out of Sockets. You may have to adjust some TCPIP parameters. Adjust these two in the registry:</p>\n\n<pre><code>HKLM\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\n MaxUserPort REG_DWORD 65534 (decimal)\n TcpTimedWaitDelay REG_DWORD 60 (decimal)\n</code></pre>\n\n<p>By default, there's a few minutes delay between releasing a network port (socket) and when it can be reused. Also, depending on the OS version, there's only a few thousand in the range that windows will use. On the server, run this at a command prompt: </p>\n\n<blockquote>\n <p>netstat -an</p>\n</blockquote>\n\n<p>and look at the results (pipe to a file is easiest: netstat -an > netstat.txt). If you see a large number of ports from 1025->5000 in Timed Wait Delay status, then this is your problem and it's solved by adjusting up the max user port from 5000 to 65534 using the registry entry above. You can also adjust the delay by using the registry entry above to recycle the ports more quickly.</p>\n\n<p>If this is not the problem, then the problem is likely the number of pending connections that you have set in your Listen() method. </p>\n" }, { "answer_id": 642694, "author": "a_mole", "author_id": 77711, "author_profile": "https://Stackoverflow.com/users/77711", "pm_score": 2, "selected": false, "text": "<p>The original problem has nothing to do with winsock. All the answers above are WRONG. Ignore the first-chance exception, it is not a problem with your application, just some internal error handling.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34731/" ]
I am using winsock and C++ to set up a server application. The problem I'm having is that the call to `listen` results in a first chance exception. I guess normally these can be ignored (?) but I've found others having the same issue I am where it causes the application to hang every once in a while. Any help would be greatly appreciated. The first chance exception is: > > First-chance exception at 0x\*12345678\* in *MyApp*.exe: 0x000006D9: There are no more endpoints available from the endpoint mapper. > > > I've found some evidence that this could be cause by the socket And the code that I'm working with is as follows. The exception occurs on the call to `listen` in the fifth line from the bottom. ``` m_accept_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (m_accept_fd == INVALID_SOCKET) { return false; } int optval = 1; if (setsockopt (m_accept_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval))) { closesocket(m_accept_fd); m_accept_fd = INVALID_SOCKET; return false; } struct sockaddr_in local_addr; local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = INADDR_ANY; local_addr.sin_port = htons(m_port); if (bind(m_accept_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in)) == SOCKET_ERROR) { closesocket(m_accept_fd); return false; } if (listen (m_accept_fd, 5) == SOCKET_ERROR) { closesocket(m_accept_fd); return false; } ```
On a very busy server, you may be running out of Sockets. You may have to adjust some TCPIP parameters. Adjust these two in the registry: ``` HKLM\System\CurrentControlSet\Services\Tcpip\Parameters MaxUserPort REG_DWORD 65534 (decimal) TcpTimedWaitDelay REG_DWORD 60 (decimal) ``` By default, there's a few minutes delay between releasing a network port (socket) and when it can be reused. Also, depending on the OS version, there's only a few thousand in the range that windows will use. On the server, run this at a command prompt: > > netstat -an > > > and look at the results (pipe to a file is easiest: netstat -an > netstat.txt). If you see a large number of ports from 1025->5000 in Timed Wait Delay status, then this is your problem and it's solved by adjusting up the max user port from 5000 to 65534 using the registry entry above. You can also adjust the delay by using the registry entry above to recycle the ports more quickly. If this is not the problem, then the problem is likely the number of pending connections that you have set in your Listen() method.
272,528
<p>I was thinking of adding some <strong>Achievements</strong> to our internal bug-tracking and time logging system. It's connected to an SQL Server back-end.</p> <p>At first I thought that the system could be run on the database, using triggers to, for example, know when:</p> <ul> <li>you've logged 1000 hours</li> <li>created 1000 tickets</li> <li>closed your own ticket</li> <li>worked on a ticket that has been not touched in a while.</li> <li>etc (you know - database-ish things)</li> </ul> <p>But then I realized that I would also want purely <strong>front-end achivements</strong> </p> <ul> <li>used the advanced search abiltiy</li> <li>sorted by a column</li> <li>reset settings to default</li> <li>searched 500 times</li> </ul> <p>It seems like the logic of every achievement must be hand coded. Could anyone imagine an some sort of <em>Achievements Rules Engine</em>, that you for example create scripts for?</p> <p>And how to store them? If the achievement is:</p> <ul> <li>change column sort order 50 times in one session</li> </ul> <p>that would imply that every time they sort a listview column it updates the database. </p> <p>Any thoughts on this Win32 application design problem? I don't think that the <a href="http://en.wikipedia.org/wiki/Gang_of_Four" rel="nofollow noreferrer">Gang of Four</a> have an Achievements <strong>design pattern</strong>.</p> <hr> <p><strong>Note:</strong> It's a Win32 client application, not a web-site.</p> <hr> <p>i definetly like the idea of an eventing system. Various actions the user takes can raise events through a single eventing object:</p> <pre><code>protected void TimeEntriesListView_ColumnSort(object sender, EventArgs e) { _globalListener.RaiseEvent(EventType.ListViewColumnSort, sender, e); } protected void TimeEntriesListView_ColumnDrag(object sender, EventArgs e) { _globalListener.RaiseEvent(EventType.ListViewColumnDrag, sender, e); } </code></pre> <p>That object can then have logic added to it to decide which events it wants to count. But more reasonably, various event listeners can attached to the central event listener, and have their custom achievement logic.</p>
[ { "answer_id": 272542, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 1, "selected": false, "text": "<p>The backend achievements should be simple - they seem to be based on already tracked items. The front end, as you correctly stated, will require more tracking. One way you might want to do this is implement an analytics engine for your front end site.</p>\n\n<p>Piwik at <a href=\"http://www.piwik.org\" rel=\"nofollow noreferrer\">http://www.piwik.org</a> might help here - it is a google analytics clone, that you host yourself. The idea would be to use it's logging capabilities to track when an achievement has been completed.</p>\n\n<p>As for some form of scripting of the rules, you will always have to hand code them - you can perhaps make it simpler though, by creating your own small scripting engine, or implementing a custom Lua set.</p>\n" }, { "answer_id": 272597, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 4, "selected": true, "text": "<p>The trick isn't the coding of the rules, really, those are straightforward, and can perhaps be simple expressions (number_of_bugs > 1000).</p>\n\n<p>The trick is accumulating the statistics. You should look at a form of Event Stream Processing to record your achievements. For example, you don't really want to implement the \"1000 bugs\" achievement with \"select count(*) from bugs where user= :user\" all the time (you could do it this way, but arguably shouldn't). Rather you should get an event every time they post a bug, and you achievement system records \"found another bug\". Then the rule can check the \"number_of_bugs > 1000\".</p>\n\n<p>Obviously you may need to \"prime the pump\" so to speak, setting the number_of_bugs to the current number in the DB when you start the achievement system up.</p>\n\n<p>But the goal is to keep the actual event processing light weight, so let it track the events as they go by with all of the events running on a common, internal pipe or bus.</p>\n\n<p>A scripting language is a good idea as well, as they can easily evaluate both expressions and more complicated logic. \"number_of_bugs > 1000\" is a perfectly valid Javascript program for example. The game is just getting the environment set up.</p>\n\n<p>You can also store the scripts in the DB and make an \"achievement\" editor to add them on the fly if you like, assuming you're capturing all of the relevant events.</p>\n" }, { "answer_id": 272611, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 1, "selected": false, "text": "<p>How about storing the sql query associated with the achievement in the database itself, so adding a new achievement would only involve adding the name and the sql query for it.</p>\n\n<p>for e.g.</p>\n\n<p>you've logged 1000 hours - \"select case sum(hours) > 1000 then 'true' else ' false' end from user where user_id = ?\"</p>\n\n<p>The UI based achievements would have to have the data stored in the db as well because you may use the same data for other achievements going forward.</p>\n" }, { "answer_id": 470026, "author": "ceetheman", "author_id": 16154, "author_profile": "https://Stackoverflow.com/users/16154", "pm_score": 2, "selected": false, "text": "<p>I am also trying to figure out how to build an achievements rules engine.</p>\n\n<p>I checked around rules engines and what are the basics of it. There is a <a href=\"http://en.wikipedia.org/wiki/Business_rules_engine\" rel=\"nofollow noreferrer\">good summary of that in wikipedia</a></p>\n\n<p>Basically, you either have foward chaining when you, for example, check availability for something; otherwise, you use <a href=\"http://en.wikipedia.org/wiki/Event_Condition_Action\" rel=\"nofollow noreferrer\">Event Condition Action</a> rules. Its the latest that caught my attention. </p>\n\n<p>So you could predefine a set of triggered events. In the engine you can define what are the checked conditions who are based on available metrics, and specify the association achievement.</p>\n\n<p>This way seems more flexible, but you have to define the events, possible condition checks and metrics. </p>\n\n<p>For example, you would have various events like TicketCreated triggered in the code. </p>\n\n<p>In the rule engine you could have something like</p>\n\n<pre><code>Event: TicketCreated\nCondition: UserTicketCount &gt;= 1000\nAchivement: \"Created 1000 tickets\"\n</code></pre>\n\n<p>or for \"reset settings to default\"</p>\n\n<pre><code>Event: SettingsChanged\nCondition: Settings = DEFAULT\nAchievement: \"Reset to Default\"\n</code></pre>\n\n<p>I haven't tried it yet, but I'm going to pretty soon. It's mostly theoric for now. </p>\n" }, { "answer_id": 1760359, "author": "Bo Flexson", "author_id": 199706, "author_profile": "https://Stackoverflow.com/users/199706", "pm_score": 1, "selected": false, "text": "<p>I think one table to hold each event that you want to track. Such as \"<em>Performed a search</em>\". Then each achievement could have an SQL associated with it.</p>\n\n<p>You could then build one trigger, on the <strong>Event</strong> table, which would compare the achievements that apply to that event, and add the achievement to the <strong>Achivement</strong> table.</p>\n\n<p>Here are the quickie table designs:</p>\n\n<pre><code>EventItems:\nUserId, EventName, DateOccured, AnyOtherInfo\n\nAchievementQualifiers: \nAchievement Name, AchievementCheckSQL, EventsThisAppliesTo \n(Normalize this, if multiple events apply)\n</code></pre>\n\n<p>In you System, weather its web or win32, you simply insert into the <strong>EventItems</strong> table whenever the user does some event that you want to track. You could make one class to handle this. For purely DB type events, such as \"Item Posted\" or \"Comment Posted\" you could do this with a trigger instead.</p>\n\n<p>Then, in the triggers on <strong>EventItems</strong>, for each <strong>AchievementQualifer</strong> that has that <strong>EventThisAppliesTo</strong>, run the SQL check, and update an <strong>UserAchievement</strong> table if it's true and hasn't been awarded yet.</p>\n\n<p><em>Excuse my spelling, as I'm typing this while sitting in a brew pub.</em></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
I was thinking of adding some **Achievements** to our internal bug-tracking and time logging system. It's connected to an SQL Server back-end. At first I thought that the system could be run on the database, using triggers to, for example, know when: * you've logged 1000 hours * created 1000 tickets * closed your own ticket * worked on a ticket that has been not touched in a while. * etc (you know - database-ish things) But then I realized that I would also want purely **front-end achivements** * used the advanced search abiltiy * sorted by a column * reset settings to default * searched 500 times It seems like the logic of every achievement must be hand coded. Could anyone imagine an some sort of *Achievements Rules Engine*, that you for example create scripts for? And how to store them? If the achievement is: * change column sort order 50 times in one session that would imply that every time they sort a listview column it updates the database. Any thoughts on this Win32 application design problem? I don't think that the [Gang of Four](http://en.wikipedia.org/wiki/Gang_of_Four) have an Achievements **design pattern**. --- **Note:** It's a Win32 client application, not a web-site. --- i definetly like the idea of an eventing system. Various actions the user takes can raise events through a single eventing object: ``` protected void TimeEntriesListView_ColumnSort(object sender, EventArgs e) { _globalListener.RaiseEvent(EventType.ListViewColumnSort, sender, e); } protected void TimeEntriesListView_ColumnDrag(object sender, EventArgs e) { _globalListener.RaiseEvent(EventType.ListViewColumnDrag, sender, e); } ``` That object can then have logic added to it to decide which events it wants to count. But more reasonably, various event listeners can attached to the central event listener, and have their custom achievement logic.
The trick isn't the coding of the rules, really, those are straightforward, and can perhaps be simple expressions (number\_of\_bugs > 1000). The trick is accumulating the statistics. You should look at a form of Event Stream Processing to record your achievements. For example, you don't really want to implement the "1000 bugs" achievement with "select count(\*) from bugs where user= :user" all the time (you could do it this way, but arguably shouldn't). Rather you should get an event every time they post a bug, and you achievement system records "found another bug". Then the rule can check the "number\_of\_bugs > 1000". Obviously you may need to "prime the pump" so to speak, setting the number\_of\_bugs to the current number in the DB when you start the achievement system up. But the goal is to keep the actual event processing light weight, so let it track the events as they go by with all of the events running on a common, internal pipe or bus. A scripting language is a good idea as well, as they can easily evaluate both expressions and more complicated logic. "number\_of\_bugs > 1000" is a perfectly valid Javascript program for example. The game is just getting the environment set up. You can also store the scripts in the DB and make an "achievement" editor to add them on the fly if you like, assuming you're capturing all of the relevant events.
272,541
<p>Is it possible to disable AJAX without disabling JavaScript completely? </p>
[ { "answer_id": 272558, "author": "Jonathan Adelson", "author_id": 8092, "author_profile": "https://Stackoverflow.com/users/8092", "pm_score": -1, "selected": false, "text": "<p>No. AJAX is just a particular use of javascript.</p>\n\n<p>If you could block the particular function call back to the server you might be able to do it, but you would probably have to edit your browser.</p>\n\n<p>I assume you want to do this from the client end... Can you list some more specific goals? What is the expected outcome?</p>\n" }, { "answer_id": 272561, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 2, "selected": false, "text": "<p>AJAX is simply the usage of the XMLHttpRequest function in Javascript. Depending on your browser, you may be able to lock down access to this function through your security settings.\nAt least with Firefox, you could disable it either through using a custom Extension.</p>\n" }, { "answer_id": 272588, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 5, "selected": true, "text": "<p>If you are using Firefox, you could accomplish this with GreaseMonkey. (<a href=\"https://addons.mozilla.org/en-US/firefox/addon/748\" rel=\"nofollow noreferrer\">https://addons.mozilla.org/en-US/firefox/addon/748</a>)</p>\n\n<p>GM is a framework for applying scripts to some or all of the pages you visit. I have GM scripts that disable google-analytics downloads (because they slow things down), and which disable google-click-tracking on google result pages (because it bothers me that they are doing that).</p>\n\n<p>Here is my google-click disable script:</p>\n\n<pre><code>// ==UserScript==\n// @name Google Clk\n// @namespace googleclk\n// @description Disable Google click tracking\n// @include http://*google.com/*\n// ==/UserScript==\n// Override google's clk() function, which reports all clicks back to google\nunsafeWindow.clk = function(url) {} // { alert(url); } // I use this to test.\n</code></pre>\n\n<p>By doing something similar with XMLHttpRequest (and other functions) you can effectively disable them. Of course, you may completely break the page by doing this, but you already knew that.</p>\n" }, { "answer_id": 272596, "author": "JoeBloggs", "author_id": 34097, "author_profile": "https://Stackoverflow.com/users/34097", "pm_score": -1, "selected": false, "text": "<p>No more than you can disable any other function - there may be some kludges or hacks to be found that could interfere with or break javascript, but we would hope not to find such vulnerabilities.</p>\n\n<p>I'll take a wild stab in the dark and guess that you're trying to stop Ajax in untrusted user input of some kind? Your best bet in that case would be to avoid over-specifying your search parameters by mentioning Ajax, rather, search for 'sanitize javascript', 'user javascript safe'... that kind of thing.</p>\n" }, { "answer_id": 272612, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "<p>You can replace the browser tool to make AJAX (XMLHttpRequest object) with your own that does nothing.</p>\n\n<pre><code>XMLHttpRequest = function(){}\nXMLHttpRequest.prototype = {\n open: function(){},\n send: function(){}\n}\n</code></pre>\n\n<p>Be sure that your replacement code executes before any AJAX call.</p>\n\n<p>This will work for any browser that implement AJAX through the XMLHttpRequest object but will not work for IE. For IE, you may have to overload the CreateObject() function if possible...</p>\n" }, { "answer_id": 272707, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<p>Additionally to the Firefox suggestion, you can do it in IE as a side-effect of disabling ActiveX. Also on IE7+ you have to disable the ‘Native XMLHttpRequest’ option.</p>\n" }, { "answer_id": 1237291, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This is a late comment on a question that has already been answered, but for the benefit of people coming in from Google:</p>\n\n<p>With the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/4757\" rel=\"nofollow noreferrer\">Tab Permissions</a> extension for Firefox you can disable JavaScript for a particular tab (as opposed to globally for all tabs) with a right-click context menu. I configured the \"Permissions\" menu item to toggle \"Redirect\" and \"JavaScript,\" so if I stumble onto a page that has annoying refreshes and AJAX, I can quickly and easily shut down the bandwidth activity of the misbehaving tab without affecting the JavaScript on my other open tabs.</p>\n" }, { "answer_id": 7110984, "author": "Jon", "author_id": 901035, "author_profile": "https://Stackoverflow.com/users/901035", "pm_score": 3, "selected": false, "text": "<p>In IE this can be done with: Tools -> Internet Options -> Advanced Tab -> Scroll down to Security -> Uncheck 'Enable Native XMLHTTP Support'.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms537505%28v=vs.85%29.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms537505%28v=vs.85%29.aspx</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196/" ]
Is it possible to disable AJAX without disabling JavaScript completely?
If you are using Firefox, you could accomplish this with GreaseMonkey. (<https://addons.mozilla.org/en-US/firefox/addon/748>) GM is a framework for applying scripts to some or all of the pages you visit. I have GM scripts that disable google-analytics downloads (because they slow things down), and which disable google-click-tracking on google result pages (because it bothers me that they are doing that). Here is my google-click disable script: ``` // ==UserScript== // @name Google Clk // @namespace googleclk // @description Disable Google click tracking // @include http://*google.com/* // ==/UserScript== // Override google's clk() function, which reports all clicks back to google unsafeWindow.clk = function(url) {} // { alert(url); } // I use this to test. ``` By doing something similar with XMLHttpRequest (and other functions) you can effectively disable them. Of course, you may completely break the page by doing this, but you already knew that.
272,544
<p>I'm reading Erica Sadun's <em>iPhone Developer's Cookbook</em>, and ran into a question.</p> <p>She says in the book that the way to find the user's Documents directory is with the code:</p> <pre><code>[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; </code></pre> <p>but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be:</p> <pre><code>NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES); </code></pre> <p>Are there any particular reasons to use one over the other?</p>
[ { "answer_id": 272677, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 8, "selected": true, "text": "<p>Objc:</p>\n\n<pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)\n</code></pre>\n\n<p>Swift:</p>\n\n<pre><code>var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)\n</code></pre>\n\n<p>You'll want the first element of the returned array.</p>\n" }, { "answer_id": 346992, "author": "Lee", "author_id": 31063, "author_profile": "https://Stackoverflow.com/users/31063", "pm_score": 6, "selected": false, "text": "<p>Here is the code that I use in my framework.</p>\n\n<pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);\nNSString *documentsDirectory = [paths objectAtIndex:0];\n</code></pre>\n" }, { "answer_id": 12850202, "author": "Zelko", "author_id": 999638, "author_profile": "https://Stackoverflow.com/users/999638", "pm_score": 4, "selected": false, "text": "<h3>You should consider using the FileManager methods which return URLs, which are the preferred format.</h3>\n<pre><code>let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first\n</code></pre>\n<p>This method is intended to locate known and common directories in the system.</p>\n<p>An array of URL objects identifying the requested directories. The directories are ordered according to the order of the domain mask constants, with items in the user domain first and items in the system domain last.</p>\n" }, { "answer_id": 27995841, "author": "Nguyễn Văn Chung", "author_id": 4373040, "author_profile": "https://Stackoverflow.com/users/4373040", "pm_score": 1, "selected": false, "text": "<p>I use this</p>\n\n<pre><code>NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];\nNSString *zipLocalPath = [documentPath stringByAppendingString:fileName];\n</code></pre>\n" }, { "answer_id": 46130372, "author": "Suresh Velusamy", "author_id": 1614189, "author_profile": "https://Stackoverflow.com/users/1614189", "pm_score": -1, "selected": false, "text": "<p>In swift v3, I used the following snippet </p>\n\n<pre><code>var paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735/" ]
I'm reading Erica Sadun's *iPhone Developer's Cookbook*, and ran into a question. She says in the book that the way to find the user's Documents directory is with the code: ``` [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; ``` but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be: ``` NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES); ``` Are there any particular reasons to use one over the other?
Objc: ``` NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ``` Swift: ``` var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) ``` You'll want the first element of the returned array.
272,577
<p>Wanting to build and test a bunch of Borland Delphi 6 projects that are integrated with ASP.NET services. Had been using WANT and CruiseControl for building Delphi. With TFS Build agent we can tie all together and do some testing. I am looking for guidance and direction. </p> <p>One issue I see is that there is no "solution" in a Delphi project to be given to MSBuild as a '&lt;'SolutionToBuild'>'. </p> <pre><code>&lt;SolutionToBuild Include="There is no such thing as a Delphi.sln"&gt; &lt;Targets&gt;&lt;/Targets&gt; &lt;Properties&gt;&lt;/Properties&gt; &lt;/SolutionToBuild&gt; </code></pre> <p>Also, I have references to <code>&lt;UsingTask</code>> but am a little unsure how to use them. The <code>&lt;UsingTask</code>> allows run custom task for Delphi command-line compile. </p> <p>Your guidance would be appreciated.</p>
[ { "answer_id": 272614, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 1, "selected": false, "text": "<p>No.. lightroom plugins are written in the scripting language lua, photoshop plugins are written in C++.</p>\n" }, { "answer_id": 272640, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 1, "selected": false, "text": "<p>As noted by kasperjj, the Lightroom plugins are written in Lua so there is not a direct way to convert something from Photoshop over to Lightroom. Additionally, as per the <a href=\"http://www.adobe.com/devnet/photoshoplightroom/\" rel=\"nofollow noreferrer\">Adobe Lightroom Developer Center</a>, the only features that are extendable in the current SDK are the export functionality, metadata, and web engine functionality.</p>\n" }, { "answer_id": 564253, "author": "RBerteig", "author_id": 68204, "author_profile": "https://Stackoverflow.com/users/68204", "pm_score": 0, "selected": false, "text": "<p>As pointed out by Rob, the Lightroom SDK does not expose any interface that allows manipulations of the image files themselves. Partly this is because Lightroom is a non-destructive editor. None of the edits made in its Develop module are applied to the original image file; they are applied to the file generated when the image is exported, printed, or used in a web gallery.</p>\n\n<p>That said, there are examples of export plugins that manipulate the image <em>after</em> Lightroom has finished applying its adjustments. In principle, it would be possible to create a host application that loaded a Photoshop plugin and applied it during Lightroom export. It might even be possible to use Photoshop itself as that host application...</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35527/" ]
Wanting to build and test a bunch of Borland Delphi 6 projects that are integrated with ASP.NET services. Had been using WANT and CruiseControl for building Delphi. With TFS Build agent we can tie all together and do some testing. I am looking for guidance and direction. One issue I see is that there is no "solution" in a Delphi project to be given to MSBuild as a '<'SolutionToBuild'>'. ``` <SolutionToBuild Include="There is no such thing as a Delphi.sln"> <Targets></Targets> <Properties></Properties> </SolutionToBuild> ``` Also, I have references to `<UsingTask`> but am a little unsure how to use them. The `<UsingTask`> allows run custom task for Delphi command-line compile. Your guidance would be appreciated.
No.. lightroom plugins are written in the scripting language lua, photoshop plugins are written in C++.
272,584
<p>I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text). </p> <p>SInce it appears that heightForRowAtIndexPath is called <em>before</em> I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height <em>after</em> I've laid out the text in the cell and have an idea of exactly what size it should be?</p>
[ { "answer_id": 273008, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 4, "selected": true, "text": "<p>It's going to sound dumb, but ...uh... \"layout your cell before you exit heightForRowAtIndexPath\" ;)</p>\n\n<p>Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell &amp; display it on screen), so laying it out &amp; getting ready to display is not wasted effort.</p>\n\n<p>Note, you do <strong>not</strong> have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.</p>\n\n<p>If the data is static, you can create a height table and cache the info.</p>\n\n<pre><code>if (0 == heightTable[index]) {\n heightTable[index] = [self prepLayoutForCellAtIndex:index];\n}\nreturn (heightTable[index]);\n</code></pre>\n\n<p>Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.</p>\n" }, { "answer_id": 273059, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>I use the following, usually:</p>\n\n<pre><code>- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {\nUITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];\nreturn cell.bounds.size.height;\n</code></pre>\n\n<p>}</p>\n\n<p>Note that I use this for tables where I pre-cache a bunch of rows ahead of time, not for those with a LOT of cells. However, for things like Settings tables, where there are just a few rows, but most likely very differently sized, it works well. For larger tables, I do something along the lines of what Olie suggested.</p>\n" }, { "answer_id": 273443, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 0, "selected": false, "text": "<p>If you look at SMS.app as example, Apple saves the row height of the cell in the SMS.app sqlite database.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967/" ]
I have a UITableView cell that is going to have a variable size depending on it's content (potentially several lines of text). SInce it appears that heightForRowAtIndexPath is called *before* I layout the cell, I just guess the correct height by calling [NSString sizeWithFont] on my text string. Is there a better way to set the height *after* I've laid out the text in the cell and have an idea of exactly what size it should be?
It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;) Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort. Note, you do **not** have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine. If the data is static, you can create a height table and cache the info. ``` if (0 == heightTable[index]) { heightTable[index] = [self prepLayoutForCellAtIndex:index]; } return (heightTable[index]); ``` Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.
272,590
<p>We are developing a WPF application that uses the System.AddIn framework to host add-ins that display additional WPF content. Everything seems to be working fine, but overnight, the application threw the following NullReferenceException:</p> <pre> Message: Error : Object reference not set to an instance of an object. StackTrace : at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.AddIn.Pipeline.AddInHwndSourceWrapper.TranslateAccelerator(MSG msg, ModifierKeys modifiers) at MS.Internal.Controls.AddInHost.System.Windows.Interop.IKeyboardInputSink.TranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.Windows.Interop.HwndHost.OnKeyUp(KeyEventArgs e) at System.Windows.UIElement.OnKeyUpThunk(Object sender, KeyEventArgs e) at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey) at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled) at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled) at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled) at System.Windows.Interop.ThreadMessageEventHandler.Invoke(MSG& msg, Boolean& handled) at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() </pre> <p>As you can see, none of our code is in the stack trace, so I have no place to fix anything. Anybody have any ideas about possible workarounds?</p> <p>Thanks for the help!</p>
[ { "answer_id": 273008, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 4, "selected": true, "text": "<p>It's going to sound dumb, but ...uh... \"layout your cell before you exit heightForRowAtIndexPath\" ;)</p>\n\n<p>Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell &amp; display it on screen), so laying it out &amp; getting ready to display is not wasted effort.</p>\n\n<p>Note, you do <strong>not</strong> have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine.</p>\n\n<p>If the data is static, you can create a height table and cache the info.</p>\n\n<pre><code>if (0 == heightTable[index]) {\n heightTable[index] = [self prepLayoutForCellAtIndex:index];\n}\nreturn (heightTable[index]);\n</code></pre>\n\n<p>Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.</p>\n" }, { "answer_id": 273059, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>I use the following, usually:</p>\n\n<pre><code>- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {\nUITableViewCell *cell = [self tableView: tableView cellForRowAtIndexPath: indexPath];\nreturn cell.bounds.size.height;\n</code></pre>\n\n<p>}</p>\n\n<p>Note that I use this for tables where I pre-cache a bunch of rows ahead of time, not for those with a LOT of cells. However, for things like Settings tables, where there are just a few rows, but most likely very differently sized, it works well. For larger tables, I do something along the lines of what Olie suggested.</p>\n" }, { "answer_id": 273443, "author": "catlan", "author_id": 23028, "author_profile": "https://Stackoverflow.com/users/23028", "pm_score": 0, "selected": false, "text": "<p>If you look at SMS.app as example, Apple saves the row height of the cell in the SMS.app sqlite database.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9268/" ]
We are developing a WPF application that uses the System.AddIn framework to host add-ins that display additional WPF content. Everything seems to be working fine, but overnight, the application threw the following NullReferenceException: ``` Message: Error : Object reference not set to an instance of an object. StackTrace : at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.AddIn.Pipeline.AddInHwndSourceWrapper.TranslateAccelerator(MSG msg, ModifierKeys modifiers) at MS.Internal.Controls.AddInHost.System.Windows.Interop.IKeyboardInputSink.TranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.Windows.Interop.HwndHost.OnKeyUp(KeyEventArgs e) at System.Windows.UIElement.OnKeyUpThunk(Object sender, KeyEventArgs e) at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args) at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey) at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled) at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers) at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled) at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled) at System.Windows.Interop.ThreadMessageEventHandler.Invoke(MSG& msg, Boolean& handled) at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run() ``` As you can see, none of our code is in the stack trace, so I have no place to fix anything. Anybody have any ideas about possible workarounds? Thanks for the help!
It's going to sound dumb, but ...uh... "layout your cell before you exit heightForRowAtIndexPath" ;) Seriously, though -- the OS only ever calls this if it's going to be needed (as in: it's about to create the cell & display it on screen), so laying it out & getting ready to display is not wasted effort. Note, you do **not** have to do your layout separately, logic-wise. Just make a call to your [self prepLayoutForCellAtIndex:index] within your heightForRowAtIndexPath routine. If the data is static, you can create a height table and cache the info. ``` if (0 == heightTable[index]) { heightTable[index] = [self prepLayoutForCellAtIndex:index]; } return (heightTable[index]); ``` Heck, even if the data changes, you can either recalculate the table value in the method that changes the data, or clear to 0 so it gets recalculated the next time it's needed.
272,607
<p>Is there a way to pre-compute an array of values based on templates? In the following example I would like the 'powers_of_2' array to have 256 values computed at compile-time if that is possible without having to type all of the values.</p> <pre><code>#include &lt;iostream&gt; using namespace std; template &lt;int X, char Y&gt; struct power { enum { value = X * power&lt;X,Y-1&gt;::value }; }; template &lt;int X&gt; struct power&lt;X,1&gt; { enum { value = X }; }; template &lt;int X&gt; struct power&lt;X,0&gt; { enum { value = 1 }; }; int _tmain(int argc, _TCHAR* argv[]) { int powers_of_2[] = { power&lt;2,0&gt;::value, power&lt;2,1&gt;::value, ..., power&lt;2,255&gt;::value }; cout &lt;&lt; powers_of_2[1] &lt;&lt; endl; return 0; } </code></pre>
[ { "answer_id": 272615, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 1, "selected": false, "text": "<p>That is exactly what a macro is useful for...</p>\n" }, { "answer_id": 272622, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 2, "selected": false, "text": "<p>Unless you plan on using a big integer package you will overflow the integer type at 2^32 (or 2^64, depending), but to answer your real question look at this wikipedia article on <A href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\">template metaprogramming</A>.</p>\n" }, { "answer_id": 272625, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 0, "selected": false, "text": "<p>You could easily write a small script to prepopulate the array for you using your preferred scripting language. Depending on the compiler and preprocessor you use, you should also be able to do it as a macro.</p>\n" }, { "answer_id": 272712, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Holding the value 2^255 would require 32 bytes. This cannot be held in an int; you'd need a char array</p>\n\n<pre><code>typedef unsigned char BYTE32[32];\nBYTE32 powers_of_2[256] =\n{\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},\n {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0},\n// :\n// :\n {32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},\n {128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}\n};\n</code></pre>\n" }, { "answer_id": 273343, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 0, "selected": false, "text": "<p>I agree with Lokkju. It is not possible to initialize the array by only means of template metaprogramming and macros in this case are very useful. Even Boost libraries make use of macros to implement repetitive statements. </p>\n\n<p>Examples of useful macros are available here: <a href=\"http://awgn.antifork.org/codes++/macro_template.h\" rel=\"nofollow noreferrer\">http://awgn.antifork.org/codes++/macro_template.h</a></p>\n" }, { "answer_id": 280682, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 1, "selected": false, "text": "<p>What I do in situations like that is write a small program that generates and writes to a file the array initialization in C++ source and then #include that file. This technique is simple and effective.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
Is there a way to pre-compute an array of values based on templates? In the following example I would like the 'powers\_of\_2' array to have 256 values computed at compile-time if that is possible without having to type all of the values. ``` #include <iostream> using namespace std; template <int X, char Y> struct power { enum { value = X * power<X,Y-1>::value }; }; template <int X> struct power<X,1> { enum { value = X }; }; template <int X> struct power<X,0> { enum { value = 1 }; }; int _tmain(int argc, _TCHAR* argv[]) { int powers_of_2[] = { power<2,0>::value, power<2,1>::value, ..., power<2,255>::value }; cout << powers_of_2[1] << endl; return 0; } ```
Unless you plan on using a big integer package you will overflow the integer type at 2^32 (or 2^64, depending), but to answer your real question look at this wikipedia article on [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming).
272,618
<p>I've created a MATLAB class, something like:</p> <pre><code>classdef myclass properties x_array = []; end methods function increment(obj,value) obj.x_array = [obj.x_array ; value); end end end </code></pre> <p>The problem is, the property <code>x_array</code> is never modified when I invoke the <code>increment()</code> function: ex:</p> <pre><code>&gt;&gt;s = myclass &gt;&gt;increment(s,5) &gt;&gt;s.x_array ans = [] </code></pre> <p>I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:</p> <pre><code>classdef myclass &lt; handle </code></pre> <p>or are there any extra steps?</p>
[ { "answer_id": 272920, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 5, "selected": false, "text": "<p>This is similar to <a href=\"https://stackoverflow.com/questions/209005/object-oriented-matlab-properties\">this question</a>. In short all you should have to do is inherit from handle class.</p>\n\n<p>Quick example </p>\n\n<p>Contents of file myclass.m</p>\n\n<pre><code>classdef myclass&lt;handle\n properties\n x_array = []\n end\n methods\n function obj=increment(obj,val)\n obj.x_array=[obj.x_array val];\n end\n end\nend\n</code></pre>\n\n<p>Now from the Matlab command prompt, you can do the following</p>\n\n<pre><code>&gt;&gt; s=myclass;\n&gt;&gt; s.increment(5)\n&gt;&gt; s.increment(6)\n&gt;&gt; s\n\ns = \n\nmyclass handle\n\nproperties:\n x_array: [5 6]\n\nlists of methods, events, superclasses\n</code></pre>\n" }, { "answer_id": 39391035, "author": "Meisam Jalalvand", "author_id": 6809197, "author_profile": "https://Stackoverflow.com/users/6809197", "pm_score": 0, "selected": false, "text": "<p>There is an easier way. You only need to overwrite your initial instance <code>s</code> as follows:</p>\n\n<pre><code>s = increment(s,5);\n</code></pre>\n\n<p>More information <a href=\"https://www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oo-languages.html\" rel=\"nofollow noreferrer\">in the documentation</a>.</p>\n\n<p>PS: While it is fine to use <em>handle</em>, the way copy function works is different and you should be careful about the way you use it. When you use <em>handle</em>, in fact you are making a new address/reference to an obj</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34830/" ]
I've created a MATLAB class, something like: ``` classdef myclass properties x_array = []; end methods function increment(obj,value) obj.x_array = [obj.x_array ; value); end end end ``` The problem is, the property `x_array` is never modified when I invoke the `increment()` function: ex: ``` >>s = myclass >>increment(s,5) >>s.x_array ans = [] ``` I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it: ``` classdef myclass < handle ``` or are there any extra steps?
This is similar to [this question](https://stackoverflow.com/questions/209005/object-oriented-matlab-properties). In short all you should have to do is inherit from handle class. Quick example Contents of file myclass.m ``` classdef myclass<handle properties x_array = [] end methods function obj=increment(obj,val) obj.x_array=[obj.x_array val]; end end end ``` Now from the Matlab command prompt, you can do the following ``` >> s=myclass; >> s.increment(5) >> s.increment(6) >> s s = myclass handle properties: x_array: [5 6] lists of methods, events, superclasses ```
272,620
<p>I am trying to setup a WCF service with multiple endpoints with one of the endpoints using the enableWebScript endpoint behavior so that a Javascript proxy will be created on the client (jsdebug/js).</p> <p>When adding the Service Reference to my AJAX ScriptManager, the jsdebug file is not found unless the address of the endpoint is blank. The ScriptManager proxy seems to always generate a path of "MyService.svc/jsdebug" to look for the file even though my service has an address of "ajax". The proxy should generate the path as "MyService.svc/ajax/jsdebug".</p> <p>Is there a setting to get the Proxy generated with the right path? My service is at the root of my website.</p> <p>works:</p> <pre><code>&lt;endpoint address="" behaviorConfiguration="ajaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="MyTest.Web.ICustomerService" /&gt; </code></pre> <p>want this (doesn't work):</p> <pre><code>&lt;endpoint address="ajax" behaviorConfiguration="ajaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="MyTest.Web.ICustomerService" /&gt; </code></pre>
[ { "answer_id": 692198, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 2, "selected": false, "text": "<p><code>&lt;enableWebScript /&gt;</code> also known as AJAX-enabled endpoints essentially hard-codes everything to do with address so you can generate the client-side code.</p>\n\n<p>The way it's hard-coded is that everything is directly relative to the .svc file.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/bb628467.aspx\" rel=\"nofollow noreferrer\">How to: Use Configuration to Add an ASP.NET AJAX Endpoint</a></p>\n\n<blockquote>\n <p>The endpoint is configured at an empty\n address relative to the .svc file, so\n the service is now available and can\n be invoked by sending requests to\n <code>service.svc/&lt;operation&gt;</code> - for example,\n <code>service.svc/Add</code> for the <code>Add</code> operation.</p>\n</blockquote>\n\n<p>For this reason, you can't mix <code>&lt;enableWebScript /&gt;</code> with <code>UriTemplate</code>, which takes away half the fun out of WCF in my opinion. See <a href=\"http://blogs.msdn.com/justinjsmith/archive/2008/02/15/enablewebscript-uritemplate-and-http-methods.aspx\" rel=\"nofollow noreferrer\">enableWebScript, UriTemplate, and HTTP methods</a>.</p>\n\n<p>Personally, I like to configure my URI and serve both POX and JSON, as well as SOAP. See <a href=\"http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html\" rel=\"nofollow noreferrer\">WCF RESTful POX, JSON and SOAP Coexist</a>.</p>\n" }, { "answer_id": 1263661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In the ScriptManager, put MyService.svc/ajax instead of MyService.svc</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24188/" ]
I am trying to setup a WCF service with multiple endpoints with one of the endpoints using the enableWebScript endpoint behavior so that a Javascript proxy will be created on the client (jsdebug/js). When adding the Service Reference to my AJAX ScriptManager, the jsdebug file is not found unless the address of the endpoint is blank. The ScriptManager proxy seems to always generate a path of "MyService.svc/jsdebug" to look for the file even though my service has an address of "ajax". The proxy should generate the path as "MyService.svc/ajax/jsdebug". Is there a setting to get the Proxy generated with the right path? My service is at the root of my website. works: ``` <endpoint address="" behaviorConfiguration="ajaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="MyTest.Web.ICustomerService" /> ``` want this (doesn't work): ``` <endpoint address="ajax" behaviorConfiguration="ajaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="MyTest.Web.ICustomerService" /> ```
`<enableWebScript />` also known as AJAX-enabled endpoints essentially hard-codes everything to do with address so you can generate the client-side code. The way it's hard-coded is that everything is directly relative to the .svc file. See [How to: Use Configuration to Add an ASP.NET AJAX Endpoint](http://msdn.microsoft.com/en-us/library/bb628467.aspx) > > The endpoint is configured at an empty > address relative to the .svc file, so > the service is now available and can > be invoked by sending requests to > `service.svc/<operation>` - for example, > `service.svc/Add` for the `Add` operation. > > > For this reason, you can't mix `<enableWebScript />` with `UriTemplate`, which takes away half the fun out of WCF in my opinion. See [enableWebScript, UriTemplate, and HTTP methods](http://blogs.msdn.com/justinjsmith/archive/2008/02/15/enablewebscript-uritemplate-and-http-methods.aspx). Personally, I like to configure my URI and serve both POX and JSON, as well as SOAP. See [WCF RESTful POX, JSON and SOAP Coexist](http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html).
272,633
<p>Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals"</p> <p>Here is my attempt with a RegEx</p> <pre><code>System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0") </code></pre>
[ { "answer_id": 272666, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>What you have works perfectly. Just remember to reassign <code>value</code> to the return value of this function.</p>\n\n<pre><code>value = System.Text.RegularExpressions.Regex.Replace(value, \"[A-Z]\", \" $0\");\n</code></pre>\n" }, { "answer_id": 272809, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 7, "selected": false, "text": "<p>Your solution has an issue in that it puts a space before the first letter T so you get </p>\n\n<pre><code>\" This String...\" instead of \"This String...\"\n</code></pre>\n\n<p>To get around this look for the lower case letter preceding it as well and then insert the space in the middle:</p>\n\n<pre><code>newValue = Regex.Replace(value, \"([a-z])([A-Z])\", \"$1 $2\");\n</code></pre>\n\n<p><strong>Edit 1:</strong></p>\n\n<p>If you use <code>@\"(\\p{Ll})(\\p{Lu})\"</code> it will pick up accented characters as well.</p>\n\n<p><strong>Edit 2:</strong></p>\n\n<p>If your strings can contain acronyms you may want to use this:</p>\n\n<pre><code>newValue = Regex.Replace(value, @\"((?&lt;=\\p{Ll})\\p{Lu})|((?!\\A)\\p{Lu}(?&gt;\\p{Ll}))\", \" $0\");\n</code></pre>\n\n<p>So \"DriveIsSCSICompatible\" becomes \"Drive Is SCSI Compatible\"</p>\n" }, { "answer_id": 272897, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 2, "selected": false, "text": "<p>Here's mine:</p>\n\n<pre><code>private string SplitCamelCase(string s) \n{ \n Regex upperCaseRegex = new Regex(@\"[A-Z]{1}[a-z]*\"); \n MatchCollection matches = upperCaseRegex.Matches(s); \n List&lt;string&gt; words = new List&lt;string&gt;(); \n foreach (Match match in matches) \n { \n words.Add(match.Value); \n } \n return String.Join(\" \", words.ToArray()); \n}\n</code></pre>\n" }, { "answer_id": 272929, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 9, "selected": true, "text": "<p>The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse)</p>\n\n<p>This function </p>\n\n<pre><code>string AddSpacesToSentence(string text, bool preserveAcronyms)\n{\n if (string.IsNullOrWhiteSpace(text))\n return string.Empty;\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i &lt; text.Length; i++)\n {\n if (char.IsUpper(text[i]))\n if ((text[i - 1] != ' ' &amp;&amp; !char.IsUpper(text[i - 1])) ||\n (preserveAcronyms &amp;&amp; char.IsUpper(text[i - 1]) &amp;&amp; \n i &lt; text.Length - 1 &amp;&amp; !char.IsUpper(text[i + 1])))\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n</code></pre>\n\n<p>Will do it 100,000 times in 2,968,750 ticks, the regex will take 25,000,000 ticks (and thats with the regex compiled).</p>\n\n<p>It's better, for a given value of better (i.e. faster) however it's more code to maintain. \"Better\" is often compromise of competing requirements.</p>\n\n<p>Hope this helps :)</p>\n\n<p><strong>Update</strong><br>\nIt's a good long while since I looked at this, and I just realised the timings haven't been updated since the code changed (it only changed a little).</p>\n\n<p>On a string with 'Abbbbbbbbb' repeated 100 times (i.e. 1,000 bytes), a run of 100,000 conversions takes the hand coded function 4,517,177 ticks, and the Regex below takes 59,435,719 making the Hand coded function run in 7.6% of the time it takes the Regex.</p>\n\n<p><strong>Update 2</strong>\nWill it take Acronyms into account? It will now!\nThe logic of the if statment is fairly obscure, as you can see expanding it to this ...</p>\n\n<pre><code>if (char.IsUpper(text[i]))\n if (char.IsUpper(text[i - 1]))\n if (preserveAcronyms &amp;&amp; i &lt; text.Length - 1 &amp;&amp; !char.IsUpper(text[i + 1]))\n newText.Append(' ');\n else ;\n else if (text[i - 1] != ' ')\n newText.Append(' ');\n</code></pre>\n\n<p>... doesn't help at all!</p>\n\n<p>Here's the original <em>simple</em> method that doesn't worry about Acronyms</p>\n\n<pre><code>string AddSpacesToSentence(string text)\n{\n if (string.IsNullOrWhiteSpace(text))\n return \"\";\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i &lt; text.Length; i++)\n {\n if (char.IsUpper(text[i]) &amp;&amp; text[i - 1] != ' ')\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n</code></pre>\n" }, { "answer_id": 677522, "author": "Richard Priddy", "author_id": 82024, "author_profile": "https://Stackoverflow.com/users/82024", "pm_score": 2, "selected": false, "text": "<p>Binary Worrier, I have used your suggested code, and it is rather good, I have just one minor addition to it:</p>\n\n<pre><code>public static string AddSpacesToSentence(string text)\n{\n if (string.IsNullOrEmpty(text))\n return \"\";\n StringBuilder newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i &lt; result.Length; i++)\n {\n if (char.IsUpper(result[i]) &amp;&amp; !char.IsUpper(result[i - 1]))\n {\n newText.Append(' ');\n }\n else if (i &lt; result.Length)\n {\n if (char.IsUpper(result[i]) &amp;&amp; !char.IsUpper(result[i + 1]))\n newText.Append(' ');\n\n }\n newText.Append(result[i]);\n }\n return newText.ToString();\n}\n</code></pre>\n\n<p>I have added a condition <code>!char.IsUpper(text[i - 1])</code>. This fixed a bug that would cause something like 'AverageNOX' to be turned into 'Average N O X', which is obviously wrong, as it should read 'Average NOX'.</p>\n\n<p>Sadly this still has the bug that if you have the text 'FromAStart', you would get 'From AStart' out.</p>\n\n<p>Any thoughts on fixing this?</p>\n" }, { "answer_id": 5021570, "author": "EtienneT", "author_id": 9140, "author_profile": "https://Stackoverflow.com/users/9140", "pm_score": 7, "selected": false, "text": "<p>Didn't test performance, but here in one line with linq:</p>\n\n<pre><code>var val = \"ThisIsAStringToTest\";\nval = string.Concat(val.Select(x =&gt; Char.IsUpper(x) ? \" \" + x : x.ToString())).TrimStart(' ');\n</code></pre>\n" }, { "answer_id": 5021700, "author": "Justin Morgan", "author_id": 399649, "author_profile": "https://Stackoverflow.com/users/399649", "pm_score": 2, "selected": false, "text": "<p>Make sure you <strong>aren't</strong> putting spaces at the beginning of the string, but you <strong>are</strong> putting them between consecutive capitals. Some of the answers here don't address one or both of those points. There are other ways than regex, but if you prefer to use that, try this:</p>\n\n<pre><code>Regex.Replace(value, @\"\\B[A-Z]\", \" $0\")\n</code></pre>\n\n<p>The <code>\\B</code> is a negated <code>\\b</code>, so it represents a non-word-boundary. It means the pattern matches \"Y\" in <code>XYzabc</code>, but not in <code>Yzabc</code> or <code>X Yzabc</code>. As a little bonus, you can use this on a string with spaces in it and it won't double them.</p>\n" }, { "answer_id": 5149388, "author": "tchrist", "author_id": 471272, "author_profile": "https://Stackoverflow.com/users/471272", "pm_score": 3, "selected": false, "text": "<h1>Welcome to Unicode</h1>\n\n<p>All these solutions are essentially wrong for modern text. You need to use something that understands case. Since Bob asked for other languages, I'll give a couple for Perl.</p>\n\n<p>I provide four solutions, ranging from worst to best. Only the best one is always right. The others have problems. Here is a test run to show you what works and what doesn’t, and where. I’ve used underscores so that you can see where the spaces have been put, and I’ve marked as wrong anything that is, well, wrong. </p>\n\n<pre><code>Testing TheLoneRanger\n Worst: The_Lone_Ranger\n Ok: The_Lone_Ranger\n Better: The_Lone_Ranger\n Best: The_Lone_Ranger\nTesting MountMᶜKinleyNationalPark\n [WRONG] Worst: Mount_MᶜKinley_National_Park\n [WRONG] Ok: Mount_MᶜKinley_National_Park\n [WRONG] Better: Mount_MᶜKinley_National_Park\n Best: Mount_Mᶜ_Kinley_National_Park\nTesting ElÁlamoTejano\n [WRONG] Worst: ElÁlamo_Tejano\n Ok: El_Álamo_Tejano\n Better: El_Álamo_Tejano\n Best: El_Álamo_Tejano\nTesting TheÆvarArnfjörðBjarmason\n [WRONG] Worst: TheÆvar_ArnfjörðBjarmason\n Ok: The_Ævar_Arnfjörð_Bjarmason\n Better: The_Ævar_Arnfjörð_Bjarmason\n Best: The_Ævar_Arnfjörð_Bjarmason\nTesting IlCaffèMacchiato\n [WRONG] Worst: Il_CaffèMacchiato\n Ok: Il_Caffè_Macchiato\n Better: Il_Caffè_Macchiato\n Best: Il_Caffè_Macchiato\nTesting MisterDženanLjubović\n [WRONG] Worst: MisterDženanLjubović\n [WRONG] Ok: MisterDženanLjubović\n Better: Mister_Dženan_Ljubović\n Best: Mister_Dženan_Ljubović\nTesting OleKingHenryⅧ\n [WRONG] Worst: Ole_King_HenryⅧ\n [WRONG] Ok: Ole_King_HenryⅧ\n [WRONG] Better: Ole_King_HenryⅧ\n Best: Ole_King_Henry_Ⅷ\nTesting CarlosⅤºElEmperador\n [WRONG] Worst: CarlosⅤºEl_Emperador\n [WRONG] Ok: CarlosⅤº_El_Emperador\n [WRONG] Better: CarlosⅤº_El_Emperador\n Best: Carlos_Ⅴº_El_Emperador\n</code></pre>\n\n<p>BTW, almost everyone here has selected the first way, the one marked \"Worst\". A few have selected the second way, marked \"OK\". But no one else before me has shown you how to do either the \"Better\" or the \"Best\" approach.</p>\n\n<p>Here is the test program with its four methods:</p>\n\n<pre><code>#!/usr/bin/env perl\nuse utf8;\nuse strict;\nuse warnings;\n\n# First I'll prove these are fine variable names:\nmy (\n $TheLoneRanger ,\n $MountMᶜKinleyNationalPark ,\n $ElÁlamoTejano ,\n $TheÆvarArnfjörðBjarmason ,\n $IlCaffèMacchiato ,\n $MisterDženanLjubović ,\n $OleKingHenryⅧ ,\n $CarlosⅤºElEmperador ,\n);\n\n# Now I'll load up some string with those values in them:\nmy @strings = qw{\n TheLoneRanger\n MountMᶜKinleyNationalPark\n ElÁlamoTejano\n TheÆvarArnfjörðBjarmason\n IlCaffèMacchiato\n MisterDženanLjubović\n OleKingHenryⅧ\n CarlosⅤºElEmperador\n};\n\nmy($new, $best, $ok);\nmy $mask = \" %10s %-8s %s\\n\";\n\nfor my $old (@strings) {\n print \"Testing $old\\n\";\n ($best = $old) =~ s/(?&lt;=\\p{Lowercase})(?=[\\p{Uppercase}\\p{Lt}])/_/g;\n\n ($new = $old) =~ s/(?&lt;=[a-z])(?=[A-Z])/_/g;\n $ok = ($new ne $best) &amp;&amp; \"[WRONG]\";\n printf $mask, $ok, \"Worst:\", $new;\n\n ($new = $old) =~ s/(?&lt;=\\p{Ll})(?=\\p{Lu})/_/g;\n $ok = ($new ne $best) &amp;&amp; \"[WRONG]\";\n printf $mask, $ok, \"Ok:\", $new;\n\n ($new = $old) =~ s/(?&lt;=\\p{Ll})(?=[\\p{Lu}\\p{Lt}])/_/g;\n $ok = ($new ne $best) &amp;&amp; \"[WRONG]\";\n printf $mask, $ok, \"Better:\", $new;\n\n ($new = $old) =~ s/(?&lt;=\\p{Lowercase})(?=[\\p{Uppercase}\\p{Lt}])/_/g;\n $ok = ($new ne $best) &amp;&amp; \"[WRONG]\";\n printf $mask, $ok, \"Best:\", $new;\n}\n</code></pre>\n\n<p>When you can score the same as the \"Best\" on this dataset, you’ll know you’ve done it correctly. Until then, you haven’t. No one else here has done better than \"Ok\", and most have done it \"Worst\". I look forward to seeing someone post the correct ℂ♯ code.</p>\n\n<p>I notice that StackOverflow’s highlighting code is miserably stoopid again. They’re making all the same old lame as (most but not all) of the rest of the poor approaches mentioned here have made. Isn’t it long past time to put ASCII to rest? It doens’t make sense anymore, and pretending it’s all you have is simply wrong. It makes for bad code.</p>\n" }, { "answer_id": 6536233, "author": "Randyaa", "author_id": 9518, "author_profile": "https://Stackoverflow.com/users/9518", "pm_score": 1, "selected": false, "text": "<pre><code>replaceAll(\"(?&lt;=[^^\\\\p{Uppercase}])(?=[\\\\p{Uppercase}])\",\" \");\n</code></pre>\n" }, { "answer_id": 9316659, "author": "Daryl", "author_id": 227436, "author_profile": "https://Stackoverflow.com/users/227436", "pm_score": 0, "selected": false, "text": "<p>In addition to Martin Brown's Answer, I had an issue with numbers as well. For Example: \"Location2\", or \"Jan22\" should be \"Location 2\", and \"Jan 22\" respectively.</p>\n\n<p>Here is my Regular Expression for doing that, using Martin Brown's answer:</p>\n\n<pre><code>\"((?&lt;=\\p{Ll})\\p{Lu})|((?!\\A)\\p{Lu}(?&gt;\\p{Ll}))|((?&lt;=[\\p{Ll}\\p{Lu}])\\p{Nd})|((?&lt;=\\p{Nd})\\p{Lu})\"\n</code></pre>\n\n<p>Here are a couple great sites for figuring out what each part means as well:</p>\n\n<p><a href=\"http://xenon.stanford.edu/~xusch/regexp/analyzer.html\" rel=\"nofollow\">Java Based Regular Expression Analyzer (but works for most .net regex's)</a></p>\n\n<p><a href=\"http://gskinner.com/RegExr/\" rel=\"nofollow\">Action Script Based Analyzer</a></p>\n\n<p>The above regex won't work on the action script site unless you replace all of the <code>\\p{Ll}</code> with <code>[a-z]</code>, the <code>\\p{Lu}</code> with <code>[A-Z]</code>, and <code>\\p{Nd}</code> with <code>[0-9]</code>.</p>\n" }, { "answer_id": 11037992, "author": "cyril", "author_id": 1456860, "author_profile": "https://Stackoverflow.com/users/1456860", "pm_score": 1, "selected": false, "text": "<pre><code>static string AddSpacesToColumnName(string columnCaption)\n {\n if (string.IsNullOrWhiteSpace(columnCaption))\n return \"\";\n StringBuilder newCaption = new StringBuilder(columnCaption.Length * 2);\n newCaption.Append(columnCaption[0]);\n int pos = 1;\n for (pos = 1; pos &lt; columnCaption.Length-1; pos++)\n { \n if (char.IsUpper(columnCaption[pos]) &amp;&amp; !(char.IsUpper(columnCaption[pos - 1]) &amp;&amp; char.IsUpper(columnCaption[pos + 1])))\n newCaption.Append(' ');\n newCaption.Append(columnCaption[pos]);\n }\n newCaption.Append(columnCaption[pos]);\n return newCaption.ToString();\n }\n</code></pre>\n" }, { "answer_id": 11677460, "author": "Artem", "author_id": 1555960, "author_profile": "https://Stackoverflow.com/users/1555960", "pm_score": 1, "selected": false, "text": "<p>In Ruby, via Regexp:</p>\n\n<pre><code>\"FooBarBaz\".gsub(/(?!^)(?=[A-Z])/, ' ') # =&gt; \"Foo Bar Baz\"\n</code></pre>\n" }, { "answer_id": 12566426, "author": "Yetiish", "author_id": 855448, "author_profile": "https://Stackoverflow.com/users/855448", "pm_score": 0, "selected": false, "text": "<p>Here's my solution, based on Binary Worriers suggestion and building in Richard Priddys' comments, but also taking into account that white space may exist in the provided string, so it won't add white space next to existing white space.</p>\n\n<pre><code>public string AddSpacesBeforeUpperCase(string nonSpacedString)\n {\n if (string.IsNullOrEmpty(nonSpacedString))\n return string.Empty;\n\n StringBuilder newText = new StringBuilder(nonSpacedString.Length * 2);\n newText.Append(nonSpacedString[0]);\n\n for (int i = 1; i &lt; nonSpacedString.Length; i++)\n {\n char currentChar = nonSpacedString[i];\n\n // If it is whitespace, we do not need to add another next to it\n if(char.IsWhiteSpace(currentChar))\n {\n continue;\n }\n\n char previousChar = nonSpacedString[i - 1];\n char nextChar = i &lt; nonSpacedString.Length - 1 ? nonSpacedString[i + 1] : nonSpacedString[i];\n\n if (char.IsUpper(currentChar) &amp;&amp; !char.IsWhiteSpace(nextChar) \n &amp;&amp; !(char.IsUpper(previousChar) &amp;&amp; char.IsUpper(nextChar)))\n {\n newText.Append(' ');\n }\n else if (i &lt; nonSpacedString.Length)\n {\n if (char.IsUpper(currentChar) &amp;&amp; !char.IsWhiteSpace(nextChar) &amp;&amp; !char.IsUpper(nextChar))\n {\n newText.Append(' ');\n }\n }\n\n newText.Append(currentChar);\n }\n\n return newText.ToString();\n }\n</code></pre>\n" }, { "answer_id": 12732616, "author": "Kevin Stricker", "author_id": 486620, "author_profile": "https://Stackoverflow.com/users/486620", "pm_score": 4, "selected": false, "text": "<p>I set out to make a simple extension method based on Binary Worrier's code which will handle acronyms properly, and is repeatable (won't mangle already spaced words). Here is my result.</p>\n\n<pre><code>public static string UnPascalCase(this string text)\n{\n if (string.IsNullOrWhiteSpace(text))\n return \"\";\n var newText = new StringBuilder(text.Length * 2);\n newText.Append(text[0]);\n for (int i = 1; i &lt; text.Length; i++)\n {\n var currentUpper = char.IsUpper(text[i]);\n var prevUpper = char.IsUpper(text[i - 1]);\n var nextUpper = (text.Length &gt; i + 1) ? char.IsUpper(text[i + 1]) || char.IsWhiteSpace(text[i + 1]): prevUpper;\n var spaceExists = char.IsWhiteSpace(text[i - 1]);\n if (currentUpper &amp;&amp; !spaceExists &amp;&amp; (!nextUpper || !prevUpper))\n newText.Append(' ');\n newText.Append(text[i]);\n }\n return newText.ToString();\n}\n</code></pre>\n\n<p>Here are the unit test cases this function passes. I added most of tchrist's suggested cases to this list. The three of those it doesn't pass (two are just Roman numerals) are commented out:</p>\n\n<pre><code>Assert.AreEqual(\"For You And I\", \"ForYouAndI\".UnPascalCase());\nAssert.AreEqual(\"For You And The FBI\", \"ForYouAndTheFBI\".UnPascalCase());\nAssert.AreEqual(\"A Man A Plan A Canal Panama\", \"AManAPlanACanalPanama\".UnPascalCase());\nAssert.AreEqual(\"DNS Server\", \"DNSServer\".UnPascalCase());\nAssert.AreEqual(\"For You And I\", \"For You And I\".UnPascalCase());\nAssert.AreEqual(\"Mount Mᶜ Kinley National Park\", \"MountMᶜKinleyNationalPark\".UnPascalCase());\nAssert.AreEqual(\"El Álamo Tejano\", \"ElÁlamoTejano\".UnPascalCase());\nAssert.AreEqual(\"The Ævar Arnfjörð Bjarmason\", \"TheÆvarArnfjörðBjarmason\".UnPascalCase());\nAssert.AreEqual(\"Il Caffè Macchiato\", \"IlCaffèMacchiato\".UnPascalCase());\n//Assert.AreEqual(\"Mister Dženan Ljubović\", \"MisterDženanLjubović\".UnPascalCase());\n//Assert.AreEqual(\"Ole King Henry Ⅷ\", \"OleKingHenryⅧ\".UnPascalCase());\n//Assert.AreEqual(\"Carlos Ⅴº El Emperador\", \"CarlosⅤºElEmperador\".UnPascalCase());\nAssert.AreEqual(\"For You And The FBI\", \"For You And The FBI\".UnPascalCase());\nAssert.AreEqual(\"A Man A Plan A Canal Panama\", \"A Man A Plan A Canal Panama\".UnPascalCase());\nAssert.AreEqual(\"DNS Server\", \"DNS Server\".UnPascalCase());\nAssert.AreEqual(\"Mount Mᶜ Kinley National Park\", \"Mount Mᶜ Kinley National Park\".UnPascalCase());\n</code></pre>\n" }, { "answer_id": 12902560, "author": "KCITGuy", "author_id": 1748092, "author_profile": "https://Stackoverflow.com/users/1748092", "pm_score": 2, "selected": false, "text": "<p>Here is how you could do it in SQL </p>\n\n<pre><code>create FUNCTION dbo.PascalCaseWithSpace(@pInput AS VARCHAR(MAX)) RETURNS VARCHAR(MAX)\nBEGIN\n declare @output varchar(8000)\n\nset @output = ''\n\n\nDeclare @vInputLength INT\nDeclare @vIndex INT\nDeclare @vCount INT\nDeclare @PrevLetter varchar(50)\nSET @PrevLetter = ''\n\nSET @vCount = 0\nSET @vIndex = 1\nSET @vInputLength = LEN(@pInput)\n\nWHILE @vIndex &lt;= @vInputLength\nBEGIN\n IF ASCII(SUBSTRING(@pInput, @vIndex, 1)) = ASCII(Upper(SUBSTRING(@pInput, @vIndex, 1)))\n begin \n\n if(@PrevLetter != '' and ASCII(@PrevLetter) = ASCII(Lower(@PrevLetter)))\n SET @output = @output + ' ' + SUBSTRING(@pInput, @vIndex, 1)\n else\n SET @output = @output + SUBSTRING(@pInput, @vIndex, 1) \n\n end\n else\n begin\n SET @output = @output + SUBSTRING(@pInput, @vIndex, 1) \n\n end\n\nset @PrevLetter = SUBSTRING(@pInput, @vIndex, 1) \n\n SET @vIndex = @vIndex + 1\nEND\n\n\nreturn @output\nEND\n</code></pre>\n" }, { "answer_id": 17888613, "author": "lbrendanl", "author_id": 1362348, "author_profile": "https://Stackoverflow.com/users/1362348", "pm_score": 0, "selected": false, "text": "<p>For anyone who is looking for a C++ function answering this same question, you can use the following. This is modeled after the answer given by @Binary Worrier. This method just preserves Acronyms automatically. </p>\n\n<pre><code>using namespace std;\n\nvoid AddSpacesToSentence(string&amp; testString)\n stringstream ss;\n ss &lt;&lt; testString.at(0);\n for (auto it = testString.begin() + 1; it != testString.end(); ++it )\n {\n int index = it - testString.begin();\n char c = (*it);\n if (isupper(c))\n {\n char prev = testString.at(index - 1);\n if (isupper(prev))\n {\n if (index &lt; testString.length() - 1)\n {\n char next = testString.at(index + 1);\n if (!isupper(next) &amp;&amp; next != ' ')\n {\n ss &lt;&lt; ' ';\n }\n }\n }\n else if (islower(prev)) \n {\n ss &lt;&lt; ' ';\n }\n }\n\n ss &lt;&lt; c;\n }\n\n cout &lt;&lt; ss.str() &lt;&lt; endl;\n</code></pre>\n\n<p>The tests strings I used for this function, and the results are:</p>\n\n<ul>\n<li>\"helloWorld\" -> \"hello World\"</li>\n<li>\"HelloWorld\" -> \"Hello World\"</li>\n<li>\"HelloABCWorld\" -> \"Hello ABC World\"</li>\n<li>\"HelloWorldABC\" -> \"Hello World ABC\"</li>\n<li>\"ABCHelloWorld\" -> \"ABC Hello World\"</li>\n<li>\"ABC HELLO WORLD\" -> \"ABC HELLO WORLD\"</li>\n<li>\"ABCHELLOWORLD\" -> \"ABCHELLOWORLD\"</li>\n<li>\"A\" -> \"A\"</li>\n</ul>\n" }, { "answer_id": 19052099, "author": "Rob Hardy", "author_id": 1733091, "author_profile": "https://Stackoverflow.com/users/1733091", "pm_score": 5, "selected": false, "text": "<p>I know this is an old one, but this is an extension I use when I need to do this:</p>\n\n<pre><code>public static class Extensions\n{\n public static string ToSentence( this string Input )\n {\n return new string(Input.SelectMany((c, i) =&gt; i &gt; 0 &amp;&amp; char.IsUpper(c) ? new[] { ' ', c } : new[] { c }).ToArray());\n }\n}\n</code></pre>\n\n<p>This will allow you to use <code>MyCasedString.ToSentence()</code></p>\n" }, { "answer_id": 19361158, "author": "Brad Irby", "author_id": 188138, "author_profile": "https://Stackoverflow.com/users/188138", "pm_score": 1, "selected": false, "text": "<p>I took Kevin Strikers excellent solution and converted to VB. Since i'm locked into .NET 3.5, i also had to write IsNullOrWhiteSpace. This passes all of his tests.</p>\n\n<pre><code>&lt;Extension()&gt;\nPublic Function IsNullOrWhiteSpace(value As String) As Boolean\n If value Is Nothing Then\n Return True\n End If\n For i As Integer = 0 To value.Length - 1\n If Not Char.IsWhiteSpace(value(i)) Then\n Return False\n End If\n Next\n Return True\nEnd Function\n\n&lt;Extension()&gt;\nPublic Function UnPascalCase(text As String) As String\n If text.IsNullOrWhiteSpace Then\n Return String.Empty\n End If\n\n Dim newText = New StringBuilder()\n newText.Append(text(0))\n For i As Integer = 1 To text.Length - 1\n Dim currentUpper = Char.IsUpper(text(i))\n Dim prevUpper = Char.IsUpper(text(i - 1))\n Dim nextUpper = If(text.Length &gt; i + 1, Char.IsUpper(text(i + 1)) Or Char.IsWhiteSpace(text(i + 1)), prevUpper)\n Dim spaceExists = Char.IsWhiteSpace(text(i - 1))\n If (currentUpper And Not spaceExists And (Not nextUpper Or Not prevUpper)) Then\n newText.Append(\" \")\n End If\n newText.Append(text(i))\n Next\n Return newText.ToString()\nEnd Function\n</code></pre>\n" }, { "answer_id": 24089054, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 0, "selected": false, "text": "<p>A <strong>C#</strong> solution for an input string that consists only of ASCII characters. The <strong>regex</strong> incorporates <strong>negative lookbehind</strong> to ignore a capital (upper case) letter that appears at the beginning of the string. Uses <a href=\"http://msdn.microsoft.com/en-us/library/xwewhkd1%28v=vs.110%29.aspx\" rel=\"nofollow\">Regex.Replace()</a> to return the desired string.</p>\n\n<p>Also see <a href=\"http://regex101.com/r/gS6kD5\" rel=\"nofollow\">regex101.com demo</a>.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Text.RegularExpressions;\n\npublic class RegexExample\n{\n public static void Main()\n {\n var text = \"ThisStringHasNoSpacesButItDoesHaveCapitals\";\n\n // Use negative lookbehind to match all capital letters\n // that do not appear at the beginning of the string.\n var pattern = \"(?&lt;!^)([A-Z])\";\n\n var rgx = new Regex(pattern);\n var result = rgx.Replace(text, \" $1\");\n Console.WriteLine(\"Input: [{0}]\\nOutput: [{1}]\", text, result);\n }\n}\n</code></pre>\n\n<p><strong>Expected Output:</strong></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Input: [ThisStringHasNoSpacesButItDoesHaveCapitals]\nOutput: [This String Has No Spaces But It Does Have Capitals]\n</code></pre>\n\n<hr>\n\n<p><strong>Update:</strong> Here's a variation that will also handle <strong>acronyms</strong> (sequences of upper-case letters).</p>\n\n<p>Also see <a href=\"http://regex101.com/r/yM8mJ2\" rel=\"nofollow\">regex101.com demo</a> and <a href=\"http://ideone.com/uJ1DHP\" rel=\"nofollow\">ideone.com demo</a>.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Text.RegularExpressions;\n\npublic class RegexExample\n{\n public static void Main()\n {\n var text = \"ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ\";\n\n // Use positive lookbehind to locate all upper-case letters\n // that are preceded by a lower-case letter.\n var patternPart1 = \"(?&lt;=[a-z])([A-Z])\";\n\n // Used positive lookbehind and lookahead to locate all\n // upper-case letters that are preceded by an upper-case\n // letter and followed by a lower-case letter.\n var patternPart2 = \"(?&lt;=[A-Z])([A-Z])(?=[a-z])\";\n\n var pattern = patternPart1 + \"|\" + patternPart2;\n var rgx = new Regex(pattern);\n var result = rgx.Replace(text, \" $1$2\");\n\n Console.WriteLine(\"Input: [{0}]\\nOutput: [{1}]\", text, result);\n }\n}\n</code></pre>\n\n<p><strong>Expected Output:</strong></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Input: [ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ]\nOutput: [This String Has No Spaces ASCII But It Does Have Capitals LINQ]\n</code></pre>\n" }, { "answer_id": 24177148, "author": "Jonas Pegerfalk", "author_id": 1918, "author_profile": "https://Stackoverflow.com/users/1918", "pm_score": 1, "selected": false, "text": "<p>The question is a bit old but nowadays there is a nice library on Nuget that does exactly this as well as many other conversions to human readable text.</p>\n\n<p>Check out <a href=\"http://humanizr.net/\" rel=\"nofollow\">Humanizer</a> on <a href=\"https://github.com/MehdiK/Humanizer\" rel=\"nofollow\">GitHub</a> or Nuget.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>\"PascalCaseInputStringIsTurnedIntoSentence\".Humanize() =&gt; \"Pascal case input string is turned into sentence\"\n\"Underscored_input_string_is_turned_into_sentence\".Humanize() =&gt; \"Underscored input string is turned into sentence\"\n\"Underscored_input_String_is_turned_INTO_sentence\".Humanize() =&gt; \"Underscored input String is turned INTO sentence\"\n\n// acronyms are left intact\n\"HTML\".Humanize() =&gt; \"HTML\"\n</code></pre>\n" }, { "answer_id": 27326598, "author": "Serj Sagan", "author_id": 550975, "author_profile": "https://Stackoverflow.com/users/550975", "pm_score": 0, "selected": false, "text": "<p>This one includes acronyms and acronym plurals and is a bit faster than the accepted answer:</p>\n\n<pre><code>public string Sentencify(string value)\n{\n if (string.IsNullOrWhiteSpace(value))\n return string.Empty;\n\n string final = string.Empty;\n for (int i = 0; i &lt; value.Length; i++)\n {\n if (i != 0 &amp;&amp; Char.IsUpper(value[i]))\n {\n if (!Char.IsUpper(value[i - 1]))\n final += \" \";\n else if (i &lt; (value.Length - 1))\n {\n if (!Char.IsUpper(value[i + 1]) &amp;&amp; !((value.Length &gt;= i &amp;&amp; value[i + 1] == 's') ||\n (value.Length &gt;= i + 1 &amp;&amp; value[i + 1] == 'e' &amp;&amp; value[i + 2] == 's')))\n final += \" \";\n }\n }\n\n final += value[i];\n }\n\n return final;\n}\n</code></pre>\n\n<p>Passes these tests:</p>\n\n<pre><code>string test1 = \"RegularOTs\";\nstring test2 = \"ThisStringHasNoSpacesASCIIButItDoesHaveCapitalsLINQ\";\nstring test3 = \"ThisStringHasNoSpacesButItDoesHaveCapitals\";\n</code></pre>\n" }, { "answer_id": 29222001, "author": "CrazyTim", "author_id": 737393, "author_profile": "https://Stackoverflow.com/users/737393", "pm_score": 0, "selected": false, "text": "<p>Here is a more thorough solution that doesn't put spaces in front of words:</p>\n\n<p><strong>Note:</strong> I have used multiple Regexs (not concise but it will also handle acronyms and single letter words)</p>\n\n<pre><code>Dim s As String = \"ThisStringHasNoSpacesButItDoesHaveCapitals\"\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z](?=[A-Z])[a-z]*)\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([A-Z])([A-Z][a-z])\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z][a-z])\", \"$1 $2\")\ns = System.Text.RegularExpressions.Regex.Replace(s, \"([a-z])([A-Z][a-z])\", \"$1 $2\") // repeat a second time\n</code></pre>\n\n<p><strong>In</strong>: </p>\n\n<pre><code>\"ThisStringHasNoSpacesButItDoesHaveCapitals\"\n\"IAmNotAGoat\"\n\"LOLThatsHilarious!\"\n\"ThisIsASMSMessage\"\n</code></pre>\n\n<p><strong>Out</strong>:</p>\n\n<pre><code>\"This String Has No Spaces But It Does Have Capitals\"\n\"I Am Not A Goat\"\n\"LOL Thats Hilarious!\"\n\"This Is ASMS Message\" // (Difficult to handle single letter words when they are next to acronyms.)\n</code></pre>\n" }, { "answer_id": 34857039, "author": "st3_121", "author_id": 3259100, "author_profile": "https://Stackoverflow.com/users/3259100", "pm_score": 0, "selected": false, "text": "<p>All the previous responses looked too over complicated.</p>\n\n<p>I had string that had a mixture of capitals and _ so used, string.Replace() to make the _, \" \" and used the following to add a space at the capital letters.</p>\n\n<pre><code>for (int i = 0; i &lt; result.Length; i++)\n{\n if (char.IsUpper(result[i]))\n {\n counter++;\n if (i &gt; 1) //stops from adding a space at if string starts with Capital\n {\n result = result.Insert(i, \" \");\n i++; //Required** otherwise stuck in infinite \n //add space loop over a single capital letter.\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 35486198, "author": "Matthias Thomann", "author_id": 2987659, "author_profile": "https://Stackoverflow.com/users/2987659", "pm_score": 3, "selected": false, "text": "<p>This Regex places a space character in front of every capital letter:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nconst string myStringWithoutSpaces = \"ThisIsAStringWithoutSpaces\";\nvar myStringWithSpaces = Regex.Replace(myStringWithoutSpaces, \"([A-Z])([a-z]*)\", \" $1$2\");\n</code></pre>\n\n<p>Mind the space in front if \"$1$2\", this is what will get it done.</p>\n\n<p>This is the outcome:</p>\n\n<pre><code>\"This Is A String Without Spaces\"\n</code></pre>\n" }, { "answer_id": 36755271, "author": "johnny 5", "author_id": 1938988, "author_profile": "https://Stackoverflow.com/users/1938988", "pm_score": 2, "selected": false, "text": "<p>Inspired from @MartinBrown, \nTwo Lines of Simple Regex, which will resolve your name, including Acyronyms anywhere in the string.</p>\n\n<pre><code>public string ResolveName(string name)\n{\n var tmpDisplay = Regex.Replace(name, \"([^A-Z ])([A-Z])\", \"$1 $2\");\n return Regex.Replace(tmpDisplay, \"([A-Z]+)([A-Z][^A-Z$])\", \"$1 $2\").Trim();\n}\n</code></pre>\n" }, { "answer_id": 42671598, "author": "João Sequeira", "author_id": 5218746, "author_profile": "https://Stackoverflow.com/users/5218746", "pm_score": 0, "selected": false, "text": "<p>Inspired by Binary Worrier answer I took a swing at this.</p>\n\n<p>Here's the result:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// String Extension Method\n/// Adds white space to strings based on Upper Case Letters\n/// &lt;/summary&gt;\n/// &lt;example&gt;\n/// strIn =&gt; \"HateJPMorgan\"\n/// preserveAcronyms false =&gt; \"Hate JP Morgan\"\n/// preserveAcronyms true =&gt; \"Hate JPMorgan\"\n/// &lt;/example&gt;\n/// &lt;param name=\"strIn\"&gt;to evaluate&lt;/param&gt;\n/// &lt;param name=\"preserveAcronyms\" &gt;determines saving acronyms (Optional =&gt; false) &lt;/param&gt;\npublic static string AddSpaces(this string strIn, bool preserveAcronyms = false)\n{\n if (string.IsNullOrWhiteSpace(strIn))\n return String.Empty;\n\n var stringBuilder = new StringBuilder(strIn.Length * 2)\n .Append(strIn[0]);\n\n int i;\n\n for (i = 1; i &lt; strIn.Length - 1; i++)\n {\n var c = strIn[i];\n\n if (Char.IsUpper(c) &amp;&amp; (Char.IsLower(strIn[i - 1]) || (preserveAcronyms &amp;&amp; Char.IsLower(strIn[i + 1]))))\n stringBuilder.Append(' ');\n\n stringBuilder.Append(c);\n }\n\n return stringBuilder.Append(strIn[i]).ToString();\n}\n</code></pre>\n\n<p>Did test using stopwatch running 10000000 iterations and various string lengths and combinations.</p>\n\n<p>On average 50% (maybe a bit more) faster than Binary Worrier answer.</p>\n" }, { "answer_id": 43238888, "author": "Dave Cousineau", "author_id": 621316, "author_profile": "https://Stackoverflow.com/users/621316", "pm_score": 1, "selected": false, "text": "<p>Seems like a good opportunity for <code>Aggregate</code>. This is designed to be readable, not necessarily especially fast.</p>\n\n<pre><code>someString\n.Aggregate(\n new StringBuilder(),\n (str, ch) =&gt; {\n if (char.IsUpper(ch) &amp;&amp; str.Length &gt; 0)\n str.Append(\" \");\n str.Append(ch);\n return str;\n }\n).ToString();\n</code></pre>\n" }, { "answer_id": 44899859, "author": "Hareendra Donapati", "author_id": 6690847, "author_profile": "https://Stackoverflow.com/users/6690847", "pm_score": 0, "selected": false, "text": "<pre><code> private string GetProperName(string Header)\n {\n if (Header.ToCharArray().Where(c =&gt; Char.IsUpper(c)).Count() == 1)\n {\n return Header;\n }\n else\n {\n string ReturnHeader = Header[0].ToString();\n for(int i=1; i&lt;Header.Length;i++)\n {\n if (char.IsLower(Header[i-1]) &amp;&amp; char.IsUpper(Header[i]))\n {\n ReturnHeader += \" \" + Header[i].ToString();\n }\n else\n {\n ReturnHeader += Header[i].ToString();\n }\n }\n\n return ReturnHeader;\n }\n\n return Header;\n }\n</code></pre>\n" }, { "answer_id": 50480513, "author": "Artur A", "author_id": 304371, "author_profile": "https://Stackoverflow.com/users/304371", "pm_score": 0, "selected": false, "text": "<p>An implementation with <code>fold</code>, also known as <code>Aggregate</code>:</p>\n\n<pre><code> public static string SpaceCapitals(this string arg) =&gt;\n new string(arg.Aggregate(new List&lt;Char&gt;(),\n (accum, x) =&gt; \n {\n if (Char.IsUpper(x) &amp;&amp;\n accum.Any() &amp;&amp;\n // prevent double spacing\n accum.Last() != ' ' &amp;&amp;\n // prevent spacing acronyms (ASCII, SCSI)\n !Char.IsUpper(accum.Last()))\n {\n accum.Add(' ');\n }\n\n accum.Add(x);\n\n return accum;\n }).ToArray());\n</code></pre>\n\n<p>In addition to the request, this implementation correctly saves leading, inner, trailing spaces and acronyms, for example, </p>\n\n<pre><code>\" SpacedWord \" =&gt; \" Spaced Word \", \n\n\"Inner Space\" =&gt; \"Inner Space\", \n\n\"SomeACRONYM\" =&gt; \"Some ACRONYM\".\n</code></pre>\n" }, { "answer_id": 55565072, "author": "Prince Owusu", "author_id": 5265873, "author_profile": "https://Stackoverflow.com/users/5265873", "pm_score": 0, "selected": false, "text": "<p>A simple way to add spaces after lower case letters, upper case letters or digits. </p>\n\n<pre><code> string AddSpacesToSentence(string value, bool spaceLowerChar = true, bool spaceDigitChar = true, bool spaceSymbolChar = false)\n {\n var result = \"\";\n\n for (int i = 0; i &lt; value.Length; i++)\n {\n char currentChar = value[i];\n char nextChar = value[i &lt; value.Length - 1 ? i + 1 : value.Length - 1];\n\n if (spaceLowerChar &amp;&amp; char.IsLower(currentChar) &amp;&amp; !char.IsLower(nextChar))\n {\n result += value[i] + \" \";\n }\n else if (spaceDigitChar &amp;&amp; char.IsDigit(currentChar) &amp;&amp; !char.IsDigit(nextChar))\n {\n result += value[i] + \" \";\n }\n else if(spaceSymbolChar &amp;&amp; char.IsSymbol(currentChar) &amp;&amp; !char.IsSymbol(nextChar))\n {\n result += value[i];\n }\n else\n {\n result += value[i];\n }\n }\n\n return result;\n }\n</code></pre>\n" }, { "answer_id": 63618605, "author": "Adam Short", "author_id": 9993088, "author_profile": "https://Stackoverflow.com/users/9993088", "pm_score": 1, "selected": false, "text": "<p>Found a lot of these answers to be rather obtuse but I haven't fully tested my solution, but it works for what I need, should handle acronyms, and is much more compact/readable than the others IMO:</p>\n<pre><code>private string CamelCaseToSpaces(string s)\n {\n if (string.IsNullOrEmpty(s)) return string.Empty;\n\n StringBuilder stringBuilder = new StringBuilder();\n for (int i = 0; i &lt; s.Length; i++)\n {\n stringBuilder.Append(s[i]);\n\n int nextChar = i + 1;\n if (nextChar &lt; s.Length &amp;&amp; char.IsUpper(s[nextChar]) &amp;&amp; !char.IsUpper(s[i]))\n {\n stringBuilder.Append(&quot; &quot;);\n }\n }\n\n return stringBuilder.ToString();\n }\n</code></pre>\n" }, { "answer_id": 69785447, "author": "hossein sedighian", "author_id": 10143546, "author_profile": "https://Stackoverflow.com/users/10143546", "pm_score": 0, "selected": false, "text": "<p>I wanna to use this one</p>\n<pre><code>string InsertSpace(string text ) {\n return string.Join(&quot;&quot; , text.Select(ch =&gt; char.IsUpper(ch) ? &quot; &quot; : &quot;&quot; + ch)) ;\n} \n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals" Here is my attempt with a RegEx ``` System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0") ```
The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse) This function ``` string AddSpacesToSentence(string text, bool preserveAcronyms) { if (string.IsNullOrWhiteSpace(text)) return string.Empty; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (char.IsUpper(text[i])) if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) || (preserveAcronyms && char.IsUpper(text[i - 1]) && i < text.Length - 1 && !char.IsUpper(text[i + 1]))) newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } ``` Will do it 100,000 times in 2,968,750 ticks, the regex will take 25,000,000 ticks (and thats with the regex compiled). It's better, for a given value of better (i.e. faster) however it's more code to maintain. "Better" is often compromise of competing requirements. Hope this helps :) **Update** It's a good long while since I looked at this, and I just realised the timings haven't been updated since the code changed (it only changed a little). On a string with 'Abbbbbbbbb' repeated 100 times (i.e. 1,000 bytes), a run of 100,000 conversions takes the hand coded function 4,517,177 ticks, and the Regex below takes 59,435,719 making the Hand coded function run in 7.6% of the time it takes the Regex. **Update 2** Will it take Acronyms into account? It will now! The logic of the if statment is fairly obscure, as you can see expanding it to this ... ``` if (char.IsUpper(text[i])) if (char.IsUpper(text[i - 1])) if (preserveAcronyms && i < text.Length - 1 && !char.IsUpper(text[i + 1])) newText.Append(' '); else ; else if (text[i - 1] != ' ') newText.Append(' '); ``` ... doesn't help at all! Here's the original *simple* method that doesn't worry about Acronyms ``` string AddSpacesToSentence(string text) { if (string.IsNullOrWhiteSpace(text)) return ""; StringBuilder newText = new StringBuilder(text.Length * 2); newText.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (char.IsUpper(text[i]) && text[i - 1] != ' ') newText.Append(' '); newText.Append(text[i]); } return newText.ToString(); } ```
272,635
<p>I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders.</p> <p>It works, but its not specific enough. </p> <p>Hopefully this makes sense...</p> <pre><code>$('div.toggle').hide();//hide all divs that are part of the expand/collapse $('ul.product-info li a').toggle(function(event){ event.preventDefault(); $(this).next('div').slideToggle(200);//find the next div and sliiiide it $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!! },function(event) { // opposite here event.preventDefault(); $(this).next('div').slideToggle(200); $('img.expander').attr('src','img/content/info-open.gif'); }); &lt;ul class="product-info"&gt; &lt;li&gt; &lt;a class="img-link" href="#"&gt;&lt;img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /&gt; &lt;span&gt;How it compares to the other options&lt;/span&gt; &lt;/a&gt; &lt;div class="toggle"&gt;&lt;p&gt;Content viewable when expanded!&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>There are loads of <code>$('img.expander')</code> tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks.</p> <p>EDIT, updated code as per Douglas' solution:</p> <pre><code>$('div.toggle').hide(); $('ul.product-info li a').toggle(function(event){ //$('#faq-copy .answer').hide(); event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-close.gif'); //alert('on'); },function(event) { // same here event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-open.gif'); }); </code></pre>
[ { "answer_id": 272711, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 1, "selected": false, "text": "<p>Have you tried the .siblings() method?</p>\n\n<pre><code>$(this).siblings('img.expander').attr('src','img/content/info-close.gif');\n</code></pre>\n" }, { "answer_id": 272720, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "<p>How about making your click event toggle a CSS class on a parent item (in your case, perhaps the ul.product-info). Then you can use CSS background properties to change the background image for a &lt;span&gt; instead of using a literal &lt;img&gt; and trying to fiddle with the src. You would also be able to accomplish a showing and hiding on your div.toggle's.</p>\n\n<pre><code>ul.product-info.open span.toggler {\n background-image: url( \"open-toggler.png\" );\n}\nul.product-info.closed span.toggler {\n background-image: url( \"closed-toggler.png\" );\n}\n\nul.product-info.open div.toggle {\n display: block;\n}\nul.product-info.closed div.toggle {\n display: hidden;\n}\n</code></pre>\n\n<p>Using jQuery navigation/spidering functions can be slow when the DOM has many items and deep nesting. With CSS, your browser will render and change things more quickly.</p>\n" }, { "answer_id": 272721, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "<pre><code>$(this).contents('img.expander')\n</code></pre>\n\n<p>This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders. It works, but its not specific enough. Hopefully this makes sense... ``` $('div.toggle').hide();//hide all divs that are part of the expand/collapse $('ul.product-info li a').toggle(function(event){ event.preventDefault(); $(this).next('div').slideToggle(200);//find the next div and sliiiide it $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!! },function(event) { // opposite here event.preventDefault(); $(this).next('div').slideToggle(200); $('img.expander').attr('src','img/content/info-open.gif'); }); <ul class="product-info"> <li> <a class="img-link" href="#"><img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /> <span>How it compares to the other options</span> </a> <div class="toggle"><p>Content viewable when expanded!</p></div> </li> </ul> ``` There are loads of `$('img.expander')` tags on the page, but I need to be specific. I've tried the next() functionality ( like I've used to find the next div), but it says that its undefined. How can I locate my specific img.expander tag? Thanks. EDIT, updated code as per Douglas' solution: ``` $('div.toggle').hide(); $('ul.product-info li a').toggle(function(event){ //$('#faq-copy .answer').hide(); event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-close.gif'); //alert('on'); },function(event) { // same here event.preventDefault(); $(this).next('div').slideToggle(200); $(this).contents('img.expander').attr('src','img/content/info-open.gif'); }); ```
``` $(this).contents('img.expander') ``` This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.
272,638
<p>Below is what I'm trying to achieve. The problem is "errors" is not defined. If I remove my match logic, the errors are displayed on the web page. Is there anyway of evaluating the text the error contains?</p> <pre><code>&lt;logic:messagesPresent&gt; &lt;tr&gt; &lt;td class="errorcicon"&gt;&lt;img src="images/icon_caution.gif" width="18" height="18" alt="Caution" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td colspan="4"&gt;&lt;html:errors /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/logic:messagesPresent&gt; &lt;logic:match name="errors" property="text" value="Service Start date is required" &gt; &lt;% pageContext.setAttribute("NOORIGIONALSERVICEDATE", "-1");%&gt; &lt;/logic:match&gt; </code></pre>
[ { "answer_id": 272711, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 1, "selected": false, "text": "<p>Have you tried the .siblings() method?</p>\n\n<pre><code>$(this).siblings('img.expander').attr('src','img/content/info-close.gif');\n</code></pre>\n" }, { "answer_id": 272720, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 2, "selected": false, "text": "<p>How about making your click event toggle a CSS class on a parent item (in your case, perhaps the ul.product-info). Then you can use CSS background properties to change the background image for a &lt;span&gt; instead of using a literal &lt;img&gt; and trying to fiddle with the src. You would also be able to accomplish a showing and hiding on your div.toggle's.</p>\n\n<pre><code>ul.product-info.open span.toggler {\n background-image: url( \"open-toggler.png\" );\n}\nul.product-info.closed span.toggler {\n background-image: url( \"closed-toggler.png\" );\n}\n\nul.product-info.open div.toggle {\n display: block;\n}\nul.product-info.closed div.toggle {\n display: hidden;\n}\n</code></pre>\n\n<p>Using jQuery navigation/spidering functions can be slow when the DOM has many items and deep nesting. With CSS, your browser will render and change things more quickly.</p>\n" }, { "answer_id": 272721, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "<pre><code>$(this).contents('img.expander')\n</code></pre>\n\n<p>This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Below is what I'm trying to achieve. The problem is "errors" is not defined. If I remove my match logic, the errors are displayed on the web page. Is there anyway of evaluating the text the error contains? ``` <logic:messagesPresent> <tr> <td class="errorcicon"><img src="images/icon_caution.gif" width="18" height="18" alt="Caution" /></td> <td></td> <td colspan="4"><html:errors /></td> </tr> </logic:messagesPresent> <logic:match name="errors" property="text" value="Service Start date is required" > <% pageContext.setAttribute("NOORIGIONALSERVICEDATE", "-1");%> </logic:match> ```
``` $(this).contents('img.expander') ``` This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want.
272,644
<p>I have a class called <code>Ship</code> and a class called <code>Lifeboat</code></p> <p>Lifeboat inherits from Ship.</p> <p>Ship contains a method called <code>Validate()</code> which is called before save and it has an abstract method called <code>FurtherValidate()</code> which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have</p> <pre><code>public class Ship public bool Validate() { //validate properties only found on a ship FurtherValidate(); } public abstract bool FurtherValidate(); </code></pre> <p>So <code>Lifeboat</code> has </p> <pre><code>public override bool FurtherValidate() { //validate properties only found on a lifeboat } </code></pre> <p>This means anyone implementing <code>Ship</code> also needs to provide their own validation for their class and it's guaranteed to be called on the save as the base ship. <code>Validate()</code> is called which in turns calls the inherited validate.</p> <p>How can we re work this so we still force inherited classes to implement <code>FurtherValidate()</code> but <code>FurtherValidate()</code> can never be called by the programmer. Currently you can called <code>Lifeboat.FurtherValidate()</code> and I want to somehow prevent this.</p>
[ { "answer_id": 272653, "author": "Stephan Leclercq", "author_id": 34838, "author_profile": "https://Stackoverflow.com/users/34838", "pm_score": 1, "selected": false, "text": "<p>Making it protected instead of public will at least prevent outside objects from calling it. </p>\n" }, { "answer_id": 272654, "author": "alvin", "author_id": 15121, "author_profile": "https://Stackoverflow.com/users/15121", "pm_score": 3, "selected": false, "text": "<pre><code>protected abstract bool FurtherValidate();\n</code></pre>\n\n<p>only Ship and Lifeboat can see it now.</p>\n\n<p>EDIT:\nLifeboat must be able to see it. How should it be able to override <code>FurtherValidate</code> when it can't even see it. I would rename it to <code>ValidateCore</code>, the 'Core' part (to me) implies that it should not be called without a very good reason.</p>\n\n<p>I don't think it's easy to make it abstract but not visible. You need to have some faith in your lifeboat ;)</p>\n" }, { "answer_id": 272656, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<p>You could mark the method as <code>protected</code> so only inheriting classes can access it. This does not prevent inheritors from exposing the method through another public method but that's usually not a major concern.</p>\n" }, { "answer_id": 272663, "author": "Jack Ryan", "author_id": 28882, "author_profile": "https://Stackoverflow.com/users/28882", "pm_score": 2, "selected": false, "text": "<p>The most simple answer would be to make the method protected. This allows the inheritors to call it but does not make it publicly available. However there is nothing to stop the inheriting classes changing the method to public.</p>\n\n<p>I would be more inclined to remove the FurtherValidate method entirely and have any inheriting classes override Validate, calling base.Validate() if they wish. This allows any class that inherits from ship to have a greater degree of control over the validate method.</p>\n" }, { "answer_id": 272678, "author": "D. Rattansingh", "author_id": 31274, "author_profile": "https://Stackoverflow.com/users/31274", "pm_score": -1, "selected": false, "text": "<p>Probably you could try the private modifier</p>\n" }, { "answer_id": 272685, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 3, "selected": false, "text": "<p>Short answer is, you can't hide the derived method from the class that's deriving it. However, you can refactor your code to accomplish what you're trying to achieve:</p>\n\n<pre><code>public class Ship\n{ \n public virtual bool Validate() \n { \n //validate properties only found on a ship\n return true;\n }\n}\npublic class Lifeboat : Ship\n{ \n public override bool Validate() \n { \n base.Validate(); \n // lifeboat specific code\n return true;\n }\n}\n</code></pre>\n" }, { "answer_id": 272688, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>protected is the correct approach here. But in another situation, you may wish to use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx\" rel=\"nofollow noreferrer\">editorbrowsableattribute</a> which will hide the method from intellisense. You can still call it, but it slows down devs from calling something that could blow up the program, and will usually force them to read your giant comment-warnings.</p>\n" }, { "answer_id": 272703, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 3, "selected": true, "text": "<p>The exact scenario you describe isn't possible. You can restrict access to the <code>FurtherValidate</code> method to only derived classes by using the <code>protected</code> access modifier. You could also restrict it to only classes in the same assembly by using the <code>internal</code> modifier, but this would still allow the programmer writing the derived class to call FurtherValidate any time they wish. Using both protected and internal combines the two and really means that is restricted to derived classes or classes defined in the same assembly.</p>\n\n<p>Using the [EditorBrowsable] attribute is an IDE trick that will hide the method from IntelliSense (unless the other programmer has turned on the right options in VS). That will effectively prevent most people from calling it (if they can't see it, it doesn't exist).</p>\n\n<p>You could possibly achieve this using reflection to interrogate who your caller is, but I think the performance costs of doing this would be too high compared to the benefit.</p>\n" }, { "answer_id": 272921, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 1, "selected": false, "text": "<p>I see a code smell here, since Validate isn't part of the functional responsibility of a ship. In other words, I think maybe you're trying to solve a problem using inheritance when maybe that's not the best solution. Try refactoring your validation logic so that you inject your validation in to the class. This will make better sense in terms of a domain object <code>Ship</code>, since ships don't validate themselves, they're validated externally. If you want to enforce that there <em>must</em> be a validator, then you can throw an exception if the property is null.</p>\n\n<pre><code>protected IValidator FurtherValidation { private get; set; }\n\npublic bool Validate()\n{\n//validate properties only found on a ship\n\n if (FurtherValidation == null)\n throw new ValidationIsRequiredException();\n if (!FurtherValidation.IsValid(this))\n // logic for invalid state\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27412/" ]
I have a class called `Ship` and a class called `Lifeboat` Lifeboat inherits from Ship. Ship contains a method called `Validate()` which is called before save and it has an abstract method called `FurtherValidate()` which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have ``` public class Ship public bool Validate() { //validate properties only found on a ship FurtherValidate(); } public abstract bool FurtherValidate(); ``` So `Lifeboat` has ``` public override bool FurtherValidate() { //validate properties only found on a lifeboat } ``` This means anyone implementing `Ship` also needs to provide their own validation for their class and it's guaranteed to be called on the save as the base ship. `Validate()` is called which in turns calls the inherited validate. How can we re work this so we still force inherited classes to implement `FurtherValidate()` but `FurtherValidate()` can never be called by the programmer. Currently you can called `Lifeboat.FurtherValidate()` and I want to somehow prevent this.
The exact scenario you describe isn't possible. You can restrict access to the `FurtherValidate` method to only derived classes by using the `protected` access modifier. You could also restrict it to only classes in the same assembly by using the `internal` modifier, but this would still allow the programmer writing the derived class to call FurtherValidate any time they wish. Using both protected and internal combines the two and really means that is restricted to derived classes or classes defined in the same assembly. Using the [EditorBrowsable] attribute is an IDE trick that will hide the method from IntelliSense (unless the other programmer has turned on the right options in VS). That will effectively prevent most people from calling it (if they can't see it, it doesn't exist). You could possibly achieve this using reflection to interrogate who your caller is, but I think the performance costs of doing this would be too high compared to the benefit.
272,665
<p>First of all, some background.</p> <p>We have an order processing system, where staff enter billing data about orders in an app that stores it in a sql server 2000 database. This database isn't the real billing system: it's just a holding location so that the records can be run into a mainframe system via a nightly batch process. </p> <p>This batch process is a canned third party package provided by an outside vendor. Part of what it's supposed to do is provide a report for any records that were rejected. The reject report is worked manually.</p> <p>Unfortunately, it turns out the third party software doesn't catch all the errors. We have separate processes that pull back the data from the mainframe into another table in the database and load the rejected charges into yet another table. </p> <p>An audit process then runs to make sure everything that was originally entered by the staff can be accounted for somewhere. This audit takes the form of an sql query we run, and it looks something like this:</p> <pre><code>SELECT * FROM [StaffEntry] s with (nolock) LEFT JOIN [MainFrame] m with (nolock) ON m.ItemNumber = s.ItemNumber AND m.Customer=s.Customer AND m.CustomerPO = s.CustomerPO -- purchase order AND m.CustPORev = s.CustPORev -- PO revision number LEFT JOIN [Rejected] r with (nolock) ON r.OrderID = s.OrderID WHERE s.EntryDate BETWEEN @StartDate AND @EndDate AND r.OrderID IS NULL AND m.MainFrameOrderID IS NULL </code></pre> <p>That's heavily modified, of course, but I believe the important parts are represented. The problem is that this query is starting to take too long to run, and I'm trying to figure out how to speed it up.</p> <p>I'm pretty sure the problem is the JOIN from the <code>StaffEntry</code> table to the <code>MainFrame</code> table. Since both hold data for every order since the beginning of time (2003 in this system), they tend to be a little large. The <code>OrderID</code> and <code>EntryDate</code> values used in the <code>StaffEntry</code> table are not preserved when imported to the mainframe, which is why that join is a little more complicated. And finally, since I'm looking for records in the <code>MainFrame</code> table that don't exist, after doing the JOIN we have that ugly <code>IS NULL</code> in the where clause.</p> <p>The <code>StaffEntry</code> table is indexed by EntryDate (clustered) and separately on Customer/PO/rev. <code>MainFrame</code> is indexed by customer and the mainframe charge number (clustered, this is needed for other systems) and separately by customer/PO/Rev. <code>Rejected</code> is not indexed at all, but it's small and testing shows it's not the problem. </p> <p>So, I'm wondering if there is another (hopefully faster) way I can express that relationship?</p>
[ { "answer_id": 272680, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 1, "selected": false, "text": "<p>Before you even start looking at changing your query, you should ensure that all tables have a clustered index that makes sense for both this query and all other vital queries. Having clustered indexes on your tables i vital in sql server to ensure proper performance.</p>\n" }, { "answer_id": 272684, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>This doesn't make sense:</p>\n\n<pre><code>SELECT *\nFROM [StaffEntry] s\nLEFT JOIN [MainFrame] m ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nLEFT JOIN [Rejected] r ON r.OrderID = s.OrderID\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND r.OrderID IS NULL AND s.OrderID IS NULL\n</code></pre>\n\n<p>if <code>s.OrderID IS NULL</code>, then <code>r.OrderID = s.OrderID</code> will never be true, so no rows from <code>[Rejected]</code> will ever be included, thus as given, it is equivalent to:</p>\n\n<pre><code>SELECT *\nFROM [StaffEntry] s\nLEFT JOIN [MainFrame] m ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL\n</code></pre>\n\n<p>Are you sure that code you posted is right?</p>\n" }, { "answer_id": 272690, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": false, "text": "<p>First off, you can get rid of the second LEFT JOIN.</p>\n\n<p>Your WHERE was removing out any matches, anyhow... For instance, if S.OrderID was 1 and there was a R.OrderID with a value of 1, the IS NULL enforcement in the WHERE wouldn't allow it. So it'll only return records where s.OrderID IS NULL, if I'm reading it correctly...</p>\n\n<p>Secondly, if you're dealing with a large amount of data, adding on a NOLOCK table hint typically won't hurt. Assuming you don't mind the possibility of a dirty-read here or there :-P Usually worth the risk, though.</p>\n\n<pre><code>SELECT *\nFROM [StaffEntry] s (nolock)\nLEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL\n</code></pre>\n\n<p>Lastly, there was a part of your question which wasn't too clear for me...</p>\n\n<blockquote>\n <p>\"since I'm looking for\n records in the MainFrame table that\n don't exist, after doing the JOIN we\n have that ugly IS NULL in the where\n clause.\"</p>\n</blockquote>\n\n<p>Ok... But are you trying to limit it to just where those MainFrame table records don't exist? If so, you'll want that expressed in the WHERE as well, right? So something like this...</p>\n\n<pre><code>SELECT *\nFROM [StaffEntry] s (nolock)\nLEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber \n AND m.Customer=s.Customer \n AND m.CustomerPO = s.CustomerPO -- purchase order\n AND m.CustPORev = s.CustPORev -- PO revision number\nWHERE s.EntryDate BETWEEN @StartDate AND @EndDate\n AND s.OrderID IS NULL AND m.ItemNumber IS NULL\n</code></pre>\n\n<p>If that's what you were intending with the original statement, perhaps you can get rid of the s.OrderID IS NULL check?</p>\n" }, { "answer_id": 272714, "author": "Frank V", "author_id": 18196, "author_profile": "https://Stackoverflow.com/users/18196", "pm_score": 1, "selected": false, "text": "<p>In addition to what Kasperjj has suggested (which I do agree should be first), you might consider using temp tables to restrict the amount of data. Now, I know, I know that everyone says to stay away from temp tables. And i <em>Usually</em> do but sometimes, it is worth giving it a try because you can shrink the amount of data to join drastically with this method; this makes the overall query faster. (of course this does depend on how much you can shrink the result sets.) </p>\n\n<p>My final thought is sometimes you will just need to experiment with different methods of pulling together the query. There might be too many variables for anyone here to give a answer.... On the other hand, people here are smart so I could be wrong.</p>\n\n<p>Best of luck!</p>\n\n<p>Regards,\nFrank</p>\n\n<p>PS: I forgot to mention that if you wanted to try this temp table method, you'd also need to experiment with different indexes and primary keys on the temp tables. Depending on the amount of data, indexes and PKs can help.</p>\n" }, { "answer_id": 272741, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "<p>Indexing on all the tables is going to be important. If you can't do much with the indexing on the [MainFrame] columns used in the join, you can also pre-limit the rows to be searched in [MainFrame] (and [Rejected], although that already looks like it has a PK)by specifying a date range - if the window of date should be roughly similar. This can cut down on the right hand side on that join.</p>\n\n<p>I would also look at the execution plan and also do a simple black box evaluation of which of your <code>JOIN</code>s is really the most expensive - <code>m</code> or <code>r</code>, by benchmarking the query with only one or the other. I would suspect it is <code>m</code> because of the multiple columns and missing useful indexes.</p>\n\n<p>You could use m.EntryDate within a few days or months of your range. But if you already have indexes on Mainframe, the question is why aren't they being used, or if they are being used, why is the performance so slow.</p>\n" }, { "answer_id": 272866, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p><strong>Update:</strong><br>\nIn case it wasn't already obvious, I made a mistake in the code for the original question. That's now fixed, but unfortunately it means some of the better responses here are actually going the completely wrong direction.</p>\n\n<p>I also have some statistics updates: I can make the query run nice and quick by severely limiting the data range used with <code>StaffEntry.EntryDate</code>. Unfortunately, I'm only able to do that because after running it the long way once I then know exactly which dates I care about. I don't normally know that in advance. </p>\n\n<p>Tthe execution plan from the original run showed 78% cost for a clustered index scan on the <code>StaffEntry</code> table, and 11% cost on an index seek for the <code>MainFrame</code> table, and then 0% cost on the join itself. Running it using the narrow date range, that changes to 1% for an index seek of <code>StaffEntry</code>, 1% for an index seek of 'MainFrame', and 93% for a table scan of <code>Rejected</code>. These are 'actual' plans, not estimated.</p>\n" }, { "answer_id": 273972, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 1, "selected": false, "text": "<p>try changing \nLEFT JOIN [Rejected] r with (nolock) ON r.OrderID = s.OrderID\ninto the RIGHT MERGE JOIN:</p>\n\n<pre><code>SELECT ...\nFROM [Rejected] r\n RIGHT MERGE JOIN [StaffEntry] s with (nolock) ON r.OrderID = s.OrderID\n LEFT JOIN [MainFrame] m with (nolock) ON....\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
First of all, some background. We have an order processing system, where staff enter billing data about orders in an app that stores it in a sql server 2000 database. This database isn't the real billing system: it's just a holding location so that the records can be run into a mainframe system via a nightly batch process. This batch process is a canned third party package provided by an outside vendor. Part of what it's supposed to do is provide a report for any records that were rejected. The reject report is worked manually. Unfortunately, it turns out the third party software doesn't catch all the errors. We have separate processes that pull back the data from the mainframe into another table in the database and load the rejected charges into yet another table. An audit process then runs to make sure everything that was originally entered by the staff can be accounted for somewhere. This audit takes the form of an sql query we run, and it looks something like this: ``` SELECT * FROM [StaffEntry] s with (nolock) LEFT JOIN [MainFrame] m with (nolock) ON m.ItemNumber = s.ItemNumber AND m.Customer=s.Customer AND m.CustomerPO = s.CustomerPO -- purchase order AND m.CustPORev = s.CustPORev -- PO revision number LEFT JOIN [Rejected] r with (nolock) ON r.OrderID = s.OrderID WHERE s.EntryDate BETWEEN @StartDate AND @EndDate AND r.OrderID IS NULL AND m.MainFrameOrderID IS NULL ``` That's heavily modified, of course, but I believe the important parts are represented. The problem is that this query is starting to take too long to run, and I'm trying to figure out how to speed it up. I'm pretty sure the problem is the JOIN from the `StaffEntry` table to the `MainFrame` table. Since both hold data for every order since the beginning of time (2003 in this system), they tend to be a little large. The `OrderID` and `EntryDate` values used in the `StaffEntry` table are not preserved when imported to the mainframe, which is why that join is a little more complicated. And finally, since I'm looking for records in the `MainFrame` table that don't exist, after doing the JOIN we have that ugly `IS NULL` in the where clause. The `StaffEntry` table is indexed by EntryDate (clustered) and separately on Customer/PO/rev. `MainFrame` is indexed by customer and the mainframe charge number (clustered, this is needed for other systems) and separately by customer/PO/Rev. `Rejected` is not indexed at all, but it's small and testing shows it's not the problem. So, I'm wondering if there is another (hopefully faster) way I can express that relationship?
First off, you can get rid of the second LEFT JOIN. Your WHERE was removing out any matches, anyhow... For instance, if S.OrderID was 1 and there was a R.OrderID with a value of 1, the IS NULL enforcement in the WHERE wouldn't allow it. So it'll only return records where s.OrderID IS NULL, if I'm reading it correctly... Secondly, if you're dealing with a large amount of data, adding on a NOLOCK table hint typically won't hurt. Assuming you don't mind the possibility of a dirty-read here or there :-P Usually worth the risk, though. ``` SELECT * FROM [StaffEntry] s (nolock) LEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber AND m.Customer=s.Customer AND m.CustomerPO = s.CustomerPO -- purchase order AND m.CustPORev = s.CustPORev -- PO revision number WHERE s.EntryDate BETWEEN @StartDate AND @EndDate AND s.OrderID IS NULL ``` Lastly, there was a part of your question which wasn't too clear for me... > > "since I'm looking for > records in the MainFrame table that > don't exist, after doing the JOIN we > have that ugly IS NULL in the where > clause." > > > Ok... But are you trying to limit it to just where those MainFrame table records don't exist? If so, you'll want that expressed in the WHERE as well, right? So something like this... ``` SELECT * FROM [StaffEntry] s (nolock) LEFT JOIN [MainFrame] m (nolock) ON m.ItemNumber = s.ItemNumber AND m.Customer=s.Customer AND m.CustomerPO = s.CustomerPO -- purchase order AND m.CustPORev = s.CustPORev -- PO revision number WHERE s.EntryDate BETWEEN @StartDate AND @EndDate AND s.OrderID IS NULL AND m.ItemNumber IS NULL ``` If that's what you were intending with the original statement, perhaps you can get rid of the s.OrderID IS NULL check?
272,674
<p>I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table.</p> <p>Here's some pseudocode of what I'm working on:</p> <pre><code>class MyClass { private Map&lt;Integer, Integer&gt; cache = new HashMap&lt;Integer, Integer&gt;(); public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } </code></pre> <p>What happens is that there are some values of <code>n</code> for which <code>myFunc()</code> will be called lots of times, but many other values of <code>n</code> which will only be computed once. So the cache could fill up with millions of values that are never needed again. I'd like to have a way for the cache to automatically remove elements that are not frequently retrieved.</p> <p>This feels like a problem that must be solved already, but I'm not sure what the data structure is that I would use to do it efficiently. Can anyone point me in the right direction?</p> <hr> <p><strong>Update</strong> I knew this had to be an already-solved problem. It's called an LRU Cache and is easy to make by extending the LinkedHashMap class. Here is the code that incorporates the solution:</p> <pre><code>class MyClass { private final static int SIZE_LIMIT = 1000; private Map&lt;Integer, Integer&gt; cache = new LinkedHashMap&lt;Integer, Integer&gt;(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry&lt;Integer, Integer&gt; eldest) { return size() &gt; SIZE_LIMIT; } }; public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } </code></pre>
[ { "answer_id": 272675, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 0, "selected": false, "text": "<p>Take a look at <strong>WeakHashMap</strong></p>\n" }, { "answer_id": 272710, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 1, "selected": false, "text": "<p>WeakHashMap will probably not do what you expect it to... read the documentation carefully and ensure that you know exactly what you from weak and strong references.</p>\n\n<p>I would recommend you have a look at java.util.LinkedHashMap and use its removeEldestEntry method to maintain your cache. If your math is very resource intensive, you might want to move entries to the front whenever they are used to ensure that only unused entries fall to the end of the set.</p>\n" }, { "answer_id": 272727, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 2, "selected": false, "text": "<p>Googling \"LRU map\" and \"I'm feeling lucky\" gives you this:</p>\n\n<p><a href=\"http://commons.apache.org/proper/commons-collections//javadocs/api-release/org/apache/commons/collections4/map/LRUMap.html\" rel=\"nofollow noreferrer\">http://commons.apache.org/proper/commons-collections//javadocs/api-release/org/apache/commons/collections4/map/LRUMap.html</a></p>\n\n<blockquote>\n <p>A Map implementation with a fixed\n maximum size which removes the least\n recently used entry if an entry is\n added when full.</p>\n</blockquote>\n\n<p>Sounds pretty much spot on :)</p>\n" }, { "answer_id": 272729, "author": "ReneS", "author_id": 33229, "author_profile": "https://Stackoverflow.com/users/33229", "pm_score": 5, "selected": true, "text": "<p>You are looking for an <code>LRUList</code>/<code>Map</code>. Check out <code>LinkedHashMap</code>:</p>\n\n<p>The <code>removeEldestEntry(Map.Entry)</code> method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.</p>\n" }, { "answer_id": 272749, "author": "albertb", "author_id": 26715, "author_profile": "https://Stackoverflow.com/users/26715", "pm_score": 0, "selected": false, "text": "<p>You probably want to implement a Least-Recently Used policy for your map. There's a simple way to do it on top of a LinkedHashMap:</p>\n\n<p><a href=\"http://www.roseindia.net/java/example/java/util/LRUCacheExample.shtml\" rel=\"nofollow noreferrer\">http://www.roseindia.net/java/example/java/util/LRUCacheExample.shtml</a></p>\n" }, { "answer_id": 272804, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.usenix.org/publications/library/proceedings/fast03/tech/megiddo.html\" rel=\"nofollow noreferrer\">Adaptive Replacement Cache</a> policy is designed to keep one-time requests from polluting your cache. This may be fancier than you're looking for, but it does directly address your \"filling up with values that are never needed again\".</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table. Here's some pseudocode of what I'm working on: ``` class MyClass { private Map<Integer, Integer> cache = new HashMap<Integer, Integer>(); public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } ``` What happens is that there are some values of `n` for which `myFunc()` will be called lots of times, but many other values of `n` which will only be computed once. So the cache could fill up with millions of values that are never needed again. I'd like to have a way for the cache to automatically remove elements that are not frequently retrieved. This feels like a problem that must be solved already, but I'm not sure what the data structure is that I would use to do it efficiently. Can anyone point me in the right direction? --- **Update** I knew this had to be an already-solved problem. It's called an LRU Cache and is easy to make by extending the LinkedHashMap class. Here is the code that incorporates the solution: ``` class MyClass { private final static int SIZE_LIMIT = 1000; private Map<Integer, Integer> cache = new LinkedHashMap<Integer, Integer>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > SIZE_LIMIT; } }; public int myFunc(int n) { if(cache.containsKey(n)) return cache.get(n); int next = . . . ; //some complicated math. guaranteed next != n. int ret = 1 + myFunc(next); cache.put(n, ret); return ret; } } ```
You are looking for an `LRUList`/`Map`. Check out `LinkedHashMap`: The `removeEldestEntry(Map.Entry)` method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
272,694
<p>I've got a strange problem with indexing PDF files in SQL Server 2005, and hope someone can help. My database has a table called MediaFile with the following fields - MediaFileId int identity pk, FileContent image, and FileExtension varchar(5). I've got my web application storing file contents in this table with no problems, and am able to use full-text searching on doc, xls, etc with no problems - the only file extension not working is PDF. When performing full-text searches on this table for words which I know exist inside of PDF files saved in the table, these files are not returned in the search results.</p> <p>The OS is Windows Server 2003 SP2, and I've installed <a href="http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611" rel="noreferrer">Adobe iFilter 6.0</a>. Following the instructions on <a href="http://weblogs.asp.net/wallym/archive/2005/02/28/382060.aspx" rel="noreferrer">this blog entry</a>, I executed the following commands:</p> <pre><code>exec sp_fulltext_service 'load_os_resources', 1; exec sp_fulltext_service 'verify_signature', 0; </code></pre> <p>After this, I restarted the SQL Server, and verified that the iFilter for the PDF extensions is installed correctly by executing the following command:</p> <pre><code>select document_type, path from sys.fulltext_document_types where document_type = '.pdf' </code></pre> <p>This returns the following information, which looks correct:</p> <blockquote> <p>document_type: .pdf<br/> path: C:\Program Files\Adobe\PDF IFilter 6.0\PDFFILT.dll</p> </blockquote> <p>Then I (re)created the index on the MediaFile table, selecting FileContent as the column to index and the FileExtension as its type. The wizard creates the index and completes successfully. To test, I'm performing a search like this:</p> <pre><code>SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(*, '"house"'); </code></pre> <p>This returns DOC files which contain this term, but not any PDF files, although I know that there are definitely PDF files in the table which contain the word <em>house</em>.</p> <p>Incidentally, I got this working once for a few minutes, where the search above returned the correct PDF files, but then it just stopped working again for no apparent reason.</p> <p>Any ideas as to what could be stopping SQL Server 2005 from indexing PDF's, even though Adobe iFilter is installed and appears to be loaded?</p>
[ { "answer_id": 282339, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've just struggled with it for an hour, but finally got it working. I did everything you did, so just try to simplify the query (I replaced <code>*</code> with field name and removed double quotes on term):</p>\n\n<pre><code>SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(FileContent, 'house')\n</code></pre>\n\n<p>Also when you create full text index make sure you specify the language. And the last thing is maybe you can try to change the field type from <code>Image</code> to <code>varbinary(MAX)</code>.</p>\n" }, { "answer_id": 285595, "author": "Mun", "author_id": 775, "author_profile": "https://Stackoverflow.com/users/775", "pm_score": 4, "selected": true, "text": "<p>Thanks Ivan. Managed to eventually get this working by starting everything from scratch. It seems like the order in which things are done makes a big difference, and the advice given on the linked blog to to turn off the 'load_os_resources' setting after loading the iFilter probably isn't the best option, as this will cause the iFilter to not be loaded when the SQL Server is restarted.</p>\n\n<p>If I recall correctly, the sequence of steps that eventually worked for me was as follows:</p>\n\n<ol>\n<li>Ensure that the table does not have an index already (and if so, delete it)</li>\n<li>Install Adobe iFilter</li>\n<li>Execute the command exec sp_fulltext_service 'load_os_resources', 1;</li>\n<li>Execute the command exec sp_fulltext_service 'verify_signature', 0;</li>\n<li>Restart SQL Server</li>\n<li>Verify PDF iFilter is installed</li>\n<li>Create full-text index on table</li>\n<li>Do full re-index</li>\n</ol>\n\n<p>Although this did the trick, I'm quite sure I performed these steps a few times before it eventually started working properly.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/775/" ]
I've got a strange problem with indexing PDF files in SQL Server 2005, and hope someone can help. My database has a table called MediaFile with the following fields - MediaFileId int identity pk, FileContent image, and FileExtension varchar(5). I've got my web application storing file contents in this table with no problems, and am able to use full-text searching on doc, xls, etc with no problems - the only file extension not working is PDF. When performing full-text searches on this table for words which I know exist inside of PDF files saved in the table, these files are not returned in the search results. The OS is Windows Server 2003 SP2, and I've installed [Adobe iFilter 6.0](http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611). Following the instructions on [this blog entry](http://weblogs.asp.net/wallym/archive/2005/02/28/382060.aspx), I executed the following commands: ``` exec sp_fulltext_service 'load_os_resources', 1; exec sp_fulltext_service 'verify_signature', 0; ``` After this, I restarted the SQL Server, and verified that the iFilter for the PDF extensions is installed correctly by executing the following command: ``` select document_type, path from sys.fulltext_document_types where document_type = '.pdf' ``` This returns the following information, which looks correct: > > document\_type: .pdf > > path: C:\Program Files\Adobe\PDF IFilter 6.0\PDFFILT.dll > > > Then I (re)created the index on the MediaFile table, selecting FileContent as the column to index and the FileExtension as its type. The wizard creates the index and completes successfully. To test, I'm performing a search like this: ``` SELECT MediaFileId, FileExtension FROM MediaFile WHERE CONTAINS(*, '"house"'); ``` This returns DOC files which contain this term, but not any PDF files, although I know that there are definitely PDF files in the table which contain the word *house*. Incidentally, I got this working once for a few minutes, where the search above returned the correct PDF files, but then it just stopped working again for no apparent reason. Any ideas as to what could be stopping SQL Server 2005 from indexing PDF's, even though Adobe iFilter is installed and appears to be loaded?
Thanks Ivan. Managed to eventually get this working by starting everything from scratch. It seems like the order in which things are done makes a big difference, and the advice given on the linked blog to to turn off the 'load\_os\_resources' setting after loading the iFilter probably isn't the best option, as this will cause the iFilter to not be loaded when the SQL Server is restarted. If I recall correctly, the sequence of steps that eventually worked for me was as follows: 1. Ensure that the table does not have an index already (and if so, delete it) 2. Install Adobe iFilter 3. Execute the command exec sp\_fulltext\_service 'load\_os\_resources', 1; 4. Execute the command exec sp\_fulltext\_service 'verify\_signature', 0; 5. Restart SQL Server 6. Verify PDF iFilter is installed 7. Create full-text index on table 8. Do full re-index Although this did the trick, I'm quite sure I performed these steps a few times before it eventually started working properly.
272,726
<p>I have a Stored Procedure that is constantly failing with the error message "Timeout expired," on a specific user.</p> <p>All other users are able to invoke the sp just fine, and even I am able to invoke the sp normally using the Query Analyzer--it finishes in just 10 seconds. However with the user in question, the logs show that the ASP always hangs for about 5 minutes and then aborts with a timeout.</p> <p>I invoke from the ASP page like so "<code>EXEC SP_TV_GET_CLOSED_BANKS_BY_USERS '006111'</code>"</p> <p>Anybody know how to diagnose the problem? I have already tried looking at deadlocks in the DB, but didn't find any.</p> <p>Thanks,</p>
[ { "answer_id": 273172, "author": "Chris Gillum", "author_id": 2069, "author_profile": "https://Stackoverflow.com/users/2069", "pm_score": 0, "selected": false, "text": "<p>I think to answer your question, we may need a bit more information.</p>\n\n<p>For example, are you using Active directory to authenticate your users? Have you used the SQL profiler to investigate? It sounds like it could be an auth issue where SQL Server is having problems authenticating this particular user.</p>\n" }, { "answer_id": 273195, "author": "dswatik", "author_id": 22093, "author_profile": "https://Stackoverflow.com/users/22093", "pm_score": 0, "selected": false, "text": "<p>Sounds to me like a dead lock issue..</p>\n\n<p>Also make sure this user has execute rights and read rights in SQL Server</p>\n\n<p>But if at the time info is being written as its trying to be read you will dead lock, as the transaction has not yet been committed.</p>\n\n<p>Jeff did a great post about his experience with that and stackoverflow.\n<a href=\"http://www.codinghorror.com/blog/archives/001166.html\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/archives/001166.html</a></p>\n" }, { "answer_id": 274352, "author": "Traveling Tech Guy", "author_id": 19856, "author_profile": "https://Stackoverflow.com/users/19856", "pm_score": 0, "selected": false, "text": "<p>Couple of things to check:</p>\n\n<ol>\n<li>Does this happen only on that specific user's machine? Can he try it from another\nmachine? - it might be a client configuration problem.</li>\n<li>Can you capture the actual string that this specific user runs and run it from an ASP page? It might be that user executes the SP in a way that generates either a loop or a massive load of data.</li>\n<li>Finally, if you're using an intra-organization application, it might be that your particular user's permissions are different than the others. You can compare them at the Active Directory level.</li>\n</ol>\n\n<p>Now, I can recommend a commercial software that will definitely solve your issue. It records end-to-end transactions, and analyzes particular failures. But I do not want to advertise in this forum. If you'd like, drop me a note and I'll explain more.</p>\n" }, { "answer_id": 274673, "author": "Ghazaly", "author_id": 35410, "author_profile": "https://Stackoverflow.com/users/35410", "pm_score": 0, "selected": false, "text": "<p>Well, I could suggest that you use SQL Server Profiler and open a new session. Invoke your stored procedure from your ASP page and see what is happening. While this may not solve your problem, it can surely provide a starting point for you to carry out some 'investigation' of your own.</p>\n" }, { "answer_id": 275739, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 3, "selected": false, "text": "<p>Some thoughts...</p>\n\n<p>Reading the comments suggests that parameter sniffing is causing the issue.</p>\n\n<ul>\n<li>For the other users, the cached plan is good enough for the parameter that they send</li>\n<li>For this user, the cached plan is probably wrong</li>\n</ul>\n\n<p>This could happen if this user has far more rows than other users, or has rows in another table (so a different table/index seek/scan would be better)</p>\n\n<p>To test for parameter sniffing:</p>\n\n<ul>\n<li>use RECOMPILE (temporarily) on the call or in the def. This could be slow for complex query</li>\n<li>Rebuild the indexes (or just statistics) after the timeout and try again. This invalidates all cached plans</li>\n</ul>\n\n<p>To fix:\nMask the parameter</p>\n\n<pre><code>DECLARE @MaskedParam varchar(10)\nSELECT @MaskedParam = @SignaureParam\n\nSELECT...WHERE column = @MaskedParam\n</code></pre>\n\n<p>Just google \"Parameter sniffing\" and \"Parameter masking\"</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12772/" ]
I have a Stored Procedure that is constantly failing with the error message "Timeout expired," on a specific user. All other users are able to invoke the sp just fine, and even I am able to invoke the sp normally using the Query Analyzer--it finishes in just 10 seconds. However with the user in question, the logs show that the ASP always hangs for about 5 minutes and then aborts with a timeout. I invoke from the ASP page like so "`EXEC SP_TV_GET_CLOSED_BANKS_BY_USERS '006111'`" Anybody know how to diagnose the problem? I have already tried looking at deadlocks in the DB, but didn't find any. Thanks,
Some thoughts... Reading the comments suggests that parameter sniffing is causing the issue. * For the other users, the cached plan is good enough for the parameter that they send * For this user, the cached plan is probably wrong This could happen if this user has far more rows than other users, or has rows in another table (so a different table/index seek/scan would be better) To test for parameter sniffing: * use RECOMPILE (temporarily) on the call or in the def. This could be slow for complex query * Rebuild the indexes (or just statistics) after the timeout and try again. This invalidates all cached plans To fix: Mask the parameter ``` DECLARE @MaskedParam varchar(10) SELECT @MaskedParam = @SignaureParam SELECT...WHERE column = @MaskedParam ``` Just google "Parameter sniffing" and "Parameter masking"
272,738
<p>Is there any way of pulling in a CSS stylesheet into FireFox 2 or 3 that is not a static file? </p> <p>Bellow is the code we are using to pull in a stylesheet dynamically generated by a CGI script.</p> <pre><code>&lt;link rel="stylesheet" href="/cgi-bin/Xebra?ShowIt&amp;s=LH4X6I2l4fSYwf4pky4k&amp;shw=795430-0&amp;path=customer/DEMO/demo1.css" type="text/css"&gt; </code></pre> <p>/cgi-bin/Xebra?ShowIt&amp;s=LH4X6I2l4fSYwf4pky4k&amp;shw=795430-0&amp;path=customer/DEMO/demo1.css</p> <p><strong>Note that the URL above that pulls in the CSS does not end with .css rather the parameters do.</strong></p>
[ { "answer_id": 272755, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": true, "text": "<p>Is the Content Type from the server the correct one for the file that is served up?</p>\n\n<pre><code>Content-type: text/css\n</code></pre>\n" }, { "answer_id": 272766, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 2, "selected": false, "text": "<p>why isn't this working?\nDouble check that the response header for the cgi script has </p>\n\n<pre><code>Content-Type: text/css\n</code></pre>\n" }, { "answer_id": 272767, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "<p>The extension doesn't matter but you should make sure the content type is <strong>\"text/css\"</strong>.</p>\n" }, { "answer_id": 272768, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 0, "selected": false, "text": "<p>I've done the same thing in the past - <a href=\"http://support.specorp.com\" rel=\"nofollow noreferrer\">a former employer's site</a> uses a link tag much like yours, and works fine in FF2 at least (I just checked it, though I tested it in FF when we added that link). If it's not working, I'd suspect it's something about the generated CSS file rather than the importing page. The consensus appears to be the Content-Type from the server may be wrong.</p>\n" }, { "answer_id": 272773, "author": "John Dunagan", "author_id": 28939, "author_profile": "https://Stackoverflow.com/users/28939", "pm_score": 0, "selected": false, "text": "<p>Your server procs (like the CGI) run first, don't they? Seems to me that that link tag will only pull in a file that exists already.</p>\n\n<p>So what I'd do is put a server tag (my lang's ASP/ASP.Net, but you could use PHP or anything, really) in the href.</p>\n\n<p>Like so:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" type=\"text/css href=\"&lt;% =getStylesheetPath() %&gt;\" media=\"all\"&gt;\n</code></pre>\n\n<p>Give that a shot.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18149/" ]
Is there any way of pulling in a CSS stylesheet into FireFox 2 or 3 that is not a static file? Bellow is the code we are using to pull in a stylesheet dynamically generated by a CGI script. ``` <link rel="stylesheet" href="/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css" type="text/css"> ``` /cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css **Note that the URL above that pulls in the CSS does not end with .css rather the parameters do.**
Is the Content Type from the server the correct one for the file that is served up? ``` Content-type: text/css ```
272,764
<p>I want a small (&lt; 30MB) standalone Windows executable (a single file) that creates a window which asks the user for the location of a directory and then launches a different program in that directory. </p> <p>This executable has to run on XP, Vista, Server 2003, and Server 2008 versions of Windows in 32-bits and 64 bits on x86-64 architecture as well as Itanium chips. </p> <p>It would be spectacular if we only had to build it once in order to run it on all these platforms, but that is not a requirement. This is for a proprietary system, so GPL code is off-limits.</p> <p>What is the fastest way to put this together?</p> <p>These are some things I'm looking into, so if you have info about their viability, I'm all about it:</p> <ul> <li>Perl/Tk using perl2exe to get the binary.</li> <li>Ruby with wxruby</li> <li>Learn MFC programming and do it the right way like everybody else.</li> </ul>
[ { "answer_id": 272775, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 2, "selected": false, "text": "<p>You could do this in MFC and have an executable in under 100k. In general, if you want to keep the size of your executables down, you can use UPX to perform exe compression. If you want an example, take a look at <a href=\"http://www.utorrent.com/\" rel=\"nofollow noreferrer\">uTorrent</a>. It's a full featured BitTorrent app in less than 300k of executable.</p>\n" }, { "answer_id": 272795, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": true, "text": "<p>What about a WSH script? It won't be an exe, right, but to ask for a folder I don't see the need for an exe file, much less a 30Mb one...</p>\n\n<p>A 1Kb script, save it as whatever name you like with vbs extension and run it. This, in case it's not clear, asks you for a folder name and then runs calc.exe from the system32 subdirectory. You can of course do a lot better than this in 2 or 4 Kb.</p>\n\n<pre><code>Set WshShell = WScript.CreateObject(\"WScript.Shell\")\nwin = InputBox(\"Please type your Windows folder location.\")\nIf Right(win,1) &lt;&gt; \"\\\" Then\n win = win &amp; \"\\\"\nEnd If\nWshShell.Run win &amp; \"system32\\calc.exe\"\n</code></pre>\n\n<p>To add a Folder Browser dialog instead of an InputBox, check <a href=\"http://wsh2.uw.hu/ch12f.html\" rel=\"noreferrer\">this</a> out.</p>\n\n<p>Clear benefits are:</p>\n\n<ul>\n<li>Simplicity (well, VB is ugly, but you can use JScript if you prefer), no need to compile it!</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/x66z77t4(VS.85).aspx\" rel=\"noreferrer\">Compatibility</a>, works on every windows machine I have available (from 98 onwards)</li>\n</ul>\n" }, { "answer_id": 272819, "author": "utku_karatas", "author_id": 14716, "author_profile": "https://Stackoverflow.com/users/14716", "pm_score": 3, "selected": false, "text": "<p>Quickest way on Windows for a lightweight and fast GUI? One word.. <strong>Delphi!</strong> It lacks the 64 bit support for now but then <a href=\"http://www.freepascal.org/\" rel=\"noreferrer\">FreePascal</a> would come to the rescue.</p>\n" }, { "answer_id": 272822, "author": "Jaywalker", "author_id": 382974, "author_profile": "https://Stackoverflow.com/users/382974", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.wxwidgets.org/\" rel=\"nofollow noreferrer\">wxWidgets</a>; it's cross platform, free, open source and easy to learn</p>\n" }, { "answer_id": 272836, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 2, "selected": false, "text": "<p>For all of its flaws, Visual Basic has historically been great for super-simple apps like this.</p>\n" }, { "answer_id": 272856, "author": "Electrons_Ahoy", "author_id": 19074, "author_profile": "https://Stackoverflow.com/users/19074", "pm_score": 3, "selected": false, "text": "<p>Python with either <a href=\"https://www.wxwidgets.org/\" rel=\"nofollow noreferrer\">wxWidgets</a> or <a href=\"https://docs.python.org/2/library/tkinter.html\" rel=\"nofollow noreferrer\">Tkinter</a> should be able to do this with almost no effort at all. Runs on everything, and py2exe will get you a standalone executable.</p>\n" }, { "answer_id": 272893, "author": "user3891", "author_id": 3891, "author_profile": "https://Stackoverflow.com/users/3891", "pm_score": 3, "selected": false, "text": "<p>I'd use .NET and WinForms. The idea of scripted solution is appealing, but in practice I often find you end up jumping through hoops to do anything beyond the basic case and still don't have the flexibility to do everything you want.</p>\n" }, { "answer_id": 272909, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 3, "selected": false, "text": "<p>Having a small stand-alone application and developing it quickly are, I'm sorry to say, usually conflicting requirements.</p>\n\n<p>To be honest, given how incredibly simple the application is, I would write it in C with direct Win32 calls: one call to SHBrowseForFolder() to get the directory, and one to ShellExecuteEx() to run the program. Even MFC is far too heavy-weight for such a modest application. Set the C runtime to be statically linked and you should be able to keep the size of the stand-alone executable to less than 100k. A decent Windows C coder should be able to knock that up in less than an hour, assuming you have one to hand.</p>\n" }, { "answer_id": 272915, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 0, "selected": false, "text": "<p>Similar to what Vinko Vrsalovic said, you can use a HTA application. It is as easy as building a webpage with windows scripting host functionality. I have built a few utilities with jscript and it is really easy and quick\n<a href=\"http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx</a></p>\n" }, { "answer_id": 272925, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 0, "selected": false, "text": "<p>These responses are unbelievable.</p>\n\n<p>Visual Studio Forms editor lets you draw out WinForms and autogenerates the boilerplate GUI code (which is a pain in the ass at best for most other languages and toolkits). Then you can use C# or any other .NET language. .NET has stock widgets for file pickers. I could write that script in 20 minutes and it will run on every one of your target platforms for free. Draw out the GUI, drag-n-drop a file picker, fill out maybe two hooks to do the \"launch a different file than they wanted\" thing, done.</p>\n" }, { "answer_id": 272931, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "<p>Tcl/tk is one solution. You can have a single file executable (including custom images, dlls, etc) using something called a \"starpack\" -- a virtual filesystem that is both tcl interpreter and application code. I think it would weigh in at maybe a couple megabytes.</p>\n\n<p>From your specifications it would take me personally maybe 15 minutes to get a first working version.</p>\n\n<p>Tcl/Tk has a BSD license.</p>\n" }, { "answer_id": 272995, "author": "Dexygen", "author_id": 34806, "author_profile": "https://Stackoverflow.com/users/34806", "pm_score": 2, "selected": false, "text": "<p>I agree with the Tcl/Tk answer above. For more information about the starpack that he refers to, see: <a href=\"http://www.equi4.com/tclkit/\" rel=\"nofollow noreferrer\">http://www.equi4.com/tclkit/</a> it's a Tcl/Tk interpreter available for various OS's all in about 1MB. In the past there apparently has been concerned about the look and feel of Tcl/Tk UI's, but this has been addressed by a new framework named \"Tile\" that supports the native look and feel of the user's OS.</p>\n" }, { "answer_id": 273092, "author": "Ken Paul", "author_id": 26671, "author_profile": "https://Stackoverflow.com/users/26671", "pm_score": 1, "selected": false, "text": "<p>I use HTA (HTML Application) for quick-and-dirty form &amp; script applications. See <a href=\"http://www.microsoft.com/technet/scriptcenter/hubs/htas.mspx\" rel=\"nofollow noreferrer\">Microsoft's HTA Developers Center</a> for details and examples. This basically uses HTML for the form, and any HTML-accessible scripting language for the script. Normal browser security is bypassed so that you can get at almost all OS internals. The above site also contains links to several tools that nearly automate the scripting part for you.</p>\n" }, { "answer_id": 273357, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "<p>For a quick and dirty GUI program like you said, you can use an <a href=\"http://www.autoitscript.com/autoit3/\" rel=\"nofollow noreferrer\">AutoIt</a> script. You can even compile to an exe.</p>\n\n<p>For an GUI example of AutoIt, you can check my stdout redirect script in a previous answer <a href=\"https://stackoverflow.com/questions/8004/best-way-to-wrap-rsync-progress-in-a-gui\">here</a> </p>\n" }, { "answer_id": 4726689, "author": "David Watson", "author_id": 173308, "author_profile": "https://Stackoverflow.com/users/173308", "pm_score": 1, "selected": false, "text": "<p>PyQt works really well for this. Binaries for Windows here:</p>\n\n<p><a href=\"http://www.riverbankcomputing.co.uk/software/pyqt/download\" rel=\"nofollow noreferrer\">http://www.riverbankcomputing.co.uk/software/pyqt/download</a></p>\n\n<p>A good book here:</p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0132354187\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Programming-Python-Prentice-Software-Development/dp/0132354187/ref=sr_1_1?ie=UTF8&amp;qid=1295369454&amp;sr=8-1</a></p>\n\n<p>And you can freeze these using various methods if you need exe(s).</p>\n" }, { "answer_id": 21327510, "author": "Vijay", "author_id": 107537, "author_profile": "https://Stackoverflow.com/users/107537", "pm_score": 0, "selected": false, "text": "<p>I suggest <a href=\"http://www.autohotkey.com\" rel=\"nofollow\">Autohotkey (AHK)</a> or <a href=\"http://www.autoitscript.com/site/autoit/\" rel=\"nofollow\">Autoit</a>. Both support win95+ (with caveats for certain functions). They can be compiled into small .exe without external dependency (besides native DLL's). </p>\n\n<p>Pros:</p>\n\n<ul>\n<li>small size</li>\n<li>easy to write code</li>\n<li>useful for simple - complex operations</li>\n<li>can create GUI easily</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>learning curve (as syntax is unusual)</li>\n</ul>\n" }, { "answer_id": 63196806, "author": "user26742873", "author_id": 8535456, "author_profile": "https://Stackoverflow.com/users/8535456", "pm_score": 0, "selected": false, "text": "<p>30MB is pretty huge!</p>\n<p>Qt (C++) may be the best choice. It is portable, quick to develop and relatively fast to run. With UPX (Ultimate Packer for eXecutables) your program will be 10M+.</p>\n<p>Qt (Python) is OK too, but will be slower.</p>\n<p>If you want it less than 1M and/or you want it quick, you can write it in C with win32 api, or use Delphi.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8344/" ]
I want a small (< 30MB) standalone Windows executable (a single file) that creates a window which asks the user for the location of a directory and then launches a different program in that directory. This executable has to run on XP, Vista, Server 2003, and Server 2008 versions of Windows in 32-bits and 64 bits on x86-64 architecture as well as Itanium chips. It would be spectacular if we only had to build it once in order to run it on all these platforms, but that is not a requirement. This is for a proprietary system, so GPL code is off-limits. What is the fastest way to put this together? These are some things I'm looking into, so if you have info about their viability, I'm all about it: * Perl/Tk using perl2exe to get the binary. * Ruby with wxruby * Learn MFC programming and do it the right way like everybody else.
What about a WSH script? It won't be an exe, right, but to ask for a folder I don't see the need for an exe file, much less a 30Mb one... A 1Kb script, save it as whatever name you like with vbs extension and run it. This, in case it's not clear, asks you for a folder name and then runs calc.exe from the system32 subdirectory. You can of course do a lot better than this in 2 or 4 Kb. ``` Set WshShell = WScript.CreateObject("WScript.Shell") win = InputBox("Please type your Windows folder location.") If Right(win,1) <> "\" Then win = win & "\" End If WshShell.Run win & "system32\calc.exe" ``` To add a Folder Browser dialog instead of an InputBox, check [this](http://wsh2.uw.hu/ch12f.html) out. Clear benefits are: * Simplicity (well, VB is ugly, but you can use JScript if you prefer), no need to compile it! * [Compatibility](http://msdn.microsoft.com/en-us/library/x66z77t4(VS.85).aspx), works on every windows machine I have available (from 98 onwards)
272,765
<p>I've created a c# webservice that allows our front end support teams to view and update a few selected Active Directory values using system.directoryservices</p> <p>Fields that I want to update are [job] title, department, telephone and employeeid.</p> <p>I can use a service account with "delegates rights" to update [job] title, department, telephone etc. but when I try to update employeeid I get an "not authorised" error message.</p> <p>If I use a domain admin account then the same code works fine.</p> <p>I don't want to use a domain admin account for this webservice, so what privileges do I need?</p>
[ { "answer_id": 272777, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 0, "selected": false, "text": "<p>A sample of the code (the moving parts at least)</p>\n\n<pre><code>string distinguishedname = \"CN=Wicks\\, Guy,OU=Users,DC=ad,DC=com\"\nusing (DirectoryEntry myDirectoryEntry = new DirectoryEntry(string.Format(\"LDAP://{0}\", distinguishedname), null, null, AuthenticationTypes.Secure))\n{\n try\n {\n myDirectoryEntry.Username = \"serviceaccount\";\n myDirectoryEntry.Password = \"pa55word\";\n\n myDirectoryEntry.Properties[\"employeeid\"][0] = employeeID;\n myDirectoryEntry.CommitChanges();\n setresult.result = myDirectoryEntry.Properties[\"employeeid\"][0].ToString();\n }\n catch ( Exception ex )\n {\n setresult.result = ex.Message;\n }\n} // end using\n</code></pre>\n\n<p>(I do apologise for my c#)</p>\n" }, { "answer_id": 272790, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 3, "selected": true, "text": "<p><strong>ANSWER</strong></p>\n\n<p><em>The ADS_SCHEMA_ID_GUID_USER GUID allows you to update the base user class details, including the employee id</em></p>\n\n<p><a href=\"http://www.microsoft.com/technet/scriptcenter/topics/security/exrights.mspx\" rel=\"nofollow noreferrer\">Based on MSDN article</a></p>\n\n<p>The vbscript used to grant to the service account user the selected delegated rights: </p>\n\n<pre><code>REM #\nREM # Delegate AD property set admin rights to named account\nREM # Based on: http://www.microsoft.com/technet/scriptcenter/topics/security/propset.mspx\nREM #\n\nConst TRUSTEE_ACCOUNT_SAM = \"ad\\ADStaffUpdates\"\n\nConst ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &amp;H5\nConst ADS_RIGHT_DS_READ_PROP = &amp;H10\nConst ADS_RIGHT_DS_WRITE_PROP = &amp;H20\nConst ADS_FLAG_OBJECT_TYPE_PRESENT = &amp;H1\nConst ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT = &amp;H2\nConst ADS_ACEFLAG_INHERIT_ACE = &amp;H2\n\nConst ADS_SCHEMA_ID_GUID_USER = \"{bf967aba-0de6-11d0-a285-00aa003049e2}\"\nConst ADS_SCHEMA_ID_GUID_PS_PERSONAL = \"{77b5b886-944a-11d1-aebd-0000f80367c1}\"\nConst ADS_SCHEMA_ID_GUID_PS_PUBLIC = \"{e48d0154-bcf8-11d1-8702-00c04fb96050}\"\n\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_USER\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PERSONAL\nad_setUserDelegation \"OU=USERS, DC=AD, DC=COM\", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PUBLIC\n\nFunction ad_setUserDelegation( _\n ByVal strOU _\n ,ByVal strTrusteeAccount _\n ,ByVal strSchema_GUID _\n )\n\n Set objSdUtil = GetObject( \"LDAP://\" &amp; strOU )\n\n Set objSD = objSdUtil.Get( \"ntSecurityDescriptor\" )\n Set objDACL = objSD.DiscretionaryACL\n\n Set objAce = CreateObject( \"AccessControlEntry\" )\n\n objAce.Trustee = strTrusteeAccount\n objAce.AceFlags = ADS_ACEFLAG_INHERIT_ACE\n objAce.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT\n objAce.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT OR ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT\n\n objAce.ObjectType = strSchema_GUID\n\n objACE.InheritedObjectType = ADS_SCHEMA_ID_GUID_USER\n objAce.AccessMask = ADS_RIGHT_DS_READ_PROP OR ADS_RIGHT_DS_WRITE_PROP\n objDacl.AddAce objAce\n\n objSD.DiscretionaryAcl = objDacl\n\n objSDUtil.Put \"ntSecurityDescriptor\", Array( objSD )\n objSDUtil.SetInfo\n\nEnd Function\n\n\nFunction ad_revokeUserDelegation( _\n ByVal strOU _\n ,ByVal strTrusteeAccount _\n )\n\n Set objSdUtil = GetObject( \"LDAP://\" &amp; strOU )\n\n Set objSD = objSdUtil.Get( \"ntSecurityDescriptor\" )\n Set objDACL = objSD.DiscretionaryACL\n\n For Each objACE in objDACL\n If UCase(objACE.Trustee) = UCase(strTrusteeAccount) Then\n objDACL.RemoveAce objACE\n End If\n Next\n\n objSDUtil.Put \"ntSecurityDescriptor\", Array(objSD)\n objSDUtil.SetInfo\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 278648, "author": "Alexander Taran", "author_id": 35954, "author_profile": "https://Stackoverflow.com/users/35954", "pm_score": 0, "selected": false, "text": "<p>do users of your service have the rights to modify those fields through AD users and computers?\nif they are then maybe you can use impersonation and just make your service host computer \"trusted for delegation\" (in AD properties for it) always worked fine for me.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/993/" ]
I've created a c# webservice that allows our front end support teams to view and update a few selected Active Directory values using system.directoryservices Fields that I want to update are [job] title, department, telephone and employeeid. I can use a service account with "delegates rights" to update [job] title, department, telephone etc. but when I try to update employeeid I get an "not authorised" error message. If I use a domain admin account then the same code works fine. I don't want to use a domain admin account for this webservice, so what privileges do I need?
**ANSWER** *The ADS\_SCHEMA\_ID\_GUID\_USER GUID allows you to update the base user class details, including the employee id* [Based on MSDN article](http://www.microsoft.com/technet/scriptcenter/topics/security/exrights.mspx) The vbscript used to grant to the service account user the selected delegated rights: ``` REM # REM # Delegate AD property set admin rights to named account REM # Based on: http://www.microsoft.com/technet/scriptcenter/topics/security/propset.mspx REM # Const TRUSTEE_ACCOUNT_SAM = "ad\ADStaffUpdates" Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 Const ADS_RIGHT_DS_READ_PROP = &H10 Const ADS_RIGHT_DS_WRITE_PROP = &H20 Const ADS_FLAG_OBJECT_TYPE_PRESENT = &H1 Const ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT = &H2 Const ADS_ACEFLAG_INHERIT_ACE = &H2 Const ADS_SCHEMA_ID_GUID_USER = "{bf967aba-0de6-11d0-a285-00aa003049e2}" Const ADS_SCHEMA_ID_GUID_PS_PERSONAL = "{77b5b886-944a-11d1-aebd-0000f80367c1}" Const ADS_SCHEMA_ID_GUID_PS_PUBLIC = "{e48d0154-bcf8-11d1-8702-00c04fb96050}" ad_setUserDelegation "OU=USERS, DC=AD, DC=COM", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_USER ad_setUserDelegation "OU=USERS, DC=AD, DC=COM", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PERSONAL ad_setUserDelegation "OU=USERS, DC=AD, DC=COM", TRUSTEE_ACCOUNT_SAM, ADS_SCHEMA_ID_GUID_PS_PUBLIC Function ad_setUserDelegation( _ ByVal strOU _ ,ByVal strTrusteeAccount _ ,ByVal strSchema_GUID _ ) Set objSdUtil = GetObject( "LDAP://" & strOU ) Set objSD = objSdUtil.Get( "ntSecurityDescriptor" ) Set objDACL = objSD.DiscretionaryACL Set objAce = CreateObject( "AccessControlEntry" ) objAce.Trustee = strTrusteeAccount objAce.AceFlags = ADS_ACEFLAG_INHERIT_ACE objAce.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT objAce.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT OR ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT objAce.ObjectType = strSchema_GUID objACE.InheritedObjectType = ADS_SCHEMA_ID_GUID_USER objAce.AccessMask = ADS_RIGHT_DS_READ_PROP OR ADS_RIGHT_DS_WRITE_PROP objDacl.AddAce objAce objSD.DiscretionaryAcl = objDacl objSDUtil.Put "ntSecurityDescriptor", Array( objSD ) objSDUtil.SetInfo End Function Function ad_revokeUserDelegation( _ ByVal strOU _ ,ByVal strTrusteeAccount _ ) Set objSdUtil = GetObject( "LDAP://" & strOU ) Set objSD = objSdUtil.Get( "ntSecurityDescriptor" ) Set objDACL = objSD.DiscretionaryACL For Each objACE in objDACL If UCase(objACE.Trustee) = UCase(strTrusteeAccount) Then objDACL.RemoveAce objACE End If Next objSDUtil.Put "ntSecurityDescriptor", Array(objSD) objSDUtil.SetInfo End Function ```
272,783
<p>I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode).</p> <p>How would I get a unique Process ID and Thread ID in Delphi?</p> <p>Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?</p> <p><em>Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames</em></p>
[ { "answer_id": 272789, "author": "Jamie", "author_id": 922, "author_profile": "https://Stackoverflow.com/users/922", "pm_score": 2, "selected": false, "text": "<p>Could you not use a <a href=\"http://en.wikipedia.org/wiki/Globally_Unique_Identifier\" rel=\"nofollow noreferrer\">GUID</a> instead? </p>\n\n<p>Edit: Should have said first time around, check out the following two functions</p>\n\n<pre><code>CreateGuid\nGuidToString\n</code></pre>\n" }, { "answer_id": 272797, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 2, "selected": false, "text": "<p>Process IDs are not guaranteed to be unique on windows. They are certainly unique for the life of the process, but once a process dies its id can be immediately reused. I am not certain about ThreadIDs. If these are temporary files you could use something equivalent to tmpfile or tmpnam (C functions, but I assume Delphi has an equivalent).</p>\n\n<p>As Jamie posted a GUID may be better.</p>\n" }, { "answer_id": 272812, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 2, "selected": false, "text": "<p>Better than either of of those options, you should be using the system function <a href=\"http://msdn.microsoft.com/en-us/library/hs3e7355.aspx\" rel=\"nofollow noreferrer\">_tempnam</a>. It returns a random file name in the directory for a file that does not exist. If you want to, you can supply a prefix to _tempnam so that the file you create is recognizably yours. If you are providing a unique prefix, there is shouldn't be any worry about someone opening your file. There is another solution, however.</p>\n\n<p>_tempnam is only good if you want to put the file into an arbitrary directory. If you don't care that the directory is the system temporary directory, use <a href=\"http://msdn.microsoft.com/en-us/library/b3dz6009.aspx\" rel=\"nofollow noreferrer\">tempfile_s</a> instead. It will also create the file for you, so no worry about race conditions... Errors will only occur if you try to open more temp files than the system can handle. The big downside to tempfile_s is that the file will disappear once you fclose it.</p>\n\n<p>EDIT: I've gotten a downvote because this is a C function. You have access to the C runtime by importing them into delphi. Have a look at some examples with msvcrt.dll <a href=\"http://rvelthuis.de/articles/articles-cobjs.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>function _tempnam(const Dir: PChar, const Prefix: PChar): PChar; cdecl;\n external 'msvcrt.dll' name '_tempnam';\n</code></pre>\n" }, { "answer_id": 272903, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 1, "selected": false, "text": "<p>Others all gave you a good and reasonable ideas, but still - if you're using files for temporary storage and if those files will always be created first (it doesn't matter if there is a leftover file with a same name already on the disk as you'll overwrite it anyway) then processid_threadid approach is completely valid.</p>\n\n<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/ms683180.aspx\" rel=\"nofollow noreferrer\">GetCurrentProcessID</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms683183.aspx\" rel=\"nofollow noreferrer\">GetCurrentThreadID</a> Win32 calls to access those two IDs.</p>\n" }, { "answer_id": 272919, "author": "X-Ray", "author_id": 14031, "author_profile": "https://Stackoverflow.com/users/14031", "pm_score": 4, "selected": true, "text": "<p>you have many good ideas presented here.</p>\n\n<blockquote>\n <p>Does it also create an empty file to \"get a lock on\" the name?</p>\n</blockquote>\n\n<p>no; i believe we rely on Windows to ensure the same temp file name is never given twice on the same computer since boot time.</p>\n\n<blockquote>\n <p>is there <em>any</em> chance of a clash if there is a split second delay between generating the name and creating the file (if I need to create the file myself).</p>\n</blockquote>\n\n<p>no; that'd be a pretty bad thing.</p>\n\n<p>here's a routine i've been using for getting a temp file.</p>\n\n<pre><code>function GetTemporaryFileName:string;\nvar\n Path, FileName: array[0..MAX_PATH] of Char;\nbegin\n Win32Check(GetTempPath(MAX_PATH, Path) &lt;&gt; 0);\n Win32Check(GetTempFileName(Path, '~EX', 0, FileName) &lt;&gt; 0);\n Result:=String(Filename);\nend;\n</code></pre>\n\n<p>you could instead use FileGetTempName( ) from JclFileUtils.pas in JCL.</p>\n" }, { "answer_id": 274318, "author": "Darian Miller", "author_id": 35696, "author_profile": "https://Stackoverflow.com/users/35696", "pm_score": 2, "selected": false, "text": "<p>1) How to get a unique Process ID &amp; ThreadID in Delphi:</p>\n\n<p>Answer: <br>\nNOTE: Ensure to add 'windows' to your uses clause in the implementation section<br>\nNOTE: Cardinals are unsigned 32-bit integers ranging from 0 to 4294967295</p>\n\n<pre><code>implementation\nuses Windows;\n\nprocedure MySolution();\nvar\n myThreadID:Cardinal; \n myProcessID:Cardinal;\nbegin\n myThreadID := windows.GetCurrentThreadID;\n myProcessID := windows.GetCurrentProcessId;\nend;\n</code></pre>\n\n<p>2) Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?<br>\n<strong>Answer: Yes.</strong></p>\n\n<blockquote>\n <p>The process identifier is valid from\n the time the process is created until\n the process has been terminated and is\n unique throughout the system. (Not\n unique to processor)</p>\n \n <p>Until the thread terminates, the\n thread identifier uniquely identifies\n the thread throughout the system. \n (Again, system wide, not unique to\n processor)</p>\n</blockquote>\n" }, { "answer_id": 274364, "author": "Nick Hodges", "author_id": 2044, "author_profile": "https://Stackoverflow.com/users/2044", "pm_score": 3, "selected": false, "text": "<p>Windows provides functionality for creating guaranteed unique file names. No need for creating your own:</p>\n\n<p>Here's a Delphi wrapper around that functionality:</p>\n\n<pre><code>function CreateTempFileName(aPrefix: string): string;\nvar\n Buf: array[0..MAX_PATH] of Char;\n Temp: array[0..MAX_PATH] of Char;\nbegin\n GetTempPath(MAX_PATH, Buf);\n if GetTempFilename(Buf, PChar(aPrefix), 0, Temp) = 0 then\n begin\n raise Exception.CreateFmt(sWin32Error, [GetLastError, SysErrorMessage(GetLastError)]);\n end;\n Result := string(Temp);\nend;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ]
I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode). How would I get a unique Process ID and Thread ID in Delphi? Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)? *Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames*
you have many good ideas presented here. > > Does it also create an empty file to "get a lock on" the name? > > > no; i believe we rely on Windows to ensure the same temp file name is never given twice on the same computer since boot time. > > is there *any* chance of a clash if there is a split second delay between generating the name and creating the file (if I need to create the file myself). > > > no; that'd be a pretty bad thing. here's a routine i've been using for getting a temp file. ``` function GetTemporaryFileName:string; var Path, FileName: array[0..MAX_PATH] of Char; begin Win32Check(GetTempPath(MAX_PATH, Path) <> 0); Win32Check(GetTempFileName(Path, '~EX', 0, FileName) <> 0); Result:=String(Filename); end; ``` you could instead use FileGetTempName( ) from JclFileUtils.pas in JCL.
272,799
<p>Is there a (portable) way to rotate text in a HTML table cell by 90°?</p> <p>(I have a table with many columns and much text for the headings, so I'd like to write it vertically to save space.)</p>
[ { "answer_id": 272860, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 5, "selected": false, "text": "<h2>Alternate Solution?</h2>\n<p>Instead of rotating the text, would it work to have it written &quot;top to bottom?&quot;</p>\n<p>Like this:</p>\n<pre><code>S \nO \nM \nE \n\nT \nE \nX \nT \n</code></pre>\n<p>I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.</p>\n<p>This could be done via JavaScript in the browser like this:</p>\n<pre><code>&quot;SOME TEXT&quot;.split(&quot;&quot;).join(&quot;\\n&quot;)\n</code></pre>\n<p>... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by &quot;portable?&quot;)</p>\n<p>Also the user doesn't have to turn his/her head sideways to read it. :)</p>\n<h3>Update</h3>\n<p><a href=\"https://stackoverflow.com/questions/278940/vertical-text-with-jquery\">This thread</a> is about doing this with jQuery.</p>\n" }, { "answer_id": 272891, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://ajaxian.com/archives/transformie-implement-webkit-css-transforms-in-ie\" rel=\"nofollow noreferrer\">IE filters</a>\nplus\nCSS transforms (<a href=\"http://webkit.org/blog/130/css-transforms/\" rel=\"nofollow noreferrer\">Safari</a> and <a href=\"https://developer.mozilla.org/En/CSS/CSS_transform_functions\" rel=\"nofollow noreferrer\">Firefox</a>).</p>\n\n<p>IE's support is the oldest, Safari has [at least some?] support in 3.1.2, and Firefox won't have support until 3.1.</p>\n\n<p>Alternatively, I would recommend a mix of Canvas/VML or SVG/VML. (Canvas has wider support.)</p>\n" }, { "answer_id": 2416032, "author": "Álvaro González", "author_id": 13508, "author_profile": "https://Stackoverflow.com/users/13508", "pm_score": 8, "selected": true, "text": "<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-css lang-css prettyprint-override\"><code>.box_rotate {\r\n -moz-transform: rotate(7.5deg); /* FF3.5+ */\r\n -o-transform: rotate(7.5deg); /* Opera 10.5 */\r\n -webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */\r\n filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */\r\n -ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)\"; /* IE8 */\r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;\r\n&lt;div class=\"box_rotate\"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;\r\n&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Taken from <a href=\"http://css3please.com/\" rel=\"nofollow noreferrer\">http://css3please.com/</a></p>\n\n<p>As of 2017, the aforementioned site has simplified the rule set to drop legacy Internet Explorer filter and rely more in the now standard <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/transform\" rel=\"nofollow noreferrer\"><code>transform</code> property</a>:</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-css lang-css prettyprint-override\"><code>.box_rotate {\r\n -webkit-transform: rotate(7.5deg); /* Chrome, Opera 15+, Safari 3.1+ */\r\n -ms-transform: rotate(7.5deg); /* IE 9 */\r\n transform: rotate(7.5deg); /* Firefox 16+, IE 10+, Opera */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;\r\n&lt;div class=\"box_rotate\"&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;\r\n&lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 4809384, "author": "Rob Pinion", "author_id": 591246, "author_profile": "https://Stackoverflow.com/users/591246", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-css prettyprint-override\"><code>-moz-transform: rotate(7.5deg); /* FF3.5+ */\n-o-transform: rotate(7.5deg); /* Opera 10.5 */\n-webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */\nfilter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); /* IE6,IE7 allows only 1, 2, 3 */\n-ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)\"; /* IE8 allows only 1 2 or 3*/\n</code></pre>\n" }, { "answer_id": 4809513, "author": "Rob Pinion", "author_id": 591246, "author_profile": "https://Stackoverflow.com/users/591246", "pm_score": 4, "selected": false, "text": "<p>There is a quote in the original answer and my previous answer on the IE8 line that throws this off, right near the semi-colon. Yikes and BAAAAD! The code below has the rotation set correctly and works. You have to float in IE for the filter to be applied.</p>\n\n<pre>\n&lt;div style=\"\n float: left; \n position: relative;\n -moz-transform: rotate(270deg); /* FF3.5+ */ \n -o-transform: rotate(270deg); /* Opera 10.5 */ \n -webkit-transform: rotate(270deg); /* Saf3.1+, Chrome */ \n filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); /* IE6,IE7 */ \n -ms-filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); /* IE8 */ \n\"\n>Count & Value&lt;/div>;\n</pre>\n" }, { "answer_id": 10946566, "author": "Cine", "author_id": 264022, "author_profile": "https://Stackoverflow.com/users/264022", "pm_score": 2, "selected": false, "text": "<p>Here is one that works for plain-text with some server side processing:</p>\n\n<pre><code>public string RotateHtmltext(string innerHtml)\n{\n const string TRANSFORMTEXT = \"transform: rotate(90deg);\";\n const string EXTRASTYLECSS = \"&lt;style type='text/css'&gt;.r90 {\"\n + \"-webkit-\" + TRANSFORMTEXT\n + \"-moz-\" + TRANSFORMTEXT\n + \"-o-\" + TRANSFORMTEXT\n + \"-ms-\" + TRANSFORMTEXT\n + \"\" + TRANSFORMTEXT\n + \"width:1em;line-height:1ex}&lt;/style&gt;\";\n const string WRAPPERDIV = \"&lt;div style='display: table-cell; vertical-align: middle;'&gt;\";\n\n var newinnerHtml = string.Join(\"&lt;/div&gt;\"+WRAPPERDIV, Regex.Split(innerHtml, @\"&lt;br */?&gt;\").Reverse());\n\n newinnerHtml = Regex.Replace(newinnerHtml, @\"((?:&lt;[^&gt;]*&gt;)|(?:[^&lt;]+))\",\n match =&gt; match.Groups[1].Value.StartsWith(\"&lt;\")\n ? match.Groups[1].Value\n : string.Join(\"\", match.Groups[1].Value.ToCharArray().Select(x=&gt;\"&lt;div class='r90'&gt;\"+x+\"&lt;/div&gt;\")),\n RegexOptions.Singleline);\n return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + \"&lt;/div&gt;\";\n}\n</code></pre>\n\n<p>which gives something like:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;.r90 {\n-webkit-transform: rotate(90deg);\n-moz-transform: rotate(90deg);\n-o-transform: rotate(90deg);\n-ms-transform: rotate(90deg);\ntransform: rotate(90deg);\nwidth: 1em;\nline-height: 1ex; \n}&lt;/style&gt;\n&lt;div style=\"display: table-cell; vertical-align: middle;\"&gt;\n&lt;div class=\"r90\"&gt;p&lt;/div&gt;\n&lt;div class=\"r90\"&gt;o&lt;/div&gt;\n&lt;div class=\"r90\"&gt;s&lt;/div&gt;\n&lt;/div&gt;&lt;div style=\"display: table-cell; vertical-align: middle;\"&gt;\n&lt;div class=\"r90\"&gt;(&lt;/div&gt;\n&lt;div class=\"r90\"&gt;A&lt;/div&gt;\n&lt;div class=\"r90\"&gt;b&lt;/div&gt;\n&lt;div class=\"r90\"&gt;s&lt;/div&gt;\n&lt;div class=\"r90\"&gt;)&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/TzzHy/\" rel=\"nofollow\">http://jsfiddle.net/TzzHy/</a></p>\n" }, { "answer_id": 12969105, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "<p>After having tried for over two hours, I can safely say that all the method mentioned so far don't work across browsers, or for IE even across browser versions...</p>\n\n<p>For example (top upvoted answer):</p>\n\n<pre><code> filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */\n -ms-filter: \"progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)\"; /* IE8 */\n</code></pre>\n\n<p>rotates twice in IE9, once for filter, and once for -ms-filter, so...</p>\n\n<p>All other mentioned methods do not work either, at least not if you have to set no fixed height/width of the table header cell (with background color), where it should automatically adjust to size of the highest element.</p>\n\n<p>So to elaborate on the server-side image generation proposed by Nathan Long, which is really the only universially working method, here my VB.NET code for a generic handler (*.ashx ):</p>\n\n<pre><code>Imports System.Web\nImports System.Web.Services\n\n\nPublic Class GenerateImage\n Implements System.Web.IHttpHandler\n\n\n Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest\n 'context.Response.ContentType = \"text/plain\"\n 'context.Response.Write(\"Hello World!\")\n context.Response.ContentType = \"image/png\"\n\n Dim strText As String = context.Request.QueryString(\"text\")\n Dim strRotate As String = context.Request.QueryString(\"rotate\")\n Dim strBGcolor As String = context.Request.QueryString(\"bgcolor\")\n\n Dim bRotate As Boolean = True\n\n If String.IsNullOrEmpty(strText) Then\n strText = \"No Text\"\n End If\n\n\n Try\n If Not String.IsNullOrEmpty(strRotate) Then\n bRotate = System.Convert.ToBoolean(strRotate)\n End If\n Catch ex As Exception\n\n End Try\n\n\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n 'Dim img As System.Drawing.Image = CreateBitmapImage(strText, bRotate)\n\n ' Generic error in GDI+\n 'img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n\n 'Dim bm As System.Drawing.Bitmap = New System.Drawing.Bitmap(img)\n 'bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n\n Using msTempOutputStream As New System.IO.MemoryStream\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)\n img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)\n msTempOutputStream.Flush()\n\n context.Response.Buffer = True\n context.Response.ContentType = \"image/png\"\n context.Response.BinaryWrite(msTempOutputStream.ToArray())\n End Using ' img\n\n End Using ' msTempOutputStream\n\n End Sub ' ProcessRequest\n\n\n Private Function CreateBitmapImage(strImageText As String) As System.Drawing.Image\n Return CreateBitmapImage(strImageText, True)\n End Function ' CreateBitmapImage\n\n\n Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean) As System.Drawing.Image\n Return CreateBitmapImage(strImageText, bRotate, Nothing)\n End Function\n\n\n Private Function InvertMeAColour(ColourToInvert As System.Drawing.Color) As System.Drawing.Color\n Const RGBMAX As Integer = 255\n Return System.Drawing.Color.FromArgb(RGBMAX - ColourToInvert.R, RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B)\n End Function\n\n\n\n Private Function CreateBitmapImage(strImageText As String, bRotate As Boolean, strBackgroundColor As String) As System.Drawing.Image\n Dim bmpEndImage As System.Drawing.Bitmap = Nothing\n\n If String.IsNullOrEmpty(strBackgroundColor) Then\n strBackgroundColor = \"#E0E0E0\"\n End If\n\n Dim intWidth As Integer = 0\n Dim intHeight As Integer = 0\n\n\n Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray\n bgColor = System.Drawing.ColorTranslator.FromHtml(strBackgroundColor)\n\n Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black\n TextColor = InvertMeAColour(bgColor)\n\n 'TextColor = Color.FromArgb(102, 102, 102)\n\n\n\n ' Create the Font object for the image text drawing.\n Using fntThisFont As New System.Drawing.Font(\"Arial\", 11, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel)\n\n ' Create a graphics object to measure the text's width and height.\n Using bmpInitialImage As New System.Drawing.Bitmap(1, 1)\n\n Using gStringMeasureGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpInitialImage)\n ' This is where the bitmap size is determined.\n intWidth = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Width)\n intHeight = CInt(gStringMeasureGraphics.MeasureString(strImageText, fntThisFont).Height)\n\n ' Create the bmpImage again with the correct size for the text and font.\n bmpEndImage = New System.Drawing.Bitmap(bmpInitialImage, New System.Drawing.Size(intWidth, intHeight))\n\n ' Add the colors to the new bitmap.\n Using gNewGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpEndImage)\n ' Set Background color\n 'gNewGraphics.Clear(Color.White)\n gNewGraphics.Clear(bgColor)\n gNewGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias\n gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias\n\n\n ''''\n\n 'gNewGraphics.TranslateTransform(bmpEndImage.Width, bmpEndImage.Height)\n 'gNewGraphics.RotateTransform(180)\n 'gNewGraphics.RotateTransform(0)\n 'gNewGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault\n\n\n gNewGraphics.DrawString(strImageText, fntThisFont, New System.Drawing.SolidBrush(TextColor), 0, 0)\n\n gNewGraphics.Flush()\n\n If bRotate Then\n 'bmpEndImage = rotateImage(bmpEndImage, 90)\n 'bmpEndImage = RotateImage(bmpEndImage, New PointF(0, 0), 90)\n 'bmpEndImage.RotateFlip(RotateFlipType.Rotate90FlipNone)\n bmpEndImage.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone)\n End If ' bRotate\n\n End Using ' gNewGraphics\n\n End Using ' gStringMeasureGraphics\n\n End Using ' bmpInitialImage\n\n End Using ' fntThisFont\n\n Return bmpEndImage\n End Function ' CreateBitmapImage\n\n\n ' http://msdn.microsoft.com/en-us/library/3zxbwxch.aspx\n ' http://msdn.microsoft.com/en-us/library/7e1w5dhw.aspx\n ' http://www.informit.com/guides/content.aspx?g=dotnet&amp;seqNum=286\n ' http://road-blogs.blogspot.com/2011/01/rotate-text-in-ssrs.html\n Public Shared Function GenerateImage_CrappyOldReportingServiceVariant(ByVal strText As String, ByVal strFont As String, bRotate As Boolean) As System.Drawing.Image\n Dim bgColor As System.Drawing.Color = System.Drawing.Color.LemonChiffon ' LightGray\n bgColor = System.Drawing.ColorTranslator.FromHtml(\"#E0E0E0\")\n\n\n Dim TextColor As System.Drawing.Color = System.Drawing.Color.Black\n 'TextColor = System.Drawing.Color.FromArgb(255, 0, 0, 255)\n\n If String.IsNullOrEmpty(strFont) Then\n strFont = \"Arial\"\n Else\n If strFont.Trim().Equals(String.Empty) Then\n strFont = \"Arial\"\n End If\n End If\n\n\n 'Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Regular\n Dim fsFontStyle As System.Drawing.FontStyle = System.Drawing.FontStyle.Bold\n Dim fontFamily As New System.Drawing.FontFamily(strFont)\n Dim iFontSize As Integer = 8 '//Change this as needed\n\n\n ' vice-versa, because 270° turn\n 'Dim height As Double = 2.25\n Dim height As Double = 4\n Dim width As Double = 1\n\n ' width = 10\n ' height = 10\n\n Dim bmpImage As New System.Drawing.Bitmap(1, 1)\n Dim iHeight As Integer = CInt(height * 0.393700787 * bmpImage.VerticalResolution) 'y DPI\n Dim iWidth As Integer = CInt(width * 0.393700787 * bmpImage.HorizontalResolution) 'x DPI\n\n bmpImage = New System.Drawing.Bitmap(bmpImage, New System.Drawing.Size(iWidth, iHeight))\n\n\n\n '// Create the Font object for the image text drawing.\n 'Dim MyFont As New System.Drawing.Font(\"Arial\", iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)\n '// Create a graphics object to measure the text's width and height.\n Dim MyGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmpImage)\n MyGraphics.Clear(bgColor)\n\n\n Dim stringFormat As New System.Drawing.StringFormat()\n stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical\n 'stringFormat.FormatFlags = System.Drawing.StringFormatFlags.DirectionVertical Or System.Drawing.StringFormatFlags.DirectionRightToLeft\n Dim solidBrush As New System.Drawing.SolidBrush(TextColor)\n Dim pointF As New System.Drawing.PointF(CSng(iWidth / 2 - iFontSize / 2 - 2), 5)\n Dim font As New System.Drawing.Font(fontFamily, iFontSize, fsFontStyle, System.Drawing.GraphicsUnit.Point)\n\n\n MyGraphics.TranslateTransform(bmpImage.Width, bmpImage.Height)\n MyGraphics.RotateTransform(180)\n MyGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault\n MyGraphics.DrawString(strText, font, solidBrush, pointF, stringFormat)\n MyGraphics.ResetTransform()\n\n MyGraphics.Flush()\n\n 'If Not bRotate Then\n 'bmpImage.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone)\n 'End If\n\n Return bmpImage\n End Function ' GenerateImage\n\n\n\n ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable\n Get\n Return False\n End Get\n End Property ' IsReusable\n\n\nEnd Class\n</code></pre>\n\n<p>Note that if you think that this part </p>\n\n<pre><code> Using msTempOutputStream As New System.IO.MemoryStream\n 'Dim img As System.Drawing.Image = GenerateImage(strText, \"Arial\", bRotate)\n Using img As System.Drawing.Image = CreateBitmapImage(strText, bRotate, strBGcolor)\n img.Save(msTempOutputStream, System.Drawing.Imaging.ImageFormat.Png)\n msTempOutputStream.Flush()\n\n context.Response.Buffer = True\n context.Response.ContentType = \"image/png\"\n context.Response.BinaryWrite(msTempOutputStream.ToArray())\n End Using ' img\n\n End Using ' msTempOutputStream\n</code></pre>\n\n<p>can be replaced with </p>\n\n<pre><code>img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png)\n</code></pre>\n\n<p>because it works on the development server, then you are sorely mistaken to assume the very same code wouldn't throw a Generic GDI+ exception if you deploy it to a Windows 2003 IIS 6 server...</p>\n\n<p>then use it like this:</p>\n\n<pre><code>&lt;img alt=\"bla\" src=\"GenerateImage.ashx?no_cache=123&amp;text=Hello%20World&amp;rotate=true\" /&gt;\n</code></pre>\n" }, { "answer_id": 24110160, "author": "Jeff Ancel", "author_id": 72947, "author_profile": "https://Stackoverflow.com/users/72947", "pm_score": 1, "selected": false, "text": "<p>I was using the Font Awesome library and was able to achieve this affect by tacking on the following to any html element. </p>\n\n<pre><code>&lt;div class=\"fa fa-rotate-270\"&gt;\n My Test Text\n&lt;/div&gt;\n</code></pre>\n\n<p>Your mileage may vary.</p>\n" }, { "answer_id": 24139529, "author": "James Nicholson", "author_id": 1356819, "author_profile": "https://Stackoverflow.com/users/1356819", "pm_score": 1, "selected": false, "text": "<p>Have a look at this, i found this while looking for a solution for IE 7. </p>\n\n<p>totally a cool solution for css only vibes</p>\n\n<p>Thanks aiboy for the soultion</p>\n\n<p><a href=\"https://gist.github.com/aiboy/7406727\" rel=\"nofollow noreferrer\" title=\"The link\">heres the link</a></p>\n\n<p>and here is the stack-overflow link where i came across this <a href=\"https://stackoverflow.com/questions/17286651/vertical-text-in-ie7-ie8-ie9-and-ie10-with-css-only\">link meow</a></p>\n\n<pre><code> .vertical-text-vibes{\n\n /* this is for shity \"non IE\" browsers\n that dosn't support writing-mode */\n -webkit-transform: translate(1.1em,0) rotate(90deg);\n -moz-transform: translate(1.1em,0) rotate(90deg);\n -o-transform: translate(1.1em,0) rotate(90deg);\n transform: translate(1.1em,0) rotate(90deg);\n -webkit-transform-origin: 0 0;\n -moz-transform-origin: 0 0;\n -o-transform-origin: 0 0;\n transform-origin: 0 0; \n /* IE9+ */ ms-transform: none; \n -ms-transform-origin: none; \n /* IE8+ */ -ms-writing-mode: tb-rl; \n /* IE7 and below */ *writing-mode: tb-rl;\n\n }\n</code></pre>\n" }, { "answer_id": 27258573, "author": "omardiaze", "author_id": 2984315, "author_profile": "https://Stackoverflow.com/users/2984315", "pm_score": 2, "selected": false, "text": "<p>My first contribution to the community , example as rotating a simple text and the header of a table, only using html and css.</p>\n\n<p><img src=\"https://i.stack.imgur.com/AYhIl.png\" alt=\"enter image description here\"></p>\n\n<p>HTML</p>\n\n<pre><code>&lt;div class=\"rotate\"&gt;text&lt;/div&gt;\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>.rotate {\n display:inline-block;\n filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n -webkit-transform: rotate(270deg);\n -ms-transform: rotate(270deg);\n transform: rotate(270deg);\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/omardiaze/a2uxgm44/\" rel=\"nofollow noreferrer\">Here an example in jsfiddle</a></p>\n" }, { "answer_id": 29625740, "author": "arkod", "author_id": 1506301, "author_profile": "https://Stackoverflow.com/users/1506301", "pm_score": 1, "selected": false, "text": "<p>Another solution:</p>\n\n<pre><code>(function () {\n\n var make_rotated_text = function (text)\n {\n var can = document.createElement ('canvas');\n can.width = 10;\n can.height = 10;\n var ctx=can.getContext (\"2d\");\n ctx.font=\"20px Verdana\";\n var m = ctx.measureText(text);\n can.width = 20;\n can.height = m.width;\n ctx.font=\"20px Verdana\";\n ctx.fillStyle = \"#000000\";\n ctx.rotate(90 * (Math.PI / 180));\n ctx.fillText (text, 0, -2);\n return can;\n };\n\n var canvas = make_rotated_text (\"Hellooooo :D\");\n var body = document.getElementsByTagName ('body')[0];\n body.appendChild (canvas);\n\n}) ();\n</code></pre>\n\n<p>I do absolutely admit that this is quite hackish, but it's a simple solution if you want to avoid bloating your css.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23813/" ]
Is there a (portable) way to rotate text in a HTML table cell by 90°? (I have a table with many columns and much text for the headings, so I'd like to write it vertically to save space.)
```css .box_rotate { -moz-transform: rotate(7.5deg); /* FF3.5+ */ -o-transform: rotate(7.5deg); /* Opera 10.5 */ -webkit-transform: rotate(7.5deg); /* Saf3.1+, Chrome */ filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */ -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */ } ``` ```html <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> <div class="box_rotate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> ``` Taken from <http://css3please.com/> As of 2017, the aforementioned site has simplified the rule set to drop legacy Internet Explorer filter and rely more in the now standard [`transform` property](https://developer.mozilla.org/en-US/docs/Web/CSS/transform): ```css .box_rotate { -webkit-transform: rotate(7.5deg); /* Chrome, Opera 15+, Safari 3.1+ */ -ms-transform: rotate(7.5deg); /* IE 9 */ transform: rotate(7.5deg); /* Firefox 16+, IE 10+, Opera */ } ``` ```html <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> <div class="box_rotate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vitae porta lectus. Suspendisse dolor mauris, scelerisque ut diam vitae, dictum ultricies est. Cras sit amet erat porttitor arcu lacinia ultricies. Morbi sodales, nisl vitae imperdiet consequat, purus nunc maximus nulla, et pharetra dolor ex non dolor.</div> ```
272,803
<p>I have an interesting problem and would appreciate your thoughts for the best solution. I need to parse a set of logs. The logs are produced by a multi-threaded program and a single process cycle produces several lines of logs.</p> <p>When parsing these logs I need to pull out specific pieces of information from each process - naturally this information is across the multiple lines (I want to compress these pieces of data into a single line). Due to the application being multi-threaded, the block of lines belonging to a process can be fragmented as other processes at written to the same log file at the same time.</p> <p>Fortunately, each line gives a process ID so I'm able to distinguish what logs belong to what process.</p> <p>Now, there are already several parsers which all extend the same class but were designed to read logs from a single threaded application (no fragmentation - from original system) and use a readLine() method in the super class. These parsers will keep reading lines until all regular expressions have been matched for a block of lines (i.e. lines written in a single process cycle).</p> <p>So, what can I do with the super class so that it can manage the fragmented logs, and ensure change to the existing implemented parsers is minimal?</p>
[ { "answer_id": 272834, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 0, "selected": false, "text": "<p>You need to store lines temporarily in a queue where a single thread consumes them and passes them on once each set has been completed. If you have no way of knowing the if a set is complete or not by either the number of lines or the content of the lines, you could consider using a sliding window technique where you don't collect the individual sets until after a certain time has passed.</p>\n" }, { "answer_id": 272972, "author": "Skip Head", "author_id": 23271, "author_profile": "https://Stackoverflow.com/users/23271", "pm_score": 0, "selected": false, "text": "<p>Would something like this do it? It runs a new Thread for each Process ID in the log file.</p>\n\n<pre><code>class Parser {\n String currentLine;\n Parser() {\n //Construct parser\n }\n synchronized String readLine(String processID) {\n if (currentLine == null)\n currentLine = readLinefromLog();\n\n while (currentline != null &amp;&amp; ! getProcessIdFromLine(currentLine).equals(processId)\n wait();\n\n String line = currentLine;\n currentLine = readLinefromLog();\n notify();\n return line;\n }\n}\n\nclass ProcessParser extends Parser implements Runnable{\n String processId;\n ProcessParser(String processId) {\n super();\n this.processId = processId;\n }\n\n void startParser() {\n new Thread(this).start();\n }\n\n public void run() {\n String line = null;\n while ((line = readLine()) != null) {\n // process log line here\n }\n }\n\n String readLine() {\n String line = super.readLine(processId);\n return line;\n } \n</code></pre>\n" }, { "answer_id": 273001, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 3, "selected": true, "text": "<p>It sounds like there are some existing parser classes already in use that you wish to leverage. In this scenario, I would write a <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">decorator</a> for the parser which strips out lines not associated with the process you are monitoring.</p>\n\n<p>It sounds like your classes might look like this:</p>\n\n<pre><code>abstract class Parser {\n public abstract void parse( ... );\n protected String readLine() { ... }\n}\n\nclass SpecialPurposeParser extends Parser {\n public void parse( ... ) { \n // ... special stuff\n readLine();\n // ... more stuff\n }\n}\n</code></pre>\n\n<p>And I would write something like:</p>\n\n<pre><code>class SingleProcessReadingDecorator extends Parser {\n private Parser parser;\n private String processId;\n public SingleProcessReadingDecorator( Parser parser, String processId ) {\n this.parser = parser;\n this.processId = processId;\n }\n\n public void parse( ... ) { parser.parse( ... ); }\n\n public String readLine() {\n String text = super.readLine();\n if( /*text is for processId */ ) { \n return text; \n }\n else {\n //keep readLine'ing until you find the next line and then return it\n return this.readLine();\n }\n }\n</code></pre>\n\n<p>Then any occurrence you want to modify would be used like this:</p>\n\n<pre><code>//old way\nParser parser = new SpecialPurposeParser();\n//changes to\nParser parser = new SingleProcessReadingDecorator( new SpecialPurposeParser(), \"process1234\" );\n</code></pre>\n\n<p>This code snippet is simple and incomplete, but gives you the idea of how the decorator pattern could work here.</p>\n" }, { "answer_id": 273324, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 0, "selected": false, "text": "<p>One simple solution could be to read the file line by line and write several files, one for each process id. The list of process id's can be kept in a hash-map in memory to determine if a new file is needed or in which already created file the lines for a certain process id will go. Once all the (temporary) files are written, the existing parsers can do the job on each one.</p>\n" }, { "answer_id": 273932, "author": "micro", "author_id": 23275, "author_profile": "https://Stackoverflow.com/users/23275", "pm_score": 1, "selected": false, "text": "<p>I would write a simple distributor that reads the log file line by line and stores them in different VirtualLog objects in memory -- a VirtualLog being a kind of virtual file, actually just a String or something that the existing parsers can be applied to. The VirtualLogs are stored in a Map with the process ID (PID) as the key. When you read a line from the log, check if the PID is already there. If so, add the line to the PID's respective VirtualLog. If not, create a new VirtualLog object and add it to the Map. Parsers run as separate Threads, one on every VirtualLog. Every VirtualLog object is destroyed as soon as it has been completely parsed. </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35033/" ]
I have an interesting problem and would appreciate your thoughts for the best solution. I need to parse a set of logs. The logs are produced by a multi-threaded program and a single process cycle produces several lines of logs. When parsing these logs I need to pull out specific pieces of information from each process - naturally this information is across the multiple lines (I want to compress these pieces of data into a single line). Due to the application being multi-threaded, the block of lines belonging to a process can be fragmented as other processes at written to the same log file at the same time. Fortunately, each line gives a process ID so I'm able to distinguish what logs belong to what process. Now, there are already several parsers which all extend the same class but were designed to read logs from a single threaded application (no fragmentation - from original system) and use a readLine() method in the super class. These parsers will keep reading lines until all regular expressions have been matched for a block of lines (i.e. lines written in a single process cycle). So, what can I do with the super class so that it can manage the fragmented logs, and ensure change to the existing implemented parsers is minimal?
It sounds like there are some existing parser classes already in use that you wish to leverage. In this scenario, I would write a [decorator](http://en.wikipedia.org/wiki/Decorator_pattern) for the parser which strips out lines not associated with the process you are monitoring. It sounds like your classes might look like this: ``` abstract class Parser { public abstract void parse( ... ); protected String readLine() { ... } } class SpecialPurposeParser extends Parser { public void parse( ... ) { // ... special stuff readLine(); // ... more stuff } } ``` And I would write something like: ``` class SingleProcessReadingDecorator extends Parser { private Parser parser; private String processId; public SingleProcessReadingDecorator( Parser parser, String processId ) { this.parser = parser; this.processId = processId; } public void parse( ... ) { parser.parse( ... ); } public String readLine() { String text = super.readLine(); if( /*text is for processId */ ) { return text; } else { //keep readLine'ing until you find the next line and then return it return this.readLine(); } } ``` Then any occurrence you want to modify would be used like this: ``` //old way Parser parser = new SpecialPurposeParser(); //changes to Parser parser = new SingleProcessReadingDecorator( new SpecialPurposeParser(), "process1234" ); ``` This code snippet is simple and incomplete, but gives you the idea of how the decorator pattern could work here.
272,818
<p>Does anyone know how I can get a list of products belonging to a specific category from within a view file in <a href="http://www.magentocommerce.com/" rel="noreferrer">Magento</a>?</p>
[ { "answer_id": 295987, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": false, "text": "<p>It all depends on which view you're in. ;-)</p>\n\n<p>First off, I hope you stayed within your template set (default in my example).</p>\n\n<p>Use this as an <strong>example</strong>:</p>\n\n<pre><code>&lt;?php\n$_cat = $this-&gt;getCurrentCategory();\n$_parent = $_cat-&gt;getParentCategory();\n$_categories = $_parent-&gt;getChildren();\n\n/* @var $category Mage_Catalog_Model_Category */\n$collection = Mage::getModel('catalog/category')-&gt;getCollection();\n/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */\n$collection-&gt;addAttributeToSelect('url_key')\n -&gt;addAttributeToSelect('name')\n -&gt;addAttributeToSelect('is_anchor')\n -&gt;addAttributeToFilter('is_active', 1)\n -&gt;addIdFilter($_categories)\n -&gt;setOrder('position', 'ASC')\n -&gt;joinUrlRewrite()\n -&gt;load();\n\n$productCollection = Mage::getResourceModel('catalog/product_collection');\n$layer = Mage::getSingleton('catalog/layer');\n$layer-&gt;prepareProductCollection($productCollection);\n$productCollection-&gt;addCountToCategories($collection);\n// $productCollection should be ready here ;-)\n?&gt;\n</code></pre>\n\n<p>I'm using the above code to display sister categories in my template - it's not ideal but it works.</p>\n\n<p>It's sort of a hack because I did not yet have time to learn all the layout XML madness. Otherwise if you use the XMLs you need to keep in mind - it all depends on where you are at. <strong>Where</strong> means the template file and essentially also the layout (in terms of app/design/frontend/default/default/layout/*).</p>\n\n<p>I know it's not much, but I hope it helps to get you started.</p>\n" }, { "answer_id": 5536921, "author": "Mukesh Chapagain", "author_id": 327862, "author_profile": "https://Stackoverflow.com/users/327862", "pm_score": 3, "selected": false, "text": "<p>Here is the code to get products from any particular category. You can use this in view file as well.</p>\n\n<pre><code>// if you want to display products from current category\n$category = Mage::registry('current_category'); \n\n// if you want to display products from any specific category\n$categoryId = 10;\n$category = Mage::getModel('catalog/category')-&gt;load($categoryId);\n\n$productCollection = Mage::getResourceModel('catalog/product_collection')\n -&gt;addCategoryFilter($category);\n\n// printing products name\nforeach ($productCollection as $product) {\n echo $product-&gt;getName(); \n echo \"&lt;br /&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 5566694, "author": "mivec", "author_id": 377395, "author_profile": "https://Stackoverflow.com/users/377395", "pm_score": 4, "selected": false, "text": "<p>You can use magento object to filter.</p>\n\n<p>Example:</p>\n\n<pre><code>$categoryId = 123; // a category id that you can get from admin\n$category = Mage::getModel('catalog/category')-&gt;load($categoryId);\n\n$products = Mage::getModel('catalog/product')\n -&gt;getCollection()\n -&gt;addCategoryFilter($category)\n -&gt;load();\n\nprint_r($products);\n</code></pre>\n" }, { "answer_id": 10549635, "author": "Andrew", "author_id": 1185624, "author_profile": "https://Stackoverflow.com/users/1185624", "pm_score": 0, "selected": false, "text": "<p>You should always avoid putting code like this into a view, it's very bad practice. \nYou can also run into issues as views can be cached, leading to unexpected behaviour.</p>\n\n<p>you should override the block you are using, placing code there. you can then call any new methods inside your view files.</p>\n\n<p>for example, you could copy Mage_Catalog_Block_Product_List </p>\n\n<p>from: app/code/core/Catalog/Block/Product/List.php </p>\n\n<p>to: app/code/local/Catalog/Block/Product/List.php </p>\n\n<p>you could then add a new method, possibly using some of the code mentioned in the above posts.\nyour new method would then be available inside your view file (list.phtml or any view using this block)</p>\n" }, { "answer_id": 11394926, "author": "Raheel Hasan", "author_id": 1093486, "author_profile": "https://Stackoverflow.com/users/1093486", "pm_score": 2, "selected": false, "text": "<p>I pretty much needed the same. Here is how I have done it:</p>\n\n<pre><code>$prod_whole = array();\nif(!empty($_menu)) //$_menu = array of Categories with some basic info\nforeach($_menu as $v)\n{\n if($v['name']=='HOME')\n continue;\n\n $cat_id = $v['id'];\n\n #/ Setup Products\n $category = Mage::getModel('catalog/category')-&gt;load($cat_id);\n\n $collection = Mage::getModel('catalog/product')-&gt;getCollection()\n -&gt;addAttributeToSelect('*') // select all attributes\n -&gt;addCategoryFilter($category)\n -&gt;setPageSize(8) // limit number of results returned\n -&gt;setCurPage(0)\n -&gt;load()\n ;\n\n\n $prod_collection = array();\n foreach ($collection as $product)\n {\n $prod_collection_1 = array();\n\n #/ Basic Info\n $prod_collection_1['id'] = $product-&gt;getId();\n $prod_collection_1['name'] = $product-&gt;getName();\n $prod_collection_1['price'] = (float) $product-&gt;getPrice();\n //$prod_collection_1['desc'] = $product-&gt;getDescription();\n //$prod_collection_1['short'] = $product-&gt;getShortDescription();\n $prod_collection_1['type'] = $product-&gt;getTypeId();\n $prod_collection_1['status'] = $product-&gt;getStatus();\n $prod_collection_1['special_price'] = $product-&gt;getSpecialPrice();\n $prod_collection_1['direct_url'] = $product-&gt;getProductUrl();\n\n\n #/ getCategoryIds(); returns an array of category IDs associated with the product\n foreach ($product-&gt;getCategoryIds() as $category_id)\n {\n $category = Mage::getModel('catalog/category')-&gt;load($category_id);\n $prod_collection_1['parent_category'] = $category-&gt;getParentCategory()-&gt;getName();\n $prod_collection_1['category'] = $category-&gt;getName();\n //$prod_collection_1['category_idx'] = preg_replace('/[\\s\\'\\\"]/i', '_', strtolower(trim($prod_collection_1['category'])));\n $prod_collection_1['category_id'] = $category-&gt;getId();\n }\n\n #/gets the image url of the product\n $prod_collection_1['img'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product-&gt;getImage();\n\n\n $prod_collection[] = $prod_collection_1;\n\n }//end foreach.....\n\n $prod_whole[$cat_id] = $prod_collection;\n\n}//end foreach categories.......\n//var_dump('&lt;pre&gt;', $prod_whole);\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 16413619, "author": "Chiragit007", "author_id": 2010505, "author_profile": "https://Stackoverflow.com/users/2010505", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;?php\n\n $category_id = 10; // if you know static category then enter number\n\n$catagory_model = Mage::getModel('catalog/category')-&gt;load($category_id); //where $category_id is the id of the category\n\n\n\n $collection = Mage::getResourceModel('catalog/product_collection');\n\n $collection-&gt;addCategoryFilter($catagory_model); //category filter\n\n $collection-&gt;addAttributeToFilter('status',1); //only enabled product\n\n $collection-&gt;addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched\n\n //$collection-&gt;getSelect()-&gt;order('rand()'); //uncomment to get products in random order \n\n $collection-&gt;addStoreFilter(); \n\n if(!empty($collection))\n\n {\n\n foreach ($collection as $_product):\n\n echo $_product-&gt;getName(); //get product name \n\n endforeach;\n\n }else\n\n {\n\n echo 'No products exists';\n\n } \n\n ?&gt;\n</code></pre>\n" }, { "answer_id": 17717089, "author": "Jatin Soni", "author_id": 2594374, "author_profile": "https://Stackoverflow.com/users/2594374", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;?php\n$c_id = 2;\n$category = new Mage_Catalog_Model_Category();\n$category-&gt;load($c_id);\n$collection = $category-&gt;getProductCollection();\n$collection-&gt;addAttributeToSelect('*');\nforeach ($collection as $_product) { ?&gt;\n&lt;a href=\"&lt;?php echo $_product-&gt;getProductUrl(); ?&gt;\"&gt;&lt;?php echo $_product-&gt;getName(); ?&gt;&lt;/a&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" }, { "answer_id": 49813389, "author": "Shorabh", "author_id": 4070360, "author_profile": "https://Stackoverflow.com/users/4070360", "pm_score": 0, "selected": false, "text": "<p>Here is a code to export all product with it's category into csv </p>\n\n<pre><code>&lt;?php \nset_time_limit(0);\nini_set(\"memory_limit\",-1);\nini_set('max_execution_time','1800000000');\n\nrequire_once '../app/Mage.php';\nMage::app(); \n\n$category = Mage::getModel('catalog/category');\n$tree = $category-&gt;getTreeModel();\n$tree-&gt;load();\n\n$ids = $tree-&gt;getCollection()-&gt;getAllIds();\n$fp = fopen('category-product-export.csv', 'w');\n$field = array('Product SKU','Category Name'); \nfputcsv($fp, $field);\n\n$_productCollection = Mage::getModel('catalog/product')\n -&gt;getCollection()\n -&gt;addAttributeToSelect('*')\n -&gt;addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)\n -&gt;load();\n\nforeach ($_productCollection as $_product){\n $cats = $_product-&gt;getCategoryIds();\n $cnt = 0;\n $catName = '';\n foreach($cats as $id) {\n $category-&gt;load($id);\n $root = 'Root Catalog';\n $isRoot = strtolower($root);\n $categoryName = strtolower($category-&gt;getName());\n if($categoryName == $isRoot){\n continue;\n }\n $categories[$id]['name'] = $category-&gt;getName();\n $categories[$id]['path'] = $category-&gt;getPath();\n\n $path = explode('/', $categories[$id]['path']);\n $len = count($path);\n $string = '';\n if($id &gt; 2){\n foreach ($path as $k=&gt;$pathId)\n {\n $separator = '';\n if($pathId &gt; 2){\n $category-&gt;load($pathId);\n if($k != $len-1){ $separator = ' || ';}\n $string.= $category-&gt;getName() . $separator;\n }\n\n }\n if($cnt &gt; 0) {\n $catName.= ','.$string;\n } else {\n $catName = $string;\n }\n\n $cnt++;\n }\n }\n //echo $catName;\n $field = array($_product-&gt;getSku(),$catName); \n fputcsv($fp, $field); \n\n} \n\n?&gt;\n&lt;a href=\"category-product-export.csv\"&gt;Download&lt;/a&gt;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anyone know how I can get a list of products belonging to a specific category from within a view file in [Magento](http://www.magentocommerce.com/)?
You can use magento object to filter. Example: ``` $categoryId = 123; // a category id that you can get from admin $category = Mage::getModel('catalog/category')->load($categoryId); $products = Mage::getModel('catalog/product') ->getCollection() ->addCategoryFilter($category) ->load(); print_r($products); ```
272,826
<p>I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP.</p> <p>I've tried the following functions:</p> <ul> <li>system</li> <li>passthru</li> <li>exec</li> <li>shell_exec</li> </ul> <p>example:</p> <pre><code>system('mysql -u root -pxxxx db_name'); </code></pre> <p>But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?</p>
[ { "answer_id": 272845, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "<p>Give MySQL a script to run that's separate from the PHP script:</p>\n\n<pre><code>system('mysql -u root -pxxxx db_name &lt; script.mysql');\n</code></pre>\n" }, { "answer_id": 272894, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 0, "selected": false, "text": "<p>In addition to what acrosman said, you can also use the <code>-e</code> switch to pass SQL from the command line.</p>\n\n<pre><code>$sql = \".....\";\nsystem(\"mysql -u root -pxxxx db_name -e \\\"$sql\\\"\");\n</code></pre>\n\n<p>Also, I hope your not actually connecting to the database as root from a PHP application.</p>\n" }, { "answer_id": 273992, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 3, "selected": true, "text": "<p>If you want shell commands to be interactive, use:</p>\n\n<pre><code>system(\"mysql -uroot -p db_name &gt; `tty`\");\n</code></pre>\n\n<p>That will work for most cases, but will break if you aren't in a terminal.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261/" ]
I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP. I've tried the following functions: * system * passthru * exec * shell\_exec example: ``` system('mysql -u root -pxxxx db_name'); ``` But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?
If you want shell commands to be interactive, use: ``` system("mysql -uroot -p db_name > `tty`"); ``` That will work for most cases, but will break if you aren't in a terminal.
272,876
<blockquote> <p>char *strtok(char *s1, const char *s2)</p> <p>repeated calls to this function break string s1 into "tokens"--that is the string is broken into substrings, each terminating with a '\0', where the '\0' replaces any characters contained in string s2. The first call uses the string to be tokenized as s1; subsequent calls use NULL as the first argument. A pointer to the beginning of the current token is returned; NULL is returned if there are no more tokens.</p> </blockquote> <p>Hi, </p> <p>I have been trying to use <code>strtok</code> just now and found out that if I pass in a <code>char*</code> into <code>s1</code>, I get a segmentation fault. If I pass in a <code>char[]</code>, <code>strtok</code> works fine. </p> <p>Why is this?</p> <p>I googled around and the reason seems to be something about how <code>char*</code> is read only and <code>char[]</code> is writeable. A more thorough explanation would be much appreciated.</p>
[ { "answer_id": 272904, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 5, "selected": true, "text": "<p>What did you initialize the <code>char *</code> to?</p>\n\n<p>If something like</p>\n\n<pre><code>char *text = \"foobar\";\n</code></pre>\n\n<p>then you have a pointer to some read-only characters</p>\n\n<p>For </p>\n\n<pre><code>char text[7] = \"foobar\";\n</code></pre>\n\n<p>then you have a seven element array of characters that you can do what you like with.</p>\n\n<p><code>strtok</code> writes into the string you give it - overwriting the separator character with <code>null</code> and keeping a pointer to the rest of the string.</p>\n\n<p>Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.</p>\n\n<p>Also, becasue <code>strtok</code> keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here: <a href=\"http://www.rt.com/man/strsep.3.html\" rel=\"nofollow noreferrer\">http://www.rt.com/man/strsep.3.html</a> (although that still writes into the string so has the same read-only/segfault issue)</p>\n" }, { "answer_id": 273347, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>I blame the C standard.</p>\n\n<pre><code>char *s = \"abc\";\n</code></pre>\n\n<p>could have been defined to give the same error as</p>\n\n<pre><code>const char *cs = \"abc\";\nchar *s = cs;\n</code></pre>\n\n<p>on grounds that string literals are unmodifiable. But it wasn't, it was defined to compile. Go figure. [Edit: Mike B has gone figured - \"const\" didn't exist at all in K&amp;R C. ISO C, plus every version of C and C++ since, has wanted to be backward-compatible. So it has to be valid.]</p>\n\n<p>If it had been defined to give an error, then you couldn't have got as far as the segfault, because strtok's first parameter is char*, so the compiler would have prevented you passing in the pointer generated from the literal.</p>\n\n<p>It may be of interest that there was at one time a plan in C++ for this to be deprecated (<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1996/N0896.asc\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1996/N0896.asc</a>). But 12 years later I can't persuade either gcc or g++ to give me any kind of warning for assigning a literal to non-const char*, so it isn't all that loudly deprecated.</p>\n\n<p>[Edit: aha: -Wwrite-strings, which isn't included in -Wall or -Wextra]</p>\n" }, { "answer_id": 275077, "author": "Jason L", "author_id": 35616, "author_profile": "https://Stackoverflow.com/users/35616", "pm_score": 3, "selected": false, "text": "<p>An important point that's inferred but not stated explicitly:</p>\n\n<p>Based on your question, I'm guessing that you're fairly new to programming in C, so I'd like to explain a little more about your situation. Forgive me if I'm mistaken; C can be hard to learn mostly because of subtle misunderstanding in underlying mechanisms so I like to make things as plain as possible.</p>\n\n<p>As you know, when you write out your C program the compiler pre-creates everything for you based on the syntax. When you declare a variable anywhere in your code, e.g.:</p>\n\n<p><code>int x = 0;</code></p>\n\n<p>The compiler reads this line of text and says to itself: OK, I need to replace all occurrences in the current code scope of <code>x</code> with a constant reference to a region of memory I've allocated to hold an integer.</p>\n\n<p>When your program is run, this line leads to a new action: I need to set the region of memory that <code>x</code> references to <code>int</code> value <code>0</code>.</p>\n\n<p>Note the subtle difference here: the memory location that reference point <code>x</code> holds is constant (and cannot be changed). However, the value that <code>x</code> points can be changed. You do it in your code through assignment, e.g. <code>x = 15;</code>. Also note that the single line of code actually amounts to two separate commands to the compiler.</p>\n\n<p>When you have a statement like:</p>\n\n<p><code>char *name = \"Tom\";</code></p>\n\n<p>The compiler's process is like this: OK, I need to replace all occurrences in the current code scope of <code>name</code> with a constant reference to a region of memory I've allocated to hold a <code>char</code> pointer value. And it does so.</p>\n\n<p>But there's that second step, which amounts to this: I need to create a constant array of characters which holds the values 'T', 'o', 'm', and <code>NULL</code>. Then I need to replace the part of the code which says <code>\"Tom\"</code> with the memory address of that constant string.</p>\n\n<p>When your program is run, the final step occurs: setting the pointer to <code>char</code>'s value (which isn't constant) to the memory address of that automatically created string (which <em>is</em> constant).</p>\n\n<p>So a <code>char *</code> is not read-only. Only a <code>const char *</code> is read-only. But your problem in this case isn't that <code>char *</code>s are read-only, it's that your pointer references a read-only regions of memory.</p>\n\n<p>I bring all this up because understanding this issue is the barrier between you looking at the definition of that function from the library and understanding the issue yourself versus having to ask us. And I've somewhat simplified some of the details in the hopes of making the issue more understandable.</p>\n\n<p>I hope this was helpful. ;)</p>\n" }, { "answer_id": 571863, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In brief:</p>\n\n<pre><code>char *s = \"HAPPY DAY\";\nprintf(\"\\n %s \", s);\n\ns = \"NEW YEAR\"; /* Valid */\nprintf(\"\\n %s \", s);\n\ns[0] = 'c'; /* Invalid */\n</code></pre>\n" }, { "answer_id": 571917, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>If you look at your compiler documentation, odds are there is a option you can set to make those strings writable.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14520/" ]
> > char \*strtok(char \*s1, const char \*s2) > > > repeated calls to this function break string s1 into "tokens"--that is > the string is broken into substrings, > each terminating with a '\0', where > the '\0' replaces any characters > contained in string s2. The first call > uses the string to be tokenized as s1; > subsequent calls use NULL as the first > argument. A pointer to the beginning > of the current token is returned; NULL > is returned if there are no more > tokens. > > > Hi, I have been trying to use `strtok` just now and found out that if I pass in a `char*` into `s1`, I get a segmentation fault. If I pass in a `char[]`, `strtok` works fine. Why is this? I googled around and the reason seems to be something about how `char*` is read only and `char[]` is writeable. A more thorough explanation would be much appreciated.
What did you initialize the `char *` to? If something like ``` char *text = "foobar"; ``` then you have a pointer to some read-only characters For ``` char text[7] = "foobar"; ``` then you have a seven element array of characters that you can do what you like with. `strtok` writes into the string you give it - overwriting the separator character with `null` and keeping a pointer to the rest of the string. Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault. Also, becasue `strtok` keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here: <http://www.rt.com/man/strsep.3.html> (although that still writes into the string so has the same read-only/segfault issue)
272,900
<p>Can anyone explain why following code won't compile? At least on g++ 4.2.4.</p> <p>And more interesting, why it will compile when I cast MEMBER to int?</p> <pre><code>#include &lt;vector&gt; class Foo { public: static const int MEMBER = 1; }; int main(){ vector&lt;int&gt; v; v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER' v.push_back( (int) Foo::MEMBER ); // OK return 0; } </code></pre>
[ { "answer_id": 272965, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 9, "selected": true, "text": "<p>You need to actually define the static member somewhere (after the class definition). Try this:</p>\n\n<pre><code>class Foo { /* ... */ };\n\nconst int Foo::MEMBER;\n\nint main() { /* ... */ }\n</code></pre>\n\n<p>That should get rid of the undefined reference.</p>\n" }, { "answer_id": 272982, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 6, "selected": false, "text": "<p>The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the <code>push_back</code> signature:</p>\n\n<pre><code>void push_back(const T&amp;)\n</code></pre>\n\n<p>It's expecting a reference to an object of type <code>T</code>. Under the old system of initialization, such a member exists. For example, the following code compiles just fine:</p>\n\n<pre><code>#include &lt;vector&gt;\n\nclass Foo {\npublic:\n static const int MEMBER;\n};\n\nconst int Foo::MEMBER = 1; \n\nint main(){\n std::vector&lt;int&gt; v;\n v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'\n v.push_back( (int) Foo::MEMBER ); // OK \n return 0;\n}\n</code></pre>\n\n<p>This is because there is an actual object somewhere that has that value stored in it. If, however, you switch to the new method of specifying static const members, like you have above, <code>Foo::MEMBER</code> is no longer an object. It is a constant, somewhat akin to:</p>\n\n<pre><code>#define MEMBER 1\n</code></pre>\n\n<p>But without the headaches of a preprocessor macro (and with type safety). That means that the vector, which is expecting a reference, can't get one.</p>\n" }, { "answer_id": 272986, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>No idea why the cast works, but Foo::MEMBER isn't allocated until the first time Foo is loaded, and since you're never loading it, it's never allocated. If you had a reference to a Foo somewhere, it would probably work.</p>\n" }, { "answer_id": 272996, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 6, "selected": false, "text": "<p>The C++ standard requires a definition for your static const member if the definition is somehow needed. </p>\n\n<p>The definition is required, for example if it's address is used. <code>push_back</code> takes its parameter by const reference, and so strictly the compiler needs the address of your member and you need to define it in the namespace.</p>\n\n<p>When you explicitly cast the constant, you're creating a temporary and it's this temporary which is bound to the reference (under special rules in the standard).</p>\n\n<p>This is a really interesting case, and I actually think it's worth raising an issue so that the std be changed to have the same behaviour for your constant member!</p>\n\n<p>Although, in a weird kind of way this could be seen as a legitimate use of the unary '+' operator. Basically the result of the <code>unary +</code> is an rvalue and so the rules for binding of rvalues to const references apply and we don't use the address of our static const member:</p>\n\n<pre><code>v.push_back( +Foo::MEMBER );\n</code></pre>\n" }, { "answer_id": 13698802, "author": "iso9660", "author_id": 1184922, "author_profile": "https://Stackoverflow.com/users/1184922", "pm_score": 3, "selected": false, "text": "<p><strong>Aaa.h</strong></p>\n\n<pre><code>class Aaa {\n\nprotected:\n\n static Aaa *defaultAaa;\n\n};\n</code></pre>\n\n<p><strong>Aaa.cpp</strong></p>\n\n<pre><code>// You must define an actual variable in your program for the static members of the classes\n\nstatic Aaa *Aaa::defaultAaa;\n</code></pre>\n" }, { "answer_id": 24825377, "author": "Quarra", "author_id": 1076113, "author_profile": "https://Stackoverflow.com/users/1076113", "pm_score": 0, "selected": false, "text": "<p>Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.</p>\n\n<p>Or at least my colleague who resolved this said so.</p>\n" }, { "answer_id": 37916521, "author": "starturtle", "author_id": 1864036, "author_profile": "https://Stackoverflow.com/users/1864036", "pm_score": 1, "selected": false, "text": "<p>With C++11, the above would be possible for basic types as</p>\n\n<pre><code>class Foo {\npublic: \n static constexpr int MEMBER = 1; \n};\n</code></pre>\n\n<p>The <code>constexpr</code> part creates a static <em>expression</em> as opposed to a static <em>variable</em> - and that behaves just like an extremely simple inline method definition. The approach proved a bit wobbly with C-string constexprs inside template classes, though. </p>\n" }, { "answer_id": 66569786, "author": "Quimby", "author_id": 7691729, "author_profile": "https://Stackoverflow.com/users/7691729", "pm_score": 3, "selected": false, "text": "<p>In C++17, there is an easier solution using <code>inline</code> variables:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Foo{\n inline static int member;\n};\n</code></pre>\n<p>This is a definition of <code>member</code>, not just its declaration. Similar to inline functions, multiple identical definitions in different translation units do not violate ODR. There is no longer any need to pick a favourite .cpp file for the definition.</p>\n" }, { "answer_id": 69239673, "author": "Marc", "author_id": 3832484, "author_profile": "https://Stackoverflow.com/users/3832484", "pm_score": 2, "selected": false, "text": "<p>Just some additional info:</p>\n<p>C++ allows to &quot;define&quot; const static types of integral and enumeration types as class members. But this is actually not a definition, just an &quot;initializiation-marker&quot;</p>\n<p>You should still write a definition of your member outside of the class.</p>\n<blockquote>\n<p>9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.</p>\n</blockquote>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35281/" ]
Can anyone explain why following code won't compile? At least on g++ 4.2.4. And more interesting, why it will compile when I cast MEMBER to int? ``` #include <vector> class Foo { public: static const int MEMBER = 1; }; int main(){ vector<int> v; v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER' v.push_back( (int) Foo::MEMBER ); // OK return 0; } ```
You need to actually define the static member somewhere (after the class definition). Try this: ``` class Foo { /* ... */ }; const int Foo::MEMBER; int main() { /* ... */ } ``` That should get rid of the undefined reference.
272,908
<p>I'm trying to install RSpec as a gem after having it installed as a plugin. I've gone ahead and followed the directions found here <a href="http://github.com/dchelimsky/rspec-rails/wikis" rel="noreferrer">http://github.com/dchelimsky/rspec-rails/wikis</a> for the section titled <strong>rspec and rspec-rails gems</strong>. When I run <code>ruby script/generate rspec</code>, I get the error <code>Couldn't find 'rspec' generator</code>. Do only the plugins work? If so, why do they even offer the gems for rspec and rspec-rails? I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11.</p> <p>EDIT Nov 12, 2008 I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.</p>
[ { "answer_id": 273526, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 1, "selected": false, "text": "<p>Is there supposed to be an 'rspec' generator? I've only used the following:</p>\n\n<pre><code>script/generate rspec_model mymodel\nscript/generate rspec_controller mycontroller\n</code></pre>\n" }, { "answer_id": 273936, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 3, "selected": false, "text": "<p>Have you installed both rspec and rspec-rails gems?</p>\n\n<pre><code>script/generate rspec\n</code></pre>\n\n<p>requires rspec-rails gem to be installed.</p>\n" }, { "answer_id": 405143, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 1, "selected": false, "text": "<p>I've had this problem before, it boiled down to the version of RSpec I had not working with the version of Rails I was using. IIRC it was a 2.1 Rails and the updated RSpec hadn't been released as a gem. In fact, 1.1.11 is the gem I have, which would be the latest available (ignoring github gems), so I'm pretty sure that's exactly what my problem was.</p>\n\n<p>I've taken to just using the head of master rspec with whatever version of Rails I happen to be on, it seems stable to me (and isn't going to break things in production, unless somehow a test broke with a false positive).</p>\n\n<p>I do it with git using submodules, for example:</p>\n\n<pre><code>git submodule add git://github.com/dchelimsky/rspec.git vendor/plugins/rspec\ngit submodule add git://github.com/dchelimsky/rspec-rails.git vendor/plugins/rspec_on_rails\n</code></pre>\n" }, { "answer_id": 902009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>On Fedora 9 (OLPC) I did:</p>\n\n<pre><code>$ sudo gem install rspec\n\n$ sudo gem install rspec-rails \n</code></pre>\n\n<p>Those got me to where I could run</p>\n\n<pre><code>$ ruby script/generate rspec\n</code></pre>\n\n<p>This worked for me, whereas the git instructions did not work.</p>\n" }, { "answer_id": 2445165, "author": "makuchaku", "author_id": 184078, "author_profile": "https://Stackoverflow.com/users/184078", "pm_score": -1, "selected": false, "text": "<p>You'll need to do</p>\n\n<pre><code>sudo gem install cucumber-rails\n</code></pre>\n" }, { "answer_id": 3800367, "author": "inger", "author_id": 174284, "author_profile": "https://Stackoverflow.com/users/174284", "pm_score": 1, "selected": false, "text": "<p>In case anyone is wondering about Rails 3 now,\nthis seems to do the trick for me:\n<a href=\"http://github.com/rspec/rspec-rails/blob/29817932b99fc45adaa93c3f75d503c69aafcaef/README.markdown\" rel=\"nofollow\">http://github.com/rspec/rspec-rails/blob/29817932b99fc45adaa93c3f75d503c69aafcaef/README.markdown</a></p>\n" }, { "answer_id": 4479718, "author": "Moiz Raja", "author_id": 420504, "author_profile": "https://Stackoverflow.com/users/420504", "pm_score": 1, "selected": false, "text": "<p>I'm using rails 2.3.9. I started of trying to use the gem(s) but just couldn't get the generator for rspec to show up. Then I installed the plugin(s) using the instructions on <a href=\"https://github.com/dchelimsky/rspec/wiki/rails\" rel=\"nofollow\">https://github.com/dchelimsky/rspec/wiki/rails</a> and that did the trick. </p>\n" }, { "answer_id": 4767258, "author": "Overbryd", "author_id": 128351, "author_profile": "https://Stackoverflow.com/users/128351", "pm_score": 0, "selected": false, "text": "<p>If you are using bundler version 1.0.8 you should <code>$ gem update bundler</code> to a newer version 1.0.9.</p>\n\n<p>I had the same symptons and updating bundler helped me out.\nNow <code>$ rails g</code> is using gems defined in the Gemfile. Also I grouped my gems like this:</p>\n\n<pre><code>source 'http://rubygems.org'\n\ngem 'rails', '3.0.3'\ngem 'sqlite3-ruby', :require =&gt; 'sqlite3'\n\ngroup :test, :development do\n gem 'capybara', '0.4.1.1'\n gem 'database_cleaner'\n gem 'cucumber-rails'\n gem 'rspec-rails', '~&gt; 2.4'\n gem 'launchy'\nend\n</code></pre>\n\n<p>(Note that test gems are also in the <code>:development</code> group.)</p>\n\n<p>Have a nice day :)</p>\n\n<p>Lukas</p>\n" }, { "answer_id": 6098841, "author": "user766202", "author_id": 766202, "author_profile": "https://Stackoverflow.com/users/766202", "pm_score": 2, "selected": false, "text": "<p>For Rails 3 and rspec 2+\nYou must make sure you include 'rspec' and rspec-rails' in your Gemfile\nRun Bundle Install\nthen run rails g rspec:install</p>\n" }, { "answer_id": 6189374, "author": "Peter Nixey", "author_id": 400790, "author_profile": "https://Stackoverflow.com/users/400790", "pm_score": 3, "selected": false, "text": "<p>Since RSpec has been become the default testing framework in Rails you no longer need to create spec docs via the rspec generators:</p>\n\n<p><strong>Rails 2 RSpec generator</strong></p>\n\n<pre><code> rails generate rspec_model mymodel\n</code></pre>\n\n<p><strong>Rails 3 RSpec generator</strong></p>\n\n<p>With RSpec as the default testing framework simply use Rails' own generators. This will construct all of the files you need including the RSpec tests. e.g.</p>\n\n<pre><code> $rails generate model mymodel\n invoke active_record\n create db/migrate/20110531144454_create_mymodels.rb\n create app/models/mymodel.rb\n invoke rspec\n create spec/models/mymodel_spec.rb\n</code></pre>\n" }, { "answer_id": 7597973, "author": "pedroconsuegrat", "author_id": 644729, "author_profile": "https://Stackoverflow.com/users/644729", "pm_score": 2, "selected": false, "text": "<p>If you are using rails 2.3 You need to use</p>\n\n<p>ruby script/plugin install git://github.com/dchelimsky/rspec-rails.git -r 'refs/tags/1.3.3'</p>\n\n<p>and then</p>\n\n<p>ruby script/generate rspec</p>\n" }, { "answer_id": 10449182, "author": "Trip", "author_id": 93311, "author_profile": "https://Stackoverflow.com/users/93311", "pm_score": -1, "selected": false, "text": "<p>You might need to run bundle exec :</p>\n\n<pre><code>bundle exec rails g rspec:install\n</code></pre>\n" }, { "answer_id": 13426843, "author": "Dan K.K.", "author_id": 1040889, "author_profile": "https://Stackoverflow.com/users/1040889", "pm_score": 0, "selected": false, "text": "<p>If you type <code>script/rails generate</code>, the only <em>RSpec</em> generator you'll actually see is <code>rspec:install</code>. That's because <em>RSpec</em> is registered with <em>Rails</em> as the test framework, so whenever you generate application components like models, controllers, etc, <em>RSpec</em> specs are generated instead of <code>Test::Unit</code> tests.</p>\n\n<p>Please note that the generators are there to help you get started, but they are no substitute for writing your own examples, and they are only guaranteed to work out of the box for the default scenario (<em>ActiveRecord</em> &amp; <em>Webrat</em>).</p>\n\n<p><a href=\"https://github.com/rspec/rspec-rails\" rel=\"nofollow\">https://github.com/rspec/rspec-rails</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35564/" ]
I'm trying to install RSpec as a gem after having it installed as a plugin. I've gone ahead and followed the directions found here <http://github.com/dchelimsky/rspec-rails/wikis> for the section titled **rspec and rspec-rails gems**. When I run `ruby script/generate rspec`, I get the error `Couldn't find 'rspec' generator`. Do only the plugins work? If so, why do they even offer the gems for rspec and rspec-rails? I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11. EDIT Nov 12, 2008 I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.
Have you installed both rspec and rspec-rails gems? ``` script/generate rspec ``` requires rspec-rails gem to be installed.
272,910
<p>When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.</p> <pre><code>try { URL url = new URL("http://foo.bar"); URLConnection conn = url.openConnection(); // use the connection } catch (Exception e) { // any clean up here? } </code></pre>
[ { "answer_id": 272918, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 7, "selected": true, "text": "<p>It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do.</p>\n\n<p>From the javadoc for java.net.URLConnection</p>\n\n<blockquote>\n <p>Invoking the close() methods on the\n InputStream or OutputStream of an\n URLConnection after a request may free\n network resources associated with this\n instance, unless particular protocol\n specifications specify different\n behaviours for it.</p>\n</blockquote>\n" }, { "answer_id": 272947, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 6, "selected": false, "text": "<p>If you cast to an HttpURLConnection, there is a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#disconnect()\" rel=\"noreferrer\">disconnect()</a> method. If the connection is idle, it will probably disconnect immediately. No guarantees.</p>\n" }, { "answer_id": 70305155, "author": "Artem Mostyaev", "author_id": 1219012, "author_profile": "https://Stackoverflow.com/users/1219012", "pm_score": 0, "selected": false, "text": "<p>I had to download several hunders of files at a time and meet the problem.</p>\n<p>You may check your app's open descriptors with the following command:</p>\n<pre><code>adb shell ps\n</code></pre>\n<p>Find your application PID in the list and use another command:</p>\n<pre><code>adb shell run-as YOUR_PACKAGE_NAME ls -l /proc/YOUR_PID/fd\n</code></pre>\n<p>I see about 150 open descriptors on a usual launch. And there are 700+ when files are downloading. Their number decreases only after some minutes, looks like Android frees them in the background, not when you can <code>close</code> on a stream.</p>\n<p>So we can't be sure when the connection closes actually.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14481/" ]
When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler. ``` try { URL url = new URL("http://foo.bar"); URLConnection conn = url.openConnection(); // use the connection } catch (Exception e) { // any clean up here? } ```
It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do. From the javadoc for java.net.URLConnection > > Invoking the close() methods on the > InputStream or OutputStream of an > URLConnection after a request may free > network resources associated with this > instance, unless particular protocol > specifications specify different > behaviours for it. > > >
272,928
<p>I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.</p> <p>How and where shoud I be doing this? Should I be doing it before Page_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all?</p> <pre><code> namespace CloudNavigation { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { // how can I re-generate the button and hook up the event here // without executing heavy search 1 } else { // Execute heavy search 1 to generate buttons Button b = new Button(); b.Text = "Selection 1"; b.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b); } } void b_Command(object sender, CommandEventArgs e) { // Execute heavy search 2 to generate new buttons Button b2 = new Button(); b2.Text = "Selection 2"; b2.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b2); } } } </code></pre>
[ { "answer_id": 272992, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "<p>Does your ASPX have the event handler wired up?</p>\n\n<pre><code>&lt;asp:Button id=\"btnCommand\" runat=\"server\" onClick=\"b_Command\" text=\"Submit\" /&gt;\n</code></pre>\n" }, { "answer_id": 273011, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>The buttons need to be created <em>before</em> the load event, or state won't be wired up correctly. Re-create your buttons in Init() instead.</p>\n\n<p>As for how to do this without re-running the search, I suggest you cache the results somewhere. The existence of a result set in the cache is how your button code in the Init() event will know it needs to run.</p>\n\n<p>Alternatively, you could place the buttons on the page statically. Just put enough there to handle whatever the search returns. If you're thinking that maybe that would be <em>way</em> too many items, then ask your self this: will your users really want to sort through that many items? Maybe you should consider paging this data, in which case static buttons aren't as big a deal any more.</p>\n" }, { "answer_id": 273047, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "<p>I agree with Joel about caching the search results. As for the buttons you can create them dynamically at the init or load phases of the page lifecycle but be aware that if you remove a button and then add it back programmatically you will mess up your state.</p>\n\n<p>In one of my projects we have a dynamic form that generates field son the fly and the way we make it work is through an array that is stored in the cache or in the viewstate for the page. The array contains the buttons to display and on each page load it re-creates the buttons so that state can be loaded properly into them. Then if I need more buttons or a whole new set I flag the hide value in the array and add a new set of values in the array for the new set of corresponding buttons. This way state is not lost and the buttons continue to work.</p>\n\n<p>You also need to ensure that you add a handler for the on_click event for your buttons if you create them programmatically which I think I see in your code up at the top.</p>\n" }, { "answer_id": 273068, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 1, "selected": false, "text": "<p>What happens when the postback event handling tries to find the control it dosen't exists on the collection.\nCheckout Denis DynamicControlsPlaceholder @ <a href=\"http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx\" rel=\"nofollow noreferrer\">http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx</a></p>\n\n<p>Hope it helps\nBruno Figueiredo\n<a href=\"http://www.brunofigueiredo.com\" rel=\"nofollow noreferrer\">http://www.brunofigueiredo.com</a></p>\n" }, { "answer_id": 273093, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 0, "selected": false, "text": "<p>Here is a sample with custom viewstate handling (note that buttons have <code>EnableViewState = false</code>):</p>\n\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n // Execute heavy search 1 to generate buttons\n ButtonTexts = new ButtonState[] { \n new ButtonState() { ID = \"Btn1\", Text = \"Selection 1\" } \n };\n }\n AddButtons();\n }\n\n void b_Command(object sender, CommandEventArgs e)\n {\n TextBox1.Text = ((Button)sender).Text;\n\n // Execute heavy search 2 to generate new buttons\n ButtonTexts = new ButtonState[] { \n new ButtonState() { ID = \"Btn1\", Text = \"Selection 1\" }, \n new ButtonState() { ID = \"Btn2\", Text = \"Selection 2\" } \n };\n AddButtons();\n }\n\n private void AddButtons()\n {\n Panel1.Controls.Clear();\n foreach (ButtonState buttonState in this.ButtonTexts)\n {\n Button b = new Button();\n b.EnableViewState = false;\n b.ID = buttonState.ID;\n b.Text = buttonState.Text;\n b.Command += new CommandEventHandler(b_Command);\n Panel1.Controls.Add(b);\n }\n }\n\n private ButtonState[] ButtonTexts\n {\n get\n {\n ButtonState[] list = ViewState[\"ButtonTexts\"] as ButtonState[];\n if (list == null)\n ButtonTexts = new ButtonState[0];\n return list;\n }\n set { ViewState[\"ButtonTexts\"] = value; }\n }\n\n [Serializable]\n class ButtonState\n {\n public string ID { get; set; }\n public string Text { get; set; }\n }\n</code></pre>\n" }, { "answer_id": 276224, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 4, "selected": true, "text": "<p>The b_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state. </p>\n\n<p>If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page. \nIf the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.</p>\n\n<p>This scenario means that you need just to store some info about your button in your b_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now).</p>\n\n<p>so your code would become something like:</p>\n\n<pre><code>namespace CloudNavigation\n{\n public partial class Test : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n if (IsPostBack)\n {\n this.recreateButtons();\n }\n else\n {\n // Execute heavy search 1 to generate buttons\n Button b = new Button();\n b.Text = \"Selection 1\";\n b.Command += new CommandEventHandler(b_Command);\n Panel1.Controls.Add(b);\n //store this stuff in ViewState for the very first time\n }\n }\n\n void b_Command(object sender, CommandEventArgs e)\n {\n //Execute heavy search 2 to generate new buttons\n //TODO: store data into ViewState or Session\n //and maybe create some new buttons\n }\n\n void recreateButtons()\n {\n //retrieve data from ViewState or Session and create all the buttons\n //wiring them up to eventHandler\n }\n }\n}\n</code></pre>\n\n<p>If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).</p>\n\n<p>Someone will hate this solution but as far as I know the only way to retain state data server-side is <strong>ViewState</strong> - <strong>Session</strong> - Page.Transfer or client-side cookies.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22100/" ]
I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b\_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info. How and where shoud I be doing this? Should I be doing it before Page\_Load for example? How can I re-construct the CommandEventHandler from the postback - if at all? ``` namespace CloudNavigation { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { // how can I re-generate the button and hook up the event here // without executing heavy search 1 } else { // Execute heavy search 1 to generate buttons Button b = new Button(); b.Text = "Selection 1"; b.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b); } } void b_Command(object sender, CommandEventArgs e) { // Execute heavy search 2 to generate new buttons Button b2 = new Button(); b2.Text = "Selection 2"; b2.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b2); } } } ```
The b\_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state. If this a page-scoped operation easiest way is to store it in the ViewState (as strings - if you start loading the ViewState with objects you'll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page. If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls. This scenario means that you need just to store some info about your button in your b\_Command EventHandler instead of creating and adding buttons since if you do so you'll lose relative information in the next postback (as it is happening now). so your code would become something like: ``` namespace CloudNavigation { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { this.recreateButtons(); } else { // Execute heavy search 1 to generate buttons Button b = new Button(); b.Text = "Selection 1"; b.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b); //store this stuff in ViewState for the very first time } } void b_Command(object sender, CommandEventArgs e) { //Execute heavy search 2 to generate new buttons //TODO: store data into ViewState or Session //and maybe create some new buttons } void recreateButtons() { //retrieve data from ViewState or Session and create all the buttons //wiring them up to eventHandler } } } ``` If you don't want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don't see a difference since you'll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons). Someone will hate this solution but as far as I know the only way to retain state data server-side is **ViewState** - **Session** - Page.Transfer or client-side cookies.
272,941
<p>I've done development in both VB6 and VB.NET, and I've used ADODB objects in VB6 to handle recordset navigation (i.e. the MoveFirst, MoveNext, etc. methods), and I have used ADO.NET to handle queries in a row-by-row nature (i.e For Each Row In Table.Rows ...)</p> <p>But now I seem to have come to a dilemma. I am now building a program in VB.NET where I need to use the equivalent functionality of the Move commands of the old Recordset object. Does VB.NET have some sort of object that supports this functionality, or do I have to resort to using the old ADODB COM object?</p> <p>Edit: Just for clarification, I want the user to be able to navigate through the query moving forwards or backwards. Looping through the rows is a simple task.</p>
[ { "answer_id": 272962, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>In .Net, there are many ways to do this. One that I like is to use a DataReader, which can return multiple recordsets. You can loop through its records using While DataReader.Read.</p>\n\n<p>One of the advantages of using DataReader is that it is a forward-only, read-only object, so it's fast and light-weight.</p>\n\n<p>To allow the user to navigate through all of the records, one at a time, you do not want to hold a DataReader open while the user navigates. you can read the DataReader records into objects. Or, you can retrieve the records into a DataSet, and display the DataRows from the DataTable one at a time.</p>\n\n<p>I would suggest that, if possible, you retrieve all of the records at once if there are not too many. This will save repeated calls to the database.</p>\n\n<p>On the other hand, if there are a lot of records, you could retrieve the first few (say, 10 or 20) and only retrieve the next set of records with a new database call if the user clicks beyond the initial set. This is lazy loading.</p>\n" }, { "answer_id": 272968, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 3, "selected": true, "text": "<p>There is no need to go back to the bad old days. If you can give a pseudo code example, I can translate to vb.net for you. </p>\n\n<p>This is kind of a generic way to do it. </p>\n\n<pre><code>Dim ds as DataSet\n\n'populate your DataSet'\n\nFor each dr as DataRow in ds.Tables(&lt;tableIndex&gt;).Rows\n 'Do something with the row'\n\nNext\n</code></pre>\n\n<p>Per Edit 1: The user will navigate the results, not the query. So what you want to do is either a) get the results and display only the current rowindex of ds.Tables.Row() to them, or b) execute a new query with each navigation (not a real well performing option.)</p>\n\n<p>Per comment: No, they havent. But the user usually will not be working interactively with the database like this. You will need to get your dataset / table of the results, and use the buttons to retrieve the relevant row from the dataset/table. </p>\n\n<ul>\n<li>The First Row is DataTable.Rows(0)</li>\n<li>The Last Row is DataTable.Rows(DataTable.Rows.Count-1) </li>\n<li><ul>\n<li>for any row in between (store the currently displayed rowindex in your app), then call</li>\n</ul></li>\n<li>DataTable.Rows(currentRowIndex -1) for previous and </li>\n<li>DataTable.Rows(currentRowIndex +1) for next.</li>\n</ul>\n" }, { "answer_id": 272999, "author": "steve", "author_id": 32103, "author_profile": "https://Stackoverflow.com/users/32103", "pm_score": 0, "selected": false, "text": "<p>Here's a quick example of using the datareader:</p>\n\n<pre><code> Dim cmd As New OleDb.OleDbCommand(sql, Conn) 'You can also use command parameter here\n Dim dr As OleDb.OleDbDataReader\n dr = cmd.ExecuteReader\n\n While dr.Read\n\n ‘Do something with data\n ‘ access fields\n dr(\"fieldname\")\n ‘Check for null\n IsDBNull(dr(\"fieldname\"))\n\n End While\n\n dr.Close()\n</code></pre>\n" }, { "answer_id": 273018, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 2, "selected": false, "text": "<p>It all depends on the usage:\nIf you need only to list the results of one or more queries you should use the datareader. Has DOK pointed out, it's read-only and foward-only so it's fast.\n<a href=\"http://www.startvbdotnet.com/ado/sqlserver.aspx\" rel=\"nofollow noreferrer\">http://www.startvbdotnet.com/ado/sqlserver.aspx</a></p>\n\n<p>If you need to navigate thou the records you should use a dataset.\n<a href=\"http://www.c-sharpcorner.com/UploadFile/raghavnayak/DataSetsIn.NET12032005003647AM/DataSetsIn.NET.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/raghavnayak/DataSetsIn.NET12032005003647AM/DataSetsIn.NET.aspx</a></p>\n\n<p>The dataset also has the advantage of working \"disconnected\", so you build all the logic, and only when you need the data you call the Fill method. The dataset is populated and then you can start working with the data, now disconnected from the DB.</p>\n\n<p>Hope it helps,\nBruno Figueiredo\n<a href=\"http://www.brunofigueiredo.com\" rel=\"nofollow noreferrer\">http://www.brunofigueiredo.com</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29115/" ]
I've done development in both VB6 and VB.NET, and I've used ADODB objects in VB6 to handle recordset navigation (i.e. the MoveFirst, MoveNext, etc. methods), and I have used ADO.NET to handle queries in a row-by-row nature (i.e For Each Row In Table.Rows ...) But now I seem to have come to a dilemma. I am now building a program in VB.NET where I need to use the equivalent functionality of the Move commands of the old Recordset object. Does VB.NET have some sort of object that supports this functionality, or do I have to resort to using the old ADODB COM object? Edit: Just for clarification, I want the user to be able to navigate through the query moving forwards or backwards. Looping through the rows is a simple task.
There is no need to go back to the bad old days. If you can give a pseudo code example, I can translate to vb.net for you. This is kind of a generic way to do it. ``` Dim ds as DataSet 'populate your DataSet' For each dr as DataRow in ds.Tables(<tableIndex>).Rows 'Do something with the row' Next ``` Per Edit 1: The user will navigate the results, not the query. So what you want to do is either a) get the results and display only the current rowindex of ds.Tables.Row() to them, or b) execute a new query with each navigation (not a real well performing option.) Per comment: No, they havent. But the user usually will not be working interactively with the database like this. You will need to get your dataset / table of the results, and use the buttons to retrieve the relevant row from the dataset/table. * The First Row is DataTable.Rows(0) * The Last Row is DataTable.Rows(DataTable.Rows.Count-1) * + for any row in between (store the currently displayed rowindex in your app), then call * DataTable.Rows(currentRowIndex -1) for previous and * DataTable.Rows(currentRowIndex +1) for next.
272,964
<p>If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.)</p> <p>Elementary example:</p> <pre><code>ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails() { //Do stuff to members of MyClass that never fails return successfulResultObject; } void MyClass::DoWork() { // Do some stuff FunctionThatAltersMembersAndNeverFails(); // Do more stuff } </code></pre> <p>In this case, will the <code>ReturnValue</code> object get copied at all? Does it even get constructed? (I know it probably depends on the compiler, but let's narrow this discussion down to the popular modern ones.)</p> <p>EDIT: Let's simplify this a bit, since there doesn't seem to be a consensus in the general case. What if <code>ReturnValue</code> is an int, and we return 0 instead of <code>successfulResultObject</code>?</p>
[ { "answer_id": 272971, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>I doubt most compilers could do that if they were in different compilation objects (ie. different files). Maybe if they were both in the same file, they could.</p>\n" }, { "answer_id": 272988, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 1, "selected": false, "text": "<p>They most likely will if the optimization level causes them to inline the code. If not, they would have to generate two different translations of the same code to make it work, which could open up a lot of edge case problems.</p>\n" }, { "answer_id": 272998, "author": "Sniggerfardimungus", "author_id": 30997, "author_profile": "https://Stackoverflow.com/users/30997", "pm_score": 1, "selected": false, "text": "<p>The linker can take care of this sort of thing, even if the original caller and called are in different compilation units.</p>\n\n<p>If you have a good reason to be concerned about the CPU load dedicated to a method call (premature optimization is the root of all evil,) you might consider the many inlining options available to you, including (gasp!) a macro.</p>\n\n<p>Do you REALLY need to optimize at this level?</p>\n" }, { "answer_id": 273032, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 3, "selected": true, "text": "<p>If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked.</p>\n\n<p>If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code (also depending on whether FunctionThatAltersMembersAndNeverFails is inline).</p>\n" }, { "answer_id": 273052, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 0, "selected": false, "text": "<p>There is a pretty good chance that a peephole optimizer will catch this. Many (most?) compilers implement one, so the answer is probably \"yes\".</p>\n\n<p>As others have notes this is not a trivial question at the AST rewriting level.</p>\n\n<hr>\n\n<p>Peephole optimizers work on a representation of the code at a level equivalent to assembly language (but before generation of actual machine code). There is a chance to notice the load of the return value into a register followed by a overwrite with no intermediate read, and just remove the load. This is done on a case by case basis.</p>\n" }, { "answer_id": 279792, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 1, "selected": false, "text": "<p>If return value is an int and you return 0 (as in the edited question), then this <i>may</i> get optimized away.</p>\n\n<p>You have to look at the underlying assembly. If the function is not inlined then the underlying assembly will execute a mov eax, 0 (or xor eax, eax) to set eax (which is usually used for integer return values) to 0. If the function is inlined, this will certainly get optimized away.</p>\n\n<p>But this senario isn't too useful if you're worried about what happens when you return objects larger than 32-bits. You'll need to refer to the answers to the unedit question, which paint a pretty good picture: If everything is inlined then most of it will be optimized out. If it is not inlined, then the functions must be called even if they don't really do anything, and that includes the constructor of an object (since the compiler doesn't know whether the constructor modified global variables or did something else weird).</p>\n" }, { "answer_id": 64436238, "author": "Gukki5", "author_id": 5689597, "author_profile": "https://Stackoverflow.com/users/5689597", "pm_score": 0, "selected": false, "text": "<p>just tried this example on compiler explorer, and at -O3 the <code>mov</code> is not generated when the return value is not used.</p>\n<p><a href=\"https://gcc.godbolt.org/z/v5WGPr\" rel=\"nofollow noreferrer\">https://gcc.godbolt.org/z/v5WGPr</a></p>\n<p><a href=\"https://i.stack.imgur.com/mCmTI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mCmTI.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22724/" ]
If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.) Elementary example: ``` ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails() { //Do stuff to members of MyClass that never fails return successfulResultObject; } void MyClass::DoWork() { // Do some stuff FunctionThatAltersMembersAndNeverFails(); // Do more stuff } ``` In this case, will the `ReturnValue` object get copied at all? Does it even get constructed? (I know it probably depends on the compiler, but let's narrow this discussion down to the popular modern ones.) EDIT: Let's simplify this a bit, since there doesn't seem to be a consensus in the general case. What if `ReturnValue` is an int, and we return 0 instead of `successfulResultObject`?
If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked. If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code (also depending on whether FunctionThatAltersMembersAndNeverFails is inline).
272,973
<p>I have a single form for editing an event, in which the user can (a) edit the details of the event (title, description, dates, etc.) in a FormView and (b) view and edit a ListView of contacts who are registered for the event. </p> <p>Here's my LinqDataSource, which allows me to add and remove contacts to the event. </p> <pre><code>&lt;asp:linqdatasource runat="server" id="ContactsDatasource" contexttypename="Db" tablename="ContactsCalendarEventsXtabs" autogeneratewhereclause="true" enabledelete="true" enableinsert="true"&gt; &lt;whereparameters&gt; &lt;asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" /&gt; &lt;/whereparameters&gt; &lt;insertparameters&gt; &lt;asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" /&gt; &lt;/insertparameters&gt; &lt;/asp:linqdatasource&gt; </code></pre> <p>This works fine, but of course it persists the changes to the database as they're made; and it only works when the event has already been created. Ideally, I'd like for my changes to the ListView to be persisted only once the FormView saves (so if someone makes some changes to the ListView and then cancels out of the FormView, the changes are discarded). Along the same lines, I'd like to be able to create a new event, enter its details, and sign some people up for it, all at once; when the FormView saves, it gets the new ID for the event, and then the ListView saves using that ID.</p> <p>In the past (pre-Linq) I've accomplished this with my own extensively customized FormView and SqlDataSource objects, which take care of temporarily persisting the data changes, getting the event ID from the FormView, etc. Is there a more standard way of dealing with this scenario using the LinqDataSource? </p>
[ { "answer_id": 276419, "author": "Alexander Taran", "author_id": 35954, "author_profile": "https://Stackoverflow.com/users/35954", "pm_score": 0, "selected": false, "text": "<p>Do you you have a foreign key set between tables?\nif you do - then it should throw an exception when saving list for new event.</p>\n\n<p>And on topic there is a way to create an event + list records at the same time programmaticaly.</p>\n\n<p>but you will have to write some code.</p>\n\n<pre><code>create all list items programmaticaly.\ncreate event proggramaticaly.\nevent myevent = new event();\nevent.someprop = zzxxx;\n\nlink them programmaticaly.\nthen use yourdatacontext.events.InsertOnSubmit(event);\n</code></pre>\n\n<p>and same for list items.</p>\n\n<p>ScottGu's Blog LINQ series has this one described for sure</p>\n" }, { "answer_id": 555535, "author": "Liam", "author_id": 28594, "author_profile": "https://Stackoverflow.com/users/28594", "pm_score": 1, "selected": false, "text": "<p>So effectively you want to wrap the two LinqDataSources in a single transaction. There is a sneaky way to leverage the LinqDataSource databinding and events and still do only one commit. Using this method you can still use Dynamic Data, FormView, GridView, validation, etc. It only relies on hooking into the data sources.</p>\n\n<p>Example markup:</p>\n\n<pre><code>&lt;FormView&gt;...&lt;/FormView&gt;\n&lt;ListView&gt;...&lt;/ListView&gt;\n&lt;LinqDataSource ID=\"dsEvent\" ...&gt; &lt;/LinqDataSource&gt;\n&lt;LinqDataSource ID=\"dsContact\" ...&gt; &lt;/LinqDataSource&gt;\n&lt;asp:Button ID=\"btnSubmit\" runat=\"server\" OnClick=\"btnSubmit_Click\" Text=\"Submit it All!\"/&gt;\n</code></pre>\n\n<p>Now in the code behind you are using the single Submit button to mimic the behaviour of the LinqDataSources. You use the datasource to insert the item, which creates the new object, snaffle the object, do it again for the second object. Link the two items together and any other logic you want and then insert it into the database as a single transaction. The key is to set the Cancel flag in the Inserting event so that the datasource doesn't actually insert into the database.</p>\n\n<pre><code>protected void btnSubmit_Click(object sender, EventArgs e)\n{\n Event evt = null;\n Contact contact = null;\n\n dsEvent.Inserting += (o,ea) =&gt; { evt = (ea.NewObject as Event); ea.Cancel = true; };\n dsEvent.InsertItem(true);\n dsContact.Inserting += (o, ea) =&gt; { contact = (ea.NewObject as Contact); ea.Cancel = true; };\n dsContact.InsertItem(true);\n\n evt.Contacts.Add(contact);\n\n using (var dbContext = new ContactsCalendarEventsXtabs())\n {\n dbContext.Events.InsertOnSubmit(evt);\n dbContext.SubmitChanges();\n }\n}\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I have a single form for editing an event, in which the user can (a) edit the details of the event (title, description, dates, etc.) in a FormView and (b) view and edit a ListView of contacts who are registered for the event. Here's my LinqDataSource, which allows me to add and remove contacts to the event. ``` <asp:linqdatasource runat="server" id="ContactsDatasource" contexttypename="Db" tablename="ContactsCalendarEventsXtabs" autogeneratewhereclause="true" enabledelete="true" enableinsert="true"> <whereparameters> <asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" /> </whereparameters> <insertparameters> <asp:querystringparameter name="CalendarEventID" querystringfield="id" type="Int32" /> </insertparameters> </asp:linqdatasource> ``` This works fine, but of course it persists the changes to the database as they're made; and it only works when the event has already been created. Ideally, I'd like for my changes to the ListView to be persisted only once the FormView saves (so if someone makes some changes to the ListView and then cancels out of the FormView, the changes are discarded). Along the same lines, I'd like to be able to create a new event, enter its details, and sign some people up for it, all at once; when the FormView saves, it gets the new ID for the event, and then the ListView saves using that ID. In the past (pre-Linq) I've accomplished this with my own extensively customized FormView and SqlDataSource objects, which take care of temporarily persisting the data changes, getting the event ID from the FormView, etc. Is there a more standard way of dealing with this scenario using the LinqDataSource?
So effectively you want to wrap the two LinqDataSources in a single transaction. There is a sneaky way to leverage the LinqDataSource databinding and events and still do only one commit. Using this method you can still use Dynamic Data, FormView, GridView, validation, etc. It only relies on hooking into the data sources. Example markup: ``` <FormView>...</FormView> <ListView>...</ListView> <LinqDataSource ID="dsEvent" ...> </LinqDataSource> <LinqDataSource ID="dsContact" ...> </LinqDataSource> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit it All!"/> ``` Now in the code behind you are using the single Submit button to mimic the behaviour of the LinqDataSources. You use the datasource to insert the item, which creates the new object, snaffle the object, do it again for the second object. Link the two items together and any other logic you want and then insert it into the database as a single transaction. The key is to set the Cancel flag in the Inserting event so that the datasource doesn't actually insert into the database. ``` protected void btnSubmit_Click(object sender, EventArgs e) { Event evt = null; Contact contact = null; dsEvent.Inserting += (o,ea) => { evt = (ea.NewObject as Event); ea.Cancel = true; }; dsEvent.InsertItem(true); dsContact.Inserting += (o, ea) => { contact = (ea.NewObject as Contact); ea.Cancel = true; }; dsContact.InsertItem(true); evt.Contacts.Add(contact); using (var dbContext = new ContactsCalendarEventsXtabs()) { dbContext.Events.InsertOnSubmit(evt); dbContext.SubmitChanges(); } } ```
272,987
<p>We have a pretty mature COM dll, which we test using DUnit. One of our recent tests creates a few threads, and tests the object from those threads. This test works fine when running the test using the gui front-end, but hangs when running as a console application. Here's a quick pseudo view of what we have in the test</p> <pre><code>SetupTest; fThreadRefCount := 0; //number of active threads Thread1 := TMyThread.Create(True); Inc(fThreadRefCount); Thread1.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread3 := TMyThread.Create(True); Inc(fThreadRefCount); Thread2.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread3 := TMyThread.Create(True); Inc(fThreadRefCount); Thread3.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread1.Resume; Thread2.Resume; Thread3.Resume; while fThreadRefCount &gt; 0 do Application.ProcessMessages; </code></pre> <p>I have tried doing nothing in the OnExecute, so I'm sure it's not the actual code I'm testing. In the console, fThreadRefCount never decrements, while if I run it as a gui app, it's fine!</p> <p>As far as I can see, the OnTerminate event is just not called.</p>
[ { "answer_id": 273236, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<p>You need to provide more data.</p>\n<p>Note that <code>OnTerminate</code> is called via <code>Synchronize()</code>, which requires a call to <code>CheckSynchronize()</code> at some point somewhere. <code>Application.ProcessMessages()</code> normally does this, but depending on how the VCL has been initialized, it's possible that the <code>Synchronize()</code> mechanism hasn't been fully hooked together in a Console application.</p>\n<p>In any case, this program works as expected on my machine:</p>\n<pre><code>uses Windows, SysUtils, Classes, Forms;\n\nvar\n threadCount: Integer;\n\ntype\n TMyThread = class(TThread)\n public\n procedure Execute; override;\n class procedure Go;\n class procedure HandleOnTerminate(Sender: TObject);\n end;\n \nprocedure TMyThread.Execute;\nbegin\nend;\n\nclass procedure TMyThread.Go;\n function MakeThread: TThread;\n begin\n Result := TMyThread.Create(True);\n Inc(threadCount);\n Result.OnTerminate := HandleOnTerminate;\n end;\nvar\n t1, t2, t3: TThread;\nbegin\n t1 := MakeThread;\n t2 := MakeThread;\n t3 := MakeThread;\n t1.Resume;\n t2.Resume;\n t3.Resume;\n while threadCount &gt; 0 do\n Application.ProcessMessages;\nend;\n\nclass procedure TMyThread.HandleOnTerminate(Sender: TObject);\nbegin\n InterlockedDecrement(threadCount);\nend;\n\nbegin\n try\n TMyThread.Go;\n except\n on e: Exception do\n Writeln(e.Message);\n end;\nend.\n</code></pre>\n" }, { "answer_id": 275993, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 3, "selected": false, "text": "<p>As Barry rightly pointed out, unless <code>CheckSyncronize()</code> is called, <code>Synchronize()</code> is not processed, and if <code>Synchronize()</code> is not processed, then the <code>OnTerminate</code> event is not fired.</p>\n<p>What seems to be happening is that when I run my unit tests as a Console application, there are no messages on the message queue, and thus <code>Application.ProcessMessage()</code>, which is called from <code>Application.ProcessMessages()</code>, never gets to call <code>CheckSynchronize()</code>.</p>\n<p>I've now solved the problem by changing the loop to this:</p>\n<pre><code>While fThreadRefCount &gt; 0 do\nbegin\n Application.ProcessMessages;\n CheckSynchronize;\nend;\n</code></pre>\n<p>It now works in both Console and GUI modes.</p>\n<p>The whole <code>WakeupMainThread</code> hook seems to be setup properly. It's this hook which posts the <code>WM_NULL</code> message that triggers the <code>CheckSynchronize()</code>. It just doesn't get that far in the Console app.</p>\n<p><strong>More Investigation</strong></p>\n<p>So, <code>Synchronize()</code> <em>does</em> get called. <code>DoTerminate()</code> calls <code>Synchronize(CallOnTerminate)</code> but there's a line in there:</p>\n<pre><code>WaitForSingleObject(SyncProcPtr.Signal, Infinite); \n</code></pre>\n<p>which just waits forever.</p>\n<p>So, while my fix above works, there's something deeper to this!</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
We have a pretty mature COM dll, which we test using DUnit. One of our recent tests creates a few threads, and tests the object from those threads. This test works fine when running the test using the gui front-end, but hangs when running as a console application. Here's a quick pseudo view of what we have in the test ``` SetupTest; fThreadRefCount := 0; //number of active threads Thread1 := TMyThread.Create(True); Inc(fThreadRefCount); Thread1.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread3 := TMyThread.Create(True); Inc(fThreadRefCount); Thread2.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread3 := TMyThread.Create(True); Inc(fThreadRefCount); Thread3.OnTerminate := HandleTerminate; //HandleOnTerminate decrements fThreadRefCount Thread1.Resume; Thread2.Resume; Thread3.Resume; while fThreadRefCount > 0 do Application.ProcessMessages; ``` I have tried doing nothing in the OnExecute, so I'm sure it's not the actual code I'm testing. In the console, fThreadRefCount never decrements, while if I run it as a gui app, it's fine! As far as I can see, the OnTerminate event is just not called.
You need to provide more data. Note that `OnTerminate` is called via `Synchronize()`, which requires a call to `CheckSynchronize()` at some point somewhere. `Application.ProcessMessages()` normally does this, but depending on how the VCL has been initialized, it's possible that the `Synchronize()` mechanism hasn't been fully hooked together in a Console application. In any case, this program works as expected on my machine: ``` uses Windows, SysUtils, Classes, Forms; var threadCount: Integer; type TMyThread = class(TThread) public procedure Execute; override; class procedure Go; class procedure HandleOnTerminate(Sender: TObject); end; procedure TMyThread.Execute; begin end; class procedure TMyThread.Go; function MakeThread: TThread; begin Result := TMyThread.Create(True); Inc(threadCount); Result.OnTerminate := HandleOnTerminate; end; var t1, t2, t3: TThread; begin t1 := MakeThread; t2 := MakeThread; t3 := MakeThread; t1.Resume; t2.Resume; t3.Resume; while threadCount > 0 do Application.ProcessMessages; end; class procedure TMyThread.HandleOnTerminate(Sender: TObject); begin InterlockedDecrement(threadCount); end; begin try TMyThread.Go; except on e: Exception do Writeln(e.Message); end; end. ```
272,993
<p>I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following:</p> <pre><code>var volumes = { &lt;% for volume in @volumes %&gt; &lt;%= volume.id %&gt; : &lt;%= volume.data %&gt; &lt;%= ',' unless volume === @volumes.last %&gt; &lt;% end %&gt; }; </code></pre> <p>Note the <code>unless</code> statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations).</p> <p>This appears to work, but as a matter of style, do people think it is reasonable to rely on <code>&lt;%= value unless condition %&gt;</code> in the template generating an appropriate <code>render</code> call?</p>
[ { "answer_id": 273010, "author": "Jim Puls", "author_id": 6010, "author_profile": "https://Stackoverflow.com/users/6010", "pm_score": 4, "selected": true, "text": "<p>I don't see why not, but generally if you find yourself conditionalizing a comma on the last member, you probably want to use <code>join</code> instead:</p>\n\n<pre><code>&lt;%= @volumes.map {|v| \"#{v.id} : #{v.data}\"}.join \",\" %&gt;\n</code></pre>\n" }, { "answer_id": 273472, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "<p>Or even:</p>\n\n<pre><code>&lt;%= @volumes.map { |v| \"#{v.id} : #{v.data}\"}.to_sentence -%&gt;\n</code></pre>\n\n<p>To get \"a: something, b: something else, c: anything, and d: another thing.\"</p>\n" }, { "answer_id": 273892, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 2, "selected": false, "text": "<p>If you would like to contruct JSON (and BTW you are constructing JavaScript Object not Array) then I suggest to use to_json method:</p>\n\n<pre><code>var volumes = &lt;%= @volumes.inject({}){|h,v| h.merge(v.id=&gt;v.data)}.to_json %&gt;;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var volumes = &lt;%= Hash[*@volumes.map{|v| [v.id, v.data]}.flatten].to_json %&gt;;\n</code></pre>\n\n<p>Even better would be to move Ruby Hash construction to model as it is too complex for view.</p>\n\n<pre><code>class Volume\n def self.to_hash(volumes)\n Hash[*volumes.map{|v| [v.id, v.data]}.flatten]\n end\nend\n</code></pre>\n\n<p>and then in view you can put much simpler code:</p>\n\n<pre><code>var volumes = &lt;%= Volume.to_hash(@volumes).to_json %&gt;;\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/272993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10026/" ]
I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following: ``` var volumes = { <% for volume in @volumes %> <%= volume.id %> : <%= volume.data %> <%= ',' unless volume === @volumes.last %> <% end %> }; ``` Note the `unless` statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations). This appears to work, but as a matter of style, do people think it is reasonable to rely on `<%= value unless condition %>` in the template generating an appropriate `render` call?
I don't see why not, but generally if you find yourself conditionalizing a comma on the last member, you probably want to use `join` instead: ``` <%= @volumes.map {|v| "#{v.id} : #{v.data}"}.join "," %> ```
273,002
<p>First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.</p> <p>Here's some example code:</p> <pre><code>#!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() </code></pre> <p>I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?</p>
[ { "answer_id": 274366, "author": "bhadra", "author_id": 30289, "author_profile": "https://Stackoverflow.com/users/30289", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I want to generate a WSDL that I can give to the web folks, ....</p>\n</blockquote>\n\n<p>You can try <a href=\"http://soaplib.github.com/soaplib/2_0/\" rel=\"nofollow noreferrer\">soaplib</a>. It has on-demand WSDL generation.</p>\n" }, { "answer_id": 276994, "author": "che", "author_id": 7806, "author_profile": "https://Stackoverflow.com/users/7806", "pm_score": 5, "selected": true, "text": "<p>When I tried to write Python web service last year, I ended up using <a href=\"http://pywebsvcs.sourceforge.net/\" rel=\"noreferrer\">ZSI-2.0</a> (which is something like heir of SOAPpy) and a <a href=\"http://pywebsvcs.sourceforge.net/holger.pdf\" rel=\"noreferrer\">paper available on its web</a>.</p>\n\n<p>Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.</p>\n" }, { "answer_id": 8336051, "author": "user1064941", "author_id": 1064941, "author_profile": "https://Stackoverflow.com/users/1064941", "pm_score": 1, "selected": false, "text": "<p>Sorry for the question few days ago. Now I can invoke the server successfully. A demo is provided:</p>\n\n<pre><code>def test_soappy():\n \"\"\"test for SOAPpy.SOAPServer\n \"\"\"\n #okay\n # it's good for SOAPpy.SOAPServer.\n # in a method,it can have morn than 2 ws server.\n server = SOAPProxy(\"http://localhost:8081/\")\n print server.sum(1,2)\n print server.div(10,2)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31319/" ]
First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value. Here's some example code: ``` #!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() ``` I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?
When I tried to write Python web service last year, I ended up using [ZSI-2.0](http://pywebsvcs.sourceforge.net/) (which is something like heir of SOAPpy) and a [paper available on its web](http://pywebsvcs.sourceforge.net/holger.pdf). Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.
273,009
<p>I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY.</p>
[ { "answer_id": 273017, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 2, "selected": false, "text": "<p>This should help. It contains all (or most anyway) the different date formats</p>\n\n<p><a href=\"http://wiki.lessthandot.com/index.php/Formatting_Dates\" rel=\"nofollow noreferrer\">http://wiki.lessthandot.com/index.php/Formatting_Dates</a></p>\n\n<p>I think you'd be better off handling the string conversion in client if possible.</p>\n" }, { "answer_id": 273020, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": false, "text": "<pre><code>select convert(nvarchar(10), datefield, 103)\n</code></pre>\n" }, { "answer_id": 273021, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": true, "text": "<p>Here is the convert documentation:</p>\n<blockquote>\n<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql</a></p>\n</blockquote>\n<p>Looking through that, it looks like you want style 103:</p>\n<pre><code>SELECT CONVERT(nvarchar(10), getdate(), 103)\n</code></pre>\n" }, { "answer_id": 273022, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<pre><code>select CONVERT (NVARCHAR, GETDATE(), 103)\n</code></pre>\n" }, { "answer_id": 273024, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>Look up convert in BOL.</p>\n" }, { "answer_id": 273026, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 1, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/aa226054.aspx\" rel=\"nofollow noreferrer\">Convert</a> with the 103 option.</p>\n" }, { "answer_id": 41594976, "author": "Ema.H", "author_id": 2630447, "author_profile": "https://Stackoverflow.com/users/2630447", "pm_score": 2, "selected": false, "text": "<p>You can convert a date in many formats, in your case :</p>\n<pre><code>CONVERT(NVARCHAR(10), YOUR_DATE_TIME, 103) =&gt; 15/09/2016\nCONVERT(NVARCHAR(10), YOUR_DATE_TIME, 3) =&gt; 15/09/16\n</code></pre>\n<p>Syntax:</p>\n<pre><code>CONVERT('TheDataTypeYouWant', 'TheDateToConvert', 'TheCodeForFormating' * )\n</code></pre>\n<p>The code is an integer, here 3 is the third formatting option (without century), if you want the century just change the code to 103.</p>\n<p>See more at: <a href=\"http://www.w3schools.com/sql/func_convert.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/sql/func_convert.asp</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY.
Here is the convert documentation: > > <https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql> > > > Looking through that, it looks like you want style 103: ``` SELECT CONVERT(nvarchar(10), getdate(), 103) ```
273,027
<p>I am following the <strong><em>learning</em> ASP.NET 3.5</strong> by O'REILLY to write some ASP.NET 3.5 code using Visual Studio 2008 SP1. I have gotten to the point to where I need to Configure a Data Source using the SqlDataSource control. I chose <strong>Microsoft SQL Server (SqlClient)</strong> even though I have SQL Server Express 2005 - This seems like the only logical choice. </p> <p>I get to the <strong>Add Connection</strong> window and successfully add a <strong>Server name</strong> and I use the <strong>Select or enter a database name</strong> of <strong>AdventureWorks</strong>. When I click on Test Connection I get the <strong>Test Connection Succeeded</strong> message box.</p> <p>Unfortunately, when I click OK I get an error message of the following:</p> <pre><code>Could not load file or assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKey Token=89845dcd8080cc91' or one of its dependecies. The system cannot find the file specified. </code></pre> <p>At his point I am at a loss and everywhere I look and find something similar to my issue it involves other versions of either Visual Studio or SQL Server.</p> <p>I'd really appreciate any help on this!</p>
[ { "answer_id": 274821, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 1, "selected": false, "text": "<p>You may investigate <a href=\"http://social.msdn.microsoft.com/forums/es-ES/Offtopic/thread/70a5cb26-6b20-43a0-8cef-a0c5716a3e1c/\" rel=\"nofollow noreferrer\">this</a> recipe.</p>\n" }, { "answer_id": 328585, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 0, "selected": false, "text": "<p>You may need to reinstall your copy of SQL 2005 Express. But sure to install all of the client-side developer packages in the installer.</p>\n" }, { "answer_id": 1130321, "author": "Steven", "author_id": 91612, "author_profile": "https://Stackoverflow.com/users/91612", "pm_score": 0, "selected": false, "text": "<p>I had the exact same issue.</p>\n\n<p>Following the <a href=\"http://social.msdn.microsoft.com/forums/es-ES/Offtopic/thread/70a5cb26-6b20-43a0-8cef-a0c5716a3e1c/\" rel=\"nofollow noreferrer\">suggestions in this thread</a> , I went to the \"<a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=C6C3E9EF-BA29-4A43-8D69-A2BED18FE73C&amp;displaylang=en#filelist\" rel=\"nofollow noreferrer\">Microsoft SQL Server 2008 Feature Pack, August 2008</a> \" - and downloaded (and installed) the \"Microsoft SQL Server 2005 Backward Compatibility Components \". This did not help.</p>\n\n<p>Then I also downloaded and installed the following components: SharedManagementObjects.msi, sqlncli.msi, SQLSysClrTypes.msi.</p>\n\n<p>And now it works for me.</p>\n\n<p>I'm using SQL Server 2008 Express and Visual Web Developer 2008 Express Edition.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am following the ***learning* ASP.NET 3.5** by O'REILLY to write some ASP.NET 3.5 code using Visual Studio 2008 SP1. I have gotten to the point to where I need to Configure a Data Source using the SqlDataSource control. I chose **Microsoft SQL Server (SqlClient)** even though I have SQL Server Express 2005 - This seems like the only logical choice. I get to the **Add Connection** window and successfully add a **Server name** and I use the **Select or enter a database name** of **AdventureWorks**. When I click on Test Connection I get the **Test Connection Succeeded** message box. Unfortunately, when I click OK I get an error message of the following: ``` Could not load file or assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKey Token=89845dcd8080cc91' or one of its dependecies. The system cannot find the file specified. ``` At his point I am at a loss and everywhere I look and find something similar to my issue it involves other versions of either Visual Studio or SQL Server. I'd really appreciate any help on this!
You may investigate [this](http://social.msdn.microsoft.com/forums/es-ES/Offtopic/thread/70a5cb26-6b20-43a0-8cef-a0c5716a3e1c/) recipe.
273,029
<p>In converting from short to a byte array I found the following solution on the web but could not quite understand the logic involved.</p> <pre><code>//buffer is an array of bytes, bytes[] buffer[position] = (byte)(sample &amp; 0xff); buffer[position+1] = (byte)((sample &gt;&gt; 8) &amp; 0xff); </code></pre> <p>Can someone tell me why 0xff (256) is being anded to the sample which is a short? </p>
[ { "answer_id": 273058, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>This code probably comes from C code (or was written by a C programmer who don't parse Java as well as erickson does). This is because in Java a cast from a type with more information to a type with less information will discard the higher order bits and thus the &amp; 0xff is unnecessary in both cases.</p>\n\n<p>A short has 16 bits, two bytes. So it needs to take two slots in the byte array, because if we just casted a short into a byte one byte would be lost. </p>\n\n<p>So, the code you have does</p>\n\n<pre><code>1110001100001111 sample\n0000000011111111 0xff\n0000000000001111 sample &amp; 0xff =&gt; first byte`\n</code></pre>\n\n<p>Then, displaces the sample to get the second byte</p>\n\n<pre><code>0000000011100011 sample &gt;&gt; 8\n0000000011111111 0xff\n0000000011100011 (sample &gt;&gt; 8 ) &amp; 0xff =&gt; second byte\n</code></pre>\n\n<p>Which can be a lot better written as erickson shows below (hopefully it'll be above soon).</p>\n" }, { "answer_id": 273061, "author": "Paul Sonier", "author_id": 28053, "author_profile": "https://Stackoverflow.com/users/28053", "pm_score": 1, "selected": false, "text": "<p>It makes sure there's no overflow; specifically, the first line there is taking the LSByte of \"sample\" and masking OUT your upper 8 bits, giving you only values in the range of 0-255; the second line there is taking the MSByte of \"sample\" (by performing the right-shift) and doing the same thing. It shouldn't be necessary on the second line, since the right-shift by 8 should drop out the 8 least significant bits, but it does make the code a little bit more symmetric.</p>\n\n<p>I would assume that this is because since sample is a short (2 bytes) any values in the range of 256-6553 would be interpreted as 255 by the byte conversion.</p>\n" }, { "answer_id": 273323, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "<p>The other answers have some good information, but unfortunately, they both promote an incorrect idea about the cast to byte.</p>\n\n<p>The <code>&amp; 0xFF</code> is unnecessary in both cases in your original code.</p>\n\n<p>A narrowing cast discards the high-order bits that don't fit into the narrower type. In fact, the <code>&amp; 0xFF</code> actually first causes the short to be promoted to an <code>int</code> with the most significant 24 bits cleared, which is then chopped down and stuffed in a byte by the cast. See the <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25363\" rel=\"nofollow noreferrer\">Java Language Specification Section §5.1.3</a> for details.</p>\n\n<pre><code>buffer[position] = (byte) sample;\nbuffer[position+1] = (byte) (sample &gt;&gt;&gt; 8);\n</code></pre>\n\n<p>Also, note my use of the right shift with zero extension, rather than sign extension. In this case, since you're immediately casting the result of the shift to a byte, it doesn't matter. In general, however, the operators give different results, and you should be deliberate in what you choose. </p>\n" }, { "answer_id": 5495400, "author": "user633535", "author_id": 633535, "author_profile": "https://Stackoverflow.com/users/633535", "pm_score": 1, "selected": false, "text": "<pre><code>buffer[position] = (byte)(sample &amp; 0xff);\nbuffer[position+1] = (byte)((sample &gt;&gt; 8) &amp; 0xff);\n</code></pre>\n\n<p>must be :</p>\n\n<pre><code>buffer[position] = (byte)((sample &gt;&gt; 8) &amp; 0xff);\nbuffer[position+1] = (byte)(sample &amp; 0xff);\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In converting from short to a byte array I found the following solution on the web but could not quite understand the logic involved. ``` //buffer is an array of bytes, bytes[] buffer[position] = (byte)(sample & 0xff); buffer[position+1] = (byte)((sample >> 8) & 0xff); ``` Can someone tell me why 0xff (256) is being anded to the sample which is a short?
This code probably comes from C code (or was written by a C programmer who don't parse Java as well as erickson does). This is because in Java a cast from a type with more information to a type with less information will discard the higher order bits and thus the & 0xff is unnecessary in both cases. A short has 16 bits, two bytes. So it needs to take two slots in the byte array, because if we just casted a short into a byte one byte would be lost. So, the code you have does ``` 1110001100001111 sample 0000000011111111 0xff 0000000000001111 sample & 0xff => first byte` ``` Then, displaces the sample to get the second byte ``` 0000000011100011 sample >> 8 0000000011111111 0xff 0000000011100011 (sample >> 8 ) & 0xff => second byte ``` Which can be a lot better written as erickson shows below (hopefully it'll be above soon).
273,039
<p>In Xcode, I can use <kbd>CMD</kbd>-<kbd>R</kbd> to run (or <kbd>CMD</kbd>-<kbd>Y</kbd> to debug), and my app will compile, install on the phone &amp; start-up. (I've already prepped my phone &amp; Xcode so this part works as expected.)</p> <p>What I'd <strong><em>LIKE</em></strong> to do is type CMD-&lt;something else&gt; and have my program compile &amp; install on the phone, but <em>NOT</em> start-up.</p> <p>I realize that I can just <kbd>CMD</kbd>-<kbd>B</kbd> to build, then go through some rigamarole to deploy, but I'm hoping one of you smart-folk can tell me the lazy-man's shortcut for all of this.</p>
[ { "answer_id": 273064, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>Have you looked into using <a href=\"http://en.wikipedia.org/wiki/Automator\" rel=\"nofollow noreferrer\">Automator</a>? Here's a <a href=\"http://developer.apple.com/tools/xcode/automatorforxcode.html\" rel=\"nofollow noreferrer\">good write up</a> on how to automate XCode to build and what not.</p>\n" }, { "answer_id": 273095, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 3, "selected": true, "text": "<p>Hey Olie, I haven't tried this because I don't have an iPhone to deploy to at the moment, but this /should/ work:</p>\n\n<p>You can create a script which runs xcodebuild in your current project directory and give it the install target. Assuming you're going to want to debug at sometime, use the Debug configuration, otherwise use release. Then bind the script to some command key in the Xcode preferences and you should be on your way. To launch xcodebuild with debug you would do something like:</p>\n\n<pre><code>xcodebuild install -configuration Debug\n</code></pre>\n\n<p>If you have more than one target in your project you will have to specify that to xcodebuild as well:</p>\n\n<pre><code>xcodebuild install -target iPhoneApp -configuration Debug\n</code></pre>\n\n<p>You could also create a configuration specific to this scenario in your projects and pass that to xcodebuild and you should be able to script this in your favorite supported language (i.e., AppleScript, python, ruby, etc.).</p>\n\n<p>HTH</p>\n" }, { "answer_id": 2824325, "author": "m nelson", "author_id": 339928, "author_profile": "https://Stackoverflow.com/users/339928", "pm_score": 1, "selected": false, "text": "<p>I had the same question.</p>\n\n<p>I ended up using the XCode Organizer. Select your current device. Summary Tab. \"+\" Applications..then select the one you just built (under /build/[debug|release]-iphoneos/.app</p>\n\n<p>This does the install very easily.</p>\n" }, { "answer_id": 14788189, "author": "MaulingMonkey", "author_id": 953531, "author_profile": "https://Stackoverflow.com/users/953531", "pm_score": 0, "selected": false, "text": "<p><strong>To build</strong> (exact flags documented under \"man xcodebuild\", install xcode's command line tools): <pre>xcodebuild build -sdk iphoneos6.0 <em>workspace/project, targets, configs and/or scheme flags</em></pre></p>\n\n<p><strong>To install</strong> (<a href=\"https://github.com/cowboygneox/fruitstrap\" rel=\"nofollow\">grab from github here</a> then simply make and run): <pre><a href=\"https://github.com/cowboygneox/fruitstrap\" rel=\"nofollow\">path/to/fruitstrap</a> --id <em>device-uuid-to-install-on</em> --bundle <em>path/to/ios.app</em></pre></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34820/" ]
In Xcode, I can use `CMD`-`R` to run (or `CMD`-`Y` to debug), and my app will compile, install on the phone & start-up. (I've already prepped my phone & Xcode so this part works as expected.) What I'd ***LIKE*** to do is type CMD-<something else> and have my program compile & install on the phone, but *NOT* start-up. I realize that I can just `CMD`-`B` to build, then go through some rigamarole to deploy, but I'm hoping one of you smart-folk can tell me the lazy-man's shortcut for all of this.
Hey Olie, I haven't tried this because I don't have an iPhone to deploy to at the moment, but this /should/ work: You can create a script which runs xcodebuild in your current project directory and give it the install target. Assuming you're going to want to debug at sometime, use the Debug configuration, otherwise use release. Then bind the script to some command key in the Xcode preferences and you should be on your way. To launch xcodebuild with debug you would do something like: ``` xcodebuild install -configuration Debug ``` If you have more than one target in your project you will have to specify that to xcodebuild as well: ``` xcodebuild install -target iPhoneApp -configuration Debug ``` You could also create a configuration specific to this scenario in your projects and pass that to xcodebuild and you should be able to script this in your favorite supported language (i.e., AppleScript, python, ruby, etc.). HTH
273,043
<p>We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: </p> <blockquote> <p>Python Fatal Error: GC Object already tracked</p> </blockquote> <p>which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.</p>
[ { "answer_id": 273063, "author": "RaySl", "author_id": 30089, "author_profile": "https://Stackoverflow.com/users/30089", "pm_score": 1, "selected": false, "text": "<p>If you have mac or sun box kicking around you could use <a href=\"http://en.wikipedia.org/wiki/DTrace\" rel=\"nofollow noreferrer\">dtrace</a> and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy.</p>\n\n<p>If that isn't available to you, then you can <a href=\"http://www.python.org/doc/2.5.2/lib/module-gc.html\" rel=\"nofollow noreferrer\">import gc</a> and enable debugging which you can then put out to a log file.</p>\n\n<p>To specifically answer your question regarding debugging with GDB you might want to read \"<a href=\"http://wiki.python.org/moin/DebuggingWithGdb\" rel=\"nofollow noreferrer\">Debugging With GDB</a>\" on the python wiki.</p>\n" }, { "answer_id": 273111, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": true, "text": "<p>Yes, you can do this kind of thing:</p>\n\n<pre><code>(gdb) print PyRun_SimpleString(\"import traceback; traceback.print_stack()\")\n File \"&lt;string&gt;\", line 1, in &lt;module&gt;\n File \"/var/tmp/foo.py\", line 2, in &lt;module&gt;\n i**2\n File \"&lt;string&gt;\", line 1, in &lt;module&gt;\n$1 = 0\n</code></pre>\n\n<p>It should also be possible to use the <code>pystack</code> command defined in the python <a href=\"http://svn.python.org/view/python/trunk/Misc/gdbinit?view=auto\" rel=\"noreferrer\">gdbinit</a> file, but it's not working for me. It's discussed <a href=\"http://wiki.python.org/moin/DebuggingWithGdb\" rel=\"noreferrer\">here</a> if you want to look into it.</p>\n\n<p>Also, if you suspect memory issues, it's worth noting that you can use <a href=\"http://valgrind.org/\" rel=\"noreferrer\"><code>valgrind</code></a> with python, if you're prepared to recompile it. The procedure is described <a href=\"http://svn.python.org/projects/python/trunk/Misc/README.valgrind\" rel=\"noreferrer\">here.</a></p>\n" }, { "answer_id": 273204, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 0, "selected": false, "text": "<p>If you're using CDLL to wrap a C library in python, and this is 64-bit linux, there's a good chance that you're CDLL wrapper is misconfigured. CDLL defaults to int return types on all platforms (should be a long long on 64-bit systems) and just expects you to pass the right arguments in. You may need to verify the CDLL wrapper in this case...</p>\n" }, { "answer_id": 273212, "author": "utku_karatas", "author_id": 14716, "author_profile": "https://Stackoverflow.com/users/14716", "pm_score": 0, "selected": false, "text": "<p>In addition to all above one can quickly implement an adhoc tracer via the <a href=\"http://www.python.org/doc/2.5.2/lib/module-trace.html\" rel=\"nofollow noreferrer\">trace module</a>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29825/" ]
We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: > > Python Fatal Error: GC Object already tracked > > > which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.
Yes, you can do this kind of thing: ``` (gdb) print PyRun_SimpleString("import traceback; traceback.print_stack()") File "<string>", line 1, in <module> File "/var/tmp/foo.py", line 2, in <module> i**2 File "<string>", line 1, in <module> $1 = 0 ``` It should also be possible to use the `pystack` command defined in the python [gdbinit](http://svn.python.org/view/python/trunk/Misc/gdbinit?view=auto) file, but it's not working for me. It's discussed [here](http://wiki.python.org/moin/DebuggingWithGdb) if you want to look into it. Also, if you suspect memory issues, it's worth noting that you can use [`valgrind`](http://valgrind.org/) with python, if you're prepared to recompile it. The procedure is described [here.](http://svn.python.org/projects/python/trunk/Misc/README.valgrind)
273,048
<p>How can I calculate the last business day of the month in .NET?</p>
[ { "answer_id": 273065, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 3, "selected": false, "text": "<p>First, get the last day of the month. Then keep decrementing until you're either past the beginning of the month, or have hit a date that validates as a \"business day\".</p>\n" }, { "answer_id": 273094, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 3, "selected": false, "text": "<p>general purpose, pseudocode:</p>\n\n<pre><code>Day day = getLastDayOfMonth\nint days = getDaysInMonth\nfor i = days to 0\n if day is weekday\n if day is not holiday\n return day\n end if\n end if\n day = prevDay\n days--\nend for\n\nthrow exception because no business day was found in the month\n</code></pre>\n" }, { "answer_id": 273099, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 4, "selected": false, "text": "<p>Assuming business days are monday to friday (this doesn't account for holidays), this function should return the proper answer:</p>\n\n<pre><code>Function GetLastBusinessDay(ByVal Year As Integer, ByVal Month As Integer) As DateTime\n Dim LastOfMonth As DateTime\n Dim LastBusinessDay As DateTime\n\n LastOfMonth = New DateTime(Year, Month, DateTime.DaysInMonth(Year, Month))\n\n If LastOfMonth.DayOfWeek = DayOfWeek.Sunday Then \n LastBusinessDay = LastOfMonth.AddDays(-2)\n ElseIf LastOfMonth.DayOfWeek = DayOfWeek.Saturday Then\n LastBusinessDay = LastOfMonth.AddDays(-1)\n Else\n LastBusinessDay = LastOfMonth\n End If\n\n Return LastBusinessDay\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 273162, "author": "Middletone", "author_id": 35331, "author_profile": "https://Stackoverflow.com/users/35331", "pm_score": 0, "selected": false, "text": "<pre><code>Function GetLastDay(ByVal month As Int32, ByVal year As Int32) As Date\n Dim D As New Date(year, month, Date.DaysInMonth(year, month))\n For i As Integer = 0 To Date.DaysInMonth(year, month)\n Select Case D.AddDays(-i).DayOfWeek\n Case DayOfWeek.Saturday, DayOfWeek.Sunday 'Not a weekday\n Case Else 'Is a weekday. Flag as first weekday found\n Return D.AddDays(-i)\n 'you can add other code here which could also do a check for holidays or ther stuff since you have a proper date value to look at in the loop\n End Select\n Next\nEnd Function\n</code></pre>\n" }, { "answer_id": 273182, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 5, "selected": true, "text": "<p>I would do it like this for a Monday through Friday business week:</p>\n\n<pre><code>var holidays = new List&lt;DateTime&gt;{/* list of observed holidays */};\nDateTime lastBusinessDay = new DateTime();\nvar i = DateTime.DaysInMonth(year, month);\nwhile (i &gt; 0)\n{\n var dtCurrent = new DateTime(year, month, i);\n if(dtCurrent.DayOfWeek &lt; DayOfWeek.Saturday &amp;&amp; dtCurrent.DayOfWeek &gt; DayOfWeek.Sunday &amp;&amp; \n !holidays.Contains(dtCurrent))\n {\n lastBusinessDay = dtCurrent;\n i = 0;\n }\n else\n {\n i = i - 1;\n }\n}\n</code></pre>\n" }, { "answer_id": 8801826, "author": "Arvind Sedha", "author_id": 1045321, "author_profile": "https://Stackoverflow.com/users/1045321", "pm_score": 3, "selected": false, "text": "<p>I could think of this simple C# code which gives you the last business day of current month. This only takes Saturday or Sunday as holidays. Country specific local holidays should be handled manually.</p>\n\n<pre><code>private DateTime GetLastBusinessDayOfCurrentMonth()\n{\n var lastDayOfCurrentMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));\n\n if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Sunday)\n lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-2);\n else if(lastDayOfCurrentMonth.DayOfWeek == DayOfWeek.Saturday)\n lastDayOfCurrentMonth = lastDayOfCurrentMonth.AddDays(-1);\n\n return lastDayOfCurrentMonth;\n}\n</code></pre>\n" }, { "answer_id": 26368338, "author": "rbianchi", "author_id": 2347115, "author_profile": "https://Stackoverflow.com/users/2347115", "pm_score": 2, "selected": false, "text": "<p>Using LINQ:</p>\n\n<pre><code> public static DateTime GetLastBussinessDayCurrentMonth(DateTime[] holidays)\n {\n DateTime todayDateTime = DateTime.Today;\n\n return\n Enumerable.Range(1, DateTime.DaysInMonth(todayDateTime.Year, todayDateTime.Month))\n .Select(day =&gt; new DateTime(todayDateTime.Year, todayDateTime.Month, day))\n .Where(\n dt =&gt;\n dt.DayOfWeek != DayOfWeek.Sunday &amp;&amp; dt.DayOfWeek != DayOfWeek.Saturday\n &amp;&amp; (holidays == null || !holidays.Any(h =&gt; h.Equals(dt))))\n .Max(d =&gt; d.Date);\n }\n</code></pre>\n\n<h2>Explaining</h2>\n\n<p>Creating a list of integers with all days available in month</p>\n\n<pre><code> Enumerable.Range(1, DateTime.DaysInMonth(todayDateTime.Year, todayDateTime.Month))\n</code></pre>\n\n<p>Filtering only days that do not fall on weekends and do not fall on holidays</p>\n\n<pre><code> .Where(\n dt =&gt;\n dt.DayOfWeek != DayOfWeek.Sunday &amp;&amp; dt.DayOfWeek != DayOfWeek.Saturday\n &amp;&amp; (holidays == null || !holidays.Any(h =&gt; h.Equals(dt))))\n</code></pre>\n\n<p>Create new datetime with the filtered dates </p>\n\n<pre><code> .Select(day =&gt; new DateTime(todayDateTime.Year, todayDateTime.Month, day))\n\n .Max(d =&gt; d.Date);\n</code></pre>\n" }, { "answer_id": 30877297, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 1, "selected": false, "text": "<p>I came up with an additional method that can be used to get the closest previous or current business day which can then be used to get the last business day of the month - this also takes into account if you are adjusting for weekend holidays:</p>\n\n<pre><code>public static DateTime LastBusinessDayInMonth(int year, int month, bool adjustForWeekend = true)\n{\n var lastDay = DateTime.DaysInMonth(year, month);\n return PreviousOrCurrentBusinessDay(new DateTime(year, month, lastDay), adjustForWeekend);\n}\n\npublic static DateTime PreviousOrCurrentBusinessDay(DateTime? beforeOrOnDate = null, bool adjustForWeekend = true)\n{\n var fromDate = beforeOrOnDate ?? DateTime.Today;\n var year = fromDate.Year;\n var month = fromDate.Month;\n var day = fromDate.Day;\n var holidays = UsHolidays(fromDate.Year, true).ToList(); // defined below\n var dtCurrent = new DateTime(year, month, day);\n\n while (!(dtCurrent.DayOfWeek &lt; DayOfWeek.Saturday &amp;&amp; dtCurrent.DayOfWeek &gt; DayOfWeek.Sunday &amp;&amp; !holidays.Contains(dtCurrent)))\n {\n dtCurrent = dtCurrent.AddDays(-1);\n }\n return dtCurrent;\n}\n</code></pre>\n\n<p>I also use the US holidays in my calculation which I get from the following code I developed from looking at this post: <a href=\"http://geekswithblogs.net/wpeck/archive/2011/12/27/us-holiday-list-in-c.aspx\" rel=\"nofollow\">http://geekswithblogs.net/wpeck/archive/2011/12/27/us-holiday-list-in-c.aspx</a></p>\n\n<p>The code can be seen here for that:</p>\n\n<pre><code>public static IEnumerable&lt;DateTime&gt; UsHolidays(int year, bool adjustForWeekend)\n{\n return new List&lt;DateTime&gt;()\n {\n NewYears(year, adjustForWeekend),\n MlkDay(year),\n PresidentsDay(year),\n GoodFriday(year),\n MemorialDay(year),\n IndependenceDay(year, adjustForWeekend),\n LaborDay(year),\n Thanksgiving(year),\n Christmas(year, adjustForWeekend),\n };\n}\n\npublic static DateTime NewYears(int year, bool adjustForWeekend)\n{\n //NEW YEARS \n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 1, 1).Date) : new DateTime(year, 1, 1).Date;\n}\n\npublic static DateTime MemorialDay(int year)\n{\n //MEMORIAL DAY -- last monday in May \n var memorialDay = new DateTime(year, 5, 31);\n var dayOfWeek = memorialDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n memorialDay = memorialDay.AddDays(-1);\n dayOfWeek = memorialDay.DayOfWeek;\n }\n return memorialDay.Date;\n}\n\npublic static DateTime IndependenceDay(int year, bool adjustForWeekend)\n{\n //INDEPENCENCE DAY \n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 7, 4).Date) : new DateTime(year, 7, 4).Date;\n}\n\npublic static DateTime LaborDay(int year)\n{\n //LABOR DAY -- 1st Monday in September \n var laborDay = new DateTime(year, 9, 1);\n var dayOfWeek = laborDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n laborDay = laborDay.AddDays(1);\n dayOfWeek = laborDay.DayOfWeek;\n }\n return laborDay.Date;\n}\n\npublic static DateTime Thanksgiving(int year)\n{\n //THANKSGIVING DAY - 4th Thursday in November \n var thanksgiving = (from day in Enumerable.Range(1, 30)\n where new DateTime(year, 11, day).DayOfWeek == DayOfWeek.Thursday\n select day).ElementAt(3);\n var thanksgivingDay = new DateTime(year, 11, thanksgiving);\n return thanksgivingDay.Date;\n}\n\npublic static DateTime Christmas(int year, bool adjustForWeekend)\n{\n return adjustForWeekend ? AdjustForWeekendHoliday(new DateTime(year, 12, 25).Date) : new DateTime(year, 12, 25).Date;\n}\n\npublic static DateTime MlkDay(int year)\n{\n //Martin Luther King Day -- third monday in January\n var MLKDay = new DateTime(year, 1, 21);\n var dayOfWeek = MLKDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n MLKDay = MLKDay.AddDays(-1);\n dayOfWeek = MLKDay.DayOfWeek;\n }\n return MLKDay.Date;\n}\n\npublic static DateTime PresidentsDay(int year)\n{\n //President's Day -- third monday in February\n var presDay = new DateTime(year, 2, 21);\n var dayOfWeek = presDay.DayOfWeek;\n while (dayOfWeek != DayOfWeek.Monday)\n {\n presDay = presDay.AddDays(-1);\n dayOfWeek = presDay.DayOfWeek;\n }\n return presDay.Date;\n}\n\npublic static DateTime EasterSunday(int year)\n{\n var g = year % 19;\n var c = year / 100;\n var h = (c - c / 4 - (8 * c + 13) / 25 + 19 * g + 15) % 30;\n var i = h - h / 28 * (1 - h / 28 * (29 / (h + 1)) * ((21 - g) / 11));\n\n var day = i - ((year + year / 4 + i + 2 - c + c / 4) % 7) + 28;\n var month = 3;\n\n if (day &gt; 31)\n {\n month++;\n day -= 31;\n }\n\n return new DateTime(year, month, day);\n}\n\npublic static DateTime GoodFriday(int year)\n{\n return EasterSunday(year).AddDays(-2);\n}\n\npublic static DateTime AdjustForWeekendHoliday(DateTime holiday)\n{\n if (holiday.DayOfWeek == DayOfWeek.Saturday)\n {\n return holiday.AddDays(-1);\n }\n return holiday.DayOfWeek == DayOfWeek.Sunday ? holiday.AddDays(1) : holiday;\n}\n</code></pre>\n" }, { "answer_id": 34235887, "author": "user5671127", "author_id": 5671127, "author_profile": "https://Stackoverflow.com/users/5671127", "pm_score": -1, "selected": false, "text": "<p>Here is how to find the last day of the month in C#:</p>\n\n<pre><code>DateTime today = DateTime.Today;\nDateTime endOfMonth = new DateTime(today.Year,\n today.Month,\n DateTime.DaysInMonth(today.Year,\n today.Month));\n</code></pre>\n\n<p><a href=\"http://geekprogrammers.com/question/how-can-i-find-the-last-day-of-the-month-in-c/\" rel=\"nofollow\">Source</a></p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
How can I calculate the last business day of the month in .NET?
I would do it like this for a Monday through Friday business week: ``` var holidays = new List<DateTime>{/* list of observed holidays */}; DateTime lastBusinessDay = new DateTime(); var i = DateTime.DaysInMonth(year, month); while (i > 0) { var dtCurrent = new DateTime(year, month, i); if(dtCurrent.DayOfWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek > DayOfWeek.Sunday && !holidays.Contains(dtCurrent)) { lastBusinessDay = dtCurrent; i = 0; } else { i = i - 1; } } ```
273,081
<p>I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout. </p> <p>I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary.</p> <p>Something like:</p> <pre><code>if (UserProperties.Role == Roles.Admin) { btnDelete.Visible = false; } </code></pre> <p>What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these.</p> <p>Is a User object that gets passed around to each form's contructor just as bad?</p>
[ { "answer_id": 273098, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 0, "selected": false, "text": "<p>You can use the Profile provider from the asp.net in you Windows App. Check it out @ <a href=\"http://fredrik.nsquared2.com/viewpost.aspx?PostID=244&amp;showfeedback=true\" rel=\"nofollow noreferrer\">http://fredrik.nsquared2.com/viewpost.aspx?PostID=244&amp;showfeedback=true</a></p>\n\n<p>Hope it helps,\nBruno Figueiredo\n<a href=\"http://www.brunofigueiredo.com\" rel=\"nofollow noreferrer\">http://www.brunofigueiredo.com</a></p>\n" }, { "answer_id": 273100, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 2, "selected": false, "text": "<p>Maybe my judgement is clouded by my frequent use of javascript, but I think that if you have something that is <strong>meant</strong> to be global, then using global variables is okay.</p>\n\n<p>Global is bad when you are exposing things globally that shouldn't be. Global is okay if it is semantically correct for the intended use of the data.</p>\n" }, { "answer_id": 273292, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "<p>Set <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx\" rel=\"nofollow noreferrer\">Thread.CurrentPrincipal</a> with either the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.aspx\" rel=\"nofollow noreferrer\">WindowsPrincipal</a>, a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx\" rel=\"nofollow noreferrer\">GenericPrincipal</a> or your custom principal. Then, you can just call <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.isinrole.aspx\" rel=\"nofollow noreferrer\">IsInRole</a>:</p>\n\n<pre><code>if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) {\n btnDelete.Visible = false;\n}\n</code></pre>\n" }, { "answer_id": 273320, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 0, "selected": false, "text": "<p>Static data (or a singleton) seems fine for this if you want to scope the data to the application instance (or AppDomain).</p>\n\n<p>However, given that you're talking about in effect caching a user's security credentials, you may want to carefully think about security loopholes. For example, what happens if the user leaves the application running for days? They could be performing operations under their days-old credentials rather than their most current credentials. Depending on what you're securing you might be better off checking credentials on demand or at least expiring the cached credentials periodically.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout. I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary. Something like: ``` if (UserProperties.Role == Roles.Admin) { btnDelete.Visible = false; } ``` What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these. Is a User object that gets passed around to each form's contructor just as bad?
Set [Thread.CurrentPrincipal](http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx) with either the [WindowsPrincipal](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.aspx), a [GenericPrincipal](http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx) or your custom principal. Then, you can just call [IsInRole](http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.isinrole.aspx): ``` if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) { btnDelete.Visible = false; } ```
273,103
<p>I have a class that inherits from a base class and implements the following...</p> <pre><code> Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo </code></pre> <p>Now the base class it inherits from also implements this System.IComparable.CompareTo so I'm getting the following compiler warning:</p> <p><em>Warning: 'System.IComparable.CompareTo' is already implemented by the base class. Re-implementation of function assumed.</em> </p> <p>I'm fine with that so my question is how can I suppress this warning for just this function (i.e. not all such warnings).</p> <p><strong>Clarifications:</strong> </p> <ul> <li>Here is a <a href="http://msdn.microsoft.com/en-us/library/dwwt4s94(VS.80).aspx" rel="noreferrer">link</a> to the error on MSDN. </li> <li>I've already tried both Shadows and Overrides and neither eliminates the warning. </li> <li>The warning isn't on the method itself (unless Shadows or Overrides are omitted), but rather it's on "Implements System.IComparable.CompareTo" specifically.</li> <li>I am not looking to suppress all warnings of this type (if they crop up), just this one.</li> </ul> <p><strong>Solution:</strong><br> I was hoping to use the System.Diagnostics.CodeAnalysis.SuppressMessage attribute or something like C#'s #pragma but looks like there's no way to suppress the warning for a single line. There is a way to turn this message off for this project though, without turning <em>all</em> warnings off.</p> <p>I manually edited the .vbproj file and included 42015 in the node for Debug and Release compilations. Not ideal but better than always seeing the warning in the IDE.</p> <p>If someone has a better solution please add it and I'll gladly try it flag the answer.</p>
[ { "answer_id": 273114, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": -1, "selected": false, "text": "<p>On the properties of your project, go to the build tab and use the suppress warnings textbox.</p>\n" }, { "answer_id": 273137, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": -1, "selected": false, "text": "<p>Add the keyword Shadows to the function definition. </p>\n\n<pre><code>Public Shadows Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n</code></pre>\n" }, { "answer_id": 273143, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": -1, "selected": false, "text": "<p>Rather than suppressing the warning, shouldn't you be fixing it? Assuming that the base is Overridable,</p>\n\n<pre><code>Public Overrides Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n</code></pre>\n\n<p>If not, then shadow it,</p>\n\n<pre><code>Public Shadows Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n</code></pre>\n\n<p>(I think this is correct, I am a C# programmer. If not, please comment and I will update.)</p>\n" }, { "answer_id": 305418, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 1, "selected": false, "text": "<p>You can use the supress warnings just to suppress one warning. See here for <a href=\"http://msdn.microsoft.com/en-us/library/ms182069(VS.80).aspx\" rel=\"nofollow noreferrer\">more</a> on how to.\nYou can also use the <a href=\"http://msdn.microsoft.com/en-us/library/ms182068(VS.80).aspx\" rel=\"nofollow noreferrer\">SuppressMessage Attribute</a>.</p>\n" }, { "answer_id": 2324880, "author": "Topi", "author_id": 280188, "author_profile": "https://Stackoverflow.com/users/280188", "pm_score": 4, "selected": true, "text": "<p>Only use 'Implements' in the base class:</p>\n\n<p>Signature in the base class: </p>\n\n<pre><code>Public Overridable Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo\n</code></pre>\n\n<p>Signature in the inherited class:</p>\n\n<pre><code>Public Overrides Function CompareTo(ByVal obj As Object) As Integer\n</code></pre>\n" }, { "answer_id": 17092972, "author": "Chris", "author_id": 2483199, "author_profile": "https://Stackoverflow.com/users/2483199", "pm_score": 0, "selected": false, "text": "<p>If you don't have access to the base class and therefore can't make the method Overrideable, you can add <code>&lt;NoWarn&gt;42015&lt;/NoWarn&gt;</code> to the project file.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
I have a class that inherits from a base class and implements the following... ``` Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo ``` Now the base class it inherits from also implements this System.IComparable.CompareTo so I'm getting the following compiler warning: *Warning: 'System.IComparable.CompareTo' is already implemented by the base class. Re-implementation of function assumed.* I'm fine with that so my question is how can I suppress this warning for just this function (i.e. not all such warnings). **Clarifications:** * Here is a [link](http://msdn.microsoft.com/en-us/library/dwwt4s94(VS.80).aspx) to the error on MSDN. * I've already tried both Shadows and Overrides and neither eliminates the warning. * The warning isn't on the method itself (unless Shadows or Overrides are omitted), but rather it's on "Implements System.IComparable.CompareTo" specifically. * I am not looking to suppress all warnings of this type (if they crop up), just this one. **Solution:** I was hoping to use the System.Diagnostics.CodeAnalysis.SuppressMessage attribute or something like C#'s #pragma but looks like there's no way to suppress the warning for a single line. There is a way to turn this message off for this project though, without turning *all* warnings off. I manually edited the .vbproj file and included 42015 in the node for Debug and Release compilations. Not ideal but better than always seeing the warning in the IDE. If someone has a better solution please add it and I'll gladly try it flag the answer.
Only use 'Implements' in the base class: Signature in the base class: ``` Public Overridable Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo ``` Signature in the inherited class: ``` Public Overrides Function CompareTo(ByVal obj As Object) As Integer ```
273,126
<p>I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless.</p> <p>Is an identifier being for the HttpContext object being sent as part of the __EVENTTarget / __EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)? I don't think</p> <p>Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this.</p> <p>I understand something like HttpContext.Current.Session["myKey"] = Value;</p> <p>just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I?</p> <p>Thanks -Venu</p>
[ { "answer_id": 273154, "author": "Greg Smalter", "author_id": 34290, "author_profile": "https://Stackoverflow.com/users/34290", "pm_score": 0, "selected": false, "text": "<p>I don't think there is one answer to your question, because I don't think everything under the HttpContext umbrella works the same way. In the example you chose, session state, both the key and value are stored on the server side. The way it knows how to hook up future requests to that session state is by using a cookie that has a (totally different) key in it. When the browser makes another request, it sends this cookie with the request and the server uses it to figure out which session to map to. Once it figures it out, you've again got access to your dictionary, across responses.</p>\n\n<p>So, to do it in perl, you'd want to manually create a cookie and store a unique key in it, have a server-side mapping of those unique keys to session state dictionaries, and pretty much do what I described above.</p>\n" }, { "answer_id": 273224, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "<p>The HttpContext is recreated for each request. The HttpSession, however, is stored on the server across requests. Basically, HttpSession is a Dictionary&lt;string, Dictionary&lt;string, object&gt;&gt;. The initial key, the session id, is provided by either a cookie or a query string parameter (if using cookie-less sessions). If you use Fiddler, you'll see the ASP.NET_SessionId cookie that contains the key for that user's session.</p>\n\n<p>In code:</p>\n\n<pre><code>class HttpSessionState {\n private static readonly Sessions = \n new Dictionary&lt;string, Dictionary&lt;string, object&gt;&gt;();\n\n public object this(string key) {\n get {\n return GetCurrentUserSession()[key]\n }\n set {\n GetCurrentUserSession()[key] = value;\n }\n }\n\n private Dictionary&lt;string, object&gt; GetCurrentUserSession() {\n var id = GetCurrentUserSessionId[]\n var d = Sessions[id];\n if (d == null) {\n d = new Dictionary&lt;string, object&gt;();\n Sessions[id] = d;\n }\n return d;\n }\n\n private string GetCurrentUserSessionId() {\n return HttpContext.Current.Request.Cookies[\"ASP.NET_SessionId\"].Value;\n }\n}\n</code></pre>\n\n<p>The real implementation also handles session timeouts, abandons, and cookieless sessions - but the basic idea is the same.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35559/" ]
I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless. Is an identifier being for the HttpContext object being sent as part of the \_\_EVENTTarget / \_\_EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)? I don't think Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this. I understand something like HttpContext.Current.Session["myKey"] = Value; just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I? Thanks -Venu
The HttpContext is recreated for each request. The HttpSession, however, is stored on the server across requests. Basically, HttpSession is a Dictionary<string, Dictionary<string, object>>. The initial key, the session id, is provided by either a cookie or a query string parameter (if using cookie-less sessions). If you use Fiddler, you'll see the ASP.NET\_SessionId cookie that contains the key for that user's session. In code: ``` class HttpSessionState { private static readonly Sessions = new Dictionary<string, Dictionary<string, object>>(); public object this(string key) { get { return GetCurrentUserSession()[key] } set { GetCurrentUserSession()[key] = value; } } private Dictionary<string, object> GetCurrentUserSession() { var id = GetCurrentUserSessionId[] var d = Sessions[id]; if (d == null) { d = new Dictionary<string, object>(); Sessions[id] = d; } return d; } private string GetCurrentUserSessionId() { return HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value; } } ``` The real implementation also handles session timeouts, abandons, and cookieless sessions - but the basic idea is the same.
273,141
<p>I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.</p> <pre><code>string compare = "1234=4321"; Regex regex = new Regex(@"[\d]"); if (regex.IsMatch(compare)) { //true } regex = new Regex("[0-9]"); if (regex.IsMatch(compare)) { //true } </code></pre> <p>In case it matters, I'm using C# and .NET2.0.</p>
[ { "answer_id": 273144, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 10, "selected": true, "text": "<p>Use the beginning and end anchors.</p>\n\n<pre><code>Regex regex = new Regex(@\"^\\d$\");\n</code></pre>\n\n<p>Use <code>\"^\\d+$\"</code> if you need to match more than one digit.</p>\n\n<hr>\n\n<p>Note that <code>\"\\d\"</code> will match <code>[0-9]</code> and other digit characters like the Eastern Arabic numerals <code>٠١٢٣٤٥٦٧٨٩</code>. Use <code>\"^[0-9]+$\"</code> to restrict matches to just the Arabic numerals 0 - 9.</p>\n\n<hr>\n\n<p>If you need to include any numeric representations other than just digits (like decimal values for starters), then see <a href=\"https://stackoverflow.com/users/471272/tchrist\">@tchrist</a>'s <a href=\"https://stackoverflow.com/a/4247184/1288\">comprehensive guide to parsing numbers with regular expressions</a>.</p>\n" }, { "answer_id": 273150, "author": "kasperjj", "author_id": 34240, "author_profile": "https://Stackoverflow.com/users/34240", "pm_score": 4, "selected": false, "text": "<p>It is matching because it is finding \"a match\" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.</p>\n\n<pre><code>^\\d+$\n</code></pre>\n" }, { "answer_id": 273152, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 7, "selected": false, "text": "<p>Your regex will match anything that contains a number, you want to use anchors to match the whole string and then match one or more numbers:</p>\n\n<pre><code>regex = new Regex(\"^[0-9]+$\");\n</code></pre>\n\n<p>The <code>^</code> will anchor the beginning of the string, the <code>$</code> will anchor the end of the string, and the <code>+</code> will match one or more of what precedes it (a number in this case).</p>\n" }, { "answer_id": 273156, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": false, "text": "<p>^\\d+$, which is \"start of string\", \"1 or more digits\", \"end of string\" in English.</p>\n" }, { "answer_id": 4085796, "author": "James Selvakumar", "author_id": 361172, "author_profile": "https://Stackoverflow.com/users/361172", "pm_score": 2, "selected": false, "text": "<p>If you want to extract only numbers from a string the pattern \"\\d+\" should help.</p>\n" }, { "answer_id": 5717007, "author": "Andrew Chaa", "author_id": 437961, "author_profile": "https://Stackoverflow.com/users/437961", "pm_score": 6, "selected": false, "text": "<p>If you need to tolerate decimal point and thousand marker</p>\n\n<pre><code>var regex = new Regex(@\"^-?[0-9][0-9,\\.]+$\");\n</code></pre>\n\n<p>You will need a \"-\", if the number can go negative.</p>\n" }, { "answer_id": 10367753, "author": "S.M.Mousavi", "author_id": 1074799, "author_profile": "https://Stackoverflow.com/users/1074799", "pm_score": 3, "selected": false, "text": "<p>Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression:</p>\n\n<pre><code>Regex = new Regex(@\"^[\\p{N}]+$\");\n</code></pre>\n\n<p>To match literal period character use:</p>\n\n<pre><code>Regex = new Regex(@\"^[\\p{N}\\.]+$\");\n</code></pre>\n" }, { "answer_id": 21267370, "author": "Rezo Megrelidze", "author_id": 2204040, "author_profile": "https://Stackoverflow.com/users/2204040", "pm_score": 4, "selected": false, "text": "<p>Perhaps my method will help you. </p>\n\n<pre><code> public static bool IsNumber(string s)\n {\n return s.All(char.IsDigit);\n }\n</code></pre>\n" }, { "answer_id": 22112198, "author": "ultraklon", "author_id": 680933, "author_profile": "https://Stackoverflow.com/users/680933", "pm_score": 5, "selected": false, "text": "<p>This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator , </p>\n\n<pre><code>\"^-?\\\\d*(\\\\.\\\\d+)?$\"\n</code></pre>\n\n<p>some strings that matches with this:</p>\n\n<pre><code>894\n923.21\n76876876\n.32\n-894\n-923.21\n-76876876\n-.32\n</code></pre>\n\n<p>some strings that doesn't:</p>\n\n<pre><code>hello\n9bye\nhello9bye\n888,323\n5,434.3\n-8,336.09\n87078.\n</code></pre>\n" }, { "answer_id": 22858505, "author": "fnc12", "author_id": 1927176, "author_profile": "https://Stackoverflow.com/users/1927176", "pm_score": 4, "selected": false, "text": "<p>Sorry for ugly formatting.\nFor any number of digits:</p>\n\n<pre><code>[0-9]*\n</code></pre>\n\n<p>For one or more digit:</p>\n\n<pre><code>[0-9]+\n</code></pre>\n" }, { "answer_id": 23798355, "author": "Ujjal Suttra Dhar", "author_id": 1591437, "author_profile": "https://Stackoverflow.com/users/1591437", "pm_score": 4, "selected": false, "text": "<p>If you need to check if all the digits are number (0-9) or not,</p>\n<pre><code>^[0-9]+$\n</code></pre>\n<p>Matches</p>\n<pre><code>1425\n0142\n0\n1\n</code></pre>\n<p>And does not match</p>\n<pre><code>154a25\n1234=3254\n</code></pre>\n" }, { "answer_id": 29996319, "author": "Giri babu vuppula", "author_id": 4855723, "author_profile": "https://Stackoverflow.com/users/4855723", "pm_score": -1, "selected": false, "text": "<p>Regex regex = new Regex (\"^[0-9]{1,4}=[0-9]{1,4]$\")</p>\n" }, { "answer_id": 33976065, "author": "Marina", "author_id": 5311928, "author_profile": "https://Stackoverflow.com/users/5311928", "pm_score": 4, "selected": false, "text": "<p>Here is my working one:</p>\n\n<pre><code>^(-?[1-9]+\\\\d*([.]\\\\d+)?)$|^(-?0[.]\\\\d*[1-9]+)$|^0$\n</code></pre>\n\n<p>And some tests</p>\n\n<p>Positive tests:</p>\n\n<pre><code>string []goodNumbers={\"3\",\"-3\",\"0\",\"0.0\",\"1.0\",\"0.1\",\"0.0001\",\"-555\",\"94549870965\"};\n</code></pre>\n\n<p>Negative tests:</p>\n\n<pre><code>string []badNums={\"a\",\"\",\" \",\"-\",\"001\",\"-00.2\",\"000.5\",\".3\",\"3.\",\" -1\",\"--1\",\"-.1\",\"-0\"};\n</code></pre>\n\n<p>Checked not only for C#, but also with Java, Javascript and PHP</p>\n" }, { "answer_id": 35545697, "author": "Tagar", "author_id": 470583, "author_profile": "https://Stackoverflow.com/users/470583", "pm_score": 3, "selected": false, "text": "<p>Regex for integer and floating point numbers:</p>\n\n<pre><code>^[+-]?\\d*\\.\\d+$|^[+-]?\\d+(\\.\\d*)?$\n</code></pre>\n\n<p>A number can start with a period (without leading digits(s)),\nand a number can end with a period (without trailing digits(s)).\nAbove regex will recognize both as correct numbers.</p>\n\n<p>A . (period) itself without any digits is not a correct number.\nThat's why we need two regex parts there (separated with a \"|\").</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 38222062, "author": "lipika chakraborty", "author_id": 6400165, "author_profile": "https://Stackoverflow.com/users/6400165", "pm_score": 3, "selected": false, "text": "<p>Use beginning and end anchors.</p>\n<pre><code> Regex regex = new Regex(@&quot;^\\d$&quot;);\n</code></pre>\n<p>Use <code>&quot;^\\d+$&quot;</code> if you need to match more than one digit.</p>\n" }, { "answer_id": 39266103, "author": "Azur", "author_id": 4700600, "author_profile": "https://Stackoverflow.com/users/4700600", "pm_score": 2, "selected": false, "text": "<p>I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12\nAlso this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22\nIn addition to this numbers like .55 or ,55 would pass. This may be handy.</p>\n\n<pre><code>^([,|.]?[0-9])+$\n</code></pre>\n" }, { "answer_id": 39446526, "author": "Daniele D.", "author_id": 4454567, "author_profile": "https://Stackoverflow.com/users/4454567", "pm_score": 3, "selected": false, "text": "<p>While non of the above solutions was fitting my purpose, this worked for me.</p>\n<pre><code>var pattern = @&quot;^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$|^0.0$&quot;;\nreturn Regex.Match(value, pattern, RegexOptions.IgnoreCase).Success;\n</code></pre>\n<p>Example of valid values:</p>\n<pre><code>&quot;3&quot;,\n&quot;-3&quot;,\n&quot;0&quot;,\n&quot;0.0&quot;,\n&quot;1.0&quot;,\n&quot;0.7&quot;,\n&quot;690.7&quot;,\n&quot;0.0001&quot;,\n&quot;-555&quot;,\n&quot;945465464654&quot;\n</code></pre>\n<p>Example of not valid values:</p>\n<pre><code>&quot;a&quot;,\n&quot;&quot;,\n&quot; &quot;,\n&quot;.&quot;,\n&quot;-&quot;,\n&quot;001&quot;,\n&quot;00.2&quot;,\n&quot;000.5&quot;,\n&quot;.3&quot;,\n&quot;3.&quot;,\n&quot; -1&quot;,\n&quot;--1&quot;,\n&quot;-.1&quot;,\n&quot;-0&quot;,\n&quot;00099&quot;,\n&quot;099&quot;\n</code></pre>\n" }, { "answer_id": 64798219, "author": "Chathuranga Kasthuriarachchi", "author_id": 12212419, "author_profile": "https://Stackoverflow.com/users/12212419", "pm_score": 2, "selected": false, "text": "<pre><code> console.log(/^(0|[1-9][0-9]*)$/.test(3000)) // true\n</code></pre>\n" }, { "answer_id": 67945746, "author": "Programmer", "author_id": 5714602, "author_profile": "https://Stackoverflow.com/users/5714602", "pm_score": 0, "selected": false, "text": "<p>The following regex accepts only numbers (also floating point) in both English and Arabic (Persian) languages (just like Windows calculator):</p>\n<pre><code>^((([0\\u0660\\u06F0]|([1-9\\u0661-\\u0669\\u06F1-\\u06F9][0\\u0660\\u06F0]*?)+)(\\.)[0-9\\u0660-\\u0669\\u06F0-\\u06F9]+)|(([0\\u0660\\u06F0]?|([1-9\\u0661-\\u0669\\u06F1-\\u06F9][0\\u0660\\u06F0]*?)+))|\\b)$\n</code></pre>\n<p>The above regex accepts the following patterns:</p>\n<pre><code>11\n1.2\n0.3\n۱۲\n۱.۳\n۰.۲\n۲.۷\n</code></pre>\n<p>The above regex doesn't accept the following patterns:</p>\n<pre><code>3.\n.3\n0..3\n.۱۲\n</code></pre>\n" }, { "answer_id": 69031564, "author": "Yawar Ali", "author_id": 5951242, "author_profile": "https://Stackoverflow.com/users/5951242", "pm_score": 0, "selected": false, "text": "<p>To check string is uint, ulong or contains only digits one .(dot) and digits\nSample inputs</p>\n<pre><code>Regex rx = new Regex(@&quot;^([1-9]\\d*(\\.)\\d*|0?(\\.)\\d*[1-9]\\d*|[1-9]\\d*)$&quot;);\nstring text = &quot;12.0&quot;;\nvar result = rx.IsMatch(text);\nConsole.WriteLine(result);\n</code></pre>\n<p>Samples</p>\n<pre><code>123 =&gt; True\n123.1 =&gt; True\n0.123 =&gt; True\n.123 =&gt; True\n0.2 =&gt; True\n3452.434.43=&gt; False\n2342f43.34 =&gt; False\nsvasad.324 =&gt; False\n3215.afa =&gt; False\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4660/" ]
I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions. ``` string compare = "1234=4321"; Regex regex = new Regex(@"[\d]"); if (regex.IsMatch(compare)) { //true } regex = new Regex("[0-9]"); if (regex.IsMatch(compare)) { //true } ``` In case it matters, I'm using C# and .NET2.0.
Use the beginning and end anchors. ``` Regex regex = new Regex(@"^\d$"); ``` Use `"^\d+$"` if you need to match more than one digit. --- Note that `"\d"` will match `[0-9]` and other digit characters like the Eastern Arabic numerals `٠١٢٣٤٥٦٧٨٩`. Use `"^[0-9]+$"` to restrict matches to just the Arabic numerals 0 - 9. --- If you need to include any numeric representations other than just digits (like decimal values for starters), then see [@tchrist](https://stackoverflow.com/users/471272/tchrist)'s [comprehensive guide to parsing numbers with regular expressions](https://stackoverflow.com/a/4247184/1288).
273,142
<p>I'm looking to patch a piece of abandonware with some code.</p> <p>The software is carbon based, so I can not use an InputManager (at least, I do not think I can). My idea was to add a dylib reference to the mach-o header, and launch a new thread when the initialization routine is called.</p> <p>I have mucked around with the mach-o header using a hexeditor to add the appropriate load command (LC_ LOAD_DYLIB). </p> <p>otool reports what I expect to see, so I'm fairly confident that the file is correctly formatted.</p> <pre> Load command 63 cmd LC_LOAD_DYLIB cmdsize 60 name @executable_path/libAltInput.dylib (offset 24) time stamp 1183743291 Fri Jul 6 19:34:51 2007 current version 0.0.0 compatibility version 0.0.0 </pre> <p>However, launching the binary gives me the following error</p> <pre> dyld: bad external relocation length </pre> <p>All I can guess this means is that I need to modify the LC_ SYMTAB or LC_ DYNSYMTAB sections...</p> <p>Anyone have any ideas?</p>
[ { "answer_id": 273213, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 4, "selected": true, "text": "<p>I'm not entirely sure what you're trying to accomplish, but the easiest way to do this is probably to inject a thread into the mach task after it starts. A great source of information on doing this (as well as running code to do it) can be found here: <a href=\"http://rentzsch.com/mach_inject/\" rel=\"noreferrer\">http://rentzsch.com/mach_inject/</a>.</p>\n\n<p>Some caveats that you should be aware of:</p>\n\n<ol>\n<li>the mach task_for_pid() call necessary to get the mach port to the task is now privleged and requires authorization to call. The reason for this is pretty self-evident but if you were planning on releasing something with injected code, you should be aware of this.</li>\n<li>Your code will be running in the same process space as the original application but on a separate thread. You will, therefore, have full access to the application, however, if it is not thread-aware be very careful about using and manipulating data from outside of your injected code. Obviously all multithreaded issues will be amplified here because the original code was never aware of your additions.</li>\n</ol>\n" }, { "answer_id": 1990844, "author": "caleb", "author_id": 242160, "author_profile": "https://Stackoverflow.com/users/242160", "pm_score": 2, "selected": false, "text": "<p>The easiest solution that doesn't involve patching the binary is to simply use the DYLD_INSERT_LIBRARIES environment variable and then run your application.</p>\n\n<pre><code>set DYLD_INSERT_LIBRARIES to /my/path/libAltInput.dylib\n</code></pre>\n\n<p>I'm assuming the reason the dynamic linker reported an error is because many fields in the Mach-O file format contain addresses specified as an offset from the beginning of the file so adding another load command would invalidate every address. For example, see the <code>symoff</code> and <code>stroff</code> entries in the <a href=\"http://developer.apple.com/Mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html#//apple_ref/c/tag/symtab_command\" rel=\"nofollow noreferrer\">Mac OS X ABI Mach-O File Format Reference</a>.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking to patch a piece of abandonware with some code. The software is carbon based, so I can not use an InputManager (at least, I do not think I can). My idea was to add a dylib reference to the mach-o header, and launch a new thread when the initialization routine is called. I have mucked around with the mach-o header using a hexeditor to add the appropriate load command (LC\_ LOAD\_DYLIB). otool reports what I expect to see, so I'm fairly confident that the file is correctly formatted. ``` Load command 63 cmd LC_LOAD_DYLIB cmdsize 60 name @executable_path/libAltInput.dylib (offset 24) time stamp 1183743291 Fri Jul 6 19:34:51 2007 current version 0.0.0 compatibility version 0.0.0 ``` However, launching the binary gives me the following error ``` dyld: bad external relocation length ``` All I can guess this means is that I need to modify the LC\_ SYMTAB or LC\_ DYNSYMTAB sections... Anyone have any ideas?
I'm not entirely sure what you're trying to accomplish, but the easiest way to do this is probably to inject a thread into the mach task after it starts. A great source of information on doing this (as well as running code to do it) can be found here: <http://rentzsch.com/mach_inject/>. Some caveats that you should be aware of: 1. the mach task\_for\_pid() call necessary to get the mach port to the task is now privleged and requires authorization to call. The reason for this is pretty self-evident but if you were planning on releasing something with injected code, you should be aware of this. 2. Your code will be running in the same process space as the original application but on a separate thread. You will, therefore, have full access to the application, however, if it is not thread-aware be very careful about using and manipulating data from outside of your injected code. Obviously all multithreaded issues will be amplified here because the original code was never aware of your additions.
273,151
<p>I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks or other characters depending on the encoding used to load into a string.</p> <p>I'm using this to read the text:</p> <pre><code>string html = File.ReadAllText(myFileSpec); </code></pre> <p>I've also tried using StreamReader, but get the same results (maybe it's used internally by File.ReadAllText).</p> <p>I've also tried specifying every type of Encoding in the second overload of File.ReadAllText:</p> <pre><code>string html = File.ReadAllText(originalFile, Encoding.ASCII); </code></pre> <p>I've tried all the available enums for the Encoding type.</p> <p>Any ideas?</p>
[ { "answer_id": 273171, "author": "osp70", "author_id": 2357, "author_profile": "https://Stackoverflow.com/users/2357", "pm_score": 0, "selected": false, "text": "<p>Did you try opening the file in binary mode. If you open in test mode I think it will chop up the unicode characters.</p>\n" }, { "answer_id": 273423, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 0, "selected": false, "text": "<p>Isn't the problem that Word's <code>.doc</code> to <code>.html</code> conversion turns the bullet points to question marks (and it hasn't got anything to do with <code>File.ReadAllText</code> or <code>StreamReader</code> etc)?</p>\n\n<p>i.e. by the time it gets to <code>File.ReadAllText</code> it is already a question mark.</p>\n\n<p>When I convert a simple simple Word list to HTML in Word 2003, I get </p>\n\n<pre><code> &lt;ul style='margin-top:0cm' type=disc&gt; \n &lt;li class=MsoNormal style='mso-list:l0 level1 lfo1;tab-stops:list 36.0pt'&gt;\n &lt;span lang=EN-GB style='mso-ansi-language:EN-GB'&gt;Test 1&lt;/span&gt;\n &lt;/li&gt; \n &lt;li class=MsoNormal style='mso-list:l0 level1 lfo1;tab-stops:list 36.0pt'&gt;\n &lt;span lang=EN-GB style='mso-ansi-language:EN-GB'&gt;Test 2&lt;/span&gt;\n &lt;/li&gt; \n &lt;/ul&gt;\n</code></pre>\n\n<p>It's ugly, but it doesn't contain anything that could become a question mark</p>\n" }, { "answer_id": 273441, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>What these characters look like in the HTML file? What is the encoding declaration of this file (in the meta tag \"Content-Type\")? Ideally, these characters should be transformed into entities or UTF-8 characters.<br>\nAnswering these questions might lead you to the solution... :-)</p>\n" }, { "answer_id": 273573, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 3, "selected": true, "text": "<p>On my system (using US-English) Word saves *.htm files in the Windows-1252 codepage. If your system uses that codepage, then that is what you should read it in as.</p>\n\n<pre><code>string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252));\n</code></pre>\n\n<p>It is also possible that whatever you are using the view the results may be creating the question marks for you, though, so be sure and check for that too.</p>\n" }, { "answer_id": 273640, "author": "Todd Price", "author_id": 29107, "author_profile": "https://Stackoverflow.com/users/29107", "pm_score": 0, "selected": false, "text": "<p>OK, apparently I lied in my first statement. I thought I had tried every encoding, but I had not tried this:</p>\n\n<pre><code>data = File.ReadAllText(tempFile, Encoding.Default);\n</code></pre>\n\n<p>You'd think that the overload of this method where you DO NOT specify an encoding would work just fine, expecting the default encoding to be, well, Encoding.Default. However, it actually uses Encoding.UTF8 by default. Hope this helps someone else.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29107/" ]
I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks or other characters depending on the encoding used to load into a string. I'm using this to read the text: ``` string html = File.ReadAllText(myFileSpec); ``` I've also tried using StreamReader, but get the same results (maybe it's used internally by File.ReadAllText). I've also tried specifying every type of Encoding in the second overload of File.ReadAllText: ``` string html = File.ReadAllText(originalFile, Encoding.ASCII); ``` I've tried all the available enums for the Encoding type. Any ideas?
On my system (using US-English) Word saves \*.htm files in the Windows-1252 codepage. If your system uses that codepage, then that is what you should read it in as. ``` string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252)); ``` It is also possible that whatever you are using the view the results may be creating the question marks for you, though, so be sure and check for that too.
273,169
<p>How can I dynamically invoke a class method in PHP? The class method is not static. It appears that </p> <pre><code>call_user_func(...) </code></pre> <p>only works with static functions?</p> <p>Thanks.</p>
[ { "answer_id": 273175, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 2, "selected": false, "text": "<pre><code>call_user_func(array($object, 'methodName'));\n</code></pre>\n\n<p>For more details, see the <a href=\"http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback\" rel=\"nofollow noreferrer\">php callback documentation.</a></p>\n" }, { "answer_id": 273176, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 8, "selected": true, "text": "<p>It works both ways - you need to use the right syntax</p>\n\n<pre><code>// Non static call\ncall_user_func( array( $obj, 'method' ) );\n\n// Static calls\ncall_user_func( array( 'ClassName', 'method' ) );\ncall_user_func( 'ClassName::method' ); // (As of PHP 5.2.3)\n</code></pre>\n" }, { "answer_id": 273186, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "<p>You mean like this?</p>\n\n<pre><code>&lt;?php\n\nclass A {\n function test() {\n print 'test';\n }\n}\n\n$function = 'test';\n\n// method 1\nA::$function();\n\n// method 2\n$a = new A; \n$a-&gt;$function();\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 273930, "author": "David", "author_id": 9908, "author_profile": "https://Stackoverflow.com/users/9908", "pm_score": 5, "selected": false, "text": "<p>Option 1</p>\n\n<pre><code>// invoke an instance method\n$instance = new Instance();\n$instanceMethod = 'bar';\n$instance-&gt;$instanceMethod();\n\n// invoke a static method\n$class = 'NameOfTheClass';\n$staticMethod = 'blah';\n$class::$staticMethod();\n</code></pre>\n\n<p>Option 2</p>\n\n<pre><code>// invoke an instance method\n$instance = new Instance();\ncall_user_func( array( $instance, 'method' ) );\n\n// invoke a static method\n$class = 'NameOfTheClass';\ncall_user_func( array( $class, 'nameOfStaticMethod' ) );\ncall_user_func( 'NameOfTheClass::nameOfStaticMethod' ); // (As of PHP 5.2.3)\n</code></pre>\n\n<p>Option 1 is faster than Option 2 so try to use them unless you don't know how many arguments your going to be passing to the method.</p>\n\n<hr>\n\n<p>Edit: Previous editor did great job of cleaning up my answer but removed mention of call_user_func_array which is different then call_user_func. </p>\n\n<p>PHP has </p>\n\n<pre><code>mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) \n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.call-user-func.php\" rel=\"noreferrer\">http://php.net/manual/en/function.call-user-func.php</a></p>\n\n<p>AND </p>\n\n<pre><code>mixed call_user_func_array ( callable $callback , array $param_arr )\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.call-user-func-array.php\" rel=\"noreferrer\">http://php.net/manual/en/function.call-user-func-array.php</a></p>\n\n<p>Using call_user_func_array is orders of magnitude slower then using either option listed above.</p>\n" }, { "answer_id": 276913, "author": "Bingy", "author_id": 69518, "author_profile": "https://Stackoverflow.com/users/69518", "pm_score": 1, "selected": false, "text": "<p>EDIT: I just worked out what you were trying to ask... ah well.. will leave my comments in anyway. You can substitute names of classes and methods with variables if you like..(but you are crazy) - nick</p>\n\n<hr>\n\n<p>To call a function from within a class you can do it one of two ways...</p>\n\n<p>Either you can create an instance of the class, and then call it.\ne.g.:</p>\n\n<pre><code>$bla = new Blahh_class();\n$bla-&gt;do_something();\n</code></pre>\n\n<p>or... you can call the function statically.. i.e. with no instance of the class.\ne.g.:</p>\n\n<pre><code>Blahh_class::do_something()\n</code></pre>\n\n<p>of course you do need to declare that your function is static:</p>\n\n<pre><code>class Blahh_class { \n public static function do_something(){\n echo 'I am doing something';\n }\n}\n</code></pre>\n\n<p>If a class is not defined as static, then you must create an instance of the object.. (so the object needs a constructor)\ne.g.:</p>\n\n<pre><code>class Blahh_class {\n $some_value;\n\n public function __construct($data) {\n $this-&gt;$some_value = $data;\n }\n\n public function do_something() {\n echo $this-&gt;some_value;\n }\n}\n</code></pre>\n\n<p>The important thing to remember is that static class functions can not use <code>$this</code> as there is no instance of the class. (this is one of the reasons why they go much faster.)</p>\n" }, { "answer_id": 36996060, "author": "user2288580", "author_id": 2288580, "author_profile": "https://Stackoverflow.com/users/2288580", "pm_score": 0, "selected": false, "text": "<p>This may be useful as a substitute</p>\n\n<pre><code>class ReferenceContainer {\n\n function __construct(CallbackContainer $callbackContainer) {\n\n //Alternatively you can have no parameters in this constructor and create a new instance of CallbackContainer and invoke the callback in the same manner \n //var_dump($this-&gt;callbackContainer);\n $data = 'This is how you parse a class by reference';\n $callbackContainer-&gt;myCallback($data);\n\n }\n\n}\n\nclass CallbackContainer {\n\n function __construct() {}\n\n function myCallback($data) {\n\n echo $data.\"\\n\";\n\n }\n\n}\n\n$callbackContainer = new CallbackContainer();\n$doItContainer = new ReferenceContainer($callbackContainer);\n</code></pre>\n" }, { "answer_id": 57075994, "author": "MAChitgarha", "author_id": 4215651, "author_profile": "https://Stackoverflow.com/users/4215651", "pm_score": 3, "selected": false, "text": "<p>As of PHP7, you use an array-like way:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// Static call only\n[TestClass::class, $methodName](...$args);\n\n// Dynamic call, static or non-static doesn't matter\n$instance = new TestClass();\n[$instance, $methodName](...$args);\n</code></pre>\n<p>Just replace the class name with <code>TestClass</code>, the method name with <code>$methodName</code> and the method arguments with <code>...$args</code>. Note that, in the later case, it doesn't matter that the method is static or non-static.</p>\n<p>One advantage is you can pass the array as a callable to a function.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
How can I dynamically invoke a class method in PHP? The class method is not static. It appears that ``` call_user_func(...) ``` only works with static functions? Thanks.
It works both ways - you need to use the right syntax ``` // Non static call call_user_func( array( $obj, 'method' ) ); // Static calls call_user_func( array( 'ClassName', 'method' ) ); call_user_func( 'ClassName::method' ); // (As of PHP 5.2.3) ```
273,192
<p>How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?</p>
[ { "answer_id": 273206, "author": "gone", "author_id": 26880, "author_profile": "https://Stackoverflow.com/users/26880", "pm_score": 6, "selected": false, "text": "<p>Try the <a href=\"https://docs.python.org/2/library/os.path.html#os.path.exists\" rel=\"noreferrer\" title=\"os.path.exists\"><code>os.path.exists</code></a> function</p>\n\n<pre><code>if not os.path.exists(dir):\n os.mkdir(dir)\n</code></pre>\n" }, { "answer_id": 273208, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 7, "selected": false, "text": "<p>Check <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"noreferrer\"><code>os.makedirs</code></a>: (It makes sure the complete path exists.)<br>\n To handle the fact the directory might exist, catch <code>OSError</code>.\n(If <code>exist_ok</code> is <code>False</code> (the default), an <code>OSError</code> is raised if the target directory already exists.)</p>\n\n<pre><code>import os\ntry:\n os.makedirs('./path/to/somewhere')\nexcept OSError:\n pass\n</code></pre>\n" }, { "answer_id": 273227, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 14, "selected": true, "text": "<p>On Python ≥ 3.5, use <a href=\"https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir\" rel=\"noreferrer\"><code>pathlib.Path.mkdir</code></a>:</p>\n\n<pre><code>from pathlib import Path\nPath(\"/my/directory\").mkdir(parents=True, exist_ok=True)\n</code></pre>\n\n<p>For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:</p>\n\n<p>Try <a href=\"https://docs.python.org/library/os.path.html#os.path.exists\" rel=\"noreferrer\"><code>os.path.exists</code></a>, and consider <a href=\"https://docs.python.org/library/os.html#os.makedirs\" rel=\"noreferrer\"><code>os.makedirs</code></a> for the creation.</p>\n\n<pre><code>import os\nif not os.path.exists(directory):\n os.makedirs(directory)\n</code></pre>\n\n<p>As noted in comments and elsewhere, there's a race condition &ndash; if the directory is created between the <code>os.path.exists</code> and the <code>os.makedirs</code> calls, the <code>os.makedirs</code> will fail with an <code>OSError</code>. Unfortunately, blanket-catching <code>OSError</code> and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.</p>\n\n<p>One option would be to trap the <code>OSError</code> and examine the embedded error code (see <a href=\"https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror\">Is there a cross-platform way of getting information from Python’s OSError</a>):</p>\n\n<pre><code>import os, errno\n\ntry:\n os.makedirs(directory)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise\n</code></pre>\n\n<p>Alternatively, there could be a second <code>os.path.exists</code>, but suppose another created the directory after the first check, then removed it before the second one &ndash; we could still be fooled. </p>\n\n<p>Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.</p>\n\n<p>Modern versions of Python improve this code quite a bit, both by exposing <a href=\"https://docs.python.org/3.3/library/exceptions.html?#FileExistsError\" rel=\"noreferrer\"><code>FileExistsError</code></a> (in 3.3+)...</p>\n\n<pre><code>try:\n os.makedirs(\"path/to/directory\")\nexcept FileExistsError:\n # directory already exists\n pass\n</code></pre>\n\n<p>...and by allowing <a href=\"https://docs.python.org/3.2/library/os.html#os.makedirs\" rel=\"noreferrer\">a keyword argument to <code>os.makedirs</code> called <code>exist_ok</code></a> (in 3.2+).</p>\n\n<pre><code>os.makedirs(\"path/to/directory\", exist_ok=True) # succeeds even if directory exists.\n</code></pre>\n" }, { "answer_id": 273679, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 5, "selected": false, "text": "<p>I have put the following down. It's not totally foolproof though.</p>\n\n<pre><code>import os\n\ndirname = 'create/me'\n\ntry:\n os.makedirs(dirname)\nexcept OSError:\n if os.path.exists(dirname):\n # We are nearly safe\n pass\n else:\n # There was an error on creation, so make sure we know about it\n raise\n</code></pre>\n\n<p>Now as I say, this is not really foolproof, because we have the possiblity of failing to create the directory, and another process creating it during that period.</p>\n" }, { "answer_id": 444023, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>I would personally recommend that you use <code>os.path.isdir()</code> to test instead of <code>os.path.exists()</code>.</p>\n<pre><code>&gt;&gt;&gt; os.path.exists('/tmp/dirname')\nTrue\n&gt;&gt;&gt; os.path.exists('/tmp/dirname/filename.etc')\nTrue\n&gt;&gt;&gt; os.path.isdir('/tmp/dirname/filename.etc')\nFalse\n&gt;&gt;&gt; os.path.isdir('/tmp/fakedirname')\nFalse\n</code></pre>\n<p>If you have:</p>\n<pre><code>&gt;&gt;&gt; directory = raw_input(&quot;:: &quot;)\n</code></pre>\n<p>And a foolish user input:</p>\n<pre><code>:: /tmp/dirname/filename.etc\n</code></pre>\n<p>... You're going to end up with a directory named <code>filename.etc</code> when you pass that argument to <code>os.makedirs()</code> if you test with <code>os.path.exists()</code>.</p>\n" }, { "answer_id": 5032238, "author": "Heikki Toivonen", "author_id": 62596, "author_profile": "https://Stackoverflow.com/users/62596", "pm_score": 9, "selected": false, "text": "<p>Using try except and the right error code from errno module gets rid of the race condition and is cross-platform:</p>\n\n<pre><code>import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n</code></pre>\n\n<p>In other words, we try to create the directories, but if they already exist we ignore the error. On the other hand, any other error gets reported. For example, if you create dir 'a' beforehand and remove all permissions from it, you will get an <code>OSError</code> raised with <code>errno.EACCES</code> (Permission denied, error 13).</p>\n" }, { "answer_id": 14364249, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 11, "selected": false, "text": "<h2>Python 3.5+:</h2>\n\n<pre><code>import pathlib\npathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) \n</code></pre>\n\n<p><a href=\"https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir\" rel=\"noreferrer\"><code>pathlib.Path.mkdir</code></a> as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don't need or want the parents to be created, skip the <code>parents</code> argument.</p>\n\n<h2>Python 3.2+:</h2>\n\n<p><strong>Using <code>pathlib</code>:</strong></p>\n\n<p>If you can, install the current <code>pathlib</code> backport named <a href=\"https://pypi.python.org/pypi/pathlib2/\" rel=\"noreferrer\"><code>pathlib2</code></a>. Do not install the older unmaintained backport named <a href=\"https://pypi.python.org/pypi/pathlib/\" rel=\"noreferrer\"><code>pathlib</code></a>. Next, refer to the Python 3.5+ section above and use it the same.</p>\n\n<p>If using Python 3.4, even though it comes with <code>pathlib</code>, it is missing the useful <code>exist_ok</code> option. The backport is intended to offer a newer and superior implementation of <code>mkdir</code> which includes this missing option.</p>\n\n<p><strong>Using <code>os</code>:</strong></p>\n\n<pre><code>import os\nos.makedirs(path, exist_ok=True)\n</code></pre>\n\n<p><a href=\"https://docs.python.org/library/os.html#os.makedirs\" rel=\"noreferrer\"><code>os.makedirs</code></a> as used above recursively creates the directory and does not raise an exception if the directory already exists. It has the optional <code>exist_ok</code> argument only if using Python 3.2+, with a default value of <code>False</code>. This argument does not exist in Python 2.x up to 2.7. As such, there is no need for manual exception handling as with Python 2.7.</p>\n\n<h2>Python 2.7+:</h2>\n\n<p><strong>Using <code>pathlib</code>:</strong></p>\n\n<p>If you can, install the current <code>pathlib</code> backport named <a href=\"https://pypi.python.org/pypi/pathlib2/\" rel=\"noreferrer\"><code>pathlib2</code></a>. Do not install the older unmaintained backport named <a href=\"https://pypi.python.org/pypi/pathlib/\" rel=\"noreferrer\"><code>pathlib</code></a>. Next, refer to the Python 3.5+ section above and use it the same.</p>\n\n<p><strong>Using <code>os</code>:</strong></p>\n\n<pre><code>import os\ntry: \n os.makedirs(path)\nexcept OSError:\n if not os.path.isdir(path):\n raise\n</code></pre>\n\n<p>While a naive solution may first use <a href=\"https://docs.python.org/2/library/os.path.html#os.path.isdir\" rel=\"noreferrer\" title=\"os.path.isdir\"><code>os.path.isdir</code></a> followed by <a href=\"https://docs.python.org/2/library/os.html#os.makedirs\" rel=\"noreferrer\" title=\"os.makedirs\"><code>os.makedirs</code></a>, the solution above reverses the order of the two operations. In doing so, it prevents a common race condition having to do with a duplicated attempt at creating the directory, and also disambiguates files from directories.</p>\n\n<p>Note that capturing the exception and using <code>errno</code> is of limited usefulness because <code>OSError: [Errno 17] File exists</code>, i.e. <code>errno.EEXIST</code>, is raised for both files and directories. It is more reliable simply to check if the directory exists.</p>\n\n<h2>Alternative:</h2>\n\n<p><a href=\"https://docs.python.org/distutils/apiref.html#distutils.dir_util.mkpath\" rel=\"noreferrer\"><code>mkpath</code></a> creates the nested directory, and does nothing if the directory already exists. This works in both Python 2 and 3.</p>\n\n<pre><code>import distutils.dir_util\ndistutils.dir_util.mkpath(path)\n</code></pre>\n\n<p>Per <a href=\"http://bugs.python.org/issue10948\" rel=\"noreferrer\">Bug 10948</a>, a severe limitation of this alternative is that it works only once per python process for a given path. In other words, if you use it to create a directory, then delete the directory from inside or outside Python, then use <code>mkpath</code> again to recreate the same directory, <code>mkpath</code> will simply silently use its invalid cached info of having previously created the directory, and will not actually make the directory again. In contrast, <code>os.makedirs</code> doesn't rely on any such cache. This limitation may be okay for some applications.</p>\n\n<hr>\n\n<p>With regard to the directory's <em>mode</em>, please refer to the documentation if you care about it.</p>\n" }, { "answer_id": 24740135, "author": "kavadias", "author_id": 2258526, "author_profile": "https://Stackoverflow.com/users/2258526", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/2/library/os.html#files-and-directories\" rel=\"noreferrer\">relevant Python documentation</a> suggests the use of the <a href=\"https://docs.python.org/2/library/os.html#files-and-directories\" rel=\"noreferrer\">EAFP coding style (Easier to Ask for Forgiveness than Permission)</a>. This means that the code</p>\n\n<pre><code>try:\n os.makedirs(path)\nexcept OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n else:\n print \"\\nBE CAREFUL! Directory %s already exists.\" % path\n</code></pre>\n\n<p>is better than the alternative</p>\n\n<pre><code>if not os.path.exists(path):\n os.makedirs(path)\nelse:\n print \"\\nBE CAREFUL! Directory %s already exists.\" % path\n</code></pre>\n\n<p>The documentation suggests this exactly because of the race condition discussed in this question. In addition, as others mention here, there is a performance advantage in querying once instead of twice the OS. Finally, the argument placed forward, potentially, in favour of the second code in some cases --when the developer knows the environment the application is running-- can only be advocated in the special case that the program has set up a private environment for itself (and other instances of the same program).</p>\n\n<p>Even in that case, this is a bad practice and can lead to long useless debugging. For example, the fact we set the permissions for a directory should not leave us with the impression permissions are set appropriately for our purposes. A parent directory could be mounted with other permissions. In general, a program should always work correctly and the programmer should not expect one specific environment.</p>\n" }, { "answer_id": 28100717, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p><strong>Check if a directory exists and create it if necessary?</strong></p>\n</blockquote>\n\n<p>The direct answer to this is, assuming a simple situation where you don't expect other users or processes to be messing with your directory:</p>\n\n<pre><code>if not os.path.exists(d):\n os.makedirs(d)\n</code></pre>\n\n<p><strong>or</strong> if making the directory is subject to race conditions (i.e. if after checking the path exists, something else may have already made it) do this:</p>\n\n<pre><code>import errno\ntry:\n os.makedirs(d)\nexcept OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n</code></pre>\n\n<p>But perhaps an even better approach is to sidestep the resource contention issue, by using temporary directories via <a href=\"https://docs.python.org/library/tempfile.html#tempfile.mkdtemp\" rel=\"noreferrer\" title=\"tempfile.mkdtemp\"><code>tempfile</code></a>:</p>\n\n<pre><code>import tempfile\n\nd = tempfile.mkdtemp()\n</code></pre>\n\n<p>Here's the essentials from the online doc:</p>\n\n<blockquote>\n<pre><code>mkdtemp(suffix='', prefix='tmp', dir=None)\n User-callable function to create and return a unique temporary\n directory. The return value is the pathname of the directory.\n\n The directory is readable, writable, and searchable only by the\n creating user.\n\n Caller is responsible for deleting the directory when done with it.\n</code></pre>\n</blockquote>\n\n<h2>New in Python 3.5: <code>pathlib.Path</code> with <code>exist_ok</code></h2>\n\n<p>There's a new <code>Path</code> object (as of 3.4) with lots of methods one would want to use with paths - one of which is <code>mkdir</code>.</p>\n\n<p>(For context, I'm tracking my weekly rep with a script. Here's the relevant parts of code from the script that allow me to avoid hitting Stack Overflow more than once a day for the same data.)</p>\n\n<p>First the relevant imports:</p>\n\n<pre><code>from pathlib import Path\nimport tempfile\n</code></pre>\n\n<p>We don't have to deal with <code>os.path.join</code> now - just join path parts with a <code>/</code>:</p>\n\n<pre><code>directory = Path(tempfile.gettempdir()) / 'sodata'\n</code></pre>\n\n<p>Then I idempotently ensure the directory exists - the <code>exist_ok</code> argument shows up in Python 3.5:</p>\n\n<pre><code>directory.mkdir(exist_ok=True)\n</code></pre>\n\n<p>Here's the relevant part of the <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\" rel=\"noreferrer\">documentation</a>:</p>\n\n<blockquote>\n <p>If <code>exist_ok</code> is true, <code>FileExistsError</code> exceptions will be ignored (same behavior as the <code>POSIX mkdir -p</code> command), but only if the last path component is not an existing non-directory file.</p>\n</blockquote>\n\n<p>Here's a little more of the script - in my case, I'm not subject to a race condition, I only have one process that expects the directory (or contained files) to be there, and I don't have anything trying to remove the directory. </p>\n\n<pre><code>todays_file = directory / str(datetime.datetime.utcnow().date())\nif todays_file.exists():\n logger.info(\"todays_file exists: \" + str(todays_file))\n df = pd.read_json(str(todays_file))\n</code></pre>\n\n<p><code>Path</code> objects have to be coerced to <code>str</code> before other APIs that expect <code>str</code> paths can use them.</p>\n\n<p>Perhaps Pandas should be updated to accept instances of the abstract base class, <code>os.PathLike</code>.</p>\n" }, { "answer_id": 28100757, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<h1>Insights on the specifics of this situation</h1>\n\n<p>You give a particular file at a certain path and you pull the directory from the file path. Then after making sure you have the directory, you attempt to open a file for reading. To comment on this code:</p>\n\n<blockquote>\n<pre><code>filename = \"/my/directory/filename.txt\"\ndir = os.path.dirname(filename)\n</code></pre>\n</blockquote>\n\n<p>We want to avoid overwriting the builtin function, <code>dir</code>. Also, <code>filepath</code> or perhaps <code>fullfilepath</code> is probably a better semantic name than <code>filename</code> so this would be better written:</p>\n\n<pre><code>import os\nfilepath = '/my/directory/filename.txt'\ndirectory = os.path.dirname(filepath)\n</code></pre>\n\n<p>Your end goal is to open this file, you initially state, for writing, but you're essentially approaching this goal (based on your code) like this, which opens the file for <strong>reading</strong>:</p>\n\n<blockquote>\n<pre><code>if not os.path.exists(directory):\n os.makedirs(directory)\nf = file(filename)\n</code></pre>\n</blockquote>\n\n<h2>Assuming opening for reading</h2>\n\n<p>Why would you make a directory for a file that you expect to be there and be able to read? </p>\n\n<p>Just attempt to open the file.</p>\n\n<pre><code>with open(filepath) as my_file:\n do_stuff(my_file)\n</code></pre>\n\n<p>If the directory or file isn't there, you'll get an <code>IOError</code> with an associated error number: <code>errno.ENOENT</code> will point to the correct error number regardless of your platform. You can catch it if you want, for example:</p>\n\n<pre><code>import errno\ntry:\n with open(filepath) as my_file:\n do_stuff(my_file)\nexcept IOError as error:\n if error.errno == errno.ENOENT:\n print 'ignoring error because directory or file is not there'\n else:\n raise\n</code></pre>\n\n<h2>Assuming we're opening for writing</h2>\n\n<p>This is <em>probably</em> what you're wanting.</p>\n\n<p>In this case, we probably aren't facing any race conditions. So just do as you were, but note that for writing, you need to open with the <code>w</code> mode (or <code>a</code> to append). It's also a Python best practice to use the context manager for opening files.</p>\n\n<pre><code>import os\nif not os.path.exists(directory):\n os.makedirs(directory)\nwith open(filepath, 'w') as my_file:\n do_stuff(my_file)\n</code></pre>\n\n<p>However, say we have several Python processes that attempt to put all their data into the same directory. Then we may have contention over creation of the directory. In that case it's best to wrap the <code>makedirs</code> call in a try-except block.</p>\n\n<pre><code>import os\nimport errno\nif not os.path.exists(directory):\n try:\n os.makedirs(directory)\n except OSError as error:\n if error.errno != errno.EEXIST:\n raise\nwith open(filepath, 'w') as my_file:\n do_stuff(my_file)\n</code></pre>\n" }, { "answer_id": 28997083, "author": "Antti Haapala -- Слава Україні", "author_id": 918959, "author_profile": "https://Stackoverflow.com/users/918959", "pm_score": 5, "selected": false, "text": "<p>In Python 3.4 you can also use the <a href=\"https://docs.python.org/3/library/pathlib.html\">brand new <code>pathlib</code> module</a>:</p>\n\n<pre><code>from pathlib import Path\npath = Path(\"/my/directory/filename.txt\")\ntry:\n if not path.parent.exists():\n path.parent.mkdir(parents=True)\nexcept OSError:\n # handle error; you can also catch specific errors like\n # FileExistsError and so on.\n</code></pre>\n" }, { "answer_id": 35262209, "author": "alissonmuller", "author_id": 3051142, "author_profile": "https://Stackoverflow.com/users/3051142", "pm_score": 3, "selected": false, "text": "<p>I saw <a href=\"https://stackoverflow.com/a/5032238/3051142\">Heikki Toivonen</a> and <a href=\"https://stackoverflow.com/a/14364249\">A-B-B</a>'s answers and thought of this variation.</p>\n\n<pre><code>import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST or not os.path.isdir(path):\n raise\n</code></pre>\n" }, { "answer_id": 36289129, "author": "tashuhka", "author_id": 2039736, "author_profile": "https://Stackoverflow.com/users/2039736", "pm_score": 5, "selected": false, "text": "<p>For a one-liner solution, you can use <a href=\"https://github.com/ipython/ipython/blob/b70b3f21749ca969088fdb54edcc36bb8a2267b9/IPython/utils/path.py#L423-L438\" rel=\"noreferrer\"><code>IPython.utils.path.ensure_dir_exists()</code></a>:</p>\n<pre><code>from IPython.utils.path import ensure_dir_exists\nensure_dir_exists(dir)\n</code></pre>\n<p>From the <a href=\"https://ipython.org/ipython-doc/3/api/generated/IPython.utils.path.html#IPython.utils.path.ensure_dir_exists\" rel=\"noreferrer\">documentation</a>: <em>Ensure that a directory exists. If it doesn’t exist, try to create it and protect against a race condition if another process is doing the same.</em></p>\n<p>IPython is an extension package, not part of the standard library.</p>\n" }, { "answer_id": 37703074, "author": "iPhynx", "author_id": 5489173, "author_profile": "https://Stackoverflow.com/users/5489173", "pm_score": 3, "selected": false, "text": "<p>You can use <code>os.listdir</code> for this:</p>\n\n<pre><code>import os\nif 'dirName' in os.listdir('parentFolderPath')\n print('Directory Exists')\n</code></pre>\n" }, { "answer_id": 39479473, "author": "Dennis Golomazov", "author_id": 304209, "author_profile": "https://Stackoverflow.com/users/304209", "pm_score": 4, "selected": false, "text": "<p>You can use <a href=\"https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.mkpath\" rel=\"noreferrer\"><code>mkpath</code></a></p>\n\n<pre><code># Create a directory and any missing ancestor directories. \n# If the directory already exists, do nothing.\n\nfrom distutils.dir_util import mkpath\nmkpath(\"test\") \n</code></pre>\n\n<p>Note that it will create the ancestor directories as well. </p>\n\n<p>It works for Python 2 and 3.</p>\n" }, { "answer_id": 40949679, "author": "Ralph Schwerdt", "author_id": 4606792, "author_profile": "https://Stackoverflow.com/users/4606792", "pm_score": 3, "selected": false, "text": "<p>If you consider the following: </p>\n\n<pre><code>os.path.isdir('/tmp/dirname')\n</code></pre>\n\n<p>means a directory (path) exists AND is a directory. So for me this way does what I need. So I can make sure it is folder (not a file) and exists.</p>\n" }, { "answer_id": 41147087, "author": "hiro protagonist", "author_id": 4954037, "author_profile": "https://Stackoverflow.com/users/4954037", "pm_score": 7, "selected": false, "text": "<p>Starting from Python 3.5, <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\" rel=\"noreferrer\"><code>pathlib.Path.mkdir</code></a> has an <code>exist_ok</code> flag:</p>\n<pre><code>from pathlib import Path\npath = Path('/my/directory/filename.txt')\npath.parent.mkdir(parents=True, exist_ok=True) \n# path.parent ~ os.path.dirname(path)\n</code></pre>\n<p>This recursively creates the directory and does not raise an exception if the directory already exists.</p>\n<p>(just as <a href=\"https://docs.python.org/3/library/os.html?highlight=makedirs#os.makedirs\" rel=\"noreferrer\"><code>os.makedirs</code></a> got an <code>exist_ok</code> flag starting from python 3.2 e.g <code>os.makedirs(path, exist_ok=True)</code>)</p>\n<hr />\n<p>Note: when i posted this answer none of the other answers mentioned <code>exist_ok</code>...</p>\n" }, { "answer_id": 41453417, "author": "euccas", "author_id": 3109254, "author_profile": "https://Stackoverflow.com/users/3109254", "pm_score": 5, "selected": false, "text": "<p>In <strong>Python3</strong>, <code>os.makedirs</code> supports setting <code>exist_ok</code>. The default setting is <code>False</code>, which means an <code>OSError</code> will be raised if the target directory already exists. By setting <code>exist_ok</code> to <code>True</code>, <code>OSError</code> (directory exists) will be ignored and the directory will not be created.</p>\n\n<pre><code>os.makedirs(path,exist_ok=True)\n</code></pre>\n\n<p>In <strong>Python2</strong>, <code>os.makedirs</code> doesn't support setting <code>exist_ok</code>. You can use the approach in <a href=\"https://stackoverflow.com/a/5032238/3109254\">heikki-toivonen's answer</a>:</p>\n\n<pre><code>import os\nimport errno\n\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n</code></pre>\n" }, { "answer_id": 42127930, "author": "Michael Strobel", "author_id": 7424032, "author_profile": "https://Stackoverflow.com/users/7424032", "pm_score": 3, "selected": false, "text": "<p>I use <code>os.path.exists()</code>, <a href=\"http://pastebin.com/vnVk2rY5\" rel=\"noreferrer\">here</a> is a Python 3 script that can be used to check if a directory exists, create one if it does not exist, and delete it if it does exist (if desired).</p>\n\n<p>It prompts users for input of the directory and can be easily modified.</p>\n" }, { "answer_id": 47842472, "author": "Victoria Stuart", "author_id": 1904943, "author_profile": "https://Stackoverflow.com/users/1904943", "pm_score": 4, "selected": false, "text": "<p>I found this Q/A after I was puzzled by some of the failures and errors I was getting while working with directories in Python. I am working in Python 3 (v.3.5 in an Anaconda virtual environment on an Arch Linux x86_64 system).</p>\n<p>Consider this directory structure:</p>\n<pre><code>└── output/ ## dir\n ├── corpus ## file\n ├── corpus2/ ## dir\n └── subdir/ ## dir\n</code></pre>\n<p>Here are my experiments/notes, which provides clarification:</p>\n<pre><code># ----------------------------------------------------------------------------\n# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist\n\nimport pathlib\n\n&quot;&quot;&quot; Notes:\n 1. Include a trailing slash at the end of the directory path\n (&quot;Method 1,&quot; below).\n 2. If a subdirectory in your intended path matches an existing file\n with same name, you will get the following error:\n &quot;NotADirectoryError: [Errno 20] Not a directory:&quot; ...\n&quot;&quot;&quot;\n# Uncomment and try each of these &quot;out_dir&quot; paths, singly:\n\n# ----------------------------------------------------------------------------\n# METHOD 1:\n# Re-running does not overwrite existing directories and files; no errors.\n\n# out_dir = 'output/corpus3' ## no error but no dir created (missing tailing /)\n# out_dir = 'output/corpus3/' ## works\n# out_dir = 'output/corpus3/doc1' ## no error but no dir created (missing tailing /)\n# out_dir = 'output/corpus3/doc1/' ## works\n# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but no file created (os.makedirs creates dir, not files! ;-)\n# out_dir = 'output/corpus2/tfidf/' ## fails with &quot;Errno 20&quot; (existing file named &quot;corpus2&quot;)\n# out_dir = 'output/corpus3/tfidf/' ## works\n# out_dir = 'output/corpus3/a/b/c/d/' ## works\n\n# [2] https://docs.python.org/3/library/os.html#os.makedirs\n\n# Uncomment these to run &quot;Method 1&quot;:\n\n#directory = os.path.dirname(out_dir)\n#os.makedirs(directory, mode=0o777, exist_ok=True)\n\n# ----------------------------------------------------------------------------\n# METHOD 2:\n# Re-running does not overwrite existing directories and files; no errors.\n\n# out_dir = 'output/corpus3' ## works\n# out_dir = 'output/corpus3/' ## works\n# out_dir = 'output/corpus3/doc1' ## works\n# out_dir = 'output/corpus3/doc1/' ## works\n# out_dir = 'output/corpus3/doc1/doc.txt' ## no error but creates a .../doc.txt./ dir\n# out_dir = 'output/corpus2/tfidf/' ## fails with &quot;Errno 20&quot; (existing file named &quot;corpus2&quot;)\n# out_dir = 'output/corpus3/tfidf/' ## works\n# out_dir = 'output/corpus3/a/b/c/d/' ## works\n\n# Uncomment these to run &quot;Method 2&quot;:\n\n#import os, errno\n#try:\n# os.makedirs(out_dir)\n#except OSError as e:\n# if e.errno != errno.EEXIST:\n# raise\n# ----------------------------------------------------------------------------\n</code></pre>\n<p>Conclusion: in my opinion, &quot;Method 2&quot; is more robust.</p>\n<p>[1] <a href=\"https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist\">How can I safely create a nested directory?</a></p>\n<p>[2] <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/os.html#os.makedirs</a></p>\n" }, { "answer_id": 49851755, "author": "Manivannan Murugavel", "author_id": 6559063, "author_profile": "https://Stackoverflow.com/users/6559063", "pm_score": 3, "selected": false, "text": "<p>Use this command check and create dir</p>\n\n<pre><code> if not os.path.isdir(test_img_dir):\n os.mkdir(test_img_dir)\n</code></pre>\n" }, { "answer_id": 50078422, "author": "Steffi Keran Rani J", "author_id": 7245145, "author_profile": "https://Stackoverflow.com/users/7245145", "pm_score": 3, "selected": false, "text": "<p>Call the function <code>create_dir()</code> at the entry point of your program/project.</p>\n\n<pre><code>import os\n\ndef create_dir(directory):\n if not os.path.exists(directory):\n print('Creating Directory '+directory)\n os.makedirs(directory)\n\ncreate_dir('Project directory')\n</code></pre>\n" }, { "answer_id": 52282050, "author": "Geoff Paul Bremner", "author_id": 4821206, "author_profile": "https://Stackoverflow.com/users/4821206", "pm_score": 3, "selected": false, "text": "<p>Why not use subprocess module if running on a machine that supports command \n<code>mkdir</code> with <code>-p</code> option ? \nWorks on python 2.7 and python 3.6</p>\n\n<pre><code>from subprocess import call\ncall(['mkdir', '-p', 'path1/path2/path3'])\n</code></pre>\n\n<p>Should do the trick on most systems.</p>\n\n<p>In situations where portability doesn't matter (ex, using docker) the solution is a clean 2 lines. You also don't have to add logic to check if directories exist or not. Finally, it is safe to re-run without any side effects</p>\n\n<p>If you need error handling:</p>\n\n<pre><code>from subprocess import check_call\ntry:\n check_call(['mkdir', '-p', 'path1/path2/path3'])\nexcept:\n handle...\n</code></pre>\n" }, { "answer_id": 56203876, "author": "Hussam Kurd", "author_id": 1627358, "author_profile": "https://Stackoverflow.com/users/1627358", "pm_score": 3, "selected": false, "text": "<p>You have to set the full path before creating the directory:</p>\n\n<pre><code>import os,sys,inspect\nimport pathlib\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nyour_folder = currentdir + \"/\" + \"your_folder\"\n\nif not os.path.exists(your_folder):\n pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)\n</code></pre>\n\n<p>This works for me and hopefully, it will works for you as well</p>\n" }, { "answer_id": 64474894, "author": "korakot", "author_id": 6729010, "author_profile": "https://Stackoverflow.com/users/6729010", "pm_score": 2, "selected": false, "text": "<p>This may not exactly answer the question. But I guess your real intention is to create a file and its parent directories, given its content all in 1 command.</p>\n<p>You can do that with <code>fastcore</code> extension to pathlib: <code>path.mk_write(data)</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>from fastcore.utils import Path\nPath('/dir/to/file.txt').mk_write('Hello World')\n</code></pre>\n<p>See more in <a href=\"https://fastcore.fast.ai/xtras.html#Path.mk_write\" rel=\"nofollow noreferrer\">fastcore documentation</a></p>\n" }, { "answer_id": 68821616, "author": "Dominykas Mostauskis", "author_id": 1714997, "author_profile": "https://Stackoverflow.com/users/1714997", "pm_score": 4, "selected": false, "text": "<p>In case you're writing a file to a variable path, you can use this on the file's path to make sure that the parent directories are created.</p>\n<pre><code>from pathlib import Path\n\npath_to_file = Path(&quot;zero/or/more/directories/file.ext&quot;)\nparent_directory_of_file = path_to_file.parent\nparent_directory_of_file.mkdir(parents=True, exist_ok=True)\n</code></pre>\n<p>Works even if <code>path_to_file</code> is <code>file.ext</code> (zero directories deep).</p>\n<p>See <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent\" rel=\"noreferrer\">pathlib.PurePath.parent</a> and <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir\" rel=\"noreferrer\">pathlib.Path.mkdir</a>.</p>\n" }, { "answer_id": 71029280, "author": "Devil", "author_id": 9427260, "author_profile": "https://Stackoverflow.com/users/9427260", "pm_score": 5, "selected": false, "text": "<p><strong>Best way to do this in python</strong></p>\n<pre><code>#Devil\nimport os\ndirectory = &quot;./out_dir/subdir1/subdir2&quot;\nif not os.path.exists(directory):\n os.makedirs(directory)\n</code></pre>\n" }, { "answer_id": 71466038, "author": "Simone", "author_id": 8411609, "author_profile": "https://Stackoverflow.com/users/8411609", "pm_score": 5, "selected": false, "text": "<p>fastest safest way to do it is:\nit will create if not exists and skip if exists:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\nPath(&quot;path/with/childs/.../&quot;).mkdir(parents=True, exist_ok=True)\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?
On Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir): ``` from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True) ``` For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try [`os.path.exists`](https://docs.python.org/library/os.path.html#os.path.exists), and consider [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) for the creation. ``` import os if not os.path.exists(directory): os.makedirs(directory) ``` As noted in comments and elsewhere, there's a race condition – if the directory is created between the `os.path.exists` and the `os.makedirs` calls, the `os.makedirs` will fail with an `OSError`. Unfortunately, blanket-catching `OSError` and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc. One option would be to trap the `OSError` and examine the embedded error code (see [Is there a cross-platform way of getting information from Python’s OSError](https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror)): ``` import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise ``` Alternatively, there could be a second `os.path.exists`, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled. Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation. Modern versions of Python improve this code quite a bit, both by exposing [`FileExistsError`](https://docs.python.org/3.3/library/exceptions.html?#FileExistsError) (in 3.3+)... ``` try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass ``` ...and by allowing [a keyword argument to `os.makedirs` called `exist_ok`](https://docs.python.org/3.2/library/os.html#os.makedirs) (in 3.2+). ``` os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists. ```
273,199
<p>I'm trying to convert some Xaml to HTML using the .NET XslCompiledTransform and am running into difficulties getting the xslt to match Xaml tags. For instance with this Xaml input:</p> <pre><code>&lt;FlowDocument PagePadding="5,0,5,0" AllowDrop="True" NumberSubstitution.CultureSource="User" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt; &lt;Paragraph&gt;a&lt;/Paragraph&gt; &lt;/FlowDocument&gt; </code></pre> <p>And this xslt:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" &gt; &lt;xsl:output method="html" indent="yes"/&gt; &lt;xsl:template match="/"&gt; &lt;html&gt; &lt;body&gt; &lt;xsl:apply-templates /&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;xsl:template match="FlowDocument"&gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Paragraph" &gt; &lt;p&gt; &lt;xsl:apply-templates /&gt; &lt;/p&gt; &lt;/xsl:template&gt; </code></pre> <p>I get this output:</p> <pre><code>&lt;html&gt; &lt;body&gt; a &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Rather than the expected:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;p&gt;a&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Could this be a problem with the namespace? This is my first attempt at an xsl transform, so I'm at a loss.</p>
[ { "answer_id": 273257, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 6, "selected": true, "text": "<p>Yes, it's a problem with the namespace. All of the elements in your input document are in the namespace <code>http://schemas.microsoft.com/winfx/2006/xaml/presentation</code>. Your template is trying to match elements that are in the default namespace, and it's not finding any.</p>\n\n<p>You need to declare this namespace in your transform, assign it a prefix, and then use that prefix in any patterns that are intended to match elements in that namespace. So your XSLT should look something like this:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" \n xmlns:p=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n exclude-result-prefixes=\"msxsl\"/&gt;\n\n&lt;xsl:output method=\"html\" indent=\"yes\"/&gt;\n\n&lt;xsl:template match=\"/\"&gt;\n &lt;html&gt;\n &lt;body&gt;\n &lt;xsl:apply-templates /&gt;\n &lt;/body&gt;\n &lt;/html&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"p:FlowDocument\"&gt;\n &lt;xsl:apply-templates /&gt;\n&lt;/xsl:template&gt;\n\n&lt;xsl:template match=\"p:Paragraph\" &gt;\n &lt;p&gt;\n &lt;xsl:apply-templates /&gt;\n &lt;/p&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 273300, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 0, "selected": false, "text": "<p>It works when I remove this from your source document:</p>\n\n<pre><code>xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n</code></pre>\n\n<p>I don't believe your last two templates are matching at all. (You can test by putting something like a wrapping &lt;div&gt; in your FlowDocument template.)</p>\n" }, { "answer_id": 2998676, "author": "Somesh", "author_id": 361520, "author_profile": "https://Stackoverflow.com/users/361520", "pm_score": 0, "selected": false, "text": "<p>Just try changing </p>\n\n<p>\"xsl:template match='/'\"</p>\n\n<p>tag in your xsl file with </p>\n\n<p>\"xsl:template match='*'\"</p>\n\n<p>This should give you the desired output.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807/" ]
I'm trying to convert some Xaml to HTML using the .NET XslCompiledTransform and am running into difficulties getting the xslt to match Xaml tags. For instance with this Xaml input: ``` <FlowDocument PagePadding="5,0,5,0" AllowDrop="True" NumberSubstitution.CultureSource="User" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Paragraph>a</Paragraph> </FlowDocument> ``` And this xslt: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <html> <body> <xsl:apply-templates /> </body> </html> </xsl:template> <xsl:template match="FlowDocument"> <xsl:apply-templates /> </xsl:template> <xsl:template match="Paragraph" > <p> <xsl:apply-templates /> </p> </xsl:template> ``` I get this output: ``` <html> <body> a </body> </html> ``` Rather than the expected: ``` <html> <body> <p>a</p> </body> </html> ``` Could this be a problem with the namespace? This is my first attempt at an xsl transform, so I'm at a loss.
Yes, it's a problem with the namespace. All of the elements in your input document are in the namespace `http://schemas.microsoft.com/winfx/2006/xaml/presentation`. Your template is trying to match elements that are in the default namespace, and it's not finding any. You need to declare this namespace in your transform, assign it a prefix, and then use that prefix in any patterns that are intended to match elements in that namespace. So your XSLT should look something like this: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:p="http://schemas.microsoft.com/winfx/2006/xaml/presentation" exclude-result-prefixes="msxsl"/> <xsl:output method="html" indent="yes"/> <xsl:template match="/"> <html> <body> <xsl:apply-templates /> </body> </html> </xsl:template> <xsl:template match="p:FlowDocument"> <xsl:apply-templates /> </xsl:template> <xsl:template match="p:Paragraph" > <p> <xsl:apply-templates /> </p> </xsl:template> ```
273,203
<p>I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?</p>
[ { "answer_id": 273386, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "<p>There are a few possible methods <a href=\"http://www.sommarskog.se/share_data.html\" rel=\"nofollow noreferrer\">here</a>. If the result sets are all the same, you might be able to use the INSERT...EXEC method. Otherwise OPENQUERY might work.</p>\n" }, { "answer_id": 313665, "author": "TJG", "author_id": 40211, "author_profile": "https://Stackoverflow.com/users/40211", "pm_score": 4, "selected": false, "text": "<p>No need for anything fancy. Just use the <a href=\"https://github.com/mkleehammer/pyodbc/wiki/Cursor#nextset\" rel=\"nofollow noreferrer\">cursor's <code>nextset()</code> method</a>:</p>\n<pre><code>\nimport pyodbc\n\ndb = pyodbc.connect (\"\")\nq = db.cursor ()\nq.execute (\"\"\"\nSELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES\nSELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS\n\"\"\")\ntables = q.fetchall ()\nq.nextset ()\ncolumns = q.fetchall ()\n\nassert len (tables) == 5\nassert len (columns) == 10\n\n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?
No need for anything fancy. Just use the [cursor's `nextset()` method](https://github.com/mkleehammer/pyodbc/wiki/Cursor#nextset): ``` import pyodbc db = pyodbc.connect ("") q = db.cursor () q.execute (""" SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES SELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS """) tables = q.fetchall () q.nextset () columns = q.fetchall () assert len (tables) == 5 assert len (columns) == 10 ```
273,217
<p>Does anybody know what's going on here:</p> <p>I run hibernate 3.2.6 against a PostgreSQL 8.3 (installed via fink) database on my Mac OS X. The setup works fine when I use Java 6 and the JDBC 4 driver (postgresql-8.3-603.jdbc4). However, I need this stuff to work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3). When I change the jar in the classpath and switch to Java 5 (I do this in eclipse), I get the following error:</p> <pre><code>Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74) &lt;Rows clipped for readability&gt; Caused by: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getConnection(DriverManager.java:545) at java.sql.DriverManager.getConnection(DriverManager.java:140) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423) </code></pre> <p>What's the problem here? I cannot see it. Here is my hibernate configuration:</p> <pre><code>&lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="connection.url"&gt;jdbc:postgresql:test&lt;/property&gt; &lt;property name="connection.username"&gt;postgres&lt;/property&gt; &lt;property name="connection.password"&gt;p&lt;/property&gt; &lt;property name="connection.pool_size"&gt;1&lt;/property&gt; &lt;property name="dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/property&gt; &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;mapping resource="com/mydomain/MyClass.hbm.xml"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p><strong>EDIT:</strong> The longer, more usual form of the connection URL: <em>jdbc:postgresql://localhost/test</em> has the exact same behaviour.</p> <p>The driver jar is definitely in the classpath, and I also do not manage to get any errors with this direct JDBC test code:</p> <pre><code>public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); Connection con=DriverManager.getConnection("jdbc:postgresql://localhost/test","postgres", "p"); } </code></pre>
[ { "answer_id": 273391, "author": "shyam", "author_id": 7616, "author_profile": "https://Stackoverflow.com/users/7616", "pm_score": 1, "selected": false, "text": "<p>did you notice that the connection url is incomplete</p>\n\n<pre><code>&lt;property name=\"connection.url\"&gt;jdbc:postgresql:test&lt;/property&gt;\n</code></pre>\n\n<p>as opposed to </p>\n\n<pre><code>&lt;property name=\"connection.url\"&gt;jdbc:postgresql://localhost/test&lt;/property&gt;\n</code></pre>\n" }, { "answer_id": 273517, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 1, "selected": false, "text": "<p>You say \"work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3).\" Maybe this is a faulty assumption.</p>\n\n<p>The <a href=\"http://jdbc.postgresql.org/download.html\" rel=\"nofollow noreferrer\">download page</a> is confusing to me. It seems to imply that for Java 1.5 you need JDBC3 but it's not 100% clear. I'm not sure why the JDBC4 driver won't work with Java 1.5 (we use a DB2 JDBC4 driver with Java 1.5).</p>\n\n<p>Have you tried the JDBC4 driver with Java 1.5?</p>\n" }, { "answer_id": 273634, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 3, "selected": true, "text": "<p>I don't see you specifying the driver class in your Hibernate configuration. Try adding the following:</p>\n\n<pre><code>&lt;hibernate-configuration&gt;\n &lt;session-factory&gt;\n .\n .\n &lt;property name=\"connection.driver_class\"&gt;org.postgresql.Driver&lt;/property&gt;\n .\n &lt;/session-factory&gt;\n&lt;/hibernate-configuration&gt;\n</code></pre>\n" }, { "answer_id": 1964954, "author": "Kris Jurka", "author_id": 239027, "author_profile": "https://Stackoverflow.com/users/239027", "pm_score": 1, "selected": false, "text": "<p>One of the new JDBC4 features is automatic loading via the Service Provider mechanism. By including a META-INF/services/java.sql.Driver file in the jar file, there is no longer the need to do Class.forName(\"\"). This only works with the 1.6 JVM.</p>\n" }, { "answer_id": 4183311, "author": "Solution", "author_id": 508110, "author_profile": "https://Stackoverflow.com/users/508110", "pm_score": 1, "selected": false, "text": "<p>I had the same problem \"no suiteble driver found\" using a servlet the solution to register a driver is:</p>\n\n<pre><code>Class driverClass = Class.forName(\"org.postgresql.Driver\");\nDriverManager.registerDriver((Driver) driverClass.newInstance());\n</code></pre>\n\n<p>Found the solution here:</p>\n\n<p><a href=\"http://www.java2s.com/Tutorial/Java/0340__Database/DriverManagergetDriversenumeratealltheloadedJDBCdrivers.htm\" rel=\"nofollow\">http://www.java2s.com/Tutorial/Java/0340__Database/DriverManagergetDriversenumeratealltheloadedJDBCdrivers.htm</a></p>\n\n<p><a href=\"http://codingexplorer.wordpress.com/2009/09/06/%E2%80%9Cno-suitable-driver%E2%80%9D-for-postgresql/\" rel=\"nofollow\">http://codingexplorer.wordpress.com/2009/09/06/%E2%80%9Cno-suitable-driver%E2%80%9D-for-postgresql/</a> </p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110/" ]
Does anybody know what's going on here: I run hibernate 3.2.6 against a PostgreSQL 8.3 (installed via fink) database on my Mac OS X. The setup works fine when I use Java 6 and the JDBC 4 driver (postgresql-8.3-603.jdbc4). However, I need this stuff to work with Java 5 and (hence) JDBC 3 (postgresql-8.3-603.jdbc3). When I change the jar in the classpath and switch to Java 5 (I do this in eclipse), I get the following error: ``` Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74) <Rows clipped for readability> Caused by: java.sql.SQLException: No suitable driver at java.sql.DriverManager.getConnection(DriverManager.java:545) at java.sql.DriverManager.getConnection(DriverManager.java:140) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423) ``` What's the problem here? I cannot see it. Here is my hibernate configuration: ``` <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:postgresql:test</property> <property name="connection.username">postgres</property> <property name="connection.password">p</property> <property name="connection.pool_size">1</property> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <mapping resource="com/mydomain/MyClass.hbm.xml"/> </session-factory> </hibernate-configuration> ``` **EDIT:** The longer, more usual form of the connection URL: *jdbc:postgresql://localhost/test* has the exact same behaviour. The driver jar is definitely in the classpath, and I also do not manage to get any errors with this direct JDBC test code: ``` public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); Connection con=DriverManager.getConnection("jdbc:postgresql://localhost/test","postgres", "p"); } ```
I don't see you specifying the driver class in your Hibernate configuration. Try adding the following: ``` <hibernate-configuration> <session-factory> . . <property name="connection.driver_class">org.postgresql.Driver</property> . </session-factory> </hibernate-configuration> ```
273,218
<p>In layman's terms, what's a RDF triple?</p>
[ { "answer_id": 273240, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>An RDF file should parse down to a\n list of triples.</p>\n \n <p>A triple consists of a subject, a\n predicate, and an object. But what do\n these actually mean?</p>\n \n <p>The subject is, well, the subject. It\n identifies what object the triple is\n describing.</p>\n \n <p>The predicate defines the piece of\n data in the object we are giving a\n value to.</p>\n \n <p>The object is the actual value.</p>\n</blockquote>\n\n<p>From: <a href=\"http://www.robertprice.co.uk/robblog/archive/2004/10/What_Is_An_RDF_Triple_.shtml\" rel=\"noreferrer\">http://www.robertprice.co.uk/robblog/archive/2004/10/What_Is_An_RDF_Triple_.shtml</a></p>\n" }, { "answer_id": 273250, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 2, "selected": false, "text": "<p>It has been awhile since I worked with RDF, but here it goes :D</p>\n\n<p>A triple is a subject, predicate and object. </p>\n\n<p>The subject is a URI which uniquely identifies something. For example, your openid uniquely identifies you.</p>\n\n<p>The object defines how the subject and object are related.</p>\n\n<p>The predicate is some attribute of the subject. For example a name.</p>\n\n<p>Given that, the triples form a graph S->P. Given more triplets, the graph grows. For example, you can have the same person identified as the subject of a bunch of triples, you can then connect all of the predicates through that unique subject.</p>\n" }, { "answer_id": 273251, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 5, "selected": false, "text": "<p>An RDF Triple is a statement which relates one object to another. For Example:</p>\n\n<pre><code>\"gcc\" \"Compiles\" \"c\" .\n\"gcc\" \"compiles\" \"Java\" . \n\"gcc\" \"compiles\" \"fortran\" .\n\"gcc\" \"has a website at\" &lt;http://gcc.gnu.org/&gt; .\n\"gcc\" \"has a mailing list at\" &lt;mailto:[email protected]&gt; .\n\"c\" \"is a\" \"programming language\" .\n\"c\" \"is documented in\" &lt;http://www.amazon.com/Programming-Language-Prentice-Hall-Software/dp/0131103628/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1226085111&amp;sr=8-1&gt; .\n</code></pre>\n" }, { "answer_id": 273342, "author": "Ather", "author_id": 1065163, "author_profile": "https://Stackoverflow.com/users/1065163", "pm_score": 2, "selected": false, "text": "<p>RDF Triple is an actual expression that defines a way in which you can represent a relationship between objects. There are three parts to a triple: Subject, Predicate and Object (typically written in the same order). A predicate relates subject to object.</p>\n\n<p>Subject ----Predicate---> Object</p>\n\n<p>More useful information can be found at:</p>\n\n<p><a href=\"http://www.w3.org/TR/rdf-concepts/\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/rdf-concepts/</a></p>\n" }, { "answer_id": 273387, "author": "Kaarel", "author_id": 12547, "author_profile": "https://Stackoverflow.com/users/12547", "pm_score": 0, "selected": false, "text": "<p>See:\n<a href=\"http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-rdf-triple\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-rdf-triple</a></p>\n\n<p>An RDF triple contains three components:</p>\n\n<ul>\n<li>the subject, which is an RDF URI reference or a blank node</li>\n<li>the predicate, which is an RDF URI reference</li>\n<li>the object, which is an RDF URI reference, a literal or a blank node</li>\n</ul>\n\n<p>where literals are essentially strings with optional language tags,\nand blank nodes are also strings. URIs, literals and blank nodes must\nbe from pair-wise disjoint sets.</p>\n" }, { "answer_id": 273594, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 4, "selected": false, "text": "<p>Regarding the answer by Adam N. I believe the O.P. <a href=\"https://stackoverflow.com/questions/272911/what-is-the-best-way-to-organize-user-generated-content-in-a-social-network#273053\">asked a previous question regarding data for a social network</a>, so although the answer is excellent, I will just clarify in relation to the \"original original\" question. (As I feel responsible).</p>\n\n<pre>\n John | Is a Friend of | James\n James | Is a friend of | Jill\n Jill | Likes | Snowboarding\n Snowboarding | Is a | Sport\n</pre>\n\n<p>Using triples like this you can have a really flexible data structure.</p>\n\n<p>Look at the <a href=\"http://www.foaf-project.org/\" rel=\"nofollow noreferrer\">Friend of a friend (FOAF)</a> perhaps for a better example.</p>\n" }, { "answer_id": 506524, "author": "vartec", "author_id": 60711, "author_profile": "https://Stackoverflow.com/users/60711", "pm_score": 3, "selected": false, "text": "<p>Note, that it can get a bit more complicated. RDF triples can also be considered Subjects or Objects, so you can have something like:\n Bart -> said -> ( triples -> can be -> objects)</p>\n" }, { "answer_id": 1122451, "author": "Nico Adams", "author_id": 137730, "author_profile": "https://Stackoverflow.com/users/137730", "pm_score": 6, "selected": false, "text": "<p>I think the question needs to be split into two parts - what is a triple and what makes an \"RDF triple\" so special?</p>\n\n<p>Firstly, a triple is, as most of the other commenters here have already pointed out, a statement in \"subject/predicate/object\" form - i.e. a statement linking one object (subject) to another object(object) or a literal, via a predicate. We are all familiar with triples: a triple is the smallest irreducible representation for binary relationship. In plain English: a spreadsheet is a collection of triples, for example, if a column in your spreadsheet has the heading \"Paul\" and a row has the heading \"has Sister\" and the value in the cell is \"Lisa\". Here you have a triple: Paul (subject) has Sister(predicate) Lisa (literal/object).</p>\n\n<p>What makes RDF triples special is that EVERY PART of the triple has a URI associated with it, so the everyday statement \"Mike Smith knows John Doe\" might be represented in RDF as:</p>\n\n<pre><code>uri://people#MikeSmith12 http://xmlns.com/foaf/0.1/knows uri://people#JohnDoe45\n</code></pre>\n\n<p>The analogy to the spreadsheet is that by giving every part of the URI a unique address, you give the cell in the spreadsheet its whole address space....so you could in principle stick every cell (if expressed in RDF triples) of the spreadsheet into a different document on a different server and reconstitute the spreadsheet through a single query.</p>\n\n<p>Edit: \n<a href=\"https://www.w3.org/TR/2014/NOTE-rdf11-primer-20140624/#section-triple\" rel=\"noreferrer\">This section</a> of the official documentation addresses the original question.</p>\n" }, { "answer_id": 30900130, "author": "Kingsley Uyi Idehen", "author_id": 213503, "author_profile": "https://Stackoverflow.com/users/213503", "pm_score": 3, "selected": false, "text": "<p>RDF is a Language, i.e., a system of signs, syntax, and semantics for encoding and decoding information (data in some context). </p>\n\n<p>In RDF, a unit of observation (Data) is represented by a sentence that consists of three parts: subject, predicate, object. Basically, this is the fundamental structure of natural language speech. </p>\n\n<p>The sign used to denote entities (things) participating in entity relationships represented by RDF is an IRI (which includes HTTP URIs). Each subject and predicate (and optionally, object) component of an RDF sentence is denoted by an IRI.</p>\n\n<p>The syntax (grammar) is abstract (meaning it can be represented using a variety of notations) in the form of subject, predicate, and object arrangement order. </p>\n\n<p>The semantics (the part overlooked most often) is all about the meaning of the subject, predicate, and object roles in an RDF statement. </p>\n\n<p>When you use HTTP URIs to denote RDF statement subject, predicates, and (optionally) objects, you end up with structured data (collections of entity relationship types) that form a web -- just as you have today on the World Wide Web. </p>\n\n<p>When the semantics of a predicate (in particular) in an RDF statement are both machine and human comprehensible you have a web of entity relationship types that provide powerful encoding of information that is a foundation for knowledge (inference and reasoning). </p>\n\n<p>Here are examples of simple RDF statements:</p>\n\n<pre><code>{\n &lt;#this&gt; a schema:WebPage .\n &lt;#this&gt; schema:about dbpedia:Resource_Description_Framework .\n &lt;#this&gt; skos:related &lt;https://stackoverflow.com/questions/30742747/convert-a-statement-with-adjective-in-rdf-triple/30836089#30836089&gt; . \n}\n</code></pre>\n\n<p>I've used braces to enclose the examples so that this post turns into a live RDF-based Linked Data demonstration, courtesy of relative HTTP URIs and the <code>#</code> based fragment identifier (indexical). </p>\n\n<p>Results of the RDF statements embedded in this post, courtesy of nanotation (embedding RDF statements wherever text is accepted):</p>\n\n<ol>\n<li><a href=\"http://linkeddata.uriburner.com/about/html/https://stackoverflow.com/questions/273218/whats-an-rdf-triple/30900130\" rel=\"nofollow noreferrer\">Basic Entity Description Page</a> -- Each Statement is identified by a hyperlink that resolves to its description (subject, predicate, object parts)</li>\n<li><a href=\"http://linkeddata.uriburner.com/c/9DA56OB6\" rel=\"nofollow noreferrer\">Deeper Faceted Browsing Page</a> -- Alternative view that lends itself to deeper exploration and discovery by following-your-nose through the hyperlinks that constitute the data web or web of linked data.</li>\n<li><a href=\"http://linkeddata.uriburner.com/c/9BI56JYX\" rel=\"nofollow noreferrer\">Description of an embedded statement</a> -- About a specific RDF statement. </li>\n</ol>\n\n<p>Here's the visualization generated from the triples embedded in this post (using our <a href=\"http://osds.openlinksw.com\" rel=\"nofollow noreferrer\">Structured Data Sniffer Browser Extension</a>, using RDF-Turtle Notation:\n<a href=\"https://i.stack.imgur.com/FWNjv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FWNjv.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 32305453, "author": "Batman22", "author_id": 2322576, "author_profile": "https://Stackoverflow.com/users/2322576", "pm_score": 2, "selected": false, "text": "<p>One can think of a triple as a type of sentence that states a single \"fact\" about a resource. First of all to understand RDF Triple you should know that each and every thing in RDF is defined in terms of URI <code>http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-URI-reference</code>or blank node <code>http://www.w3.org/TR/2004/REC-rdf-concepts-20040210/#dfn-blank-node</code>. </p>\n\n<p>An RDF Triple consists of three components :-\n1) Subject\n2) Predicate\n3) Object\nFor ex :- Pranay hasCar Ferrari\nHere Subject is Pranay, hasCar is a predicate and Ferrari is a object. This are each defined with RDF-URI. For more information you can visit :- <a href=\"http://www.w3.org/TR/owl-ref/\" rel=\"nofollow\">http://www.w3.org/TR/owl-ref/</a></p>\n" }, { "answer_id": 40117404, "author": "Hernan Acosta", "author_id": 4196199, "author_profile": "https://Stackoverflow.com/users/4196199", "pm_score": 2, "selected": false, "text": "<p>A <strong>simple answer</strong> can be that an RDF triple is a <strong>representation</strong> of some knowledge <strong>using RDF data model</strong>. This model is based upon the idea of <strong>making statements</strong> about resources (in particular web resources URIs) in the form of <strong>subject–predicate–object</strong> expressions. RDF is also a standard model for <strong>data interchange on the Web</strong>. RDF has features that <strong>facilitate data merging</strong> even if the underlying schemas differ, and it specifically <strong>supports the evolution of schemas</strong> over time without requiring all the data consumers to be changed. I recommend this article to know how: <a href=\"https://www.w3.org/DesignIssues/RDF-XML.html\" rel=\"nofollow noreferrer\">https://www.w3.org/DesignIssues/RDF-XML.html</a></p>\n" }, { "answer_id": 42616673, "author": "Mike Maxwell", "author_id": 1068689, "author_profile": "https://Stackoverflow.com/users/1068689", "pm_score": 3, "selected": false, "text": "<p>I'm going to have to agree with A Pa in part, even though he was down-voted.</p>\n<p>Background: I'm a linguist, with a PhD in that subject, and I work in computational linguistics.</p>\n<p>The statement that &quot;...a sentence that consists of three parts: subject, predicate, object. Basically, this is the fundamental structure of natural language speech&quot; (which A Pa quotes from Kingsley Uyi Idehen's answer) is simply wrong. And it's not just that Kingsley says this, I've heard it from many advocates of RDF triples.</p>\n<p>It's wrong for many reasons, for example: Predicates (in English, arguably, and in many other natural languages) consist of a verb (or a verb-like thing) + the object (and perhaps other complements). It is definitely NOT the case that the syntactic structure of English is Subj-Pred-Obj.</p>\n<p>Furthermore, not all natural language sentences in English have an object; intransitive verbs, in particular, by definition do not take objects. And weather verbs (among other things) don't even take a &quot;real&quot; subject (the &quot;it&quot; of &quot;it rains&quot; has no reference). And on the other hand, ditransitive verbs like &quot;give&quot; take both a direct and an indirect object. Then there are verbs like &quot;put&quot; that take a locative in addition to the direct object, or &quot;tell&quot; that take an object and a clause. Not to mention adjuncts, like time and manner adverbials.</p>\n<p>Yes, of course you can represent embedded clauses as embedded triples (to the extent that you can represent any statement as triples, which as I hope you've made clear, you can't), but what I don't think you can do in RDF (at least I've never seen it done, and it seems like it would take a quadruple) is to have both an object and an embedded clause. Likewise both a direct and an indirect object, or adjuncts.</p>\n<p>So whatever the motivation for RDF triples, I wish the advocates would stop pretending that there's a linguistic motivation, or that the triples in any way resemble natural language syntax. Because they don't.</p>\n" }, { "answer_id": 49066324, "author": "jschnasse", "author_id": 1485527, "author_profile": "https://Stackoverflow.com/users/1485527", "pm_score": 1, "selected": false, "text": "<p><strong>Triple explained by example</strong></p>\n<p>Be there a table that relates users and questions.</p>\n<pre>\nTABLE dc:creator\n-------------------------\n| Question | User |\n-------------------------\n| 45 | 485527 |\n| 44 | 485527 |\n| 40 | 485528 |\n</pre>\n<p>This could conceptually be expressed in three <a href=\"https://www.w3.org/TR/rdf-concepts/#section-Concepts\" rel=\"nofollow noreferrer\">RDF triples</a> like...</p>\n<pre><code>&lt;question:45&gt; &lt;dc:creator&gt; &lt;user:485527&gt;\n&lt;question:44&gt; &lt;dc:creator&gt; &lt;user:485527&gt;\n&lt;question:40&gt; &lt;dc:creator&gt; &lt;user:485528&gt;\n</code></pre>\n<p>...so that each row is converted to one <code>triple</code> that relates a user to a question. The general form of each triple can be described as:</p>\n<p><code>&lt;Subject&gt; &lt;Predicate&gt; &lt;Object&gt;</code></p>\n<p>One specialty about RDF is, that you can (or must) use <a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">URIs</a>/<a href=\"https://www.rfc-editor.org/rfc/rfc3987\" rel=\"nofollow noreferrer\">IRIs</a> to identify <a href=\"https://www.w3.org/TR/rdf-schema/#ch_classes\" rel=\"nofollow noreferrer\">entities</a> as well as <a href=\"https://www.w3.org/TR/rdf-schema/#ch_properties\" rel=\"nofollow noreferrer\">relations</a>. Find more <a href=\"https://www.w3.org/TR/rdf-concepts/#section-triples\" rel=\"nofollow noreferrer\">here</a>. This makes it possible for everyone to <a href=\"http://lov.okfn.org/dataset/lov/\" rel=\"nofollow noreferrer\">reuse already existing</a> relations (predicates) and to publish statements about arbitrary entities <a href=\"https://www.w3.org/standards/semanticweb/data\" rel=\"nofollow noreferrer\">in the www</a>.</p>\n<p>Example relating a SO answer to its creator:</p>\n<pre><code>&lt;https://stackoverflow.com/a/49066324/1485527&gt; \n&lt;http://purl.org/dc/terms/creator&gt; \n&lt;https://stackoverflow.com/users/1485527&gt;\n</code></pre>\n" }, { "answer_id": 53530532, "author": "Max Dor", "author_id": 4761274, "author_profile": "https://Stackoverflow.com/users/4761274", "pm_score": 1, "selected": false, "text": "<p>As a developer, I have struggled for a while until I finally understood what RDF and its tripes was about, mostly because I have always seen the world through code and not through data.</p>\n\n<p>Given this is posted on StackOverflow, here is the Java analogy that finally made it click for me: a RDF triple is to data what a class' method/parameter is to code.</p>\n\n<p>So:</p>\n\n<ul>\n<li>A class with its package name is the Subject</li>\n<li>A method on this class is the Predicate</li>\n<li>Parameter(s) on the method is the Object, which are themselves represented by classes</li>\n<li>Contexts are import statements to avoid writing the full canonical name of classes</li>\n</ul>\n\n<p>The only point where this analogy breaks down a bit is that Predicates also have namespaces, while methods do not. But the overall relationships created between class instances as Subject and Object when a Predicate is used reflects on the idea of calling a method to do something.</p>\n\n<p>Basically, RDF is to data what OO is to code.</p>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35588/" ]
In layman's terms, what's a RDF triple?
I think the question needs to be split into two parts - what is a triple and what makes an "RDF triple" so special? Firstly, a triple is, as most of the other commenters here have already pointed out, a statement in "subject/predicate/object" form - i.e. a statement linking one object (subject) to another object(object) or a literal, via a predicate. We are all familiar with triples: a triple is the smallest irreducible representation for binary relationship. In plain English: a spreadsheet is a collection of triples, for example, if a column in your spreadsheet has the heading "Paul" and a row has the heading "has Sister" and the value in the cell is "Lisa". Here you have a triple: Paul (subject) has Sister(predicate) Lisa (literal/object). What makes RDF triples special is that EVERY PART of the triple has a URI associated with it, so the everyday statement "Mike Smith knows John Doe" might be represented in RDF as: ``` uri://people#MikeSmith12 http://xmlns.com/foaf/0.1/knows uri://people#JohnDoe45 ``` The analogy to the spreadsheet is that by giving every part of the URI a unique address, you give the cell in the spreadsheet its whole address space....so you could in principle stick every cell (if expressed in RDF triples) of the spreadsheet into a different document on a different server and reconstitute the spreadsheet through a single query. Edit: [This section](https://www.w3.org/TR/2014/NOTE-rdf11-primer-20140624/#section-triple) of the official documentation addresses the original question.
273,238
<p>How do I get:</p> <pre><code>id Name Value 1 A 4 1 B 8 2 C 9 </code></pre> <p>to</p> <pre><code>id Column 1 A:4, B:8 2 C:9 </code></pre>
[ { "answer_id": 273256, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<p>This kind of question is asked here very often, and the solution is going to depend a lot on the underlying requirements:</p>\n\n<p><a href=\"https://stackoverflow.com/search?q=sql+pivot\">https://stackoverflow.com/search?q=sql+pivot</a></p>\n\n<p>and</p>\n\n<p><a href=\"https://stackoverflow.com/search?q=sql+concatenate\">https://stackoverflow.com/search?q=sql+concatenate</a></p>\n\n<p>Typically, there is no SQL-only way to do this without either dynamic sql, a user-defined function, or a cursor.</p>\n" }, { "answer_id": 273293, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 3, "selected": false, "text": "<p>Just to add to what Cade said, this is usually a front-end display thing and should therefore be handled there. I know that sometimes it's easier to write something 100% in SQL for things like file export or other \"SQL only\" solutions, but most of the times this concatenation should be handled in your display layer.</p>\n" }, { "answer_id": 273319, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>Don't need a cursor... a while loop is sufficient.</p>\n\n<pre><code>------------------------------\n-- Setup\n------------------------------\n\nDECLARE @Source TABLE\n(\n id int,\n Name varchar(30),\n Value int\n)\n\nDECLARE @Target TABLE\n(\n id int,\n Result varchar(max) \n)\n\n\nINSERT INTO @Source(id, Name, Value) SELECT 1, 'A', 4\nINSERT INTO @Source(id, Name, Value) SELECT 1, 'B', 8\nINSERT INTO @Source(id, Name, Value) SELECT 2, 'C', 9\n\n\n------------------------------\n-- Technique\n------------------------------\n\nINSERT INTO @Target (id)\nSELECT id\nFROM @Source\nGROUP BY id\n\nDECLARE @id int, @Result varchar(max)\nSET @id = (SELECT MIN(id) FROM @Target)\n\nWHILE @id is not null\nBEGIN\n SET @Result = null\n\n SELECT @Result =\n CASE\n WHEN @Result is null\n THEN ''\n ELSE @Result + ', '\n END + s.Name + ':' + convert(varchar(30),s.Value)\n FROM @Source s\n WHERE id = @id\n\n UPDATE @Target\n SET Result = @Result\n WHERE id = @id\n\n SET @id = (SELECT MIN(id) FROM @Target WHERE @id &lt; id)\nEND\n\nSELECT *\nFROM @Target\n</code></pre>\n" }, { "answer_id": 273330, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 10, "selected": true, "text": "<p><strong>No CURSOR, WHILE loop, or User-Defined Function needed</strong>. </p>\n\n<p>Just need to be creative with FOR XML and PATH.</p>\n\n<p>[Note: This solution only works on SQL 2005 and later. Original question didn't specify the version in use.]</p>\n\n<pre><code>CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\nSELECT \n [ID],\n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) \n FROM #YourTable \n WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID\n\nDROP TABLE #YourTable\n</code></pre>\n" }, { "answer_id": 304305, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>SQL Server 2005 and later allow you to create your own <a href=\"http://msdn.microsoft.com/en-us/library/ms182741.aspx\" rel=\"noreferrer\">custom aggregate functions</a>, including for things like concatenation- see the sample at the bottom of the linked article.</p>\n" }, { "answer_id": 3013557, "author": "cyberkiwi", "author_id": 363337, "author_profile": "https://Stackoverflow.com/users/363337", "pm_score": 5, "selected": false, "text": "<p>Another option using Sql Server 2005 and above</p>\n\n<pre><code>---- test data\ndeclare @t table (OUTPUTID int, SCHME varchar(10), DESCR varchar(10))\ninsert @t select 1125439 ,'CKT','Approved'\ninsert @t select 1125439 ,'RENO','Approved'\ninsert @t select 1134691 ,'CKT','Approved'\ninsert @t select 1134691 ,'RENO','Approved'\ninsert @t select 1134691 ,'pn','Approved'\n\n---- actual query\n;with cte(outputid,combined,rn)\nas\n(\n select outputid, SCHME + ' ('+DESCR+')', rn=ROW_NUMBER() over (PARTITION by outputid order by schme, descr)\n from @t\n)\n,cte2(outputid,finalstatus,rn)\nas\n(\nselect OUTPUTID, convert(varchar(max),combined), 1 from cte where rn=1\nunion all\nselect cte2.outputid, convert(varchar(max),cte2.finalstatus+', '+cte.combined), cte2.rn+1\nfrom cte2\ninner join cte on cte.OUTPUTID = cte2.outputid and cte.rn=cte2.rn+1\n)\nselect outputid, MAX(finalstatus) from cte2 group by outputid\n</code></pre>\n" }, { "answer_id": 5939601, "author": "Phillip", "author_id": 571814, "author_profile": "https://Stackoverflow.com/users/571814", "pm_score": 3, "selected": false, "text": "<p>This is just an addition to Kevin Fairchild's post (very clever by the way). I would have added it as a comment, but I don't have enough points yet :)</p>\n\n<p>I was using this idea for a view I was working on, however the items I was concatinating contained spaces. So I modified the code slightly to not use spaces as delimiters. </p>\n\n<p>Again thanks for the cool workaround Kevin!</p>\n\n<pre><code>CREATE TABLE #YourTable ( [ID] INT, [Name] CHAR(1), [Value] INT ) \n\nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'A', 4) \nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'B', 8) \nINSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (2, 'C', 9) \n\nSELECT [ID], \n REPLACE(REPLACE(REPLACE(\n (SELECT [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) as A \n FROM #YourTable \n WHERE ( ID = Results.ID ) \n FOR XML PATH (''))\n , '&lt;/A&gt;&lt;A&gt;', ', ')\n ,'&lt;A&gt;','')\n ,'&lt;/A&gt;','') AS NameValues \nFROM #YourTable Results \nGROUP BY ID \n\nDROP TABLE #YourTable \n</code></pre>\n" }, { "answer_id": 7806049, "author": "Jonathan Sayce", "author_id": 13153, "author_profile": "https://Stackoverflow.com/users/13153", "pm_score": 5, "selected": false, "text": "<p>I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (<code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>) which were encoded.</p>\n\n<p>The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:</p>\n\n<pre><code>CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges &amp; Lemons',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 &lt; 2',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\nSELECT [ID],\n STUFF((\n SELECT ', ' + CAST([Name] AS VARCHAR(MAX))\n FROM #YourTable WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE \n /* Use .value to uncomment XML entities e.g. &amp;gt; &amp;lt; etc*/\n ).value('.','VARCHAR(MAX)') \n ,1,2,'') as NameValues\nFROM #YourTable Results\nGROUP BY ID\n\nDROP TABLE #YourTable\n</code></pre>\n\n<p>Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses <code>STUFF</code> to remove the first two characters.</p>\n\n<p>The XML encoding is taken care of automatically by using the <a href=\"http://msdn.microsoft.com/en-us/library/ms190025.aspx\" rel=\"noreferrer\">TYPE</a> directive.</p>\n" }, { "answer_id": 8404473, "author": "Allen", "author_id": 1015072, "author_profile": "https://Stackoverflow.com/users/1015072", "pm_score": 6, "selected": false, "text": "<p>using XML path will not perfectly concatenate as you might expect... it will replace \"&amp;\" with \"&amp;amp;\" and will also mess with <code>&lt;\" and \"&gt;</code>\n...maybe a few other things, not sure...but you can try this</p>\n\n<p>I came across a workaround for this... you need to replace:</p>\n\n<pre><code>FOR XML PATH('')\n)\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>FOR XML PATH(''),TYPE\n).value('(./text())[1]','VARCHAR(MAX)')\n</code></pre>\n\n<p>...or <code>NVARCHAR(MAX)</code> if thats what youre using.</p>\n\n<p>why the hell doesn't <code>SQL</code> have a concatenate aggregate function? this is a PITA.</p>\n" }, { "answer_id": 14646419, "author": "Michal B.", "author_id": 989256, "author_profile": "https://Stackoverflow.com/users/989256", "pm_score": 3, "selected": false, "text": "<h1>An example would be</h1>\n<p>In Oracle you can use LISTAGG aggregate function.</p>\n<p><strong>Original records</strong></p>\n<pre><code>name type\n------------\nname1 type1\nname2 type2\nname2 type3\n</code></pre>\n<p><strong>Sql</strong></p>\n<pre><code>SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)\nFROM table\nGROUP BY name\n</code></pre>\n<p><strong>Result in</strong></p>\n<pre><code>name type\n------------\nname1 type1\nname2 type2; type3\n</code></pre>\n" }, { "answer_id": 29356760, "author": "Marquinho Peli", "author_id": 2992192, "author_profile": "https://Stackoverflow.com/users/2992192", "pm_score": 2, "selected": false, "text": "<p>Let's get very simple:</p>\n\n<pre><code>SELECT stuff(\n (\n select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb \n FOR XML PATH('')\n )\n, 1, 2, '')\n</code></pre>\n\n<p>Replace this line:</p>\n\n<pre><code>select ', ' + x from (SELECT 'xxx' x union select 'yyyy') tb\n</code></pre>\n\n<p>With your query.</p>\n" }, { "answer_id": 31002733, "author": "Eduard", "author_id": 5040220, "author_profile": "https://Stackoverflow.com/users/5040220", "pm_score": 2, "selected": false, "text": "<p>You can improve performance significant the following way if group by contains mostly one item: </p>\n\n<pre><code>SELECT \n [ID],\n\nCASE WHEN MAX( [Name]) = MIN( [Name]) THEN \nMAX( [Name]) NameValues\nELSE\n\n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) \n FROM #YourTable \n WHERE (ID = Results.ID) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\n\nEND\n\nFROM #YourTable Results\nGROUP BY ID\n</code></pre>\n" }, { "answer_id": 36097542, "author": "Orlando Colamatteo", "author_id": 222606, "author_profile": "https://Stackoverflow.com/users/222606", "pm_score": 4, "selected": false, "text": "<p>Install the SQLCLR Aggregates from <a href=\"http://groupconcat.codeplex.com\" rel=\"noreferrer\">http://groupconcat.codeplex.com</a></p>\n\n<p>Then you can write code like this to get the result you asked for:</p>\n\n<pre><code>CREATE TABLE foo\n(\n id INT,\n name CHAR(1),\n Value CHAR(1)\n);\n\nINSERT INTO dbo.foo\n (id, name, Value)\nVALUES (1, 'A', '4'),\n (1, 'B', '8'),\n (2, 'C', '9');\n\nSELECT id,\n dbo.GROUP_CONCAT(name + ':' + Value) AS [Column]\nFROM dbo.foo\nGROUP BY id;\n</code></pre>\n" }, { "answer_id": 42168649, "author": "Shem Sargent", "author_id": 4759851, "author_profile": "https://Stackoverflow.com/users/4759851", "pm_score": 4, "selected": false, "text": "<p>Eight years later... Microsoft SQL Server vNext Database Engine has finally enhanced Transact-SQL to directly support grouped string concatenation. The Community Technical Preview version 1.0 added the STRING_AGG function and CTP 1.1 added the WITHIN GROUP clause for the STRING_AGG function.</p>\n\n<p>Reference: <a href=\"https://msdn.microsoft.com/en-us/library/mt775028.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/mt775028.aspx</a></p>\n" }, { "answer_id": 42807061, "author": "Mordechai", "author_id": 1047231, "author_profile": "https://Stackoverflow.com/users/1047231", "pm_score": 2, "selected": false, "text": "<p>didn't see any cross apply answers, also no need for xml extraction. Here is a slightly different version of what Kevin Fairchild wrote. It's faster and easier to use in more complex queries:</p>\n\n<pre><code> select T.ID\n,MAX(X.cl) NameValues\n from #YourTable T\n CROSS APPLY \n (select STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))\n FROM #YourTable \n WHERE (ID = T.ID) \n FOR XML PATH(''))\n ,1,2,'') [cl]) X\n GROUP BY T.ID\n</code></pre>\n" }, { "answer_id": 43664415, "author": "Kannan Kandasamy", "author_id": 6466279, "author_profile": "https://Stackoverflow.com/users/6466279", "pm_score": 8, "selected": false, "text": "<p>If it is SQL Server 2017 or SQL Server Vnext, SQL Azure you can use <code>STRING_AGG</code> as below:</p>\n<pre><code>SELECT id, STRING_AGG(CONCAT(name, ':', [value]), ', ')\nFROM #YourTable \nGROUP BY id\n</code></pre>\n" }, { "answer_id": 57726143, "author": "Mahesh", "author_id": 4790127, "author_profile": "https://Stackoverflow.com/users/4790127", "pm_score": 1, "selected": false, "text": "<p>Using Replace Function and FOR JSON PATH</p>\n\n<pre><code>SELECT T3.DEPT, REPLACE(REPLACE(T3.ENAME,'{\"ENAME\":\"',''),'\"}','') AS ENAME_LIST\nFROM (\n SELECT DEPT, (SELECT ENAME AS [ENAME]\n FROM EMPLOYEE T2\n WHERE T2.DEPT=T1.DEPT\n FOR JSON PATH,WITHOUT_ARRAY_WRAPPER) ENAME\n FROM EMPLOYEE T1\n GROUP BY DEPT) T3\n</code></pre>\n\n<p>For sample data and more ways <a href=\"https://www.devgateways.com/2019/08/concatenate-values-within-each-group-defined-by-sql-server.html\" rel=\"nofollow noreferrer\">click here</a></p>\n" }, { "answer_id": 59783512, "author": "Manfred Wippel", "author_id": 5974965, "author_profile": "https://Stackoverflow.com/users/5974965", "pm_score": 1, "selected": false, "text": "<p>If you have clr enabled you could use the <a href=\"https://github.com/orlando-colamatteo/ms-sql-server-group-concat-sqlclr\" rel=\"nofollow noreferrer\">Group_Concat</a> library from GitHub</p>\n" }, { "answer_id": 64346774, "author": "Syzako", "author_id": 5725441, "author_profile": "https://Stackoverflow.com/users/5725441", "pm_score": 0, "selected": false, "text": "<p>Another example without the garbage: &quot;,TYPE).value('(./text())[1]','VARCHAR(MAX)')&quot;</p>\n<pre><code>WITH t AS (\n SELECT 1 n, 1 g, 1 v\n UNION ALL \n SELECT 2 n, 1 g, 2 v\n UNION ALL \n SELECT 3 n, 2 g, 3 v\n)\nSELECT g\n , STUFF (\n (\n SELECT ', ' + CAST(v AS VARCHAR(MAX))\n FROM t sub_t\n WHERE sub_t.g = main_t.g\n FOR XML PATH('')\n )\n , 1, 2, ''\n ) cg\nFROM t main_t\nGROUP BY g\n</code></pre>\n<p>Input-output is</p>\n<pre><code>************************* -&gt; *********************\n* n * g * v * * g * cg *\n* - * - * - * * - * - *\n* 1 * 1 * 1 * * 1 * 1, 2 *\n* 2 * 1 * 2 * * 2 * 3 *\n* 3 * 2 * 3 * *********************\n************************* \n</code></pre>\n" }, { "answer_id": 64901189, "author": "CJurkus", "author_id": 3813981, "author_profile": "https://Stackoverflow.com/users/3813981", "pm_score": 2, "selected": false, "text": "<p>Using the Stuff and for xml path operator to concatenate rows to string :Group By two columns --&gt;</p>\n<pre><code>CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)\n\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',5)\nINSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)\n\n-- retrieve each unique id and name columns and concatonate the values into one column\nSELECT \n [ID], \n STUFF((\n SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES EACH APPLICATION : VALUE SET \n FROM #YourTable \n WHERE (ID = Results.ID and Name = results.[name] ) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID\n\n\nSELECT \n [ID],[Name] , --these are acting as the group by clause\n STUFF((\n SELECT ', '+ CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES THE VALUES FOR EACH ID NAME COMBINATION \n FROM #YourTable \n WHERE (ID = Results.ID and Name = results.[name] ) \n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,1,2,'') AS NameValues\nFROM #YourTable Results\nGROUP BY ID, name\n\nDROP TABLE #YourTable\n</code></pre>\n" }, { "answer_id": 66463664, "author": "Ken Lassesen", "author_id": 5749406, "author_profile": "https://Stackoverflow.com/users/5749406", "pm_score": 0, "selected": false, "text": "<p>I used this approach which may be easier to grasp. Get a root element, then concat to choices any item with the same ID but not the 'official' name</p>\n<pre><code> Declare @IdxList as Table(id int, choices varchar(max),AisName varchar(255))\n Insert into @IdxLIst(id,choices,AisName)\n Select IdxId,''''+Max(Title)+'''',Max(Title) From [dbo].[dta_Alias] \n where IdxId is not null group by IdxId\n Update @IdxLIst\n set choices=choices +','''+Title+''''\n From @IdxLIst JOIN [dta_Alias] ON id=IdxId And Title &lt;&gt; AisName\n where IdxId is not null\n Select * from @IdxList where choices like '%,%'\n</code></pre>\n" }, { "answer_id": 67129566, "author": "Aus_10", "author_id": 4254538, "author_profile": "https://Stackoverflow.com/users/4254538", "pm_score": 0, "selected": false, "text": "<p>For all my healthcare folks out there:</p>\n<pre class=\"lang-sql prettyprint-override\"><code> \nSELECT\ns.NOTE_ID\n,STUFF ((\n SELECT\n [note_text] + ' ' \n FROM\n HNO_NOTE_TEXT s1\n WHERE\n (s1.NOTE_ID = s.NOTE_ID)\n ORDER BY [line] ASC\n FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')\n ,\n 1,\n 2,\n '') AS NOTE_TEXT_CONCATINATED\nFROM\n HNO_NOTE_TEXT s\n GROUP BY NOTE_ID\n \n</code></pre>\n" } ]
2008/11/07
[ "https://Stackoverflow.com/questions/273238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
How do I get: ``` id Name Value 1 A 4 1 B 8 2 C 9 ``` to ``` id Column 1 A:4, B:8 2 C:9 ```
**No CURSOR, WHILE loop, or User-Defined Function needed**. Just need to be creative with FOR XML and PATH. [Note: This solution only works on SQL 2005 and later. Original question didn't specify the version in use.] ``` CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT) INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4) INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8) INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9) SELECT [ID], STUFF(( SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) FROM #YourTable WHERE (ID = Results.ID) FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)') ,1,2,'') AS NameValues FROM #YourTable Results GROUP BY ID DROP TABLE #YourTable ```