qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
17,532
<h2>Summary</h2> <p>Hi All,<br /> OK, further into my adventures with custom controls...</p> <p>In summary, here is that I have learned of three main &quot;classes&quot; of custom controls. Please feel free to correct me if any of this is wrong!</p> <ol> <li><strong>UserControls</strong> - Which inherit from <em>UserControl</em> and are contained within an <em>ASCX</em> file. These are pretty limited in what they can do, but are a quick and light way to get some UI commonality with designer support.</li> <li><strong>Custom Composite Controls</strong> - These are controls that inherit from <em>WebControl</em> where you add pre-existing controls to the control within the <em>CreateChildControls</em> method. This provides great flexibility, but lack of designer support without additional coding. They are highly portable though since they can be compiled into a DLL.</li> <li><strong>Custom Rendered Controls</strong> - Similar to Custom Composite Controls, these are added to a Web Control Library project. The rendering of the control is completely controlled by the programmer by overriding the <em>Render</em> method.</li> </ol> <h2>My Thoughts..</h2> <p>OK, so while playing with custom composites, I found the following:</p> <ul> <li>You have little/no control over the HTML output making it difficult to &quot;debug&quot;.</li> <li>The <em>CreateChildControls</em> (and subsequent methods) can get real busy with <em>Controls.Add(myControl)</em> everywhere.</li> <li>I found rendering tables (be it for layout or content) to be considerably awkward.</li> </ul> <h2>The Question(s)..</h2> <p>So, I admit, I am new to this so I could be way off-base with some of my points noted above..</p> <ul> <li>Do you use Composites?</li> <li>Do you have any neat tricks to control the HTML output?</li> <li>Do you just say &quot;to hell with it&quot; and go ahead and create a custom rendered control?</li> </ul> <p><strong>Its something I am keen to get really firm in my mind since I know how much <em>good</em> control development can cut overall development time.</strong></p> <p>I look forward to your answers ^_^</p>
[ { "answer_id": 17546, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "//Controls.Add(c1, c2, c3)\nstatic void Add(this ControlCollection coll, params Control[] controls)\n { foreach(Control control in controls) coll.Add(control);\n }\n writer.Render(@\"<table>\n <tr><td>{0}</td></tr>\n <tr>\n <td>\", Text);\ncontrol1.RenderControl(writer);\nwriter.Render(\"</td></tr></table>\");\n childControl = new Control { ID=\"Foo\"\n , CssClass=\"class1\"\n , CausesValidation=true;\n };\n" }, { "answer_id": 17916, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": " public static void WriteControls\n (this HtmlTextWriter o, string format, params object[] args)\n { \n const string delimiter = \"<2E01A260-BD39-47d0-8C5E-0DF814FDF9DC>\";\n var controls = new Dictionary<string,Control>();\n\n for(int i =0; i < args.Length; ++i)\n { \n var c = args[i] as Control; \n if (c==null) continue;\n var guid = Guid.NewGuid().ToString();\n controls[guid] = c;\n args[i] = delimiter+guid+delimiter;\n }\n\n var _strings = string.Format(format, args)\n .Split(new string[]{delimiter},\n StringSplitOptions.None);\n foreach(var s in _strings)\n { \n if (controls.ContainsKey(s)) \n controls[s].RenderControl(o);\n else \n o.Write(s);\n }\n}\n protected override void RenderContents(HtmlTextWriter o)\n{ \n o.WriteControls\n (@\"<table>\n <tr>\n <td>{0}</td>\n <td>{1}</td>\n </tr>\n </table>\"\n ,Text\n ,control1);\n }\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
17,533
<p>For my C# app, I don't want to always prompt for elevation on application start, but if they choose an output path that is UAC protected then I need to request elevation.</p> <p>So, how do I check if a path is UAC protected and then how do I request elevation mid-execution?</p>
[ { "answer_id": 90442, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 6, "selected": true, "text": "UnauthorizedAccessException" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147/" ]
17,576
<p>In C#, when you implement an interface, all members are implicitly public. Wouldn't it be better if we could specify the accessibility modifier (<code>protected</code>, <code>internal</code>, except <code>private</code> of course), or should we just use an abstract class instead?</p>
[ { "answer_id": 17598, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 4, "selected": false, "text": "public interface IInterface {\n public void Method();\n}\n\npublic class A : IInterface {\n public void IInterface.Method() {\n // Do something\n }\n}\n\npublic class Program {\n public static void Main() {\n A o = new A();\n o.Method(); // Will not compile\n ((IInterface)o).Method(); // Will compile\n }\n}\n" }, { "answer_id": 251340, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "interface IVehicle\n{\n void Drive();\n void Steer();\n void UseHook();\n}\nabstract class Vehicle // :IVehicle // Try it and see!\n{\n /// <summary>\n /// Consuming classes are not required to implement this method.\n /// </summary>\n protected virtual void Hook()\n {\n return;\n }\n}\nclass Car : Vehicle, IVehicle\n{\n protected override void Hook() // you must use keyword \"override\"\n {\n Console.WriteLine(\" Car.Hook(): Uses abstracted method.\");\n }\n #region IVehicle Members\n\n public void Drive()\n {\n Console.WriteLine(\" Car.Drive(): Uses a tires and a motor.\");\n }\n\n public void Steer()\n {\n Console.WriteLine(\" Car.Steer(): Uses a steering wheel.\");\n }\n /// <summary>\n /// This code is duplicated in implementing classes. Hmm.\n /// </summary>\n void IVehicle.UseHook()\n {\n this.Hook();\n }\n\n #endregion\n}\nclass Airplane : Vehicle, IVehicle\n{\n protected override void Hook() // you must use keyword \"override\"\n {\n Console.WriteLine(\" Airplane.Hook(): Uses abstracted method.\");\n }\n #region IVehicle Members\n\n public void Drive()\n {\n Console.WriteLine(\" Airplane.Drive(): Uses wings and a motor.\");\n }\n\n public void Steer()\n {\n Console.WriteLine(\" Airplane.Steer(): Uses a control stick.\");\n }\n /// <summary>\n /// This code is duplicated in implementing classes. Hmm.\n /// </summary>\n void IVehicle.UseHook()\n {\n this.Hook();\n }\n\n #endregion\n}\n class Program\n{\n static void Main(string[] args)\n {\n Car car = new Car();\n IVehicle contract = (IVehicle)car;\n UseContract(contract); // This line is identical...\n Airplane airplane = new Airplane();\n contract = (IVehicle)airplane;\n UseContract(contract); // ...to the line above!\n }\n\n private static void UseContract(IVehicle contract)\n {\n // Try typing these 3 lines yourself, watch IDE behavior.\n contract.Drive();\n contract.Steer();\n contract.UseHook();\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadLine();\n }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/718/" ]
17,586
<p>Word wrap is one of the must-have features in a modern text editor.</p> <p>How word wrap be handled? What is the best algorithm for word-wrap?</p> <p>If text is several million lines, how can I make word-wrap very fast?</p> <p>Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance.</p> <p>The running environment is Windows Mobile devices. The maximum 600&nbsp;MHz speed with very small memory size.</p> <p>How should I handle line information? Let's assume original data has three lines.</p> <pre><code>THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. </code></pre> <p>Afterwards, the break text will be shown like this:</p> <pre><code>THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. </code></pre> <p>Should I allocate three lines more? Or any other suggestions? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17635, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 5, "selected": false, "text": "IndexOfAny static char[] splitChars = new char[] { ' ', '-', '\\t' };\n\nprivate static string WordWrap(string str, int width)\n{\n string[] words = Explode(str, splitChars);\n\n int curLineLength = 0;\n StringBuilder strBuilder = new StringBuilder();\n for(int i = 0; i < words.Length; i += 1)\n {\n string word = words[i];\n // If adding the new word to the current line would be too long,\n // then put it on a new line (and split it up if it's too long).\n if (curLineLength + word.Length > width)\n {\n // Only move down to a new line if we have text on the current line.\n // Avoids situation where wrapped whitespace causes emptylines in text.\n if (curLineLength > 0)\n {\n strBuilder.Append(Environment.NewLine);\n curLineLength = 0;\n }\n\n // If the current word is too long to fit on a line even on it's own then\n // split the word up.\n while (word.Length > width)\n {\n strBuilder.Append(word.Substring(0, width - 1) + \"-\");\n word = word.Substring(width - 1);\n\n strBuilder.Append(Environment.NewLine);\n }\n\n // Remove leading whitespace from the word so the new line starts flush to the left.\n word = word.TrimStart();\n }\n strBuilder.Append(word);\n curLineLength += word.Length;\n }\n\n return strBuilder.ToString();\n}\n\nprivate static string[] Explode(string str, char[] splitChars)\n{\n List<string> parts = new List<string>();\n int startIndex = 0;\n while (true)\n {\n int index = str.IndexOfAny(splitChars, startIndex);\n\n if (index == -1)\n {\n parts.Add(str.Substring(startIndex));\n return parts.ToArray();\n }\n\n string word = str.Substring(startIndex, index - startIndex);\n char nextChar = str.Substring(index, 1)[0];\n // Dashes and the likes should stick to the word occuring before it. Whitespace doesn't have to.\n if (char.IsWhiteSpace(nextChar))\n {\n parts.Add(word);\n parts.Add(nextChar.ToString());\n }\n else\n {\n parts.Add(word + nextChar);\n }\n\n startIndex = index + 1;\n }\n}\n" }, { "answer_id": 29807751, "author": "BigBangBuddha", "author_id": 4821288, "author_profile": "https://Stackoverflow.com/users/4821288", "pm_score": 1, "selected": false, "text": "public static void WordWrap(this StringBuilder sb, int tabSize, int width)\n{\n string[] lines = sb.ToString().Replace(\"\\r\\n\", \"\\n\").Split('\\n');\n sb.Clear();\n for (int i = 0; i < lines.Length; ++i)\n {\n var line = lines[i];\n if (line.Length < 1)\n sb.AppendLine();//empty lines\n else\n {\n int indent = line.TakeWhile(c => c == '\\t').Count(); //tab indents \n line = line.Replace(\"\\t\", new String(' ', tabSize)); //need to expand tabs here\n string lead = new String(' ', indent * tabSize); //create the leading space\n do\n {\n //get the string that fits in the window\n string subline = line.Substring(0, Math.Min(line.Length, width));\n if (subline.Length < line.Length && subline.Length > 0)\n {\n //grab the last non white character\n int lastword = subline.LastOrDefault() == ' ' ? -1 : subline.LastIndexOf(' ', subline.Length - 1);\n if (lastword >= 0)\n subline = subline.Substring(0, lastword);\n sb.AppendLine(subline);\n\n //next part\n line = lead + line.Substring(subline.Length).TrimStart();\n }\n else \n {\n sb.AppendLine(subline); //everything fits\n break;\n }\n }\n while (true);\n }\n }\n}\n" }, { "answer_id": 34097833, "author": "Jeff Y", "author_id": 5379657, "author_profile": "https://Stackoverflow.com/users/5379657", "pm_score": 0, "selected": false, "text": "fold -s wc -w wc -c #!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $WIDTH = 80;\n\nif ($ARGV[0] =~ /^[1-9][0-9]*$/) {\n $WIDTH = $ARGV[0];\n shift @ARGV;\n}\n\nwhile (<>) {\n\ns/\\r\\n$/\\n/;\nchomp;\n\nif (length $_ <= $WIDTH) {\n print \"$_\\n\";\n next;\n}\n\n@_=split /(\\s+)/;\n\n# make @_ start with a separator field and end with a content field\nunshift @_, \"\";\npush @_, \"\" if @_%2;\n\nmy ($sep,$cont) = splice(@_, 0, 2);\ndo {\n if (length $cont > $WIDTH) {\n print \"$cont\";\n ($sep,$cont) = splice(@_, 0, 2);\n }\n elsif (length($sep) + length($cont) > $WIDTH) {\n printf \"%*s%s\", $WIDTH - length $cont, \"\", $cont;\n ($sep,$cont) = splice(@_, 0, 2);\n }\n else {\n my $remain = $WIDTH;\n { do {\n print \"$sep$cont\";\n $remain -= length $sep;\n $remain -= length $cont;\n ($sep,$cont) = splice(@_, 0, 2) or last;\n }\n while (length($sep) + length($cont) <= $remain);\n }\n }\n print \"\\n\";\n $sep = \"\";\n}\nwhile ($cont);\n\n}\n" }, { "answer_id": 37738188, "author": "Philippe Carphin", "author_id": 5795941, "author_profile": "https://Stackoverflow.com/users/5795941", "pm_score": 1, "selected": false, "text": "'\\n' This line breaks here\n This line breaks\n here\n '\\n' #include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\nint isDelim(char c){\n switch(c){\n case '\\0':\n case '\\t':\n case ' ' :\n return 1;\n break; /* As a matter of style, put the 'break' anyway even if there is a return above it.*/\n default:\n return 0;\n }\n}\n\nint printLine(const char * start, const char * end){\n const char * p = start;\n while ( p <= end )\n putchar(*p++);\n putchar('\\n');\n}\n\nint main ( int argc , char ** argv ) {\n\n if( argc <= 2 )\n exit(1);\n\n char * start = argv[1];\n char * lastChar = argv[1];\n char * current = argv[1];\n int wrapLength = atoi(argv[2]);\n\n int chars = 1;\n while( *current != '\\0' ){\n while( chars <= wrapLength ){\n while ( !isDelim( *current ) ) ++current, ++chars;\n if( chars <= wrapLength){\n if(*current == '\\0'){\n puts(start);\n return 0;\n }\n lastChar = current-1;\n current++,chars++;\n }\n }\n\n if( lastChar == start )\n lastChar = current-1;\n\n printLine(start,lastChar);\n current = lastChar + 1;\n while(isDelim(*current)){\n if( *current == '\\0')\n return 0;\n else\n ++current;\n }\n start = current;\n lastChar = current;\n chars = 1;\n }\n return 0;\n}\n start lastChar '\\n' while(!isDelim(*current)) ++current,++chars; lastChar while(chars <= wrapLength) start lastChar newline current lastChar+1 return 0 start lastChar current if(*current == '\\0'){\n puts(start);\n return 0;\n}\n if( lastChar == start )\n lastChar = current-1;\n printLine() lastChar" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
17,612
<p>Programmatic solution of course...</p>
[ { "answer_id": 17618, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 4, "selected": false, "text": "public static class Recycle\n{\n private const int FO_DELETE = 3;\n private const int FOF_ALLOWUNDO = 0x40;\n private const int FOF_NOCONFIRMATION = 0x0010;\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]\n public struct SHFILEOPSTRUCT\n {\n public IntPtr hwnd;\n [MarshalAs(UnmanagedType.U4)]\n public int wFunc;\n public string pFrom;\n public string pTo;\n public short fFlags;\n [MarshalAs(UnmanagedType.Bool)]\n public bool fAnyOperationsAborted;\n public IntPtr hNameMappings;\n public string lpszProgressTitle;\n }\n\n [DllImport(\"shell32.dll\", CharSet = CharSet.Auto)]\n static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);\n\n public static void DeleteFileOperation(string filePath)\n {\n SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();\n fileop.wFunc = FO_DELETE;\n fileop.pFrom = filePath + '\\0' + '\\0';\n fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;\n\n SHFileOperation(ref fileop);\n }\n}\n" }, { "answer_id": 17620, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 6, "selected": true, "text": "using Microsoft.VisualBasic;\n\nstring path = @\"c:\\myfile.txt\";\nFileIO.FileSystem.DeleteDirectory(path, \n FileIO.UIOption.OnlyErrorDialogs, \n RecycleOption.SendToRecycleBin);\n" }, { "answer_id": 17623, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 4, "selected": false, "text": "FileSystem.DeleteFile Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file.FullName,\n Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,\n Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);\n Microsoft.VisualBasic Microsoft.VisualBasic" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
17,624
<p>I have a table with a 'filename' column. I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.</p> <p>How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?</p>
[ { "answer_id": 17627, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 6, "selected": true, "text": "UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50\n" }, { "answer_id": 17629, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "update MyTable\nset filename = filename + '.jpg'\nwhere ...\n" }, { "answer_id": 77596, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "DECLARE @Name char(10), @Name2 varchar(10)\nSELECT\n @Name = 'Bob',\n @Name2 = 'Bob'\n\nSELECT\n CASE WHEN @Name2 = @Name THEN 1 ELSE 0 END as Equal,\n CASE WHEN @Name2 like @Name THEN 1 ELSE 0 END as Similiar\n" }, { "answer_id": 79750, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 1, "selected": false, "text": "SELECT *\nFROM tablename \nWHERE LEN(RTRIM([filename])) > 46 \n-- The column size varchar(50) minus 4 chars \n-- for the needed file extension '.jpg' is 46.\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
17,664
<p>I have an ASP.net Application that runs on the internal network (well, actually it's running on Sharepoint 2007). </p> <p>I just wonder:</p> <p>Can I somehow retrieve the name of the PC the Client is using? I would have access to Active Directory if that helps. The thing is, people use multiple PCs. So, I cannot use any manual/static mapping.</p> <p>If possible, I do not want to use any client-side (read: JavaScript) code, but if it cannot be done server-side, JavaScript would be OK as well. ActiveX is absolutely out of question.</p>
[ { "answer_id": 17698, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": true, "text": "System.Net.Dns.GetHostEntry(Page.Request.UserHostAddress).HostName\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
17,681
<p>I have a <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a> installed on a Windows server, serving several repositories.</p> <p>Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a> on top of my repositories.</p> <p>The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials.</p> <p>By visiting the cached copy of the topmost link on <a href="http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN" rel="nofollow noreferrer">this google query</a> you can see what I've found so far that looks promising.<br> (the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de)</p> <p>There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in.</p> <p>Unfortunately, php and apache is largely black magic to me.</p> <p>So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories?</p>
[ { "answer_id": 233587, "author": "Kit Roed", "author_id": 1339, "author_profile": "https://Stackoverflow.com/users/1339", "pm_score": 2, "selected": false, "text": "[components]\ntrac.ticket.* = disabled\ntrac.wiki.* = disabled\n [trac] default_handler = TimelineModule\n default_handler = BrowserModule\n" }, { "answer_id": 2941178, "author": "MatthewMartin", "author_id": 33264, "author_profile": "https://Stackoverflow.com/users/33264", "pm_score": 1, "selected": false, "text": "# For PHP 5 do something like this:\nLoadModule php5_module \"F:/wamp/bin/php/php5.3.0/php5apache2_2.dll\"\nAddType application/x-httpd-php .php\n\n\n# configure the path to php.ini\nPHPIniDir \"f:/wamp/bin/php/php5.3.0/\"\n\n<IfModule dir_module>\n DirectoryIndex index.html index.php \n</IfModule>\n\n#Alias /websvn/ \"F:/Program Files/VisualSVN Server/htdocs/websvn-2.3.1/\" \n\n<Location /websvn-2.3.1/>\n Options FollowSymLinks\n\n AuthName \"Subversion Repositories\"\n AuthType VisualSVN\n AuthzVisualSVNAccessFile \"F:/Repositories/authz-windows\"\n AuthnVisualSVNBasic on\n AuthnVisualSVNIntegrated off\n AuthnVisualSVNUPN Off\n Require valid-user\n\n\n SVNListParentPath on\n SVNParentPath \"f:/Repositories/\"\n</Location>\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
17,721
<p>Have any of you tried Hadoop? Can it be used without the distributed filesystem that goes with it, in a Share-nothing architecture? Would that make sense?</p> <p>I'm also interested into any performance results you have...</p>
[ { "answer_id": 30162186, "author": "sras", "author_id": 4324632, "author_profile": "https://Stackoverflow.com/users/4324632", "pm_score": 0, "selected": false, "text": " <property>\n <name>fs.defaultFS</name>\n <value>file:///</value>\n </property>\n <property>\n <name>fs.default.name</name>\n <value>file:///</value>\n </property>\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446497/" ]
17,725
<p>Hello again ladies and gents!</p> <p>OK, following on from my other question on <a href="https://stackoverflow.com/questions/6681/aspnet-web-service-results-proxy-classes-and-type-conversion">ASP.NET Web Service Results, Proxy Classes and Type Conversion</a>. I've come to a part in my project where I need to get my thinking cap on.</p> <p>Basically, we have a large, complex custom object that needs to be returned from a Web Service and consumed in the client application.</p> <p>Now, based on the previous discussion, we know this is going to then take the form of the proxy class(es) as the return type. To overcome this, we need to basically copy the properties from one to the other.</p> <p>In this case, that is something that I would really, really, <em>really!</em> like to avoid!</p> <p>So, it got me thinking, <strong>how else could we do this?</strong></p> <p>My current thoughts are to enable the object for complete serialization to XML and then return the XML as a string from the Web Service. We then de-serialize at the client. This will mean a fair bit of attribute decorating, but at least the code at both endpoints will be light, namely by just using the .NET XML Serializer.</p> <h2>What are your thoughts on this?</h2>
[ { "answer_id": 17778, "author": "Peter Short", "author_id": 158302, "author_profile": "https://Stackoverflow.com/users/158302", "pm_score": 2, "selected": false, "text": "JSON jQuery jQuery ajax" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
17,732
<p>There's a <a href="http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/8e0235d58c8635c2" rel="noreferrer" title="assertions: does it matter that they are disabled in production?">discussion</a> going on over at comp.lang.c++.moderated about whether or not assertions, which in C++ only exist in debug builds by default, should be kept in production code or not.</p> <p>Obviously, each project is unique, so my question here is <strong>not</strong> so much <strong>whether</strong> assertions should be kept, <strong>but in which cases</strong> this is recommendable/not a good idea.</p> <p>By assertion, I mean:</p> <ul> <li>A run-time check that tests a condition which, when false, reveals a bug in the software.</li> <li>A mechanism by which the program is halted (maybe after really minimal clean-up work).</li> </ul> <p>I'm not necessarily talking about C or C++.</p> <p>My own opinion is that if you're the programmer, but don't own the data (which is the case with most commercial desktop applications), you should keep them on, because a failing asssertion shows a bug, and you should not go on with a bug, with the risk of corrupting the user's data. This forces you to test strongly before you ship, and makes bugs more visible, thus easier to spot and fix.</p> <p>What's your opinion/experience?</p> <p>Cheers,</p> <p>Carl</p> <p>See related question <a href="https://stackoverflow.com/questions/419406/are-assertions-good">here</a></p> <hr> <p><strong>Responses and Updates</strong></p> <p>Hey Graham,</p> <blockquote> <p>An assertion is error, pure and simple and therefore should be handled like one. Since an error should be handled in release mode then you don't really need assertions.</p> </blockquote> <p>That's why I prefer the word "bug" when talking about assertions. It makes things much clearer. To me, the word "error" is too vague. A missing file is an error, not a bug, and the program should deal with it. Trying to dereference a null pointer is a bug, and the program should acknowledge that something smells like bad cheese.</p> <p>Hence, you should test the pointer with an assertion, but the presence of the file with normal error-handling code.</p> <hr> <p>Slight off-topic, but an important point in the discussion.</p> <p>As a heads-up, if your assertions break into the debugger when they fail, why not. But there are plenty of reasons a file could not exist that are completely outside of the control of your code: read/write rights, disk full, USB device unplugged, etc. Since you don't have control over it, I feel assertions are not the right way to deal with that.</p> <p>Carl</p> <hr> <p>Thomas,</p> <p>Yes, I have Code Complete, and must say I strongly disagree with that particular advice.</p> <p>Say your custom memory allocator screws up, and zeroes a chunk of memory that is still used by some other object. I happens to zero a pointer that this object dereferences regularly, and one of the invariants is that this pointer is never null, and you have a couple of assertions to make sure it stays that way. What do you do if the pointer suddenly is null. You just if() around it, hoping that it works?</p> <p>Remember, we're talking about product code here, so there's no breaking into the debugger and inspecting the local state. This is a real bug on the user's machine.</p> <p>Carl</p>
[ { "answer_id": 17754, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 0, "selected": false, "text": "file = create-some-file();\n_throwExceptionIf( file.exists() == false, \"FILE DOES NOT EXIST\");\n file = create-some-file();\nASSERT(file.exists());\n try catch" }, { "answer_id": 25998849, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 4, "selected": false, "text": "if( condition != expected ) throw exception" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
17,735
<p>When I first started using revision control systems like <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a> and <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow noreferrer">SVN</a>, I didn't really understand the concepts of the "trunk", branching, merging and tagging. I'm now starting to understand these concepts, and really get the importance and power behind them.</p> <p>So, I'm starting to do it properly. Or so I think... This is what I understand so far: The latest release/stable version of your code should sit in /trunk/ while beta versions or bleeding edge versions sit inside the /branches/ directory as different directories for each beta release, and then merged into the trunk when you release.</p> <p>Is this too simplistic a view on things? What repository layouts do you guys recommend? If it makes a difference, I'm using Subversion.</p>
[ { "answer_id": 17782, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 1, "selected": false, "text": "//MYPROJECT/MAIN/... - the top level folder for a complete build of all the product in main.\n//MYPROJECT/DEV/ArseKickingFeature/... - a branch from MAIN where developers work.\n//MYPROJECT/RELEASE/1.0/...\n//MYPROJECT/RELEASE/2.0/...\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1951/" ]
17,770
<p>What do the clever programmers here do to keep track of handy programming tricks and useful information they pick up over their many years of experience? Things like useful compiler arguments, IDE short-cuts, clever code snippets, etc.</p> <p>I sometimes find myself frustrated when looking up something that I used to know a year or two ago. My IE favorites probably represent a good chunk of the Internet in the late 1990s, so clearly that isn't effective (at least for me). Or am I just getting old?</p> <p>So.. what do you do? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17792, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 0, "selected": false, "text": "//print spool stop.notes.txt\nIf the printer spooler stops, start it again by \n- Services > Provision Networks > Restart Service\n\ntags: printer provision no printer spooler cannot print remote desktop\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
17,772
<p>This is probably best shown with an example. I have an enum with attributes:</p> <pre><code>public enum MyEnum { [CustomInfo("This is a custom attrib")] None = 0, [CustomInfo("This is another attrib")] ValueA, [CustomInfo("This has an extra flag", AllowSomething = true)] ValueB, } </code></pre> <p>I want to get to those attributes from an instance:</p> <pre><code>public CustomInfoAttribute GetInfo( MyEnum enumInput ) { Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum ) //here is the problem, GetField takes a string // the .ToString() on enums is very slow FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() ); //get the attribute from the field return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ). FirstOrDefault() //Linq method to get first or null as CustomInfoAttribute; //use as operator to convert } </code></pre> <p>As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it.</p> <p>Does anyone have a better way?</p>
[ { "answer_id": 17807, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 5, "selected": true, "text": "public delegate object FastPropertyGetHandler(object target); \n\nprivate static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)\n{\n if (type.IsValueType)\n {\n ilGenerator.Emit(OpCodes.Box, type);\n }\n}\n\npublic static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)\n{\n // generates a dynamic method to generate a FastPropertyGetHandler delegate\n DynamicMethod dynamicMethod =\n new DynamicMethod(\n string.Empty, \n typeof (object), \n new Type[] { typeof (object) },\n propInfo.DeclaringType.Module);\n\n ILGenerator ilGenerator = dynamicMethod.GetILGenerator();\n // loads the object into the stack\n ilGenerator.Emit(OpCodes.Ldarg_0);\n // calls the getter\n ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);\n // creates code for handling the return value\n EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);\n // returns the value to the caller\n ilGenerator.Emit(OpCodes.Ret);\n // converts the DynamicMethod to a FastPropertyGetHandler delegate\n // to get the property\n FastPropertyGetHandler getter =\n (FastPropertyGetHandler) \n dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));\n\n\n return getter;\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
17,781
<p>I am running a number of SSL-encrypted websites, and need to generate certificates to run on these. They are all internal applications, so I don't need to purchase a certificate, I can create my own.</p> <p>I have found it quite tedious to do everything using openssl all the time, and figure this is the kind of thing that has probably been done before and software exists for it.</p> <p>My preference is for linux-based systems, and I would prefer a command-line system rather than a GUI.</p> <p>Does anyone have some suggestions?</p>
[ { "answer_id": 31560, "author": "paan", "author_id": 2976, "author_profile": "https://Stackoverflow.com/users/2976", "pm_score": 3, "selected": false, "text": "CA" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
17,785
<p>I know this is not programming directly, but it's regarding a development workstation I'm setting up.</p> <p>I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x</p> <p>The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on <em>that</em> specific LAN.</p> <p>I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access?</p>
[ { "answer_id": 17809, "author": "kaa", "author_id": 2105, "author_profile": "https://Stackoverflow.com/users/2105", "pm_score": 3, "selected": true, "text": "route add 0.0.0.0 MASK 0.0.0.0 <address of gateway on 10.17.x.x net>\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
17,786
<p>When compiling my C++ .Net application I get 104 warnings of the type:</p> <pre><code>Warning C4341 - 'XX': signed value is out of range for enum constant </code></pre> <p>Where XX can be</p> <ul> <li>WCHAR</li> <li>LONG</li> <li>BIT</li> <li>BINARY</li> <li>GUID</li> <li>...</li> </ul> <p>I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings.</p> <p>Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings!</p>
[ { "answer_id": 17793, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 3, "selected": true, "text": "#pragma warning( push )\n#pragma warning( disable: 4341 )\n\n// code affected by bug\n\n#pragma warning( pop )\n" }, { "answer_id": 19081, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 0, "selected": false, "text": "#include" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
17,795
<p>I wanted to show the users Name Address (see <a href="http://www.ipchicken.com" rel="nofollow noreferrer">www.ipchicken.com</a>), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either:</p> <pre><code>IPAddress ip = IPAddress.Parse(this.lblIp.Text); string hostName = Dns.GetHostByAddress(ip).HostName; this.lblHost.Text = hostName; </code></pre> <p>But HostName is the same as the IP address.</p> <p>Who know's what I need to do?</p> <p>Thanks. Gab.</p>
[ { "answer_id": 17801, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 3, "selected": true, "text": " Dim sTmp As String\n Dim ip As IPHostEntry\n\n sTmp = MaskedTextBox1.Text\n Dim ipAddr As IPAddress = IPAddress.Parse(sTmp)\n ip = Dns.GetHostEntry(ipAddr)\n MaskedTextBox2.Text = ip.HostName\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104/" ]
17,806
<p>I am currently developing a .NET application, which consists of 20 projects. Some of those projects are compiled using .NET 3.5, some others are still .NET 2.0 projects (so far no problem).</p> <p>The problem is that if I include an external component I always get the following warning:</p> <blockquote> <p>Found conflicts between different versions of the same dependent assembly.</p> </blockquote> <p>What exactly does this warning mean and is there maybe a possibility to exclude this warning (like using #pragma disable in the source code files)?</p>
[ { "answer_id": 2137718, "author": "Brian Low", "author_id": 46039, "author_profile": "https://Stackoverflow.com/users/46039", "pm_score": 10, "selected": true, "text": "System.Windows.Forms System.Windows.Forms CopyLocal=true" }, { "answer_id": 13312274, "author": "Gorgsenegger", "author_id": 412036, "author_profile": "https://Stackoverflow.com/users/412036", "pm_score": 5, "selected": false, "text": "Solution A\n+--Project A\n +--Reference A (version 1.1.0.0)\n +--Reference B\n+--Project B\n +--Reference A (version 1.1.0.0)\n +--Reference B\n +--Reference C\n+--Project C\n +--Reference X (this indirectly references Reference A, but with e.g. version 1.1.1.0)\n\nSolution B\n+--Project A\n +--Reference A (version 1.1.1.0)\n" }, { "answer_id": 24724384, "author": "Phil50", "author_id": 2669005, "author_profile": "https://Stackoverflow.com/users/2669005", "pm_score": 3, "selected": false, "text": "<dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-6.0.0.0\" newVersion=\"6.0.0.0\" />\n</dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0-6.0.0.0\" newVersion=\"4.5.0.0\" />\n</dependentAssembly>\n" }, { "answer_id": 33633349, "author": "user1477388", "author_id": 1477388, "author_profile": "https://Stackoverflow.com/users/1477388", "pm_score": 5, "selected": false, "text": "3> There was a conflict between \"EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" and \"EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\".\n3> \"EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" was chosen because it was primary and \"EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" was not.\n" }, { "answer_id": 56570312, "author": "newprint", "author_id": 465292, "author_profile": "https://Stackoverflow.com/users/465292", "pm_score": 2, "selected": false, "text": "FastMember.dll Tools > Options > Build and Run > MSBuld Project build output verbosity: (set to) Diagnostics. There was a conflict between Output 1> There was a conflict between \"FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null\" and \"FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null\". (TaskId:19)\n1> \"FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null\" was chosen because it was primary and \"FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null\" was not. (TaskId:19)\n1> References which depend on \"FastMember, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null\" [C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\FastMember.1.5.0\\lib\\net461\\FastMember.dll]. (TaskId:19)\n1> C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\FastMember.1.5.0\\lib\\net461\\FastMember.dll (TaskId:19)\n1> Project file item includes which caused reference \"C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\FastMember.1.5.0\\lib\\net461\\FastMember.dll\". (TaskId:19)\n1> FastMember, Version=1.5.0.0, Culture=neutral, processorArchitecture=MSIL (TaskId:19)\n1> References which depend on \"FastMember, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null\" []. (TaskId:19)\n1> C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\ClosedXML.0.94.2\\lib\\net46\\ClosedXML.dll (TaskId:19)\n1> Project file item includes which caused reference \"C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\ClosedXML.0.94.2\\lib\\net46\\ClosedXML.dll\". (TaskId:19)\n1> ClosedXML, Version=0.94.2.0, Culture=neutral, processorArchitecture=MSIL (TaskId:19)\n Project file item includes which caused reference \"C:\\Users\\ksd3jvp\\Source\\Temp\\AITool\\Misra\\AMSAITool\\packages\\ClosedXML.0.94.2\\lib\\net46\\ClosedXML.dll\" ClosedXML.dll ClosedXML FastMember.dll 1.3.0.0 FastMember FastMember.dll 1.5.0.0 ClosedXML FastMember ClosedXML" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078/" ]
17,870
<p>Is there a way to select data where any one of multiple conditions occur on the same field?</p> <p>Example: I would typically write a statement such as:</p> <pre><code>select * from TABLE where field = 1 or field = 2 or field = 3 </code></pre> <p>Is there a way to instead say something like:</p> <pre><code>select * from TABLE where field = 1 || 2 || 3 </code></pre> <p>Any help is appreciated.</p>
[ { "answer_id": 17872, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 6, "selected": true, "text": "select foo from bar where baz in (1,2,3)\n" }, { "answer_id": 17873, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "select * from TABLE where field IN (1,2,3)\n select * from TABLE where field IN (SELECT boom FROM anotherTable)\n" }, { "answer_id": 17875, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "WHERE field IN (1, 2, 3)\n" }, { "answer_id": 17887, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 3, "selected": false, "text": "SELECT foo FROM bar WHERE baz BETWEEN 1 AND 3\n" }, { "answer_id": 17895, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 1, "selected": false, "text": "select *\nfrom table\nwhere field = '1' or field = '2' or field = '3'\n select * from table where field in ('1','2','3')\n" }, { "answer_id": 54392634, "author": "S.Witch", "author_id": 10905600, "author_profile": "https://Stackoverflow.com/users/10905600", "pm_score": 0, "selected": false, "text": "in or in and SELECT * FROM table\n WHERE column1='x' AND (column2='y' OR column2='z');\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2116/" ]
17,877
<p>Just looking for the first step basic solution here that keeps the honest people out.</p> <p>Thanks, Mike</p>
[ { "answer_id": 17872, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 6, "selected": true, "text": "select foo from bar where baz in (1,2,3)\n" }, { "answer_id": 17873, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "select * from TABLE where field IN (1,2,3)\n select * from TABLE where field IN (SELECT boom FROM anotherTable)\n" }, { "answer_id": 17875, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "WHERE field IN (1, 2, 3)\n" }, { "answer_id": 17887, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 3, "selected": false, "text": "SELECT foo FROM bar WHERE baz BETWEEN 1 AND 3\n" }, { "answer_id": 17895, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 1, "selected": false, "text": "select *\nfrom table\nwhere field = '1' or field = '2' or field = '3'\n select * from table where field in ('1','2','3')\n" }, { "answer_id": 54392634, "author": "S.Witch", "author_id": 10905600, "author_profile": "https://Stackoverflow.com/users/10905600", "pm_score": 0, "selected": false, "text": "in or in and SELECT * FROM table\n WHERE column1='x' AND (column2='y' OR column2='z');\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785/" ]
17,906
<p>I have a rather classic UI situation - two ListBoxes named <code>SelectedItems</code> and <code>AvailableItems</code> - the idea being that the items you have already selected live in <code>SelectedItems</code>, while the items that are available for adding to <code>SelectedItems</code> (i.e. every item that isn't already in there) live in <code>AvailableItems</code>.</p> <p>Also, I have the <code>&lt;</code> and <code>&gt;</code> buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).</p> <p>Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? <code>SelectedItems</code> is on the left side, so the <code>&lt;</code> button will move the selected <code>AvailableItems</code> to that list. However, if no items are selected (<code>AvailableItems.SelectedIndex == -1</code>), I want this button to be disabled (<code>IsEnabled == false</code>) - and the other way around for the other list/button.</p> <p>Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?</p>
[ { "answer_id": 18026, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<Button Name=\"btn1\" >click me \n <Button.Style> \n <Style> \n <Style.Triggers> \n <DataTrigger \n Binding =\"{Binding ElementName=list1, Path=SelectedIndex}\" \n Value=\"-1\"> \n <Setter Property=\"Button.IsEnabled\" Value=\"false\"/> \n </DataTrigger> \n </Style.Triggers> \n </Style> \n </Button.Style> \n</Button>\n" }, { "answer_id": 12476073, "author": "Karlas", "author_id": 777313, "author_profile": "https://Stackoverflow.com/users/777313", "pm_score": 6, "selected": false, "text": "<Button Name=\"button1\" IsEnabled=\"{Binding ElementName=listBox1, Path=SelectedItems.Count}\" />\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122/" ]
17,911
<p>I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a <code>URLLoader</code> to load a XML file, and upon <code>Event.COMPLETE</code> creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception:</p> <pre><code>TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "&lt;/link&gt;". </code></pre> <p>We think the problem is that The XML is large, and perhaps the <code>Event.COMPLETE</code> event is fired before the XML is actually downloaded from the <code>URLLoader</code>. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this.</p> <p>Is there any surefire way to parse XML within Flash?</p> <p><strong>Update Sept 2 2008</strong> We have concluded the following, the excption is fired in the code at this point:</p> <pre><code>data = new XML(mainXMLLoader.data); // calculate the total number of entries. for each (var i in data.channel.item){ _totalEntries++; } </code></pre> <p>I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the <code>bytesLoaded == bytesTotal</code>?</p> <hr> <p>I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an <code>XML</code> object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)?</p> <hr> <p>@Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing <code>mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded</code></p>
[ { "answer_id": 17963, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 1, "selected": false, "text": "URLLoader.bytesLoaded == URLLoader.bytesTotal\n" }, { "answer_id": 18365, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "URLLoader.bytesLoaded URLLoader.bytesTotal Event.COMPLETE bytesLoaded bytesTotal Event.COMPLETE" }, { "answer_id": 20037, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "bytesTotal data Event.COMPLETE </link>" }, { "answer_id": 20639, "author": "Jeff Winkworth", "author_id": 1306, "author_profile": "https://Stackoverflow.com/users/1306", "pm_score": 0, "selected": false, "text": "public class BlogReader extends MovieClip {\n public static const DOWNLOAD_ERROR:String = \"Download_Error\";\n public static const FEED_PARSED:String = \"Feed_Parsed\";\n\n private var mainXMLLoader:URLLoader = new URLLoader();\n public var data:XML;\n private var _totalEntries:Number = 0;\n\n public function BlogReader(url:String){\n mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n mainXMLLoader.load(new URLRequest(url));\n XML.ignoreWhitespace;\n }\n private function errorCatch(e:IOErrorEvent){\n trace(\"Oh noes! Yous gots no internets!\");\n dispatchEvent(new Event(DOWNLOAD_ERROR));\n }\n private function LoadList(e:Event):void {\n data = new XML(e.target.data);\n\n // calculate the total number of entries.\n for each (var i in data.channel.item){\n _totalEntries++;\n }\n\n dispatchEvent(new Event(FEED_PARSED));\n }\n}\n public class BlogReader extends MovieClip {\n public static const DOWNLOAD_ERROR:String = \"Download_Error\";\n public static const FEED_PARSED:String = \"Feed_Parsed\";\n\n private var mainXMLLoader:URLLoader = new URLLoader();\n public var data:XML;\n protected var _totalEntries:Number = 0;\n\n public function BlogReader(url:String){\n mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n mainXMLLoader.load(new URLRequest(url));\n XML.ignoreWhitespace;\n }\n private function errorCatch(e:IOErrorEvent){\n trace(\"Oh noes! Yous gots no internets!\");\n dispatchEvent(e);\n }\n private function LoadList(e:Event):void {\n isDownloadComplete(); \n }\n private function isDownloadComplete() {\n trace (mainXMLLoader.bytesLoaded + \"/\" + mainXMLLoader.bytesLoaded);\n if (mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded){\n trace (\"xml fully loaded\");\n\n data = new XML(mainXMLLoader.data);\n\n // calculate the total number of entries.\n for each (var i in data.channel.item){\n _totalEntries++;\n }\n\n dispatchEvent(new Event(FEED_PARSED));\n } else {\n trace (\"xml not fully loaded, starting timer\");\n var t:Timer = new Timer(300, 1);\n t.addEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n t.start();\n }\n }\n private function loaded(e:TimerEvent){\n trace (\"timer finished, trying again\");\n e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n e.target.stop();\n\n isDownloadComplete();\n }\n}\n mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded" }, { "answer_id": 21928, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "XML.ignoreWhitespace;\n ignoreWhitespace true XML.ingoreWhitespace = true;\n" }, { "answer_id": 21929, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "Event.COMPLETE bytesLoaded bytesTotal Event.COMPLETE bytesLoaded == bytesTotal" }, { "answer_id": 132117, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 0, "selected": false, "text": "//The XML\n//Flash ignores the line that specifies the XML version and encoding so I have here as well.\n\n<parent>\n <child name=\"child1\" />\n <child name=\"child2\" />\n <child name=\"child3\" />\n <child name=\"child4\" />\n <documentEnd value=\"true\" />\n</parent>\n\n//Sorry about the spacing, but it is difficult to get XML to show.\n\n//Flash\nvar loader:URLLoader = new URLLoader();\nvar request:URLRequest = new URLRequest('pathToXML/xmlFileName.xml');\n\nvar xml:XML;\n\n//Event Listener with weak reference set to true (5th parameter);\n//The above comment does not define a required practice, this is to aid with garbage collection.\n\nloader.addEventListener(Event.COMPLETE, onXMLLoadComplete, false, 0, true);\nloader.load(request);\nfunction onXMLLoadComplete(e:Event):void\n{\n xml = new XML(e.target.data);\n\n //Now we check the last element (child) to see if it is documentEnd.\n if(xml[xml.length()-1].documentEnd.@value == \"true\")\n {\n trace(\"Woot, it seems your xml made it!\");\n }\n else\n {\n //Attempt the load again because it seems it failed when it was unable to find documentEnd in the XML Object.\n loader.load(request);\n }\n}\n" }, { "answer_id": 1287231, "author": "enzuguri", "author_id": 61466, "author_profile": "https://Stackoverflow.com/users/61466", "pm_score": 0, "selected": false, "text": "xml = new XML(event.target.data);\n\n//the data should already be XML, so only casting is necessary\nxml = XML(event.target.data);\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1306/" ]
17,928
<p>I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. </p>
[ { "answer_id": 19021, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "Alt+F11 Tools References Browse... Insert UserForm Toolbox Additional Controls Run" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781/" ]
17,944
<p>I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.</p> <p>If I have <em>x</em> items which I want to display in chunks of <em>y</em> per page, how many pages will be needed?</p>
[ { "answer_id": 17954, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 6, "selected": false, "text": "int x = number_of_items;\nint y = items_per_page;\n\n// with out library\nint pages = x/y + (x % y > 0 ? 1 : 0)\n\n// with library\nint pages = (int)Math.Ceiling((double)x / (double)y);\n" }, { "answer_id": 17957, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 7, "selected": false, "text": "int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);\n" }, { "answer_id": 17974, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 10, "selected": true, "text": "int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n" }, { "answer_id": 96921, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 4, "selected": false, "text": "int long int pageCount = (-1L + records + recordsPerPage) / recordsPerPage; records long" }, { "answer_id": 503201, "author": "rjmunro", "author_id": 3408, "author_profile": "https://Stackoverflow.com/users/3408", "pm_score": 8, "selected": false, "text": "int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n int pageCount = (records - 1) / recordsPerPage + 1;\n int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');\n int recordsPerPage = config.fetch_value('records per page')\nint pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n int pageCount = (records - 1) / config.fetch_value('records per page') + 1;\n" }, { "answer_id": 536219, "author": "Mike", "author_id": 65004, "author_profile": "https://Stackoverflow.com/users/65004", "pm_score": 2, "selected": false, "text": "int pageCount = 0;\nif (records > 0)\n{\n pageCount = (((records - 1) / recordsPerPage) + 1);\n}\n// no else required\n" }, { "answer_id": 3473687, "author": "flux", "author_id": 228406, "author_profile": "https://Stackoverflow.com/users/228406", "pm_score": 0, "selected": false, "text": "int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);\n" }, { "answer_id": 4043686, "author": "Jeremy Hadfied", "author_id": 490178, "author_profile": "https://Stackoverflow.com/users/490178", "pm_score": -1, "selected": false, "text": "public static Object[][] chunk(Object[] src, int chunkSize) {\n\n int overflow = src.length%chunkSize;\n int numChunks = (src.length/chunkSize) + (overflow>0?1:0);\n Object[][] dest = new Object[numChunks][]; \n for (int i=0; i<numChunks; i++) {\n dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];\n System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); \n }\n return dest;\n}\n" }, { "answer_id": 5883806, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 3, "selected": false, "text": "int q = records / recordsPerPage, r = records % recordsPerPage;\nint pageCount = q - (-r >> (Integer.SIZE - 1));\n (-r >> (Integer.SIZE - 1)) r >> r r q records % recordsPerPage > 0" }, { "answer_id": 9771364, "author": "Richard Parsons", "author_id": 1278685, "author_profile": "https://Stackoverflow.com/users/1278685", "pm_score": -1, "selected": false, "text": "int hrs = 0; int mins = 0;\n\nfloat tm = totalmins;\n\nif ( tm > 60 ) ( hrs = (int) (tm / 60);\n\nmins = (int) (tm - (hrs * 60));\n\nSystem.out.println(\"Total time in Hours & Minutes = \" + hrs + \":\" + mins);\n" }, { "answer_id": 14754238, "author": "Jim Watson", "author_id": 2051259, "author_profile": "https://Stackoverflow.com/users/2051259", "pm_score": -1, "selected": false, "text": "uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )\n{\n // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)\n return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;\n}\n" }, { "answer_id": 21548669, "author": "Sam Jones", "author_id": 1428089, "author_profile": "https://Stackoverflow.com/users/1428089", "pm_score": 2, "selected": false, "text": "var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;\n public static bool IsDivisble(this int x, int n)\n{\n return (x%n) == 0;\n}\n var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;\n" }, { "answer_id": 39519292, "author": "Nicholas Petersen", "author_id": 264031, "author_profile": "https://Stackoverflow.com/users/264031", "pm_score": 3, "selected": false, "text": " public static int DivideUp(this int dividend, int divisor)\n {\n return (dividend + (divisor - 1)) / divisor;\n }\n DivideByZero int remainder; \n int result = Math.DivRem(dividend, divisor, out remainder);\n" }, { "answer_id": 63012251, "author": "SendETHToThisAddress", "author_id": 5835002, "author_profile": "https://Stackoverflow.com/users/5835002", "pm_score": 3, "selected": false, "text": "int result = (int1 / int2);\nif (int1 % int2 != 0) { result++; }\n int result = (int)Math.Ceiling((double)int1 / (double)int2);\n" }, { "answer_id": 69479389, "author": "H.M.Mubashir", "author_id": 16925201, "author_profile": "https://Stackoverflow.com/users/16925201", "pm_score": 2, "selected": false, "text": "(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));\n" }, { "answer_id": 74147725, "author": "Jin-K", "author_id": 7210166, "author_profile": "https://Stackoverflow.com/users/7210166", "pm_score": 0, "selected": false, "text": "public static int RoundedUpDivisionBy(this int @this, int divider)\n{ \n var result = @this / divider;\n if (@this % divider is 0) return result;\n return result + Math.Sign(@this * divider);\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2084/" ]
17,947
<p>I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is:</p> <pre><code>System.AccessViolationException was unhandled Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: </code></pre> <p><em>UPDATE:</em><br> Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now.</p>
[ { "answer_id": 17985, "author": "Adam Lerman", "author_id": 673, "author_profile": "https://Stackoverflow.com/users/673", "pm_score": 0, "selected": false, "text": "{IntPtr DispatchMessageW(MSG ByRef)}" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
17,960
<p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
[ { "answer_id": 5625350, "author": "millerjs", "author_id": 312103, "author_profile": "https://Stackoverflow.com/users/312103", "pm_score": 6, "selected": true, "text": "[appdomain]::CurrentDomain.SetData(\"APP_CONFIG_FILE\", $configpath)\nAdd-Type -AssemblyName System.Configuration\n" }, { "answer_id": 28241616, "author": "yzorg", "author_id": 195755, "author_profile": "https://Stackoverflow.com/users/195755", "pm_score": 2, "selected": false, "text": "$global:MyComponent_MySetting = '12'\n# i.e. \n$PSDefaultParameterValues\n$ErrorActionPreference\n $env:PATH\n$env:PSModulePath\n .AddEnvironmentVariables() <appSettings> PATH" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
17,965
<p>I have a process in Linux that's getting a segmentation fault. How can I tell it to generate a core dump when it fails?</p>
[ { "answer_id": 17994, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 9, "selected": true, "text": "ulimit -c unlimited\n limit coredumpsize unlimited\n" }, { "answer_id": 18400, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 5, "selected": false, "text": "generate-core-file" }, { "answer_id": 2139719, "author": "t0mm13b", "author_id": 206367, "author_profile": "https://Stackoverflow.com/users/206367", "pm_score": 4, "selected": false, "text": "AIX sprintf gdb #include <stdio.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <stdarg.h>\n\nstatic void signal_handler(int);\nstatic void dumpstack(void);\nstatic void cleanup(void);\nvoid init_signals(void);\nvoid panic(const char *, ...);\n\nstruct sigaction sigact;\nchar *progname;\n\nint main(int argc, char **argv) {\n char *s;\n progname = *(argv);\n atexit(cleanup);\n init_signals();\n printf(\"About to seg fault by assigning zero to *s\\n\");\n *s = 0;\n sigemptyset(&sigact.sa_mask);\n return 0;\n}\n\nvoid init_signals(void) {\n sigact.sa_handler = signal_handler;\n sigemptyset(&sigact.sa_mask);\n sigact.sa_flags = 0;\n sigaction(SIGINT, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGSEGV);\n sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGBUS);\n sigaction(SIGBUS, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGQUIT);\n sigaction(SIGQUIT, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGHUP);\n sigaction(SIGHUP, &sigact, (struct sigaction *)NULL);\n\n sigaddset(&sigact.sa_mask, SIGKILL);\n sigaction(SIGKILL, &sigact, (struct sigaction *)NULL);\n}\n\nstatic void signal_handler(int sig) {\n if (sig == SIGHUP) panic(\"FATAL: Program hanged up\\n\");\n if (sig == SIGSEGV || sig == SIGBUS){\n dumpstack();\n panic(\"FATAL: %s Fault. Logged StackTrace\\n\", (sig == SIGSEGV) ? \"Segmentation\" : ((sig == SIGBUS) ? \"Bus\" : \"Unknown\"));\n }\n if (sig == SIGQUIT) panic(\"QUIT signal ended program\\n\");\n if (sig == SIGKILL) panic(\"KILL signal ended program\\n\");\n if (sig == SIGINT) ;\n}\n\nvoid panic(const char *fmt, ...) {\n char buf[50];\n va_list argptr;\n va_start(argptr, fmt);\n vsprintf(buf, fmt, argptr);\n va_end(argptr);\n fprintf(stderr, buf);\n exit(-1);\n}\n\nstatic void dumpstack(void) {\n /* Got this routine from http://www.whitefang.com/unix/faq_toc.html\n ** Section 6.5. Modified to redirect to file to prevent clutter\n */\n /* This needs to be changed... */\n char dbx[160];\n\n sprintf(dbx, \"echo 'where\\ndetach' | dbx -a %d > %s.dump\", getpid(), progname);\n /* Change the dbx to gdb */\n\n system(dbx);\n return;\n}\n\nvoid cleanup(void) {\n sigemptyset(&sigact.sa_mask);\n /* Do any cleaning up chores here */\n}\n" }, { "answer_id": 9191175, "author": "mlutescu", "author_id": 1196859, "author_profile": "https://Stackoverflow.com/users/1196859", "pm_score": 4, "selected": false, "text": "/proc/sys/kernel/core_pattern /proc/sys/fs/suid_dumpable man core" }, { "answer_id": 12968632, "author": "Edgar Jordi", "author_id": 1758419, "author_profile": "https://Stackoverflow.com/users/1758419", "pm_score": 3, "selected": false, "text": "/etc/profile # ulimit -S -c 0 > /dev/null 2>&1\n /etc/security/limits.conf * soft core 0\n limit coredumpsize unlimited limit # limit coredumpsize unlimited\n# limit\ncputime unlimited\nfilesize unlimited\ndatasize unlimited\nstacksize 10240 kbytes\ncoredumpsize unlimited\nmemoryuse unlimited\nvmemoryuse unlimited\ndescriptors 1024\nmemorylocked 32 kbytes\nmaxproc 528383\n#\n kill -s SEGV <PID> # kill -s SEGV <PID>\n" }, { "answer_id": 14709836, "author": "George Co", "author_id": 893982, "author_profile": "https://Stackoverflow.com/users/893982", "pm_score": 6, "selected": false, "text": "gcore <pid>\n kill -ABRT <pid>\n" }, { "answer_id": 32461658, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 5, "selected": false, "text": "sysctl kernel.core_pattern\n cat /proc/sys/kernel/core_pattern\n %e %t /etc/sysctl.conf sysctl -p sleep 10 & killall -SIGSEGV sleep ulimit -a ulimit -c unlimited\n /var/crash/" }, { "answer_id": 35747215, "author": "mrgloom", "author_id": 1179925, "author_profile": "https://Stackoverflow.com/users/1179925", "pm_score": 4, "selected": false, "text": "ulimit -a\n core file size (blocks, -c) unlimited\n gedit ~/.bashrc ulimit -c unlimited -O0 -g ./application_name\n gdb application_name core\n" }, { "answer_id": 52000790, "author": "kgbook", "author_id": 5393174, "author_profile": "https://Stackoverflow.com/users/5393174", "pm_score": 2, "selected": false, "text": "setrlimit #include <sys/resource.h>\n\nbool enable_core_dump(){ \n struct rlimit corelim;\n\n corelim.rlim_cur = RLIM_INFINITY;\n corelim.rlim_max = RLIM_INFINITY;\n\n return (0 == setrlimit(RLIMIT_CORE, &corelim));\n}\n" }, { "answer_id": 54275787, "author": "Pawel Veselov", "author_id": 622266, "author_profile": "https://Stackoverflow.com/users/622266", "pm_score": 2, "selected": false, "text": "core_pattern systemd-coredump(8) coredumpctl(1) coredump.conf(5) [vps@phoenix]~$ coredumpctl list test_me | tail -1\nSun 2019-01-20 11:17:33 CET 16163 1224 1224 11 present /home/vps/test_me\n [vps@phoenix]~$ coredumpctl -o test_me.core dump 16163\n" }, { "answer_id": 58593462, "author": "DarkTrick", "author_id": 6702598, "author_profile": "https://Stackoverflow.com/users/6702598", "pm_score": 3, "selected": false, "text": "~/.config/apport/settings [main]\nunpackaged=true\n ulimit -c ulimit -c unlimited\n sudo systemctl restart apport\n /var/crash/ apport-unpack <location_of_report> <target_directory>\n core_pattern ulimit -c" }, { "answer_id": 70872068, "author": "theicfire", "author_id": 1394731, "author_profile": "https://Stackoverflow.com/users/1394731", "pm_score": 2, "selected": false, "text": "ulimit -c unlimited\n echo '* soft core unlimited' >> /etc/security/limits.conf\n sudo systemctl status apport.service\n /var/lib/apport/coredump \n/var/crash\n sysctl -w kernel.core_pattern=/coredumps/core-%e-%s-%u-%g-%p-%t\nmkdir /coredumps\n chmod 777 /coredumps\n > crash.c\ngcc -Wl,--defsym=main=0 crash.c\n./a.out\n==output== Segmentation fault (core dumped)\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084/" ]
17,980
<p>I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using <code>printf</code>?. For example:</p> <pre><code>double radius = 1.0; double area = 0.0; area = calculateArea( radius ); printf( "%10.1f %10.2\n", radius, area ); </code></pre> <p>I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with <code>10.1f</code> and <code>10.2f</code>? Could someone please explain this?</p>
[ { "answer_id": 17987, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "man 3 printf\n" }, { "answer_id": 17989, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 5, "selected": true, "text": "printf( \"%10.1f %10.2\\n\", radius, area );\n" }, { "answer_id": 17995, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 1, "selected": false, "text": "printf radius 10.1" }, { "answer_id": 17999, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 0, "selected": false, "text": "printf( \"%10.2f\", 1.5 )\n 1.50\n printf(\"%.2f\", 1.5 )\n 1.50\n printf(\"%10.1f\", 1.5 )\n 1.5\n" }, { "answer_id": 18004, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "%d - integer\n%x - hex integer\n%s - string\n%c - char (only one)\n%f - floating point (float)\n%d - signed int (decimal)\n%i - signed int (integer) (same as decimal).\n%u - unsigned int\n%ld - long (signed) int\n%lu - long unsigned int\n%lld - long long (signed) int\n%llu - long long unsigned int\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
17,984
<p>Alright, this might be a bit of a long shot, but I have having problems getting AnkhSVN to connect from Visual Studio 2005 to an external SVN server. There is a network proxy in the way, but I can't seem to find a way in AnkhSVN to configure the proxy and doesn't seem to be detecting the Internet Explorer proxy configuration. Is there any way to resolve this issue, or will it likely just not work?</p>
[ { "answer_id": 17987, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "man 3 printf\n" }, { "answer_id": 17989, "author": "robintw", "author_id": 1912, "author_profile": "https://Stackoverflow.com/users/1912", "pm_score": 5, "selected": true, "text": "printf( \"%10.1f %10.2\\n\", radius, area );\n" }, { "answer_id": 17995, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 1, "selected": false, "text": "printf radius 10.1" }, { "answer_id": 17999, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 0, "selected": false, "text": "printf( \"%10.2f\", 1.5 )\n 1.50\n printf(\"%.2f\", 1.5 )\n 1.50\n printf(\"%10.1f\", 1.5 )\n 1.5\n" }, { "answer_id": 18004, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 2, "selected": false, "text": "%d - integer\n%x - hex integer\n%s - string\n%c - char (only one)\n%f - floating point (float)\n%d - signed int (decimal)\n%i - signed int (integer) (same as decimal).\n%u - unsigned int\n%ld - long (signed) int\n%lu - long unsigned int\n%lld - long long (signed) int\n%llu - long long unsigned int\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/17984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
18,006
<p>I've been asked to write a Windows service in C# to periodically monitor an email inbox and insert the details of any messages received into a database table.</p> <p>My instinct is to do this via POP3 and sure enough, Googling for ".NET POP3 component" produces countless (ok, 146,000) results.</p> <p>Has anybody done anything similar before and can you recommend a decent component that won't break the bank (a few hundred dollars maximum)?</p> <p>Would there be any benefits to using IMAP rather than POP3?</p>
[ { "answer_id": 2383070, "author": "Martin Vobr", "author_id": 16132, "author_profile": "https://Stackoverflow.com/users/16132", "pm_score": 2, "selected": false, "text": "POP3 POP3 IMAP Imap Rebex.Net.Imap // create client, connect and log in \nImap client = new Imap();\nclient.Connect(\"imap.example.org\");\nclient.Login(\"username\", \"password\");\n\n// select folder \nclient.SelectFolder(\"Inbox\");\n\n// get message list - envelope headers \nImapMessageCollection messages = client.Search\n (\n ImapSearchParameter.HasFlagsNoneOf(ImapMessageFlags.Seen)\n ); \n\n// display info about each message \nConsole.WriteLine(\"UID | From | To | Subject\");\nforeach (ImapMessageInfo message in messages)\n{\n Console.WriteLine(\n \"{0} | {1} | {2} | {3}\",\n message.UniqueId,\n message.From,\n message.To,\n message.Subject);\n}\n\n// disconnect \nclient.Disconnect();\n ImapMessageCollection messages = client.Search\n (\n ImapSearchParameter.Arrived(DateTime.Now.AddYears(-1), DateTime.Now),\n ImapSearchParameter.Size(1024 * 100, Int32.MaxValue)\n ); \n" }, { "answer_id": 4427982, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 3, "selected": false, "text": "using(Imap imap = new Imap())\n{\n imap.Connect(\"imap.server.com\"); // or ConnectSSL for SSL\n imap.Login(\"user\", \"password\");\n\n imap.SelectInbox();\n List<long> uids = imap.Search(Flag.Unseen);\n foreach (long uid in uids)\n {\n IMail mail = new MailBuilder()\n .CreateFromEml(imap.GetMessageByUID(uid));\n Console.WriteLine(mail.Subject);\n }\n imap.Close();\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2084/" ]
18,010
<p>I asked a couple of coworkers about <a href="http://ankhsvn.open.collab.net" rel="nofollow noreferrer">AnkhSVN</a> and neither one of them was happy with it. One of them went as far as saying that AnkhSVN has messed up his devenv several times.</p> <p>What's your experience with AnkhSVN? I really miss having an IDE integrated source control tool.</p>
[ { "answer_id": 58518, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 0, "selected": false, "text": "originalFile deleted\nnewFile added (+)\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
18,034
<p>How do I create a self signed SSL certificate for an Apache Server to use while testing a web app?</p>
[ { "answer_id": 18062, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 6, "selected": true, "text": "openssl req -new -x509 -nodes -out server.crt -keyout server.key\n SSLCertificateFile /path/to/this/server.crt\nSSLCertificateKeyFile /path/to/this/server.key\n openssl rsa -des3 -in server.key -out server.key.new\nmv server.key.new server.key\n" }, { "answer_id": 57600107, "author": "Francisco Luz", "author_id": 859837, "author_profile": "https://Stackoverflow.com/users/859837", "pm_score": 0, "selected": false, "text": "[ req ]\nprompt = no \ndefault_bits = 2048 \ndefault_keyfile = MYDOMAIN.pem \ndistinguished_name = subject \nreq_extensions = req_ext \nx509_extensions = x509_ext \nstring_mask = utf8only\n\n# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).\n# Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.\n[ subject ]\ncountryName = KE \nstateOrProvinceName = Nairobi \nlocalityName = Nairobi\norganizationName = Localhost\n\n\n# Use a friendly name here because its presented to the user. The server's DNS\n# names are placed in Subject Alternate Names. Plus, DNS names here is deprecated\n# by both IETF and CA/Browser Forums. If you place a DNS name here, then you \n# must include the DNS name in the SAN too (otherwise, Chrome and others that\n# strictly follow the CA/Browser Baseline Requirements will fail).\ncommonName = Localhost dev cert \nemailAddress [email protected]\n\n# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...\n[ x509_ext ]\n\nsubjectKeyIdentifier = hash \nauthorityKeyIdentifier = keyid,issuer\n\n# You only need digitalSignature below. *If* you don't allow\n# RSA Key transport (i.e., you use ephemeral cipher suites), then\n# omit keyEncipherment because that's key transport.\nbasicConstraints = CA:FALSE \nkeyUsage = digitalSignature, keyEncipherment \nsubjectAltName = @alternate_names \nnsComment = \"OpenSSL Generated Certificate\"\n\n# RFC 5280, Section 4.2.1.12 makes EKU optional\n# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused\n# In either case, you probably only need serverAuth.\n# extendedKeyUsage = serverAuth, clientAuth\n\n# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...\n[ req_ext ]\n\nsubjectKeyIdentifier = hash\n\nbasicConstraints = CA:FALSE \nkeyUsage = digitalSignature, keyEncipherment \nsubjectAltName = @alternate_names \nnsComment = \"OpenSSL Generated Certificate\"\n\n# RFC 5280, Section 4.2.1.12 makes EKU optional\n# CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused\n# In either case, you probably only need serverAuth.\n# extendedKeyUsage = serverAuth, clientAuth\n\n[ alternate_names ]\n\nDNS.1 = MYDOMAIN\n\n# Add these if you need them. But usually you don't want them or\n# need them in production. You may need them for development.\n# DNS.5 = localhost\n# DNS.6 = localhost.localdomain\nDNS.7 = 127.0.0.1\n\n# IPv6 localhost\n# DNS.8 = ::1\n $ sudo openssl req -config MYDOMAIN.conf -new -x509 -sha256 -newkey rsa:2048 -nodes -keyout MYDOMAIN.key -days 1024 -out MYDOMAIN.crt\n$ sudo openssl pkcs12 -export -out MYDOMAIN.pfx -inkey MYDOMAIN.key -in MYDOMAIN.crt\n$ sudo chown -R $USER *\n # Install the cert utils\n$ sudo apt-get install libnss3-tools\n\n# Trust the certificate for SSL\n$ pk12util -d sql:$HOME/.pki/nssdb -i MYDOMAIN.pfx\n\n# Trust self-signed server certificate\n$ certutil -d sql:$HOME/.pki/nssdb -A -t \"P,,\" -n 'dev cert' -i MYDOMAIN.crt\n /etc/apache2/sites-available/default-ssl.conf SSLCertificateFile /path/to/MYDOMAIN.crt\nSSLCertificateKeyFile /path/to/MYDOMAIN.key\n # If you are not using the default configuration ( /etc/apache2/sites-available/default-ssl.conf ),\n# then replace \"default-ssl\" for whatever conf file name you've chosen\n# ( DO NOT include the .conf bit ).\n$ sudo a2ensite default-ssl\n\n$ sudo service apache2 restart\n /usr/share/doc/apache2/README.Debian.gz" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
18,059
<p>I'm using the <code>System.Windows.Forms.WebBrowser</code>, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); } </code></pre> <p>The code above will cancel navigation and swallow the exception.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } </code></pre> <p>So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.</p> <p>Is there any way to tell the <code>WebBrowser</code> control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?</p>
[ { "answer_id": 18138, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "browser.ScriptErrorsSuppressed" }, { "answer_id": 63057905, "author": "eanv", "author_id": 13983631, "author_profile": "https://Stackoverflow.com/users/13983631", "pm_score": 0, "selected": false, "text": "webBrowserNavigating MessageBox.Show(exception.ToString()); Dispatcher.BeginInvoke(() => { throw exception; }); webBrowserNavigating" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42/" ]
18,077
<p>I wanted some of those spiffy rounded corners for a web project that I'm currently working on.</p> <p>I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.</p> <p>I already utilize jQuery so I looked at the excellent <a href="http://plugins.jquery.com/project/corners" rel="nofollow noreferrer">rounded corners plugin</a> and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.</p> <p>I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific <code>-moz-border-radius-*</code> properties and if so utilize them.</p> <p>The check for webkit support looks like this:</p> <pre><code>var webkitAvailable = false; try { webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined); } catch(err) {} </code></pre> <p>That, however, did not work for <code>-moz-border-radius</code> so I started checking for alternatives.</p> <p>My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.</p> <p>My best solution yet is as follows.</p> <pre><code>var mozborderAvailable = false; try { var o = jQuery('&lt;div&gt;').css('-moz-border-radius', '1px'); mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px'; o = null; } catch(err) {} </code></pre> <p>It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties</p> <ul> <li><code>-moz-border-radius-topleft</code></li> <li><code>-moz-border-radius-topright</code></li> <li><code>-moz-border-radius-bottomleft</code></li> <li><code>-moz-border-radius-bottomright</code></li> </ul> <p>Is there any javascript/CSS guru out there that have a better solution?</p> <p>(The feature request for this page is at <a href="http://plugins.jquery.com/node/3619" rel="nofollow noreferrer">http://plugins.jquery.com/node/3619</a>)</p>
[ { "answer_id": 19080, "author": "M. Dave Auayan", "author_id": 2007, "author_profile": "https://Stackoverflow.com/users/2007", "pm_score": 2, "selected": false, "text": "-moz-border-radius -webkit-border-radius" }, { "answer_id": 19203, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 1, "selected": false, "text": "element.style.MozBorderRadius" }, { "answer_id": 19329, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 5, "selected": true, "text": "var mozborderAvailable = false;\ntry {\n if (typeof(document.body.style.MozBorderRadius) !== \"undefined\") {\n mozborderAvailable = true;\n }\n} catch(err) {}\n" }, { "answer_id": 1996390, "author": "Cybolic", "author_id": 242846, "author_profile": "https://Stackoverflow.com/users/242846", "pm_score": 1, "selected": false, "text": "function checkBorders() {\n var div = document.createElement('div');\n div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');\n for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {\n if ( /border.*?-radius/i.test(div.style[stylenr]) ) {\n return true;\n };\n return false;\n};\n if ( /Gecko\\/\\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\\/\\d*/)[0].split('/')[1]) > 20070501 )\n function checkBorders() {\n if ( /Gecko\\/\\d*/.test(navigator.userAgent) && parseInt(navigator.userAgent.match(/Gecko\\/\\d*/)[0].split('/')[1]) > 20070501 ) {\n return true;\n } else {\n var div = document.createElement('div');\n div.setAttribute('style', '-moz-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px;');\n for ( stylenr=0; stylenr<div.style.length; stylenr++ ) {\n if ( /border.*?-radius/i.test(div.style[stylenr]) ) {\n return true;\n };\n return false;\n };\n};\n" }, { "answer_id": 3458857, "author": "vernonk", "author_id": 223910, "author_profile": "https://Stackoverflow.com/users/223910", "pm_score": 2, "selected": false, "text": "jQuery(function() {\njQuery.support.borderRadius = false;\njQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {\n if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;\n return (!jQuery.support.borderRadius);\n}); });\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
18,082
<p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p> <p>Bonus points for:</p> <ol> <li>Clarity. Solution should be clean and simple.</li> <li>Cross-platform.</li> </ol> <p>Test cases:</p> <pre><code>01. IsNumeric('-1') =&gt; true 02. IsNumeric('-1.5') =&gt; true 03. IsNumeric('0') =&gt; true 04. IsNumeric('0.42') =&gt; true 05. IsNumeric('.42') =&gt; true 06. IsNumeric('99,999') =&gt; false 07. IsNumeric('0x89f') =&gt; false 08. IsNumeric('#abcdef') =&gt; false 09. IsNumeric('1.2.3') =&gt; false 10. IsNumeric('') =&gt; false 11. IsNumeric('blah') =&gt; false </code></pre>
[ { "answer_id": 18085, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 6, "selected": false, "text": "function IsNumeric(input){\n var RE = /^-{0,1}\\d*\\.{0,1}\\d+$/;\n return (RE.test(input));\n}\n const IsNumeric = (num) => /^-{0,1}\\d*\\.{0,1}\\d+$/.test(num);\n const IsNumeric = (num) => /^-{0,1}\\d*\\.{0,1}\\d+$/.test(num);\n \n function TestIsNumeric(){\n var results = ''\n results += (IsNumeric('-1')?\"Pass\":\"Fail\") + \": IsNumeric('-1') => true\\n\";\n results += (IsNumeric('-1.5')?\"Pass\":\"Fail\") + \": IsNumeric('-1.5') => true\\n\";\n results += (IsNumeric('0')?\"Pass\":\"Fail\") + \": IsNumeric('0') => true\\n\";\n results += (IsNumeric('0.42')?\"Pass\":\"Fail\") + \": IsNumeric('0.42') => true\\n\";\n results += (IsNumeric('.42')?\"Pass\":\"Fail\") + \": IsNumeric('.42') => true\\n\";\n results += (!IsNumeric('99,999')?\"Pass\":\"Fail\") + \": IsNumeric('99,999') => false\\n\";\n results += (!IsNumeric('0x89f')?\"Pass\":\"Fail\") + \": IsNumeric('0x89f') => false\\n\";\n results += (!IsNumeric('#abcdef')?\"Pass\":\"Fail\") + \": IsNumeric('#abcdef') => false\\n\";\n results += (!IsNumeric('1.2.3')?\"Pass\":\"Fail\") + \": IsNumeric('1.2.3') => false\\n\";\n results += (!IsNumeric('')?\"Pass\":\"Fail\") + \": IsNumeric('') => false\\n\";\n results += (!IsNumeric('blah')?\"Pass\":\"Fail\") + \": IsNumeric('blah') => false\\n\";\n \n return results;\n }\n\nconsole.log(TestIsNumeric()); .as-console-wrapper { max-height: 100% !important; top: 0; } /^ match beginning of string\n-{0,1} optional negative sign\n\\d* optional digits\n\\.{0,1} optional decimal point\n\\d+ at least one digit\n$/ match end of string\n" }, { "answer_id": 18148, "author": "pottedmeat", "author_id": 2120, "author_profile": "https://Stackoverflow.com/users/2120", "pm_score": 3, "selected": false, "text": "IsNumeric('01.05') => false\nIsNumeric('1.') => false\nIsNumeric('.') => false\n function IsNumeric(input) {\n return /^-?(0|[1-9]\\d*|(?=\\.))(\\.\\d+)?$/.test(input);\n}\n" }, { "answer_id": 18249, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 3, "selected": false, "text": "1. IsNumeric('0x89f') => true\n2. IsNumeric('075') => true 0x -0x 0 -0 4e3.2 function IsNumeric(input){\n var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\\.,]))([\\.,][0-9]+)?([eE]-?\\d+)?))$/;\n return (RE.test(input));\n}\n" }, { "answer_id": 19176, "author": "bubbassauro", "author_id": 1328, "author_profile": "https://Stackoverflow.com/users/1328", "pm_score": 4, "selected": false, "text": "isNaN !isNaN(yourstringhere)" }, { "answer_id": 19317, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 5, "selected": false, "text": "isNaN(object) // IS NUMERIC\ndocument.write(!isNaN('-1') + \"<br />\"); // true\ndocument.write(!isNaN('-1.5') + \"<br />\"); // true\ndocument.write(!isNaN('0') + \"<br />\"); // true\ndocument.write(!isNaN('0.42') + \"<br />\"); // true\ndocument.write(!isNaN('.42') + \"<br />\"); // true\ndocument.write(!isNaN('99,999') + \"<br />\"); // false\ndocument.write(!isNaN('0x89f') + \"<br />\"); // true\ndocument.write(!isNaN('#abcdef') + \"<br />\"); // false\ndocument.write(!isNaN('1.2.3') + \"<br />\"); // false\ndocument.write(!isNaN('') + \"<br />\"); // true\ndocument.write(!isNaN('blah') + \"<br />\"); // false\n" }, { "answer_id": 22604, "author": "Aquatic", "author_id": 2080, "author_profile": "https://Stackoverflow.com/users/2080", "pm_score": 4, "selected": false, "text": "function IsNumeric(data){\n return parseFloat(data)==data;\n}\n" }, { "answer_id": 174921, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 8, "selected": false, "text": "isNaN() function IsNumeric(input)\n{\n return (input - 0) == input && (''+input).trim().length > 0;\n}\n (input - 0) NaN NaN NaN isNaN() isNaN() 0 NaN" }, { "answer_id": 1280236, "author": "camomileCase", "author_id": 143145, "author_profile": "https://Stackoverflow.com/users/143145", "pm_score": 6, "selected": false, "text": "isNumber: function(o) {\n return typeof o === 'number' && isFinite(o);\n}\n" }, { "answer_id": 1561597, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "function IsNumeric(num) {\n return (num >=0 || num < 0);\n}\n" }, { "answer_id": 1830844, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 13, "selected": true, "text": "// Whitespace strings:\nIsNumeric(' ') == true;\nIsNumeric('\\t\\t') == true;\nIsNumeric('\\n\\r') == true;\n\n// Number literals:\nIsNumeric(-1) == false;\nIsNumeric(0) == false;\nIsNumeric(1.1) == false;\nIsNumeric(8e5) == false;\n IsNumeric String Number +true == 1; true \"numeric\" function isNumeric(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n isNumeric: function(obj) {\n var realStringObj = obj && obj.toString();\n return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;\n}\n export function isNumeric(value: any): boolean {\n return !isNaN(value - parseFloat(value));\n}\n" }, { "answer_id": 2928538, "author": "InsertNameHere", "author_id": 352835, "author_profile": "https://Stackoverflow.com/users/352835", "pm_score": 3, "selected": false, "text": "isNumber : function(v){\n return typeof v === 'number' && isFinite(v);\n}\n" }, { "answer_id": 4365908, "author": "user532188", "author_id": 532188, "author_profile": "https://Stackoverflow.com/users/532188", "pm_score": 2, "selected": false, "text": " function isNumeric(n)\n {\n var n2 = n;\n n = parseFloat(n);\n return (n!='NaN' && n2==n);\n }\n" }, { "answer_id": 4674364, "author": "jberenguer", "author_id": 573156, "author_profile": "https://Stackoverflow.com/users/573156", "pm_score": -1, "selected": false, "text": "function isNumeric(v) {\n return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;\n };\n" }, { "answer_id": 4827657, "author": "jayakumar", "author_id": 593720, "author_profile": "https://Stackoverflow.com/users/593720", "pm_score": 3, "selected": false, "text": "return (input - 0) == input && input.length > 0;\n input.length undefined var temp = '' + input;\nreturn (input - 0) == input && temp.length > 0;\n" }, { "answer_id": 4975201, "author": "Manusoftar", "author_id": 613785, "author_profile": "https://Stackoverflow.com/users/613785", "pm_score": 2, "selected": false, "text": "function isNumeric(input) {\n var number = /^\\-{0,1}(?:[0-9]+){0,1}(?:\\.[0-9]+){0,1}$/i;\n var regex = RegExp(number);\n return regex.test(input) && input.length>0;\n}\n" }, { "answer_id": 6306344, "author": "solidarius", "author_id": 792721, "author_profile": "https://Stackoverflow.com/users/792721", "pm_score": 2, "selected": false, "text": "function isNumeric(value) {\n var bool = isNaN(+value));\n bool = bool || (value.indexOf('.') != -1);\n bool = bool || (value.indexOf(\",\") != -1);\n return !bool;\n};\n" }, { "answer_id": 7349746, "author": "Doctor Rudolf", "author_id": 563688, "author_profile": "https://Stackoverflow.com/users/563688", "pm_score": -1, "selected": false, "text": "typeof (n) === 'string' function isNumber(n) {\n if (typeof (n) === 'string') {\n n = n.replace(/,/, \".\");\n }\n return !isNaN(parseFloat(n)) && isFinite(n);\n }\n isNumber('12,50') isNumber(2011)" }, { "answer_id": 9776221, "author": "Rafael", "author_id": 1279325, "author_profile": "https://Stackoverflow.com/users/1279325", "pm_score": -1, "selected": false, "text": "function checkNumber(value) {\n if ( value % 1 == 0 )\n return true;\n else\n return false;\n}\n" }, { "answer_id": 10992737, "author": "Hans Schmucker", "author_id": 1450658, "author_profile": "https://Stackoverflow.com/users/1450658", "pm_score": 3, "selected": false, "text": "Infinity NaN + - /^(?:(?:(?:[1-9]\\d*|\\d)\\.\\d*|(?:[1-9]\\d*|\\d)?\\.\\d+|(?:[1-9]\\d*|\\d)) \n(?:[e]\\d+)?|0[0-7]+|0x[0-9a-f]+)$/i\n - 0\n - 00\n - 01\n - 10\n - 0e1\n - 0e01\n - .0\n - 0.\n - .0e1\n - 0.e1\n - 0.e00\n - 0xf\n - 0Xf\n - 00e1\n - 01e1\n - 00.0\n - 00x0\n - .\n - .e0\n" }, { "answer_id": 11063402, "author": "Ali Gonabadi", "author_id": 1016287, "author_profile": "https://Stackoverflow.com/users/1016287", "pm_score": 2, "selected": false, "text": "function isNumber(num) {\n return parseFloat(num).toString() == num\n}\n" }, { "answer_id": 13618756, "author": "bob", "author_id": 1088866, "author_profile": "https://Stackoverflow.com/users/1088866", "pm_score": -1, "selected": false, "text": "console.log var isNumeric = function(val){\n // --------------------------\n // Recommended\n // --------------------------\n\n // jQuery - works rather well\n // See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html\n return !isNaN(parseFloat(val)) && isFinite(val);\n\n // Aquatic - good and fast, fails the \"0x89f\" test, but that test is questionable.\n //return parseFloat(val)==val;\n\n // --------------------------\n // Other quirky options\n // --------------------------\n // Fails on \"\", null, newline, tab negative.\n //return !isNaN(val);\n\n // user532188 - fails on \"0x89f\"\n //var n2 = val;\n //val = parseFloat(val);\n //return (val!='NaN' && n2==val);\n\n // Rafael - fails on negative + decimal numbers, may be good for isInt()?\n // return ( val % 1 == 0 ) ? true : false;\n\n // pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?\n //return /^-?(0|[1-9]\\d*|(?=\\.))(\\.\\d+)?$/.test(val);\n\n // Haren - passes all\n // borrowed from http://www.codetoad.com/javascript/isnumeric.asp\n //var RE = /^-{0,1}\\d*\\.{0,1}\\d+$/;\n //return RE.test(val);\n\n // YUI - good for strict adherance to number type. Doesn't let stringy numbers through.\n //return typeof val === 'number' && isFinite(val);\n\n // user189277 - fails on \"\" and \"\\n\"\n //return ( val >=0 || val < 0);\n}\n\nvar tests = [0, 1, \"0\", 0x0, 0x000, \"0000\", \"0x89f\", 8e5, 0x23, -0, 0.0, \"1.0\", 1.0, -1.5, 0.42, '075', \"01\", '-01', \"0.\", \".0\", \"a\", \"a2\", true, false, \"#000\", '1.2.3', '#abcdef', '', \"\", \"\\n\", \"\\t\", '-', null, undefined];\n\nfor (var i=0; i<tests.length; i++){\n console.log( \"test \" + i + \": \" + tests[i] + \" \\t \" + isNumeric(tests[i]) );\n}\n" }, { "answer_id": 14932605, "author": "Kuf", "author_id": 1393862, "author_profile": "https://Stackoverflow.com/users/1393862", "pm_score": 4, "selected": false, "text": "jQuery.isNumeric() $.isNumeric('-1'); // true\n$.isNumeric('-1.5'); // true\n$.isNumeric('0'); // true\n$.isNumeric('0.42'); // true\n$.isNumeric('.42'); // true\n$.isNumeric('0x89f'); // true (valid hexa number)\n$.isNumeric('99,999'); // false\n$.isNumeric('#abcdef'); // false\n$.isNumeric('1.2.3'); // false\n$.isNumeric(''); // false\n$.isNumeric('blah'); // false\n 0x89f" }, { "answer_id": 15043984, "author": "Xotic750", "author_id": 592253, "author_profile": "https://Stackoverflow.com/users/592253", "pm_score": 6, "selected": false, "text": "isNumeric function isNumber(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n function isNumber(n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n);\n}\n Array.isArray $.isArray Object.isArray Object.prototype.toString.call(n) !== '[object Array]' function isNumber(n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\n}\n var isNumber = (function () {\n var rx = /^-/;\n\n return function (n) {\n return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(rx, ''));\n };\n}());\n function isNumber(n) {\n return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\n}\n var testHelper = function() {\n\n var testSuite = function() {\n test(\"Integer Literals\", function() {\n ok(isNumber(\"-10\"), \"Negative integer string\");\n ok(isNumber(\"0\"), \"Zero string\");\n ok(isNumber(\"5\"), \"Positive integer string\");\n ok(isNumber(-16), \"Negative integer number\");\n ok(isNumber(0), \"Zero integer number\");\n ok(isNumber(32), \"Positive integer number\");\n ok(isNumber(\"040\"), \"Octal integer literal string\");\n ok(isNumber(0144), \"Octal integer literal\");\n ok(isNumber(\"-040\"), \"Negative Octal integer literal string\");\n ok(isNumber(-0144), \"Negative Octal integer literal\");\n ok(isNumber(\"0xFF\"), \"Hexadecimal integer literal string\");\n ok(isNumber(0xFFF), \"Hexadecimal integer literal\");\n ok(isNumber(\"-0xFF\"), \"Negative Hexadecimal integer literal string\");\n ok(isNumber(-0xFFF), \"Negative Hexadecimal integer literal\");\n });\n\n test(\"Foating-Point Literals\", function() {\n ok(isNumber(\"-1.6\"), \"Negative floating point string\");\n ok(isNumber(\"4.536\"), \"Positive floating point string\");\n ok(isNumber(-2.6), \"Negative floating point number\");\n ok(isNumber(3.1415), \"Positive floating point number\");\n ok(isNumber(8e5), \"Exponential notation\");\n ok(isNumber(\"123e-2\"), \"Exponential notation string\");\n });\n\n test(\"Non-Numeric values\", function() {\n equals(isNumber(\"\"), false, \"Empty string\");\n equals(isNumber(\" \"), false, \"Whitespace characters string\");\n equals(isNumber(\"\\t\\t\"), false, \"Tab characters string\");\n equals(isNumber(\"abcdefghijklm1234567890\"), false, \"Alphanumeric character string\");\n equals(isNumber(\"xabcdefx\"), false, \"Non-numeric character string\");\n equals(isNumber(true), false, \"Boolean true literal\");\n equals(isNumber(false), false, \"Boolean false literal\");\n equals(isNumber(\"bcfed5.2\"), false, \"Number with preceding non-numeric characters\");\n equals(isNumber(\"7.2acdgs\"), false, \"Number with trailling non-numeric characters\");\n equals(isNumber(undefined), false, \"Undefined value\");\n equals(isNumber(null), false, \"Null value\");\n equals(isNumber(NaN), false, \"NaN value\");\n equals(isNumber(Infinity), false, \"Infinity primitive\");\n equals(isNumber(Number.POSITIVE_INFINITY), false, \"Positive Infinity\");\n equals(isNumber(Number.NEGATIVE_INFINITY), false, \"Negative Infinity\");\n equals(isNumber(new Date(2009, 1, 1)), false, \"Date object\");\n equals(isNumber(new Object()), false, \"Empty object\");\n equals(isNumber(function() {}), false, \"Instance of a function\");\n equals(isNumber([]), false, \"Empty Array\");\n equals(isNumber([\"-10\"]), false, \"Array Negative integer string\");\n equals(isNumber([\"0\"]), false, \"Array Zero string\");\n equals(isNumber([\"5\"]), false, \"Array Positive integer string\");\n equals(isNumber([-16]), false, \"Array Negative integer number\");\n equals(isNumber([0]), false, \"Array Zero integer number\");\n equals(isNumber([32]), false, \"Array Positive integer number\");\n equals(isNumber([\"040\"]), false, \"Array Octal integer literal string\");\n equals(isNumber([0144]), false, \"Array Octal integer literal\");\n equals(isNumber([\"-040\"]), false, \"Array Negative Octal integer literal string\");\n equals(isNumber([-0144]), false, \"Array Negative Octal integer literal\");\n equals(isNumber([\"0xFF\"]), false, \"Array Hexadecimal integer literal string\");\n equals(isNumber([0xFFF]), false, \"Array Hexadecimal integer literal\");\n equals(isNumber([\"-0xFF\"]), false, \"Array Negative Hexadecimal integer literal string\");\n equals(isNumber([-0xFFF]), false, \"Array Negative Hexadecimal integer literal\");\n equals(isNumber([1, 2]), false, \"Array with more than 1 Positive interger number\");\n equals(isNumber([-1, -2]), false, \"Array with more than 1 Negative interger number\");\n });\n }\n\n var functionsToTest = [\n\n function(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n },\n\n function(n) {\n return !isNaN(n) && !isNaN(parseFloat(n));\n },\n\n function(n) {\n return !isNaN((n));\n },\n\n function(n) {\n return !isNaN(parseFloat(n));\n },\n\n function(n) {\n return typeof(n) != \"boolean\" && !isNaN(n);\n },\n\n function(n) {\n return parseFloat(n) === Number(n);\n },\n\n function(n) {\n return parseInt(n) === Number(n);\n },\n\n function(n) {\n return !isNaN(Number(String(n)));\n },\n\n function(n) {\n return !isNaN(+('' + n));\n },\n\n function(n) {\n return (+n) == n;\n },\n\n function(n) {\n return n && /^-?\\d+(\\.\\d+)?$/.test(n + '');\n },\n\n function(n) {\n return isFinite(Number(String(n)));\n },\n\n function(n) {\n return isFinite(String(n));\n },\n\n function(n) {\n return !isNaN(n) && !isNaN(parseFloat(n)) && isFinite(n);\n },\n\n function(n) {\n return parseFloat(n) == n;\n },\n\n function(n) {\n return (n - 0) == n && n.length > 0;\n },\n\n function(n) {\n return typeof n === 'number' && isFinite(n);\n },\n\n function(n) {\n return !Array.isArray(n) && !isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));\n }\n\n ];\n\n\n // Examines the functionsToTest array, extracts the return statement of each function\n // and fills the toTest select element.\n var fillToTestSelect = function() {\n for (var i = 0; i < functionsToTest.length; i++) {\n var f = functionsToTest[i].toString();\n var option = /[\\s\\S]*return ([\\s\\S]*);/.exec(f)[1];\n $(\"#toTest\").append('<option value=\"' + i + '\">' + (i + 1) + '. ' + option + '</option>');\n }\n }\n\n var performTest = function(functionNumber) {\n reset(); // Reset previous test\n $(\"#tests\").html(\"\"); //Clean test results\n isNumber = functionsToTest[functionNumber]; // Override the isNumber global function with the one to test\n testSuite(); // Run the test\n\n // Get test results\n var totalFail = 0;\n var totalPass = 0;\n $(\"b.fail\").each(function() {\n totalFail += Number($(this).html());\n });\n $(\"b.pass\").each(function() {\n totalPass += Number($(this).html());\n });\n $(\"#testresult\").html(totalFail + \" of \" + (totalFail + totalPass) + \" test failed.\");\n\n $(\"#banner\").attr(\"class\", \"\").addClass(totalFail > 0 ? \"fail\" : \"pass\");\n }\n\n return {\n performTest: performTest,\n fillToTestSelect: fillToTestSelect,\n testSuite: testSuite\n };\n}();\n\n\n$(document).ready(function() {\n testHelper.fillToTestSelect();\n testHelper.performTest(0);\n\n $(\"#toTest\").change(function() {\n testHelper.performTest($(this).children(\":selected\").val());\n });\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\" type=\"text/javascript\"></script>\n<script src=\"https://rawgit.com/Xotic750/testrunner-old/master/testrunner.js\" type=\"text/javascript\"></script>\n<link href=\"https://rawgit.com/Xotic750/testrunner-old/master/testrunner.css\" rel=\"stylesheet\" type=\"text/css\">\n<h1>isNumber Test Cases</h1>\n\n<h2 id=\"banner\" class=\"pass\"></h2>\n\n<h2 id=\"userAgent\">Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11</h2>\n\n<div id=\"currentFunction\"></div>\n\n<div id=\"selectFunction\">\n <label for=\"toTest\" style=\"font-weight:bold; font-size:Large;\">Select function to test:</label>\n <select id=\"toTest\" name=\"toTest\">\n </select>\n</div>\n\n<div id=\"testCode\"></div>\n\n<ol id=\"tests\">\n <li class=\"pass\">\n <strong>Integer Literals <b style=\"color:black;\">(0, 10, 10)</b></strong>\n\n <ol style=\"display: none;\">\n <li class=\"pass\">Negative integer string</li>\n\n <li class=\"pass\">Zero string</li>\n\n <li class=\"pass\">Positive integer string</li>\n\n <li class=\"pass\">Negative integer number</li>\n\n <li class=\"pass\">Zero integer number</li>\n\n <li class=\"pass\">Positive integer number</li>\n\n <li class=\"pass\">Octal integer literal string</li>\n\n <li class=\"pass\">Octal integer literal</li>\n\n <li class=\"pass\">Hexadecimal integer literal string</li>\n\n <li class=\"pass\">Hexadecimal integer literal</li>\n </ol>\n </li>\n\n <li class=\"pass\">\n <strong>Foating-Point Literals <b style=\"color:black;\">(0, 6, 6)</b></strong>\n\n <ol style=\"display: none;\">\n <li class=\"pass\">Negative floating point string</li>\n\n <li class=\"pass\">Positive floating point string</li>\n\n <li class=\"pass\">Negative floating point number</li>\n\n <li class=\"pass\">Positive floating point number</li>\n\n <li class=\"pass\">Exponential notation</li>\n\n <li class=\"pass\">Exponential notation string</li>\n </ol>\n </li>\n\n <li class=\"pass\">\n <strong>Non-Numeric values <b style=\"color:black;\">(0, 18, 18)</b></strong>\n\n <ol style=\"display: none;\">\n <li class=\"pass\">Empty string: false</li>\n\n <li class=\"pass\">Whitespace characters string: false</li>\n\n <li class=\"pass\">Tab characters string: false</li>\n\n <li class=\"pass\">Alphanumeric character string: false</li>\n\n <li class=\"pass\">Non-numeric character string: false</li>\n\n <li class=\"pass\">Boolean true literal: false</li>\n\n <li class=\"pass\">Boolean false literal: false</li>\n\n <li class=\"pass\">Number with preceding non-numeric characters: false</li>\n\n <li class=\"pass\">Number with trailling non-numeric characters: false</li>\n\n <li class=\"pass\">Undefined value: false</li>\n\n <li class=\"pass\">Null value: false</li>\n\n <li class=\"pass\">NaN value: false</li>\n\n <li class=\"pass\">Infinity primitive: false</li>\n\n <li class=\"pass\">Positive Infinity: false</li>\n\n <li class=\"pass\">Negative Infinity: false</li>\n\n <li class=\"pass\">Date object: false</li>\n\n <li class=\"pass\">Empty object: false</li>\n\n <li class=\"pass\">Instance of a function: false</li>\n </ol>\n </li>\n</ol>\n\n<div id=\"main\">\n This page contains tests for a set of isNumber functions. To see them, take a look at the source.\n</div>\n\n<div>\n <p class=\"result\">Tests completed in 0 milliseconds.\n <br>0 tests of 0 failed.</p>\n</div>" }, { "answer_id": 15103743, "author": "NaveenKumar1410", "author_id": 2060915, "author_profile": "https://Stackoverflow.com/users/2060915", "pm_score": 2, "selected": false, "text": "self.number = ko.observable(numberValue) numberValue = '0.0' --> true\nnumberValue = '0' --> true\nnumberValue = '25' --> true\nnumberValue = '-1' --> true\nnumberValue = '-3.5' --> true\nnumberValue = '11.112' --> true\nnumberValue = '0x89f' --> false\nnumberValue = '' --> false\nnumberValue = 'sfsd' --> false\nnumberValue = 'dg##$' --> false\n self.number = ko.observable(numberValue) numberValue = '0' --> true\nnumberValue = '25' --> true\nnumberValue = '0.0' --> false\nnumberValue = '-1' --> false\nnumberValue = '-3.5' --> false\nnumberValue = '11.112' --> false\nnumberValue = '0x89f' --> false\nnumberValue = '' --> false\nnumberValue = 'sfsd' --> false\nnumberValue = 'dg##$' --> false\n self.number = ko.observable(numberValue) numberValue = '5' --> true\nnumberValue = '6' --> true\nnumberValue = '6.5' --> true\nnumberValue = '9' --> true\nnumberValue = '11' --> false\nnumberValue = '0' --> false\nnumberValue = '' --> false\n" }, { "answer_id": 15997937, "author": "Phil", "author_id": 1129712, "author_profile": "https://Stackoverflow.com/users/1129712", "pm_score": 1, "selected": false, "text": "is_float = function(v) {\n return !isNaN(v) && isFinite(v) &&\n (typeof(v) == 'number' || v.replace(/^\\s+|\\s+$/g, '').length > 0);\n}\n var t = [\n 0,\n 1.2123,\n '0',\n '2123.4',\n -1,\n '-1',\n -123.423,\n '-123.432',\n 07,\n 0xad,\n '07',\n '0xad'\n ];\n var t = [\n 'hallo',\n [],\n {},\n 'jklsd0',\n '',\n \"\\t\",\n \"\\n\",\n ' '\n ];\n" }, { "answer_id": 16654296, "author": "Arman", "author_id": 1847185, "author_profile": "https://Stackoverflow.com/users/1847185", "pm_score": 2, "selected": false, "text": "function isNumeric(val) {\n return !isNaN(+val) && isFinite(val);\n}\n \"123abc\" parseFloat | parseInt isFinite +" }, { "answer_id": 16973976, "author": "hobs", "author_id": 623735, "author_profile": "https://Stackoverflow.com/users/623735", "pm_score": 3, "selected": false, "text": "NaN NaN NaN != NaN function isNumber(n) {\n n = parseFloat(n);\n return !isNaN(n) || n != n;\n}\nfunction isFiniteNumber(n) {\n n = parseFloat(n);\n return !isNaN(n) && isFinite(n);\n} \nfunction isComparableNumber(n) {\n n = parseFloat(n);\n return (n >=0 || n < 0);\n}\n\nisFiniteNumber('NaN')\nfalse\nisFiniteNumber('OxFF')\ntrue\nisNumber('NaN')\ntrue\nisNumber(1/0-1/0)\ntrue\nisComparableNumber('NaN')\nfalse\nisComparableNumber('Infinity')\ntrue\n" }, { "answer_id": 17559810, "author": "Mr Br", "author_id": 2188869, "author_profile": "https://Stackoverflow.com/users/2188869", "pm_score": 0, "selected": false, "text": "var val=1+$(e).val()+'';\nvar n=parseInt(val)+'';\nif(val.length == n.length )alert('Is int');\n" }, { "answer_id": 19056758, "author": "Aaron Gong", "author_id": 2215486, "author_profile": "https://Stackoverflow.com/users/2215486", "pm_score": 2, "selected": false, "text": "parseFloat Number function IsNumeric(_in) {\n return (parseFloat(_in) === Number(_in) && Number(_in) !== NaN);\n}\n" }, { "answer_id": 20712631, "author": "daniel1426", "author_id": 1985601, "author_profile": "https://Stackoverflow.com/users/1985601", "pm_score": 1, "selected": false, "text": "function isNumeric(num) {\n return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);\n}\n" }, { "answer_id": 21096633, "author": "Sean the Bean", "author_id": 814160, "author_profile": "https://Stackoverflow.com/users/814160", "pm_score": 3, "selected": false, "text": "$.isNumeric(val)\n" }, { "answer_id": 23049711, "author": "donquixote", "author_id": 246724, "author_profile": "https://Stackoverflow.com/users/246724", "pm_score": 2, "selected": false, "text": "function isDecimal(x) {\n return '' + x === '' + +x;\n}\n\nfunction isInteger(x) {\n return '' + x === '' + parseInt(x);\n}\n isDecimal function testIsNumber(f) {\n return f('-1') && f('-1.5') && f('0') && f('0.42')\n && !f('.42') && !f('99,999') && !f('0x89f')\n && !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');\n}\n isNumber() var obj = {};\nobj['4'] = 'canonical 4';\nobj['04'] = 'alias of 4';\nobj[4]; // prints 'canonical 4' to the console.\n" }, { "answer_id": 25861284, "author": "Nik", "author_id": 1180387, "author_profile": "https://Stackoverflow.com/users/1180387", "pm_score": -1, "selected": false, "text": "v * 1 == v\n" }, { "answer_id": 27471814, "author": "Simon Hi", "author_id": 2458202, "author_profile": "https://Stackoverflow.com/users/2458202", "pm_score": 1, "selected": false, "text": "function isNumber(n) {\n return (n===n+''||n===n-0) && n*0==0 && /\\S/.test(n);\n}\n (n===n-0||n===n+'') (n===n-0||n===n+'') n!==undefined && n!==null && (n.constructor===Number||n.constructor===String) n*0==0 isFinite(n) n*0==0 n.toString().replace(/^\\s*-/,'')*0==0 /\\S/.test(n) isFinite(n) or n*0==0 false .test(n) (n!=0||/0/.test(n)) /\\S/.test(n) (n!=0||(n+'').indexOf('0')>=0)" }, { "answer_id": 27622495, "author": "John", "author_id": 606371, "author_profile": "https://Stackoverflow.com/users/606371", "pm_score": 2, "selected": false, "text": "false function is_numeric(n)\n{\n return (n != '' && !isNaN(parseFloat(n)) && isFinite(n));\n}\n" }, { "answer_id": 34791974, "author": "Dmitry Sheiko", "author_id": 998008, "author_profile": "https://Stackoverflow.com/users/998008", "pm_score": 1, "selected": false, "text": "is.nan = function(value) { // NaN is number :) \n return value !== value;\n};\n // is a given value number?\nis.number = function(value) {\n return !is.nan(value) && Object.prototype.toString.call(value) === '[object Number]';\n};\n /**\n * This is JSDOC syntax\n * @param {number|string} sum\n * @param {Object.<string, string>} payload\n * @param {function} cb\n */\nfunction foo( sum, payload, cb ) {\n // Test if the contract is respected at entry point\n byContract( arguments, [ \"number|string\", \"Object.<string, string>\", \"function\" ] );\n}\n// Test it\nfoo( 100, { foo: \"foo\" }, function(){}); // ok\nfoo( 100, { foo: 100 }, function(){}); // exception\n" }, { "answer_id": 35324436, "author": "studio-klik", "author_id": 4813369, "author_profile": "https://Stackoverflow.com/users/4813369", "pm_score": 2, "selected": false, "text": "<input type=\"text\" name=\"date\" value=\"\" pattern=\"[0-9]){1,2}(\\.){1}([0-9]){2}\" maxlength=\"6\" placeholder=\"od npr.: 16.06\" onchange=\"date(this);\" />\n function date(inputField) { \n var isValid = /^([0-9]){1,2}(\\.){1}([0-9]){2}$/.test(inputField.value); \n if (isValid) {\n inputField.style.backgroundColor = '#bfa';\n } else {\n inputField.style.backgroundColor = '#fba';\n }\n return isValid;\n}\n" }, { "answer_id": 36318751, "author": "Shishir Arora", "author_id": 3221274, "author_profile": "https://Stackoverflow.com/users/3221274", "pm_score": 2, "selected": false, "text": "isNumeric=(el)=>{return Boolean(parseFloat(el)) && isFinite(el)}" }, { "answer_id": 36533370, "author": "adius", "author_id": 1850340, "author_profile": "https://Stackoverflow.com/users/1850340", "pm_score": 3, "selected": false, "text": "Number.isFinite(value) Number.isFinite(Infinity) // false\nNumber.isFinite(NaN) // false\nNumber.isFinite(-Infinity) // false\n\nNumber.isFinite(0) // true\nNumber.isFinite(2e64) // true\n\nNumber.isFinite('0') // false\nNumber.isFinite(null) // false\n" }, { "answer_id": 37331792, "author": "Syed Nasir Abbas", "author_id": 585237, "author_profile": "https://Stackoverflow.com/users/585237", "pm_score": -1, "selected": false, "text": "function isNumeric(n) {\n var isNumber = true;\n\n $.each(n.replace(/ /g,'').toString(), function(i, v){\n if(v!=',' && v!='.' && v!='-'){\n if(isNaN(v)){\n isNumber = false;\n return false;\n }\n }\n });\n\n return isNumber;\n}\n\nisNumeric(-3,4567.89); // true <br>\n\nisNumeric(3,4567.89); // true <br>\n\nisNumeric(\"-3,4567.89\"); // true <br>\n\nisNumeric(3d,4567.89); // false\n" }, { "answer_id": 37384296, "author": "paulalexandru", "author_id": 3522687, "author_profile": "https://Stackoverflow.com/users/3522687", "pm_score": 1, "selected": false, "text": "function isThisActuallyANumber(data){\n return ( typeof data === \"number\" && !isNaN(data) );\n}\n" }, { "answer_id": 37975166, "author": "John Mikic", "author_id": 1636207, "author_profile": "https://Stackoverflow.com/users/1636207", "pm_score": 3, "selected": false, "text": "isNumeric(Infinity) == true function isNumeric(n) {\n\n return parseFloat(n) == n;\n}\n" }, { "answer_id": 38882756, "author": "chrmcpn", "author_id": 3626940, "author_profile": "https://Stackoverflow.com/users/3626940", "pm_score": 2, "selected": false, "text": "function inNumeric(n){\n return Number(n).toString() === n;\n}\n Number(n) toString() Number(n) NaN n" }, { "answer_id": 41526723, "author": "solimanware", "author_id": 4591364, "author_profile": "https://Stackoverflow.com/users/4591364", "pm_score": 2, "selected": false, "text": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar isNumber = function(s) {\n return s.trim()!==\"\" && !isNaN(Number(s));\n};" }, { "answer_id": 42018658, "author": "Saurabh Chandra Patel", "author_id": 1371778, "author_profile": "https://Stackoverflow.com/users/1371778", "pm_score": -1, "selected": false, "text": "$('.rsval').bind('keypress', function(e){ \n var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];\n var keynum = (!window.event) ? e.which : e.keyCode; \n var splitn = this.value.split(\".\"); \n var decimal = splitn.length;\n var precision = splitn[1]; \n if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); } \n if( keynum == 46 ){ \n if(decimal > 2) { e.preventDefault(); } \n } \n if ($.inArray(keynum, asciiCodeOfNumbers) == -1)\n e.preventDefault(); \n });\n" }, { "answer_id": 42419193, "author": "Vixed", "author_id": 1076753, "author_profile": "https://Stackoverflow.com/users/1076753", "pm_score": 2, "selected": false, "text": "$('.number').on('input',function(){\n var n=$(this).val().replace(/ /g,'').replace(/\\D/g,'');\n if (!$.isNumeric(n))\n $(this).val(n.slice(0, -1))\n else\n $(this).val(n)\n});\n" }, { "answer_id": 47009183, "author": "Alston", "author_id": 1599462, "author_profile": "https://Stackoverflow.com/users/1599462", "pm_score": 2, "selected": false, "text": "const IsNumeric = (...numbers) => {\n return numbers.reduce((pre, cur) => pre && !!(cur === 0 || +cur), true);\n};\n > IsNumeric(1)\ntrue\n> IsNumeric(1,2,3)\ntrue\n> IsNumeric(1,2,3,0)\ntrue\n> IsNumeric(1,2,3,0,'')\nfalse\n> IsNumeric(1,2,3,0,'2')\ntrue\n> IsNumeric(1,2,3,0,'200')\ntrue\n> IsNumeric(1,2,3,0,'-200')\ntrue\n> IsNumeric(1,2,3,0,'-200','.32')\ntrue\n" }, { "answer_id": 54382602, "author": "Mhmdrz_A", "author_id": 5953610, "author_profile": "https://Stackoverflow.com/users/5953610", "pm_score": 2, "selected": false, "text": "function IsNumeric (string) {\n if(string === ' '.repeat(string.length)){\n return false\n }\n return string - 0 === string * 1\n}\n\n function IsNumeric (string) {\n if(string === ' '.repeat(string.length)){\n return false\n }\n return string - 0 === string * 1\n}\n\n\nconsole.log('-1' + ' → ' + IsNumeric('-1')) \nconsole.log('-1.5' + ' → ' + IsNumeric('-1.5')) \nconsole.log('0' + ' → ' + IsNumeric('0')) \nconsole.log('0.42' + ' → ' + IsNumeric('0.42')) \nconsole.log('.42' + ' → ' + IsNumeric('.42')) \nconsole.log('99,999' + ' → ' + IsNumeric('99,999'))\nconsole.log('0x89f' + ' → ' + IsNumeric('0x89f')) \nconsole.log('#abcdef' + ' → ' + IsNumeric('#abcdef'))\nconsole.log('1.2.3' + ' → ' + IsNumeric('1.2.3')) \nconsole.log('' + ' → ' + IsNumeric('')) \nconsole.log('33 ' + ' → ' + IsNumeric('33 '))" }, { "answer_id": 58091055, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 2, "selected": false, "text": "function isNumeric(x) {\n return parseFloat(x) == x;\n}\n console.log('trues');\nconsole.log(isNumeric('-1'));\nconsole.log(isNumeric('-1.5'));\nconsole.log(isNumeric('0'));\nconsole.log(isNumeric('0.42'));\nconsole.log(isNumeric('.42'));\n\nconsole.log('falses');\nconsole.log(isNumeric('99,999'));\nconsole.log(isNumeric('0x89f'));\nconsole.log(isNumeric('#abcdef'));\nconsole.log(isNumeric('1.2.3'));\nconsole.log(isNumeric(''));\nconsole.log(isNumeric('blah'));\n console.log('trues');\nconsole.log(isNumeric(0));\nconsole.log(isNumeric(-1));\nconsole.log(isNumeric(-500));\nconsole.log(isNumeric(15000));\nconsole.log(isNumeric(0.35));\nconsole.log(isNumeric(-10.35));\nconsole.log(isNumeric(2.534e25));\nconsole.log(isNumeric('2.534e25'));\nconsole.log(isNumeric('52334'));\nconsole.log(isNumeric('-234'));\nconsole.log(isNumeric(Infinity));\nconsole.log(isNumeric(-Infinity));\nconsole.log(isNumeric('Infinity'));\nconsole.log(isNumeric('-Infinity'));\n\nconsole.log('falses');\nconsole.log(isNumeric(NaN));\nconsole.log(isNumeric({}));\nconsole.log(isNumeric([]));\nconsole.log(isNumeric(''));\nconsole.log(isNumeric('one'));\nconsole.log(isNumeric(true));\nconsole.log(isNumeric(false));\nconsole.log(isNumeric());\nconsole.log(isNumeric(undefined));\nconsole.log(isNumeric(null));\nconsole.log(isNumeric('-234aa'));\n" }, { "answer_id": 71097252, "author": "chickens", "author_id": 1602301, "author_profile": "https://Stackoverflow.com/users/1602301", "pm_score": 0, "selected": false, "text": "const isNumeric = num => /^-?[0-9]+(?:\\.[0-9]+)?$/.test(num+'');\n const isInteger = num => /^-?[0-9]+$/.test(num+'');\n" }, { "answer_id": 72830995, "author": "Mykola Uspalenko", "author_id": 8413306, "author_profile": "https://Stackoverflow.com/users/8413306", "pm_score": 0, "selected": false, "text": "typeof n === 'string' function isNumeric(n)\n{\n if(n === null || typeof n === 'undefined')\n return false;\n\n if(typeof n === 'string')\n n = n.split(',').join('');\n\n return !isNaN(parseFloat(n)) && isFinite(n);\n}\n" }, { "answer_id": 74242649, "author": "Timothy C. Quinn", "author_id": 286807, "author_profile": "https://Stackoverflow.com/users/286807", "pm_score": 0, "selected": false, "text": "function isNumeric(n, parse) {\n var t = typeof(n);\n if (parse){\n if (t !== 'number' && t !=='string') return false;\n return !isNaN(parseFloat(n)) && isFinite(n);\n }else{\n if (t !== 'number') return false;\n return !isNaN(n) && isFinite(n) && !_.isString(n);\n }\n}\n\nfunction isInteger(n, parse) { \n return isNumeric(n, parse) && n % 1 === 0;\n}\n\nfunction isFloat(n, parse) {\n return isNumeric(n, parse) && n % 1 !== 0;\n}\n underscore-contrib isNumeric([1]) parseFloat() parse" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ]
18,097
<p>In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?</p> <pre><code>class BaseClass { public BaseClass() { // ... some code } } class MyClass : BaseClass { public MyClass() // Do I need to put ": base()" here or is it implied? { // ... some code } } </code></pre>
[ { "answer_id": 18109, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 7, "selected": true, "text": "using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n MyClass foo = new MyClass();\n\n Console.ReadLine();\n }\n }\n\n class BaseClass\n {\n public BaseClass()\n {\n Console.WriteLine(\"BaseClass constructor called.\");\n }\n }\n\n class MyClass : BaseClass\n {\n public MyClass()\n {\n Console.WriteLine(\"MyClass constructor called.\");\n }\n }\n}\n" }, { "answer_id": 18170, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 5, "selected": false, "text": "public class SuperClassEmptyCtor\n{\n public SuperClassEmptyCtor()\n {\n // Default Ctor\n }\n}\n\npublic class SubClassA : SuperClassEmptyCtor\n{\n // No Ctor's this is fine since we have\n // a default (empty ctor in the base)\n}\n\npublic class SuperClassCtor\n{\n public SuperClassCtor(string value)\n {\n // Default Ctor\n }\n}\n\npublic class SubClassB : SuperClassCtor\n{\n // This fails because we need to satisfy\n // the ctor for the base class.\n}\n\npublic class SubClassC : SuperClassCtor\n{\n public SubClassC(string value) : base(value)\n {\n // make it easy and pipe the params\n // straight to the base!\n }\n}\n" }, { "answer_id": 18185, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "public class BaseClass {\n protected string X;\n\n public BaseClass() {\n this.X = \"Foo\";\n }\n}\n\npublic class MyClass : BaseClass\n{\n public MyClass() \n // no ref to base needed\n {\n // initialise stuff\n this.X = \"bar\";\n }\n\n public MyClass(int param1, string param2)\n :this() // This is needed to hit the parameterless ..ctor\n {\n // this.X will be \"bar\"\n }\n\n public MyClass(string param1, int param2)\n // :base() // can be implied\n {\n // this.X will be \"foo\"\n }\n}\n" }, { "answer_id": 18196, "author": "jl23x", "author_id": 2143, "author_profile": "https://Stackoverflow.com/users/2143", "pm_score": -1, "selected": false, "text": "using System;\nnamespace StackOverflow.Examples\n{\n class Program\n {\n static void Main(string[] args)\n {\n NewClass foo = new NewClass(\"parameter1\",\"parameter2\");\n Console.WriteLine(foo.GetUpperParameter());\n Console.ReadKey();\n }\n }\n\n interface IClass\n {\n string GetUpperParameter();\n }\n\n class BaseClass : IClass\n {\n private string parameter;\n public BaseClass (string someParameter)\n {\n this.parameter = someParameter;\n }\n\n public string GetUpperParameter()\n {\n return this.parameter.ToUpper();\n }\n }\n\n class NewClass : IClass\n {\n private BaseClass internalClass;\n private string newParameter;\n\n public NewClass (string someParameter, string newParameter)\n {\n this.internalClass = new BaseClass(someParameter);\n this.newParameter = newParameter;\n }\n\n public string GetUpperParameter()\n {\n return this.internalClass.GetUpperParameter() + this.newParameter.ToUpper();\n }\n }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
18,119
<p>In a world where manual memory allocation and pointers still rule (Borland Delphi) I need a general solution for what I think is a general problem:</p> <p>At a given moment an object can be referenced from multiple places (lists, other objects, ...). Is there a good way to keep track of all these references so that I can update them when the object is destroyed? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 18165, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "// Anything that will use one of your tracked objects implements this interface\ninterface ITrackedObjectUser {\n public void objectDestroyed(TrackedObject o);\n}\n\n// All objects you want to track extends this class\nclass TrackedObject {\n private List<ITrackedObjectUser> users;\n\n public void registerRef(ITrackedObjectUser u) {\n users.add(u);\n }\n\n public void destroy() {\n foreach(ITrackedObjectUser u in users) {\n u.objectDestroyed(this);\n }\n }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
18,166
<p>I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response:</p> <pre><code>$request = trim(file_get_contents('test.xml')); $curlHandle = curl_init($servletURL); curl_setopt($curlHandle, CURLOPT_POST, TRUE); curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=&gt;$request)); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curlHandle, CURLOPT_HEADER, FALSE); # Have also tried leaving this out $response = curl_exec($curlHandle); </code></pre> <p>That code, in an of itself, works OK, but the other server returns a response from it's XML parser stating:</p> <blockquote> <p>Content not allowed in prolog</p> </blockquote> <p>I looked that error up and this is normally caused by whitespace before the XML, but I made sure that the XML file itself has no whitespace and the trim() should clear that up anyway. I did a TCPDump on the connection while I ran the code and this is what is sent out:</p> <pre><code>POST {serverURL} HTTP/1.1 Host: {ip of server}:8080 Accept: */* Content-Length: 921 Expect: 100-continue Content-Type: multipart/form-data; boundry:---------------------------01e7cda3896f ---------------------------01e7cda3896f Content-Disposition: form-data; name="XML" [SNIP - the XML was displayed] ---------------------------01e7cda3896f-- </code></pre> <p>Before and after the [SNIP] line there is visible whitespace when I replay the session in Ethereal. Is this what is causing the problem and, if so, how can I remove it, or am I looking too far and this may be an issue with the server I'm posting against?</p>
[ { "answer_id": 18215, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "$file = 'test.xml';\n$fileHandle = fopen($file, 'r');\n$request = fread($fileHandle, filesize($file));\nfclose($fileHandle);\n$request = trim($request);\n $request = trim(file_get_contents('test.xml'));\n" }, { "answer_id": 18247, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 0, "selected": false, "text": "wc -m test.xml var_dump $request trim() print \"=====\" . $request . \"=====\";\n" }, { "answer_id": 18287, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 3, "selected": true, "text": "# This sets the encoding to multipart/form-data\ncurl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request));\n # This sets it to application/x-www-form-urlencoded\ncurl_setopt($curlHandle, CURLOPT_POSTFIELDS, 'XML=' . urlencode($request));\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
18,167
<p>I've got a database server that I am unable to connect to using the credentials I've been provided. However, on the staging version of the same server, there's a linked server that points to the production database. Both the staging server and the linked server have the same schema.</p> <p>I've been reassured that I should expect to be able to connect to the live server before we go live. Unfortunately, I've reached a point in my development where I need more than the token sample records that are currently in the staging database. So, I was hoping to connect to the linked server.</p> <p>Thus far in my development against this schema has been against the staging server itself, using Subsonic objects. That all works fine.</p> <p>I can connect via SQL Server Management Studio to that linked server and execute my queries directly. I can also execute 'manual" queries in C# against the linked server by having my connection string hook up to the staging server and running my queries as </p> <p>SELECT * FROM OpenQuery([LINKEDSERVER],'QUERY')</p> <p>However, the Subsonic objects are what's enabling me to bring this project in on time and under budget, so I'm not looking to do straight queries in my code.</p> <p>What I'm looking for is whether there's a way to state the connection string to the linked server. I've looked at lots of forum entries, etc. on the topic and most of the answers seem to completely gloss over the "linked server" portion of the question, focusing on basic connection string syntax.</p>
[ { "answer_id": 18695, "author": "TheEmirOfGroofunkistan", "author_id": 1874, "author_profile": "https://Stackoverflow.com/users/1874", "pm_score": 2, "selected": false, "text": "databaseA.dbo.tableName\n linkedServerName.databaseA.dbo.tableName\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124/" ]
18,172
<p>I am looking for a robust way to copy files over a Windows network share that is tolerant of intermittent connectivity. The application is often used on wireless, mobile workstations in large hospitals, and I'm assuming connectivity can be lost either momentarily or for several minutes at a time. The files involved are typically about 200KB - 500KB in size. The application is written in VB6 (ugh), but we frequently end up using Windows DLL calls.</p> <p>Thanks!</p>
[ { "answer_id": 19606, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "sourceFile = Compress(\"*.*\");\ndestFile = \"X:\\files.zip\";\n\nint copyFlags = COPYFILEFAILIFEXISTS | COPYFILERESTARTABLE;\nwhile (CopyFileEx(sourceFile, destFile, null, null, false, copyFlags) == 0) {\n do {\n // optionally, increment a failed counter to break out at some point\n Sleep(1000);\n while (!IsNetworkAlive(NETWORKALIVELAN));\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2144/" ]
18,216
<p>I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.</p> <p>I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table.</p> <p>The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK"</p> <p>What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like:</p> <pre><code>ID NAME SPECIALTYPE 1 Red Dragon Archfiend Synchro 1 Red Dragon Archfiend DARK 1 Red Dragon Archfiend Effect </code></pre> <p>and I could tally my results that way.</p> <p>I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like:</p> <pre><code>1 Red Dragon Archfiend Synchro/DARK/Effect </code></pre> <p>..but I don't know if that's feasible.</p> <p>Help me stackoverflow Kenobi! You're my only hope.</p>
[ { "answer_id": 18245, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "table cards\ninteger ID | string name | ... (other properties common to all Cards)\n\ntable property_types\ninteger ID | string name | string format | ... (possibly validations)\n\ntable properties\ninteger ID | integer property_type_id | string name | string value\nforeign key property_type_id references property_types.ID\n\ntable cards_properties\ninteger ID | integer card_id | integer property_id\nforeign key card_id references cards.ID\nforeign key property_id references propertiess.ID\n" }, { "answer_id": 18262, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 1, "selected": false, "text": "Select\n ID,NAME\n ,Synchro+DARK+Effect -- add a some substring logic to trim any trailing /'s\nfrom\n (select\n ID\n ,NAME\n --may need to replace max() with min().\n ,MAX(CASE SPECIALTYPE WHEN \"Synchro\" THEN SPECIALTYPE +\"/\" ELSE \"\" END) Synchro\n ,MAX(CASE SPECIALTYPE WHEN \"DARK\" THEN SPECIALTYPE +\"/\" ELSE \"\" END) DARK\n ,MAX(CASE SPECIALTYPE WHEN \"Effect\" THEN SPECIALTYPE ELSE \"\" END) Effect\n from\n table\n group by\n ID\n ,NAME) sub1\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
18,223
<p>I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005?</p> <p>The insert I'm doing is:</p> <pre><code>INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems] </code></pre> <p>Here is what the trigger looks like:</p> <pre><code>CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems] FOR INSERT AS Declare @iRoleID int Declare @iMenuItemID int Select @iMenuItemID = [ID] from Inserted DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles OPEN tblUserRoles FETCH NEXT FROM tblUserRoles INTO @iRoleID WHILE (@@FetchStatus = 0) BEGIN INSERT INTO tblRestrictedMenuItems( [RoleID], [MenuItemID], [RestrictLevel]) VALUES( @iRoleID, @iMenuItemID, 1) FETCH NEXT FROM tblUserRoles INTO @iRoleID END CLOSE tblUserRoles Deallocate tblUserRoles </code></pre>
[ { "answer_id": 18230, "author": "Martin", "author_id": 770, "author_profile": "https://Stackoverflow.com/users/770", "pm_score": 1, "selected": false, "text": "SELECT COUNT(*) FROM inserted \n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741/" ]
18,224
<p>So, in your experience, whats the best way? Is there a secure way that's also scriptable/triggerable in a build automation tool?</p> <p>Edit: I should mention this is windows/.net and I'll be deploying to iis6</p>
[ { "answer_id": 18243, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\nset -e\ncp -R /var/livesite /var/newversion\nrsync user@devserver:/var/readytogolive /var/newversion\nmv /var/livesite /var/oldlivesite\nmv /var/newversion /var/livesite\n" }, { "answer_id": 18267, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 1, "selected": false, "text": "set -e rsync set -e set -e #!/bin/bash" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
18,265
<p>What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file. </p> <p>Bonus points for the following optional features:</p> <ul> <li>Extra information gathering at crash time (eg. config files).</li> <li>Email a crash info bundle to the developers.</li> <li>Ability to add this in a <code>dlopen</code>ed shared library</li> <li>Not requiring a GUI</li> </ul>
[ { "answer_id": 18406, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": true, "text": "backtrace backtrace #include <execinfo.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid sig_handler(int sig)\n{\n void * array[25];\n int nSize = backtrace(array, 25);\n char ** symbols = backtrace_symbols(array, nSize);\n\n for (int i = 0; i < nSize; i++)\n {\n puts(symbols[i]);;\n }\n\n free(symbols);\n\n signal(sig, &sig_handler);\n}\n\nvoid h()\n{\n kill(0, SIGSEGV);\n}\n\nvoid g()\n{\n h();\n}\n\nvoid f()\n{\n g();\n}\n\nint main(int argc, char ** argv)\n{\n signal(SIGSEGV, &sig_handler);\n f();\n}\n 0 a.out 0x00001f2d sig_handler + 35\n1 libSystem.B.dylib 0x95f8f09b _sigtramp + 43\n2 ??? 0xffffffff 0x0 + 4294967295\n3 a.out 0x00001fb1 h + 26\n4 a.out 0x00001fbe g + 11\n5 a.out 0x00001fcb f + 11\n6 a.out 0x00001ff5 main + 40\n7 a.out 0x00001ede start + 54\n" }, { "answer_id": 41924, "author": "AndersO", "author_id": 22021, "author_profile": "https://Stackoverflow.com/users/22021", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <cxxabi.h>\n\nvoid sig_handler(int sig)\n{\n std::stringstream stream;\n void * array[25];\n int nSize = backtrace(array, 25);\n char ** symbols = backtrace_symbols(array, nSize);\n for (unsigned int i = 0; i < size; i++) {\n int status;\n char *realname;\n std::string current = symbols[i];\n size_t start = current.find(\"(\");\n size_t end = current.find(\"+\");\n realname = NULL;\n if (start != std::string::npos && end != std::string::npos) {\n std::string symbol = current.substr(start+1, end-start-1);\n realname = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);\n }\n if (realname != NULL)\n stream << realname << std::endl;\n else\n stream << symbols[i] << std::endl;\n free(realname);\n }\n free(symbols);\n std::cerr << stream.str();\n std::ofstream file(\"/tmp/error.log\");\n if (file.is_open()) {\n if (file.good())\n file << stream.str();\n file.close();\n }\n signal(sig, &sig_handler);\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954/" ]
18,272
<p>Server Management Studio tends to be a bit un-intuitive when it comes to managing Extended Properties, so can anyone recommend a decent tool that improves the situation.</p> <p>One thing I would like to do is to have templates that I can apply objects, thus standardising the nomenclature and content of the properties applied to objects.</p>
[ { "answer_id": 15105932, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo]. [snap_xpColumn_addUpdate]') AND type in (N'P', N'PC'))\nDROP PROCEDURE [dbo].snap_xpColumn_addUpdate\nGO\n\nCREATE PROCEDURE [dbo].[snap_xpColumn_addUpdate]\n @TableName NVARCHAR(255), \n @ColumnName NVARCHAR(255),\n @ExtPropName NVARCHAR(255), \n @ExtPropValue NVARCHAR(255), \n @SchemaOwner NVARCHAR(255) = 'dbo'\nAS\n\n IF EXISTS(SELECT * FROM ::fn_listextendedproperty(@ExtPropName,'SCHEMA',@SchemaOwner,\n 'TABLE',@TableName,'COLUMN',@ColumnName))\n BEGIN\n -- drop it\n EXEC sys.sp_dropextendedproperty @name=@ExtPropName, \n @level0type=N'SCHEMA',\n @level0name=@SchemaOwner, \n @level1type=N'TABLE',\n @level1name=@TableName, \n @level2type=N'COLUMN',\n @level2name=@ColumnName\n END\n\n -- add it\n EXEC sys.sp_addextendedproperty @name=@ExtPropName, \n @value=@ExtPropValue, \n @level0type=N'SCHEMA',\n @level0name=@SchemaOwner, \n @level1type=N'TABLE',\n @level1name=@TableName, \n @level2type=N'COLUMN',\n @level2name=@ColumnName\n\n\nGO\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/770/" ]
18,290
<p>Within Ruby on Rails applications database.yml is a plain text file that stores database credentials.</p> <p>When I deploy my Rails applications I have an after deploy callback in my Capistrano recipe that creates a symbolic link within the application's /config directory to the database.yml file. The file itself is stored in a separate directory that's outside the standard Capistrano /releases directory structure. I chmod 400 the file so it's only readable by the user who created it.</p> <ul> <li>Is this sufficient to lock it down? If not, what else do you do?</li> <li>Is anyone encrypting their database.yml files?</li> </ul>
[ { "answer_id": 1001484, "author": "Olly", "author_id": 1174, "author_profile": "https://Stackoverflow.com/users/1174", "pm_score": 5, "selected": false, "text": "production:\n adapter: mysql\n database: my_db\n username: db_user\n password: <%= begin IO.read(\"/home/my_deploy_user/.db\") rescue \"\" end %>\n" }, { "answer_id": 62938385, "author": "Rajkaran Mishra", "author_id": 5946118, "author_profile": "https://Stackoverflow.com/users/5946118", "pm_score": 2, "selected": false, "text": "config/credentials.yml.enc $ EDITOR=nano rails credentials:edit\n\nsecret_key_base: 3b7cd727ee24e8444053437c36cc66c3\nproduction_dbpwd: my-secret-password\n Rails.application.credentials production:\n adapter: mysql\n database: my_db\n username: db_user\n password: <%= Rails.application.credentials.production_dbpwd %>\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
18,291
<p>I'm wondering how the few Delphi users here are doing unit testing, if any? Is there anything that integrates with the IDE that you've found works well? If not, what tools are you using and do you have or know of example mini-projects that demonstrate how it all works?</p> <h3>Update:</h3> <p>I forgot to mention that I'm using BDS 2006 Pro, though I occasionally drop into Delphi 7, and of course others may be using other versions.</p>
[ { "answer_id": 5653865, "author": "Arnaud Bouchez", "author_id": 458259, "author_profile": "https://Stackoverflow.com/users/458259", "pm_score": 3, "selected": false, "text": "type\n TTestNumbersAdding = class(TSynTestCase)\n published\n procedure TestIntegerAdd;\n procedure TestDoubleAdd;\n end;\n\nprocedure TTestNumbersAdding.TestDoubleAdd;\nvar A,B: double;\n i: integer;\nbegin\n for i := 1 to 1000 do\n begin\n A := Random;\n B := Random;\n CheckSame(A+B,Adding(A,B));\n end;\nend;\n C:\\Dev\\lib\\SQLite3\\exe\\TestSQL3.exe 0.0.0.0 (2011-04-13)\nHost=Laptop User=MyName CPU=2*0-15-1027 OS=2.3=5.1.2600 Wow64=0 Freq=3579545\nTSynLogTest 1.13 2011-04-13 05:40:25\n\n20110413 05402559 fail TTestLowLevelCommon(00B31D70) Low level common: TDynArray \"\" stack trace 0002FE0B SynCommons.TDynArray.Init (15148) 00036736 SynCommons.Test64K (18206) 0003682F SynCommons.TTestLowLevelCommon._TDynArray (18214) 000E9C94 TestSQL3 (163) \n procedure TSynTestsLogged.Failed(const msg: string; aTest: TSynTestCase);\nbegin\n inherited;\n with TestCase[fCurrentMethod] do\n fLogFile.Log(sllFail,'%: % \"%\"',\n [Ident,TestName[fCurrentMethodIndex],msg],aTest);\nend;\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461/" ]
18,326
<p>I like a bit of TiVo hacking in spare time - TiVo uses a Linux variant and <a href="http://wiki.tcl.tk/299" rel="nofollow noreferrer">TCL</a>. I'd like to write TCL scripts on my Windows laptop, test them and then FTP them over to my TiVo.</p> <p>Can I have a recommendation for a TCL debugging environment for Windows, please?</p>
[ { "answer_id": 471599, "author": "ctd", "author_id": 58133, "author_profile": "https://Stackoverflow.com/users/58133", "pm_score": 0, "selected": false, "text": "proc bp {{s {}}} {\n if ![info exists ::bp_skip] {\n set ::bp_skip [list]\n } elseif {[lsearch -exact $::bp_skip $s]>=0} return\n if [catch {info level -1} who] {set who ::}\n while 1 {\n puts -nonewline \"$who/$s> \"; flush stdout\n gets stdin line\n if {$line==\"c\"} {puts \"continuing..\"; break}\n if {$line==\"i\"} {set line \"info locals\"}\n catch {uplevel 1 $line} res\n puts $res\n }\n }\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1223/" ]
18,391
<p>There is previous little on the google on this subject other than people asking this very same question.</p> <p>How would I get started writing my own firewall?</p> <p>I'm looking to write one for the windows platform but I would also be interested in this information for other operating systems too. ­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 18398, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 2, "selected": false, "text": "connect listens" }, { "answer_id": 312142, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 3, "selected": false, "text": "netsh netfilter iptables" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ]
18,407
<p>If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?</p> <p>I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.</p> <p>I know I could do something like this: </p> <pre><code>int baseCase = 5; bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5; </code></pre> <p>I'm curious to see if I could do something more like this:</p> <pre><code>int baseCase = 5; bool testResult = baseCase == (3 | 7 | 12 | 5); </code></pre> <p>Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.</p> <p><strong>UPDATE:</strong><br> I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.</p> <p>Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of: </p> <pre><code>new List&lt;int&gt;(new int[] { 3, 6, 7, 1 }).Contains(5); </code></pre>
[ { "answer_id": 18416, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 5, "selected": true, "text": " bool b = new int[] { 3,7,12,5 }.Contains(5);\n" }, { "answer_id": 153037, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "bool b = ((IList<int>)new int[] { 3, 7, 12, 5 }).Contains(5); \n private readonly IList<int> someIntegers = new int[] { 1,2,3,4,5 };\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
18,413
<p>I have a column of data that contains a percentage range as a string that I'd like to convert to a number so I can do easy comparisons.</p> <p>Possible values in the string:</p> <pre><code>'&lt;5%' '5-10%' '10-15%' ... '95-100%' </code></pre> <p>I'd like to convert this in my select where clause to just the first number, 5, 10, 15, etc. so that I can compare that value to a passed in "at least this" value.</p> <p>I've tried a bunch of variations on substring, charindex, convert, and replace, but I still can't seem to get something that works in all combinations.</p> <p>Any ideas?</p>
[ { "answer_id": 18451, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 0, "selected": false, "text": "\"<5%\" => 0\n\"5-10%\" => 5\n\"95-100%\" => 95\n SELECT \"5-10%\" + 0 AS foo ...\n" }, { "answer_id": 18454, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<5% 5-10% <5% 5-10% >= <" }, { "answer_id": 18471, "author": "Martin", "author_id": 770, "author_profile": "https://Stackoverflow.com/users/770", "pm_score": 4, "selected": true, "text": "SELECT substring(replace(interest , '<',''), patindex('%[0-9]%',replace(interest , '<','')), patindex('%[^0-9]%',replace(interest, '<',''))-1) FROM table1 \n" }, { "answer_id": 18485, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "Create table rangeLookup(\n rangeID int -- or rangeCD or not at all\n ,rangeLabel varchar(50)\n ,LowValue int--real or whatever\n ,HighValue int \n)\n normalize your input by replacing all your crazy charecters.\n replace(replace(rangeLabel,\"%\",\"\"),\"<\",\"\")\n --This will entail many nested replace statments.\n\nAdd a CASE and CHARINDEX to look for a space if there is none you have your number\n else use your substring to take everything before the first \" \".\n -- theses steps are wrapped around the previous step.\n" }, { "answer_id": 18503, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 2, "selected": false, "text": "select cast(replace(replace(replace(interest,'<',''),'%',''),'-','.0') as numeric) test\nfrom table1 where interest is not null\n" }, { "answer_id": 18522, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "DECLARE @TEST varchar(10)\n\nset @Test = '<5%'\n--set @Test = '5-10%'\n--set @Test = '10-15%'\n--set @Test = '95-100%'\n\nSelect CASE WHEN \nSubstring(@TEST,1,1) = '<' \nTHEN \n0\nELSE \nCONVERT(integer,SUBSTRING(@TEST,1,CHARINDEX('-',@TEST)-1))\nEND\nAS LowerBound\n,\nCASE WHEN \nSubstring(@TEST,1,1) = '<'\nTHEN\nCONVERT(integer,Substring(@TEST,2,CHARINDEX('%',@TEST)-2))\nELSE\nCONVERT(integer,Substring(@TEST,CHARINDEX('-',@TEST)+1,CHARINDEX('%',@TEST)-CHARINDEX('-',@TEST)-1))\nEND\nAS UpperBound\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097/" ]
18,418
<p>When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:</p> <pre><code>for name in names: if name[-5:] == 'Smith': names.remove(name) </code></pre> <p>I usually end up doing something like this:</p> <pre><code>toremove = [] for name in names: if name[-5:] == 'Smith': toremove.append(name) for name in toremove: names.remove(name) del toremove </code></pre> <p>This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one? </p> <p>How about one that works with dictionaries?</p>
[ { "answer_id": 18430, "author": "pottedmeat", "author_id": 2120, "author_profile": "https://Stackoverflow.com/users/2120", "pm_score": 2, "selected": false, "text": "names = filter(lambda x: x[-5:] != \"Smith\", names);\n" }, { "answer_id": 18431, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 2, "selected": false, "text": "names = ['mike', 'dave', 'jim']\nfilter(lambda x: x != 'mike', names)\n['dave', 'jim']\n" }, { "answer_id": 18433, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 3, "selected": false, "text": "list = [x for x in list if x[-5:] != \"smith\"]\n" }, { "answer_id": 18435, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 7, "selected": true, "text": "filter names = filter(lambda name: name[-5:] != \"Smith\", names) names = [name for name in names if name[-5:] != \"Smith\"] True" }, { "answer_id": 18497, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 2, "selected": false, "text": "names = ['Jones', 'Vai', 'Smith', 'Perez']\n\nitem = 0\nwhile item <> len(names):\n name = names [item]\n if name=='Smith':\n names.remove(name)\n else:\n item += 1\n\nprint names\n" }, { "answer_id": 163925, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 1, "selected": false, "text": "names = ['Jones', 'Vai', 'Smith', 'Perez', 'Smith']\n\ntoremove = []\nfor pos, name in enumerate(names):\n if name[-5:] == 'Smith':\n toremove.append(pos)\nfor pos in sorted(toremove, reverse=True):\n del(names[pos])\n\nprint names\n" }, { "answer_id": 171848, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 2, "selected": false, "text": "for name in names[:]:\n if name[-5:] == 'Smith':\n names.remove(name)\n names[:] names" }, { "answer_id": 178735, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": ">>> {i : chr(65+i) for i in range(4)}\n >>> dict([(i, chr(65+i)) for i in range(4)])\n dict([(key, name) for key, name in some_dictionary.iteritems if name[-5:] != 'Smith'])\n" }, { "answer_id": 181062, "author": "Xavier Martinez-Hidalgo", "author_id": 25996, "author_profile": "https://Stackoverflow.com/users/25996", "pm_score": 5, "selected": false, "text": "for name in reversed(names):\n if name[-5:] == 'Smith':\n names.remove(name)\n filter [:]" }, { "answer_id": 1857734, "author": "CashMonkey", "author_id": 226094, "author_profile": "https://Stackoverflow.com/users/226094", "pm_score": 1, "selected": false, "text": "toRemove = set([]) \nfor item in mySet: \n if item is unwelcome: \n toRemove.add(item) \nmySets = mySet - toRemove \n" }, { "answer_id": 4639748, "author": "Edward Loper", "author_id": 222329, "author_profile": "https://Stackoverflow.com/users/222329", "pm_score": 5, "selected": false, "text": ">>> names = [name for name in names if name[-5:] != \"Smith\"] # <-- slower\n >>> names[:] = (name for name in names if name[-5:] != \"Smith\") # <-- faster\n" }, { "answer_id": 9979995, "author": "valyala", "author_id": 274937, "author_profile": "https://Stackoverflow.com/users/274937", "pm_score": 2, "selected": false, "text": "def filter_inplace(func, original_list):\n \"\"\" Filters the original_list in-place.\n\n Removes elements from the original_list for which func() returns False.\n\n Algrithm's computational complexity is O(N), where N is the size\n of the original_list.\n \"\"\"\n\n # Compact the list in-place.\n new_list_size = 0\n for item in original_list:\n if func(item):\n original_list[new_list_size] = item\n new_list_size += 1\n\n # Remove trailing items from the list.\n tail_size = len(original_list) - new_list_size\n while tail_size:\n original_list.pop()\n tail_size -= 1\n\n\na = [1, 2, 3, 4, 5, 6, 7]\n\n# Remove even numbers from a in-place.\nfilter_inplace(lambda x: x & 1, a)\n\n# Prints [1, 3, 5, 7]\nprint a\n def filter_inplace(func, original_list):\n \"\"\" Filters the original_list inplace.\n\n Removes elements from the original_list for which function returns False.\n\n Algrithm's computational complexity is O(N), where N is the size\n of the original_list.\n \"\"\"\n original_list[:] = [item for item in original_list if func(item)]\n" }, { "answer_id": 15434620, "author": "Cory Gross", "author_id": 1359785, "author_profile": "https://Stackoverflow.com/users/1359785", "pm_score": 1, "selected": false, "text": "filter_inplace comparisonFunc True def filter_inplace(conditionFunc, list, reversed=False):\n index = 0\n while index < len(list):\n item = list[index]\n\n shouldRemove = not conditionFunc(item)\n if reversed: shouldRemove = not shouldRemove\n\n if shouldRemove:\n list.remove(item)\n else:\n index += 1\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
18,419
<p>I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label.</p> <p>Here is what I've done so far: Embed code for the font at the top of my MXML in script:</p> <pre><code>[Embed("assets/trebuc.ttf", fontName="TrebuchetMS")] public var trebuchetMSFont:Class; </code></pre> <p>In my init function</p> <pre><code>//register the font. Font.registerFont(trebuchetMSFont); </code></pre> <p>The combobox's mxml:</p> <pre><code>&lt;mx:ComboBox id="FilterFields" styleName="FilterDropdown" left="10" right="10" top="10" fontSize="14"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:Label fontSize="10" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:ComboBox&gt; </code></pre> <p>And a style that I wrote to get the fonts applied to the combo-box:</p> <pre><code>.FilterDropdown { embedFonts: true; fontFamily: TrebuchetMS; fontWeight: normal; fontSize: 12; } </code></pre> <p>The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font. ­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 18463, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\" creationComplete=\"fx.play([panel])\">\n <mx:Style>\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n }\n\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n fontWeight: bold;\n }\n\n @font-face {\n src: local(\"Arial\");\n fontFamily: ArialEm;\n font-style: italic;\n }\n </mx:Style>\n <mx:XML id=\"items\" xmlns=\"\">\n <items>\n <item label=\"Item 1\" />\n <item label=\"Item 2\" />\n <item label=\"Item 3\" />\n </items>\n </mx:XML>\n <mx:Panel id=\"panel\" x=\"10\" y=\"10\" width=\"250\" height=\"200\" layout=\"absolute\">\n <mx:ComboBox fontFamily=\"ArialEm\" x=\"35\" y=\"10\" dataProvider=\"{items.item}\" labelField=\"@label\"></mx:ComboBox>\n </mx:Panel>\n <mx:Fade id=\"fx\" alphaFrom=\"0\" alphaTo=\"1\" duration=\"5000\" />\n</mx:Application>\n" }, { "answer_id": 749676, "author": "Marcus Stade", "author_id": 68909, "author_profile": "https://Stackoverflow.com/users/68909", "pm_score": 1, "selected": false, "text": "<mx:Label id=\"percentage\" text=\"{progress} %\" truncateToFit=\"false\">\n <mx:filters>\n <mx:BlurFilter blurX=\"0\" blurY=\"0\" />\n </mx:filters>\n</mx:Label>\n" }, { "answer_id": 2311050, "author": "akash", "author_id": 278704, "author_profile": "https://Stackoverflow.com/users/278704", "pm_score": 0, "selected": false, "text": "var htm = $('#comboboxId').find('option:selected').html();\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290/" ]
18,432
<p>I am developing a Reporting Services solution for a DOD website. Frequently I'll have a report and want to have as a parameter the Service (in addition to other similar mundane, but repetitive parameters like Fiscal Year, Data Effective Date, etc). Basically everything I've seen of SSRS 2005 says it can't be done... but I personally refuse to believe that MS would be so stupid/naive/short-sited to leave something like sharing datasets out of reporting entirely.</p> <p>Is there a clunky (or not so clunky way) to share datasets and still keep the reporting server happy? Will SSRS2008 do this?</p> <p>EDIT:</p> <p>I guess I worded that unclearly. I have a stack of reports. Since I'm in a DoD environment, one common parameter for these reports is Service (army, navy, etc. for those non US users). Since "Business rules" cause me to not be able to use stored procedures; is there a way I can make 1 dataset and link to it from the various reports? Will Reporting 2008 support something like this? I'm getting sick of re-typing the same query in a bunch of reports.</p>
[ { "answer_id": 18502, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 2, "selected": true, "text": "A B A A B" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ]
18,449
<p>For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?</p> <p>Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?</p>
[ { "answer_id": 18607, "author": "Željko Živković", "author_id": 1926, "author_profile": "https://Stackoverflow.com/users/1926", "pm_score": 5, "selected": true, "text": "SET timezone = 'Europe/London';\n //Returns the offset (time difference) between Greenwich Mean Time (GMT) \n//and local time of Date object, in minutes.\nvar offset = new Date().getTimezoneOffset(); \ndocument.cookie = 'timezoneOffset=' + escape(offset);\n" }, { "answer_id": 2550233, "author": "sbeam", "author_id": 125875, "author_profile": "https://Stackoverflow.com/users/125875", "pm_score": 2, "selected": false, "text": "define('TZ', 'US/Pacific');\n....\nif (defined('TZ') && function_exists('date_default_timezone_set')) {\n date_default_timezone_set(TZ);\n $mdb2->exec(\"SET SESSION time_zone = \" . $mdb2->quote(date('P')));\n}\n" }, { "answer_id": 42049223, "author": "Ravi Tiwari", "author_id": 1948917, "author_profile": "https://Stackoverflow.com/users/1948917", "pm_score": 0, "selected": false, "text": "ini_set(\"date.timezone\", \"America/Los_Angeles\"); date_default_timezone_set(\"America/Los_Angeles\"); SET GLOBAL time_zone = 'America/Los_Angeles';" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056/" ]
18,450
<p>Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, <em>really</em> compatible enough to just take of and run already written code for Microsoft's runtime?</p>
[ { "answer_id": 18488, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "Path.Separator \"\\\" Environment.NewLine \"\\n\"" }, { "answer_id": 19021501, "author": "head_thrash", "author_id": 750347, "author_profile": "https://Stackoverflow.com/users/750347", "pm_score": 3, "selected": false, "text": "* Assertion: should not be reached at sgen-scan-object.h:111\n\nStacktrace:\n\n\nNative stacktrace:\n\n mono() [0x4ab0ad]\n /lib/x86_64-linux-gnu/libpthread.so.0(+0xfcb0) [0x2b61ea830cb0]\n /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x35) [0x2b61eaa74425]\n /lib/x86_64-linux-gnu/libc.so.6(abort+0x17b) [0x2b61eaa77b8b]\n mono() [0x62b49d]\n mono() [0x62b5d6]\n mono() [0x5d4f84]\n mono() [0x5cb0af]\n mono() [0x5cb2cc]\n mono() [0x5cccfd]\n mono() [0x5cd944]\n mono() [0x5d12b6]\n mono(mono_gc_collect+0x28) [0x5d16f8]\n mono(mono_domain_finalize+0x7c) [0x59fb1c]\n mono() [0x596ef0]\n mono() [0x616f13]\n mono() [0x626ee0]\n /lib/x86_64-linux-gnu/libpthread.so.0(+0x7e9a) [0x2b61ea828e9a]\n /lib/x86_64-linux-gnu/libc.so.6(clone+0x6d) [0x2b61eab31ccd]\n mono: mini-amd64.c:492: amd64_patch: Assertion `0' failed.\nStacktrace:\nat <unknown> <0xffffffff>\nat System.Collections.Generic.Dictionary`2.Init (int,System.Collections.Generic.IEqualityComparer`1<TKey>) [0x00012] in /home/bkmz/my/mono/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:264\nat System.Collections.Generic.Dictionary`2..ctor () [0x00006] in /home/bkmz/my/mono/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:222\nat System.Security.Cryptography.CryptoConfig/CryptoHandler..ctor (System.Collections.Generic.IDictionary`2<string, System.Type>,System.Collections.Generic.IDictionary`2<string, string>) [0x00014] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/Crypto\nConfig.cs:582\nat System.Security.Cryptography.CryptoConfig.LoadConfig (string,System.Collections.Generic.IDictionary`2<string, System.Type>,System.Collections.Generic.IDictionary`2<string, string>) [0x00013] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/CryptoCo\nnfig.cs:473\nat System.Security.Cryptography.CryptoConfig.Initialize () [0x00697] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:457\nat System.Security.Cryptography.CryptoConfig.CreateFromName (string,object[]) [0x00027] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:495\nat System.Security.Cryptography.CryptoConfig.CreateFromName (string) [0x00000] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:484\nat System.Security.Cryptography.RandomNumberGenerator.Create (string) [0x00000] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs:59\nat System.Security.Cryptography.RandomNumberGenerator.Create () [0x00000] in /home/bkmz/my/mono/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs:53\nat System.Guid.NewGuid () [0x0001e] in /home/bkmz/my/mono/mcs/class/corlib/System/Guid.cs:492\n Assertion at mini.c:3783, condition `code' not met\nStacktrace:\nat <unknown> <0xffffffff>\nat System.IO.StreamReader.ReadBuffer () [0x00012] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.IO/StreamReader.cs:394\nat System.IO.StreamReader.Peek () [0x00006] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.IO/StreamReader.cs:429\nat Mono.Xml.SmallXmlParser.Peek () [0x00000] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/Mono.Xml/SmallXmlParser.cs:271\nat Mono.Xml.SmallXmlParser.Parse (System.IO.TextReader,Mono.Xml.SmallXmlParser/IContentHandler) [0x00020] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/Mono.Xml/SmallXmlParser.cs:346\nat System.Security.Cryptography.CryptoConfig.LoadConfig (string,System.Collections.Generic.IDictionary`2<string, System.Type>,System.Collections.Generic.IDictionary`2<string, string>) [0x00021] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptog\nraphy/CryptoConfig.cs:475\nat System.Security.Cryptography.CryptoConfig.Initialize () [0x00697] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:457\nat System.Security.Cryptography.CryptoConfig.CreateFromName (string,object[]) [0x00027] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:495\nat System.Security.Cryptography.CryptoConfig.CreateFromName (string) [0x00000] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs:484\nat System.Security.Cryptography.RandomNumberGenerator.Create (string) [0x00000] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs:59\nat System.Security.Cryptography.RandomNumberGenerator.Create () [0x00000] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Security.Cryptography/RandomNumberGenerator.cs:53\nat System.Guid.NewGuid () [0x0001e] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System/Guid.cs:483\nat System.Runtime.Remoting.RemotingServices.NewUri () [0x00020] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs:356\nat System.Runtime.Remoting.RemotingServices.Marshal (System.MarshalByRefObject,string,System.Type) [0x000ba] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System.Runtime.Remoting/RemotingServices.cs:329\nat System.AppDomain.GetMarshalledDomainObjRef () [0x00000] in /usr/src/redhat/BUILD/mono-3.0.3/mcs/class/corlib/System/AppDomain.cs:1363\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018/" ]
18,460
<p>What is the best way to authorize all users to one single page in a asp.net website.</p> <p>For except the login page and one other page, I deny all users from viewing pages in the website. </p> <p>How do you make this page accessible to all users?</p>
[ { "answer_id": 18469, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "<location path=\"Login.aspx\">\n <system.web>\n <authorization>\n <allow users =\"*\" />\n </authorization>\n </system.web>\n</location>\n\n<location path=\"ManagementFolder\">\n <system.web>\n <authorization>\n <allow roles =\"Administrator, Manager\" />\n </authorization>\n </system.web>\n</location>\n" }, { "answer_id": 18475, "author": "Louis Salin", "author_id": 160, "author_profile": "https://Stackoverflow.com/users/160", "pm_score": -1, "selected": false, "text": "<RequiresLogin()> _ \n<RequiresPermission(\"process\")> _\nPartial Class DesignReviewEditProgressPage\n Inherits MyPage 'which inherits System.Web.UI.Page and deal with logins itself\n\n ...\nEnd Class\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2172/" ]
18,465
<p>In .Net you can read a string value into another data type using either <code>&lt;datatype&gt;.parse</code> or <code>Convert.To&lt;DataType&gt;</code>. </p> <p>I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate. </p> <p>So - which way is best in what type of circumstances?</p>
[ { "answer_id": 18523, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": true, "text": "Convert.ToXXX() .Parse() .TryParse() //o is actually a boxed int\nobject o = 12345;\n\n//unboxes it\nint castVal = (int) 12345;\n\n//o is a boxed enum\nobject o = MyEnum.ValueA;\n\n//this will get the underlying int of ValueA\nint convVal = Convert.ToInt32( o );\n\n//now we have a string\nstring s = \"12345\";\n\n//this will throw an exception if s can't be parsed\nint parseVal = int.Parse( s );\n\n//alternatively:\nint tryVal;\nif( int.TryParse( s, out tryVal ) ) {\n //do something with tryVal \n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ]
18,524
<p>I have a list of integers, <code>List&lt;Integer&gt;</code> and I'd like to convert all the integer objects into Strings, thus finishing up with a new <code>List&lt;String&gt;</code>.</p> <p>Naturally, I could create a new <code>List&lt;String&gt;</code> and loop through the list calling <code>String.valueOf()</code> for each integer, but I was wondering if there was a better (read: <em>more automatic</em>) way of doing it?</p>
[ { "answer_id": 18529, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 7, "selected": true, "text": "List<Integer> oldList = ...\n/* Specify the size of the list up front to prevent resizing. */\nList<String> newList = new ArrayList<>(oldList.size());\nfor (Integer myInt : oldList) { \n newList.add(String.valueOf(myInt)); \n}\n" }, { "answer_id": 18558, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 3, "selected": false, "text": "List<Integer> oldList = ...\nList<String> newList = new ArrayList<String>(oldList.size());\n\nfor (Integer myInt : oldList) { \n newList.add(myInt.toString()); \n}\n" }, { "answer_id": 18595, "author": "Mike Polen", "author_id": 212, "author_profile": "https://Stackoverflow.com/users/212", "pm_score": 3, "selected": false, "text": "public static String valueOf(Object obj) {\n return (obj == null) ? \"null\" : obj.toString();\n}\n" }, { "answer_id": 19191, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 5, "selected": false, "text": "public class IntegerToStringTransformer implements Transformer<Integer, String> {\n public String transform(final Integer i) {\n return (i == null ? null : i.toString());\n }\n}\n CollectionUtils.collect(\n collectionOfIntegers, \n new IntegerToStringTransformer(), \n newCollectionOfStrings);\n" }, { "answer_id": 33028, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "String.valueOf(Object) int Integer.toString() String.valueOf(Object) NullPointerException List java.util.ArrayList" }, { "answer_id": 57566, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": " List<Integer> ints = ...;\n String all = new ArrayList<Integer>(ints).toString();\n String[] split = all.substring(1, all.length()-1).split(\", \");\n List<String> strs = Arrays.asList(split);\n" }, { "answer_id": 61663, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 0, "selected": false, "text": "import java.util.concurrent.forkjoin.*;\n\nprivate final ForkJoinExecutor executor = new ForkJoinPool();\n...\nList<Integer> ints = ...;\nList<String> strs =\n ParallelArray.create(ints.size(), Integer.class, executor)\n .withMapping(new Ops.Op<Integer,String>() { public String op(Integer i) {\n return String.valueOf(i);\n }})\n .all()\n .asList();\n .withMapping(#(Integer i) String.valueOf(i))\n" }, { "answer_id": 1227099, "author": "Ben Lings", "author_id": 41012, "author_profile": "https://Stackoverflow.com/users/41012", "pm_score": 7, "selected": false, "text": "transform import com.google.common.collect.Lists;\nimport com.google.common.base.Functions\n\nList<Integer> integers = Arrays.asList(1, 2, 3, 4);\n\nList<String> strings = Lists.transform(integers, Functions.toStringFunction());\n List transform Functions.toStringFunction() NullPointerException" }, { "answer_id": 2396243, "author": "Mario Fusco", "author_id": 112779, "author_profile": "https://Stackoverflow.com/users/112779", "pm_score": 2, "selected": false, "text": "List<Integer> ints = asList(1, 2, 3, 4);\nIterator<String> stringIterator = convertIterator(ints, new Converter<Integer, String> {\n public String convert(Integer i) { return Integer.toString(i); }\n}\n" }, { "answer_id": 5781802, "author": "Garrett Hall", "author_id": 554988, "author_profile": "https://Stackoverflow.com/users/554988", "pm_score": 3, "selected": false, "text": "List<String> strings = Arrays.asList(list.toString().replaceAll(\"\\\\[(.*)\\\\]\", \"$1\").split(\", \"));\n" }, { "answer_id": 12322903, "author": "Rodney P. Barbati", "author_id": 1588303, "author_profile": "https://Stackoverflow.com/users/1588303", "pm_score": -1, "selected": false, "text": "class Value {\n Integer value;\n public Integer getInt()\n {\n return value;\n }\n public String getString()\n {\n return String.valueOf(value);\n }\n}\n" }, { "answer_id": 23024375, "author": "Hakanai", "author_id": 138513, "author_profile": "https://Stackoverflow.com/users/138513", "pm_score": 7, "selected": false, "text": "import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n//...\n\nList<Integer> integers = Arrays.asList(1, 2, 3, 4);\nList<String> strings = integers.stream().map(Object::toString)\n .collect(Collectors.toList());\n List<String> strings = integers.stream().map(Object::toString)\n .collect(Collectors.toUnmodifiableList());\n map" }, { "answer_id": 23293398, "author": "sandrozbinden", "author_id": 1039517, "author_profile": "https://Stackoverflow.com/users/1039517", "pm_score": 3, "selected": false, "text": "List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);\nList<String> strings = Lists.transform(numbers, number -> String.valueOf(number));\n" }, { "answer_id": 45944083, "author": "nagendra547", "author_id": 7438973, "author_profile": "https://Stackoverflow.com/users/7438973", "pm_score": 0, "selected": false, "text": "It will be really good to remove the integer from the List<Integer> and free\nthe space, once it's added to List<String>.\n List<Integer> oldList = new ArrayList<>();\n oldList.add(12);\n oldList.add(14);\n .......\n .......\n\n List<String> newList = new ArrayList<String>(oldList.size());\n Iterator<Integer> itr = oldList.iterator();\n while(itr.hasNext()){\n newList.add(itr.next().toString());\n itr.remove();\n }\n" }, { "answer_id": 56666320, "author": "Mahesh Yadav", "author_id": 8350518, "author_profile": "https://Stackoverflow.com/users/8350518", "pm_score": 2, "selected": false, "text": "List<String> stringList = integerList.stream().map((Object s)->String.valueOf(s)).collect(Collectors.toList())\n" }, { "answer_id": 61236486, "author": "Solubris", "author_id": 1505487, "author_profile": "https://Stackoverflow.com/users/1505487", "pm_score": 2, "selected": false, "text": " List<Integer> oldList = Arrays.asList(1, 2, 3, 4, 5);\n List<String> newList = new ArrayList<>(oldList.size());\n oldList.forEach(e -> newList.add(String.valueOf(e)));\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/916/" ]
18,533
<p>I've found myself increasingly unsatisfied with the DataSet/DataTable/DataRow paradigm in .Net, mostly because it's often a couple of steps more complicated than what I really want to do. In cases where I'm binding to controls, DataSets are fine. But in other cases, there seems to be a fair amount of mental overhead.</p> <p>I've played a bit with SqlDataReader, and that seems to be good for simple jaunts through a select, but I feel like there may be some other models lurking in .Net that are useful to learn more about. I feel like all of the help I find on this just uses DataSet by default. Maybe that and DataReader really are the best options.</p> <p>I'm not looking for a best/worst breakdown, just curious what my options are and what experiences you've had with them. Thanks!</p> <p>-Eric Sipple</p>
[ { "answer_id": 18581, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "IEnumerable<T>" }, { "answer_id": 18630, "author": "Mike", "author_id": 785, "author_profile": "https://Stackoverflow.com/users/785", "pm_score": 0, "selected": false, "text": "DataTable DataSet DataSet Convert.ToDecimal(dt.Rows[i][\"blah\"].ToString())" }, { "answer_id": 103414, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "sonic.exe generate /server [servername] /db [dbname] /out [outputPathForCSfiles] /generatedNamespace [myNamespace] /useSPs true /removeUnderscores true\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
18,538
<p>I'd like some sorthand for this:</p> <pre><code>Map rowToMap(row) { def rowMap = [:]; row.columns.each{ rowMap[it.name] = it.val } return rowMap; } </code></pre> <p>given the way the GDK stuff is, I'd expect to be able to do something like:</p> <pre><code>Map rowToMap(row) { row.columns.collectMap{ [it.name,it.val] } } </code></pre> <p>but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?</p>
[ { "answer_id": 18981, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 1, "selected": false, "text": "ArrayList.metaClass.collectMap = {Closure callback->\n def map = [:]\n delegate.each {\n def r = callback.call(it)\n map[r[0]] = r[1]\n }\n return map\n}\n assert [\"foo\":\"oof\", \"42\":\"24\", \"bar\":\"rab\"] ==\n [\"foo\", \"42\", \"bar\"].collectMap { return [it, it.reverse()] }\n List.metaClass.enableGlobally()\n (0..2).collectMap{[it, it*2]}\n" }, { "answer_id": 18996, "author": "ogrodnek", "author_id": 2210, "author_profile": "https://Stackoverflow.com/users/2210", "pm_score": 3, "selected": false, "text": " map = Maps.uniqueIndex(list, Functions.identity());\n" }, { "answer_id": 19077, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 3, "selected": false, "text": "def collectMap = {Closure callback->\n def map = [:]\n delegate.each {\n def r = callback.call(it)\n map[r[0]] = r[1]\n }\n return map\n}\nExpandoMetaClass.enableGlobally()\nCollection.metaClass.collectMap = collectMap\nMap.metaClass.collectMap = collectMap\n [1:2, 3:4].collectMap{[it.value, it.key]} == [2:1, 4:3]\n [1,2].collectMap{[it,it]} == [1:1, 2:2]\n Object[].metaClass.collectMap = collectMap\n" }, { "answer_id": 149818, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 0, "selected": false, "text": "// setup\nclass Pair { \n String k; \n String v; \n public Pair(def k, def v) { this.k = k ; this.v = v; }\n}\ndef list = [ new Pair('a', 'b'), new Pair('c', 'd') ]\n\n// the idea\ndef map = [:]\nlist.each{ it -> map.putAt(it.k, it.v) }\n\n// verify\nprintln map['c']\n" }, { "answer_id": 198614, "author": "Robert Fischer", "author_id": 27561, "author_profile": "https://Stackoverflow.com/users/27561", "pm_score": 5, "selected": false, "text": "columns.inject([:]) { memo, entry ->\n memo[entry.name] = entry.val\n return memo\n}\n class PropertyMapCategory {\n static Map mapProperty(Collection c, String keyParam, String valParam) {\n return c.inject([:]) { memo, entry ->\n memo[entry[keyParam]] = entry[valParam]\n return memo\n }\n }\n}\n use(PropertyMapCategory) {\n println columns.mapProperty('name', 'val')\n}\n" }, { "answer_id": 5645413, "author": "epidemian", "author_id": 581845, "author_profile": "https://Stackoverflow.com/users/581845", "pm_score": 8, "selected": true, "text": "collectEntries collectMap Map rowToMap(row) {\n row.columns.collectEntries{[it.name, it.val]}\n}\n inject Map rowToMap(row) {\n row.columns.inject([:]) {map, col -> map << [(col.name): col.val]}\n}\n + <<" }, { "answer_id": 42689859, "author": "Abbas Gadhia", "author_id": 638670, "author_profile": "https://Stackoverflow.com/users/638670", "pm_score": 3, "selected": false, "text": "collectEntries def names = ['Foo', 'Bar']\ndef firstAlphabetVsName = names.collectEntries {[it.charAt(0), it]} // [F:Foo, B:Bar]\n groupBy def names = ['Foo', 'Bar', 'Fooey']\ndef firstAlphabetVsNames = names.groupBy { it.charAt(0) } // [F:[Foo, Fooey], B:[Bar]]\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
18,584
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c">How do I calculate someone&#39;s age in C#?</a> </p> </blockquote> <p>Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age? </p> <p>Maybe</p> <pre><code>DateTime dt1 = DateTime.Now; TimeSpan dt2; dt2 = dt1.Subtract(new DateTime(1975, 12, 01)); double year = dt2.TotalDays / 365; </code></pre> <p>The result of year is 32.77405678074</p> <p>Could this code be OK?</p>
[ { "answer_id": 18610, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "Dim myAge AS Integer = DateTime.Now.year - BirthDate.year\nIf Birthdate.month < DateTime.Now.Month _\nOrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then\nMyAge -= 1\nEND IF\n" }, { "answer_id": 10765738, "author": "Devarajan.T", "author_id": 1418924, "author_profile": "https://Stackoverflow.com/users/1418924", "pm_score": 0, "selected": false, "text": "int ag1;\nstring st, ag;\nvoid agecal()\n{\n st = TextBox4.Text;\n DateTimeFormatInfo dtfi = new DateTimeFormatInfo();\n dtfi.ShortDatePattern = \"MM/dd/yyyy\";\n dtfi.DateSeparator = \"/\";\n DateTime dt = Convert.ToDateTime(st, dtfi);\n ag1 = int.Parse(dt.Year.ToString());\n int years = DateTime.Now.Year - ag1;\n ag = years.ToString();\n TextBox3.Text = ag.ToString();\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
18,585
<h3>Update: Solved, with code</h3> <p><a href="https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056">I got it working, see my answer below for the code...</a></p> <h3>Original Post</h3> <p>As Tundey pointed out in <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456">his answer</a> to my <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">last question</a>, you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? <a href="http://www.codeproject.com/KB/cs/UserSettings.aspx" rel="nofollow noreferrer">This tutorial</a> says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:</p> <pre><code>public Size RestoreSize { get { if (this.WindowState == FormWindowState.Normal) { return this.Size; } else { return this.RestoreBounds.Size; } } set { ... } } </code></pre> <p>But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).</p>
[ { "answer_id": 18659, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key =\"FormHeight\" value=\"500\" />\n <add key =\"FormWidth\" value=\"200\"/>\n </appSettings>\n</configuration>\n private void Form1_Load(object sender, EventArgs e)\n {\n string height = ConfigurationManager.AppSettings[\"FormHeight\"];\n int h = int.Parse(height);\n string width = ConfigurationManager.AppSettings[\"FormWidth\"];\n int w = int.Parse(width);\n this.Size = new Size(h, w);\n }\n" }, { "answer_id": 19056, "author": "Brian Jorgensen", "author_id": 229, "author_profile": "https://Stackoverflow.com/users/229", "pm_score": 5, "selected": true, "text": "// Consider this code public domain. If you want, you can even tell\n// your boss, attractive women, or the other guy in your cube that\n// you wrote it. Enjoy!\n\nusing System;\nusing System.Windows.Forms;\nusing System.ComponentModel;\nusing System.Drawing;\n\nnamespace Utilities\n{\n public class RestorableForm : Form, INotifyPropertyChanged\n {\n // We invoke this event when the binding needs to be updated.\n public event PropertyChangedEventHandler PropertyChanged;\n\n // This stores the last window position and state\n private WindowRestoreStateInfo windowRestoreState;\n\n // Now we define the property that we will bind to our settings.\n [Browsable(false)] // Don't show it in the Properties list\n [SettingsBindable(true)] // But do enable binding to settings\n public WindowRestoreStateInfo WindowRestoreState\n {\n get { return windowRestoreState; }\n set\n {\n windowRestoreState = value;\n if (PropertyChanged != null)\n {\n // If anybody's listening, let them know the\n // binding needs to be updated:\n PropertyChanged(this,\n new PropertyChangedEventArgs(\"WindowRestoreState\"));\n }\n }\n }\n\n protected override void OnClosing(CancelEventArgs e)\n {\n WindowRestoreState = new WindowRestoreStateInfo();\n WindowRestoreState.Bounds\n = WindowState == FormWindowState.Normal ?\n Bounds : RestoreBounds;\n WindowRestoreState.WindowState = WindowState;\n\n base.OnClosing(e);\n }\n\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n if (WindowRestoreState != null)\n {\n Bounds = ConstrainToScreen(WindowRestoreState.Bounds);\n WindowState = WindowRestoreState.WindowState;\n }\n }\n\n // This helper class stores both position and state.\n // That way, we only have to set one binding.\n public class WindowRestoreStateInfo\n {\n Rectangle bounds;\n public Rectangle Bounds\n {\n get { return bounds; }\n set { bounds = value; }\n }\n\n FormWindowState windowState;\n public FormWindowState WindowState\n {\n get { return windowState; }\n set { windowState = value; }\n }\n }\n\n private Rectangle ConstrainToScreen(Rectangle bounds)\n {\n Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds);\n Rectangle workingArea = screen.WorkingArea;\n\n int width = Math.Min(bounds.Width, workingArea.Width);\n int height = Math.Min(bounds.Height, workingArea.Height);\n\n // mmm....minimax\n int left = Math.Min(workingArea.Right - width,\n Math.Max(bounds.Left, workingArea.Left));\n int top = Math.Min(workingArea.Bottom - height,\n Math.Max(bounds.Top, workingArea.Top));\n\n return new Rectangle(left, top, width, height);\n }\n }\n}\n" }, { "answer_id": 260707, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 3, "selected": false, "text": "private void MyForm_FormClosing(object sender, FormClosingEventArgs e)\n{\n Properties.Settings.Default.MyState = this.WindowState;\n if (this.WindowState == FormWindowState.Normal)\n {\n Properties.Settings.Default.MySize = this.Size;\n Properties.Settings.Default.MyLoc = this.Location;\n }\n else\n {\n Properties.Settings.Default.MySize = this.RestoreBounds.Size;\n Properties.Settings.Default.MyLoc = this.RestoreBounds.Location;\n }\n Properties.Settings.Default.Save();\n}\n\nprivate void MyForm_Load(object sender, EventArgs e)\n{\n this.Size = Properties.Settings.Default.MySize;\n this.Location = Properties.Settings.Default.MyLoc;\n this.WindowState = Properties.Settings.Default.MyState;\n} \n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229/" ]
18,608
<p>I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.</p> <p>For example purposes, consider the following namespaces and classes:</p> <pre><code>namespace Protocol { public abstract class Message { } public abstract class Driver { } } namespace Protocol.Tcp { public class TcpMessage : Message { } public class TcpDriver : Driver { } } namespace Protocol.Ftp { public class FtpMessage : Message { } public class FtpDriver : Driver { } } </code></pre> <p>What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.</p>
[ { "answer_id": 18616, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "using System.Data;\nusing System.Data.Sql;\n" }, { "answer_id": 18625, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "Protocol\n Protocol.Driver\n" }, { "answer_id": 124146, "author": "Ronnie", "author_id": 193, "author_profile": "https://Stackoverflow.com/users/193", "pm_score": 1, "selected": false, "text": "Message Driver" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
18,617
<p>How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?</p>
[ { "answer_id": 18623, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 8, "selected": true, "text": "tomcat/conf/server.xml" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
18,632
<p>For debugging purposes in a somewhat closed system, I have to output text to a file.</p> <p>Does anyone know of a tool that runs on windows (console based or not) that detects changes to a file and outputs them in real-time?</p>
[ { "answer_id": 18648, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 1, "selected": false, "text": "public static void Main()\n{\nRun();\n\n}\n\n[PermissionSet(SecurityAction.Demand, Name=\"FullTrust\")]\npublic static void Run()\n{\n string[] args = System.Environment.GetCommandLineArgs();\n\n // If a directory is not specified, exit program.\n if(args.Length != 2)\n {\n // Display the proper way to call the program.\n Console.WriteLine(\"Usage: Watcher.exe (directory)\");\n return;\n }\n\n // Create a new FileSystemWatcher and set its properties.\n FileSystemWatcher watcher = new FileSystemWatcher();\n watcher.Path = args[1];\n /* Watch for changes in LastAccess and LastWrite times, and \n the renaming of files or directories. */\n watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite \n | NotifyFilters.FileName | NotifyFilters.DirectoryName;\n // Only watch text files.\n watcher.Filter = \"*.txt\";\n\n // Add event handlers.\n watcher.Changed += new FileSystemEventHandler(OnChanged);\n watcher.Created += new FileSystemEventHandler(OnChanged);\n watcher.Deleted += new FileSystemEventHandler(OnChanged);\n watcher.Renamed += new RenamedEventHandler(OnRenamed);\n\n // Begin watching.\n watcher.EnableRaisingEvents = true;\n\n // Wait for the user to quit the program.\n Console.WriteLine(\"Press \\'q\\' to quit the sample.\");\n while(Console.Read()!='q');\n}\n\n// Define the event handlers.\nprivate static void OnChanged(object source, FileSystemEventArgs e)\n{\n // Specify what is done when a file is changed, created, or deleted.\n Console.WriteLine(\"File: \" + e.FullPath + \" \" + e.ChangeType);\n}\n\nprivate static void OnRenamed(object source, RenamedEventArgs e)\n{\n // Specify what is done when a file is renamed.\n Console.WriteLine(\"File: {0} renamed to {1}\", e.OldFullPath, e.FullPath);\n}\n" }, { "answer_id": 18670, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": false, "text": "Get-Content someFile.txt -wait\n" }, { "answer_id": 18672, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "tail -n 50 -f whatever.log\n tail -n 50 -f whatever.log | grep Error\n" }, { "answer_id": 39616, "author": "Mike Schall", "author_id": 4231, "author_profile": "https://Stackoverflow.com/users/4231", "pm_score": 6, "selected": false, "text": "Get-Content someFile.txt -wait\n Get-Content web.log -wait | where { $_ -match \"ERROR\" }\n" }, { "answer_id": 34039182, "author": "Chaitanya", "author_id": 2031870, "author_profile": "https://Stackoverflow.com/users/2031870", "pm_score": 1, "selected": false, "text": "@echo off\n\nset LoggingFile=C:\\foo.txt\nset lineNr=0\n\n:while1\nfor /f \"usebackq delims=\" %%i in (`more +%lineNr% %LoggingFile%`) DO (\n echo %%i\n set /a lineNr+=1\n REM Have an appropriate stop condition here by checking i\n)\ngoto :while1\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011/" ]
18,655
<p>I really need to see some honest, thoughtful debate on the merits of the currently accepted <strong><em>enterprise application</em></strong> design paradigm.</p> <p>I am not convinced that entity objects should exist.</p> <p>By entity objects I mean the typical things we tend to build for our applications, like "Person", "Account", "Order", etc.</p> <p>My current design philosophy is this:</p> <ul> <li>All database access must be accomplished via stored procedures.</li> <li>Whenever you need data, call a stored procedure and iterate over a SqlDataReader or the rows in a DataTable</li> </ul> <p>(Note: I have also built enterprise applications with Java EE, java folks please substitute the equvalent for my .NET examples)</p> <p>I am not anti-OO. I write lots of classes for different purposes, just not entities. I will admit that a large portion of the classes I write are static helper classes.</p> <p>I am not building toys. I'm talking about large, high volume transactional applications deployed across multiple machines. Web applications, windows services, web services, b2b interaction, you name it.</p> <p>I have used OR Mappers. I have written a few. I have used the Java EE stack, CSLA, and a few other equivalents. I have not only used them but actively developed and maintained these applications in production environments.</p> <p>I have come to the battle-tested conclusion that entity objects are getting in our way, and our lives would be <em>so</em> much easier without them.</p> <p>Consider this simple example: you get a support call about a certain page in your application that is not working correctly, maybe one of the fields is not being persisted like it should be. With my model, the developer assigned to find the problem opens <em>exactly 3 files</em>. An ASPX, an ASPX.CS and a SQL file with the stored procedure. The problem, which might be a missing parameter to the stored procedure call, takes minutes to solve. But with any entity model, you will invariably fire up the debugger, start stepping through code, and you may end up with 15-20 files open in Visual Studio. By the time you step down to the bottom of the stack, you forgot where you started. We can only keep so many things in our heads at one time. Software is incredibly complex without adding any unnecessary layers.</p> <p>Development complexity and troubleshooting are just one side of my gripe.</p> <p>Now let's talk about scalability.</p> <p>Do developers realize that each and every time they write or modify any code that interacts with the database, they need to do a throrough analysis of the exact impact on the database? And not just the development copy, I mean a mimic of production, so you can see that the additional column you now require for your object just invalidated the current query plan and a report that was running in 1 second will now take 2 minutes, just because you added a single column to the select list? And it turns out that the index you now require is so big that the DBA is going to have to modify the physical layout of your files?</p> <p>If you let people get too far away from the physical data store with an abstraction, they will create havoc with an application that needs to scale.</p> <p>I am not a zealot. I can be convinced if I am wrong, and maybe I am, since there is such a strong push towards Linq to Sql, ADO.NET EF, Hibernate, Java EE, etc. Please think through your responses, if I am missing something I really want to know what it is, and why I should change my thinking.</p> <p><strong><em>[Edit]</em></strong></p> <p>It looks like this question is suddenly active again, so now that we have the new comment feature I have commented directly on several answers. Thanks for the replies, I think this is a healthy discussion.</p> <p>I probably should have been more clear that I am talking about enterprise applications. I really can't comment on, say, a game that's running on someone's desktop, or a mobile app.</p> <p>One thing I have to put up here at the top in response to several similar answers: orthogonality and separation of concerns often get cited as reasons to go entity/ORM. Stored procedures, to me, are the best example of separation of concerns that I can think of. If you disallow all other access to the database, other than via stored procedures, you could in theory redesign your entire data model and not break any code, so long as you maintained the inputs and outputs of the stored procedures. They are a perfect example of programming by contract (just so long as you avoid "select *" and document the result sets).</p> <p>Ask someone who's been in the industry for a long time and has worked with long-lived applications: how many application and UI layers have come and gone while a database has lived on? How hard is it to tune and refactor a database when there are 4 or 5 different persistence layers generating SQL to get at the data? You can't change anything! ORMs or any code that generates SQL <strong><em>lock your database in stone</em></strong>.</p>
[ { "answer_id": 280560, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 2, "selected": false, "text": "void exportOrder(Order order, String fileName){...};\n" }, { "answer_id": 397093, "author": "Renaud Bompuis", "author_id": 3811, "author_profile": "https://Stackoverflow.com/users/3811", "pm_score": 2, "selected": false, "text": "dll" }, { "answer_id": 37897538, "author": "magnus", "author_id": 1420752, "author_profile": "https://Stackoverflow.com/users/1420752", "pm_score": 0, "selected": false, "text": "grep ^col /var/log/bim-sync | sed 's/.*alt:\\([0-9]\\{1,\\}\\).*/\\1/g | xargs -I replstr bim-transcoder replstr RegisterBirth BirthRegistered insert into person..." } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
18,661
<p>Is it possible to get UI text from an external application in C#. </p> <p>In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI.</p> <p>I assume there is some accessibility API (e.g. meant for screen readers) that allows this. </p> <p>Edit: Currently looking into using something like the <a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx" rel="nofollow noreferrer">Managed Spy App</a> but would still appreciate any other leads.</p>
[ { "answer_id": 18698, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 3, "selected": false, "text": "[DllImport(\"user32.dll\")]\npublic static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text);\n\nSystem.Text.StringBuilder text = new System.Text.StringBuilder(255) ; // or length from call with GETTEXTLENGTH\nint RetVal = Win32.SendMessage( hWnd , WM_GETTEXT, text.Capacity, text);\n" }, { "answer_id": 18855, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 2, "selected": false, "text": "const int WM_GETTEXT = 0x0D;\nconst int WM_GETTEXTLENGTH = 0x0E;\n" }, { "answer_id": 11042272, "author": "BrendanMcK", "author_id": 660175, "author_profile": "https://Stackoverflow.com/users/660175", "pm_score": 3, "selected": false, "text": "// compile as:\n// csc file.cs /r:UIAutomationClient.dll /r:UIAutomationTypes.dll /r:WindowsBase.dll\nusing System.Windows.Automation;\nusing System.Windows.Forms;\nusing System;\n\nclass Test\n{\n public static void Main()\n {\n // Get element under pointer. You can also get an AutomationElement from a\n // HWND handle, or by navigating the UI tree.\n System.Drawing.Point pt = Cursor.Position;\n AutomationElement el = AutomationElement.FromPoint(new System.Windows.Point(pt.X, pt.Y));\n // Prints its name - often the context, but would be corresponding label text for editable controls. Can also get the type of control, location, and other properties.\n Console.WriteLine( el.Current.Name );\n }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ]
18,671
<p>Anyone know a quick easy way to migrate a SQLite3 database to MySQL?</p>
[ { "answer_id": 25860, "author": "Richard Gourlay", "author_id": 2674, "author_profile": "https://Stackoverflow.com/users/2674", "pm_score": 4, "selected": false, "text": "sqlite3 sample.db .dump > dump.sql\n mysql -p -u root -h 127.0.0.1 test < dump.sql\n BEGIN TRANSACTION;\n...\nCOMMIT;\n BEGIN;\n...\nCOMMIT;\n" }, { "answer_id": 87531, "author": "Shalmanese", "author_id": 14559, "author_profile": "https://Stackoverflow.com/users/14559", "pm_score": 7, "selected": false, "text": "CREATE TABLE/INSERT INTO \"table_name\" CREATE TABLE/INSERT INTO table_name INSERT INTO INSERT INTO 't' 'f' 1 0 INSERT INTO AUTOINCREMENT AUTO_INCREMENT #! /usr/bin/perl\n\nwhile ($line = <>){\n if (($line !~ /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){\n \n if ($line =~ /CREATE TABLE \\\"([a-z_]*)\\\"(.*)/i){\n $name = $1;\n $sub = $2;\n $sub =~ s/\\\"//g;\n $line = \"DROP TABLE IF EXISTS $name;\\nCREATE TABLE IF NOT EXISTS $name$sub\\n\";\n }\n elsif ($line =~ /INSERT INTO \\\"([a-z_]*)\\\"(.*)/i){\n $line = \"INSERT INTO $1$2\\n\";\n $line =~ s/\\\"/\\\\\\\"/g;\n $line =~ s/\\\"/\\'/g;\n }else{\n $line =~ s/\\'\\'/\\\\\\'/g;\n }\n $line =~ s/([^\\\\'])\\'t\\'(.)/$1THIS_IS_TRUE$2/g;\n $line =~ s/THIS_IS_TRUE/1/g;\n $line =~ s/([^\\\\'])\\'f\\'(.)/$1THIS_IS_FALSE$2/g;\n $line =~ s/THIS_IS_FALSE/0/g;\n $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;\n print $line;\n }\n}\n" }, { "answer_id": 1067365, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 6, "selected": false, "text": "dump_for_mysql.py sqlite3 sample.db .dump | python dump_for_mysql.py > dump.sql\n #!/usr/bin/env python\n\nimport re\nimport fileinput\n\ndef this_line_is_useless(line):\n useless_es = [\n 'BEGIN TRANSACTION',\n 'COMMIT',\n 'sqlite_sequence',\n 'CREATE UNIQUE INDEX',\n 'PRAGMA foreign_keys=OFF',\n ]\n for useless in useless_es:\n if re.search(useless, line):\n return True\n\ndef has_primary_key(line):\n return bool(re.search(r'PRIMARY KEY', line))\n\nsearching_for_end = False\nfor line in fileinput.input():\n if this_line_is_useless(line):\n continue\n\n # this line was necessary because '');\n # would be converted to \\'); which isn't appropriate\n if re.match(r\".*, ''\\);\", line):\n line = re.sub(r\"''\\);\", r'``);', line)\n\n if re.match(r'^CREATE TABLE.*', line):\n searching_for_end = True\n\n m = re.search('CREATE TABLE \"?(\\w*)\"?(.*)', line)\n if m:\n name, sub = m.groups()\n line = \"DROP TABLE IF EXISTS %(name)s;\\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\\n\"\n line = line % dict(name=name, sub=sub)\n else:\n m = re.search('INSERT INTO \"(\\w*)\"(.*)', line)\n if m:\n line = 'INSERT INTO %s%s\\n' % m.groups()\n line = line.replace('\"', r'\\\"')\n line = line.replace('\"', \"'\")\n line = re.sub(r\"([^'])'t'(.)\", \"\\1THIS_IS_TRUE\\2\", line)\n line = line.replace('THIS_IS_TRUE', '1')\n line = re.sub(r\"([^'])'f'(.)\", \"\\1THIS_IS_FALSE\\2\", line)\n line = line.replace('THIS_IS_FALSE', '0')\n\n # Add auto_increment if it is not there since sqlite auto_increments ALL\n # primary keys\n if searching_for_end:\n if re.search(r\"integer(?:\\s+\\w+)*\\s*PRIMARY KEY(?:\\s+\\w+)*\\s*,\", line):\n line = line.replace(\"PRIMARY KEY\", \"PRIMARY KEY AUTO_INCREMENT\")\n # replace \" and ' with ` because mysql doesn't like quotes in CREATE commands \n if line.find('DEFAULT') == -1:\n line = line.replace(r'\"', r'`').replace(r\"'\", r'`')\n else:\n parts = line.split('DEFAULT')\n parts[0] = parts[0].replace(r'\"', r'`').replace(r\"'\", r'`')\n line = 'DEFAULT'.join(parts)\n\n # And now we convert it back (see above)\n if re.match(r\".*, ``\\);\", line):\n line = re.sub(r'``\\);', r\"'');\", line)\n\n if searching_for_end and re.match(r'.*\\);', line):\n searching_for_end = False\n\n if re.match(r\"CREATE INDEX\", line):\n line = re.sub('\"', '`', line)\n\n if re.match(r\"AUTOINCREMENT\", line):\n line = re.sub(\"AUTOINCREMENT\", \"AUTO_INCREMENT\", line)\n\n print line,\n" }, { "answer_id": 1498558, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\n line = re.sub(r\"([^'])'t'(.)\", \"\\1THIS_IS_TRUE\\2\", line)\n line = line.replace('THIS_IS_TRUE', '1')\n line = re.sub(r\"([^'])'f'(.)\", \"\\1THIS_IS_FALSE\\2\", line)\n line = line.replace('THIS_IS_FALSE', '0')\n" }, { "answer_id": 2543241, "author": "daicoden", "author_id": 266456, "author_profile": "https://Stackoverflow.com/users/266456", "pm_score": 1, "selected": false, "text": "tinyint([0-9]*) \n sed 's/ tinyint(1*) / boolean/g ' |\nsed 's/ tinyint([0|2-9]*) / integer /g' |\n Table.find(:all, :conditions => {:column => 1 }).each { |t| t.column = true }.each(&:save)\nTable.find(:all, :conditions => {:column => 0 }).each { |t| t.column = false}.each(&:save)\n" }, { "answer_id": 6410922, "author": "alekwisnia", "author_id": 268662, "author_profile": "https://Stackoverflow.com/users/268662", "pm_score": 2, "selected": false, "text": "sqlite3 your_sql3_database.db .dump | python ./dump.py > your_dump_name.sql\ncat your_dump_name.sql | sed '1d' | mysql --user=your_mysql_user --default-character-set=utf8 your_mysql_db -p \n" }, { "answer_id": 7747146, "author": "Dashamir Hoxha", "author_id": 992353, "author_profile": "https://Stackoverflow.com/users/992353", "pm_score": 3, "selected": false, "text": "aptitude install sqlfairy libdbd-sqlite3-perl\n\nsqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t MySQL --add-drop-table > mysql-ten-sq.sql\nsqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t Dumper --use-same-auth > sqlite2mysql-dumper.pl\nchmod +x sqlite2mysql-dumper.pl\n./sqlite2mysql-dumper.pl --help\n./sqlite2mysql-dumper.pl --add-truncate --mysql-loadfile > mysql-dump.sql\nsed -e 's/LOAD DATA INFILE/LOAD DATA LOCAL INFILE/' -i mysql-dump.sql\n\necho 'drop database `ten-sq`' | mysql -p -u root\necho 'create database `ten-sq` charset utf8' | mysql -p -u root\nmysql -p -u root -D ten-sq < mysql-ten-sq.sql\nmysql -p -u root -D ten-sq < mysql-dump.sql\n" }, { "answer_id": 10067099, "author": "mgribov", "author_id": 1320864, "author_profile": "https://Stackoverflow.com/users/1320864", "pm_score": -1, "selected": false, "text": "echo \".dump\" | sqlite3 /tmp/db.sqlite > db.sql\n" }, { "answer_id": 13365275, "author": "Snips", "author_id": 451544, "author_profile": "https://Stackoverflow.com/users/451544", "pm_score": 3, "selected": false, "text": "Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql\n Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql\n #!/usr/bin/env python\n\nimport re\nimport fileinput\n\ndef this_line_is_useless(line):\n useless_es = [\n 'BEGIN TRANSACTION',\n 'COMMIT',\n 'sqlite_sequence',\n 'CREATE UNIQUE INDEX', \n 'PRAGMA foreign_keys=OFF'\n ]\n for useless in useless_es:\n if re.search(useless, line):\n return True\n\ndef has_primary_key(line):\n return bool(re.search(r'PRIMARY KEY', line))\n\nsearching_for_end = False\nfor line in fileinput.input():\n if this_line_is_useless(line): continue\n\n # this line was necessary because ''); was getting\n # converted (inappropriately) to \\');\n if re.match(r\".*, ''\\);\", line):\n line = re.sub(r\"''\\);\", r'``);', line)\n\n if re.match(r'^CREATE TABLE.*', line):\n searching_for_end = True\n\n m = re.search('CREATE TABLE \"?([A-Za-z_]*)\"?(.*)', line)\n if m:\n name, sub = m.groups()\n line = \"DROP TABLE IF EXISTS %(name)s;\\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\\n\"\n line = line % dict(name=name, sub=sub)\n line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')\n line = line.replace('UNIQUE','')\n line = line.replace('\"','')\n else:\n m = re.search('INSERT INTO \"([A-Za-z_]*)\"(.*)', line)\n if m:\n line = 'INSERT INTO %s%s\\n' % m.groups()\n line = line.replace('\"', r'\\\"')\n line = line.replace('\"', \"'\")\n line = re.sub(r\"(?<!')'t'(?=.)\", r\"1\", line)\n line = re.sub(r\"(?<!')'f'(?=.)\", r\"0\", line)\n\n # Add auto_increment if it's not there since sqlite auto_increments ALL\n # primary keys\n if searching_for_end:\n if re.search(r\"integer(?:\\s+\\w+)*\\s*PRIMARY KEY(?:\\s+\\w+)*\\s*,\", line):\n line = line.replace(\"PRIMARY KEY\", \"PRIMARY KEY AUTO_INCREMENT\")\n # replace \" and ' with ` because mysql doesn't like quotes in CREATE commands\n\n # And now we convert it back (see above)\n if re.match(r\".*, ``\\);\", line):\n line = re.sub(r'``\\);', r\"'');\", line)\n\n if searching_for_end and re.match(r'.*\\);', line):\n searching_for_end = False\n\n if re.match(r\"CREATE INDEX\", line):\n line = re.sub('\"', '`', line)\n\n print line,\n" }, { "answer_id": 17009384, "author": "Martin Thoma", "author_id": 562769, "author_profile": "https://Stackoverflow.com/users/562769", "pm_score": 3, "selected": false, "text": "moose@pc08$ sqlite3 mySqliteDatabase.db .dump > myTemporarySQLFile.sql\n moose@pc08$ mysql -u <username> -p\nEnter password:\n....\nmysql> use somedb;\nDatabase changed\nmysql> source myTemporarySQLFile.sql;\n mysql -u root -p somedb < myTemporarySQLFile.sql\n -p mysql -u root -pYOURPASS somedb < myTemporarySQLFile.sql\n" }, { "answer_id": 32243979, "author": "Klemen Tusar", "author_id": 1040452, "author_profile": "https://Stackoverflow.com/users/1040452", "pm_score": 3, "selected": false, "text": "int(11) varchar(300) #!/usr/bin/env python3\n\n__author__ = \"Klemen Tušar\"\n__email__ = \"[email protected]\"\n__copyright__ = \"GPL\"\n__version__ = \"1.0.1\"\n__date__ = \"2015-09-12\"\n__status__ = \"Production\"\n\nimport os.path, sqlite3, mysql.connector\nfrom mysql.connector import errorcode\n\n\nclass SQLite3toMySQL:\n \"\"\"\n Use this class to transfer an SQLite 3 database to MySQL.\n\n NOTE: Requires MySQL Connector/Python 2.0.4 or higher (https://dev.mysql.com/downloads/connector/python/)\n \"\"\"\n def __init__(self, **kwargs):\n self._properties = kwargs\n self._sqlite_file = self._properties.get('sqlite_file', None)\n if not os.path.isfile(self._sqlite_file):\n print('SQLite file does not exist!')\n exit(1)\n self._mysql_user = self._properties.get('mysql_user', None)\n if self._mysql_user is None:\n print('Please provide a MySQL user!')\n exit(1)\n self._mysql_password = self._properties.get('mysql_password', None)\n if self._mysql_password is None:\n print('Please provide a MySQL password')\n exit(1)\n self._mysql_database = self._properties.get('mysql_database', 'transfer')\n self._mysql_host = self._properties.get('mysql_host', 'localhost')\n\n self._mysql_integer_type = self._properties.get('mysql_integer_type', 'int(11)')\n self._mysql_string_type = self._properties.get('mysql_string_type', 'varchar(300)')\n\n self._sqlite = sqlite3.connect(self._sqlite_file)\n self._sqlite.row_factory = sqlite3.Row\n self._sqlite_cur = self._sqlite.cursor()\n\n self._mysql = mysql.connector.connect(\n user=self._mysql_user,\n password=self._mysql_password,\n host=self._mysql_host\n )\n self._mysql_cur = self._mysql.cursor(prepared=True)\n try:\n self._mysql.database = self._mysql_database\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_BAD_DB_ERROR:\n self._create_database()\n else:\n print(err)\n exit(1)\n\n def _create_database(self):\n try:\n self._mysql_cur.execute(\"CREATE DATABASE IF NOT EXISTS `{}` DEFAULT CHARACTER SET 'utf8'\".format(self._mysql_database))\n self._mysql_cur.close()\n self._mysql.commit()\n self._mysql.database = self._mysql_database\n self._mysql_cur = self._mysql.cursor(prepared=True)\n except mysql.connector.Error as err:\n print('_create_database failed creating databse {}: {}'.format(self._mysql_database, err))\n exit(1)\n\n def _create_table(self, table_name):\n primary_key = ''\n sql = 'CREATE TABLE IF NOT EXISTS `{}` ( '.format(table_name)\n self._sqlite_cur.execute('PRAGMA table_info(\"{}\")'.format(table_name))\n for row in self._sqlite_cur.fetchall():\n column = dict(row)\n sql += ' `{name}` {type} {notnull} {auto_increment}, '.format(\n name=column['name'],\n type=self._mysql_string_type if column['type'].upper() == 'TEXT' else self._mysql_integer_type,\n notnull='NOT NULL' if column['notnull'] else 'NULL',\n auto_increment='AUTO_INCREMENT' if column['pk'] else ''\n )\n if column['pk']:\n primary_key = column['name']\n sql += ' PRIMARY KEY (`{}`) ) ENGINE = InnoDB CHARACTER SET utf8'.format(primary_key)\n try:\n self._mysql_cur.execute(sql)\n self._mysql.commit()\n except mysql.connector.Error as err:\n print('_create_table failed creating table {}: {}'.format(table_name, err))\n exit(1)\n\n def transfer(self):\n self._sqlite_cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\")\n for row in self._sqlite_cur.fetchall():\n table = dict(row)\n # create the table\n self._create_table(table['name'])\n # populate it\n print('Transferring table {}'.format(table['name']))\n self._sqlite_cur.execute('SELECT * FROM \"{}\"'.format(table['name']))\n columns = [column[0] for column in self._sqlite_cur.description]\n try:\n self._mysql_cur.executemany(\"INSERT IGNORE INTO `{table}` ({fields}) VALUES ({placeholders})\".format(\n table=table['name'],\n fields=('`{}`, ' * len(columns)).rstrip(' ,').format(*columns),\n placeholders=('%s, ' * len(columns)).rstrip(' ,')\n ), (tuple(data) for data in self._sqlite_cur.fetchall()))\n self._mysql.commit()\n except mysql.connector.Error as err:\n print('_insert_table_data failed inserting data into table {}: {}'.format(table['name'], err))\n exit(1)\n print('Done!')\n\n\ndef main():\n \"\"\" For use in standalone terminal form \"\"\"\n import sys, argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--sqlite-file', dest='sqlite_file', default=None, help='SQLite3 db file')\n parser.add_argument('--mysql-user', dest='mysql_user', default=None, help='MySQL user')\n parser.add_argument('--mysql-password', dest='mysql_password', default=None, help='MySQL password')\n parser.add_argument('--mysql-database', dest='mysql_database', default=None, help='MySQL host')\n parser.add_argument('--mysql-host', dest='mysql_host', default='localhost', help='MySQL host')\n parser.add_argument('--mysql-integer-type', dest='mysql_integer_type', default='int(11)', help='MySQL default integer field type')\n parser.add_argument('--mysql-string-type', dest='mysql_string_type', default='varchar(300)', help='MySQL default string field type')\n args = parser.parse_args()\n\n if len(sys.argv) == 1:\n parser.print_help()\n exit(1)\n\n converter = SQLite3toMySQL(\n sqlite_file=args.sqlite_file,\n mysql_user=args.mysql_user,\n mysql_password=args.mysql_password,\n mysql_database=args.mysql_database,\n mysql_host=args.mysql_host,\n mysql_integer_type=args.mysql_integer_type,\n mysql_string_type=args.mysql_string_type\n )\n converter.transfer()\n\nif __name__ == '__main__':\n main()\n" }, { "answer_id": 33796909, "author": "soulseekah", "author_id": 482864, "author_profile": "https://Stackoverflow.com/users/482864", "pm_score": 0, "selected": false, "text": "<?php\n$sq = new SQLite3( 'sqlite3.db' );\n\n$tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type=\"table\"' );\n\nwhile ( $table = $tables->fetchArray() ) {\n $table = current( $table );\n $result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );\n\n if ( strpos( $table, 'sqlite' ) !== false )\n continue;\n\n printf( \"-- %s\\n\", $table );\n while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {\n $values = array_map( function( $value ) {\n return sprintf( \"'%s'\", mysql_real_escape_string( $value ) );\n }, array_values( $row ) );\n printf( \"INSERT INTO `%s` VALUES( %s );\\n\", $table, implode( ', ', $values ) );\n }\n}\n" }, { "answer_id": 38414534, "author": "NavidIvanian", "author_id": 5162480, "author_profile": "https://Stackoverflow.com/users/5162480", "pm_score": 2, "selected": false, "text": ".csv" }, { "answer_id": 45062019, "author": "Mihkorz", "author_id": 1908693, "author_profile": "https://Stackoverflow.com/users/1908693", "pm_score": 4, "selected": false, "text": "objlist = ModelObject.objects.using('sqlite').all()\n\nfor obj in objlist:\n obj.save(using='mysql')\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534/" ]
18,676
<p>I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.</p> <p>How would I do that?</p>
[ { "answer_id": 18680, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 7, "selected": true, "text": "CInt(Math.Ceiling(Rnd() * n)) + 1\n" }, { "answer_id": 18684, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "Public Function RandomNumber(ByVal n As Integer) As Integer\n 'initialize random number generator\n Dim r As New Random(System.DateTime.Now.Millisecond)\n Return r.Next(1, n)\nEnd Function\n" }, { "answer_id": 18687, "author": "Joseph Sturtevant", "author_id": 317, "author_profile": "https://Stackoverflow.com/users/317", "pm_score": 5, "selected": false, "text": "Dim MyMin As Integer = 1, MyMax As Integer = 5, My1stRandomNumber As Integer, My2ndRandomNumber As Integer\n\n' Create a random number generator\nDim Generator As System.Random = New System.Random()\n\n' Get a random number >= MyMin and <= MyMax\nMy1stRandomNumber = Generator.Next(MyMin, MyMax + 1) ' Note: Next function returns numbers _less than_ max, so pass in max + 1 to include max as a possible value\n\n' Get another random number (don't create a new generator, use the same one)\nMy2ndRandomNumber = Generator.Next(MyMin, MyMax + 1)\n" }, { "answer_id": 2677819, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 6, "selected": false, "text": "Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n Dim Generator As System.Random = New System.Random()\n Return Generator.Next(Min, Max)\nEnd Function\n Random Dim randoms(1000) As Integer\nFor i As Integer = 0 to randoms.Length - 1\n randoms(i) = GetRandom(1, 100)\nNext\n Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer\n ' by making Generator static, we preserve the same instance '\n ' (i.e., do not create new instances with the same seed over and over) '\n ' between calls '\n Static Generator As System.Random = New System.Random()\n Return Generator.Next(Min, Max)\nEnd Function\n Non-static: 70 Static: 70\nNon-static: 70 Static: 46\nNon-static: 70 Static: 58\nNon-static: 70 Static: 19\nNon-static: 70 Static: 79\nNon-static: 70 Static: 24\nNon-static: 70 Static: 14\nNon-static: 70 Static: 46\nNon-static: 70 Static: 82\nNon-static: 70 Static: 31\nNon-static: 70 Static: 25\nNon-static: 70 Static: 8\nNon-static: 70 Static: 76\nNon-static: 70 Static: 74\nNon-static: 70 Static: 84\nNon-static: 70 Static: 39\nNon-static: 70 Static: 30\nNon-static: 70 Static: 55\nNon-static: 70 Static: 49\nNon-static: 70 Static: 21\nNon-static: 70 Static: 99\nNon-static: 70 Static: 15\nNon-static: 70 Static: 83\nNon-static: 70 Static: 26\nNon-static: 70 Static: 16\nNon-static: 70 Static: 75\n" }, { "answer_id": 13181177, "author": "Sergiu", "author_id": 1791928, "author_profile": "https://Stackoverflow.com/users/1791928", "pm_score": -1, "selected": false, "text": "Function xrand() As Long\n Dim r1 As Long = Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & Now.Millisecond\n Dim RAND As Long = Math.Max(r1, r1 * 2)\n Return RAND\nEnd Function\n" }, { "answer_id": 19567863, "author": "Rogala", "author_id": 2025711, "author_profile": "https://Stackoverflow.com/users/2025711", "pm_score": 1, "selected": false, "text": "dim i = GetRandom(1, 1715)\ndim o = GetRandom(1, 1715)\n Public Function GetRandom(ByVal min as Integer, ByVal max as Integer) as Integer\n Static staticRandomGenerator As New System.Random\n max += 1\n Return staticRandomGenerator.Next(If(min > max, max, min), If(min > max, min, max))\nEnd Function\n" }, { "answer_id": 21461274, "author": "Shawn Kovac", "author_id": 2840284, "author_profile": "https://Stackoverflow.com/users/2840284", "pm_score": 2, "selected": false, "text": "Private Function GenRandomInt(min As Int32, max As Int32) As Int32\n Static staticRandomGenerator As New System.Random\n Return staticRandomGenerator.Next(min, max + 1)\nEnd Function\n Int32 Integer ''' <summary>\n''' Generates a random Integer with any (inclusive) minimum or (inclusive) maximum values, with full range of Int32 values.\n''' </summary>\n''' <param name=\"inMin\">Inclusive Minimum value. Lowest possible return value.</param>\n''' <param name=\"inMax\">Inclusive Maximum value. Highest possible return value.</param>\n''' <returns></returns>\n''' <remarks></remarks>\nPrivate Function GenRandomInt(inMin As Int32, inMax As Int32) As Int32\n Static staticRandomGenerator As New System.Random\n If inMin > inMax Then Dim t = inMin : inMin = inMax : inMax = t\n If inMax < Int32.MaxValue Then Return staticRandomGenerator.Next(inMin, inMax + 1)\n ' now max = Int32.MaxValue, so we need to work around Microsoft's quirk of an exclusive max parameter.\n If inMin > Int32.MinValue Then Return staticRandomGenerator.Next(inMin - 1, inMax) + 1 ' okay, this was the easy one.\n ' now min and max give full range of integer, but Random.Next() does not give us an option for the full range of integer.\n ' so we need to use Random.NextBytes() to give us 4 random bytes, then convert that to our random int.\n Dim bytes(3) As Byte ' 4 bytes, 0 to 3\n staticRandomGenerator.NextBytes(bytes) ' 4 random bytes\n Return BitConverter.ToInt32(bytes, 0) ' return bytes converted to a random Int32\nEnd Function\n" }, { "answer_id": 27227997, "author": "Binny", "author_id": 1821206, "author_profile": "https://Stackoverflow.com/users/1821206", "pm_score": 0, "selected": false, "text": "Dim rnd As Random = New Random\nrnd.Next(n)\n" }, { "answer_id": 32043953, "author": "achar", "author_id": 3915785, "author_profile": "https://Stackoverflow.com/users/3915785", "pm_score": 2, "selected": false, "text": "Dim Generator As System.Random = New System.Random()\n Public Function GetRandom(myGenerator As System.Random, ByVal Min As Integer, ByVal Max As Integer) As Integer\n'min is inclusive, max is exclusive (dah!)\nReturn myGenerator.Next(Min, Max + 1)\nEnd Function\n" }, { "answer_id": 35563352, "author": "Wais", "author_id": 2514566, "author_profile": "https://Stackoverflow.com/users/2514566", "pm_score": 3, "selected": false, "text": "Randomize()\n Dim value As Integer = CInt(Int((6 * Rnd()) + 1))\n" }, { "answer_id": 39948531, "author": "Zibri", "author_id": 236062, "author_profile": "https://Stackoverflow.com/users/236062", "pm_score": 0, "selected": false, "text": "Public NotInheritable Class VBMath\n ' Methods\n Private Shared Function GetTimer() As Single\n Dim now As DateTime = DateTime.Now\n Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))\n End Function\n\n Public Shared Sub Randomize()\n Dim timer As Single = VBMath.GetTimer\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)\n num3 = (((num3 And &HFFFF) Xor (num3 >> &H10)) << 8)\n rndSeed = ((rndSeed And -16776961) Or num3)\n projectData.m_rndSeed = rndSeed\n End Sub\n\n Public Shared Sub Randomize(ByVal Number As Double)\n Dim num2 As Integer\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n If BitConverter.IsLittleEndian Then\n num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)\n Else\n num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)\n End If\n num2 = (((num2 And &HFFFF) Xor (num2 >> &H10)) << 8)\n rndSeed = ((rndSeed And -16776961) Or num2)\n projectData.m_rndSeed = rndSeed\n End Sub\n\n Public Shared Function Rnd() As Single\n Return VBMath.Rnd(1!)\n End Function\n\n Public Shared Function Rnd(ByVal Number As Single) As Single\n Dim projectData As ProjectData = ProjectData.GetProjectData\n Dim rndSeed As Integer = projectData.m_rndSeed\n If (Number <> 0) Then\n If (Number < 0) Then\n Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &HFFFFFFFF)\n rndSeed = CInt(((num1 + (num1 >> &H18)) And CULng(&HFFFFFF)))\n End If\n rndSeed = CInt((((rndSeed * &H43FD43FD) + &HC39EC3) And &HFFFFFF))\n End If\n projectData.m_rndSeed = rndSeed\n Return (CSng(rndSeed) / 1.677722E+07!)\n End Function\n\nEnd Class\n Public Class Random\n ' Methods\n <__DynamicallyInvokable> _\n Public Sub New()\n Me.New(Environment.TickCount)\n End Sub\n\n <__DynamicallyInvokable> _\n Public Sub New(ByVal Seed As Integer)\n Me.SeedArray = New Integer(&H38 - 1) {}\n Dim num4 As Integer = If((Seed = -2147483648), &H7FFFFFFF, Math.Abs(Seed))\n Dim num2 As Integer = (&H9A4EC86 - num4)\n Me.SeedArray(&H37) = num2\n Dim num3 As Integer = 1\n Dim i As Integer\n For i = 1 To &H37 - 1\n Dim index As Integer = ((&H15 * i) Mod &H37)\n Me.SeedArray(index) = num3\n num3 = (num2 - num3)\n If (num3 < 0) Then\n num3 = (num3 + &H7FFFFFFF)\n End If\n num2 = Me.SeedArray(index)\n Next i\n Dim j As Integer\n For j = 1 To 5 - 1\n Dim k As Integer\n For k = 1 To &H38 - 1\n Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &H37))))\n If (Me.SeedArray(k) < 0) Then\n Me.SeedArray(k) = (Me.SeedArray(k) + &H7FFFFFFF)\n End If\n Next k\n Next j\n Me.inext = 0\n Me.inextp = &H15\n Seed = 1\n End Sub\n\n Private Function GetSampleForLargeRange() As Double\n Dim num As Integer = Me.InternalSample\n If ((Me.InternalSample Mod 2) = 0) Then\n num = -num\n End If\n Dim num2 As Double = num\n num2 = (num2 + 2147483646)\n Return (num2 / 4294967293)\n End Function\n\n Private Function InternalSample() As Integer\n Dim inext As Integer = Me.inext\n Dim inextp As Integer = Me.inextp\n If (++inext >= &H38) Then\n inext = 1\n End If\n If (++inextp >= &H38) Then\n inextp = 1\n End If\n Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))\n If (num = &H7FFFFFFF) Then\n num -= 1\n End If\n If (num < 0) Then\n num = (num + &H7FFFFFFF)\n End If\n Me.SeedArray(inext) = num\n Me.inext = inext\n Me.inextp = inextp\n Return num\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next]() As Integer\n Return Me.InternalSample\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next](ByVal maxValue As Integer) As Integer\n If (maxValue < 0) Then\n Dim values As Object() = New Object() { \"maxValue\" }\n Throw New ArgumentOutOfRangeException(\"maxValue\", Environment.GetResourceString(\"ArgumentOutOfRange_MustBePositive\", values))\n End If\n Return CInt((Me.Sample * maxValue))\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer\n If (minValue > maxValue) Then\n Dim values As Object() = New Object() { \"minValue\", \"maxValue\" }\n Throw New ArgumentOutOfRangeException(\"minValue\", Environment.GetResourceString(\"Argument_MinMaxValue\", values))\n End If\n Dim num As Long = (maxValue - minValue)\n If (num <= &H7FFFFFFF) Then\n Return (CInt((Me.Sample * num)) + minValue)\n End If\n Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)\n End Function\n\n <__DynamicallyInvokable> _\n Public Overridable Sub NextBytes(ByVal buffer As Byte())\n If (buffer Is Nothing) Then\n Throw New ArgumentNullException(\"buffer\")\n End If\n Dim i As Integer\n For i = 0 To buffer.Length - 1\n buffer(i) = CByte((Me.InternalSample Mod &H100))\n Next i\n End Sub\n\n <__DynamicallyInvokable> _\n Public Overridable Function NextDouble() As Double\n Return Me.Sample\n End Function\n\n <__DynamicallyInvokable> _\n Protected Overridable Function Sample() As Double\n Return (Me.InternalSample * 4.6566128752457969E-10)\n End Function\n\n\n ' Fields\n Private inext As Integer\n Private inextp As Integer\n Private Const MBIG As Integer = &H7FFFFFFF\n Private Const MSEED As Integer = &H9A4EC86\n Private Const MZ As Integer = 0\n Private SeedArray As Integer()\nEnd Class\n" }, { "answer_id": 67386995, "author": "Bart Hofland", "author_id": 4174789, "author_profile": "https://Stackoverflow.com/users/4174789", "pm_score": 0, "selected": false, "text": "System.Random System.Random ToByteArray BitConverter 'Function for reuse (min is inclusive and max is exclusive)\nFunction GetRandom(min As Integer, max As Integer) As Integer\n Return BitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (max - min) + min\nEnd Function\n 'one-liner specific for your purpose (n is exclusive)\nBitConverter.ToUInt64(Guid.NewGuid.ToByteArray) Mod (n - 1) + 1\n Microsoft.VisualBasic.VBMath.Rnd Microsoft.VisualBasic" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225/" ]
18,685
<p>Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?</p>
[ { "answer_id": 18693, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 7, "selected": true, "text": "function time_since($since) {\n $chunks = array(\n array(60 * 60 * 24 * 365 , 'year'),\n array(60 * 60 * 24 * 30 , 'month'),\n array(60 * 60 * 24 * 7, 'week'),\n array(60 * 60 * 24 , 'day'),\n array(60 * 60 , 'hour'),\n array(60 , 'minute'),\n array(1 , 'second')\n );\n\n for ($i = 0, $j = count($chunks); $i < $j; $i++) {\n $seconds = $chunks[$i][0];\n $name = $chunks[$i][1];\n if (($count = floor($since / $seconds)) != 0) {\n break;\n }\n }\n\n $print = ($count == 1) ? '1 '.$name : \"$count {$name}s\";\n return $print;\n}\n" }, { "answer_id": 16248251, "author": "Dipesh", "author_id": 1689396, "author_profile": "https://Stackoverflow.com/users/1689396", "pm_score": 4, "selected": false, "text": "function timeAgo($timestamp){\n $datetime1=new DateTime(\"now\");\n $datetime2=date_create($timestamp);\n $diff=date_diff($datetime1, $datetime2);\n $timemsg='';\n if($diff->y > 0){\n $timemsg = $diff->y .' year'. ($diff->y > 1?\"'s\":'');\n\n }\n else if($diff->m > 0){\n $timemsg = $diff->m . ' month'. ($diff->m > 1?\"'s\":'');\n }\n else if($diff->d > 0){\n $timemsg = $diff->d .' day'. ($diff->d > 1?\"'s\":'');\n }\n else if($diff->h > 0){\n $timemsg = $diff->h .' hour'.($diff->h > 1 ? \"'s\":'');\n }\n else if($diff->i > 0){\n $timemsg = $diff->i .' minute'. ($diff->i > 1?\"'s\":'');\n }\n else if($diff->s > 0){\n $timemsg = $diff->s .' second'. ($diff->s > 1?\"'s\":'');\n }\n\n$timemsg = $timemsg.' ago';\nreturn $timemsg;\n}\n" }, { "answer_id": 23475770, "author": "Sebastiaan Hilbers", "author_id": 2450545, "author_profile": "https://Stackoverflow.com/users/2450545", "pm_score": 3, "selected": false, "text": "\\DateTime::diff \\DateInterval i" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
18,717
<p>As far as I know, foreign keys (FK) are used to aid the programmer to manipulate data in the correct way. Suppose a programmer is actually doing this in the right manner already, then do we really need the concept of foreign keys?</p> <p>Are there any other uses for foreign keys? Am I missing something here?</p>
[ { "answer_id": 18728, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "ON DELETE CASCADE" }, { "answer_id": 18760, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 5, "selected": false, "text": "ON DELETE CASCADE" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
18,719
<p>As part of our databuild run a 3rd party program (3D Studio Max) to export a number of assets. Unfortunately if a user is not currently logged in, or the machine is locked, then Max does not run correctly.</p> <p>This can be solved for freshly booted machines by using a method such as TweakUI for automatic login. However when a user connects via Remote Desktop (to initiate a non-scheduled build, change a setting, whatever) then after the session ends the machine is left in a locked state with Max unable to run.</p> <p>I'm looking for a way to configure windows (via fair means or foul) so either it does not lock when the remote session ends, or it "unlocks" itself a short while after. I'm aware of a method under XP where you can run a batchfile on the machine which kicks the remote user off, but this does not appear to work on Windows Server.</p>
[ { "answer_id": 154546, "author": "Ed Haber", "author_id": 2926, "author_profile": "https://Stackoverflow.com/users/2926", "pm_score": 0, "selected": false, "text": "myworkstation.mydomain.local /ADMIN\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
18,754
<p>I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run:</p> <pre><code>markdown-batch ./*.markdown </code></pre> <p>Any ideas?</p>
[ { "answer_id": 18775, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": -1, "selected": false, "text": "@echo off\nfor %i in (*.txt) python markdown.py \"%i\"\n" }, { "answer_id": 18831, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 6, "selected": true, "text": "for i in ./*.markdown; do perl markdown.pl --html4tags $i > $i.html; done;\n" }, { "answer_id": 18841, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "pandoc -f markdown index.md > index.html\n" }, { "answer_id": 40245401, "author": "Bruce Zu", "author_id": 913717, "author_profile": "https://Stackoverflow.com/users/913717", "pm_score": -1, "selected": false, "text": "for i in *.md; do asciidoc $i; done; \n" }, { "answer_id": 70998307, "author": "np8", "author_id": 3015186, "author_profile": "https://Stackoverflow.com/users/3015186", "pm_score": 0, "selected": false, "text": "Ctrl-Shift-P Markdown All In One: Print documents to HTML (select a source folder) settings.json Ctrl-Shift-P Preferences: Open Settings (JSON) \"markdown.extension.print.absoluteImgPath\": false\n" }, { "answer_id": 73435178, "author": "injashkin", "author_id": 19661777, "author_profile": "https://Stackoverflow.com/users/19661777", "pm_score": 1, "selected": false, "text": "npx md-pug-to-html /home/content\n npx /home/content" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185/" ]
18,757
<p>The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.</p> <p>However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.</p> <p>So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?<br> Should I include the operation in the view data as an enum?<br> Should I surround all the subtle differences with <em>&lt;% if( ViewData.Model.Op == Ops.Editing ) { %></em> ?</p> <p>Or is there a better way?</p>
[ { "answer_id": 18956, "author": "Jim", "author_id": 1208, "author_profile": "https://Stackoverflow.com/users/1208", "pm_score": 2, "selected": false, "text": "<%= Helper.ProfessionField() %>\n\nstring ProfessionField()\n{\n if(IsNewItem) { return /* some drop down code */ }\n else { return \"<p>\" + _profession+ \"</p>\"; } \n}\n" }, { "answer_id": 41866, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": false, "text": "public class BlogController : Controller\n{\n public ActionResult New()\n {\n var post = new Post();\n return View(\"Edit\", post);\n }\n\n public ActionResult Edit(int id)\n {\n var post = _repository.Get(id);\n return View(post);\n }\n\n ....\n\n}\n <% using(Html.Form(\"save\")) { %>\n<%= Html.Hidden(\"Id\") %>\n\n<label for=\"Title\">Title</label>\n<%= Html.TextBox(\"Title\") %>\n\n<label for=\"Body\">Body</label>\n<%= Html.TextArea(\"Body\") %>\n\n<%= Html.Submit(\"Submit\") %>\n<% } %>\n public ActionResult Save(int id, string title, string body)\n{\n var post = id == 0 ? new Post() : _repository.Get(id);\n post.Title = title;\n post.Body = body;\n\n _repository.Save(post);\n\n return RedirectToAction(\"list\");\n}\n" }, { "answer_id": 290841, "author": "labilbe", "author_id": 1195872, "author_profile": "https://Stackoverflow.com/users/1195872", "pm_score": 1, "selected": false, "text": "\npublic class MyViewData {\n public bool IsReadOnly { get; set; }\n public ModelObject MyObject { get; set; }\n}\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1851/" ]
18,764
<p>Since both a <code>Table Scan</code> and a <code>Clustered Index Scan</code> essentially scan all records in the table, why is a Clustered Index Scan supposedly better?</p> <p>As an example - what's the performance difference between the following when there are many records?:</p> <pre><code>declare @temp table( SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp ----------------------------- declare @temp table( RowID int not null identity(1,1) primary key, SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp </code></pre>
[ { "answer_id": 18906, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 7, "selected": true, "text": "INSERT UPDATE DELETE RANGE SELECT * FROM TABLE WHERE Id BETWEEN 1 AND 100 WHERE INSERT UPDATE DELETE INSERT UPDATE DELETE SELECT SELECT INSERT" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
18,765
<p>I'm currently working on creating a new C# project that needs to interact with an older C++ application. There is an error enumeration that already exists in the C++ app that I need to use in the C# app.</p> <p><em>I don't want to just re declare the enumeration in C# because that could cause sync issues down the line if the files aren't updated together</em>. </p> <p>All that being said my question is this: Is there a way for me to taken an enumeration declared like so:</p> <pre><code>typedef enum { eDEVICEINT_ERR_FATAL = 0x10001 ... } eDeviceIntErrCodes; </code></pre> <p>and use it in a C# program like so:</p> <pre><code>eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL </code></pre>
[ { "answer_id": 18786, "author": "Brian Ensink", "author_id": 1254, "author_profile": "https://Stackoverflow.com/users/1254", "pm_score": 5, "selected": true, "text": "\n public enum eDeviceIntErrCodes \n {\n /// eDEVICEINT_ERR_FATAL -> 0x10001\n eDEVICEINT_ERR_FATAL = 65537,\n }\n" }, { "answer_id": 18798, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 0, "selected": false, "text": "namespace blah\n{\n enum DEVICE_ERR_CODES\n {\n eDEVICEINT_ERR_FATAL = 0x10001,\n eDEVICEINT_ERR_OTHER = 0x10002,\n };\n} DEVICE_ERR_CODES eDeviceIntErrCodes; DEVICE_ERR_CODES err = DEVICE_ERR_CODES.eDEVICEINT_ERR_FATAL;" }, { "answer_id": 18870, "author": "Rob", "author_id": 1006, "author_profile": "https://Stackoverflow.com/users/1006", "pm_score": 4, "selected": false, "text": "#if CSharp\nnamespace MyNamespace.SharedEnumerations\n{\npublic\n#endif\n\n\nenum MyFirstEnumeration\n{\n Autodetect = -1,\n Windows2000,\n WindowsXP,\n WindowsVista,\n OSX,\n Linux,\n\n // Count must be last entry - is used to determine number of items in the enum\n Count\n};\n#if CSharp\npublic \n#endif\n\nenum MessageLevel\n{\n None, // Message is ignored\n InfoMessage, // Message is written to info port.\n InfoWarning, // Message is written to info port and warning is issued\n Popup // User is alerted to the message\n};\n\n#if CSharp\n public delegate void MessageEventHandler(MessageLevel level, string message);\n}\n#endif\n" }, { "answer_id": 51630980, "author": "doosik71", "author_id": 3763893, "author_profile": "https://Stackoverflow.com/users/3763893", "pm_score": 0, "selected": false, "text": "public enum class eDeviceIntErrCodes: int\n{\n eDEVICEINT_ERR_FATAL = 0x10001\n ...\n};\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
18,783
<p>When you have a query or stored procedure that needs performance tuning, what are some of the first things you try?</p>
[ { "answer_id": 18792, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 2, "selected": false, "text": "where SomeComplicatedFunctionOf(table.Column) = @param --silly\n" }, { "answer_id": 18822, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 2, "selected": false, "text": "declare @temp table(\n RowID int not null identity(1,1) primary key,\n SomeUniqueColumn varchar(25) not null,\n SomeNotUniqueColumn varchar(50) null,\n unique(SomeUniqueColumn)\n)\n" }, { "answer_id": 18835, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 1, "selected": false, "text": "isnull(SomeColThatMayBeNull, '')\n coalesce(SomeColThatMayBeNull, '')\n" }, { "answer_id": 19292, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 1, "selected": false, "text": "SET NOCOUNT ON\n @@ROWCOUNT" }, { "answer_id": 20254, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 0, "selected": false, "text": "set transaction isolation level read uncommitted\n" }, { "answer_id": 31615, "author": "Will SQL for Food", "author_id": 3348, "author_profile": "https://Stackoverflow.com/users/3348", "pm_score": 3, "selected": false, "text": "CREATE INDEX WHERE JOIN INSERT, UPDATE, DELETE SELECT i.make, i.model, i.price\nFROM dbo.inventory i\nWHERE i.color = 'red'\n AND i.price BETWEEN 15000 AND 18000\n idx01 CREATE INDEX idx01 ON dbo.inventory (price, color)\nCREATE INDEX idx02 ON dbo.inventory (color, price)\n" }, { "answer_id": 103176, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 7, "selected": false, "text": "#temp @table" }, { "answer_id": 103258, "author": "jinsungy", "author_id": 1316, "author_profile": "https://Stackoverflow.com/users/1316", "pm_score": 1, "selected": false, "text": "SELECT * FROM Orders (nolock) where UserName = 'momma'\n" }, { "answer_id": 473817, "author": "jandersson", "author_id": 56506, "author_profile": "https://Stackoverflow.com/users/56506", "pm_score": 3, "selected": false, "text": "UPDATE table\nSET @variable = column = @variable + otherColumn\n UPDATE table\nSET\n @variable = @variable + otherColumn,\n column = @variable\n" }, { "answer_id": 496040, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM Table1\nWHERE Table1.ID NOT IN (\n SELECT Table1ID\n FROM Table2)\n SELECT Table1.*\nFROM Table1\nLEFT OUTER JOIN Table2 ON Table1.ID = Table2.Table1ID\nWHERE Table2.ID is null\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
18,787
<p>When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:</p> <pre><code>return View("Message", new { DisplayMessage = "This is a test" }); </code></pre> <p>and on my Message control I had this:</p> <pre><code>&lt;%= ViewData["DisplayMessage"] %&gt; </code></pre> <p>I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:</p> <pre><code>public class MessageControl : ViewUserControl&lt;MessageData&gt; </code></pre> <p>and now this call works:</p> <pre><code>return View("Message", new MessageData() { DisplayMessage = "This is a test" }); </code></pre> <p>and can be displayed like this:</p> <pre><code>&lt;%= ViewData.Model.DisplayMessage %&gt; </code></pre> <p>Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?</p>
[ { "answer_id": 31726, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 4, "selected": true, "text": "ViewData.Eval(\"DisplayMessage\") \n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
18,803
<p>In college I've had numerous design and <a href="http://en.wikipedia.org/wiki/Unified_Modeling_Language" rel="noreferrer">UML</a> oriented courses, and I recognize that UML can be used to benefit a software project, especially <a href="http://en.wikipedia.org/wiki/Use_case" rel="noreferrer">use-case</a> mapping, but is it really practical? I've done a few co-op work terms, and it appears that UML is not used heavily in the industry. Is it worth the time during a project to create UML diagrams? Also, I find that class diagrams are generally not useful, because it's just faster to look at the header file for a class. Specifically which diagrams are the most useful?</p> <p><strong>Edit:</strong> My experience is limited to small, under 10 developer projects.</p> <p><strong>Edit:</strong> Many good answers, and though not the most verbose, I belive the one selected is the most balanced.</p>
[ { "answer_id": 18839, "author": "Pascal", "author_id": 1311, "author_profile": "https://Stackoverflow.com/users/1311", "pm_score": 7, "selected": true, "text": "UML" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2134/" ]
18,836
<p>I'm looking for shell scripts files installed on my system, but <strong>find</strong> doesn't work:</p> <pre><code>$ find /usr -name *.sh </code></pre> <p>But I know there are a ton of scripts out there. For instance:</p> <pre><code>$ ls /usr/local/lib/*.sh /usr/local/lib/tclConfig.sh /usr/local/lib/tkConfig.sh </code></pre> <p>Why doesn't <strong>find</strong> work?</p>
[ { "answer_id": 18837, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 7, "selected": true, "text": "$ find /usr -name \\*.sh\n $ find /usr -name '*.sh'\n $ find /usr -name tkConfig.sh\n $ cd /usr/local/lib\n$ find /usr -name *.sh\nfind: bad option tkConfig.sh\nfind: path-list predicate-list\n $ find /usr -name tclConfig.sh tkConfig.sh\n $ find /usr -follow -name '*.sh'\n" }, { "answer_id": 18843, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "find /usr -name '*.foo' -print\n" }, { "answer_id": 476874, "author": "Colas Nahaboo", "author_id": 58468, "author_profile": "https://Stackoverflow.com/users/58468", "pm_score": 3, "selected": false, "text": "locate '/usr*.sh'\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
18,858
<p>Does anyone here know of good batch file code indenters or beautifiers?</p> <p>Specifically for PHP, JS and SGML-languages.</p> <p>Preferably with options as to style.</p>
[ { "answer_id": 18837, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 7, "selected": true, "text": "$ find /usr -name \\*.sh\n $ find /usr -name '*.sh'\n $ find /usr -name tkConfig.sh\n $ cd /usr/local/lib\n$ find /usr -name *.sh\nfind: bad option tkConfig.sh\nfind: path-list predicate-list\n $ find /usr -name tclConfig.sh tkConfig.sh\n $ find /usr -follow -name '*.sh'\n" }, { "answer_id": 18843, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "find /usr -name '*.foo' -print\n" }, { "answer_id": 476874, "author": "Colas Nahaboo", "author_id": 58468, "author_profile": "https://Stackoverflow.com/users/58468", "pm_score": 3, "selected": false, "text": "locate '/usr*.sh'\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118/" ]
18,861
<p>So I am writing a registration form and I need the display name to be only numbers, letters and underscores. </p> <p>Have a look at my code and tell me what I'm doing wrong.</p> <pre><code>&lt;form method="post" action="/" onsubmit="return check_form()"&gt; &lt;input type="text" id="display-name" name="display-name" maxlength="255" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; &lt;!-- var name_regex = /^([a-zA-Z0-9_])+/ function check_form() { if (!name_regex.test(document.forms[0].elements[0].value)) { document.forms[0].elements[0].focus() alert("Your display name may only contain letters, numbers and underscores") return false } } --&gt; &lt;/script&gt; </code></pre> <p>It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.</p>
[ { "answer_id": 18874, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 3, "selected": false, "text": "/^[a-zA-Z0-9_]+$/ $" }, { "answer_id": 18881, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 0, "selected": false, "text": "$" }, { "answer_id": 18884, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "/^([a-zA-Z0-9_])+/\n $ $ /^([a-zA-Z0-9_])+$/\n document.getElementById('display-name').value document.forms" }, { "answer_id": 18892, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "$ abc123!@#" }, { "answer_id": 18903, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 0, "selected": false, "text": "<form method=\"post\" action=\"/\" onsubmit=\"return check_form()\">\n <input type=\"text\" id=\"display-name\" name=\"display-name\" maxlength=\"255\" />\n <input type=\"submit\" />\n</form>\n<script type=\"text/javascript\">\n <!--\n var name_regex = /^([a-zA-Z0-9_])+$/;\n\n function check_form()\n {\n if (!name_regex.test(document.forms[0].elements[0].value))\n {\n document.forms[0].elements[0].focus();\n alert(\"Your display name may only contain letters, numbers and underscores\");\n return false;\n }\n }\n -->\n</script>\n" }, { "answer_id": 18997, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 0, "selected": false, "text": "$" }, { "answer_id": 19026, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 0, "selected": false, "text": "var name_regex = /^([a-z0-9_])+$/i;\n" }, { "answer_id": 19341, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 0, "selected": false, "text": "var name_regex = /^\\w+$/;\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
18,869
<p>I am running a Qt 4.5 commercial snapshot and want to use a plugin that I downloaded (it's a .so file) in my <code>QWebView</code>. Is there a specific location where I need to place this file? Can I grab it using the <code>QWebPluginFactory</code>?</p>
[ { "answer_id": 22203, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 0, "selected": false, "text": "/lib/\n/usr/lib/\n/usr/share/lib/\n/usr/local/lib/\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449/" ]
18,889
<p>Is anyone working on or know if there exists a SQL 2k8 Dialect for NHibernate? </p>
[ { "answer_id": 22203, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 0, "selected": false, "text": "/lib/\n/usr/lib/\n/usr/share/lib/\n/usr/local/lib/\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975/" ]
18,912
<p>I know in JavaScript, <em>objects</em> double as hashes, but I have been unable to find a built-in function to get the keys:</p> <pre><code>var h = {a:'b', c:'d'}; </code></pre> <p>I want something like</p> <pre><code>var k = h.keys() ; // k = ['a', 'c']; </code></pre> <p>It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?</p> <p>I keep feeling it must be a simple built in function that I missed but I can't find it!</p>
[ { "answer_id": 18929, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 4, "selected": false, "text": "var keys = [];\nfor (var k in h)keys.push(k);\n" }, { "answer_id": 18930, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 3, "selected": false, "text": "function getKeys(h) {\n Array keys = new Array();\n for (var key in h)\n keys.push(key);\n return keys;\n}\n" }, { "answer_id": 18941, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 6, "selected": false, "text": "Object.keys defineProperty Object.defineProperty() Object.defineProperty(Object.prototype, 'keys', {\n value: function keys() {\n var keys = [];\n for(var i in this) if (this.hasOwnProperty(i)) {\n keys.push(i);\n }\n return keys;\n },\n enumerable: false\n});\n\nvar o = {\n 'a': 1,\n 'b': 2\n}\n\nfor (var k in o) {\n console.log(k, o[k])\n}\n\nconsole.log(o.keys())\n\n# OUTPUT\n# > a 1\n# > b 2\n# > [\"a\", \"b\"]\n Object.keys Object.defineProperty(Object.prototype, 'keys', {\n value: function keys() {\n return Object.keys(this);\n },\n enumerable: false\n});\n Object.prototype.keys = function ()\n{\n var keys = [];\n for(var i in this) if (this.hasOwnProperty(i))\n {\n keys.push(i);\n }\n return keys;\n}\n hasOwnProperty" }, { "answer_id": 3325571, "author": "Matthew Darwin", "author_id": 218940, "author_profile": "https://Stackoverflow.com/users/218940", "pm_score": 2, "selected": false, "text": "Object.prototype.keys = function () ...\n for (var key in h) ...\n" }, { "answer_id": 6921193, "author": "Ivan Nevostruev", "author_id": 93988, "author_profile": "https://Stackoverflow.com/users/93988", "pm_score": 9, "selected": true, "text": "Object.keys var obj = { \"a\" : 1, \"b\" : 2, \"c\" : 3};\nalert(Object.keys(obj)); // will output [\"a\", \"b\", \"c\"]\n if(!Object.keys) Object.keys = function(o){\n if (o !== Object(o))\n throw new TypeError('Object.keys called on non-object');\n var ret=[],p;\n for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);\n return ret;\n}\n" }, { "answer_id": 7027468, "author": "timotti", "author_id": 751340, "author_profile": "https://Stackoverflow.com/users/751340", "pm_score": 5, "selected": false, "text": "_.keys({one : 1, two : 2, three : 3});\n// => [\"one\", \"two\", \"three\"]\n" }, { "answer_id": 9293357, "author": "chim", "author_id": 673282, "author_profile": "https://Stackoverflow.com/users/673282", "pm_score": 3, "selected": false, "text": "var bobject = {primary:\"red\", bg:\"maroon\", hilite:\"green\"};\nvar keys = [];\n$.each(bobject, function(key, val){ keys.push(key); });\nconsole.log(keys); // [\"primary\", \"bg\", \"hilite\"]\n var bobject = {primary:\"red\", bg:\"maroon\", hilite:\"green\"};\n$.map(bobject, function(v, k){return k;});\n" }, { "answer_id": 9513780, "author": "zeacuss", "author_id": 312329, "author_profile": "https://Stackoverflow.com/users/312329", "pm_score": 1, "selected": false, "text": "this.getKeys = function() {\n\n var keys = new Array();\n for (var key in this) {\n\n if (typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n this" }, { "answer_id": 18153555, "author": "Leticia Santos", "author_id": 2655009, "author_profile": "https://Stackoverflow.com/users/2655009", "pm_score": 5, "selected": false, "text": "Object.keys Object.keys(h)\n" }, { "answer_id": 72699782, "author": "Mouzam Ali", "author_id": 7188711, "author_profile": "https://Stackoverflow.com/users/7188711", "pm_score": 1, "selected": false, "text": "Object.keys(h)\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
18,918
<p>Im testing an ASP.NEt site. When I execute it, it starts the ASP.NET Development Server and opens up a page.</p> <p>Now I want to test it in the intranet I have. </p> <ol> <li><p>Can I use this server or I need to configure IIS in this machine? </p></li> <li><p>Do I need to configure something for it to work?</p></li> </ol> <p>I've changed the localhost to the correct IP and I opened up the firewall.</p> <p>Thanks</p>
[ { "answer_id": 7394935, "author": "strongriley", "author_id": 561956, "author_profile": "https://Stackoverflow.com/users/561956", "pm_score": 7, "selected": true, "text": "java -jar tunnel.jar 80 localhost 1088\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
18,920
<p>When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine <code>(file:///)</code> then where should the <code>css</code> file be for the browser to find it?</p> <pre><code>&lt;link href="/temp/test.css" rel="stylesheet" type="text/css" /&gt; </code></pre>
[ { "answer_id": 18924, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 3, "selected": true, "text": "C:/" }, { "answer_id": 19338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<link href=\"file:///temp/test.css\" rel=\"stylesheet\" type=\"text/css\" />\n" }, { "answer_id": 27725, "author": "Sam Murray-Sutton", "author_id": 2977, "author_profile": "https://Stackoverflow.com/users/2977", "pm_score": 0, "selected": false, "text": "<link href=\"file:///blah/test.css\" rel=\"stylesheet\" type=\"text/css\">" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858/" ]
18,932
<p>I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).</p> <p>The rows, of course, will not be perfect duplicates because of the existence of the <code>RowID</code> identity field.</p> <p><strong>MyTable</strong></p> <pre><code>RowID int not null identity(1,1) primary key, Col1 varchar(20) not null, Col2 varchar(2048) not null, Col3 tinyint not null </code></pre> <p>How can I do this?</p>
[ { "answer_id": 18934, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 7, "selected": false, "text": "DELETE dupes\nFROM MyTable dupes, MyTable fullTable\nWHERE dupes.dupField = fullTable.dupField \nAND dupes.secondDupField = fullTable.secondDupField \nAND dupes.uniqueField > fullTable.uniqueField\n" }, { "answer_id": 18949, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 11, "selected": true, "text": "GROUP BY SELECT MIN (or MAX) DELETE FROM MyTable\nLEFT OUTER JOIN (\n SELECT MIN(RowId) as RowId, Col1, Col2, Col3 \n FROM MyTable \n GROUP BY Col1, Col2, Col3\n) as KeepRows ON\n MyTable.RowId = KeepRows.RowId\nWHERE\n KeepRows.RowId IS NULL\n MIN(RowId)\n CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))\n" }, { "answer_id": 18983, "author": "Jacob Proffitt", "author_id": 1336, "author_profile": "https://Stackoverflow.com/users/1336", "pm_score": 4, "selected": false, "text": "DELETE FROM MyTable WHERE NOT RowID IN\n (SELECT \n (SELECT TOP 1 RowID FROM MyTable mt2 \n WHERE mt2.Col1 = mt.Col1 \n AND mt2.Col2 = mt.Col2 \n AND mt2.Col3 = mt.Col3) \n FROM MyTable mt)\n" }, { "answer_id": 19034, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 3, "selected": false, "text": "-- given a table stories(story_id int not null primary key, story varchar(max) not null)\nCREATE TRIGGER prevent_plagiarism \nON stories \nafter INSERT, UPDATE \nAS \n DECLARE @cnt AS INT \n\n SELECT @cnt = Count(*) \n FROM stories \n INNER JOIN inserted \n ON ( stories.story = inserted.story \n AND stories.story_id != inserted.story_id ) \n\n IF @cnt > 0 \n BEGIN \n RAISERROR('plagiarism detected',16,1) \n\n ROLLBACK TRANSACTION \n END \n" }, { "answer_id": 839710, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "INSERT INTO tc_category1\nSELECT *\nFROM tc_category\nGROUP BY category_id, application_id\nHAVING count(*) > 1\n INSERT INTO tc_category1\nSELECT *\nFROM tc_category\nGROUP BY category_id, application_id\nHAVING count(*) = 1\n" }, { "answer_id": 1888176, "author": "codegoalie", "author_id": 12852, "author_profile": "https://Stackoverflow.com/users/12852", "pm_score": 4, "selected": false, "text": "DELETE FROM myTable WHERE RowID IN (\n SELECT MIN(RowID) AS IDNo FROM myTable\n GROUP BY Col1, Col2, Col3\n HAVING COUNT(*) = 2 )\n" }, { "answer_id": 3822833, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 10, "selected": false, "text": "; \n\n--Ensure that any immediately preceding statement is terminated with a semicolon above\nWITH cte\n AS (SELECT ROW_NUMBER() OVER (PARTITION BY Col1, Col2, Col3 \n ORDER BY ( SELECT 0)) RN\n FROM #MyTable)\nDELETE FROM cte\nWHERE RN > 1;\n ORDER BY (SELECT 0) RowID ORDER BY RowID DESC GROUP BY ROW_NUMBER GROUP BY TRUNCATE" }, { "answer_id": 3827302, "author": "SoftwareGeek", "author_id": 168882, "author_profile": "https://Stackoverflow.com/users/168882", "pm_score": 6, "selected": false, "text": "delete t1\nfrom table t1, table t2\nwhere t1.columnA = t2.columnA\nand t1.rowid>t2.rowid\n delete\nfrom table t1\nusing table t2\nwhere t1.columnA = t2.columnA\nand t1.rowid > t2.rowid\n" }, { "answer_id": 8244823, "author": "gngolakia", "author_id": 1050111, "author_profile": "https://Stackoverflow.com/users/1050111", "pm_score": 7, "selected": false, "text": "ID Column1 Column2 Column3 DELETE FROM TableName\nWHERE ID NOT IN (SELECT MAX(ID)\n FROM TableName\n GROUP BY Column1,\n Column2,\n Column3\n /*Even if ID is not null-able SQL Server treats MAX(ID) as potentially\n nullable. Because of semantics of NOT IN (NULL) including the clause\n below can simplify the plan*/\n HAVING MAX(ID) IS NOT NULL) \n GROUP BY HAVING ORDER BY SELECT YourColumnName,\n COUNT(*) TotalCount\nFROM YourTableName\nGROUP BY YourColumnName\nHAVING COUNT(*) > 1\nORDER BY COUNT(*) DESC \n" }, { "answer_id": 9193001, "author": "Sudhakar NV", "author_id": 1197119, "author_profile": "https://Stackoverflow.com/users/1197119", "pm_score": 3, "selected": false, "text": "testing empno,empname DELETE FROM testing WHERE empno not IN (SELECT empno FROM (SELECT empno, ROW_NUMBER() OVER (PARTITION BY empno ORDER BY empno) \nAS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)\nor empname not in\n(select empname from (select empname,row_number() over(PARTITION BY empno ORDER BY empno) \nAS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)\n" }, { "answer_id": 11431968, "author": "AnandPhadke", "author_id": 1495994, "author_profile": "https://Stackoverflow.com/users/1495994", "pm_score": 3, "selected": false, "text": "CREATE TABLE car(Id int identity(1,1), PersonId int, CarId int)\n\nINSERT INTO car(PersonId,CarId)\nVALUES(1,2),(1,3),(1,2),(2,4)\n\n--SELECT * FROM car\n\n;WITH CTE as(\nSELECT ROW_NUMBER() over (PARTITION BY personid,carid order by personid,carid) as rn,Id,PersonID,CarId from car)\n\nDELETE FROM car where Id in(SELECT Id FROM CTE WHERE rn>1)\n" }, { "answer_id": 12818055, "author": "heta77", "author_id": 1734652, "author_profile": "https://Stackoverflow.com/users/1734652", "pm_score": 4, "selected": false, "text": "SELECT DISTINCT *\n INTO tempdb.dbo.tmpTable\nFROM myTable\n\nTRUNCATE TABLE myTable\nINSERT INTO myTable SELECT * FROM tempdb.dbo.tmpTable\nDROP TABLE tempdb.dbo.tmpTable\n" }, { "answer_id": 14612370, "author": "Evgueny Sedov", "author_id": 1193024, "author_profile": "https://Stackoverflow.com/users/1193024", "pm_score": 3, "selected": false, "text": "SET ROWCOUNT 1 -- or set to number of rows to be deleted\ndelete from myTable where RowId = DuplicatedID\nSET ROWCOUNT 0\n" }, { "answer_id": 14717523, "author": "JuanJo", "author_id": 2044799, "author_profile": "https://Stackoverflow.com/users/2044799", "pm_score": 5, "selected": false, "text": "select distinct * into t2 from t1;\ndelete from t1;\ninsert into t1 select * from t2;\ndrop table t2;\n" }, { "answer_id": 18086447, "author": "Nitish Pareek", "author_id": 918385, "author_profile": "https://Stackoverflow.com/users/918385", "pm_score": 4, "selected": false, "text": "EMPLOYEE_ID ATTENDANCE_DATE\nA001 2011-01-01\nA001 2011-01-01\nA002 2011-01-01\nA002 2011-01-01\nA002 2011-01-01\nA003 2011-01-01\n ALTER TABLE dbo.ATTENDANCE ADD AUTOID INT IDENTITY(1,1) \n DELETE FROM dbo.ATTENDANCE WHERE AUTOID NOT IN (SELECT MIN(AUTOID) _\n FROM dbo.ATTENDANCE GROUP BY EMPLOYEE_ID,ATTENDANCE_DATE) \n" }, { "answer_id": 18719814, "author": "Syed Mohamed", "author_id": 2089963, "author_profile": "https://Stackoverflow.com/users/2089963", "pm_score": 5, "selected": false, "text": "DELETE\nFROM\n Mytable\nWHERE\n RowID NOT IN (\n SELECT\n MIN(RowID)\n FROM\n Mytable\n GROUP BY\n Col1,\n Col2,\n Col3\n )\n" }, { "answer_id": 19152091, "author": "Teena", "author_id": 2841400, "author_profile": "https://Stackoverflow.com/users/2841400", "pm_score": 3, "selected": false, "text": "DELETE\nFROM\n table_name T1\nWHERE\n rowid > (\n SELECT\n min(rowid)\n FROM\n table_name T2\n WHERE\n T1.column_name = T2.column_name\n );\n" }, { "answer_id": 20886125, "author": "Jayron Soares", "author_id": 2665070, "author_profile": "https://Stackoverflow.com/users/2665070", "pm_score": 3, "selected": false, "text": "DELETE \nFROM MyTable\nWHERE NOT EXISTS (\n SELECT min(RowID)\n FROM Mytable\n WHERE (SELECT RowID \n FROM Mytable\n GROUP BY Col1, Col2, Col3\n ))\n );\n" }, { "answer_id": 21380738, "author": "Ruben Verschueren", "author_id": 1396478, "author_profile": "https://Stackoverflow.com/users/1396478", "pm_score": 4, "selected": false, "text": "begin transaction\n-- create temp table with identical structure as source table\nSelect * Into #temp From tableName Where 1 = 2\n\n-- insert distinct values into temp\ninsert into #temp \nselect distinct * \nfrom tableName\n\n-- delete from source\ndelete from tableName \n\n-- insert into source from temp\ninsert into tableName \nselect * \nfrom #temp\n\nrollback transaction\n-- if this works, change rollback to commit and execute again to keep you changes!!\n" }, { "answer_id": 22111625, "author": "James Errico", "author_id": 832005, "author_profile": "https://Stackoverflow.com/users/832005", "pm_score": 4, "selected": false, "text": "--DELETE FROM table1 \n--WHERE id IN ( \n SELECT MIN(id) FROM table1 \n GROUP BY col1, col2, col3 \n -- could add a WHERE clause here to further filter\n HAVING count(*) > 1\n--)\n" }, { "answer_id": 23777260, "author": "Jithin Shaji", "author_id": 3265371, "author_profile": "https://Stackoverflow.com/users/3265371", "pm_score": 6, "selected": false, "text": "DELETE LU \nFROM (SELECT *, \n Row_number() \n OVER ( \n partition BY col1, col1, col3 \n ORDER BY rowid DESC) [Row] \n FROM mytable) LU \nWHERE [row] > 1 \n" }, { "answer_id": 26913528, "author": "Ostati", "author_id": 2654100, "author_profile": "https://Stackoverflow.com/users/2654100", "pm_score": 4, "selected": false, "text": ";with cte as (\n select \n min(PrimaryKey) as PrimaryKey\n UniqueColumn1,\n UniqueColumn2\n from dbo.DuplicatesTable \n group by\n UniqueColumn1, UniqueColumn1\n having count(*) > 1\n)\ndelete d\nfrom dbo.DuplicatesTable d \ninner join cte on \n d.PrimaryKey > cte.PrimaryKey and\n d.UniqueColumn1 = cte.UniqueColumn1 and \n d.UniqueColumn2 = cte.UniqueColumn2;\n" }, { "answer_id": 27409405, "author": "Draško", "author_id": 1176497, "author_profile": "https://Stackoverflow.com/users/1176497", "pm_score": 4, "selected": false, "text": "DELETE tbl\nFROM\n MyTable tbl\nWHERE\n EXISTS (\n SELECT\n *\n FROM\n MyTable tbl2\n WHERE\n tbl2.SameValue = tbl.SameValue\n AND tbl.IdUniqueValue < tbl2.IdUniqueValue\n )\n" }, { "answer_id": 27732094, "author": "Lauri Lubi", "author_id": 412368, "author_profile": "https://Stackoverflow.com/users/412368", "pm_score": 3, "selected": false, "text": "with MYCTE as (\n SELECT ROW_NUMBER() OVER (\n PARTITION BY DuplicateKey1\n ,DuplicateKey2 -- optional\n ORDER BY CreatedAt -- the first row among duplicates will be kept, other rows will be removed\n ) RN\n FROM MyTable\n)\nDELETE FROM MYCTE\nWHERE RN > 1\n" }, { "answer_id": 30328691, "author": "Shamseer K", "author_id": 4133590, "author_profile": "https://Stackoverflow.com/users/4133590", "pm_score": 5, "selected": false, "text": "WITH CTE AS\n(\nSELECT *,ROW_NUMBER() OVER (PARTITION BY col1,col2,col3 ORDER BY col1,col2,col3) AS RN\nFROM MyTable\n)\n\nDELETE FROM CTE WHERE RN<>1\n WITH CTE AS\n(SELECT *,R=RANK() OVER (ORDER BY col1,col2,col3)\nFROM MyTable)\n \nDELETE CTE\nWHERE R IN (SELECT R FROM CTE GROUP BY R HAVING COUNT(*)>1)\n" }, { "answer_id": 31586339, "author": "Haris N I", "author_id": 5073609, "author_profile": "https://Stackoverflow.com/users/5073609", "pm_score": 4, "selected": false, "text": "WITH tblTemp as\n(\nSELECT ROW_NUMBER() Over(PARTITION BY Name,Department ORDER BY Name)\n As RowNumber,* FROM <table_name>\n)\nDELETE FROM tblTemp where RowNumber >1\n" }, { "answer_id": 34305065, "author": "Chanukya", "author_id": 5093602, "author_profile": "https://Stackoverflow.com/users/5093602", "pm_score": 1, "selected": false, "text": "alter table MyTable add sno int identity(1,1)\n delete from MyTable where sno in\n (\n select sno from (\n select *,\n RANK() OVER ( PARTITION BY RowID,Col3 ORDER BY sno DESC )rank\n From MyTable\n )T\n where rank>1\n )\n\n alter table MyTable \n drop column sno\n" }, { "answer_id": 34730529, "author": "Hamit YILDIRIM", "author_id": 914284, "author_profile": "https://Stackoverflow.com/users/914284", "pm_score": 0, "selected": false, "text": "DELETE \nFROM elasticalsearch\nWHERE Id NOT IN \n (SELECT min(Id)\n FROM elasticalsearch\n GROUP BY FirmId,FilterSearchString\n ) \n" }, { "answer_id": 35147002, "author": "yuvi", "author_id": 4919084, "author_profile": "https://Stackoverflow.com/users/4919084", "pm_score": 3, "selected": false, "text": "DELETE A\nFROM TABLE A,\n TABLE B\nWHERE A.COL1 = B.COL1\n AND A.COL2 = B.COL2\n AND A.UNIQUEFIELD > B.UNIQUEFIELD \n" }, { "answer_id": 37669155, "author": "Brett Ryan", "author_id": 140037, "author_profile": "https://Stackoverflow.com/users/140037", "pm_score": 1, "selected": false, "text": "UPDATE UPDATE MY_TABLE\n SET DELETED = getDate()\n WHERE TABLE_ID IN (\n SELECT x.TABLE_ID\n FROM MY_TABLE x\n JOIN (SELECT min(TABLE_ID) id, COL_1, COL_2, COL_3\n FROM MY_TABLE d\n GROUP BY d.COL_1, d.COL_2, d.COL_3\n HAVING count(*) > 1) AS d ON d.COL_1 = x.COL_1\n AND d.COL_2 = x.COL_2\n AND d.COL_3 = x.COL_3\n AND d.TABLE_ID <> x.TABLE_ID\n /*WHERE x.COL_4 <> 'D' -- Additional filter*/)\n" }, { "answer_id": 39738697, "author": "Harikesh Yadav", "author_id": 6546950, "author_profile": "https://Stackoverflow.com/users/6546950", "pm_score": 4, "selected": false, "text": " DELETE FROM tblemp WHERE id IN \n (\n SELECT MIN(id) FROM tblemp\n GROUP BY title HAVING COUNT(id)>1\n )\n" }, { "answer_id": 41377822, "author": "Shaini Sinha", "author_id": 5887766, "author_profile": "https://Stackoverflow.com/users/5887766", "pm_score": 5, "selected": false, "text": "SELECT\nname, email, COUNT(*)\nFROM \nusers\nGROUP BY\nname, email\nHAVING COUNT(*) > 1\n DELETE users \nWHERE rowid NOT IN \n(SELECT MIN(rowid)\nFROM users\nGROUP BY name, email); \n" }, { "answer_id": 43387570, "author": "Jakub Ojmucianski", "author_id": 6696265, "author_profile": "https://Stackoverflow.com/users/6696265", "pm_score": 1, "selected": false, "text": " CREATE PROCEDURE sp_DeleteDuplicate @tableName varchar(100), @DebugMode int =1\nAS \nBEGIN\nSET NOCOUNT ON;\n\nIF(OBJECT_ID('tempdb..#tableMatrix') is not null) DROP TABLE #tableMatrix;\n\nSELECT ROW_NUMBER() OVER(ORDER BY name) as rn,name into #tableMatrix FROM sys.columns where [object_id] = object_id(@tableName) ORDER BY name\n\nDECLARE @MaxRow int = (SELECT MAX(rn) from #tableMatrix)\nIF(@MaxRow is null)\n RAISERROR ('I wasn''t able to find any columns for this table!',16,1)\nELSE \n BEGIN\nDECLARE @i int =1 \nDECLARE @Columns Varchar(max) ='';\n\nWHILE (@i <= @MaxRow)\nBEGIN \n SET @Columns=@Columns+(SELECT '['+name+'],' from #tableMatrix where rn = @i)\n\n SET @i = @i+1;\nEND\n\n---DELETE LAST comma\nSET @Columns = LEFT(@Columns,LEN(@Columns)-1)\n\nDECLARE @Sql nvarchar(max) = '\nWITH cteRowsToDelte\n AS (\nSELECT ROW_NUMBER() OVER (PARTITION BY '+@Columns+' ORDER BY ( SELECT 0)) as rowNumber,* FROM '+@tableName\n+')\n\nDELETE FROM cteRowsToDelte\nWHERE rowNumber > 1;\n'\nSET NOCOUNT OFF;\n IF(@DebugMode = 1)\n SELECT @Sql\n ELSE\n EXEC sp_executesql @Sql\n END\nEND\n IF(OBJECT_ID('MyLitleTable') is not null)\n DROP TABLE MyLitleTable \n\n\nCREATE TABLE MyLitleTable\n(\n A Varchar(10),\n B money,\n C int\n)\n---------------------------------------------------------\n\n INSERT INTO MyLitleTable VALUES\n ('ABC',100,1),\n ('ABC',100,1), -- only this row should be deleted\n ('ABC',101,1),\n ('ABC',100,2),\n ('ABCD',100,1)\n\n -----------------------------------------------------------\n\n exec sp_DeleteDuplicate 'MyLitleTable',0\n" }, { "answer_id": 50782285, "author": "Selim Reza", "author_id": 4079929, "author_profile": "https://Stackoverflow.com/users/4079929", "pm_score": 0, "selected": false, "text": "delete FROM\n(SELECT res1.*,ROW_NUMBER() OVER(PARTITION BY res1.Title ORDER BY res1.Id)as num\n FROM \n(select * from [dbo].[tbl_countries])as res1\n)as res2\nWHERE res2.num > 1\n" }, { "answer_id": 53047498, "author": "Suraj Kumar", "author_id": 10532500, "author_profile": "https://Stackoverflow.com/users/10532500", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT * INTO #TemNewTable FROM #OriginalTable\nTRUNCATE TABLE #OriginalTable\nINSERT INTO #OriginalTable SELECT * FROM #TemNewTable\nDROP TABLE #TemNewTable\n" }, { "answer_id": 63276678, "author": "Ankit Jindal", "author_id": 4198180, "author_profile": "https://Stackoverflow.com/users/4198180", "pm_score": 1, "selected": false, "text": "RowID int not null identity(1,1) primary key,\nCol1 varchar(20) not null,\nCol2 varchar(2048) not null,\nCol3 tinyint not null\n DELETE t1\nFROM MyTable t1\nINNER JOIN MyTable t2\nWHERE t1.RowID > t2.RowID\n AND t1.Col1 = t2.Col1\n AND t1.Col2=t2.Col2\n AND t1.Col3=t2.Col3;\n RowID" }, { "answer_id": 66499181, "author": "Mansour Alnasser", "author_id": 1448379, "author_profile": "https://Stackoverflow.com/users/1448379", "pm_score": 0, "selected": false, "text": "DELETE \nFROM \n TABLE_NAME \n WHERE FIRST_COLUMNS \n IN( \n SELECT * FROM \n ( SELECT MIN(FIRST_COLUMNS) \n FROM TABLE_NAME \n GROUP BY \n FIRST_COLUMNS,\n SECOND_COLUMNS \n HAVING COUNT(FIRST_COLUMNS) > 1 \n ) temp \n )\n simulate query" }, { "answer_id": 67339432, "author": "Chandan Kumar Singh", "author_id": 8124278, "author_profile": "https://Stackoverflow.com/users/8124278", "pm_score": -1, "selected": false, "text": "DELETE FROM table1 a\nUSING table1 b\nWHERE a.id < b.id\nAND a.column1 = b.column1\nAND a.column2 = b.column2;\n" }, { "answer_id": 69237652, "author": "Md. Tarikul Islam Soikot", "author_id": 15078671, "author_profile": "https://Stackoverflow.com/users/15078671", "pm_score": 0, "selected": false, "text": " SELECT MIN(RowId) as RowId\n FROM MyTable \n GROUP BY Col1, Col2, Col3\n DELETE FROM MyTable WHERE RowId Not IN()\n DELETE FROM MyTable WHERE RowId Not IN(\n\n SELECT MIN(RowId) as RowId\n FROM MyTable \n GROUP BY Col1, Col2, Col3\n)\n" }, { "answer_id": 73993006, "author": "michael satumba", "author_id": 16040742, "author_profile": "https://Stackoverflow.com/users/16040742", "pm_score": -1, "selected": false, "text": "CREATE TABLE table2 AS SELECT *, COUNT(*) FROM table1 GROUP BY name HAVING COUNT (*) > 0\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
18,943
<p>Typically in a large network a computer needs to operate behind an authenticated proxy - any connections to the outside world require a username/password which is often the password a user uses to log into email, workstation etc.</p> <p>This means having to put the network password in the <code>apt.conf</code> file as well as typically the <code>http_proxy, ftp_proxy</code> and <code>https_proxy</code> environment variables defined in <code>~/.profile</code></p> <p>I realise that with <code>apt.conf</code> that you could set <code>chmod 600</code> (which it isn't by default on Ubuntu/Debian!) but on our system there are people who need root priveleges .</p> <p>I also realise that it is technically impossible to secure a password from someone who has root access, however I was wondering if there was a way of <i>obscuring</i> the password to prevent accidental discovery. Windows operates with users as admins yet somehow stores network passwords (probably stored deep in the registry obscured in some way) so that in typical use you won't stumble across it in plain text</p> <p>I only ask since the other day, I entirely by accident discovered somebody elses password in this way when comparing configuration files across systems.</p> <p>@monjardin - Public key authentication is not an alternative on this network I'm afraid. Plus I doubt it is supported amongst the majority of commandline tools.</p> <p>@Neall - I don't mind the other users having web access, they can use my credentials to access the web, I just don't want them to happen across my password in plain text.</p>
[ { "answer_id": 20160, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "-D -L" }, { "answer_id": 26896, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 2, "selected": false, "text": "~/.profile encodedcreds=\"sbbone:cnffjbeq\"\ncreds=`echo \"$encodedcreds\" | tr n-za-mN-ZA-M a-zA-Z`\n creds foobar:password http_proxy" }, { "answer_id": 44286349, "author": "leon22", "author_id": 384556, "author_profile": "https://Stackoverflow.com/users/384556", "pm_score": 3, "selected": false, "text": "/etc/bash.bashrc alias myproxy='read -p \"Username: \" USER;read -s -p \"Password: \" PW\nPROXY=\"$USER:[email protected]:80\";\nexport http_proxy=http://$PROXY;export Proxy=$http_proxy;export https_proxy=https://$PROXY;export ftp_proxy=ftp://$PROXY'\n myproxy sudo -E sudo -E apt-get update" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199/" ]
18,955
<p>Is there a way to disable entering multi-line entries in a Text Box (i.e., I'd like to stop my users from doing ctrl-enter to get a newline)?</p>
[ { "answer_id": 20255, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 4, "selected": true, "text": "Private Sub SingleLineTextBox_ KeyPress(ByRef KeyAscii As Integer)\n If KeyAscii = 10 _\n or KeyAscii = 13 Then\n '10 -> Ctrl-Enter. AKA ^J or ctrl-j\n '13 -> Enter. AKA ^M or ctrl-m\n KeyAscii = 0 'clear the the KeyPress\n End If\nEnd Sub\n" }, { "answer_id": 22711, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "NOT LIKE \"*\"+Chr(10)+\"*\" OR \"*\"+Chr(13)+\"*\"\n" }, { "answer_id": 67730, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": false, "text": " If InStr(Me!MyMemoControl, vbCrLf) Then\n Me!MyMemoControl = Replace(Me!MyMemoControl, vbCrLf, vbNullString)\n End If\n" }, { "answer_id": 29218275, "author": "kernelk", "author_id": 1305420, "author_profile": "https://Stackoverflow.com/users/1305420", "pm_score": 1, "selected": false, "text": "Public Sub PreventNewlines(ByRef KeyAscii As Integer)\n If KeyAscii = 10 Or KeyAscii = 13 Then KeyAscii = 0\nEnd Sub\n\nPrivate Sub textbox_KeyPress(KeyAscii As Integer)\n Call PreventNewlines(KeyAscii)\nEnd Sub\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
18,959
<p>I'm writing an application that on some stage performs low-level disk operations in Linux environment. The app actually consists of 2 parts, one runs on Windows and interacts with a user and another is a linux part that runs from a LiveCD. User makes a choice of Windows drive letters and then a linux part performs actions with corresponding partitions. The problem is finding a match between a Windows drive letter (like C:) and a linux device name (like /dev/sda1). This is my current solution that I rate as ugly:</p> <ul> <li><p>store partitions information (i.e. drive letter, number of blocks, drive serial number etc.) in Windows in some pre-defined place (i.e. the root of the system partition).</p></li> <li><p>read a list of partitions from /proc/partitions. Get only those partitions that has major number for SCSI or IDE hard drives and minor number that identifies them as real partitions and not the whole disks.</p></li> <li><p>Try to mount each of them with either ntfs or vfat file systems. Check whether the mounted partition contains the information stored by Windows app.</p></li> <li><p>Upon finding the required information written by the Windows app make the actual match. For each partition found in /proc/partitions acquire drive serial number (via HDIO_GET_IDENTITY syscall), number of blocks (from /proc/partitions) and drive offset (/sys/blocks/drive_path/partition_name/start), compare this to the Windows information and if this matches - store a Windows drive letter along with a linux device name. </p></li> </ul> <p>There are a couple of problems in this scheme:</p> <ul> <li><p>This is ugly. Writing data in Windows and then reading it in Linux makes testing a nightmare.</p></li> <li><p>linux device major number is compared only with IDE or SCSI devices. This would probably fail, i.e. on USB or FireWire disks. It's possible to add these types of disks, but limiting the app to only known subset of possible devices seems to be rather bad idea.</p></li> <li><p>looks like HDIO_GET_IDENTITY works only on IDE and SATA drives.</p></li> <li><p>/sys/block hack may not work on other than IDE or SATA drives.</p></li> </ul> <p>Any ideas on how to improve this schema? Perhaps there is another way to determine windows names without writing all the data in windows app?</p> <p>P.S. The language of the app is C++. I can't change this.</p>
[ { "answer_id": 2194258, "author": "Bernhard", "author_id": 265528, "author_profile": "https://Stackoverflow.com/users/265528", "pm_score": 0, "selected": false, "text": "HANDLE fileHandle = CreateFile(L\"\\\\\\\\.\\\\C:\", // or use syntax \"\\\\?\\Volume{GUID}\" \n GENERIC_READ,\n FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,\n OPEN_EXISTING,\n NULL,\n NULL);\nDWORD i;\nNTFS_VOLUME_DATA_BUFFER ntfsInfo;\nDeviceIoControl(fileHandle, \n FSCTL_GET_NTFS_VOLUME_DATA, \n NULL, \n 0, \n &ntfsInfo,\n sizeof(ntfsInfo), \n &i, \n NULL));\ncout << \"UUID is \" << std::hex << ntfsInfo.VolumeSerialNumber.HighPart << std::hex << ntfsInfo.VolumeSerialNumber.LowPart << endl;\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2206/" ]
18,985
<p>I am writing a batch script in order to beautify JavaScript code. It needs to work on both <strong>Windows</strong> and <strong>Linux</strong>. </p> <p>How can I beautify JavaScript code using the command line tools? </p>
[ { "answer_id": 27343, "author": "Alan Storm", "author_id": 2838, "author_profile": "https://Stackoverflow.com/users/2838", "pm_score": 7, "selected": true, "text": "java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js\n //original code \n(function() { ... js_beautify code ... }());\n\n//new code\nprint(global.js_beautify(readFile(arguments[0])));\n java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js\n" }, { "answer_id": 4041563, "author": "knb", "author_id": 202553, "author_profile": "https://Stackoverflow.com/users/202553", "pm_score": 6, "selected": false, "text": " $ pip install jsbeautifier\n $ npm -g install js-beautify\n $ js-beautify file.js\n $ js-beautify -r file.js\n java -jar js.jar name-of-script.js\n ./jsbeautify somefile.js\n" }, { "answer_id": 4065400, "author": "Shonzilla", "author_id": 31625, "author_profile": "https://Stackoverflow.com/users/31625", "pm_score": 1, "selected": false, "text": "// Run the beautifier on the file passed as the first argument.\nprint( j23s_beautify( readFile( arguments[0] )));\n #!/bin/sh\njava -cp ~/dev/javascript/rhino/js.jar org.mozilla.javascript.tools.shell.Main ~/dev/web/javascript/bin/cli-beautifier.js $*\n" }, { "answer_id": 16513195, "author": "erapert", "author_id": 1411115, "author_profile": "https://Stackoverflow.com/users/1411115", "pm_score": 5, "selected": false, "text": "sudo npm install -g uglify-js uglifyjs -h foo.js // foo.js -- minified\nfunction foo(bar,baz){console.log(\"something something\");return true;}\n uglifyjs foo.js --beautify --output cutefoo.js uglify unexpand unexpand --tabs=4 cutefoo.js > cuterfoo.js uglifyjs foo.js --beautify | unexpand --tabs=4 > cutestfoo.js function foo(bar, baz) {\n console.log(\"something something\");\n return true;\n}\n" }, { "answer_id": 21812204, "author": "tmaric", "author_id": 704028, "author_profile": "https://Stackoverflow.com/users/704028", "pm_score": 2, "selected": false, "text": "--mode=java" }, { "answer_id": 55358995, "author": "Serge Stroobandt", "author_id": 2192488, "author_profile": "https://Stackoverflow.com/users/2192488", "pm_score": 4, "selected": false, "text": "$ sudo apt install jsbeautifier\n$ js-beautify ugly.js > beautiful.js\n $ js-beautify -r file.js\n$ js-beautify --replace file.js\n" }, { "answer_id": 63420552, "author": "Alex Nolasco", "author_id": 65694, "author_profile": "https://Stackoverflow.com/users/65694", "pm_score": 3, "selected": false, "text": "npx semistandard \"js/**/*.js\" --fix\n npx standard \"js/**/*.js\" --fix\n npx prettier --single-quote --write --trailing-comma all \"js/**/*.js\"\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/18985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
19,011
<p>I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits each to 64KB.</p> <p>I'm wondering if anyone else has had to tackle the problem of storing a large amount of data in the RMS and how they managed it? I'm thinking of having to calculate record sizes and split one data set accross multiple stores if its too large, but that adds a lot of complexity to keep it intact.</p> <p>There is lots of different types of data being stored but only one set in particular will exceed the 64KB limit.</p>
[ { "answer_id": 1660340, "author": "dhill", "author_id": 69769, "author_profile": "https://Stackoverflow.com/users/69769", "pm_score": 2, "selected": false, "text": "List Thread InputStreamReader.skip()" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270/" ]
19,014
<p>I want to use Lucene (in particular, Lucene.NET) to search for email address domains.</p> <p>E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.</p> <p>Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "[email protected]" is seen as a whole word, and you cannot search for just parts of a word.</p> <p>How can I do this?</p>
[ { "answer_id": 20468, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 5, "selected": true, "text": "class WhitespaceAndAtSymbolTokenizer : CharTokenizer\n{\n public WhitespaceAndAtSymbolTokenizer(TextReader input)\n : base(input)\n {\n }\n\n protected override bool IsTokenChar(char c)\n {\n // Make whitespace characters and the @ symbol be indicators of new words.\n return !(char.IsWhiteSpace(c) || c == '@');\n }\n}\n\n\ninternal class WhitespaceAndAtSymbolAnalyzer : Analyzer\n{\n public override TokenStream TokenStream(string fieldName, TextReader reader)\n {\n return new WhitespaceAndAtSymbolTokenizer(reader);\n }\n}\n IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer());\nindex.AddDocument(myDocument);\n IndexSearcher searcher = new IndexSearcher(indexDirectory);\nQuery query = new QueryParser(\"TheFieldNameToSearch\", new WhitespaceAndAtSymbolAnalyzer()).Parse(\"@gmail.com\");\nHits hits = query.Search(query);\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
19,030
<p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p> <p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p> <p>Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.</p> <p>The current code can be found <a href="http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py" rel="nofollow noreferrer">here</a></p> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. </p> <p>How could I write this system in a more expandable way?</p> <p>The rules it needs to check would be..</p> <ul> <li>File is in the format <code>Show Name - [01x23] - Episode Name.avi</code> or <code>Show Name - [01xSpecial02] - Special Name.avi</code> or <code>Show Name - [01xExtra01] - Extra Name.avi</code></li> <li>If filename is in the format <code>Show Name - [01x23].avi</code> display it a 'missing episode name' section of the output</li> <li>The path should be in the format <code>Show Name/season 2/the_file.avi</code> (where season 2 should be the correct season number in the filename)</li> <li>each <code>Show Name/season 1/</code> folder should contain "folder.jpg"</li> </ul> <p>.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..</p> <p>The only thought I had was a list of dicts in the format:</p> <pre><code>checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets } </code></pre>
[ { "answer_id": 19389, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 0, "selected": false, "text": "folder.jpg" }, { "answer_id": 21302, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 3, "selected": true, "text": "checker = {\n ...\n 'required': ['file', 'list', 'for_required']\n}\n check_dict = {\n 'delim' : /\\-/,\n 'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ],\n 'patterns' : [/valid name/, /valid episode name/, /valid number/ ],\n 'required' : ['list', 'of', 'files'],\n 'ignored' : ['.*', 'hidden.txt'],\n 'start_dir': '/path/to/dir/to/test/'\n}\n parts patterns . .. svn:ignore start_dir parts" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
19,035
<p>I am working with both <a href="http://activemq.apache.org/ajax.html" rel="nofollow noreferrer">amq.js</a> (ActiveMQ) and <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps</a>. I load my scripts in this order</p> <pre><code>&lt;head&gt; &lt;meta http-equiv="content-type" content="text/html;charset=UTF-8" /&gt; &lt;title&gt;AMQ &amp; Maps Demo&lt;/title&gt; &lt;!-- Stylesheet --&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt;&lt;/link&gt; &lt;!-- Google APIs --&gt; &lt;script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"&gt;&lt;/script&gt; &lt;!-- Active MQ --&gt; &lt;script type="text/javascript" src="amq/amq.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt;amq.uri='amq';&lt;/script&gt; &lt;!-- Application --&gt; &lt;script type="text/javascript" src="application.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. <strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong> </p> <p>Google has this nice function call <code>google.setOnLoadCallback(initialize);</code> which works great. I'm not sure amq.js has something like this.</p>
[ { "answer_id": 19067, "author": "maxsilver", "author_id": 1477, "author_profile": "https://Stackoverflow.com/users/1477", "pm_score": 2, "selected": false, "text": "application.js $(document).ready" }, { "answer_id": 19069, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 3, "selected": false, "text": "$(document).ready(function(){/*do stuff here*/});\n document.observe(\"dom:loaded\", function() {/*do stuff here*/});\n <script>\n function doIt() {/*do stuff here*/}\n</script>\n<body onLoad=\"doIt();\"></body>\n" }, { "answer_id": 601866, "author": "cmcginty", "author_id": 64313, "author_profile": "https://Stackoverflow.com/users/64313", "pm_score": 3, "selected": false, "text": "addEventListener(\"load\",fn,false) script document.createElement('script') function addJavaScript( js, onload ) {\n var head, ref;\n head = document.getElementsByTagName('head')[0];\n if (!head) { return; }\n script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = js;\n script.addEventListener( \"load\", onload, false );\n head.appendChild(script);\n}\n" }, { "answer_id": 11761498, "author": "Brian Scott", "author_id": 135731, "author_profile": "https://Stackoverflow.com/users/135731", "pm_score": 0, "selected": false, "text": "_spBodyOnLoadFunctionNames.push(\"yourFunction\");\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1992/" ]
19,058
<p>Example:</p> <pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') </code></pre> <p>and </p> <pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') </code></pre> <p>return different results</p>
[ { "answer_id": 19202, "author": "mauriciopastrana", "author_id": 547, "author_profile": "https://Stackoverflow.com/users/547", "pm_score": 3, "selected": false, "text": "USING\nENTERED\nSTORED\nSELECT of date column\n\n\nYY\n22-FEB-01\n22-FEB-1901\n22-FEB-01\n\n\nYYYY\n22-FEB-01\n22-FEB-0001\n22-FEB-0001\n\n\nRR\n22-FEB-01\n22-FEB-2001\n22-FEB-01\n\n\nRRRR\n22-FEB-01\n22-FEB-2001\n22-FEB-2001 \n" }, { "answer_id": 34434455, "author": "Pritam Bhansali", "author_id": 4585034, "author_profile": "https://Stackoverflow.com/users/4585034", "pm_score": 0, "selected": false, "text": "RR RRRR TO_DATE() TO_CHAR()" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
19,089
<p>I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.</p> <p>So far I have this (simplified):</p> <pre><code>DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName </code></pre> <p>The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist.</p> <p>Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option).</p> <p>I'm using SQL Server 2005.</p> <p><strong>Edit: @Lee:</strong> Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL.</p> <p><strong>Edit: @BCS:</strong> I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.</p>
[ { "answer_id": 19098, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "IF (EXISTS (SELECT * FROM MyTable WHERE StaffName = @StaffName))\nbegin\n UPDATE MyTable SET ... WHERE StaffName = @StaffName\nend\nelse\nbegin\n INSERT MyTable ...\nend \n" }, { "answer_id": 19099, "author": "Lee", "author_id": 1954, "author_profile": "https://Stackoverflow.com/users/1954", "pm_score": 2, "selected": false, "text": "SELECT StaffName, SUM(InStage1) AS 'JobsAtStage1', SUM(InStage2) AS 'JobsAtStage2'\n FROM ViewJob\nGROUP BY StaffName\n" }, { "answer_id": 19105, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 0, "selected": false, "text": "select distinct(rt1.StaffName), rt2.Stage1Count, rt3.Stage2Count\nfrom @ResultTable rt1\nleft join @ResultTable rt2 on rt1.StaffName=rt2.StaffName and rt2.Stage1Count is not null\nleft join @ResultTable rt3 on rt1.StaffName=rt2.StaffName and rt3.Stage2Count is not null\n" }, { "answer_id": 19109, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 2, "selected": true, "text": "INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count)\n SELECT StaffName,0,0 FROM ViewJob\n GROUP BY StaffName\n\nUPDATE @ResultTable Stage1Count= (\n SELECT COUNT(*) AS count FROM ViewJob\n WHERE InStage1 = 1\n @ResultTable.StaffName = StaffName)\n\nUPDATE @ResultTable Stage2Count= (\n SELECT COUNT(*) AS count FROM ViewJob\n WHERE InStage2 = 1\n @ResultTable.StaffName = StaffName)\n" }, { "answer_id": 19198, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 0, "selected": false, "text": "CREATE TABLE #ResultTable\n(\n StaffName nvarchar(100),\n Stage1Count int,\n Stage2Count int\n)\n\nINSERT INTO #ResultTable (StaffName)\n SELECT StaffName FROM ViewJob\n GROUP BY StaffName\n\nUPDATE #ResultTable SET \n Stage1Count= (\n SELECT COUNT(*) FROM ViewJob V\n WHERE InStage1 = 1 AND \n V.StaffName = @ResultTable.StaffName COLLATE Latin1_General_CI_AS\n GROUP BY V.StaffName),\n Stage2Count= (\n SELECT COUNT(*) FROM ViewJob V\n WHERE InStage2 = 1 AND \n V.StaffName = @ResultTable.StaffName COLLATE Latin1_General_CI_AS\n GROUP BY V.StaffName)\n\nSELECT StaffName, Stage1Count, Stage2Count FROM #ResultTable\n\nDROP TABLE #ResultTable\n" } ]
2008/08/20
[ "https://Stackoverflow.com/questions/19089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]