qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
338,934
<p>I am using the SharpZipLib open source .net library from <a href="http://www.icsharpcode.net" rel="nofollow noreferrer">www.icsharpcode.net</a></p> <p>My goal is to unzip an xml file and read it into a dataset. However I get the following error reading the file into a dataset: "Data at the root level is invalid. Line 1, position 1." I believe what is happening is the unzipping code is not releasing the file for the following reasons.</p> <p>1.) If I unzip the file and exit the application. When I restart the app I CAN read the unzipped file into a dataset. 2.) If I read in the xml file right after writing it out (no zipping) then it works fine.<br> 3.) If I write the dataset to xml, zip it up, unzip it, then attempt to read it back in I get the exception. </p> <p>The code below is pretty straight forward. UnZipFile will return the name of the file just unzipped. Right below this call is the call to read it into a dataset. The variable fileToRead is the full path to the newly unzipped xml file.</p> <pre><code>string fileToRead = UnZipFile(filepath, DOViewerUploadStoreArea); ds.ReadXml(fileToRead ) private string UnZipFile(string file, string dirToUnzipTo) { string unzippedfile = ""; try { ZipInputStream s = new ZipInputStream(File.OpenRead(file)); ZipEntry myEntry; string tmpEntry = String.Empty; while ((myEntry = s.GetNextEntry()) != null) { string directoryName = dirToUnzipTo; string fileName = Path.GetFileName(myEntry.Name); string fileWDir = directoryName + fileName; unzippedfile = fileWDir; FileStream streamWriter = File.Create(fileWDir); int size = 4096; byte[] data = new byte[4096]; while (true) { size = s.Read(data, 0, data.Length); if (size &gt; 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } s.Close(); } catch (Exception ex) { LogStatus.WriteErrorLog(ex, "ERROR", "DOViewer.UnZipFile"); } return (unzippedfile); } </code></pre>
[ { "answer_id": 338991, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "IDisposable Dispose() using Path.Combine myEntry.Name private string UnZipFile(string file, string dirToUnzipTo)\n {\n\n string unzippedfile = \"\";\n\n try\n {\n using(Stream inStream = File.OpenRead(file))\n using (ZipInputStream s = new ZipInputStream(inStream))\n {\n ZipEntry myEntry;\n byte[] data = new byte[4096];\n while ((myEntry = s.GetNextEntry()) != null)\n {\n string fileWDir = Path.Combine(dirToUnzipTo, myEntry.Name);\n string dir = Path.GetDirectoryName(fileWDir);\n // note only supports a single level of sub-directories...\n if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);\n unzippedfile = fileWDir; // note; returns last file if multiple\n\n using (FileStream outStream = File.Create(fileWDir))\n {\n int size;\n while ((size = s.Read(data, 0, data.Length)) > 0)\n {\n outStream.Write(data, 0, size);\n }\n outStream.Close();\n }\n }\n s.Close();\n }\n\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex);\n\n }\n return (unzippedfile);\n }\n" }, { "answer_id": 339208, "author": "Ron Skufca", "author_id": 4096, "author_profile": "https://Stackoverflow.com/users/4096", "pm_score": 0, "selected": false, "text": "private string UnZipFile(string file, string dirToUnzipTo)\n {\n string unzippedfile = \"\";\n\n try\n {\n using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))\n {\n\n ZipEntry theEntry;\n while ((theEntry = s.GetNextEntry()) != null)\n {\n string directoryName = dirToUnzipTo;\n string fileName = Path.GetFileName(theEntry.Name);\n string fileWDir = directoryName + fileName;\n unzippedfile = fileWDir;\n\n if (fileName != String.Empty)\n {\n using (FileStream streamWriter = File.Create(fileWDir))\n {\n int size = 2048;\n byte[] data = new byte[2048];\n while (true)\n {\n size = s.Read(data, 0, data.Length);\n if (size > 0)\n {\n streamWriter.Write(data, 0, size);\n }\n else\n {\n break;\n }\n }\n }\n }\n }\n }\n }\n catch (Exception ex)\n {\n LogStatus.WriteErrorLog(ex, \"ERROR\", \"DOViewer.UnZipFile\");\n\n }\n return (unzippedfile);\n }\n" }, { "answer_id": 869535, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 0, "selected": false, "text": "using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n{\n zip.ExtractAll(TargetDirectory); \n}\n using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n{\n foreach (ZipEntry e in zip)\n {\n if (wantThisFile(e.FileName)) e.Extract(TargetDirectory);\n }\n}\n using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n{\n zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);\n}\n using (ZipFile zip = ZipFile.Read(ExistingZipFile))\n{\n zip.Password = \"Shhhh, Very Secret!\";\n zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
338,935
<p>I am binding a List to a DataGridView. One property of the SomeObject class will be a status code (ex. Red, Yellow, Green). Can I "bind" the status to the background color of a cell easily? How about binding to a tooltip also?</p>
[ { "answer_id": 340067, "author": "Dave R.", "author_id": 42841, "author_profile": "https://Stackoverflow.com/users/42841", "pm_score": 6, "selected": true, "text": "using System.Drawing;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n private BindingSource _source = new BindingSource();\n\n public Form1()\n {\n InitializeComponent();\n\n _source.Add(new MyData(Status.Amber, \"Item A\"));\n _source.Add(new MyData(Status.Red, \"Item B\"));\n _source.Add(new MyData(Status.Green, \"Item C\"));\n _source.Add(new MyData(Status.Green, \"Item D\"));\n\n dataGridView1.DataSource = _source;\n dataGridView1.Columns[0].Visible = false;\n }\n\n private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n {\n if (e.ColumnIndex == 1)\n {\n DataGridView dgv = sender as DataGridView;\n MyData data = dgv.Rows[e.RowIndex].DataBoundItem as MyData;\n\n switch (data.Status)\n {\n case Status.Green:\n e.CellStyle.BackColor = Color.Green;\n break;\n case Status.Amber:\n e.CellStyle.BackColor = Color.Orange;\n break;\n case Status.Red:\n e.CellStyle.BackColor = Color.Red;\n break;\n }\n }\n }\n }\n\n public class MyData\n {\n public Status Status { get; set; }\n public string Text { get; set; }\n\n public MyData(Status status, string text)\n {\n Status = status;\n Text = text;\n }\n }\n\n public enum Status\n {\n Green,\n Amber,\n Red\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
338,944
<p>I'm working on a JIRA implementation and need to make use of the API. </p> <p>Does anyone know of an existing .NET wrapper for the JIRA SOAP API? </p>
[ { "answer_id": 6009304, "author": "Patrik Lindström", "author_id": 648076, "author_profile": "https://Stackoverflow.com/users/648076", "pm_score": 4, "selected": false, "text": "this.JiraSrvTalker.createIssue(string In0 and,RemoteIssue In1)\n this.LoginToken = this.JiraSrvTalker.login(JiraAdmin, JiraAdminPwd);\n" }, { "answer_id": 7157754, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 3, "selected": false, "text": "http://<servername>/rpc/soap/jirasoapservice-v2?wsdl <servername> var jira = new com.myserver.JiraSoapServiceService();\nvar loginToken = jira.login(\"user\", \"pass\");\nvar issue = new com.myserver.RemoteIssue();\njira.createIssue(loginToken, issue);\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3452/" ]
338,945
<p>When debugging my VS2005 project, I get the following error when I attempt to step into the function that returns the <em>vScenarioDescriptions</em> local variable it's struggling with...</p> <p><em><a href="http://people.ict.usc.edu/~crotchett/images/symbolnotdefined.JPG" rel="nofollow noreferrer">image no longer available http://people.ict.usc.edu/~crotchett/images/symbolnotdefined.JPG</a></em></p> <p>As I continue to walk through the code and step into functions, it appears I'm getting this error other local variables as well. Any ideas?</p> <p>Thanks in advance for your help!</p>
[ { "answer_id": 338958, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "namespace::" }, { "answer_id": 339039, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "vScenarioDescription" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191808/" ]
338,950
<p>How would one code the following C# code in Managed C++</p> <pre><code>void Foo() { using (SqlConnection con = new SqlConnection("connectionStringGoesHere")) { //do stuff } } </code></pre> <p><strong>Clarificaton:</strong> For managed objects.</p>
[ { "answer_id": 339109, "author": "Mike Hall", "author_id": 18202, "author_profile": "https://Stackoverflow.com/users/18202", "pm_score": -1, "selected": false, "text": "void Foo()\n{\n {\n SqlConnection con = new SqlConnection(\"connectionStringGoesHere\");\n // do stuff\n // delete it before end of scope of course!\n }\n}\n" }, { "answer_id": 339430, "author": "jyoung", "author_id": 14841, "author_profile": "https://Stackoverflow.com/users/14841", "pm_score": 2, "selected": false, "text": "void Foo(){\n SqlConnection con(\"connectionStringGoesHere\");\n //do stuff\n}\n" }, { "answer_id": 339818, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 6, "selected": true, "text": "{\n SqlConnection conn(connectionString);\n}\n SqlConnection^ conn = nullptr;\ntry\n{\n conn = gcnew SqlConnection(conntectionString);\n\n}\nfinally\n{\n if (conn != nullptr)\n delete conn;\n}\n" }, { "answer_id": 673336, "author": "Nick", "author_id": 3233, "author_profile": "https://Stackoverflow.com/users/3233", "pm_score": 2, "selected": false, "text": "void foo()\n{\n using( Foo, p, gcnew Foo() )\n {\n p->x = 100;\n }\n}\n template <typename T>\npublic ref class using_auto_ptr\n{\npublic:\n using_auto_ptr(T ^p) : m_p(p),m_use(1) {}\n ~using_auto_ptr() { delete m_p; }\n T^ operator -> () { return m_p; }\n int m_use;\nprivate:\n T ^ m_p;\n};\n\n#define using(CLASS,VAR,ALLOC) \\\n for ( using_auto_ptr<CLASS> VAR(ALLOC); VAR.m_use; --VAR.m_use)\n public ref class Foo\n{\npublic:\n Foo() : x(0) {}\n ~Foo()\n {\n }\n int x;\n};\n" }, { "answer_id": 45947572, "author": "Siamand", "author_id": 2276651, "author_profile": "https://Stackoverflow.com/users/2276651", "pm_score": 0, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\n\nclass Disposable{\nprivate:\n int disposed=0;\npublic:\n int notDisposed(){\n return !disposed;\n }\n\n void doDispose(){\n disposed = true;\n dispose();\n }\n\n virtual void dispose(){}\n\n};\n\n\n\nclass Connection : public Disposable {\n\nprivate:\n Connection *previous=nullptr;\npublic:\n static Connection *instance;\n\n Connection(){\n previous=instance;\n instance=this;\n }\n\n void dispose(){\n delete instance;\n instance = previous;\n }\n};\n\nConnection *Connection::instance=nullptr;\n\n\n#define using(obj) for(Disposable *__tmpPtr=obj;__tmpPtr->notDisposed();__tmpPtr->doDispose())\n\nint Execute(const char* query){\n if(Connection::instance == nullptr){\n cout << \"------- No Connection -------\" << endl;\n cout << query << endl;\n cout << \"------------------------------\" << endl;\n cout << endl;\n\n return -1;//throw some Exception\n }\n\n cout << \"------ Execution Result ------\" << endl;\n cout << query << endl;\n cout << \"------------------------------\" << endl;\n cout << endl;\n\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n\n using(new Connection())\n {\n Execute(\"SELECT King FROM goats\");//out of the scope\n }\n\n Execute(\"SELECT * FROM goats\");//in the scope\n\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
338,951
<p>I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.</p> <p>When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.</p> <p>On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.</p> <p>This is the salient code that allows me to pop up a console from the command line:</p> <pre><code>&lt;STAThread()&gt; Public Shared Sub Main() If My.Application.CommandLineArgs.Count = 0 Then Dim frm As New ISECMMParamUtilForm() frm.ShowDialog() Else Try ConsoleControl.AllocConsole() Dim exMan As New UnattendedExecutionManager(ConvertArgs()) IsInConsoleMode = True OutputMessage("Application started.") If Not exMan.SetSettings() Then OutputMessage("Execution failed.") End If Catch ex As Exception Console.WriteLine(ex.ToString()) Finally ConsoleControl.FreeConsole() End Try End If End Sub Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False) Trace.WriteLine(msg) If IsInConsoleMode Then Console.WriteLine(msg) End If If isError Then EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error) Else EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information) End If End Sub </code></pre>
[ { "answer_id": 415064, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "IMAGE_SUBSYSTEM_WINDOWS_GUI IMAGE_SUBSYSTEM_WINDOWS_CUI" }, { "answer_id": 70998076, "author": "Zhu Panda", "author_id": 17470361, "author_profile": "https://Stackoverflow.com/users/17470361", "pm_score": 1, "selected": false, "text": "Console.GetCursorPosition() (0, 0) class Program\n{\n public static void Main\n {\n if (Console.GetCursorPosition() == (0, 0))\n {\n //something GUI\n }\n else\n {\n //something not GUI\n }\n }\n}\n Console.GetCursorPosition()" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
338,978
<p>Here's my table: </p> <pre><code>CREATE TABLE `alums_alumphoto` ( `id` int(11) NOT NULL auto_increment, `alum_id` int(11) NOT NULL, `photo_id` int(11) default NULL, `media_id` int(11) default NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`), KEY `alums_alumphoto_alum_id` (`alum_id`), KEY `alums_alumphoto_photo_id` (`photo_id`), KEY `alums_alumphoto_media_id` (`media_id`), CONSTRAINT `alums_alumphoto_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES `media_mediaitem` (`id`), CONSTRAINT `alum_id_refs_id_706915ea` FOREIGN KEY (`alum_id`) REFERENCES `alums_alum` (`id`), CONSTRAINT `photo_id_refs_id_63282119` FOREIGN KEY (`photo_id`) REFERENCES `media_mediaitem` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=utf8 </code></pre> <p>I want to delete the column <code>photo_id</code>, which presumably will also require deleting the foreign key constraint and the index.</p> <p>The problem is that I get errors when I try to drop the column: </p> <pre>ERROR 1025 (HY000): Error on rename of '.\dbname\#sql-670_c5c' to '.\dbname\alums_alumphoto' (errno: 150)</pre> <p>... when I try to drop the index (same as above), and when I try to drop the foreign key constraint: </p> <pre>ERROR 1091 (42000): Can't DROP 'photo_id_refs_id_63282119'; check that column/key exists)</pre> <p>What order should I be doing all of this in? What precise commands should I be using?</p>
[ { "answer_id": 339015, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 4, "selected": true, "text": "> CREATE TABLE alums_alumphoto_new LIKE alums_alumphoto;\n> ALTER TABLE .... // Drop constraint\n> ALTER TABLE .... // Drop KEY\n> ALTER TABLE .... // Drop the column\n> INSERT INTO alums_alumphoto_new (SELECT id, alum_id, photo_id, media_id, updated FROM alums_alumphoto);\n> RENAME TABLE alums_alumphoto TO alums_alumphoto_old, alums_alumphoto_new TO alums_alumphoto;\n" }, { "answer_id": 340713, "author": "Rishi Agarwal", "author_id": 29532, "author_profile": "https://Stackoverflow.com/users/29532", "pm_score": 5, "selected": false, "text": "ALTER TABLE `alums_alumphoto` DROP FOREIGN KEY `photo_id_refs_id_63282119`;\n photo_id ALTER TABLE `alums_alumphoto` DROP COLUMN `photo_id`;\n ALTER TABLE `alums_alumphoto` \n DROP FOREIGN KEY `photo_id_refs_id_63282119` , \n DROP COLUMN `photo_id`;\n" }, { "answer_id": 375517, "author": "Ed Mays", "author_id": 47166, "author_profile": "https://Stackoverflow.com/users/47166", "pm_score": 0, "selected": false, "text": "ALTER TABLE `alums_alumphoto` \n DROP KEY KEY `alums_alumphoto_photo_id`,\n DROP FOREIGN KEY `photo_id_refs_id_63282119`;\n\nALTER TABLE `alums_alumphoto` \n DROP COLUMN `photo_id`;\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35579/" ]
338,981
<p>My dilema:</p> <p>In .htaccess in my website's root:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.example\.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] </code></pre> <p>In .htaccess in the subdirectory /foo</p> <pre><code>RewriteEngine On RewriteRule ^page1\.html$ /foo/page2.html [R=301] </code></pre> <p>In the first, I'm trying to ensure all requests include the beginning www. In the second, I'm redirecting requests for page1.html in the foo subdirectory to page2.html, also in that subdirectory.</p> <p>In my browser, trying to visit:</p> <p><a href="http://www.example.com/foo/page2.html" rel="nofollow noreferrer">http://www.example.com/foo/page2.html</a> &lt;== works, good</p> <p><a href="http://www.example.com/foo/page1.html" rel="nofollow noreferrer">http://www.example.com/foo/page1.html</a> &lt;== redirects to <a href="http://www.example.com/foo/page2.html" rel="nofollow noreferrer">http://www.example.com/foo/page2.html</a>, good</p> <p><a href="http://example.com/foo/page1.html" rel="nofollow noreferrer">http://example.com/foo/page1.html</a> &lt;== redirects to <a href="http://www.example.com/foo/page2.html" rel="nofollow noreferrer">http://www.example.com/foo/page2.html</a>, good</p> <p><strong><a href="http://example.com/foo/page2.html" rel="nofollow noreferrer">http://example.com/foo/page2.html</a> &lt;== no redirect occurs, bad</strong></p> <p>==> Should redirect to: http://**www.**example.com/foo/page2.html</p> <p>Through experimenting, it would seem the redirect rules in the .htaccess file in the website's root only take effect for requests to pages in that subdirectory <strong>IF</strong> that subdirectory does not contain a .htaccess file, or it does and specifies a rewrite rule that does take effect for this particular request.</p> <p><strong>Can anyone see what I'm doing wrong?</strong> How can I get the rewrite rule that sticks the www. in if it's missing to fire for <a href="http://example.com/foo/page2.html" rel="nofollow noreferrer">http://example.com/foo/page2.html</a>?</p> <hr> <p>Thank you hop, that worked!</p> <p>For the record, I then had to change the rewrite rule in the file in the site's root to:</p> <pre><code>RewriteRule ^.*$ http://www.example.com%{REQUEST_URI} [R=301,L] </code></pre> <p>Which is just fine. Thanks!</p>
[ { "answer_id": 339188, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "/.htaccess /foo/.htaccess .htaccess .htaccess RewriteEngine On\nRewriteCond %{HTTP_HOST} !^www\\.example\\.com [NC]\nRewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]\nRewriteRule ^foo/page1\\.html$ /foo/page2.html [R=301]\n" }, { "answer_id": 339287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "foo/.htaccess RewriteOptions inherit\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16272/" ]
338,986
<p>In a <a href="http://www.hackification.com/2008/12/03/linq-to-entities-the-blackberry-storm-of-orms/" rel="nofollow noreferrer">controversial blog post</a> today, Hackification pontificates on what appears to be a bug in the new LINQ To Entities framework: </p> <blockquote> <p>Suppose I search for a customer:</p> <pre><code>var alice = data.Customers.First( c =&gt; c.Name == "Alice" ); </code></pre> <p>Fine, that works nicely. Now let’s see if I can find one of her orders:</p> <pre><code> var order = ( from o in alice.Orders where o.Item == "Item_Name" select o ).FirstOrDefault(); </code></pre> <p>LINQ-to-SQL will find the child row. LINQ-to-Entities will silently return nothing.</p> <p>Now let’s suppose I iterate through all orders in the database:</p> <pre><code>foreach( var order in data.Orders ) { Console.WriteLine( "Order: " + order.Item ); } </code></pre> <p>And now repeat my search:</p> <pre><code>var order = ( from o in alice.Orders where o.Item == "Item_Name" select o ).FirstOrDefault(); </code></pre> <p>Wow! LINQ-to-Entities is suddenly telling me the child object exists, despite telling me earlier that it didn’t!</p> </blockquote> <p>My initial reaction was that this had to be a bug, but after further consideration (and <a href="http://www.infoq.com/news/2008/12/Lazy-Loading" rel="nofollow noreferrer">backed up by the ADO.NET Team</a>), I realized that this behavior was caused by the Entity Framework not lazy loading the Orders subquery when Alice is pulled from the datacontext.</p> <p>This is because order is a LINQ-To-Object query:</p> <pre><code>var order = ( from o in alice.Orders where o.Item == "Item_Name" select o ).FirstOrDefault(); </code></pre> <p>And is not accessing the datacontext in any way, while his foreach loop:</p> <pre><code> foreach( var order in data.Orders ) </code></pre> <p>Is accessing the datacontext.</p> <p>LINQ-To-SQL actually created lazy loaded properties for Orders, so that when accessed, would perform another query, LINQ to Entities leaves it up to you to manually retrieve related data.</p> <p>Now, I'm not a big fan of ORM's, and this is precisly the reason. I've found that in order to have all the data you want ready at your fingertips, they repeatedly execute queries behind your back, for example, that linq-to-sql query above might run an additional query per row of Customers to get Orders.</p> <p>However, the EF not doing this seems to majorly violate the principle of least surprise. While it is a technically correct way to do things (You should run a second query to retrieve orders, or retrieve everything from a view), it does not behave like you would expect from an ORM.</p> <p><strong>So, is this good framework design? Or is Microsoft over thinking this for us?</strong> </p>
[ { "answer_id": 339000, "author": "dtc", "author_id": 32892, "author_profile": "https://Stackoverflow.com/users/32892", "pm_score": 1, "selected": false, "text": "from o in alice.Orders where o.Item == \"Item_Name\" select o\n" }, { "answer_id": 378216, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 4, "selected": false, "text": "// Lazy Load Orders \nvar alice2 = data.Customers.First(c => c.Name == \"Alice\");\n\n// Should Load the Orders\nif (!alice2.Orders.IsLoaded)\n alice2.Orders.Load();\n // Include Orders in original query\nvar alice = data.Customers.Include(\"Orders\").First(c => c.Name == \"Alice\");\n\n// Should already be loaded\nif (!alice.Orders.IsLoaded)\n alice.Orders.Load();\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
338,988
<p>How do you get/set the absolute position of a MovieClip in Flash/AS3? And by absolute, I mean its position relative to the stage's origo.</p> <p>I currently have this setter:</p> <pre><code>class MyMovieClip extends MovieClip { function set xAbs(var x:Number):void { this.x = -(this.parent.localToGlobal(new Point()).x) + x; } } </code></pre> <p>This seems to work, but I have a feeling it requires that the Stage is left aligned.</p> <p>However, I don't have a working getter. This doesn't work:</p> <pre><code>public function get xAbs():Number { return -(this.parent.localToGlobal(new Point()).x) + this.x; // Doesn't work } </code></pre> <p>I'm aiming for a solution that works, and works with all Stage alignments, but it's tricky. I'm using this on a Stage which is relative to the browser's window size.</p> <p>EDIT: This works for a top-left aligned stage; not sure about others:</p> <pre><code>public function get AbsX():Number { return this.localToGlobal(new Point(0, 0)).x; } public function get AbsY():Number { return this.localToGlobal(new Point(0, 0)).y; } public function set AbsX(x:Number):void { this.x = x - this.parent.localToGlobal(new Point(0, 0)).x; } public function set AbsY(y:Number):void { this.y = y - this.parent.localToGlobal(new Point(0, 0)).y; } </code></pre>
[ { "answer_id": 339068, "author": "moritzstefaner", "author_id": 23069, "author_profile": "https://Stackoverflow.com/users/23069", "pm_score": 3, "selected": false, "text": "var x=this.parent.localToGlobal(new Point(this.x,0)).x; \n globalToLocal(this.stage)" }, { "answer_id": 2256564, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": 0, "selected": false, "text": "mynestesprite.addEventListener (MouseEvent.MOUSE_OVER, myover)\nfunction myover(e:MouseEvent){\n // e.target.parent.parent ....\n trace ( e.target.parent.parent.mouseX, e.target.parent.parent.mouseY)\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724/" ]
339,004
<p>We are busy developing a Java web service for a client. There are two possible choices:</p> <ul> <li><p>Store the encrypted user name / password on the web service client. Read from a config. file on the client side, decrypt and send.</p></li> <li><p>Store the encrypted user name / password on the web server. Read from a config. file on the web server, decrypt and use in the web service.</p></li> </ul> <p>The user name / password is used by the web service to access a third-party application.</p> <p>The client already has classes that provide this functionality but this approach involves sending the user name / password in the clear (albeit within the intranet). They would prefer storing the info. within the web service but don't really want to pay for something they already have. (Security is not a big consideration because it's only within their intranet).</p> <p>So we need something quick and easy in Java.</p> <p>Any recommendations?</p> <p>The server is Tomkat 5.5. The web service is Axis2.</p> <ul> <li>What encrypt / decrypt package should we use?</li> <li>What about a key store?</li> <li>What configuration mechanism should we use?</li> <li>Will this be easy to deploy?</li> </ul>
[ { "answer_id": 339769, "author": "Gennady Shumakher", "author_id": 42512, "author_profile": "https://Stackoverflow.com/users/42512", "pm_score": 5, "selected": false, "text": "// only the first 8 Bytes of the constructor argument are used \n// as material for generating the keySpec\nDESKeySpec keySpec = new DESKeySpec(\"YourSecr\".getBytes(\"UTF8\")); \nSecretKeyFactory keyFactory = SecretKeyFactory.getInstance(\"DES\");\nSecretKey key = keyFactory.generateSecret(keySpec);\nsun.misc.BASE64Encoder base64encoder = new BASE64Encoder();\nsun.misc.BASE64Decoder base64decoder = new BASE64Decoder();\n.........\n\n// ENCODE plainTextPassword String\nbyte[] cleartext = plainTextPassword.getBytes(\"UTF8\"); \n\nCipher cipher = Cipher.getInstance(\"DES\"); // cipher is not thread safe\ncipher.init(Cipher.ENCRYPT_MODE, key);\nString encrypedPwd = base64encoder.encode(cipher.doFinal(cleartext));\n// now you can store it \n......\n\n// DECODE encryptedPwd String\nbyte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);\n\nCipher cipher = Cipher.getInstance(\"DES\");// cipher is not thread safe\ncipher.init(Cipher.DECRYPT_MODE, key);\nbyte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9922/" ]
339,007
<p>How do I pad a numeric string with zeroes to the left, so that the string has a specific length?</p>
[ { "answer_id": 339012, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": false, "text": "zfill print(f'{number:05d}') # (since Python 3.6), or\nprint('{:05d}'.format(number)) # or\nprint('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)\nprint('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)\nprint(format(number, '05d'))\n" }, { "answer_id": 339013, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 13, "selected": true, "text": ">>> n = '4'\n>>> print(n.zfill(3))\n004\n >>> n = 4\n>>> print(f'{n:03}') # Preferred method, python >= 3.6\n004\n>>> print('%03d' % n)\n004\n>>> print(format(n, '03')) # python >= 2.6\n004\n>>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3\n004\n>>> print('{foo:03d}'.format(foo=n)) # python >= 2.6 + python 3\n004\n>>> print('{:03d}'.format(n)) # python >= 2.7 + python3\n004\n" }, { "answer_id": 339019, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 4, "selected": false, "text": "width = 10\nx = 5\nprint \"%0*d\" % (width, x)\n> 0000000005\n print(\"%0*d\" % (width, x))\n print() printf()" }, { "answer_id": 339024, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 9, "selected": false, "text": "rjust >>> s = 'test'\n>>> s.rjust(10, '0')\n>>> '000000test'\n" }, { "answer_id": 6196270, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ">>> a = 6340\n>>> b = 90210\n>>> print '%05d' % a\n06340\n>>> print '%05d' % b\n90210\n" }, { "answer_id": 6196350, "author": "johnsyweb", "author_id": 78845, "author_profile": "https://Stackoverflow.com/users/78845", "pm_score": 5, "selected": false, "text": "str(n).zfill(width) string int float >>> n = 3\n>>> str(n).zfill(5)\n'00003'\n>>> n = '3'\n>>> str(n).zfill(5)\n'00003'\n>>> n = '3.0'\n>>> str(n).zfill(5)\n'003.0'\n" }, { "answer_id": 14269071, "author": "Victor Barrantes", "author_id": 1968365, "author_profile": "https://Stackoverflow.com/users/1968365", "pm_score": 6, "selected": false, "text": ">>> '99'.zfill(5)\n'00099'\n>>> '99'.rjust(5,'0')\n'00099'\n >>> '99'.ljust(5,'0')\n'99000'\n" }, { "answer_id": 16408018, "author": "J Lacar", "author_id": 2356265, "author_profile": "https://Stackoverflow.com/users/2356265", "pm_score": 0, "selected": false, "text": "str(n) def pad_left(n, width, pad=\"0\"):\n return ((pad * width) + str(n))[-width:]\n" }, { "answer_id": 24386708, "author": "Cees Timmerman", "author_id": 819417, "author_profile": "https://Stackoverflow.com/users/819417", "pm_score": 7, "selected": false, "text": ">>> i = 1\n>>> f\"{i:0>2}\" # Works for both numbers and strings.\n'01'\n>>> f\"{i:02}\" # Works only for numbers.\n'01'\n >>> \"{:0>2}\".format(\"1\") # Works for both numbers and strings.\n'01'\n>>> \"{:02}\".format(1) # Works only for numbers.\n'01'\n" }, { "answer_id": 38353814, "author": "elad silver", "author_id": 1807569, "author_profile": "https://Stackoverflow.com/users/1807569", "pm_score": 5, "selected": false, "text": "hour = 4\nminute = 3\n\"{:0>2}:{:0>2}\".format(hour,minute)\n# prints 04:03\n\n\"{:0>3}:{:0>5}\".format(hour,minute)\n# prints '004:00003'\n\n\"{:0<3}:{:0<5}\".format(hour,minute)\n# prints '400:30000'\n\n\"{:$<3}:{:#<5}\".format(hour,minute)\n# prints '4$$:3####'\n" }, { "answer_id": 44800566, "author": "Simon Steinberger", "author_id": 996638, "author_profile": "https://Stackoverflow.com/users/996638", "pm_score": 2, "selected": false, "text": "setup = '''\nfrom random import randint\ndef test_1():\n num = randint(0,1000000)\n return str(num).zfill(7)\ndef test_2():\n num = randint(0,1000000)\n return format(num, '07')\ndef test_3():\n num = randint(0,1000000)\n return '{0:07d}'.format(num)\ndef test_4():\n num = randint(0,1000000)\n return format(num, '07d')\ndef test_5():\n num = randint(0,1000000)\n return '{:07d}'.format(num)\ndef test_6():\n num = randint(0,1000000)\n return '{x:07d}'.format(x=num)\ndef test_7():\n num = randint(0,1000000)\n return str(num).rjust(7, '0')\n'''\nimport timeit\nprint timeit.Timer(\"test_1()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_2()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_3()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_4()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_5()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_6()\", setup=setup).repeat(3, 900000)\nprint timeit.Timer(\"test_7()\", setup=setup).repeat(3, 900000)\n\n\n> [2.281613943830961, 2.2719342631547077, 2.261691106209631]\n> [2.311480238815406, 2.318420542148333, 2.3552384305184493]\n> [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]\n> [2.312442972404032, 2.318053102249902, 2.3054072168069872]\n> [2.3482314132374853, 2.3403386400002475, 2.330108825844775]\n> [2.424549090688892, 2.4346475296851438, 2.429691196530058]\n> [2.3259756401716487, 2.333549212826732, 2.32049893822186]\n zfill" }, { "answer_id": 51128565, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 5, "selected": false, "text": "str.zfill >>> '1'.zfill(4)\n'0001'\n + - >>> '+1'.zfill(4)\n'+001'\n>>> '-1'.zfill(4)\n'-001'\n str.zfill >>> help(str.zfill)\nHelp on method_descriptor:\n\nzfill(...)\n S.zfill(width) -> str\n\n Pad a numeric string S with zeros on the left, to fill a field\n of the specified width. The string S is never truncated.\n >>> min(timeit.repeat(lambda: '1'.zfill(4)))\n0.18824880896136165\n>>> min(timeit.repeat(lambda: '1'.rjust(4, '0')))\n0.2104538488201797\n>>> min(timeit.repeat(lambda: f'{1:04}'))\n0.32585487607866526\n>>> min(timeit.repeat(lambda: '{:04}'.format(1)))\n0.34988890308886766\n % >>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))\n0.19728074967861176\n>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))\n0.2347015216946602\n zfill Objects/stringlib/transmogrify.h static PyObject *\nstringlib_zfill(PyObject *self, PyObject *args)\n{\n Py_ssize_t fill;\n PyObject *s;\n char *p;\n Py_ssize_t width;\n\n if (!PyArg_ParseTuple(args, \"n:zfill\", &width))\n return NULL;\n\n if (STRINGLIB_LEN(self) >= width) {\n return return_self(self);\n }\n\n fill = width - STRINGLIB_LEN(self);\n\n s = pad(self, fill, 0, '0');\n\n if (s == NULL)\n return NULL;\n\n p = STRINGLIB_STR(s);\n if (p[fill] == '+' || p[fill] == '-') {\n /* move sign to beginning of string */\n p[0] = p[fill];\n p[fill] = '0';\n }\n\n return s;\n}\n >>> '1'.zfill(width=4)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: zfill() takes no keyword arguments\n >>> '1'.zfill(0)\n'1'\n zfill pad pad ljust rjust center static inline PyObject *\npad(PyObject *self, Py_ssize_t left, Py_ssize_t right, char fill)\n{\n PyObject *u;\n\n if (left < 0)\n left = 0;\n if (right < 0)\n right = 0;\n\n if (left == 0 && right == 0) {\n return return_self(self);\n }\n\n u = STRINGLIB_NEW(NULL, left + STRINGLIB_LEN(self) + right);\n if (u) {\n if (left)\n memset(STRINGLIB_STR(u), fill, left);\n memcpy(STRINGLIB_STR(u) + left,\n STRINGLIB_STR(self),\n STRINGLIB_LEN(self));\n if (right)\n memset(STRINGLIB_STR(u) + left + STRINGLIB_LEN(self),\n fill, right);\n }\n\n return u;\n}\n pad zfill + - >>> '+foo'.zfill(10)\n'+000000foo'\n>>> '-foo'.zfill(10)\n'-000000foo'\n" }, { "answer_id": 55988138, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 1, "selected": false, "text": "# input list of strings that we want to prepend zeros\nIn [71]: list_of_str = [\"101010\", \"10101010\", \"11110\", \"0000\"]\n\n# prepend zeros to make each string to length 8, if length of string is less than 8\nIn [83]: [\"0\"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]\nOut[83]: ['00101010', '10101010', '00011110', '00000000']\n" }, { "answer_id": 57360675, "author": "ruohola", "author_id": 9835872, "author_profile": "https://Stackoverflow.com/users/9835872", "pm_score": 5, "selected": false, "text": ">= 3.6 >>> s = f\"{1:08}\" # inline with int\n>>> s\n'00000001'\n >>> s = f\"{'1':0>8}\" # inline with str\n>>> s\n'00000001'\n >>> n = 1\n>>> s = f\"{n:08}\" # int variable\n>>> s\n'00000001'\n >>> c = \"1\"\n>>> s = f\"{c:0>8}\" # str variable\n>>> s\n'00000001'\n int >>> f\"{-1:08}\"\n'-0000001'\n\n>>> f\"{1:+08}\"\n'+0000001'\n\n>>> f\"{'-1':0>8}\"\n'000000-1'\n" }, { "answer_id": 61518229, "author": "zzfima", "author_id": 328829, "author_profile": "https://Stackoverflow.com/users/328829", "pm_score": 2, "selected": false, "text": " h = 2\n m = 7\n s = 3\n print(\"%02d:%02d:%02d\" % (h, m, s))\n" }, { "answer_id": 62827644, "author": "Julien Faujanet", "author_id": 12419998, "author_profile": "https://Stackoverflow.com/users/12419998", "pm_score": 0, "selected": false, "text": "def PadNumber(number, n_pad, add_prefix=None):\n number_str = str(number)\n paded_number = number_str.zfill(n_pad)\n if add_prefix:\n paded_number = add_prefix+paded_number\n print(paded_number)\n\nPadNumber(99, 4)\nPadNumber(1011, 8, \"b'\")\nPadNumber('7BEF', 6, \"#\")\n 0099\nb'00001011\n#007BEF\n" }, { "answer_id": 63089932, "author": "NBStephens", "author_id": 3248002, "author_profile": "https://Stackoverflow.com/users/3248002", "pm_score": 4, "selected": false, "text": ">>> pad_number = len(\"this_string\")\n11\n>>> s = f\"{1:0{pad_number}}\" }\n>>> s\n'00000000001'\n\n" }, { "answer_id": 68730826, "author": "user1315621", "author_id": 1315621, "author_profile": "https://Stackoverflow.com/users/1315621", "pm_score": 5, "selected": false, "text": "i = 12\nprint(f\"{i:05d}\")\n 00012\n" }, { "answer_id": 70949336, "author": "Lafftar", "author_id": 9420670, "author_profile": "https://Stackoverflow.com/users/9420670", "pm_score": 2, "selected": false, "text": "a = 4.432\n>> 4.432\na = f'{a:04.1f}'\n>> '04.4'\n f'{a:04.1f}'" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,041
<p>I've been working with LINQ To SQL for a little while now and when it comes to removing an entity from the DB, I've always called the table's .DeleteOnSubmit and passed in the entity. Sometimes I've found myself writing something like:</p> <pre><code>db.Users.DeleteOnSubmit(db.Users.Where(c =&gt; c.ID == xyz).Select(c =&gt; c).Single()); </code></pre> <p>This of course causes two queries. One to get the entity matching the criteria and then another to delete it. Often I have the ID of the record I need removing and I am wondering if there is a more direct way to remove a row from a table via the ID only?</p>
[ { "answer_id": 339099, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 0, "selected": false, "text": "db.spDeleteUserById(id);\n" }, { "answer_id": 339198, "author": "Christopher Edwards", "author_id": 29411, "author_profile": "https://Stackoverflow.com/users/29411", "pm_score": 3, "selected": false, "text": "public static void DeleteByPK<TSource, TPK>(TPK pk, DataContext dc)\n where TSource : class\n{\n Table<TSource> table = dc.GetTable<TSource>();\n TableDef tableDef = GetTableDef<TSource>();\n\n dc.ExecuteCommand(\"DELETE FROM [\" + tableDef.TableName\n + \"] WHERE [\" = tableDef.PKFieldName + \"] = {0}\", pk);\n}\n" }, { "answer_id": 4382966, "author": "Dragos", "author_id": 534367, "author_profile": "https://Stackoverflow.com/users/534367", "pm_score": 0, "selected": false, "text": "context.Customers.DeleteEntity(c => c.CustomerId, 12);\n\npublic static class EntityExtensions\n{\n public static EntityKey CreateEntityKey<T, TId>(this ObjectSet<T> entitySet, Expression<Func<T, TId>> entityKey, TId id)\n where T : class\n {\n var qEntitySet = entitySet.Context.DefaultContainerName + \".\" + entitySet.EntitySet.Name;\n var keyName = LinqHelper.PropertyName(entityKey);\n\n return new EntityKey(qEntitySet, keyName, id);\n }\n\n public static void DeleteEntity<T, TId>(this ObjectSet<T> entitySet, Expression<Func<T, TId>> entityKey, TId id) \n where T : EntityObject, new()\n {\n var key = CreateEntityKey(entitySet, entityKey, id);\n\n var entityInstance = new T {EntityKey = key};\n\n var propertyName = LinqHelper.PropertyName(entityKey);\n var property = typeof (T).GetProperty(propertyName);\n if (property == null)\n throw new Exception(\"Property name \" + propertyName + \" does not exist on \" + typeof(T).Name);\n property.SetValue(entityInstance, id, null);\n\n entitySet.Attach(entityInstance);\n entitySet.DeleteObject(entityInstance);\n }\n" }, { "answer_id": 17415308, "author": "Noam Ben-Ami", "author_id": 714508, "author_profile": "https://Stackoverflow.com/users/714508", "pm_score": 3, "selected": false, "text": "var myEntity = new MyEntityType { MyEntityId = xxx };\nContext.MyEntityTypeTable.Attach(myEntity, false);\nContext.MyEntityTypeTable.DeleteOnSubmit(myEntity);\nContext.SubmitChanges();\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,044
<p>A puzzler from a coworker that I cannot figure out...</p> <pre><code>update btd.dbo.tblpayroll set empname = ( select b.Legal_Name from ( SELECT Legal_Name, Employee_ID FROM Com.dbo.Workers WHERE isnumeric(Employee_ID) = 1 ) b where b.Employee_ID = empnum and b.Legal_name is not NULL ) where empname is NULL </code></pre> <hr> <p>Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value 'N0007 ' to data type int. The table alias b would actually be a view.</p> <p>The value 'N0007 ' is in the Workers table. I don't see why it is not being filtered from the results that are being joined. </p> <p>EDIT:</p> <p>The alias does, in fact, return the correct rows - so isNumeric is doing the job. </p>
[ { "answer_id": 339080, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "update btd.dbo.tblpayroll\nset empname = ( select Legal_Name\n from Com.dbo.Workers\n where isnumeric(Employee_ID) = 1\n and convert(varchar,Employee_ID)\n = convert(varchar,empnum) \n and Legal_name is not NULL)\nwhere empname is NULL\n" }, { "answer_id": 339083, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 0, "selected": false, "text": "LIKE REPLICATE('[0-9]',/*length of Employee_ID*/) \n LIKE '[0-9]%' \n" }, { "answer_id": 339162, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "ISNUMERIC()" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37379/" ]
339,045
<p>I'm not of the Perl world, so some of this is new to me. I'm running Ubuntu Hardy LTS with apache2 and mod_fcgid packages installed. I'd like to get MT4 running under fcgid rather than mod-cgi (it seems to run OK with plain-old CGI).</p> <p>I can't seem to get even a simple Perl script to run under fcgid. I created a simple "Hello World" app and included the code from <a href="https://stackoverflow.com/questions/202578/perl-modfcgid-how-can-i-be-sure-its-working">this previous question</a> to test if FCGI is running.</p> <p>I named my script HelloWorld.fcgi (currently fcgid is set to handle .fcgi files only). Code:</p> <pre><code>#!/usr/bin/perl use FCGI; print "Content-type: text/html\n\n"; print "Hello world.\n\n"; my $request = FCGI::Request(); if ( $request-&gt;IsFastCGI ) { print "we're running under FastCGI!\n"; } else { print "plain old boring CGI\n"; } </code></pre> <p>When run from the command line, it prints "plain old boring..." When invoked via an http request to apache, I get a 500 Internal Server error and the output of the script is printed to the Apache error log:</p> <pre><code>Content-type: text/html Hello world. we're running under FastCGI! [Wed Dec 03 22:26:19 2008] [warn] (104)Connection reset by peer: mod_fcgid: read data from fastcgi server error. [Wed Dec 03 22:26:19 2008] [error] [client 70.23.221.171] Premature end of script headers: HelloWorld.fcgi [Wed Dec 03 22:26:25 2008] [notice] mod_fcgid: process /www/mt/HelloWorld.fcgi(14189) exit(communication error), terminated by calling exit(), return code: 0 </code></pre> <p>When I run the .cgi version of the same code, it works fine. Any idea why the output of the script is going to the error log? Apache config is the default mod_fcgid config plus, in a VirtualHost directive:</p> <pre><code> ServerName test1.example.com DocumentRoot /www/example &lt;Directory /www/example&gt; AllowOverride None AddHandler cgi-script .cgi AddHandler fcgid-script .fcgi Options +ExecCGI +Includes +FollowSymLinks &lt;/Directory&gt; </code></pre>
[ { "answer_id": 339094, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 2, "selected": false, "text": "use FCGI;\n\nmy $count = 0;\nmy $request = FCGI::Request();\n\nwhile($request->Accept() >= 0) {\n print(\"Content-type: text/html\\r\\n\\r\\n\", ++$count);\n}\n Accept" }, { "answer_id": 391695, "author": "Brad Choate", "author_id": 553, "author_profile": "https://Stackoverflow.com/users/553", "pm_score": 2, "selected": false, "text": "#!/usr/bin/perl\n\nuse strict;\nuse CGI::Fast;\n\nmy $count = 0;\nwhile (my $q = CGI::Fast->new) {\n print(\"Content-Type: text/plain\\n\\n\");\n print(\"Process ID: $$; Count is: \" . ++$count);\n}\n mt-config.cgi AdminScript mt.fcgi\nCommentsScript mt-comments.fcgi\n" }, { "answer_id": 392281, "author": "Jamie", "author_id": 8391, "author_profile": "https://Stackoverflow.com/users/8391", "pm_score": 2, "selected": false, "text": "my $request = FCGI::Request();\nwhile($request->Accept() >= 0) {\n print(\"Content-type: text/html\\n\\n\");\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323748/" ]
339,053
<p>Using python 2.4 and the built-in <code>ZipFile</code> library, I cannot read very large zip files (greater than 1 or 2 GB) because it wants to store the entire contents of the uncompressed file in memory. Is there another way to do this (either with a third-party library or some other hack), or must I "shell out" and unzip it that way (which isn't as cross-platform, obviously).</p>
[ { "answer_id": 339506, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": true, "text": "import zipfile\nimport zlib\nimport os\n\nsrc = open( doc, \"rb\" )\nzf = zipfile.ZipFile( src )\nfor m in zf.infolist():\n\n # Examine the header\n print m.filename, m.header_offset, m.compress_size, repr(m.extra), repr(m.comment)\n src.seek( m.header_offset )\n src.read( 30 ) # Good to use struct to unpack this.\n nm= src.read( len(m.filename) )\n if len(m.extra) > 0: ex= src.read( len(m.extra) )\n if len(m.comment) > 0: cm= src.read( len(m.comment) ) \n\n # Build a decompression object\n decomp= zlib.decompressobj(-15)\n\n # This can be done with a loop reading blocks\n out= open( m.filename, \"wb\" )\n result= decomp.decompress( src.read( m.compress_size ) )\n out.write( result )\n result = decomp.flush()\n out.write( result )\n # end of the loop\n out.close()\n\nzf.close()\nsrc.close()\n" }, { "answer_id": 28766502, "author": "Martijn Pieters", "author_id": 100297, "author_profile": "https://Stackoverflow.com/users/100297", "pm_score": 4, "selected": false, "text": "ZipFile.open() import errno\nimport os\nimport shutil\nimport zipfile\n\nTARGETDIR = '/foo/bar/baz'\n\nwith open(doc, \"rb\") as zipsrc:\n zfile = zipfile.ZipFile(zipsrc)\n for member in zfile.infolist():\n target_path = os.path.join(TARGETDIR, member.filename)\n if target_path.endswith('/'): # folder entry, create\n try:\n os.makedirs(target_path)\n except (OSError, IOError) as err:\n # Windows may complain if the folders already exist\n if err.errno != errno.EEXIST:\n raise\n continue\n with open(target_path, 'wb') as outfile, zfile.open(member) as infile:\n shutil.copyfileobj(infile, outfile)\n shutil.copyfileobj()" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27020/" ]
339,054
<p>I'm updating my code generator and have a choice between implementing a method stub as a Virtual Method in a base class or a partial method in the generated code. Is there any performance difference between the two?</p>
[ { "answer_id": 339118, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "callvirt" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ]
339,056
<p>I need to be able to allow query strings that contain characters like '&lt;' and '>'. However, putting something like id=mi&lt;ke into the the URL will output an error page saying:</p> <p><em>A potentially dangerous Request.QueryString value was detected from the client (id="mi&lt;ke").</em></p> <p>If I first url encode the url (to create id=mi%3Cke) I still get the same error. I can get around this by putting ValidateRequest="false" into the Page directive, but I'd prefer not to do that if at all possible.</p> <p>So is there anyway to allow these characters in query strings and not turn off ValidateRequest?</p> <p>EDIT: I want to allow users to be able to type the urls in by hand as well, so encoding them in some way might not work.</p>
[ { "answer_id": 339104, "author": "Andrew Rollings", "author_id": 40410, "author_profile": "https://Stackoverflow.com/users/40410", "pm_score": 4, "selected": true, "text": "System.Text.ASCIIEncoding.ASCII.GetBytes\n System.Convert.ToBase64String\n System.Convert.FromBase64String\n System.Text.ASCIIEncoding.ASCII.GetString\n" }, { "answer_id": 339115, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": " $(document).ready( function() {\n $('form').bind('submit', function() {\n $('form' > 'input[type=text]').each( function(i) {\n if (this.value) {\n this.value = encode(this.value);\n }\n });\n });\n });\n\n function encode(value) {\n return ...suitable encoding...\n }\n" }, { "answer_id": 399928, "author": "melaos", "author_id": 38124, "author_profile": "https://Stackoverflow.com/users/38124", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\"> \n\n var unencodedText = \"This is my text that contains whitespaces and characters like and Ø\"; \n var encodedText = \"\"; \n var decodedText = \"\"; \n alert('unencodedText: ' + unencodedText); \n\n //To encode whitespaces and the 'Ø' character - use encodeURI \n encodedText = encodeURI(unencodedText); \n //We see that whitespaces and 'Ø' are encoded, but the '' is still there: \n alert('encodedText: ' + encodedText); \n\n //If we decode it we should get our unencodedText back \n decodedText = decodeURI(encodedText); \n alert('decodedText: ' + decodedText); \n\n //To also encode the '' we use the encodeURIComponent \n encodedText = encodeURIComponent(unencodedText); \n //Now all the characters have been encoded: \n alert('encodedText: ' + encodedText); \n\n //To get our unencodedText back we now need to use the decodeURIComponent \n decodedText = decodeURIComponent(encodedText); \n alert('decodedText: ' + decodedText); \n\n</script>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18202/" ]
339,063
<p>When would I implement IDispose on a class as opposed to a destructor? I read <a href="http://www.dotnetspider.com/resources/1382-Understanding-IDisposable-pattern.aspx" rel="noreferrer">this article</a>, but I'm still missing the point. </p> <p>My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to waiting for the garbage collector to do it. Is this correct?</p> <p>Does that mean I should always explicitly call Dispose on an object? What are some common examples of this?</p>
[ { "answer_id": 339077, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "IDisposable IDisposable Dispose() GC.SuppressFinalize(this) Dispose()" }, { "answer_id": 339085, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 5, "selected": false, "text": "Finalize() IDisposable Dispose()" }, { "answer_id": 339280, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 3, "selected": false, "text": "Dispose(False);\n" }, { "answer_id": 1400372, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 3, "selected": false, "text": "Dispose Dispose Dispose Dispose IAsyncResult.WaitHandle IAsyncResult IDisposable IDisposable IDisposable IAsyncResult Dispose" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133/" ]
339,088
<p>I'm getting an error compiling my VSTO (Visual Studio Tools for Office) project in VS.</p> <p>It says <strong>"Value does not fall within the expected range."</strong> and <strong>"There was an error during installation"</strong></p>
[ { "answer_id": 37077112, "author": "Mehdi Khademloo", "author_id": 4038978, "author_profile": "https://Stackoverflow.com/users/4038978", "pm_score": 0, "selected": false, "text": "vsto vsto" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
339,089
<p>In the iPhone SDK I don't see the same <code>SCDynamicStore</code> used on Mac OS X to get the SSID name that your wireless network is currently connected to isn't available. </p> <p>Is there a way to get the SSID name that the iPhone is currently connected to? </p> <p>I see some apps do it (<a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=296273148&amp;mt=8" rel="noreferrer">Easy Wi-Fi for AT&amp;T</a> for one) but I can't find how it's done in the iPhone SDK docs. A private or unpublish method would be acceptable just as a proof of concept (although I know that likely wouldn't make it to the AppStore).</p>
[ { "answer_id": 27191680, "author": "MSA", "author_id": 4279108, "author_profile": "https://Stackoverflow.com/users/4279108", "pm_score": 2, "selected": false, "text": "#import <SystemConfiguration/CaptiveNetwork.h>\n\nCFArrayRef myArray = CNCopySupportedInterfaces();\nCFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));\nNSDictionary *ssidList = (__bridge NSDictionary*)myDict;\nNSString *SSID = [ssidList valueForKey:@\"SSID\"];\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29263/" ]
339,100
<p>I’m selecting data on an old database which has an abused status column. The status column has multiple pieces of information in it. Values are like ‘New Contact YYYY’, ‘Online YYYY’, ‘Updated YYYY’, ‘Withdrawn YYYY’, etc…. As you may have guessed, YYYY represents the year … which I need.</p> <p>In the past I’ve done something similar to </p> <pre><code>Rtrim( ltrim( Replace(Replace(Replace(Replace(Replace( … </code></pre> <p>Basically, replacing all text values with an empty string, so the only thing that still exists is the year. I can still do this, but I’m thinking this is ridiculous, and there’s got to be a better way.</p> <p>Does anybody know of a better way to do this?</p>
[ { "answer_id": 339125, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "SELECT SUBSTRING(FieldName, PATINDEX('%[0-9][0-9][0-9][0-9]%', FieldName), 4)\nFROM TableName\n" }, { "answer_id": 339167, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "SELECT right(FieldName,4) from table\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29043/" ]
339,105
<p>I'm really struggling with grasping how to effectively use FasterCSV to accomplish what I want.</p> <p>I have a CSV file; say:</p> <pre><code>ID,day,site test,tuesday,cnn.com bozo,friday,fark.com god,monday,xkcd.com test,saturday,whatever.com </code></pre> <p>I what to go through this file and end up with a hash that has a counter for how many times the first column occurred. So:</p> <pre><code>["test" =&gt; 2, "bozo" =&gt; 1, "god" =&gt; 1] </code></pre> <p>I need to be able to do this without prior knowledge of the values in the first column.</p> <p>?</p>
[ { "answer_id": 339147, "author": "Eli", "author_id": 5958, "author_profile": "https://Stackoverflow.com/users/5958", "pm_score": 0, "selected": false, "text": "row.to_hash row FasterCSV::Row row.headers" }, { "answer_id": 339148, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": -1, "selected": false, "text": "File.open(\"file.csv\").readlines[1..-1].inject({}) {|acc,line| word = line.split(/,/).first; acc[word] ||= 0; acc[word] += 1; acc}\n" }, { "answer_id": 339253, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 4, "selected": true, "text": "h = Hash.new(0)\nFasterCSV.read(\"file.csv\")[1..-1].each {|row| h[row[0]] += 1}\n" }, { "answer_id": 1497474, "author": "kikito", "author_id": 312586, "author_profile": "https://Stackoverflow.com/users/312586", "pm_score": 0, "selected": false, "text": "counter = {}\nFasterCSV.foreach(\"path_to_your_csv_file\", :headers => :first_row) do |row|\n key=row[0]\n counter[key] = counter[key].nil? ? 1 : counter[key] + 1\nend\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
339,106
<p>Some time ago I got this error when building ANY Visual Studio Deployment project.</p> <p><strong>"Unrecoverable build error"</strong> </p> <p><em>I thought my VS installation was corrupted or I deleted some important files, but ...</em></p>
[ { "answer_id": 339111, "author": "Robin Rodricks", "author_id": 41021, "author_profile": "https://Stackoverflow.com/users/41021", "pm_score": 6, "selected": true, "text": "regsvr32 \"C:\\Program Files\\Common Files\\Microsoft Shared\\MSI Tools\\mergemod.dll\"\nregsvr32 ole32.dll\n regsvr32 \"C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\MSI Tools\\mergemod.dll\"\nregsvr32 ole32.dll\n" }, { "answer_id": 13596536, "author": "Dominik Ras", "author_id": 311410, "author_profile": "https://Stackoverflow.com/users/311410", "pm_score": 2, "selected": false, "text": "regsvr32 \"C:\\Program Files\\Common Files\\Microsoft Shared\\MSI Tools\\mergemod.dll\"\nregsvr32 ole32.dll\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
339,130
<p>I'm trying to generate a JSON response that includes some HTML. Thus, I have <code>/app/views/foo/bar.json.erb</code>:</p> <pre><code>{ someKey: 'some value', someHTML: "&lt;%= h render(:partial =&gt; '/foo/baz') -%&gt;" } </code></pre> <p>I want it to render <code>/app/views/foo/_baz.html.erb</code>, but it will only render <code>/app/views/foo/_baz.json.erb</code>. Passing <code>:format =&gt; 'html'</code> doesn't help.</p>
[ { "answer_id": 340335, "author": "roninek", "author_id": 42642, "author_profile": "https://Stackoverflow.com/users/42642", "pm_score": 3, "selected": false, "text": "render :file render :file => \"foo/_baz.json.erb\"\n <% @template_format = \"html\" %>\n<%= h render(:partial => '/foo/baz') %>\n" }, { "answer_id": 340432, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 6, "selected": true, "text": "def with_format(format, &block)\n old_format = @template_format\n @template_format = format\n result = block.call\n @template_format = old_format\n return result\nend\n <% with_format('html') do %>\n <%= h render(:partial => '/foo/baz') %>\n<% end %>\n render :format render :file" }, { "answer_id": 340508, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 6, "selected": false, "text": "render :partial => '/foo/baz.html.erb'\n with_format &block" }, { "answer_id": 3100501, "author": "Garfield", "author_id": 363502, "author_profile": "https://Stackoverflow.com/users/363502", "pm_score": 1, "selected": false, "text": "xml.items :type => \"array\" do\n @items.each do |item|\n xml << render(:partial => 'shared/partial.xml.builder', :locals => { :item => item })\n end\nend\n" }, { "answer_id": 3427634, "author": "zgchurch", "author_id": 126056, "author_profile": "https://Stackoverflow.com/users/126056", "pm_score": 5, "selected": false, "text": " def with_format(format, &block)\n old_formats = formats\n self.formats = [format]\n block.call\n self.formats = old_formats\n nil\n end\n" }, { "answer_id": 5074120, "author": "viphe", "author_id": 437585, "author_profile": "https://Stackoverflow.com/users/437585", "pm_score": 4, "selected": false, "text": "def with_format(format, &block)\n old_formats = formats\n begin\n self.formats = [format]\n return block.call\n ensure\n self.formats = old_formats\n end\nend\n" }, { "answer_id": 6181539, "author": "Tony Stubblebine", "author_id": 776875, "author_profile": "https://Stackoverflow.com/users/776875", "pm_score": 5, "selected": false, "text": "<% self.formats = [:mobile, :html] %>\n" }, { "answer_id": 9346997, "author": "Tim Haines", "author_id": 120216, "author_profile": "https://Stackoverflow.com/users/120216", "pm_score": 7, "selected": false, "text": "respond_to render formats: [ :html ]\n render format: 'html'\n" }, { "answer_id": 10697988, "author": "Mario Uher", "author_id": 326984, "author_profile": "https://Stackoverflow.com/users/326984", "pm_score": 2, "selected": false, "text": "formats {\n someKey: 'some value',\n someHTML: \"<%= h render('baz', formats: :html) -%>\"\n}\n" }, { "answer_id": 16572820, "author": "DrewB", "author_id": 1207729, "author_profile": "https://Stackoverflow.com/users/1207729", "pm_score": 5, "selected": false, "text": "render(:partial => 'form', :formats => [:html])} \n class ActionView::PartialRenderer\n private\n def setup_with_formats(context, options, block)\n formats = Array(options[:formats])\n @lookup_context.formats = formats | @lookup_context.formats\n setup_without_formats(context, options, block)\n end\n\n alias_method_chain :setup, :formats\nend\n" }, { "answer_id": 19457135, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 3, "selected": false, "text": "render file: 'api/item', formats: [:json] file formats format" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
339,133
<p>The scenario: we have a web system that automatically generates office 2003 excel files "on the fly" (using the 2003 XML file format, not the binary format.) These files do get kept on the web server for various things.</p> <p>Now, we're in a situation where the client would really like us to take the xls files generated by this process and glue them together into a single sheet of one big file. (largely so that they can press "print" only once.)</p> <p>I assume the .net framework must have some way to do this (and things like this) but I can't seem to tease what I need out of MSDN.</p> <p>For the record: .net 2.0, using VB.net and ASP.net. Excel can be installed on the server if needed, but something that opens excel in the background on every web user hit might not scale so well. ;)</p>
[ { "answer_id": 339215, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": true, "text": "strXLToOpen = \"C:\\Docs\\ltd.xls\" \nstrXLToImport = \"C:\\Docs\\ltd2.xls\"\n\nSet cn = CreateObject(\"ADODB.Connection\")\n''EDIT I not that MSDASQL is deprecated by Microsoft, so \n''Please see below.\nWith cn\n .Provider = \"MSDASQL\"\n .ConnectionString = \"Driver={Microsoft Excel Driver (*.xls)};\" & _\n\"DBQ=\" & strXLToOpen & \"; ReadOnly=False;\"\n .Open\nEnd With\n\nstrSQL = \"INSERT INTO [Sheet2$] (H1, H2) \" _\n& \"SELECT H1, H2 FROM [Sheet2$] IN '' \" _\n& \"'Excel 8.0;database=\" & strXLToImport & \"';\" \n\ncn.Execute strSQL\n cn.Open \"Driver={Microsoft Excel Driver (*.xls)};\" & _\n \"DriverId=790;\" & _\n \"DBQ=\" & strXLToOpen & \"; ReadOnly=False;\" & _\n \"DefaultDir=c:\\somepath\" \n \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n\"Data Source=C:\\Docs\\Test.xls;\" & _\n\"Mode=ReadWrite;Extended Properties=\"\"Excel 8.0;HDR=No\"\"\"\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
339,146
<p>I don't know why this bothers me so much, but when I create websites, I always try to do all my styling with CSS. However one thing I always have to remember to do when I'm working with tables is add cellspacing="0" and cellpadding="0"</p> <p>Why is there not a CSS property to override these antiquated HTML 4 attributes?</p>
[ { "answer_id": 339154, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "table { border-collapse:collapse; }\n" }, { "answer_id": 339164, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 7, "selected": true, "text": "table { border-collapse: collapse; }\n table tr td, table tr th { padding: 0; }\n" }, { "answer_id": 347015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "padding cellpadding border-spacing cellspacing border-collapse border-spacing: 0 1px" }, { "answer_id": 476912, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "/* tables still need 'cellspacing=\"0\"' in the markup */\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\n thead, tr, th, td {\n margin: 0;\n padding: 0;\n border: 0;\n outline: 0;\n font-size: 100%;\n vertical-align: baseline;\n background: transparent;\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10420/" ]
339,150
<p>I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a number and collection of digits. What would be awesome is if there was some indexable form of a floating point number, but I have been unable to find such a solution. I am throwing this question out there to see if there is something obvious I am missing or if I should just roll my own.</p> <hr> <p>Thanks for the advice! I was hoping for a solution that wouldn't convert from float -> string -> int, but I <em>think</em> that is the best way to get away from floating point quantization issues. I ended up going with boost::format and just referencing the individual characters of the string. I can't see that being a huge performance difference compared to using combinations of modf and fmod to attempt to get a digit out of a float (It probably does just that behind the scenes, only more robustly than my implementation). </p>
[ { "answer_id": 339161, "author": "Loki", "author_id": 39057, "author_profile": "https://Stackoverflow.com/users/39057", "pm_score": 4, "selected": true, "text": "char string[99];\nsprintf(string,\"%f\",floatValue);\n" }, { "answer_id": 339877, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 3, "selected": false, "text": "#define SHOW(X) cout << # X \" = \" << (X) << endl\n\nint\nmain()\n{\n double d = 1234.567;\n\n SHOW( (int(d)%10000) / 1000 );\n SHOW( (int(d)%1000) / 100 );\n SHOW( (int(d)%100) / 10 );\n SHOW( (int(d)%10) );\n SHOW( (int(d*10) % 10) );\n SHOW( (int(d*100) % 10) );\n SHOW( (int(d*1000)% 10) );\n\n SHOW( log(d)/log(10) );\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43028/" ]
339,170
<p>I have a client who had to rebuild his automated build server. He checked out his project folder from my subversion server but is now no longer able to commit - he gets this error:</p> <pre><code>Error: Commit failed (details follow): Error: Cannot write to the prototype revision file of transaction '551-1' because a Error: previous representation is currently being written by another process Finished!: </code></pre> <p>I have searched Google but although this error has been often reported there is no clear explanation - does anyone on StackOverflow have a solution?</p> <p>UPDATE: Nobody else commits to that repository, so it was not a transaction stuck (at least not from another user). In the end we found that permissions were not set correctly. Not that you would know it from this message, but that fixed the problem.</p>
[ { "answer_id": 339246, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 3, "selected": false, "text": "svnadmin lstxns /path/to/repository\n svnadmin help\n svnadmin help lstxns\n" }, { "answer_id": 11630965, "author": "Defense Contractor", "author_id": 1548711, "author_profile": "https://Stackoverflow.com/users/1548711", "pm_score": 0, "selected": false, "text": "chmod -R 777 /path/to/repo\n" }, { "answer_id": 33587674, "author": "Nvan", "author_id": 3540027, "author_profile": "https://Stackoverflow.com/users/3540027", "pm_score": 1, "selected": false, "text": "sudo chown -R www-data:www-data /home/pi/repos/\nsudo chown -R www-data:www-data /home/pi/repos/myProject\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
339,172
<p>Is there any possibility that GetPropInfo returns nil even if the given class is declared with correct {$METHODINFO} directives.</p> <pre><code> type ... ... {$METHODINFO ON} TMyClass = class private fField: integer; published property Field: integer read fField write fField; end; {$METHODINFO OFF} ... ... procedure TestRTTI; begin assert(assigned(GetPropInfo(TMyClass, 'Field')), 'WTF! No RTTI found!'); end; </code></pre>
[ { "answer_id": 339301, "author": "utku_karatas", "author_id": 14716, "author_profile": "https://Stackoverflow.com/users/14716", "pm_score": 4, "selected": true, "text": " type \n TMyClass = class; \n ... \n ...\n {$METHODINFO ON}\n TMyClass = class\n private\n fField: integer;\n published\n property Field: integer read fField write fField;\n end;\n {$METHODINFO OFF} \n ... \n ... \n procedure TestRTTI; \n begin\n assert(assigned(GetPropInfo(TMyClass, 'Field')), 'WTF! No RTTI found!'); \n end;\n type \n {$METHODINFO ON}\n TMyClass = class; \n {$METHODINFO OFF} \n ... \n ...\n TMyClass = class\n private\n fField: integer;\n published\n property Field: integer read fField write fField;\n end;\n ... \n" }, { "answer_id": 609287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$TypeInfo $M $M+/- = $TypeInfo On/Off" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14716/" ]
339,180
<p>I run all my integers through a <code>(int)Integer</code> to make them safe to use in my query strings.</p> <p>I also run my strings through this function code:-</p> <pre><code>if(!get_magic_quotes_gpc()) { $string = mysql_real_escape_string($string); } $pattern = array("\\'", "\\\"", "\\\\", "\\0"); $replace = array("", "", "", ""); if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $string))) $string = addslashes($string); $cleanedString = str_replace('%','',$string); </code></pre> <p>I obviously return the $cleanedString variable. Now I replace the % character because it is a wildcard to mySQL and it could potentially slow down my queries (or make them return incorrect data) if the user inserted them. Are there any other special characters for mySQL I should be concerned about? </p> <p>On a second note, is there anything wrong or redundant about my search and replace after the <code>mysql_real_escape_string</code>? I got it from a website when I was first starting out and (if I remember correctly) it said you had to use this search/replace in addition to the escape string. It looks like it's trying to remove any previously escaped injection characters?</p>
[ { "answer_id": 339192, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "$string = $_POST['searchTerm'];\nif (get_magic_quotes_gpc()) {\n $string = stripslashes($string);\n}\n$string = str_replace(\"%\", \"\", $string);\n$safeString = mysql_real_escape_string($string);\n" }, { "answer_id": 339195, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "if(get_magic_quotes_gpc()) {\n $string = stripslashes($string);\n}\n\n$string = mysql_real_escape_string($string);\n\n$cleanedString = str_replace('%','',$string);\n" }, { "answer_id": 339238, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "preg_match() [xyz] mysql_real_escape_string() % _ LIKE LIKE LIKE ORDER BY $quotedString = mysql_real_escape_string($string);\n $paramString = $string;\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
339,181
<p>In ruby, is there a way to "undefine" a variable or constant once it's been defined?</p> <p>In our rails environemnts, we define one of three contants to be <code>true</code>, depending on the environment: <code>TESTING</code>, <code>DEVELOPMENT</code>, or <code>PRODUCTION</code>. Then, in controller code, we use <code>defined?</code> to see if what environment we're in, ie: <code>defined? PRODUCTION</code>.</p> <p>Now, I want to unit test some of that environment-specific behavior. My initial attempt was to just set the appropriate constant in my test, and then reset them in teardown. However, I can't figure out how to reset <code>DEVELOPMENT</code> and <code>PRODUCTION</code> such that <code>defined?</code> returns false.</p> <p>Obviously, a solution would be to just check to see if the appropriate constant is also true in addition to checking if it's defined, but this will result in having to touch a fair amount of existing code.</p> <p>EDIT: I realize this is definitely NOT the right way to do things. Alas, changing it is a nontrivial task, so I'm looking for an easy way to just unit test what's there now. Plus, I'm also just curious about the lower level language question of whether it's possible to undefine a variable/constant.</p>
[ { "answer_id": 339226, "author": "grepsedawk", "author_id": 14388, "author_profile": "https://Stackoverflow.com/users/14388", "pm_score": 2, "selected": false, "text": "environment = :TESTING\n\nif(environment == :TESTING)\n" }, { "answer_id": 339259, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "ENVIRON DEV TEST PROD ENVIRON" }, { "answer_id": 339272, "author": "Tim Knight", "author_id": 43043, "author_profile": "https://Stackoverflow.com/users/43043", "pm_score": 3, "selected": false, "text": "if (RAILS_ENV == \"production\") ...\n RAILS_ENV.include?(\"development\")\n" }, { "answer_id": 339277, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 5, "selected": true, "text": "Object.send(:remove_const, \"TESTING\")\n send" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/339181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41177/" ]
339,199
<p>First, I know there are methods off of the generic <code>List&lt;&gt;</code> class already in the framework do iterate over the <code>List&lt;&gt;</code>.</p> <p>But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a <code>List&lt;&gt;</code>, and do a <code>Console.WriteLine(object.ToString())</code> on each object. Something that takes the <code>List&lt;&gt;</code> as the first argument and the lambda expression as the second argument.</p> <p>Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.</p>
[ { "answer_id": 339206, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 7, "selected": true, "text": "public void Each<T>(IEnumerable<T> items, Action<T> action)\n{\n foreach (var item in items)\n action(item);\n}\n Each(myList, i => Console.WriteLine(i));\n" }, { "answer_id": 1069952, "author": "Peanut", "author_id": 47036, "author_profile": "https://Stackoverflow.com/users/47036", "pm_score": 5, "selected": false, "text": "new List<SomeType>(items).ForEach(\n i => Console.WriteLine(i)\n);\n" }, { "answer_id": 1310851, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public static void main(string[] args)\n{\nList names = new List();\n\nnames.Add(“Saurabh”);\nnames.Add(\"Garima\");\nnames.Add(“Vivek”);\nnames.Add(“Sandeep”);\n\nstring stringResult = names.Find( name => name.Equals(“Garima”));\n}\n" }, { "answer_id": 8274515, "author": "Mauro Torres", "author_id": 1066282, "author_profile": "https://Stackoverflow.com/users/1066282", "pm_score": 6, "selected": false, "text": "int[] numbers = { 1, 2, 3 };\nnumbers.ToList().ForEach(n => Console.WriteLine(n));\n" }, { "answer_id": 16213422, "author": "Krzysztof Radzimski", "author_id": 2269514, "author_profile": "https://Stackoverflow.com/users/2269514", "pm_score": 4, "selected": false, "text": "public static void Each<T>(this IEnumerable<T> items, Action<T> action) {\nforeach (var item in items) {\n action(item);\n} }\n myList.Each(x => { x.Enabled = false; });\n" }, { "answer_id": 19672829, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 2, "selected": false, "text": "public static class Extensions\n{\n public static void Each<T>(this IEnumerable<T> items, Action<T> action)\n {\n foreach (var item in items)\n {\n action(item);\n }\n }\n}\n\n[TestFixture]\npublic class ForEachTests\n{\n public void Each<T>(IEnumerable<T> items, Action<T> action)\n {\n foreach (var item in items)\n {\n action(item);\n }\n }\n\n private string _extensionOutput;\n\n private void SaveExtensionOutput(string value)\n {\n _extensionOutput += value;\n }\n\n private string _instanceOutput;\n\n private void SaveInstanceOutput(string value)\n {\n _instanceOutput += value;\n }\n\n [Test]\n public void Test1()\n {\n string[] teams = new string[] {\"cowboys\", \"falcons\", \"browns\", \"chargers\", \"rams\", \"seahawks\", \"lions\", \"heat\", \"blackhawks\", \"penguins\", \"pirates\"};\n\n Each(teams, SaveInstanceOutput);\n\n teams.Each(SaveExtensionOutput);\n\n Assert.AreEqual(_extensionOutput, _instanceOutput);\n }\n}\n static public static void Each<T>(this IEnumerable<T> items, Action<T> action)\n{\n foreach (var item in items)\n {\n action(item);\n }\n }\n public void Each<T>(Action<T> action)\n{\n foreach (var item in items)\n {\n action(item);\n }\n }\n" }, { "answer_id": 71287650, "author": "Lodlaiden", "author_id": 877552, "author_profile": "https://Stackoverflow.com/users/877552", "pm_score": 0, "selected": false, "text": "foreach (Item i in allItems)\n{\n i.FK_ItemStatus_CustomCodeID = itemStatuses.Where(\n x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault(); \n}\n allItems.ForEach(\n i => i.FK_ItemStatus_CustomCodeID = \n itemStatuses.Where(\n x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault()\n );\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
339,200
<p>Yes, like those pretty buttons on the iPhone. ;)</p> <p>I've been searching and reading for days now and everytime I find something that will get me close (like CreateRoundRectRgn), it blows up because Windows Mobile 6 GDI+ doesn't support it.</p> <p>I can do the whole owner draw thing and such. But how do I curve those hard corners and reshape a button? :/</p> <p>Note Tools available: Native Win32 only (no MFC)</p> <hr> <p>That thought has occured to me, but it leaves two issues:</p> <p>1) Won't the bitmap with rounded edges still leave the corners of the button visible.</p> <p>2) Bitmaps are great for fixed screen size. But having a variety of resolutions, my goal is to dynamically create the button bitmap in memory at run-time and use it that way.</p> <p>I've got it working with square buttons. Yet I have seen rounded edge buttons used by other software. There <strong><em>must</em></strong> be a way to reshape buttons.</p>
[ { "answer_id": 495489, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "//Set up a brush and pen\nHBRUSH brush = CreateSolidBrush(RGB(255, 0, 0));\nHPEN pen = CreatePen(PS_SOLID, 1, RGB(0, 255, 0));\n\n//Select it\nHGDIOBJ old_brush = SelectObject(hdc, brush);\nHGDIOBJ old_pen = SelectObject(hdc, pen);\n\n//Draw your rectangle\nRoundRect(hdc, m_rect.left, m_rect.top, m_rect.right, m_rect.bottom, 10, 10);\n\n//restore the old state of your HDC\nSelectObject(hdc, old_brush);\nSelectObject(hdc, old_pen);\n\n//Clean up\nDeleteObject(brush);\nDeleteObject(pen);\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7599/" ]
339,202
<p>I'm in the process of setting up a php project, but am not very familiar with how to properly use php's include/require commands. My layout currently looks like this:</p> <pre><code>/public --apache points into this directory /public/index.php /public/blah/page.php /utils/util1.php -- useful classes/code are stored in other directories out here /dbaccess/db1.php dbaccess/db1.php require '../utils/util1.php </code></pre> <p>public/index.php</p> <pre><code>require '../dbaccess/db1.php' </code></pre> <p>public/blah/page.php</p> <pre><code>require '../../dbaccess/db1.php' </code></pre> <p>The problem is this from the php 'include' documentation:</p> <blockquote> <p>If filename begins with ./ or ../, it is looked only in the current working directory</p> </blockquote> <p>So public/blah/page.php fails because it includes dbaccess/db1.php which blows up when it tries to include util1.php. It fails because it's relative path is from the original script in public/blah/, not from dbaccess/</p> <p>This seems pretty stupid -- db1.php has to just know where it's being included from which isn't going to work.</p> <p>I've seen strategies like this:</p> <pre><code>require_once dirname(__FILE__) . '/../utils/util1.php'); </code></pre> <p>That apparently works since now the path is an absolute path, but just seems really bizarre to me. </p> <p>Is that normal? Should I continue down that path or am I missing something obvious here?</p>
[ { "answer_id": 339219, "author": "Rob Burke", "author_id": 135, "author_profile": "https://Stackoverflow.com/users/135", "pm_score": -1, "selected": false, "text": "require('/sharedhost/yourdomain.com/apache/www/dbutils.php');\n require(WWWROOT . '/dbutils.php');\n" }, { "answer_id": 339271, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "require '../path/to/file.ext';\n require '/path/to/file.ext';\n require('/path/to/file.ext');\n" }, { "answer_id": 339389, "author": "ehassler", "author_id": 38019, "author_profile": "https://Stackoverflow.com/users/38019", "pm_score": 0, "selected": false, "text": "set_include_path( $path.PATH_SEPERATOR.get_include_path());" }, { "answer_id": 339417, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<?php include dirname(__FILE__).'/../include/include.php/'; ?> include LIBRARY_DIR.'/utils/util.php'; util.php utils misc/util" }, { "answer_id": 339445, "author": "Chris Burgess", "author_id": 43034, "author_profile": "https://Stackoverflow.com/users/43034", "pm_score": 1, "selected": false, "text": "define('MYAPP_BASEDIR',realpath('.')); spl_autoload_register()" }, { "answer_id": 341235, "author": "dcousineau", "author_id": 20265, "author_profile": "https://Stackoverflow.com/users/20265", "pm_score": 5, "selected": true, "text": "define('APP_ROOT', dirname(__FILE__));\ndefine('INCLUDE_ROOT', APP_ROOT . \"/includes\");\n dirname(__FILE__); dirname(dirname(__FILE__)); ../ PATH_SEPARATOR PATH_SEPARATOR include INCLUDE_ROOT . '/path/to/some/file.php';\n define(...) www_root/\n index.php\n bootstrap.php\n include include class GlobalNamespace_Namespace_Class\n//...\n include_dir/\n GlobalNamespace/\n Namespace/\n Class.php\n __autoload()" }, { "answer_id": 381005, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "require_once APP_ROOT.\"/path/to/your/script.php\";\n <Environments>\n <Application name=\"www.domain.com\" namespace=\"\">\n <Constants>\n <Constant name=\"APP_ROOT\" value=\"/full/path/to/project/source\" />\n </Constants>\n <Constants>\n <Constant name=\"WEB_ROOT\" value=\"/full/path/to/project/public\" />\n </Constants>\n </Application>\n </Environments>\n require_once \"./relative/path/to/script.php\";\n" }, { "answer_id": 395580, "author": "Alan Gabriel Bem", "author_id": 43542, "author_profile": "https://Stackoverflow.com/users/43542", "pm_score": 0, "selected": false, "text": "<map>\n <path classname=\"MyClass\">${project_directory}/libs/my_classes/MyClass.php</path>\n <path classname=\"OtherClass\">${project_directory}/libs/some_new/Other.php</path>\n <!-- its so flexible that even external libraries fit in -->\n <path classname=\"Propel\">${project_directory}/vendors/propel/Propel.php</path>\n <!-- etc -->\n</map>\n" }, { "answer_id": 2823486, "author": "Kastor", "author_id": 339822, "author_profile": "https://Stackoverflow.com/users/339822", "pm_score": 0, "selected": false, "text": "$_server['DOCUMENT_ROOT'] public_html $_server['WEB_ROOT'] <?php\n\n//You only need to paste the following line into your script once,\n//and it must come before you reference the public document root of your website.\n//Use $pubroot.'/path_from_public_document_root_to_file/filename.php\n\n$pubroot = (str_replace(($_SERVER['PHP_SELF']), '', (str_replace('\\\\', '/', (realpath(basename(getenv(\"SCRIPT_NAME\"))))))));\n\n\n//uncomment the next line to show the calculated public document root\n//relative to the document root.\n\n//echo (\"$pubroot\");\n?>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/945/" ]
339,210
<p>[Meta-note:] I was browsing the question page, getting really tired of "DIVS vs Tables" "When to use tables vs DIVS" "Are Divs better than Tables" "Tables versus CSS" and all the questions that ask <em>THE SAME THING OMG PEOPLE</em> but I would like to see all the ways people tackle the translation of the canonical example of "why you should give up and use tables":</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; Name &lt;/td&gt; &lt;td&gt; &lt;input&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Social Security Number &lt;/td&gt; &lt;td&gt; &lt;input&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><b> Question: </b> How to best (semantically, simply, robustly, fluidly, portably) implement the above without tables. For starters, I guess a naive implementation uses a fixed column width for the first column, but that can have iffy results for dynamically generated content. Including strengths/weaknesses of your approach in the answer would be nice.</p> <p>P.S. Another one I wonder about a lot is vertical centering but the hack for that is covered pretty well at <a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html" rel="nofollow noreferrer">jakpsatweb.cz</a></p> <p>EDIT: scunlife brings up a good example of why I didn't think out the problem that carefully. Tables can align multiple columns simultaneously. The Question still stands (I'd like to see different CSS techniques used for alignment/layout) - although solutions that can handle his? more involved example definitely are preferred.</p>
[ { "answer_id": 339229, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 5, "selected": true, "text": "<form>\n <label for=\"param_1\">Param 1</label>\n <input id=\"param_1\" name=\"param_1\"><br />\n <label for=\"param_2\">Param 2</label>\n <input id=\"param_2\" name=\"param_2\"><br />\n</form>\n label,input { display: block; float: left; margin-bottom: 1ex; }\ninput { width: 20em; }\nlabel { text-align: right; width: 15em; padding-right: 2em; }\nbr { clear: left; }\n display: block float: left br clear: left br" }, { "answer_id": 339255, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "<div style=\"text-align:right; float:left;\">\n Name: <input /> <br />\n Social Security Number: <input /> <br />\n</div>\n" }, { "answer_id": 339257, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 3, "selected": false, "text": "Color: [____Red___][v]\n Hood: [*] \n Size: (_) Small\n (_) Medium\n (_) Large\n (*) X-Large\n" }, { "answer_id": 397973, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 2, "selected": false, "text": "<br /> <form>\n <fieldset>\n <legend>Personal Info</fieldset>\n <div>\n <label for=\"name\">Name</label>\n <input id=\"name\" name=\"name\" />\n </div>\n <div>\n <label for=\"ssn\">Social Security Number</label>\n <input id=\"ssn\" name=\"ssn\" />\n </div>\n </fieldset>\n</form>\n <divs> overflow: hidden Name |==============| SSN |==============|\n\nName |==============|\nSSN |==============|\n\nName |==============|\nSSN |==============|\n\n Name |==============|\n SSN |==============|\n\n Name: |==============|\n SSN: |==============|\n\nName:\n|==============|\nSSN:\n|==============|\n" }, { "answer_id": 398135, "author": "Alohci", "author_id": 42585, "author_profile": "https://Stackoverflow.com/users/42585", "pm_score": 2, "selected": false, "text": "<form action=\"www.example.com\">\n <div class=\"table\">\n <div class=\"tbody\">\n <div class=\"tr\">\n <div class=\"td\"> <label for=\"name\">Name</label> </div>\n <div class=\"td\"> <input id=\"name\"> </div>\n </div>\n <div class=\"tr\">\n <div class=\"td\"> <label for=\"ssn\">Social Security Number</label> </div>\n <div class=\"td\"> <input id=\"ssn\"> </div>\n </div>\n </div>\n </div>\n</form>\n <style type=\"text/css\">\n div.table { display:table; border-spacing:2px; }\n div.tbody { display:table-row-group; }\n div.tr { display:table-row; }\n div.td { display:table-cell; vertical-align: middle; padding:1px; }\n </style>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4435/" ]
339,217
<p>I am writing a game in python and have decided to create a DSL for the map data files. I know I could write my own parser with regex, but I am wondering if there are existing python tools which can do this more easily, like re2c which is used in the PHP engine.</p> <p>Some extra info:</p> <ul> <li>Yes, I <em>do</em> need a DSL, and even if I didn't I still want the experience of building and using one in a project.</li> <li><p>The DSL contains only data (declarative?), it doesn't get "executed". Most lines look like:</p> <p><code>SOMETHING: !abc @123 #xyz/123</code></p> <p>I just need to read the tree of data.</p></li> </ul>
[ { "answer_id": 339300, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 2, "selected": false, "text": "ParserElement" }, { "answer_id": 339329, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "abc= ONETHING( ... )\nxyz= ANOTHERTHING( ... )\npqr= SOMETHING( this=abc, that=123, more=(xyz,123) )\n" }, { "answer_id": 343028, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 2, "selected": false, "text": "with" }, { "answer_id": 1660889, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": ">>> line = 'SOMETHING: !abc @123 #xyz/123'\n\n>>> line.split()\n['SOMETHING:', '!abc', '@123', '#xyz/123']\n\n>>> import shlex\n>>> list(shlex.shlex(line))\n['SOMETHING', ':', '!', 'abc', '@', '123']\n >>> import re\n>>> result = re.match(r'([A-Z]*): !([a-z]*) @([0-9]*) #([a-z0-9/]*)', line)\n>>> result.groups()\n('SOMETHING', 'abc', '123', 'xyz/123')\n" }, { "answer_id": 69780059, "author": "abdullahmjawaz", "author_id": 13277854, "author_profile": "https://Stackoverflow.com/users/13277854", "pm_score": 1, "selected": false, "text": "<=> a <=> b\n a , b = b , a\n from tokenize import untokenize, tokenize, NUMBER, STRING, NAME, OP, COMMA\nimport io\nimport ast\n\ns = b\"a <=> b\\n\" # i may read it from file\nb = io.BytesIO(s)\ng = tokenize(b.readline)\nresult = []\nfor token_num, token_val, _, _, _ in g:\n # naive simple approach to compile a<=>b to a,b = b,a\n if token_num == OP and token_val == '<=' and next(g).string == '>':\n first = result.pop()\n next_token = next(g)\n second = (NAME, next_token.string)\n result.extend([\n first,\n (COMMA, ','),\n second,\n (OP, '='),\n second,\n (COMMA, ','),\n first,\n ])\n else:\n result.append((token_num, token_val))\n\nsrc = untokenize(result).decode('utf-8')\nexp = ast.parse(src)\ncode = compile(exp, filename='', mode='exec')\n\n\ndef my_swap(a, b):\n global code\n env = {\n \"a\": a,\n \"b\": b\n }\n exec(code, env)\n return env['a'], env['b']\n\nprint(my_swap(1,10))\n\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
339,225
<p>Does anyone know of a short cut to place my name and the date where the cursor is i.e.</p> <pre><code> //021208 DarkAxi0m </code></pre> <p>so i don't keep check what the date is when i'm adding comments. </p> <p>Im using Delphi7, with CnPack And GExperts Installed. I think it should be able to be done with one of those experts. </p>
[ { "answer_id": 339236, "author": "Christopher Chase", "author_id": 11016, "author_profile": "https://Stackoverflow.com/users/11016", "pm_score": 1, "selected": false, "text": " //%Date% DarkAxi0m\n" }, { "answer_id": 343817, "author": "Marek Jedliński", "author_id": 9226, "author_profile": "https://Stackoverflow.com/users/9226", "pm_score": 2, "selected": false, "text": ";//\n ::;//:: ; this means: when I type \";//\", do what follows\nFormatTime, curDate,, yyyy-MM-dd ; the double comma is intended\nSendInput // %curDate% %A_UserName% ; variable expansion\nreturn\n // 2008-12-05 moodforaday\n" }, { "answer_id": 1182745, "author": "TheSteven", "author_id": 140858, "author_profile": "https://Stackoverflow.com/users/140858", "pm_score": 1, "selected": false, "text": " //07.25.2009 (SLB20090725) - Added 3rd optional parameter.\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11016/" ]
339,228
<p>Excel macros do not seem to allow the use of "undo" after running them. Is there any way to bake <code>undo</code> functionality into a VBA macro in Excel?</p>
[ { "answer_id": 339239, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "C22 value 3\nC22 format general\n Step Cell Type Value\n---- ---- ----- -------\n 1 C22 value 3\n C22 format general\n 2...\n" }, { "answer_id": 339263, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 6, "selected": true, "text": "Application.OnUndo Public Sub DoSomething\n\n ... do stuff here\n\n Application.OnUndo \"Undo something\", \"UnDoSomething\"\nEnd Sub\n\nPublic Sub UnDoSomething\n\n ... reverse the action here\n\nEnd Sub" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,230
<p>I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.</p> <p>What I'm trying to accomplish is to check only the ones that have the class name as "required"</p> <pre><code>&lt;input name="a1" class="required" type="text" /&gt; &lt;input name="a2" class="" type="text" /&gt; &lt;input name="a3" class="required" type="text" /&gt; </code></pre> <p>Thanks</p>
[ { "answer_id": 339251, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " $(document).ready( function() {\n $('form').validate();\n });\n" }, { "answer_id": 339373, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 3, "selected": false, "text": "function validate() {\n var inputs = document.getElementsByTagName(\"input\");\n\n for (inputName in inputs) {\n if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {\n inputs[inputName].focus();\n return false;\n }\n }\n\n return true; \n}\n function validate() {\n for (var i = 0; i < theForm.elements.length; i++) {\n if (theForm.elements[i].className == \"required\" && theForm.elements[i].value.length == 0) {\n theForm.elements[i].focus();\n return false;\n }\n }\n\n return true;\n}\n getAttribute() <input name=\"a1\" validate=\"true\" regex=\"[0-9]{3}\" type=\"text\" />\n function validate() {\n for (var i = 0; i < theForm.elements.length; i++) {\n var elem = theForm.elements[i];\n\n if (elem.getAttribute(\"validate\") == \"true\") {\n if (!elem.value.match(elem.getAttribute(\"regex\"))) {\n elem.select();\n return false;\n }\n }\n }\n\n return true;\n}\n" }, { "answer_id": 339413, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 0, "selected": false, "text": "DIV P <div class=\"form-text required\">\n <label for=\"fieldId\">Your name</label>\n <input type=\"text\" name=\"fieldName\" id=\"fieldId\" value=\"\" />\n</div>\n .required input, .required select \n $('form').submit(function(){\n var fields = $(this).find('input, textarea, select'); // get all controls\n fields.removeClass('invalid'); // remove\n var inv = $(this).find('input[value=\"\"], select[value=\"\"]'); // select controls that have no value\n if (inv.length > 0) {\n inv.addClass('invalid'); // tag wrapper \n return false; // stop form from submitting\n }\n // else we may submit\n});\n var badfields = [];\nvar fields = theForm.getElementsByTagName('input');\nfor (var i=0; i< fields.length; i++ ) {\n if ( fields[i] && fields[i].parentNode && fields.value == '' &&\n /(^| )required( |$)/.test( fields[i].parentNode.className ) ) {\n badfields.push( fields[i] );\n }\n}\n// badfields.length > 0 == form is invalid\n .required input, .required select {\n border : 1px solid red;\n}\n.required label {\n color : #800;\n}\n.invalid input, .invalid select {\n background-color : #f88;\n}\n" }, { "answer_id": 357094, "author": "MK_Dev", "author_id": 39843, "author_profile": "https://Stackoverflow.com/users/39843", "pm_score": 0, "selected": false, "text": "var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');\nfor (var i = 0; i < aElements.length; i++)\n{\n // Validate\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,231
<p>If I have something like a loop or a set of if/else statements, and I want to return a value from within the nest (see below), is the best way of doing this to assign the value to a field or property and return that?</p> <p>See below:</p> <pre><code>bool b; public bool ifelse(int i) { if(i == 5) { b = true; } else { b = false; } return b; } </code></pre>
[ { "answer_id": 339241, "author": "gcores", "author_id": 40256, "author_profile": "https://Stackoverflow.com/users/40256", "pm_score": 3, "selected": false, "text": "return i == 5;\n" }, { "answer_id": 339242, "author": "DaEagle", "author_id": 43024, "author_profile": "https://Stackoverflow.com/users/43024", "pm_score": 3, "selected": false, "text": "public bool ifelse(int i)\n{\nif(i == 5)\n{\nreturn true\n}\nreturn false\n}\n" }, { "answer_id": 339254, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": false, "text": "public bool ifelse(int i)\n{\n bool b;\n /*\n Some code to calculate b\n */\n return b;\n}\n" }, { "answer_id": 339264, "author": "Doctor Jones", "author_id": 39277, "author_profile": "https://Stackoverflow.com/users/39277", "pm_score": 1, "selected": true, "text": "\npublic bool ifelse(int i) \n{ \n if(i == 5) \n { \n return true; \n }\n else \n { \n return false; \n }\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
339,245
<p>Sorry for the bad title, but I couldn't think of a better one.</p> <p>I'm having a class A and a class B which is kind of a sub class of A, like so:</p> <p>(Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?)</p> <pre><code>class A { int i = 0; class B { int j = 1; } } class Test { public static void main() { A a = new A(); B b = a.new B(); A c = ??? b ??? // get "a" back } } </code></pre> <p>From B every property of A can be accessed, therefore both, a.i and b.i, return 0. Now, I'm wondering whether it's somehow possible to retrieve the original object of type A out of b, as b contains everything that a contains? Simple casting apparently doesn't do the trick.</p> <p>Second one:</p> <pre><code>class A { void print() { System.out.println("This is class A."); } class B { void print() { // &lt;--- How to access print() of class A (like this.A.print() or smth)? System.out.println("This is class B."); } } } </code></pre> <p>You could alternatively also provide me with some good resources on this topic, as I've been too stupid to find a good one so far.</p> <p>Thanks in advance. :)</p>
[ { "answer_id": 339267, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 2, "selected": false, "text": "class A\n{\n public class B\n {\n public A Parent;\n public B(A parent)\n {\n this.Parent = parent;\n }\n }\n}\n public static void Main(String[] args)\n{\n A parent = new A();\n A.B child = new A.B(child);\n A backToParent = child.Parent;\n}\n class A\n{ \n public class B\n {\n public A Parent;\n public B(A parent)\n {\n this.Parent = parent;\n }\n }\n\n public B getChild()\n {\n return new B(this);\n }\n}\n\npublic static void Main(String[] args)\n{\n A parent = new A();\n A.B child = A.getChild();\n A backToParent = child.Parent;\n}\n" }, { "answer_id": 339285, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": true, "text": "class A {\n int i = 0;\n class B {\n final A outer = A.this;\n int j = 1;\n }\n}\n\nclass Test {\n public static void main() {\n A a = new A();\n A.B b = a.new B();\n A c = b.outer // get \"a\" back\n }\n}\n ClassName.this" }, { "answer_id": 339289, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 3, "selected": false, "text": "ParentClass.this public class Outter\n{\n class Inner {\n public Outter getOutter()\n {\n return Outter.this;\n }\n }\n\n public Inner getInner(){\n return new Inner();\n }\n}\n\nclass Runner{\n public static void main(String[] args){\n Outter out = new Outter(); \n Outter.Inner inner = out.getInner();\n\n System.out.println(inner.getOutter().toString());\n }\n}\n" }, { "answer_id": 816361, "author": "newacct", "author_id": 86989, "author_profile": "https://Stackoverflow.com/users/86989", "pm_score": 1, "selected": false, "text": "class A {\n int i = 0;\n class B {\n int j = 1;\n }\n}\n\nclass Test {\n public static void main() {\n A a = new A();\n A.B b = a.new B();\n A c = (A)b.getClass().getDeclaredField(\"this$0\").get(b);\n }\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36253/" ]
339,262
<p>Given a NxN matrix with 0s and 1s. Set every row that contains a <code>0</code> to all <code>0</code>s and set every column that contains a <code>0</code> to all <code>0</code>s.</p> <p>For example</p> <pre><code>1 0 1 1 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 </code></pre> <p>results in</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 </code></pre> <p>A Microsoft Engineer told me that there is a solution that involves no extra memory, just two boolean variables and one pass, so I'm looking for that answer.</p> <p>BTW, imagine it is a bit matrix, therefore just 1s and 0s are allow to be in the matrix.</p>
[ { "answer_id": 339294, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "bool matrix[5][5] = \n{ \n {1, 0, 1, 1, 0},\n {0, 1, 1, 1, 0},\n {1, 1, 1, 1, 1},\n {1, 0, 1, 1, 1},\n {1, 1, 1, 1, 1}\n};\n\nint CompleteRows = ~0;\nint CompleteCols = ~0;\n\n// Find the first 0\nfor (int row = 0; row < 5; ++row)\n{\n for (int col = 0; col < 5; ++col)\n {\n CompleteRows &= ~(!matrix[row][col] << row);\n CompleteCols &= ~(!matrix[row][col] << col);\n }\n}\n\nfor (int row = 0; row < 5; ++row)\n for (int col = 0; col < 5; ++col)\n matrix[row][col] = (CompleteRows & (1 << row)) && (CompleteCols & (1 << col));\n" }, { "answer_id": 339420, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 8, "selected": true, "text": "import pprint\n\nm = [[1, 0, 1, 1, 0],\n [0, 1, 1, 1, 0],\n [1, 1, 1, 1, 1],\n [1, 0, 1, 1, 1],\n [1, 1, 1, 1, 1]]\n\n\n\nN = len(m)\n\n### pass 1\n\n# 1 rst line/column\nc = 1\nfor i in range(N):\n c &= m[i][0]\n\nl = 1\nfor i in range(1,N):\n l &= m[0][i]\n\n\n# other line/cols\n# use line1, col1 to keep only those with 1\nfor i in range(1,N):\n for j in range(1,N):\n if m[i][j] == 0:\n m[0][j] = 0\n m[i][0] = 0\n else:\n m[i][j] = 0\n\n### pass 2\n\n# if line1 and col1 are ones: it is 1\nfor i in range(1,N):\n for j in range(1,N):\n if m[i][0] & m[0][j]:\n m[i][j] = 1\n\n# 1rst row and col: reset if 0\nif l == 0:\n for i in range(N):\n m [i][0] = 0\n\nif c == 0:\n for j in range(1,N):\n m [0][j] = 0\n\n\npprint.pprint(m)\n" }, { "answer_id": 339454, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 0, "selected": false, "text": "-----\n|----\n||---\n|||--\n||||-\n" }, { "answer_id": 349056, "author": "eaanon01", "author_id": 36986, "author_profile": "https://Stackoverflow.com/users/36986", "pm_score": 1, "selected": false, "text": "typedef unsigned short WORD;\ntypedef unsigned char BOOL;\n#define true 1\n#define false 0\nBYTE buffer[5][5] = {\n1, 0, 1, 1, 0,\n0, 1, 1, 1, 0,\n1, 1, 1, 1, 1,\n1, 0, 1, 1, 1,\n1, 1, 1, 1, 1\n};\nint scan_to_end(BOOL *h,BOOL *w,WORD N,WORD pos_N)\n{\n WORD i;\n for(i=0;i<N;i++)\n {\n if(!buffer[i][pos_N])\n *h=false;\n if(!buffer[pos_N][i])\n *w=false;\n }\n return 0;\n}\nint set_line(BOOL h,BOOL w,WORD N,WORD pos_N)\n{\n WORD i;\n if(!h)\n for(i=0;i<N;i++)\n buffer[i][pos_N] = false;\n if(!w)\n for(i=0;i<N;i++)\n buffer[pos_N][i] = false;\n return 0;\n}\nint scan(int N,int pos_N)\n{\n BOOL h = true;\n BOOL w = true;\n if(pos_N == N)\n return 0;\n // Do single scan\n scan_to_end(&h,&w,N,pos_N);\n // Scan all recursive before changeing data\n scan(N,pos_N+1);\n // Set the result of the scan\n set_line(h,w,N,pos_N);\n return 0;\n}\nint main(void)\n{\n printf(\"Old matrix\\n\");\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[0][0],(WORD)buffer[0][1],(WORD)buffer[0][2],(WORD)buffer[0][3],(WORD)buffer[0][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[1][0],(WORD)buffer[1][1],(WORD)buffer[1][2],(WORD)buffer[1][3],(WORD)buffer[1][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[2][0],(WORD)buffer[2][1],(WORD)buffer[2][2],(WORD)buffer[2][3],(WORD)buffer[2][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[3][0],(WORD)buffer[3][1],(WORD)buffer[3][2],(WORD)buffer[3][3],(WORD)buffer[3][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[4][0],(WORD)buffer[4][1],(WORD)buffer[4][2],(WORD)buffer[4][3],(WORD)buffer[4][4]);\n scan(5,0);\n printf(\"New matrix\\n\");\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[0][0],(WORD)buffer[0][1],(WORD)buffer[0][2],(WORD)buffer[0][3],(WORD)buffer[0][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[1][0],(WORD)buffer[1][1],(WORD)buffer[1][2],(WORD)buffer[1][3],(WORD)buffer[1][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[2][0],(WORD)buffer[2][1],(WORD)buffer[2][2],(WORD)buffer[2][3],(WORD)buffer[2][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[3][0],(WORD)buffer[3][1],(WORD)buffer[3][2],(WORD)buffer[3][3],(WORD)buffer[3][4]);\n printf( \"%d,%d,%d,%d,%d \\n\", (WORD)buffer[4][0],(WORD)buffer[4][1],(WORD)buffer[4][2],(WORD)buffer[4][3],(WORD)buffer[4][4]);\n system( \"pause\" );\n return 0;\n}\n s,s,s,s,s\ns,0,0,0,0\ns,0,0,0,0\ns,0,0,0,0\ns,0,0,0,0\n 0,s,0,0,0\ns,s,s,s,s\n0,s,0,0,0\n0,s,0,0,0\n0,s,0,0,0\n 0,0,0,0,c\n0,0,0,0,c\n0,0,0,0,c\n0,0,0,0,c\nc,c,c,c,c\n 0,0,0,c,0\n0,0,0,c,0\n0,0,0,c,0\nc,c,c,c,c\n0,0,0,c,0\n" }, { "answer_id": 349788, "author": "csl", "author_id": 21028, "author_profile": "https://Stackoverflow.com/users/21028", "pm_score": 1, "selected": false, "text": "1 0 1 1 0 | 0\n0 1 1 1 0 | 0\n1 1 1 1 1 | 1\n1 0 1 1 1 | 0\n1 1 1 1 1 | 1\n----------+\n0 0 1 1 0 \n" }, { "answer_id": 349883, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 1, "selected": false, "text": "foreach (my $row) rows {\n $andproduct = $andproduct & $row;\n if($row != -1) {\n zero out the row\n } else {\n replace row with a reference to andproduct\n }\n}\n int main() {\n int values[] = { -10, 14, -1, -9, -1 }; /* From the problem spec, converted to decimal for my sanity */\n int *arr[5] = { values, values+1, values+2, values+3, values+4 };\n int **p;\n int numproduct = 127;\n\n for(p = arr; p < arr+5; ++p) {\n numproduct = numproduct & **p;\n if(**p != -1) {\n **p = 0;\n } else {\n *p = &numproduct;\n }\n }\n\n /* Print our array, this loop is just for show */\n int i;\n for(i = 0; i < 5; ++i) {\n printf(\"%x\\n\",*arr[i]);\n }\n return 0;\n}\n <?php\n\n$values = array(-10, 14, -1, -9, -1);\n$numproduct = 127;\n\nfor($i = 0; $i < 5; ++$i) {\n $numproduct = $numproduct & $values[$i];\n if($values[$i] != -1) {\n $values[$i] = 0;\n } else {\n $values[$i] = &$numproduct;\n }\n}\n\nprint_r($values);\n" }, { "answer_id": 350373, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": 3, "selected": false, "text": "#include <iostream>\n\n/**\n* The idea with my algorithm is to delay the writing of zeros\n* till all rows and cols can be processed. I do this using\n* recursion:\n* 1) Enter Recursive Function:\n* 2) Check the row and col of this \"corner\" for zeros and store the results in bools\n* 3) Send recursive function to the next corner\n* 4) When the recursive function returns, use the data we stored in step 2\n* to zero the the row and col conditionally\n*\n* The corners I talk about are just how I ensure I hit all the row's a cols,\n* I progress through the matrix from (0,0) to (1,1) to (2,2) and on to (n,n).\n*\n* For simplicities sake, I use ints instead of individual bits. But I never store\n* anything but 0 or 1 so it's still fair ;)\n*/\n\n// ================================\n// Using globals just to keep function\n// call syntax as straight forward as possible\nint n = 5;\nint m[5][5] = {\n { 1, 0, 1, 1, 0 },\n { 0, 1, 1, 1, 0 },\n { 1, 1, 1, 1, 1 },\n { 1, 0, 1, 1, 1 },\n { 1, 1, 1, 1, 1 }\n };\n// ================================\n\n// Just declaring the function prototypes\nvoid processMatrix();\nvoid processCorner( int cornerIndex );\nbool checkRow( int rowIndex );\nbool checkCol( int colIndex );\nvoid zeroRow( int rowIndex );\nvoid zeroCol( int colIndex );\nvoid printMatrix();\n\n// This function primes the pump\nvoid processMatrix() {\n processCorner( 0 );\n}\n\n// Step 1) This is the heart of my recursive algorithm\nvoid processCorner( int cornerIndex ) {\n // Step 2) Do the logic processing here and store the results\n bool rowZero = checkRow( cornerIndex );\n bool colZero = checkCol( cornerIndex );\n\n // Step 3) Now progress through the matrix\n int nextCorner = cornerIndex + 1;\n if( nextCorner < n )\n processCorner( nextCorner );\n\n // Step 4) Finially apply the changes determined earlier\n if( colZero )\n zeroCol( cornerIndex );\n if( rowZero )\n zeroRow( cornerIndex );\n}\n\n// This function returns whether or not the row contains a zero\nbool checkRow( int rowIndex ) {\n bool zero = false;\n for( int i=0; i<n && !zero; ++i ) {\n if( m[ rowIndex ][ i ] == 0 )\n zero = true;\n }\n return zero;\n}\n\n// This is just a helper function for zeroing a row\nvoid zeroRow( int rowIndex ) {\n for( int i=0; i<n; ++i ) {\n m[ rowIndex ][ i ] = 0;\n }\n}\n\n// This function returns whether or not the col contains a zero\nbool checkCol( int colIndex ) {\n bool zero = false;\n for( int i=0; i<n && !zero; ++i ) {\n if( m[ i ][ colIndex ] == 0 )\n zero = true;\n }\n\n return zero;\n}\n\n// This is just a helper function for zeroing a col\nvoid zeroCol( int colIndex ) {\n for( int i=0; i<n; ++i ) {\n m[ i ][ colIndex ] = 0;\n }\n}\n\n// Just a helper function for printing our matrix to std::out\nvoid printMatrix() {\n std::cout << std::endl;\n for( int y=0; y<n; ++y ) {\n for( int x=0; x<n; ++x ) {\n std::cout << m[y][x] << \" \";\n }\n std::cout << std::endl;\n }\n std::cout << std::endl;\n}\n\n// Execute!\nint main() {\n printMatrix();\n processMatrix();\n printMatrix();\n}\n" }, { "answer_id": 353714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <memory.h>\n\n#define SIZE 5\n\ntypedef unsigned char u8;\n\nu8 g_Array[ SIZE ][ SIZE ];\n\nvoid Dump()\n{\n for ( int nRow = 0; nRow < SIZE; ++nRow )\n {\n for ( int nColumn = 0; nColumn < SIZE; ++nColumn )\n {\n printf( \"%d \", g_Array[ nRow ][ nColumn ] );\n }\n printf( \"\\n\" );\n }\n}\n\nvoid Process()\n{\n u8 fCarriedAlpha = true;\n u8 fCarriedBeta = true;\n for ( int nStep = 0; nStep < SIZE; ++nStep )\n {\n u8 fAlpha = (nStep > 0) ? g_Array[ nStep-1 ][ nStep ] : true;\n u8 fBeta = (nStep > 0) ? g_Array[ nStep ][ nStep - 1 ] : true;\n fAlpha &= g_Array[ nStep ][ nStep ];\n fBeta &= g_Array[ nStep ][ nStep ];\n g_Array[ nStep-1 ][ nStep ] = fCarriedBeta;\n g_Array[ nStep ][ nStep-1 ] = fCarriedAlpha;\n for ( int nScan = nStep + 1; nScan < SIZE; ++nScan )\n {\n fBeta &= g_Array[ nStep ][ nScan ];\n if ( nStep > 0 )\n {\n g_Array[ nStep ][ nScan ] &= g_Array[ nStep-1 ][ nScan ];\n g_Array[ nStep-1][ nScan ] = fCarriedBeta;\n }\n\n fAlpha &= g_Array[ nScan ][ nStep ];\n if ( nStep > 0 )\n {\n g_Array[ nScan ][ nStep ] &= g_Array[ nScan ][ nStep-1 ];\n g_Array[ nScan ][ nStep-1] = fCarriedAlpha;\n }\n }\n\n g_Array[ nStep ][ nStep ] = fAlpha & fBeta;\n\n for ( int nScan = nStep - 1; nScan >= 0; --nScan )\n {\n g_Array[ nScan ][ nStep ] &= fAlpha;\n g_Array[ nStep ][ nScan ] &= fBeta;\n }\n fCarriedAlpha = fAlpha;\n fCarriedBeta = fBeta;\n }\n}\n\nint main()\n{\n memset( g_Array, 1, sizeof(g_Array) );\n g_Array[0][1] = 0;\n g_Array[0][4] = 0;\n g_Array[1][0] = 0;\n g_Array[1][4] = 0;\n g_Array[3][1] = 0;\n\n printf( \"Input:\\n\" );\n Dump();\n Process();\n printf( \"\\nOutput:\\n\" );\n Dump();\n\n return 0;\n}\n" }, { "answer_id": 353936, "author": "comingstorm", "author_id": 210211, "author_profile": "https://Stackoverflow.com/users/210211", "pm_score": 0, "selected": false, "text": "void fixmatrix2(int M[][], int rows, int cols) {\n bool clearZeroRow= false;\n bool clearZeroCol= false;\n for(int j=0; j < cols; ++j) {\n if( ! M[0][j] ) {\n clearZeroRow= true;\n }\n }\n for(int i=1; i < rows; ++i) { // scan/accumulate pass\n if( ! M[i][0] ) {\n clearZeroCol= true;\n }\n for(int j=1; j < cols; ++j) {\n if( ! M[i][j] ) {\n M[0][j]= 0;\n M[i][0]= 0;\n }\n }\n }\n for(int i=1; i < rows; ++i) { // update pass\n if( M[i][0] ) {\n for(int j=0; j < cols; ++j) {\n if( ! M[j][0] ) {\n M[i][j]= 0;\n }\n }\n } else {\n for(int j=0; j < cols; ++j) {\n M[i][j]= 0;\n }\n }\n if(clearZeroCol) {\n M[i][0]= 0;\n }\n }\n if(clearZeroRow) {\n for(int j=0; j < cols; ++j) {\n M[0][j]= 0;\n }\n }\n}\n" }, { "answer_id": 355987, "author": "AnthonyLambert", "author_id": 31762, "author_profile": "https://Stackoverflow.com/users/31762", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#define BIT30 (1<<24)\n#define COLMASK 0x108421L\n#define ROWMASK 0x1fL\n unsigned long long STARTGRID = \n((0x10 | 0x0 | 0x4 | 0x2 | 0x0) << 20) |\n((0x00 | 0x8 | 0x4 | 0x2 | 0x0) << 15) |\n((0x10 | 0x8 | 0x4 | 0x2 | 0x1) << 10) |\n((0x10 | 0x0 | 0x4 | 0x2 | 0x1) << 5) |\n((0x10 | 0x8 | 0x4 | 0x2 | 0x1) << 0);\n\n\nvoid dumpGrid (char* comment, unsigned long long theGrid) {\n char buffer[1000];\n buffer[0]='\\0';\n printf (\"\\n\\n%s\\n\",comment);\n for (int j=1;j<31; j++) {\n if (j%5!=1)\n printf( \"%s%s\", ((theGrid & BIT30)==BIT30)? \"1\" : \"0\",(((j%5)==0)?\"\\n\" : \",\") ); \n theGrid = theGrid << 1;\n }\n}\n\nint main (int argc, const char * argv[]) {\n unsigned long long rowgrid = STARTGRID;\n unsigned long long colGrid = rowgrid;\n\n unsigned long long rowmask = ROWMASK;\n unsigned long long colmask = COLMASK;\n\n dumpGrid(\"Initial Grid\", rowgrid);\n for (int i=0; i<5; i++) {\n if ((rowgrid & rowmask)== rowmask) rowgrid |= rowmask;\n else rowgrid &= ~rowmask;\n if ((colGrid & colmask) == colmask) colmask |= colmask;\n else colGrid &= ~colmask;\n rowmask <<= 5;\n colmask <<= 1;\n }\n colGrid &= rowgrid;\n dumpGrid(\"RESULT Grid\", colGrid);\n return 0;\n }\n" }, { "answer_id": 357935, "author": "Nick", "author_id": 44741, "author_profile": "https://Stackoverflow.com/users/44741", "pm_score": 0, "selected": false, "text": "bool[][] matrix =\n{\n new[] { true, false, true, true, false }, // 10110\n new[] { false, true, true, true, false }, // 01110\n new[] { true, true, true, true, true }, // 11111\n new[] { true, false, true, true, true }, // 10111\n new[] { true, true, true, true, true } // 11111\n};\n\nint n = matrix.Length;\nbool[] enabledRows = new bool[n];\nbool[] enabledColumns = new bool[n];\n\nfor (int i = 0; i < n; i++)\n{\n enabledRows[i] = true;\n enabledColumns[i] = true;\n}\n\nfor (int rowIndex = 0; rowIndex < n; rowIndex++)\n{\n for (int columnIndex = 0; columnIndex < n; columnIndex++)\n {\n bool element = matrix[rowIndex][columnIndex];\n enabledRows[rowIndex] &= element;\n enabledColumns[columnIndex] &= element;\n }\n}\n\nfor (int rowIndex = 0; rowIndex < n; rowIndex++)\n{\n for (int columnIndex = 0; columnIndex < n; columnIndex++)\n {\n bool element = enabledRows[rowIndex] & enabledColumns[columnIndex];\n Console.Write(Convert.ToInt32(element));\n }\n Console.WriteLine();\n}\n\n/*\n 00000\n 00000\n 00110\n 00000\n 00110\n*/\n" }, { "answer_id": 358212, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private static void doIt(byte[,] matrix)\n{\n byte zeroCols = 0;\n bool zeroRow = false;\n\n for (int row = 0; row <= matrix.GetUpperBound(0); row++)\n {\n zeroRow = false;\n for (int col = 0; col <= matrix.GetUpperBound(1); col++)\n {\n if (matrix[row, col] == 0)\n {\n\n zeroRow = true;\n zeroCols |= (byte)(Math.Pow(2, col));\n\n // reset this column in previous rows\n for (int innerRow = 0; innerRow < row; innerRow++)\n {\n matrix[innerRow, col] = 0;\n }\n\n // reset the previous columns in this row\n for (int innerCol = 0; innerCol < col; innerCol++)\n {\n matrix[row, innerCol] = 0;\n }\n }\n else if ((int)(zeroCols & ((byte)Math.Pow(2, col))) > 0)\n {\n matrix[row, col] = 0;\n }\n\n // Force the row to zero\n if (zeroRow) { matrix[row, col] = 0; }\n }\n }\n}\n" }, { "answer_id": 757489, "author": "rvarcher", "author_id": 22828, "author_profile": "https://Stackoverflow.com/users/22828", "pm_score": 0, "selected": false, "text": "-1 0 -1 -1 0\n 0 -1 -1 -1 0\n-1 -1 1 1 -1\n-1 0 -1 -1 -1\n-1 -1 1 1 -1\n Dim D(,) As Integer = {{1, 0, 1, 1, 1}, {0, 1, 1, 0, 1}, {1, 1, 1, 1, 1}, {1, 1, 1, 1, 1}, {0, 0, 1, 1, 1}}\n\nDim B1, B2 As Boolean\n\nFor y As Integer = 0 To UBound(D)\n\n B1 = True : B2 = True\n\n For x As Integer = 0 To UBound(D)\n\n // Scan row for 0's at x and width - x positions. Halfway through I'll konw if there's a 0 in this row.\n //If a 0 is found set my first boolean to false.\n If x <= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then\n If D(x, y) = 0 Or D(UBound(D) - x, y) = 0 Then B1 = False\n End If\n\n //If the boolean is false then a 0 in this row was found. Spend the last half of this loop\n //updating the values. This is where I'm stuck. If I change a 1 to a 0 it will cause the column\n //scan to fail. So for now I change to a -1. If there was a way to change to 0 yet later tell if\n //the value had changed this would work.\n If Not B1 Then\n If x >= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then\n If D(x, y) = 1 Then D(x, y) = -1\n If D(UBound(D) - x, y) = 1 Then D(UBound(D) - x, y) = -1\n End If\n End If\n\n //These 2 block do the same as the first 2 blocks but I switch x and y to do the column.\n If x <= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then\n If D(y, x) = 0 Or D(y, UBound(D) - x) = 0 Then B2 = False\n End If\n\n If Not B2 Then\n If x >= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then\n If D(y, x) = 1 Then D(y, x) = -1\n If D(y, UBound(D) - x) = 1 Then D(y, UBound(D) - x) = -1\n End If\n End If\n\n Next\nNext\n" }, { "answer_id": 4373422, "author": "Warbum", "author_id": 533179, "author_profile": "https://Stackoverflow.com/users/533179", "pm_score": 0, "selected": false, "text": "output(x,y) = col(xy) & row(xy) == 2^n\n col(xy) xy row(xy) xy n" }, { "answer_id": 6417994, "author": "KFL", "author_id": 695964, "author_profile": "https://Stackoverflow.com/users/695964", "pm_score": 0, "selected": false, "text": "def set1(M, N):\n '''Set 1/0s on M according to the rules.\n\n M is a list of N integers. Each integer represents a binary array, e.g.,\n 000100'''\n ruler = 2**N-1\n for i,v in enumerate(M):\n ruler = ruler & M[i]\n M[i] = M[i] if M[i]==2**N-1 else 0 # set i-th row to all-0 if not all-1s\n for i,v in enumerate(M):\n if M[i]: M[i] = ruler\n return M\n M = [ 0b10110,\n 0b01110,\n 0b11111,\n 0b10111,\n 0b11111 ]\n\nprint \"Before...\"\nfor i in M: print \"{:0=5b}\".format(i)\n\nM = set1(M, len(M))\nprint \"After...\"\nfor i in M: print \"{:0=5b}\".format(i)\n Before...\n10110\n01110\n11111\n10111\n11111\nAfter...\n00000\n00000\n00110\n00000\n00110\n" }, { "answer_id": 6428608, "author": "Kenny Cason", "author_id": 403682, "author_profile": "https://Stackoverflow.com/users/403682", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include \"stdlib.h\"\n\nvoid process();\n\nint dim = 5;\nbool m[5][5]{{1,0,1,1,1},{0,1,1,0,1},{1,1,1,1,1},{1,1,1,1,1},{0,0,1,1,1}};\n\n\nint main() {\n process();\n return 0;\n}\n\nvoid process() {\n for(int j = 0; j < dim; j++) {\n for(int i = 0; i < dim; i++) {\n std::cout << (\n (m[0][j] & m[1][j] & m[2][j] & m[3][j] & m[4][j]) &\n (m[i][0] & m[i][1] & m[i][2] & m[i][3] & m[i][4])\n );\n }\n std::cout << std::endl;\n }\n}\n" }, { "answer_id": 6705056, "author": "siddharth", "author_id": 846166, "author_profile": "https://Stackoverflow.com/users/846166", "pm_score": 2, "selected": false, "text": "1 0 1 1 0\n0 1 1 1 0\n1 1 1 1 1\n1 0 1 1 1 \n1 1 1 1 1\n\none each pass save the values of i and j for an element which is 0 in arrays a and b\nwhen first row is scanned a= 1 b = 2,5\nwhen second row is scanned a=1,2 b= 1,2,5\nwhen third row is scanned no change\nwhen fourth row is scanned a= 1,2,4 and b= 1,2,5\nwhen fifth row is scanned no change .\n" }, { "answer_id": 11774579, "author": "Artemix", "author_id": 694852, "author_profile": "https://Stackoverflow.com/users/694852", "pm_score": 0, "selected": false, "text": "public void Run()\n{\n const int N = 5;\n\n int[,] m = new int[N, N] \n {{ 1, 0, 1, 1, 0 },\n { 1, 1, 1, 1, 0 },\n { 1, 1, 1, 1, 1 },\n { 1, 0, 1, 1, 1 },\n { 1, 1, 1, 1, 1 }};\n\n bool keepFirstRow = (m[0, 0] == 1);\n bool keepFirstColumn = keepFirstRow;\n\n for (int i = 1; i < N; i++)\n {\n keepFirstRow = keepFirstRow && (m[0, i] == 1);\n keepFirstColumn = keepFirstColumn && (m[i, 0] == 1);\n }\n\n Print(m); // show initial setup\n\n m[0, 0] = 1; // to protect first row from clearing by \"second pass\"\n\n // \"second pass\" is performed over i-1 row/column, \n // so we use one more index just to complete \"second pass\" over the \n // last row/column\n for (int i = 1; i <= N; i++)\n {\n for (int j = 1; j <= N; j++)\n {\n // \"first pass\" - searcing for zeroes in row/column #i\n // when i = N || j == N it is additional pass for clearing \n // the previous row/column\n // j >= i because cells with j < i may be already modified \n // by \"second pass\" part\n if (i < N && j < N && j >= i) \n {\n m[i, 0] &= m[i, j];\n m[0, j] &= m[i, j];\n\n m[0, i] &= m[j, i];\n m[j, 0] &= m[j, i];\n }\n\n // \"second pass\" - clearing the row/column scanned \n // in the previous iteration\n if (m[i - 1, 0] == 0 && j < N)\n {\n m[i - 1, j] = 0;\n }\n\n if (m[0, i - 1] == 0 && j < N)\n {\n m[j, i - 1] = 0;\n }\n }\n\n Print(m);\n }\n\n // Clear first row/column if needed\n if (!keepFirstRow || !keepFirstColumn)\n {\n for (int i = 0; i < N; i++)\n {\n if (!keepFirstRow)\n {\n m[0, i] = 0;\n }\n if (!keepFirstColumn)\n {\n m[i, 0] = 0;\n }\n }\n }\n\n Print(m);\n\n Console.ReadLine();\n}\n\nprivate static void Print(int[,] m)\n{\n for (int i = 0; i < m.GetLength(0); i++)\n {\n for (int j = 0; j < m.GetLength(1); j++)\n {\n Console.Write(\" \" + m[i, j]);\n }\n Console.WriteLine();\n }\n Console.WriteLine();\n}\n" }, { "answer_id": 14102704, "author": "B.K", "author_id": 988822, "author_profile": "https://Stackoverflow.com/users/988822", "pm_score": 1, "selected": false, "text": "void Evaluate(bool [,] matrix, int n)\n{\n bool tempvar1, tempvar2;\n\n for (var i = 0; i < n; i++)\n {\n tempvar1 = matrix[i, i];\n tempvar2 = matrix[n - i - 1, n - i - 1];\n\n var j = 0;\n\n for (j = 0; j < n; j++)\n {\n if ((i < n/2) || (((n % 2) == 1) && (i == n/2) && (j <= i)))\n {\n // store the row and col & results in corner cells of concentric squares\n tempvar1 &= matrix[j, i];\n matrix[i, i] &= matrix[i, j];\n tempvar2 &= matrix[n - j - 1, n - i - 1];\n matrix[n - i - 1, n - i - 1] &= matrix[n - i - 1, n - j - 1];\n }\n else\n {\n // skip corner cells of concentric squares\n if ((j == i) || (j == n - i - 1)) continue;\n\n // calculate the & values for rest of them\n matrix[i, j] = matrix[i, i] & matrix[n - j - 1, j];\n matrix[n - i - 1, j] = matrix[n - i - 1, n - i - 1] & matrix[n - j - 1, j];\n\n if ((i == n/2) && ((n % 2) == 1))\n {\n // if n is odd\n matrix[i, n - j - 1] = matrix[i, i] & matrix[j, n - j - 1];\n }\n }\n }\n\n if ((i < n/2) || (((n % 2) == 1) && (i <= n/2)))\n {\n // transfer the values from temp variables to appropriate corner cells of its corresponding square\n matrix[n - i - 1, i] = tempvar1;\n matrix[i, n - i - 1] = tempvar2;\n }\n else if (i == n - 1)\n {\n // update the values of corner cells of each concentric square\n for (j = n/2; j < n; j++)\n {\n tempvar1 = matrix[j, j];\n tempvar2 = matrix[n - j - 1, n - j - 1];\n\n matrix[j, j] &= matrix[n - j - 1, j];\n matrix[n - j - 1, j] &= tempvar2;\n\n matrix[n - j - 1, n - j - 1] &= matrix[j, n - j - 1];\n matrix[j, n - j - 1] &= tempvar1;\n }\n }\n }\n}\n" }, { "answer_id": 20989151, "author": "Apriori", "author_id": 3100771, "author_profile": "https://Stackoverflow.com/users/3100771", "pm_score": 0, "selected": false, "text": "template<unsigned n>\nvoid SidewaysAndRowColumn(int((&m)[n])[n]) {\n bool fcol = m[0][0] ? true : false;\n bool frow = m[0][0] ? true : false;\n for (unsigned d = 0; d <= n; ++d) {\n for (unsigned i = 1; i < n; ++i) {\n switch (d) {\n case 0:\n frow = frow && m[d][i];\n fcol = fcol && m[i][d];\n break;\n default:\n {\n unsigned const rd = n - d;\n unsigned const ri = n - i;\n if (d * n + i < rd * n + ri)\n {\n m[ d][ 0] &= m[ d][ i];\n m[ 0][ d] &= m[ i][ d];\n m[ 0][ i] &= m[ d][ i];\n m[ i][ 0] &= m[ i][ d];\n m[rd][ 0] &= m[rd][ri];\n m[ 0][rd] &= m[ri][rd];\n m[ 0][ri] &= m[rd][ri];\n m[ri][ 0] &= m[ri][rd];\n }\n else\n {\n m[ d][ i] = m[ d][0] & m[0][ i];\n m[rd][ri] = m[rd][0] & m[0][ri];\n }\n break;\n }\n case n:\n if (!frow)\n m[0][i] = 0;\n if (!fcol)\n m[i][0] = 0;\n };\n }\n }\n m[0][0] = (frow && fcol) ? 1 : 0;\n}\n" }, { "answer_id": 22003965, "author": "Eki Eqbal", "author_id": 1080046, "author_profile": "https://Stackoverflow.com/users/1080046", "pm_score": 0, "selected": false, "text": "@output @output @input require \"spec_helper\"\n\n\nclass Matrix\n def initialize(input)\n @input = input\n @zeros = []\n end\n\n def solve\n @input.each_with_index do |row, i| \n row.each_with_index do |element, j| \n @zeros << [i,j] if element == 0\n end\n end\n\n @zeros.each do |x,y|\n set_h_zero(x)\n set_v_zero(y)\n end\n\n @input\n end\n\n\n private \n\n def set_h_zero(row) \n @input[row].map!{0} \n end\n\n def set_v_zero(col)\n @input.size.times do |r|\n @input[r][col] = 0\n end\n end\nend\n\n\ndescribe \"Matrix\" do\n it \"Should set the row and column of Zero to Zeros\" do\n input = [[1, 3, 4, 9, 0], \n [0, 3, 5, 0, 8], \n [1, 9, 6, 1, 9], \n [8, 3, 2, 0, 3]]\n\n expected = [[0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0],\n [0, 9, 6, 0, 0],\n [0, 0, 0, 0, 0]]\n\n matrix = Matrix.new(input)\n\n expect(matrix.solve).to eq(expected)\n end\nend\n" }, { "answer_id": 29987179, "author": "geekprogrammer", "author_id": 1630666, "author_profile": "https://Stackoverflow.com/users/1630666", "pm_score": 0, "selected": false, "text": "import java.util.HashSet;\nimport java.util.Set;\n\npublic class MatrixExamples {\n public static void zeroOut(int[][] myArray) {\n Set<Integer> rowsToZero = new HashSet<>();\n Set<Integer> columnsToZero = new HashSet<>();\n\n for (int i = 0; i < myArray.length; i++) { \n for (int j = 0; j < myArray.length; j++) {\n if (myArray[i][j] == 0) {\n rowsToZero.add(i);\n columnsToZero.add(j);\n }\n }\n }\n\n for (int i : rowsToZero) {\n for (int j = 0; j < myArray.length; j++) {\n myArray[i][j] = 0;\n }\n }\n\n for (int i : columnsToZero) {\n for (int j = 0; j < myArray.length; j++) {\n myArray[j][i] = 0;\n }\n }\n\n for (int i = 0; i < myArray.length; i++) { // record which rows and // columns will be zeroed\n for (int j = 0; j < myArray.length; j++) {\n System.out.print(myArray[i][j] + \",\");\n if(j == myArray.length-1)\n System.out.println();\n }\n }\n\n }\n\n public static void main(String[] args) {\n int[][] a = { { 1, 0, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 },\n { 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 1 } };\n zeroOut(a);\n }\n}\n" }, { "answer_id": 41619518, "author": "user3743369", "author_id": 3743369, "author_profile": "https://Stackoverflow.com/users/3743369", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) {\n int m = 5;\n int n = 4;\n int[][] matrixInitial = initMatrix(m, n); // 5x4 matrix init randomly\n int[][] matrixFinal = matrixNull(matrixInitial, m, n); \n for (int i = 0; i < m; i++) {\n System.out.println(Arrays.toString(matrixFinal[i]));\n }\n}\n\npublic static int[][] matrixNull(int[][] matrixInitial, int m, int n) {\n int[][] matrixFinal = initFinal(m, n); // create a matrix with mxn and init it with all -1\n for (int i = 0; i < m; i++) { // iterate in initial matrix\n for (int j = 0; j < n; j++) {\n if(matrixInitial[i][j] == 0){ // if a value is 0 make rows and columns 0\n makeZeroX(matrixFinal, i, j, m, n); \n }\n }\n }\n\n for (int i = 0; i < m; i++) { // if value is -1 (original) copy from initial\n for (int j = 0; j < n; j++) {\n if(matrixFinal[i][j] == -1) {\n matrixFinal[i][j] = matrixInitial[i][j];\n }\n }\n }\n return matrixFinal;\n}\n\nprivate static void makeZeroX(int[][] matrixFinal, int x, int y, int m, int n) {\n for (int j = 0; j < n; j++) { // make all row 0\n matrixFinal[x][j] = 0;\n }\n for(int i = 0; i < m; i++) { // make all column 0\n matrixFinal[i][y] = 0; \n }\n}\n\nprivate static int[][] initMatrix(int m, int n) {\n\n int[][] matrix = new int[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n Random rn = new Random();\n int random = rn.nextInt(10);\n matrix[i][j] = random;\n }\n }\n\n for (int i = 0; i < m; i++) {\n System.out.println(Arrays.toString(matrix[i]));\n }\n System.out.println(\"******\");\n return matrix;\n}\n\nprivate static int[][] initFinal(int m, int n) {\n\n int[][] matrix = new int[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n matrix[i][j] = -1;\n }\n }\n return matrix;\n}\n\n// another approach\n/**\n * @param matrixInitial\n * @param m\n * @param n\n * @return\n */\nprivate static int[][] matrixNullNew(int[][] matrixInitial, int m, int n) {\n List<Integer> zeroRowList = new ArrayList<>(); // Store rows with 0\n List<Integer> zeroColumnList = new ArrayList<>(); // Store columns with 0\n for (int i = 0; i < m; i++) { // read through the matrix when you hit 0 add the column to zeroColumnList and add\n // the row to zeroRowList\n for (int j = 0; j < n; j++) {\n if (matrixInitial[i][j] == 0) {\n if (!zeroRowList.contains(i)) {\n zeroRowList.add(i);\n }\n if (!zeroColumnList.contains(j)) {\n zeroColumnList.add(j);\n }\n }\n }\n }\n\n for (int a = 0; a < m; a++) {\n if (zeroRowList.contains(a)) { // if the row has 0\n for (int b = 0; b < n; b++) {\n matrixInitial[a][b] = 0; // replace all row with zero\n }\n }\n }\n\n for (int b = 0; b < n; b++) {\n if (zeroColumnList.contains(b)) { // if the column has 0\n for (int a = 0; a < m; a++) {\n matrixInitial[a][b] = 0; // replace all column with zero\n }\n }\n }\n return matrixInitial;\n}\n" }, { "answer_id": 46989516, "author": "Türkmen Mustafa Demirci", "author_id": 6269836, "author_profile": "https://Stackoverflow.com/users/6269836", "pm_score": 0, "selected": false, "text": "public class EntireRowSetToZero {\n static int arr[][] = new int[3][4];\n static {\n\n arr[0][0] = 1;\n arr[0][1] = 9;\n arr[0][2] = 2;\n arr[0][3] = 2;\n\n arr[1][0] = 1;\n arr[1][1] = 5;\n arr[1][2] = 88;\n arr[1][3] = 7;\n\n arr[2][0] = 0;\n arr[2][1] = 8;\n arr[2][2] = 4;\n arr[2][3] = 4;\n}\n\npublic static void main(String[] args) {\n displayArr(EntireRowSetToZero.arr, 3, 4);\n setRowToZero(EntireRowSetToZero.arr);\n System.out.println(\"--------------\");\n displayArr(EntireRowSetToZero.arr, 3, 4);\n\n\n}\n\nstatic int[][] setRowToZero(int[][] arr) {\n for (int i = 0; i < arr.length; i++) {\n for (int j = 0; j < arr[i].length; j++) {\n if(arr[i][j]==0){\n arr[i]=new int[arr[i].length];\n }\n }\n\n }\n return arr;\n}\n\nstatic void displayArr(int[][] arr, int n, int k) {\n\n for (int i = 0; i < n; i++) {\n\n for (int j = 0; j < k; j++) {\n System.out.print(arr[i][j] + \" \");\n }\n System.out.println(\"\");\n }\n\n}\n" }, { "answer_id": 49757209, "author": "RahulDeep Attri", "author_id": 5791928, "author_profile": "https://Stackoverflow.com/users/5791928", "pm_score": 1, "selected": false, "text": "public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n int n = sc.nextInt();\n sc.nextLine();\n\n boolean rowDel = false, colDel = false;\n int arr[][] = new int[n][n];\n int res[][] = new int[n][n];\n int i, j;\n for (i = 0; i < n; i++) {\n\n for (j = 0; j < n; j++) {\n arr[i][j] = sc.nextInt();\n res[i][j] = arr[i][j]; \n }\n }\n\n for (i = 0; i < n; i++) {\n\n for (j = 0; j < n; j++) {\n if (arr[i][j] == 0)\n colDel = rowDel = true; //See if we have to delete the\n //current row and column\n if (rowDel == true){\n res[i] = new int[n];\n rowDel = false;\n }\n if(colDel == true){\n for (int k = 0; k < n; k++) {\n res[k][j] = 0;\n }\n colDel = false;\n }\n\n }\n\n }\n\n for (i = 0; i < n; i++) {\n\n for (j = 0; j < n; j++) {\n System.out.print(res[i][j]);\n }\n System.out.println();\n }\n sc.close();\n\n }\n" }, { "answer_id": 51640527, "author": "Muhammed Afsal", "author_id": 5333728, "author_profile": "https://Stackoverflow.com/users/5333728", "pm_score": 0, "selected": false, "text": "public class Main {\n\n public static void main(String[] args) {\n\n\n //test case 1\n int[][] multi = new int[][]{\n { 1, 2, 3 },\n { 4, 0, 5 },\n { 0, 6, 7 },\n };\n\n //test case 2\n int[][] multi2 = new int[][]{\n { 1, 0, 1, 1, 0 },\n { 0, 1, 1, 1, 0 },\n { 1, 1, 1, 1, 1 },\n { 1, 0, 1, 1, 1},\n { 1, 1, 1, 1, 1},\n };\n\n TwoDArraySetZero(multi2);\n }\n\n\n\n static void TwoDArraySetZero(int[][] array){\n\n //iterate through all elements\n for(int i = 0 ; i <= array.length-1 ; i++){\n for (int j = 0; j <= array.length-1; j++) {\n\n //checking if match with zero\n if (array[i][j] == 0){\n\n //set replace with -1 all matching zero row and col if not zero\n for (int k = 0; k <= array.length-1 ; k++) {\n if(array[i][k] != 0 )\n array[i][k] = -1;\n if(array[k][j] != 0)\n array[k][j]= -1;\n }\n }\n }\n }\n\n\n //print array\n for(int i = 0; i <= array.length-1; i++)\n {\n for(int j = 0; j <= array.length-1; j++)\n {\n //replace with zero all -1\n\n if(array[i][j] == -1)\n array[i][j] = 0;\n\n System.out.printf(\"%5d \", array[i][j]);\n }\n System.out.println();\n }\n\n }\n\n }\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20915/" ]
339,266
<p>I'm trying to make a calculator that will take inputs from users and estimate for them how much money they'll save if they use various different VoIP services.</p> <p>I've set it up like this:</p> <pre><code>&lt;form method="get" action="voip_calculator.php"&gt; How much is your monthly phone bill? &lt;input name="monthlybill" type="text" value="$" size="8"&gt; &lt;p&gt;&lt;input type="submit" name="Submit" value="Submit"&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>On voipcalculator.php, the page I point to, I want to call "monthlybill" but I can't figure out how to do it. I also can't figure out how to make it do the subtraction on the numbers in the rows.</p> <p>This may be very simple to you but it's very frustrating to me and I am humbly asking for a bit of help. Thank you!</p> <p></p> <p>Here is the relevant stuff from voip_calculator, you can also click on the url and submit a number to see it in (in)action. I tried various times to call it with no success:</p> <pre><code>&lt;table width="100%;" border="0" cellspacing="0" cellpadding="0"class="credit_table2" &gt; &lt;tr class="credit_table2_brd"&gt; &lt;td class="credit_table2_brd_lbl" width="100px;"&gt;Services:&lt;/td&gt; &lt;td class="credit_table2_brd_lbl" width="120px;"&gt;Our Ratings:&lt;/td&gt; &lt;td class="credit_table2_brd_lbl" width="155px;"&gt;Your Annual Savings:&lt;/td&gt; &lt;/tr&gt; Your monthly bill was &lt;?php echo 'monthlybill' ?&gt; &lt;?php echo "$monthlybill"; ?&gt; &lt;?php echo "monthlybill"; ?&gt; &lt;?php echo '$monthlybill'; ?&gt; &lt;?php echo 'monthlybill'; ?&gt; &lt;?php $monthybill="monthlybill"; $re=1; $offer ='offer'.$re.'name'; $offername= ${$offer}; while($offername!="") { $offerlo ='offer'.$re.'logo'; $offerlogo=${$offerlo}; $offerli ='offer'.$re.'link'; $offerlink=${$offerli}; $offeran ='offer'.$re.'anchor'; $offeranchor=${$offeran}; $offerst ='offer'.$re.'star1'; $offerstar=${$offerst}; $offerbot='offer'.$re.'bottomline'; $offerbottomline=${$offerbot}; $offerca ='offer'.$re.'calcsavings'; $offercalcsavings=${$offerca}; echo '&lt;tr &gt; &lt;td &gt; &lt;a href="'.$offerlink.'" target="blank"&gt; &lt;img src="http://www.nextadvisor.com'.$offerlogo.'" alt="'.$offername.'" /&gt; &lt;/a&gt; &lt;/td&gt; &lt;td &gt; &lt;span class="rating_text"&gt;Rating:&lt;/span&gt; &lt;span class="star_rating1"&gt; &lt;img src="IMAGE'.$offerstar.'" alt="" /&gt; &lt;/span&gt; &lt;br /&gt; &lt;div style="margin-top:5px; color:#0000FF;"&gt; &lt;a href="'.$offerlink.'" target="blank"&gt;Go to Site&lt;/a&gt; &lt;span style="margin:0px 7px 0px 7px;"&gt;|&lt;/span&gt; &lt;a href="'.$offeranchor.'"&gt;Review&lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;td &gt;'.$offercalcsavings.'&lt;/td&gt; &lt;/tr&gt;'; $re=$re+1; $offer ='offer'.$re.'name'; $offername= ${$offer}; } ?&gt; </code></pre> <p></p> <p>offercal(1,2,3,4,5,6,7)savings calls to a file called values.php where they are defined like this:</p> <pre><code>$offer1calcsavings="24.99"; $offer2calcsavings="20.00"; $offer3calcsavings="21.95"; $offer4calcsavings="23.95"; $offer5calcsavings="19.95"; $offer6calcsavings="23.97"; $offer7calcsavings="24.99"; </code></pre>
[ { "answer_id": 339298, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "$monthlyBill = $_GET['monthlybill'];\n echo \"Your monthly bill is: $monthlyBill\";\n" }, { "answer_id": 339316, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 1, "selected": false, "text": "echo \"<pre>\";\nprint_r($_GET);\necho \"</pre>\";\n" }, { "answer_id": 339347, "author": "Joe", "author_id": 41880, "author_profile": "https://Stackoverflow.com/users/41880", "pm_score": 1, "selected": false, "text": "$monthlyBill = $_GET['monthlybill']; //you should do some checking to prevent attacks but that's another matter\n <?php\n //...code for the rest of the page and starting your table\n\n foreach($companySavings as $savings){//insert each row into the table\n echo(\"<tr><td>\".(comapnyName/Image whatever..).\"</td><td>$\".$monthlyBill-$savings.\"</td></tr>);\n }\n //... end the table and rest of code\n ?>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43035/" ]
339,269
<p>Here is the current architecture of my transaction scope source code. The third insert throws an .NET exception (Not a SQL Exception) and it is not rolling back the two previous insert statements. What I am doing wrong?</p> <p><b>EDIT:</b> I removed the try/catch from insert2 and insert3. I also removed the exception handling utility from the insert1 try/catch and put "throw ex". It still does not rollback the transaction.</p> <p><b>EDIT 2:</b> I added the try/catch back on the Insert3 method and just put a "throw" in the catch statement. It still does not rollback the transaction.</p> <p><b>UPDATE:</b>Based on the feedback I received, the "SqlHelper" class is using the SqlConnection object to establish a connection to the database, then creates a SqlCommand object, set the CommandType property to "StoredProcedure" and calls the ExecuteNonQuery method of the SqlCommand.</p> <p>I also did not add Transaction Binding=Explicit Unbind to the current connection string. I will add that during my next test. </p> <pre><code>public void InsertStuff() { try { using(TransactionScope ts = new TransactionScope()) { //perform insert 1 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /* create parameters for first insert */ }; sh.Insert("MyInsert1", sp); } //perform insert 2 this.Insert2(); //perform insert 3 - breaks here!!!!! this.Insert3(); ts.Complete(); } } catch(Exception ex) { throw ex; } } public void Insert2() { //perform insert 2 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /* create parameters for second insert */ }; sh.Insert("MyInsert2", sp); } } public void Insert3() { //perform insert 3 using(SqlHelper sh = new SqlHelper()) { SqlParameter[] sp = { /*create parameters for third insert */ }; sh.Insert("MyInsert3", sp); } } </code></pre>
[ { "answer_id": 339638, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "Transaction Binding=Explicit Unbind" }, { "answer_id": 10212867, "author": "Omer Cansizoglu", "author_id": 497441, "author_profile": "https://Stackoverflow.com/users/497441", "pm_score": 0, "selected": false, "text": " private static readonly string _connectionString = ConnectionString.GetDbConnection();\n\n private const string inserttStr = @\"INSERT INTO dbo.testTable (col1) VALUES(@test);\";\n\n /// <summary>\n /// Execute command on DBMS.\n /// </summary>\n /// <param name=\"command\">Command to execute.</param>\n private void ExecuteNonQuery(IDbCommand command)\n {\n if (command == null)\n throw new ArgumentNullException(\"Parameter 'command' can't be null!\");\n\n using (IDbConnection connection = new SqlConnection(_connectionString))\n {\n command.Connection = connection;\n connection.Open();\n command.ExecuteNonQuery();\n }\n }\n\n public void FirstMethod()\n {\n IDbCommand command = new SqlCommand(inserttStr);\n command.Parameters.Add(new SqlParameter(\"@test\", \"Hello1\"));\n\n\n ExecuteNonQuery(command);\n\n }\n\n public void SecondMethod()\n {\n IDbCommand command = new SqlCommand(inserttStr);\n command.Parameters.Add(new SqlParameter(\"@test\", \"Hello2\"));\n\n\n ExecuteNonQuery(command);\n\n }\n\n public void ThirdMethodCauseNetException()\n {\n IDbCommand command = new SqlCommand(inserttStr);\n command.Parameters.Add(new SqlParameter(\"@test\", \"Hello3\"));\n\n\n ExecuteNonQuery(command);\n int a = 0;\n int b = 1/a;\n\n }\n\n public void MainWrap()\n {\n\n\n TransactionOptions tso = new TransactionOptions();\n tso.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;\n //TransactionScopeOption.Required, tso\n try\n {\n using (TransactionScope sc = new TransactionScope())\n {\n FirstMethod();\n SecondMethod();\n ThirdMethodCauseNetException();\n sc.Complete();\n }\n }\n catch (Exception ex)\n {\n logger.ErrorException(\"eee \",ex);\n\n }\n }\n SELECT \nrequest_session_id AS spid,\nCASE transaction_isolation_level \nWHEN 0 THEN 'Unspecified' \nWHEN 1 THEN 'ReadUncomitted' \nWHEN 2 THEN 'Readcomitted' \nWHEN 3 THEN 'Repeatable' \nWHEN 4 THEN 'Serializable' \nWHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL ,\nresource_type AS restype,\nresource_database_id AS dbid,\nDB_NAME(resource_database_id) as DBNAME,\nresource_description AS res,\nresource_associated_entity_id AS resid,\nCASE \nwhen resource_type = 'OBJECT' then OBJECT_NAME( resource_associated_entity_id) \nELSE 'N/A'\nEND as ObjectName,\nrequest_mode AS mode,\nrequest_status AS status\nFROM sys.dm_tran_locks l\nleft join sys.dm_exec_sessions s on l.request_session_id = s.session_id\nwhere resource_database_id = 24\norder by spid, restype, dbname;\n" }, { "answer_id": 57246749, "author": "Hamid Heydarian", "author_id": 4426009, "author_profile": "https://Stackoverflow.com/users/4426009", "pm_score": 0, "selected": false, "text": "TransactionScope" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
339,286
<p>I'm looking for an XML editor that lets me type and copy and paste arbitrary text into an XML element or attribute without requiring me to go back through and escape any characters that must use reserved XML entities (ampersands, angle brackets, or quote marks). XMLSpy came up short.</p>
[ { "answer_id": 339348, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 2, "selected": false, "text": "a<b < a<b/> <![CDATA[a<b]]>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,296
<p>Greetings!</p> <p>I have some XML like this:</p> <pre><code>&lt;Root&gt; &lt;AlphaSection&gt; . . . &lt;/AlphaSection&gt; &lt;BetaSection&gt; &lt;Choices&gt; &lt;SetA&gt; &lt;Choice id="choice1"&gt; &lt;Title&gt;Choice 1 Title&lt;/Title&gt; &lt;Body&gt;Choice 1 Body&lt;/Body&gt; &lt;/Choice&gt; &lt;Choice id="choice2"&gt; &lt;Title&gt;Choice 2 Title&lt;/Title&gt; &lt;Body&gt;Choice 2 Body&lt;/Body&gt; &lt;/Choice&gt; &lt;/SetA&gt; &lt;SetB&gt; &lt;Choice id="choice3"&gt; &lt;Title&gt;Choice 3 Title&lt;/Title&gt; &lt;Body&gt;Choice 3 Body&lt;/Body&gt; &lt;/Choice&gt; &lt;Choice id="choice4"&gt; &lt;Title&gt;Choice 4 Title&lt;/Title&gt; &lt;Body&gt;Choice 4 Body&lt;/Body&gt; &lt;/Choice&gt; &lt;/SetB&gt; &lt;/Choices&gt; &lt;/BetaSection&gt; &lt;GammaSection&gt; . . . &lt;/GammaSection&gt; &lt;/Root&gt; </code></pre> <p>I'm currently doing the following to retrieve the ID of each choice:</p> <pre><code>var choiceList = myXDoc.Root .Element("BetaSection") .Descendants("Choice") .Select(element =&gt; new { ID = element.Attribute("id").Value, // Title = ? // Body = ? }); </code></pre> <p>I'd also like to get the values in the Title and Body child nodes of each Choice. How would I go about it? Thanks.</p>
[ { "answer_id": 339338, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": true, "text": "element => new {\n ID = element.Attribute(\"id\").Value,\n Title = element.Element(\"Title\").Value,\n Body = element.Element(\"Body\").Value\n });\n" }, { "answer_id": 339593, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 0, "selected": false, "text": "element => new {\n ID = (string)element.Attribute(\"id\"),\n title = (string)element.Element(\"Title\"),\n Body = (string)element.Element(\"Body\")\n });\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
339,312
<p>This question is more security related than programming related, sorry if it shouldn't be here.</p> <p>I'm currently developing a web application and I'm curious as to why most websites don't mind displaying their exact server configuration in HTTP headers, like versions of Apache and PHP, with complete "mod_perl, mod_python, ..." listing and so on.</p> <p>From a security point of view, I'd prefer that it would be impossible to find out if I'm running PHP on Apache, ASP.NET on IIS or even Rails on Lighttpd.</p> <p>Obviously "obscurity is not security" but should I be worried at all that visitors know what version of Apache and PHP my server is running ? Is it good practice or totally unnecessary to hide this information ?</p>
[ { "answer_id": 339357, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 2, "selected": false, "text": "nmap -O -sV" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38072/" ]
339,314
<p>I am working on a ASP.net project created with local file system settings. I am using MVC and Jquery. Jquery is working fine when I run the application in debug mode i.e. in ASP.net Development server. I am trying to host the application in IIS 7. In hosted mode, it does not recognize Jquery and gives scripting error 'Jquery is undefined'. The locations of the script files is unchanged in both modes. Can anybody have any clue what can be the reason and how to solve this.</p> <p>My code look like this;</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"&gt;&lt;/script&gt; &lt;!-- YUI Styles --&gt; &lt;link href="../../Content/reset.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="../../Content/fonts.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="../../Content/grids.css" rel="stylesheet" type="text/css" /&gt; &lt;!-- /YUI Styles --&gt; &lt;link href="../../Content/knowledgebase.css" rel="stylesheet" type="text/css" /&gt; &lt;script type="text/javascript"&gt; //this hides the javascript warning if javascript is enabled (function($) { $(document).ready(function() { $('#jswarning').hide(); }); })(jQuery); &lt;/script&gt; &lt;asp:ContentPlaceHolder ID="ScriptContent" runat="server" /&gt; </code></pre> <p> ....</p>
[ { "answer_id": 339336, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 2, "selected": false, "text": "Jquery jQuery Jquery jQuery" }, { "answer_id": 341725, "author": "Raja", "author_id": 43049, "author_profile": "https://Stackoverflow.com/users/43049", "pm_score": 2, "selected": false, "text": "<script src=\"<%= Url.Content(\"~/Scripts/jquery-1.2.6.js\")%>\" type=\"text/javascript\"></script>\n" }, { "answer_id": 342180, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n" }, { "answer_id": 629571, "author": "Michel van Engelen", "author_id": 76068, "author_profile": "https://Stackoverflow.com/users/76068", "pm_score": 2, "selected": false, "text": "<script src=\"<%= Url.Content(\"~/Scripts/jquery-1.2.6.js\")%>\" type=\"text/javascript\"></script>\n" }, { "answer_id": 727534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<script src=\"<%= ResolveUrl(\"~/Scripts/jquery-1.2.6.js\")%>\" type=\"text/javascript\"></script>\n" }, { "answer_id": 2554291, "author": "Dan Heberden", "author_id": 306140, "author_profile": "https://Stackoverflow.com/users/306140", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\" ></script>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43049/" ]
339,344
<p>So, I've been looking at <a href="http://hadoop.apache.org/" rel="noreferrer">Hadoop</a> with keen interest, and to be honest I'm fascinated, things don't get much cooler.</p> <p>My only minor issue is I'm a C# developer and it's in Java.</p> <p>It's not that I don't understand the Java as much as I'm looking for the Hadoop.net or NHadoop or the .NET project that embraces the <a href="http://en.wikipedia.org/wiki/MapReduce" rel="noreferrer">Google MapReduce</a> approach. Does anyone know of one?</p>
[ { "answer_id": 2148366, "author": "Turbo", "author_id": 100518, "author_profile": "https://Stackoverflow.com/users/100518", "pm_score": 3, "selected": false, "text": "IEnumerable<T> PartitionedTable<T>" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30861/" ]
339,353
<p>How best can I convert instances of double backslashes to a single backslash in a string, but remove any occurrences of single backslash?</p> <p>So this:</p> <pre> \|Testing|ABC:1234\\1000-1\| </pre> <p>Should convert to this:</p> <pre> |Testing|ABC:1234\1000-1| </pre> <p>Ideally I want to avoid a temporary replace of '\' to another character. A solution using .NET or Regular Expressions is preferred.</p>
[ { "answer_id": 339369, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 4, "selected": true, "text": "Regex.Replace(input, @\"\\\\(.|$)\", \"$1\");\n" }, { "answer_id": 339396, "author": "GONeale", "author_id": 41211, "author_profile": "https://Stackoverflow.com/users/41211", "pm_score": 0, "selected": false, "text": "Regex.Replace(@\"\\L\\\\A\\\", @\"\\\\(.)\", \"$1\")\n L\\A\\ L\\A for (int i = 0; i < text.Length; i++)\n{\n if (text[i] == '\\\\' && (i + 1 <= text.Length && text[i + 1] == '\\\\'))\n newText += '\\\\';\n else if (text[i] == '\\\\')\n newText += string.Empty;\n else\n newText += text[i];\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41211/" ]
339,356
<p>Is there a public, free web service that generates tag clouds? I'm looking for something like Google Chart--URL in, image out.</p>
[ { "answer_id": 62561391, "author": "ty.", "author_id": 219604, "author_profile": "https://Stackoverflow.com/users/219604", "pm_score": 1, "selected": false, "text": "https://quickchart.io/wordcloud?text=Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.But, in a larger sense, we can not dedicate—we can not consecrate—we can not hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.\n linear sqrt log true resp = requests.post('https://quickchart.io/wordcloud', json={\n 'format': 'png',\n 'width': 1000,\n 'height': 1000,\n 'fontScale': 15,\n 'scale': 'linear',\n 'removeStopwords': True,\n 'minWordLength': 4,\n 'text': 'To be or not to be, that is the question...',\n})\n\nwith open('shakespeare.png', 'wb') as f:\n f.write(resp.content)\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13842/" ]
339,370
<p>This question is simple. What function would I use in a PHP script to load data from a URL into a string?</p>
[ { "answer_id": 339383, "author": "chews", "author_id": 33966, "author_profile": "https://Stackoverflow.com/users/33966", "pm_score": 3, "selected": false, "text": "$url_data = file_get_contents(\"http://example.com/examplefile.txt\");\n" }, { "answer_id": 340909, "author": "Keith Palmer Jr.", "author_id": 26133, "author_profile": "https://Stackoverflow.com/users/26133", "pm_score": 4, "selected": true, "text": "\n// create a new cURL resource\n$ch = curl_init();\n\n// set URL and other appropriate options\ncurl_setopt($ch, CURLOPT_URL, \"http://www.example.com/\");\ncurl_setopt($ch, CURLOPT_HEADER, 0);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n\n// grab URL and pass it to the browser\n$html = curl_exec($ch);\n\n// close cURL resource, and free up system resources\ncurl_close($ch);\n" }, { "answer_id": 342060, "author": "Derek Kurth", "author_id": 1418, "author_profile": "https://Stackoverflow.com/users/1418", "pm_score": 1, "selected": false, "text": "include \"Snoopy.class.php\";\n$snoopy = new Snoopy;\n$snoopy->fetchtext(\"http://www.example.com\");\n$html = $snoopy->results;\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26659/" ]
339,371
<p>I have this method in my db class</p> <pre><code>public function query($queryString) { if (!$this-&gt;_connected) $this-&gt;_connectToDb(); //connect to database $results = mysql_query($queryString, $this-&gt;_dbLink) or trigger_error(mysql_error()); return mysql_num_rows($results) &gt; 0 ? mysql_fetch_assoc($results) : false; } </code></pre> <p>This works great for queries that return 1 row, but how can I get an array returned something like this?</p> <pre><code>$array[0]['name'] = 'jim' $array[0]['id'] = 120 $array[1]['name'] = 'judith' $array[1]['ID'] = 121 </code></pre> <p>Now I know I could use a while loop to insert this data into the array like so, but I was wondering if PHP could do this with an internal function? I havn't been able to find on the docs what I'm after.</p> <p>The reason I don't want to run the while within the method is because I am going to reiterate back over the array when it's returned, and I'd rather not run through the results twice (for performance reasons).</p> <p>Is there a way to do this? Do I have a problem with my general query method design?</p> <p>Thank you muchly!</p>
[ { "answer_id": 339384, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": true, "text": "public function query($queryString)\n {\n\n if (!$this->_connected) $this->_connectToDb(); //connect to database\n\n $results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());\n\n $data = array();\n while($row = mysql_fetch_assoc($results))\n {\n $data[] = $row;\n }\n return $data;\n\n }\n public function query($queryString)\n {\n\n if (!$this->_connected) $this->_connectToDb(); //connect to database\n\n return mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error());\n\n }\n" }, { "answer_id": 339386, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "while() mysql_fetch_assoc()" }, { "answer_id": 355491, "author": "mcrumley", "author_id": 17287, "author_profile": "https://Stackoverflow.com/users/17287", "pm_score": 2, "selected": false, "text": "<?php\n$db = new PDO($connection_string, $username, $password);\n$result = $db->query($queryString);\nforeach($result as $row) {\n // do something\n}\n\n// or\n\n$result = $db->query($queryString);\n$result_array = $result->fetchAll(PDO::FETCH_ASSOC);\n?>\n" }, { "answer_id": 564098, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "//to create a numerically indexed array:\n$data = array();\nforeach ($results as $row)\n {\n $data[] = $row;\n }\nreturn $data; \n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
339,387
<p>I'm trying to validate that a submitted URL doesn't already exist in the database.</p> <p>The relevant parts of the Form class look like this:</p> <pre><code>from django.contrib.sites.models import Site class SignUpForm(forms.Form): # ... Other fields ... url = forms.URLField(label='URL for new site, eg: example.com') def clean_url(self): url = self.cleaned_data['url'] try: a = Site.objects.get(domain=url) except Site.DoesNotExist: return url else: raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") def clean(self): # Other form cleaning stuff. I don't *think* this is causing the grief </code></pre> <p>The problem is, regardless of what value I submit, I can't raise the <code>ValidationError</code>. And if I do something like this in the <code>clean_url()</code> method:</p> <pre><code>if Site.objects.get(domain=url): raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") </code></pre> <p>then I get a <code>DoesNotExist</code> error, even for URLs that already exist in the Database. Any ideas?</p>
[ { "answer_id": 339463, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "try:\n a = Site.objects.get(domain=url)\n raise forms.ValidationError(\"That URL is already in the database. Please submit a unique URL.\")\nexcept Site.DoesNotExist:\n pass\nreturn url\n" }, { "answer_id": 340160, "author": "Igorekk", "author_id": 36516, "author_profile": "https://Stackoverflow.com/users/36516", "pm_score": 0, "selected": false, "text": "msg = u\"That URL is already in the database. Please submit a unique URL.\"\nself._errors[\"url\"]=ErrorList([msg])\nreturn ''\n from django.contrib.sites.models import Site\nclass SignUpForm(forms.Form):\n # ... Other fields ...\n\nurl = forms.URLField(label='URL for new site, eg: example.com')\n\ndef clean_url(self):\n url = self.cleaned_data['url']\n try:\n a = Site.objects.get(domain=url)\n raise forms.ValidationError(\"That URL is already in the database. Please submit a unique URL.\")\n except Site.DoesNotExist:\n return url\n return ''\n\ndef clean(self):\n # Other form cleaning stuff. I don't *think* this is causing the grief\n" }, { "answer_id": 341621, "author": "saturdayplace", "author_id": 3912, "author_profile": "https://Stackoverflow.com/users/3912", "pm_score": 3, "selected": true, "text": "cleaned_data['url'] example.com http://example.com/ clean_url() def clean_url(self):\n url = self.cleaned_data['url'] \n bits = urlparse(url)\n dom = bits[1]\n try:\n site=Site.objects.get(domain__iexact=dom)\n except Site.DoesNotExist:\n return dom\n raise forms.ValidationError(u'That domain is already taken. Please choose another')\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3912/" ]
339,397
<p>I'm coming from a C# background and I really like the type inference that C# 3.0 has. I'm trying to do similar things in VB.NET (some of which appear possible), but in some cases the compiler seems to be not nearly as good at inferring the type.</p> <p>For example, I have a method that returns an object of type System.Guid. In C# I'd do this and the variable 'prop' would be of type Guid through inference.</p> <pre><code>var prop = RegisterProperty&lt;Guid&gt;(...); </code></pre> <p>However, if I do a similar thing in VB.NET:</p> <pre><code>Dim prop = RegisterProperty(Of Guid(...) </code></pre> <p>I get <em>prop</em> as type System.Object. I've played with some of the VB.NET project settings but the only thing it changes is whether I get a warning that the object is of type Object when I use it later as a Guid.</p> <p>Any ideas? I'm thinking the use of generics should allow the compiler to tell beyond a doubt what type <em>prop</em> should be.</p> <hr> <p>@J Cooper: ok, I did have that setting turned on, but I just re-read the documentation for that compiler option and it reads "Specifies whether to allow local type inference in variable declarations". I believe the reason it's not working for me is that I'm declaring static fields in my class. I guess even though they are initialized when declared, the compiler doesn't support type inference at that point. Bummer.</p>
[ { "answer_id": 7259611, "author": "Jim Wooley", "author_id": 112139, "author_profile": "https://Stackoverflow.com/users/112139", "pm_score": 1, "selected": false, "text": "Public Shared foo = \"Test\"\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11807/" ]
339,409
<p>I have a problem where I want to read an object from the database using Hibernate, change a value, and save the object. If changing the value takes some time, what's the best way to ensure the underlying object in the database has not changed? I am doing this in one transaction (and one session). </p> <p>The code looks something like:</p> <pre><code>// Load from DB Criteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq("id", 5) ); Dummy val = crit.uniqueResult(); // Processing time elapses. // Update value of dummy. val.x++; // Save back to database. But what if someone modified the row with ID = 5 in the meantime, and changed the value of x? session.saveOrUpdate( val ); </code></pre>
[ { "answer_id": 339449, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "session.lock( myObject , LockMode.UPGRADE );\n // Load from DB\n\nCriteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq(\"id\", 5) );\n\ncrit.setLockMode( LockMode.UPGRADE ); // issues a SELECT ... for UPDATE... \n\nDummy val = crit.uniqueResult();\n\n etc.etc\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43067/" ]
339,412
<p>What is the preferred way to use stored procedures between the following two methods and why:</p> <p>One general SP such as 'GetOrders' which returns all the columns for the table Order. Several different parts of the application will use the same SP.</p> <p>OR</p> <p>Several more specific SPs such as 'GetOrdersForUse1' and 'GetOrdersForUse2' which return a subset of all the columns. Each SP is only used by one part of the application.</p> <p>In the general case, the application will only use a subset of the columns returned by the SP. I was thinking of using the specific method for performance reasons but is it really going to be worth the extra work? I am developing a web site using ASP.NET and SQL 2005.</p>
[ { "answer_id": 339449, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "session.lock( myObject , LockMode.UPGRADE );\n // Load from DB\n\nCriteria crit = session.createCriteria( Dummy.class ).add( Restrictions.eq(\"id\", 5) );\n\ncrit.setLockMode( LockMode.UPGRADE ); // issues a SELECT ... for UPDATE... \n\nDummy val = crit.uniqueResult();\n\n etc.etc\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,424
<p>I'm a pretty experienced Grails developer, but most of my experience has been with using grails for serving up JSON/XML to a flex app and some relatively simple HTML websites.</p> <p>I've been diving deeper into using the sitemesh integration in grails and I'm struggling a little to find best practices for some more complex configurations, and I'm curious if there are any good tutorials or examples out there. The <a href="http://www.opensymphony.com/sitemesh/" rel="noreferrer">original Sitemesh</a> website isn't that useful as the tags it talks about aren't directly exposed in grails.</p> <p>A google search is mostly showing old mailing list posts and some vanilla sitemesh stuff which is helping me to move a little further along, but it's a lot of trial and error.</p> <p>I fully understand how the basic g:layoutTitle, g:layoutHead, and g:layoutBody tags work. Those are easy and well documented.</p> <p>The kinds of things that I'd like to see examples for:</p> <ul> <li><p>g:applyLayout - <a href="http://grails.org/doc/1.0.x/ref/Tags/applyLayout.html" rel="noreferrer">the documentation on this</a> is weak and I don't fully understand the uses suggested in the main docs. How is this different than setting the <code>meta name='layout' content='foo'</code> property?</p></li> <li><p>g:pageProperty - some better examples on how to pull and use properties into the main template by setting the values as meta tags in the page that's being decorated. The <a href="http://grails.org/doc/1.0.x/ref/Tags/pageProperty.html" rel="noreferrer">grails docs on pageProperty</a> show only the onload attribute from the body being brought forward. I think you can also use meta tag values here as well, anything else?</p></li> <li><p>can you use multiple levels of sitemesh layouts? My testing seems to make me think that I can't, but that seems to reduce reusability. I think that the answer here is some usage of the g:applyLayout, but that's where I'm struggling the most. </p></li> </ul>
[ { "answer_id": 343027, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 5, "selected": true, "text": "<meta name=\"layout\" content=\"editTemplate\" />\n <g:applyLayout name=\"baseTemplate\" >\n<!-- the html for the editTemplate -->\n</g:applyLayout>\n" }, { "answer_id": 921337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<html>\n<body>\n<g:pageProperty name=\"page.header\" />\n</body>\n <content tag=\"header\">\n<!-- header -->\n</content>\n" }, { "answer_id": 5145507, "author": "igor", "author_id": 497648, "author_profile": "https://Stackoverflow.com/users/497648", "pm_score": 2, "selected": false, "text": "<span class=\"errorMessageInSomeFancyBox\">\n <span class=\"errorIcon\"></span>\n <g:layoutBody />\n<span>\n <%-- let's decorate our error message with some fancy box --%>\n<g:applyLayout name=\"inline-error-message\">${some.error.message}</g:applyLayout>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
339,429
<p>Is there an SSH client that can present a client side GUI interface to the <a href="http://www.cyberciti.biz/tips/how-to-use-screen-command-under-linux.html" rel="nofollow noreferrer">screen</a>* program?</p> <p>I'm thinking of an SSH program that would hook in with screen's session handling and map client side actions (clicking on a tab, ctrl-tab, scrolling, possibly even allowing several tabs to be seen at the same time) to whatever it takes to make screen at the other end do it's thing. </p> <p><code>*</code> The <a href="http://www.cyberciti.biz/tips/how-to-use-screen-command-under-linux.html" rel="nofollow noreferrer">screen</a> program that allow multiple virtual consoles under a single terminal session, for example you can run several apps under a single SSH connection and switch between them as well as other cool things.</p>
[ { "answer_id": 830173, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "~/.screenrc startup_message off\nvbell off\nhardstatus alwayslastline\nhardstatus string '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}(%{W}%n*%f %t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%= %{g}]%{=y C}[%d/%m %c]%{W}'\n ctrl+a,a ctrl+a,[ Esc ctrl+c screen -x -r /tmp/uscreens/S-$USER/$PID.sessionname" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
339,455
<p>When I include an image as an &lt;img&gt; tag as well as a background image on a DOM element, the browser sometimes makes two requests for the same image. This also sometimes happens when using the hover pseudo-property. For example:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style&gt; div{ background: transparent url(/img/stuff.png) no-repeat; } div:hover{ background: transparent url(/img/stuff.png) no-repeat 25px 0px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;img alt="" src="/img/stuff.png"/&gt; &lt;div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Why would the image be requested twice (or possibly three times)? Is this a behavior I can avoid? If so how?</p> <p>[EDIT]</p> <p>I noticed this while watching the Google appengine local server process so I'm fairly certain it wasn't actually cached by the browser (As it could have been if I had seen it in firebug or webkit inspector).</p> <p>I've seen this in Google Chrome, IE7, and Firefox 3.</p>
[ { "answer_id": 339458, "author": "Ryan Smith", "author_id": 10420, "author_profile": "https://Stackoverflow.com/users/10420", "pm_score": 0, "selected": false, "text": "<img alt=\"\" src=\"/img/stuff.png\" style=\"display: none;\"/>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
339,469
<p>I'm using MS Access to create a database with over 5000 contacts. These contacts are separated up into which employee the contact belongs to, and then again into categories for easy searching. What I want to do is create a button that will open up a query in table form (simple), then have check boxes so an employee can select, for example, 100 contacts to send an email to out of the 110 in the table, and then send a mass email such as a newsletter (not so simple!). I've been going nuts trying to work out how to do this as I don't really understand programming (I'm a temp thrown into this job and just doing the best I can) and all I can find on the matter is something about loops (no idea!) and that I need software to do this. </p> <p>Any solutions for me please? I'd like to avoid buying/installing software if possible and if you do have an answer, please make it as simple as possible...</p> <p>Thanks in advance!</p> <p>Kate</p>
[ { "answer_id": 340009, "author": "rics", "author_id": 21047, "author_profile": "https://Stackoverflow.com/users/21047", "pm_score": 1, "selected": false, "text": "Private Sub Mail_Click()\n\n Dim r As Recordset\n Dim email As String\n Set r = CurrentDb.OpenRecordset(\"select * from Addresses\")\n Do While Not r.EOF\n email = r(2)\n DoCmd.SendObject acSendNoObject, Null, Null, email, Null, Null, \"Test subject\", \"Message body of the test letter\", False, Null\n r.MoveNext\n Loop\n r.Close\n\nEnd Sub\n" }, { "answer_id": 340866, "author": "John Mo", "author_id": 38988, "author_profile": "https://Stackoverflow.com/users/38988", "pm_score": 0, "selected": false, "text": "Dim r As Recordset\nDim email As String\nSet r = CurrentDb.OpenRecordset(\"select * from Addresses\")\nDo While Not r.EOF\n email = email & r(2) & \";\"\n r.MoveNext\nLoop\nr.Close\n\nDoCmd.SendObject acSendNoObject, Null, Null, email, Null, Null, \"Test subject\", \"Message body of the test letter\", False, Null\n" }, { "answer_id": 342836, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " Dim r As Recordset\nDim Email As String\nSet r = CurrentDb.OpenRecordset(\"select Email from FranksFinanceBrokers\")\nDo While Not r.EOF\n Email = Email & r(0) & \";\"\n r.MoveNext\nLoop\nr.Close\n\nDoCmd.SendObject acSendNoObject, Null, Null, \"\", \"\", Email, \"\", \"\", True, Null\n\nEnd Sub\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,476
<p>How do I raise an event from a user control that was created dynamically?</p> <p>Here's the code that I'm trying where Bind is a public EventHandler</p> <pre><code>protected indDemographics IndDemographics; protected UserControl uc; override protected void OnInit(EventArgs e) { uc = (UserControl)LoadControl("indDemographics.ascx"); IndDemographics.Bind += new EventHandler(test_handler); base.OnInit(e); } </code></pre> <p>I get a null object for IndDemographics. Can anyone point me to a complete code sample? Thanks in advance...</p>
[ { "answer_id": 339522, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 3, "selected": true, "text": "public class MyUserControl\n Inherits UserControl\n\n Public Event Bind(sender as object, e as EventArgs)\n\n public sub SomeFunction()\n RaiseEvent Bind(me, new EventArgS())\n End Sub\nEnd Class\n Dim btn As New Button;\nAddHandler btn.Click, AddressOf MyButtonClickEventHandler\n protected indDemographics IndDemographics;\noverride protected void OnInit(EventArgs e)\n{\n indDemographics = LoadControl(\"~/indDemographics.ascx\");\n IndDemographics.Bind += new EventHandler(test_handler);\n base.OnInit(e);\n}\n" }, { "answer_id": 342677, "author": "Geri Langlois", "author_id": 4888, "author_profile": "https://Stackoverflow.com/users/4888", "pm_score": 1, "selected": false, "text": "protected indDemographics IndDemo;\noverride protected void OnInit(EventArgs e)\n{\n Control c = LoadControl(\"~/indDemographics.ascx\");\n IndDemo = (indDemographics) c;\n IndDemo.Bind += new EventHandler(test_handler);\n place1.Controls.Add(IndDemo);\n base.OnInit(e);\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4888/" ]
339,483
<p>I need to repeatedly remove the first line from a huge text file using a bash script.</p> <p>Right now I am using <code>sed -i -e "1d" $FILE</code> - but it takes around a minute to do the deletion.</p> <p>Is there a more efficient way to accomplish this?</p>
[ { "answer_id": 339543, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 1, "selected": false, "text": "While file1 not empty\n file2 = head -n1000 file1\n process file2\n sed -i -e \"1000d\" file1\nend\n" }, { "answer_id": 339551, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": false, "text": "n n" }, { "answer_id": 339941, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 11, "selected": true, "text": "tail -n +2 \"$FILE\"\n -n x x tail -n 5 + tail x-1 tail -n +1 tail -n +2 tail sed tail -n +2 sed tail sed # THIS WILL GIVE YOU AN EMPTY FILE!\ntail -n +2 \"$FILE\" > \"$FILE\"\n > tail $FILE tail tail $FILE tail $FILE tail -n +2 \"$FILE\" > \"$FILE.tmp\" && mv \"$FILE.tmp\" \"$FILE\"\n &&" }, { "answer_id": 611242, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "man csplit\ncsplit -k file 1 '{1}'\n" }, { "answer_id": 1732943, "author": "Tim", "author_id": 210862, "author_profile": "https://Stackoverflow.com/users/210862", "pm_score": 0, "selected": false, "text": "if [[ -f $tmpf ]] ; then\n rm -f $tmpf\nfi\ncat $srcf |\n while read line ; do\n # process line\n echo \"$line\" >> $tmpf\n done\n" }, { "answer_id": 14903762, "author": "alexis", "author_id": 699305, "author_profile": "https://Stackoverflow.com/users/699305", "pm_score": 4, "selected": false, "text": "-i perl -ni -e 'print unless $. == 1' filename.txt\n" }, { "answer_id": 14952078, "author": "Nasri Najib", "author_id": 1631784, "author_profile": "https://Stackoverflow.com/users/1631784", "pm_score": 6, "selected": false, "text": "sed '1d' test.dat > tmp.dat \n" }, { "answer_id": 27099557, "author": "amit", "author_id": 2421841, "author_profile": "https://Stackoverflow.com/users/2421841", "pm_score": 8, "selected": false, "text": "sed -i '1d' filename\n" }, { "answer_id": 38797156, "author": "agc", "author_id": 6136214, "author_profile": "https://Stackoverflow.com/users/6136214", "pm_score": 4, "selected": false, "text": "sponge tail -n +2 \"$FILE\" | sponge \"$FILE\"\n" }, { "answer_id": 39764272, "author": "serup", "author_id": 3990012, "author_profile": "https://Stackoverflow.com/users/3990012", "pm_score": 3, "selected": false, "text": "cat textfile.txt | tail -n +2\n" }, { "answer_id": 46792629, "author": "Hongbo Liu", "author_id": 1969532, "author_profile": "https://Stackoverflow.com/users/1969532", "pm_score": 3, "selected": false, "text": "vim -u NONE +'1d' +'wq!' /tmp/test.txt\n" }, { "answer_id": 50357409, "author": "Mark Reed", "author_id": 797049, "author_profile": "https://Stackoverflow.com/users/797049", "pm_score": 4, "selected": false, "text": "ed sed ed \"$FILE\" <<<$'1d\\nwq\\n'\n ed ex vi ed ed <<<$'1d\\nwq\\n' <<< $' ' ed 1d wq" }, { "answer_id": 53433208, "author": "Ingo Baab", "author_id": 7977222, "author_profile": "https://Stackoverflow.com/users/7977222", "pm_score": 4, "selected": false, "text": "cat filename | sed 1d > filename_without_first_line\n -i sed -i 1d <filename>\n" }, { "answer_id": 60607633, "author": "egors", "author_id": 3299257, "author_profile": "https://Stackoverflow.com/users/3299257", "pm_score": 2, "selected": false, "text": "echo \"$(tail -n +2 \"$FILE\")\" > \"$FILE\"\n tail echo" }, { "answer_id": 69867556, "author": "Murilo Perrone", "author_id": 7626061, "author_profile": "https://Stackoverflow.com/users/7626061", "pm_score": 0, "selected": false, "text": "line=$(head -n1 list.txt && echo \"$(tail -n +2 list.txt)\" > list.txt) ~> printf \"Line #%2d\\n\" {1..3} > list.txt\n~> cat list.txt\nLine # 1\nLine # 2\nLine # 3\n~> line=$(head -n1 list.txt && echo \"$(tail -n +2 list.txt)\" > list.txt)\n~> echo $line\nLine # 1\n~> cat list.txt\nLine # 2\nLine # 3\n" }, { "answer_id": 72362398, "author": "zabop", "author_id": 8565438, "author_profile": "https://Stackoverflow.com/users/8565438", "pm_score": 1, "selected": false, "text": "tail +2 path/to/your/file\n -n" }, { "answer_id": 73184977, "author": "aidanmelen", "author_id": 3894599, "author_profile": "https://Stackoverflow.com/users/3894599", "pm_score": 1, "selected": false, "text": "sed # create multi line txt file\necho \"\"\"1. first\n2. second\n3. third\"\"\" > file.txt\n $ sed '1d' file.txt \n2. second\n3. third\n\n$ sed '2d' file.txt \n1. first\n3. third\n\n$ sed '3d' file.txt \n1. first\n2. second\n\n# delete multi lines\n$ sed '1,2d' file.txt \n3. third\n\n# delete the last line\nsed '$d' file.txt \n1. first\n2. second\n -i $ cat file.txt \n1. first\n2. second\n3. third\n\n$ sed -i '1d' file.txt\n\n$cat file.txt \n2. second\n3. third\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
339,496
<p>I've been trying to deal with some delimited text files that have non standard delimiters (not comma/quote or tab delimited). The delimiters are random ASCII characters that don't show up often between the delimiters. After searching around, I've seem to have only found no solutions in .NET will suit my needs and the custom libraries that people have written for this seem to have some flaws when it comes to gigantic input (4GB file with some field values having very easily several million characters). </p> <p>While this seems to be a bit extreme, it is actually a standard in the Electronic Document Discovery (EDD) industry for some review software to have field values that contain the full contents of a document. For reference, I've previously done this in python using the csv module with no problems.</p> <p>Here's an example input:</p> <pre><code>Field delimiter = quote character = þ þFieldName1þþFieldName2þþFieldName3þþFieldName4þ þValue1þþValue2þþValue3þþSomeVery,Very,Very,Large value(5MB or so)þ ...etc... </code></pre> <p>Edit: So I went ahead and created a delimited file parser from scratch. I'm kind of weary using this solution as it may be prone to bugs. It also doesn't feel "elegant" or correct to have to write my own parser for a task like this. I also have a feeling that I probably didn't have to write a parser from scratch for this anyway. </p>
[ { "answer_id": 339505, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 4, "selected": true, "text": "public IEnumerable<string[]> CreateEnumerable(StreamReader input)\n{\n string line;\n while ((line = input.ReadLine()) != null)\n {\n yield return line.Split('þ');\n }\n}\n using (StreamReader sr = new StreamReader(\"c:\\\\test.file\"))\n{\n var qry = from l in CreateEnumerable(sr).Skip(1)\n where l[3].Contains(\"something\")\n select new { Field1 = l[0], Field2 = l[1] };\n foreach (var item in qry)\n {\n Console.WriteLine(item.Field1 + \" , \" + item.Field2);\n }\n}\nConsole.ReadLine();\n" }, { "answer_id": 1497730, "author": "Christian Hayter", "author_id": 115413, "author_profile": "https://Stackoverflow.com/users/115413", "pm_score": 0, "selected": false, "text": "FileStream using(var reader = new EddReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)) {\n // Read a small field\n string smallField = reader.ReadFieldAsText();\n // Read a large field\n Stream largeField = reader.ReadFieldAsStream();\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469014/" ]
339,508
<p>reference, OpenCv\samples\c\lkdemo.c </p> <p>Anybody know what does the following snippet of codes does ?</p> <p>Code extracted from lkdemo.c</p> <pre><code> for( i = k = 0; i &lt; count; i++ ) { if( add_remove_pt ) { double dx = pt.x - points[1][i].x; double dy = pt.y - points[1][i].y; if( dx*dx + dy*dy &lt;= 25 ) { add_remove_pt = 0; continue; } } if( !status[i] ) continue; points[1][k++] = points[1][i]; cvCircle( image, cvPointFrom32f(points[1][i]), 3, CV_RGB(0,255,0), -1, 8,0); } count = k; </code></pre> <p>Q1.</p> <p>What does the bold line does ? >> <strong>points[1][k++] = points[1][i];</strong></p> <p>Why k++ ? I am confuse, thinking that next point is overwritten by the current point </p> <p>Q2.</p> <p>As cvCircle id drawn as the frame loops, where is the old points cleared and new point drawn ?</p> <p>I look forward to your inputs.</p> <p>Thanks =)</p>
[ { "answer_id": 339573, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "if( status[i] ) {\n points[1][k++] = points[1][i]; // <---- Q1\n cvCircle( image, cvPointFrom32f(points[1][i]), 3, CV_RGB(0,255,0), -1, 8,0);\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43076/" ]
339,510
<p>I have a html div layered on top of an interactive flash movie, but when the mouse moves over the div, it can't interact with the flash (the view changes as the mouse moves or is clicked). Is there a way to have the flash recieve the mouse movements and clicks but leaving the html visible?</p> <p>I can't modify the flash SWF file.</p> <p><strong>Edit:</strong> To make it clearer, this is an layer of information sitting on top of Google Street View (flash), the trouble is that I can't move the street view around where the layer overlaps.</p>
[ { "answer_id": 339547, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 2, "selected": false, "text": "<object> \n <param name=\"wmode\" value=\"transparent\" /> \n <embed src=\"example.swf\" wmode=\"transparent\"></embed> \n</object> \n <param /> wmode=\"transparent\" theObjects = document.getElementsByTagName(\"object\");\nfor (var i = 0; i < theObjects.length; i++) {\n theObjects[i].outerHTML = theObjects[i].outerHTML;\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43077/" ]
339,515
<p>I'm a developer who builds mainly single page client side web applications where state in maintained on the client-side. Lately some of the applications have become very complex with very rich domain models on the client-side and increasingly complicated UI interactions.</p> <p>As we've gone along we've implemented some very useful design patterns such as Passive View MVC, Observers, bindings, key-value observers (cocoa). I have recently got a lot of inspiration from the work of SproutCore and Cappuccino which are both JavaScript web frameworks inspired by Cocoa.</p> <p>Obviously all of the problems that developers are having now in building complex web applications have been solved by desktop developers many moons ago. As few months ago all I knew about Cocoa was that is was some Apple thing, now it has had a big impact in the way I develop my web applications. </p> <p>I was wondering if anyone who has more experience in building desktop GUI's than I, could point me any other frameworks out there which may also give me inspiration in terms of design patterns and structures to use for my JavaScript web applications?</p> <p>I really don't care what languages or platform these frameworks reside in, as long as they can teach me something about good application design in general.</p>
[ { "answer_id": 339547, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 2, "selected": false, "text": "<object> \n <param name=\"wmode\" value=\"transparent\" /> \n <embed src=\"example.swf\" wmode=\"transparent\"></embed> \n</object> \n <param /> wmode=\"transparent\" theObjects = document.getElementsByTagName(\"object\");\nfor (var i = 0; i < theObjects.length; i++) {\n theObjects[i].outerHTML = theObjects[i].outerHTML;\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37196/" ]
339,531
<p>I'm hearing that some people believe storing info on the server in a session is a bad idea, that its not secure.<br><br> As a result, in a multi-page business process function, the application is writing data to a db, then retrieving the info when its needed. Is there something necessarily unsafe about storing private info in a session?</p>
[ { "answer_id": 340722, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "aerlingus.ie lastminute.com" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13143/" ]
339,537
<p>When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:</p> <pre><code>f = open("myFile.txt", "r") for line in f: line = line[:-1] # do something with line </code></pre> <p>Is there an elegant way or idiom for retrieving text lines without the end-line character?</p>
[ { "answer_id": 339574, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "'\\n' line = line[:-1] def strip_trailing_newlines(file):\n for line in file:\n if line[-1] == '\\n':\n yield line[:-1]\n else:\n yield line\n\nf = open(\"myFile.txt\", \"r\")\nfor line in strip_trailing_newlines(f):\n # do something with line\n" }, { "answer_id": 339579, "author": "Vijay Dev", "author_id": 27474, "author_profile": "https://Stackoverflow.com/users/27474", "pm_score": 4, "selected": false, "text": "L = open(\"myFile.txt\", \"r\").read().splitlines();\nfor line in L: \n process(line) # this 'line' will not have '\\n' character at the end\n" }, { "answer_id": 339842, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 7, "selected": true, "text": "for line in open('myfile.txt'): # opened in text-mode; all EOLs are converted to '\\n'\n line = line.rstrip('\\n')\n process(line)\n" }, { "answer_id": 1118507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "if (not open(1,\"file.txt\")) error \"Could not open 'file.txt' for reading\"\nwhile(not eof(1)) \n line input #1 a$\n print a$\nwend\nclose\n def line_input (file):\n for line in file:\n if line[-1] == '\\n':\n yield line[:-1]\n else:\n yield line\n\nf = open(\"myFile.txt\", \"r\")\nfor line_input(f):\n # do something with line\n" }, { "answer_id": 6978968, "author": "Paweł Prażak", "author_id": 539481, "author_profile": "https://Stackoverflow.com/users/539481", "pm_score": 2, "selected": false, "text": "with open(filename) as data:\n datalines = (line.rstrip('\\r\\n') for line in data)\n for line in datalines:\n ...do something awesome...\n with" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6225/" ]
339,559
<p>I'm following <a href="http://www.stanford.edu/class/cs193p/cgi-bin/index.php" rel="nofollow noreferrer">iPhone dev courses</a> from Stanford Open-University, and I've been blocked for 2 days on <a href="http://cs193p.stanford.edu/downloads/Assignment3.pdf" rel="nofollow noreferrer">assignment3</a>, maybe someone can help me here?</p> <p>The tasks are:</p> <ol> <li>Create a custom UIView subclass that will display your PolygonShape object </li> <li>Give your view class access to the PolygonShape object so that it can retrieve the details of the polygon as needed </li> </ol> <p>The problem is: <strong>how do I give my view class access to the polygon object defined in my controller?</strong></p> <p>Here is my implementations if it can help:</p> <p>CustomView.h:</p> <pre><code>#import "PolygonShape.h" @interface CustomView : UIView { IBOutlet PolygonShape *polygon; } - (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides; @end </code></pre> <p>Controller.h:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import &lt;Foundation/Foundation.h&gt; #import "PolygonShape.h" #import "PolygonView.h" @interface Controller : NSObject { IBOutlet UIButton *decreaseButton; IBOutlet UIButton *increaseButton; IBOutlet UILabel *numberOfSidesLabel; IBOutlet PolygonShape *polygon; IBOutlet PolygonView *polygonView; } - (IBAction)decrease; - (IBAction)increase; - (void)awakeFromNib; - (void)updateInterface; @end </code></pre>
[ { "answer_id": 339590, "author": "Alex", "author_id": 16974, "author_profile": "https://Stackoverflow.com/users/16974", "pm_score": 1, "selected": false, "text": "#import \"PolygonShape.h\"\n\n@interface CustomView : UIView {\n IBOutlet PolygonShape *polygon;\n}\n\n@property (readwrite, assign) PolygonShape *polygon;\n\n- (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides;\n\n@end\n @implementation CustomView\n\n@synthesize polygon;\n\n...\n\n@end\n - (void)awakeFromNib { \n // configure your polygon here \n polygon = [[PolygonShape alloc] initWithNumberOfSides:numberOfSidesLabel.text.integerValue minimumNumberOfSides:3 maximumNumberOfSides:12];\n [polygonView setPolygon:polygon];\n NSLog (@\"My polygon: %@\", [polygon description]);\n} \n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16974/" ]
339,560
<p>I'm working on some upgrades to an internal web analytics system we provide for our clients (in the absence of a preferred vendor or Google Analytics), and I'm working on the following query:</p> <pre><code>select path as EntryPage, count(Path) as [Count] from ( /* Sub-query 1 */ select pv2.path from pageviews pv2 inner join ( /* Sub-query 2 */ select pv1.sessionid, min(pv1.created) as created from pageviews pv1 inner join Sessions s1 on pv1.SessionID = s1.SessionID inner join Visitors v1 on s1.VisitorID = v1.VisitorID where pv1.Domain = isnull(@Domain, pv1.Domain) and v1.Campaign = @Campaign group by pv1.sessionid ) t1 on pv2.sessionid = t1.sessionid and pv2.created = t1.created ) t2 group by Path; </code></pre> <p>I've tested this query with 2 million rows in the PageViews table and it takes about 20 seconds to run. I'm noticing a clustered index scan twice in the execution plan, both times it hits the PageViews table. There is a clustered index on the Created column in that table.</p> <p>The problem is that in both cases it appears to iterate over all 2 million rows, which I believe is the performance bottleneck. Is there anything I can do to prevent this, or am I pretty much maxed out as far as optimization goes?</p> <p>For reference, the purpose of the query is to find the first page view for each session.</p> <p><strong>EDIT:</strong> After much frustration, despite the help received here, I could not make this query work. Therefore, I decided to simply store a reference to the entry page (and now exit page) in the sessions table, which allows me to do the following:</p> <pre><code>select pv.Path, count(*) from PageViews pv inner join Sessions s on pv.SessionID = s.SessionID and pv.PageViewID = s.ExitPage inner join Visitors v on s.VisitorID = v.VisitorID where ( @Domain is null or pv.Domain = @Domain ) and v.Campaign = @Campaign group by pv.Path; </code></pre> <p>This query runs in 3 seconds or less. Now I either have to update the entry/exit page in real time as the page views are recorded (the optimal solution) or run a batch update at some interval. Either way, it solves the problem, but not like I'd intended. </p> <p>Edit Edit: Adding a missing index (after cleaning up from last night) reduced the query to mere milliseconds). Woo hoo!</p>
[ { "answer_id": 339572, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 3, "selected": true, "text": " where pv1.Domain = isnull(@Domain, pv1.Domain) \n" }, { "answer_id": 339589, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "where\n (@Domain is null or pv1.Domain = @Domain) and\n v1.Campaign = @Campaign\n create index idx2 on [PageViews]([SessionID], Domain, Created, Path)\n" }, { "answer_id": 339648, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 2, "selected": false, "text": "SELECT \n sessionid, \n MIN(created) AS created \nFROM \n pageviews pv \nJOIN \n visitors v ON pv.visitorid = v.visitorid \nWHERE \n v.campaign = @Campaign \nGROUP BY \n sessionid \n SELECT \n campaignid, \n sessionid, \n pv.path \nFROM \n pageviews pv \nJOIN \n visitors v ON pv.visitorid = v.visitorid \nWHERE \n v.campaign = @Campaign \n AND NOT EXISTS ( \n SELECT 1 FROM pageviews \n WHERE sessionid = pv.sessionid \n AND created < pv.created \n ) \n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34942/" ]
339,580
<p>I'm looking to log unhandled javascript exceptions. Is there an event that fires when an exception isn't caught? I'm looking to catch the exceptions before they cause javascript errors in the browser, but I'd rather not run my entire application inside of a try/catch. Any help would be appreciated. Thanks!</p> <p>Update: tvanfosson pointed out onerror as a possibility. It is not part of a spec and is only available in IE or Gecko based browsers.</p> <p>For more information - <a href="http://books.google.com/books?id=tKszhx-XkzYC&amp;pg=PA386&amp;lpg=PA386&amp;dq=safari+onerror+javascript&amp;source=web&amp;ots=gQaGbpUnjG&amp;sig=iBCtOQs0aH_EAzSbWlGa9v5flyo#PPA387,M1" rel="noreferrer">http://books.google.com/books?id=tKszhx-XkzYC&amp;pg=PA386&amp;lpg=PA386&amp;dq=safari+onerror+javascript&amp;source=web&amp;ots=gQaGbpUnjG&amp;sig=iBCtOQs0aH_EAzSbWlGa9v5flyo#PPA387,M1</a></p> <p>OnError Support Table - <a href="http://www.quirksmode.org/dom/events/error.html" rel="noreferrer">http://www.quirksmode.org/dom/events/error.html</a></p> <p>Mozilla's documentation - <a href="https://developer.mozilla.org/en/DOM/window.onerror" rel="noreferrer">https://developer.mozilla.org/en/DOM/window.onerror</a></p> <p>WebKit Bug Report - <a href="https://bugs.webkit.org/show_bug.cgi?id=8519" rel="noreferrer">https://bugs.webkit.org/show_bug.cgi?id=8519</a></p>
[ { "answer_id": 13435462, "author": "Dave Dopson", "author_id": 407731, "author_profile": "https://Stackoverflow.com/users/407731", "pm_score": 5, "selected": false, "text": "window.onerror = function (msg, url, line) {\n console.log(\"Caught[via window.onerror]: '\" + msg + \"' from \" + url + \":\" + line);\n return true; // same as preventDefault\n};\n\nwindow.addEventListener('error', function (evt) {\n console.log(\"Caught[via 'error' event]: '\" + evt.message + \"' from \" + evt.filename + \":\" + evt.lineno);\n console.log(evt); // has srcElement / target / etc\n evt.preventDefault();\n});\n\n\nthrow new Error(\"Hewwo world. I crash you!!!\");\n\nthrow new Error(\"Hewwo world. I can only crash you once... :(\");\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41122/" ]
339,582
<p>I'm trying to write a (sh -bourne shell) script that processes lines as they are written to a file. I'm attempting to do this by feeding the output of <code>tail -f</code> into a <code>while read</code> loop. This tactic seems to be proper based on my research in Google as well as <a href="https://stackoverflow.com/questions/157163/how-to-do-something-with-bash-when-a-text-line-appear-to-a-file">this question</a> dealing with a similar issue, but using bash.</p> <p>From what I've read, it seems that I should be able to break out of the loop when the file being followed ceases to exist. It doesn't. In fact, it seems the only way I can break out of this is to kill the process in another session. <code>tail</code> does seem to be working fine otherwise as testing with this:</p> <pre> touch file tail -f file | while read line do echo $line done </pre> <p>Data I append to <code>file</code> in another session appears just file from the loop processing written above.</p> <p>This is on HP-UX version B.11.23.</p> <p>Thanks for any help/insight you can provide!</p>
[ { "answer_id": 339604, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "tail tail --follow=name tail --follow=name test.txt\n" }, { "answer_id": 339695, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 1, "selected": false, "text": " test -f file || break\n tail -f test.file | while read -t 3 line || test -f test.file; do \n some stuff with $line\n done\n" }, { "answer_id": 596950, "author": "rektide", "author_id": 72070, "author_profile": "https://Stackoverflow.com/users/72070", "pm_score": 0, "selected": false, "text": "kill $(ps -o pid,cmd --no-headers --ppid $$ | grep tail | awk '{print $1}')\n" }, { "answer_id": 15042637, "author": "mazq", "author_id": 2102700, "author_profile": "https://Stackoverflow.com/users/2102700", "pm_score": 0, "selected": false, "text": "tail -f file tailpid: while while file tail -f file while # cf. \"The Heirloom Bourne Shell\",\n# http://heirloom.sourceforge.net/sh.html,\n# http://sourceforge.net/projects/heirloom/files/heirloom-sh/ and\n# http://freecode.com/projects/bournesh\n\n/usr/local/bin/bournesh -c '\ntouch file\n(tail -f file & echo \"tailpid: ${!}\" ) | while IFS=\"\" read -r line\ndo\n case \"$line\" in\n tailpid:*) while sleep 5; do \n #echo hello; \n if [ ! -f file ]; then\n IFS=\" \"; set -- ${line}\n kill -HUP \"$2\"\n exit\n fi\n done & \n continue ;;\n esac\n echo \"$line\"\ndone\necho exiting ...\n'\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1588/" ]
339,583
<p>So it's trivial to create a Settings style table on the iPhone. The problem is, they add a great deal of code as your Settings have a gamut of options/styled cells. One section might have a check list, another might have cells with accessory disclosures to drill down further, another might be labels with UITextFields.</p> <p>My question here is, what's the cleanest way to go about creating this table. Do you typically create a subclass of UITableViewController and then subclass UITableViewCell for each different type of cells, and write supporting classes for those cells? Meaning if you have a Settings style table with 4 sections, all different types of cells, you will load 4 nibs into the table and import 4 class files? Programmatically set the frame, views, textfields and tag them for later access?</p> <p>The answer(s) to this is probably subjective, but I'd like to know what you experts consider the most elegant approach to this common problem.</p>
[ { "answer_id": 341183, "author": "jpm", "author_id": 35478, "author_profile": "https://Stackoverflow.com/users/35478", "pm_score": 1, "selected": false, "text": "UITableViewCell" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
339,616
<p>With Php when does an included file get included? Is it during a preprocessing stage or is it during script evaluation?</p> <p>Right now I have several scripts that share the same header and footer code, which do input validation and exception handling. Like this:</p> <pre><code>/* validate input */ ... /* process/do task */ ... /* handle exceptions */ ... </code></pre> <p>So I'd like to do something like this</p> <pre><code>#include "verification.php" /* process/do task */ ... #include "exception_handling.php" </code></pre> <p>So if include happens as a preprocessing step, I can do the #include "exception_handling.php" but if not, then any exception will kill the script before it has a chance to evaluate the include.</p> <p>Thanks</p>
[ { "answer_id": 339629, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 4, "selected": true, "text": "vars.php\n<?php\n\n$color = 'green';\n$fruit = 'apple';\n\n?>\n\ntest.php\n<?php\n\necho \"A $color $fruit\"; // A\n\ninclude 'vars.php';\n\necho \"A $color $fruit\"; // A green apple\n\n?>\n" }, { "answer_id": 339634, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "include (\"exception_handling.php\");\ninclude 'exception_handling.php'; // or this, the parentheses are optional\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
339,620
<p>WPF doesn't provide the ability to have a window that allows resize but doesn't have maximize or minimize buttons. I'd like to able to make such a window so I can have resizable dialog boxes.</p> <p>I'm aware the solution will mean using pinvoke but I'm not sure what to call and how. A search of pinvoke.net didn't turn up any thing that jumped out at me as what I needed, mainly I'm sure because Windows Forms does provide the <code>CanMinimize</code> and <code>CanMaximize</code> properties on its windows.</p> <p>Could someone point me towards or provide code (C# preferred) on how to do this?</p>
[ { "answer_id": 339635, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 8, "selected": true, "text": "internal static class WindowExtensions\n{\n // from winuser.h\n private const int GWL_STYLE = -16,\n WS_MAXIMIZEBOX = 0x10000,\n WS_MINIMIZEBOX = 0x20000;\n\n [DllImport(\"user32.dll\")]\n extern private static int GetWindowLong(IntPtr hwnd, int index);\n\n [DllImport(\"user32.dll\")]\n extern private static int SetWindowLong(IntPtr hwnd, int index, int value);\n\n internal static void HideMinimizeAndMaximizeButtons(this Window window)\n {\n IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(window).Handle;\n var currentStyle = GetWindowLong(hwnd, GWL_STYLE);\n\n SetWindowLong(hwnd, GWL_STYLE, (currentStyle & ~WS_MAXIMIZEBOX & ~WS_MINIMIZEBOX));\n }\n}\n this.SourceInitialized += (x, y) =>\n{\n this.HideMinimizeAndMaximizeButtons();\n};\n" }, { "answer_id": 339668, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 5, "selected": false, "text": "<Window x:Class=\"DataBinding.MyWindow\" ...Title=\"MyWindow\" Height=\"300\" Width=\"300\" \n WindowStyle=\"ToolWindow\" ResizeMode=\"CanResizeWithGrip\">\n" }, { "answer_id": 5955432, "author": "Andrej", "author_id": 747478, "author_profile": "https://Stackoverflow.com/users/747478", "pm_score": 2, "selected": false, "text": "<Window x:Class=\"Example\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Example\"\n StateChanged=\"Window_StateChanged\">\n // Disable maximizing this window\nprivate void Window_StateChanged(object sender, EventArgs e)\n{\n if (this.WindowState == WindowState.Maximized)\n this.WindowState = WindowState.Normal;\n}\n" }, { "answer_id": 7669581, "author": "Musikero31", "author_id": 440310, "author_profile": "https://Stackoverflow.com/users/440310", "pm_score": 7, "selected": false, "text": "ResizeMode=\"NoResize\"" }, { "answer_id": 15678692, "author": "Eldar", "author_id": 295832, "author_profile": "https://Stackoverflow.com/users/295832", "pm_score": 3, "selected": false, "text": "public partial class MyAwesomeWindow : DXWindow\n{\n public MyAwesomeWIndow()\n {\n Loaded += OnLoaded;\n }\n\n private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)\n {\n // hides maximize button \n Button button = (Button)DevExpress.Xpf.Core.Native.LayoutHelper.FindElementByName(this, DXWindow.ButtonParts.PART_Maximize.ToString());\n button.IsHitTestVisible = false;\n button.Opacity = 0;\n\n // hides minimize button\n button = (Button)DevExpress.Xpf.Core.Native.LayoutHelper.FindElementByName(this, DXWindow.ButtonParts.PART_Minimize.ToString());\n button.IsHitTestVisible = false;\n button.Opacity = 0;\n\n // hides close button\n button = (Button)DevExpress.Xpf.Core.Native.LayoutHelper.FindElementByName(this, DXWindow.ButtonParts.PART_CloseButton.ToString());\n button.IsHitTestVisible = false;\n button.Opacity = 0;\n } \n}\n" }, { "answer_id": 52874729, "author": "Olivier Jacot-Descombes", "author_id": 880990, "author_profile": "https://Stackoverflow.com/users/880990", "pm_score": 2, "selected": false, "text": "SourceInitialized private const int GWL_STYLE = -16, WS_MAXIMIZEBOX = 0x10000, WS_MINIMIZEBOX = 0x20000;\n\n[DllImport(\"user32.dll\")]\nextern private static int GetWindowLong(IntPtr hwnd, int index);\n\n[DllImport(\"user32.dll\")]\nextern private static int SetWindowLong(IntPtr hwnd, int index, int value);\n\n/// <summary>\n/// Hides the Minimize and Maximize buttons in a Window. Must be called in the constructor.\n/// </summary>\n/// <param name=\"window\">The Window whose Minimize/Maximize buttons will be hidden.</param>\npublic static void HideMinimizeAndMaximizeButtons(this Window window)\n{\n window.SourceInitialized += (s, e) => {\n IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(window).Handle;\n int currentStyle = GetWindowLong(hwnd, GWL_STYLE);\n\n SetWindowLong(hwnd, GWL_STYLE, currentStyle & ~WS_MAXIMIZEBOX & ~WS_MINIMIZEBOX);\n };\n}\n" }, { "answer_id": 72865113, "author": "Stefan Stander", "author_id": 12391072, "author_profile": "https://Stackoverflow.com/users/12391072", "pm_score": 1, "selected": false, "text": "WindowStyle=\"ToolWindow\"\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
339,625
<p>I was told that decimal is implemented as user defined type and other c# types like int have specific opcodes devoted to them. What's the reasoning behind this?</p>
[ { "answer_id": 339650, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "decimal DateTime TimeSpan Guid float int decimal" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38807/" ]
339,654
<p>When the view property of a UIViewController is accessed, it first checks to see if it's got an existing view, and returns that. If not, it loads its nib or calls -loadView. </p> <p>When a controller receives a -didReceiveMemoryWarning message, the default behavior is to remove that cached view (assuming it's not in use at the time). </p> <p>If I override -didReceiveMemoryWarning, how can I determine whether the view has been cleared? My understanding is that the default implementation checks to see if self.view.superview == nil. If so, it clears the cached view. Of course, it first checks to see if there <em>is</em> a cached view, and if not, it does nothing. However, I, as a subclass, can't call self.view.superview, for if there <em>isn't</em> a view, it'll generate one.</p> <p>So, how do I figure out if _view exists? (I can't just look at _view; I get linking errors when building for the device).</p>
[ { "answer_id": 340224, "author": "Mike Abdullah", "author_id": 28768, "author_profile": "https://Stackoverflow.com/users/28768", "pm_score": 3, "selected": true, "text": "- (void)setView:(UIView *)view\n{\n if (!view)\n {\n // Clean up code here\n }\n\n [super setView:view];\n}\n" }, { "answer_id": 1076425, "author": "Zargony", "author_id": 44014, "author_profile": "https://Stackoverflow.com/users/44014", "pm_score": 6, "selected": false, "text": "isViewLoaded" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6694/" ]
339,663
<p>I'm having a problem getting access to a database which lives on a remote server. </p> <p>I have a ASP.NET 2.0 webpage that is trying to connect to a database.<br> The database is accessed via a virtual folder (which I set up in IIS).<br> The virtual folder points at a remote share which contains the database. </p> <p>The virtual folder (in the web apps root directory) is pointing at a share on a remote server via a UNC path: </p> <pre><code>\\databaseServerName\databaseFolder$\ </code></pre> <p>The virtual folder has 'read' and 'browse' permissions set to 'true'. </p> <p>I store the connection string in the 'appSettings' section of the web.config: </p> <pre><code>&lt;add key="conStrVirtual" value="Provider=Microsoft.Jet.OleDb.4.0;Data Source=http://webAppServerName/virtualFolderName/databaseName.MDB;Jet OLEDB:Database Password=dumbPassword;"/&gt; </code></pre> <p>The connection object is declard on my .aspx page: </p> <pre><code>Dim objConnVirtual As New OleDbConnection(ConfigurationManager.AppSettings("conStrVirtual")) </code></pre> <p>Here is the code that tries to use the connection object: </p> <pre><code>Public Sub Test() If objConnVirtual.State &lt;&gt; ConnectionState.Open Then objConnVirtual.Open() End If Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM TableName", objConnVirtual) objDR = cmd.ExecuteReader() If objDR.Read() Then response.write("Shazaam! Data shows up here") End If objDR.Close() objConnVirtual.Close() End Sub </code></pre> <p>When I run the above code I get the following error (on this line of the code 'objConnVirtual.Open()':<br> <strong>Exception Details: System.Data.OleDb.OleDbException: Not a valid file name.</strong></p> <p>I have checked the database name and it is correct (even copy/pasted it to make sure)</p> <p>If I put the 'Data Source' section of the connection string into the address bar of my browser I can successfully see the contents of the share on the remote server.</p> <p>Not sure if this is a problem with permissions or with the code.<br> I have googled the crap out of this but have not been able to find a solution.</p> <p>Any help is much appreciated.</p>
[ { "answer_id": 339716, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 0, "selected": false, "text": "<add key=\"conStrVirtual\" value=\"Provider=Microsoft.Jet.OleDb.4.0;Data Source=\\\\databaseServerName\\databaseFolder$\\databaseName.MDB;Jet OLEDB:Database Password=dumbPassword;\"/>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242/" ]
339,699
<p>I read about Java's type erasure <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html" rel="noreferrer">on Oracle's website</a>.</p> <p><strong>When does type erasure occur?</strong> At compile time or runtime? When the class is loaded? When the class is instantiated?</p> <p>A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?</p> <p>Consider the following example: Say class <code>A</code> has a method, <code>empty(Box&lt;?&nbsp;extends&nbsp;Number&gt;&nbsp;b)</code>. We compile <code>A.java</code> and get the class file <code>A.class</code>.</p> <pre><code>public class A { public static void empty(Box&lt;? extends Number&gt; b) {} } </code></pre> <pre><code>public class Box&lt;T&gt; {} </code></pre> <p>Now we create another class <code>B</code> which invokes the method <code>empty</code> with a non-parameterized argument (raw type): <code>empty(new Box())</code>. If we compile <code>B.java</code> with <code>A.class</code> in the classpath, javac is smart enough to raise a warning. So <code>A.class</code> <em>has</em> some type information stored in it.</p> <pre><code>public class B { public static void invoke() { // java: unchecked method invocation: // method empty in class A is applied to given types // required: Box&lt;? extends java.lang.Number&gt; // found: Box // java: unchecked conversion // required: Box&lt;? extends java.lang.Number&gt; // found: Box A.empty(new Box()); } } </code></pre> <p>My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen? </p>
[ { "answer_id": 339702, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": false, "text": "loophole() ArrayList" }, { "answer_id": 339708, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "List<String> list = new ArrayList<String>();\nlist.add(\"Hi\");\nString x = list.get(0);\n List list = new ArrayList();\nlist.add(\"Hi\");\nString x = (String) list.get(0);\n T=String List<T> List<String> T=String" }, { "answer_id": 339720, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "Box<String> b = new Box<String>();\nString x = b.getDefault();\n Box b = new Box();\nString x = (String) b.getDefault();\n" }, { "answer_id": 339746, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "Box<String> empty(Box<T extends Number>) getGenericParameterTypes getGenericReturnType getGenericType new Box<Integer>() Integer Box" }, { "answer_id": 40043558, "author": "porfirion", "author_id": 1349649, "author_profile": "https://Stackoverflow.com/users/1349649", "pm_score": 2, "selected": false, "text": "public static void printSuperclasses(Class clazz) {\n Type superClass = clazz.getGenericSuperclass();\n\n Log.d(\"Reflection\", \"this class: \" + (clazz == null ? \"null\" : clazz.getName()));\n Log.d(\"Reflection\", \"superClass: \" + (superClass == null ? \"null\" : superClass.toString()));\n\n while (superClass != null && clazz != null) {\n clazz = clazz.getSuperclass();\n superClass = clazz.getGenericSuperclass();\n\n Log.d(\"Reflection\", \"this class: \" + (clazz == null ? \"null\" : clazz.getName()));\n Log.d(\"Reflection\", \"superClass: \" + (superClass == null ? \"null\" : superClass.toString()));\n }\n}\n D/Reflection: this class: com.example.App.UsersList\nD/Reflection: superClass: com.example.App.SortedListWrapper<com.example.App.Models.User>\n\nD/Reflection: this class: com.example.App.SortedListWrapper\nD/Reflection: superClass: android.support.v7.util.SortedList$Callback<T>\n\nD/Reflection: this class: android.support.v7.util.SortedList$Callback\nD/Reflection: superClass: class java.lang.Object\n\nD/Reflection: this class: java.lang.Object\nD/Reflection: superClass: null\n D/Reflection: this class: com.example.App.UsersList\nD/Reflection: superClass: class com.example.App.SortedListWrapper\n\nD/Reflection: this class: com.example.App.SortedListWrapper\nD/Reflection: superClass: class android.support.v7.g.e\n\nD/Reflection: this class: android.support.v7.g.e\nD/Reflection: superClass: class java.lang.Object\n\nD/Reflection: this class: java.lang.Object\nD/Reflection: superClass: null\n" }, { "answer_id": 51613817, "author": "iconfly", "author_id": 3576723, "author_profile": "https://Stackoverflow.com/users/3576723", "pm_score": 3, "selected": false, "text": "ArrayList<T>\n{\n T[] elems;\n ...//methods\n}\n ArrayList<Integer>\n{\n Integer[] elems;\n}\n ArrayList<Integer> ArrayList\n{\n Object[] elems;\n}\n ArrayList<T extends Object> ArrayList<T> List<String> l= List.<String>of(\"h\",\"s\");\nList lRaw=l\nl.add(new Object())\nString s=l.get(2) //Cast Exception\n void function(ArrayList<Integer> list){}\nvoid function(ArrayList<Float> list){}\nvoid function(ArrayList<String> list){}\n void function(ArrayList list)\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,706
<p>DocumentsController#common_query can handle multiple different request styles.</p> <p>i.e. all docs in batch 4 or all docs tagged "happy"</p> <p>I want a single route to make em pretty, so:</p> <p>/documents/common_query?batch=4</p> <p>/documents/common_query?tag=happy</p> <p>become:</p> <p>/documents/batch/4</p> <p>/documents/tag/happy</p> <p>So the end result is that #common_query is called but part of the url was used as the param name and part as it's value.</p>
[ { "answer_id": 339869, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 1, "selected": true, "text": "ActionController::Routing::Routes.draw do |map|\n map.connect \"documents/:type/:id\", :controller => \"documents_controller\", \n :action => \"common_query\"\nend\n params[:type] \"batch\" \"tag\" params[:id] \"4\" \"happy\" DocumentsController \"documents/*/*\" map.with_options(:controller => \"documents_controller\", \n :action => \"common_query\") do |c|\n c.connect \"documents/batch/:page\", :type => \"batch\"\n c.connect \"documents/tag/:tag\", :type => \"tag\"\nend\n" }, { "answer_id": 340255, "author": "Alderete", "author_id": 11062, "author_profile": "https://Stackoverflow.com/users/11062", "pm_score": 1, "selected": false, "text": "map.connect 'documents/*specs', :controller => \"documents_controller\", :action => \"common_query\"\n @items = Item.find(:all, :conditions => Hash[params[:specs]])\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37378/" ]
339,709
<p>I need to create an object which exposes an <code>IDictionary&lt;K,V&gt;</code> interface, but I don't want to fill in the entire interface implemntation.</p> <p>It would be nice to have the equivalent of Java's AbstractDictionary, which leaves you very little to impelment a complete dictionary (HashMap, in Java):</p> <ul> <li>If you don't need to iterate the collection, you have a single method to implement (TryGetValue)</li> <li>If you want it to be writeable, you implement another entry (Add).</li> </ul>
[ { "answer_id": 339770, "author": "Sergiu Damian", "author_id": 41345, "author_profile": "https://Stackoverflow.com/users/41345", "pm_score": 2, "selected": false, "text": "System.Collections.Generic IDictionary<K,V> Dictionary<TKey, TValue> SortedDictionary<TKey, TValue> SortedList<TKey, TValue>" }, { "answer_id": 339824, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "Dictionay<integer, Order> Orders() {get;}\nCustomerOrders Orders() {get;}\n" }, { "answer_id": 339835, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 2, "selected": false, "text": "DictionaryBase" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19871/" ]
339,710
<p>In my LOB apps I usually wind up with containers that contain a bunch of different textblocks and textboxes for users to enter data. Normally I need to apply a certain margin or vertical/horizontal alignment to each control.</p> <p>Let's say I have Grid on my form that looks like this (a lot of markup was eliminated for brevity):</p> <pre><code>&lt;Grid&gt; &lt;Grid.ColumnDefinitions.../&gt; &lt;Grid.RowDefinitions.../&gt; &lt;TextBlock Text="MyLabel" /&gt; &lt;TextBox Text={Binding ...}/&gt; . ' &lt;!-- Repated a bunch more times along with all of the Grid.Row, Grid.Column definitions --&gt; &lt;/Grid&gt; </code></pre> <p>Now let's say I need every single item contained in my grid to have Margin="3,1" VerticalContentAlignment="Left" VerticalAlignment="Center". There are several ways to achieve this:</p> <ol> <li>Set the properties directly on each control - BAD!! Does not allow for skinning or centralizing styles.</li> <li>Create a Style with an x:Key="MyStyleName" and apply the style to each control. Better...Makes centralizing styles and skinning more manageable but still requires a ton of markup, and can become unwieldy.</li> <li>Create a global style (i.e. don't specify an x:Key and set the TargetType={x:Type TextBox/TextBlock} - BAD!! The problem with this is that it affects ALL controls in the app that don't explicity override this style. This can be bad for things like menus, grids, and other controls that use textblocks and textboxes.</li> <li>Create a style that targets the Grid and explicitely sets the dependecy propety values like <code>&lt;Setter Property="Frameworkelement.Margin" Value="3,1" /&gt;</code> Not bad...it correctly applies the style to every element in it's content, but also applies it directly to the Grid itself...not exactly what I want.</li> </ol> <p>So what approach do you take and why? What works the best?</p>
[ { "answer_id": 341236, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "Resources MergedDictionary Styles.xaml <ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Style x:Key=\"{x:Type ...}\"> ... </Style>\n</ResourceDictionary>\n <Grid>\n <Grid.ColumnDefinitions.../>\n <Grid.RowDefinitions.../>\n\n <Grid.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"Styles.xaml\" />\n </ResourceDictionary.MergedDictionaries>\n\n <!-- other resources here -->\n\n </ResourceDictionary>\n </Grid.Resources>\n\n ...\n</Grid>\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
339,714
<p>So I am trying to accomplish something like this:</p> <pre><code>SELECT * FROM table WHERE status_id IN (1,3,4); </code></pre> <p>using Zend_Db_Select... can't find how to do it :( Is it at all possible?</p>
[ { "answer_id": 339718, "author": "xelurg", "author_id": 35520, "author_profile": "https://Stackoverflow.com/users/35520", "pm_score": 3, "selected": false, "text": "$select->where('status_id IN(1,3,4)');\n" }, { "answer_id": 362610, "author": "Martin Rázus", "author_id": 39014, "author_profile": "https://Stackoverflow.com/users/39014", "pm_score": 8, "selected": true, "text": "$data = array(1,3,4);\n$select->where('status_id IN(?)', $data);\n" }, { "answer_id": 14122561, "author": "Manoj Bhambere", "author_id": 1942937, "author_profile": "https://Stackoverflow.com/users/1942937", "pm_score": 1, "selected": false, "text": "$completionNo = implode(\",\",$data);\n\n$db = Zend_Db_Table_Abstract::getDefaultAdapter();\n$select = $db->select()->from(array(\"p\"=>PREFIX . \"property_master\"),array('id','completion_no','total_carpet_area'))->where(\"p.completion_no IN (?)\", $completionNo);\n" }, { "answer_id": 26073340, "author": "klodoma", "author_id": 1346203, "author_profile": "https://Stackoverflow.com/users/1346203", "pm_score": 4, "selected": false, "text": "$data = array(1,3,4);\n$select->where('status_id IN(?)', $data);\n $data = array(1,3,4);\n$select->where(array('status_id' => $data));\n WHERE `status_id` IN ('1', '3', '4')\n" }, { "answer_id": 42324613, "author": "Malay M", "author_id": 4502517, "author_profile": "https://Stackoverflow.com/users/4502517", "pm_score": 2, "selected": false, "text": "Zend\\Db\\Sql\\Predicate\\In Zend\\Db\\Sql\\Where $this->status_ids = array(1,3,4);\n\n// select attributes from db by where in \n$result = $this->select(function (Select $select) {\n $predicate = new In();\n $select->where(\n $predicate->setValueSet($this->status_ids)\n ->setIdentifier('status_id')\n );\n})->toArray();\n" }, { "answer_id": 49611777, "author": "vidur punj", "author_id": 1578898, "author_profile": "https://Stackoverflow.com/users/1578898", "pm_score": 0, "selected": false, "text": "This solution works well with zf2 \n $ids = array('1', '2', '3', '4', '5', '6', '7', '8');\n $select->where(array(\"app_post_id\"=> $ids));\n $ids = array('1', '2', '3', '4', '5', '6', '7', '8');\n $sql = new Sql($this->adapter);\n $select = $sql->select();\n $select->from('app_post_comments');\n $select->where(array(\"app_post_id\"=> $ids));\n\n// echo $select->getSqlString($this->adapter->getPlatform());\n// exit;\n $statement = $sql->prepareStatementForSqlObject($select);\n $result = $statement->execute();\n $resultSet = new ResultSet();\n $resultSet->initialize($result);\n $resultSet->buffer()->toArray();\n echo '<pre>';\n print_r($resultSet);\n exit;\n return $resultSet;\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35520/" ]
339,719
<p>From the haskell report:</p> <blockquote> <p>The quot, rem, div, and mod class methods satisfy these laws if y is non-zero:</p> <pre><code>(x `quot` y)*y + (x `rem` y) == x (x `div` y)*y + (x `mod` y) == x </code></pre> <p><code>quot</code> is integer division truncated toward zero, while the result of <code>div</code> is truncated toward negative infinity.</p> </blockquote> <p>For example:</p> <pre><code>Prelude&gt; (-12) `quot` 5 -2 Prelude&gt; (-12) `div` 5 -3 </code></pre> <p>What are some examples of where the difference between how the result is truncated matters?</p>
[ { "answer_id": 339760, "author": "namin", "author_id": 34596, "author_profile": "https://Stackoverflow.com/users/34596", "pm_score": 3, "selected": false, "text": "let buggyOdd x = x `rem` 2 == 1\nbuggyOdd 1 // True\nbuggyOdd (-1) // False (wrong!)\n\nlet odd x = x `mod` 2 == 1\nodd 1 // True\nodd (-1) // True\n let odd x = x `rem` 2 /= 0\nodd 1 // True\nodd (-1) // True\n y > 0 x mod y >= 0 x rem y" }, { "answer_id": 339823, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 6, "selected": true, "text": "(-11)/5 = -2\n(-11)%5 = -1\n5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.\n quot rem div mod (-11)/5 = -3\n(-11)%5 = 4\n5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.\n div mod" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
339,722
<p>how to get GIF Transparency color in vc++ 6.0 and vc++ 2005 ?</p>
[ { "answer_id": 22986670, "author": "dexterous", "author_id": 2735434, "author_profile": "https://Stackoverflow.com/users/2735434", "pm_score": 0, "selected": false, "text": "void Display(FrameData *FrameInfo)\n{\n\n /*short int ImageStartX = 0;\n short int ImageStartY = 0; */\n unsigned int ImageStartX = 0;\n unsigned int ImageStartY = 0;\n int Index = 0;\n\n printf(\"\\r\\n INFO: Display Called.\\r\\n\");\n\n while(1)\n {\n\n Index = 0;\n ImageStartX = (FrameInfo->frameScreenInfo.LeftPosition);\n ImageStartY = (FrameInfo->frameScreenInfo.TopPosition);\n\n\n while(ImageStartY < ((FrameInfo->frameScreenInfo.ImageHeight)+(FrameInfo->frameScreenInfo.TopPosition)))\n {\n\n while(ImageStartX < ((FrameInfo->frameScreenInfo.ImageWidth)+(FrameInfo->frameScreenInfo.LeftPosition)))\n {\n if(FrameInfo->frame[Index] != FrameInfo->transperencyindex)\n {\n #ifndef __DISPLAY_DISABLE\n SetPixel(local_display_mem,ImageStartX,ImageStartY,((FrameInfo->CMAP)+(FrameInfo->frame[Index]))->Red,((FrameInfo->CMAP)+(FrameInfo->frame[Index]))->Green,((FrameInfo->CMAP)+(FrameInfo->frame[Index]))->Blue);\n #endif\n\n #ifdef DEBUG\n count++;\n #endif\n\n }\n\n\n Index++;\n ImageStartX++;\n }\n\n\n ImageStartY++;\n\n\n ImageStartX=(FrameInfo->frameScreenInfo.LeftPosition);\n\n\n }\n\n #ifdef DEBUG\n printf(\"INFO:..Dumping Framebuffer\\r\\n\");\n printf(\"Pixel hit=%d\\r\\n\",count);\n count = 0;\n printf(\"the Frameinfo.leftposition=%d FrameInfo->frameScreenInfo.topposition=%d\\r\\n\",FrameInfo->frameScreenInfo.LeftPosition,FrameInfo->frameScreenInfo.TopPosition);\n printf(\"the Frameinfo.ImageWidth=%d FrameInfo->frameScreenInfo.ImageHeight=%d\\r\\n\",FrameInfo->frameScreenInfo.ImageWidth,FrameInfo->frameScreenInfo.ImageHeight);\n #endif\n\n\n #ifndef __DISPLAY_DISABLE\n memcpy(fbp,local_display_mem,screensize);\n #endif\n\n /** Tune this multiplication to meet the right output on the display **/\n usleep((FrameInfo->InterFrameDelay)*10000);\n\n if( FrameInfo->DisposalMethod == 2)\n {\n printf(\"set the Background\\r\\n\");\n #ifndef __DISPLAY_DISABLE\n SetBackground(FrameInfo);\n #endif\n }\n FrameInfo = FrameInfo->Next;\n\n }\n\n\n}\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
339,727
<p>We've got a situation where someone messed up a Commit to our SVN server. A lot of files were deleted, etc. </p> <p><strong>Question:</strong> What is the technique for making the previous (to the bad Commit) revision the HEAD revision? I've seen discussion here on SO for doing this for 1 file, but we'd like to make it like that last commit never happened. Any ideas?</p> <p>All of these answers seem to be correct. I marked abatishchev's answer as the correct answer simply because I'm using Tortoise SVN and it's the method I actually used.</p>
[ { "answer_id": 339733, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "svnadmin dump svnadmin load" }, { "answer_id": 339742, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "--revision 303:302 --change -303 obliterate svndumpfilter" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689/" ]
339,745
<p>I am currently in the process of rewriting an application whereby teachers can plan curriculum online.</p> <p>The application guides teachers through a process of creating a unit of work for their students. The tool is currently used in three states but we have plans to get much bigger than that.</p> <p>One of the major draw cards of the application is that all of the student outcomes are preloaded into the system. This allows teachers to search or browse through and select which outcomes are going to be met in each unit of work.</p> <p>When I originally designed the system I made the assumption that all student outcomes followed a similar Hierarchy. That is, there are named nested containers and then outcomes.</p> <p>The original set of outcomes that I entered was three tiered. As such my database has the following structure:</p> <p>=========================</p> <p><em>Tables in bold</em></p> <p><strong>h1</strong></p> <p>id, Name</p> <p><strong>h2</strong></p> <p>id, parent___id (h1_id), Name</p> <p><strong>h3</strong></p> <p>id, parent___id (h2_id), Name</p> <p><strong>outcome</strong></p> <p>id, parent___id (h3_id), Name</p> <p>=========================</p> <p>Other than the obvious inability to add n/ levels of hierarchy this method also made it difficult to display a list of all of the standards without recursively querying the database.</p> <p>Once the student outcomes (and their parent categories) have been added there is very little reason for them to be modified in any way. The primary requirement is that they are easy and efficient to read.</p> <p>So far all of the student outcomes from different schools / states / countries have roughly followed my assumption. This may not always be the case.</p> <p>All existing data must of course be transferred across from the current database.</p> <p>Given the above, what is the best way for me to store all the different sets of student outcomes? Some of the ideas I have had are listed below.</p> <ul> <li><p>Continue using 4 tables in the database, when selecting either use recusion or lots of joins</p></li> <li><p>Use nested sets</p></li> <li><p>XML (Either a global XML file for all of the different sets or an XML file for each)</p></li> </ul>
[ { "answer_id": 1675311, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "A\n B\n C\n D\n E\n item | parent | path\n----------------------------\nA | NULL | A\nB | A | A--B\nC | A | A--C\nD | C | A--C--D\nE | A | A--E\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43116/" ]
339,763
<p>I want to do preliminary check if entered string looks like <a href="http://en.wikipedia.org/wiki/Vehicle_identification_number" rel="noreferrer">Vehicle Identification Number (VIN)</a>. I know what it consists of 17 letters and digits, but letters I, O and Q are not allowed inside VIN, so I use this regular expression:</p> <pre><code>^[0-9A-Z-[IOQ]]{17}$ </code></pre> <p>Now if I check a string like 1G1FP22PXS2100001 with RegularExpressionValidator it fails, but CustomValidator with this OnServerValidate event handler</p> <pre><code>Regex r = new Regex("^[0-9A-Z-[IOQ]]{17}$"); args.IsValid = r.IsMatch(TextBox1.Text); </code></pre> <p>works well. </p> <p>Experiments show what RegularExpressionValidator doesn't support <a href="http://msdn.microsoft.com/en-us/library/ms994330.aspx" rel="noreferrer">Character Class Subtraction</a>, but Regex class does.</p> <p>Now I am interested why do these two .NET classes use different regex flavors? Is it documented somethere? </p>
[ { "answer_id": 339775, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "^[0-9A-HJ-NPR-Z]{17}$\n EnableClientScript System.Text.RegularExpressions..::.Regex System.Text.RegularExpressions..::.Regex" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
339,776
<p>I want to monitor the modifications in a specified directory, and retrieve the exact change information. So I've decided to use the <a href="http://msdn.microsoft.com/en-us/library/aa365465(VS.85).aspx" rel="nofollow noreferrer">ReadDirectoryChangesW()</a> function. But I want to use it asynchronously, which means I don't want my worker thread to be blocked if there are no changes in the directory.</p> <p>How can I do this?</p>
[ { "answer_id": 339989, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 2, "selected": false, "text": "ReadDirectoryChangesW() CreateIoCompletionPort() GetQueuedCompletionStatus() CreateIoCompletionPort() ReadDirectoryChangesW() OVERLAPPED GetQueuedCompletionStatus()" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26404/" ]
339,792
<p>I'm trying to get a class memeber variable list at run time. I know this probably using typeof and reflections. but can't find an example. Please someone shed light for me.</p> <p>Here is pseudo code example:</p> <pre><code>Class Test01 { public string str01; public string str02; public int myint01; } </code></pre> <p>I want something like this (pseudo code):</p> <pre><code>Test01 tt = new Test01(); foreach(variable v in tt.PublicVariableList) { debug.print v.name; debug.print v.type; } </code></pre> <p>Please help me figure out how to do this in C# VS2005</p> <p>Thanks a lot</p>
[ { "answer_id": 339798, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "tt.GetType().GetFields()" }, { "answer_id": 339801, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "foreach (MemberInfo mi in tt.GetType().GetMembers()) ...\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36674/" ]
339,803
<p>Has anyone seen this before - and can anything be done about it? This link is to a PNG screen shot of a list display in IE - if you look closely, the line height of each element is getting a little bigger for each successive item. The web site look is entirely controlled by CSS.</p> <p><strike>Screen Shot</strike></p> <p>It's not a huge deal, but it sure is weird.</p> <p>Also, note the space between the white line and the box border - that's not there in FF or Chrome, either, only IE.</p>
[ { "answer_id": 339813, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": true, "text": "overflow:hidden" }, { "answer_id": 339870, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 2, "selected": false, "text": "text/html application/xhtml+xml" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8946/" ]
339,829
<p>Is there a built in Javascript function to turn the text string of a month into the numerical equivalent? </p> <p>Ex. I have the name of the month "December" and I want a function to return "12".</p>
[ { "answer_id": 339854, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 1, "selected": false, "text": "function getMonthNumber(monthName) { \n\n // Turn the month name into a parseable date string.\n var dateString = \"1 \" + monthName;\n\n // Parse the date into a numeric value (equivalent to Date.valueOf())\n var dateValue = Date.parse(dateString);\n\n // Construct a new JS date object based on the parsed value.\n var actualDate = new Date(dateValue);\n\n // Return the month. getMonth() returns 0..11, so we need to add 1\n return(actualDate.getMonth() + 1);\n}\n" }, { "answer_id": 339859, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 3, "selected": true, "text": "var month = (new Date(\"December 1, 1970\").getMonth() + 1);\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29297/" ]
339,833
<p>Let say I have a project that I have released under GPL, with the sources available to anyone. Later I find a very similar product, but as closed source, distributed binary-only by someone else.</p> <p>Is there a good way to find out they are using my source code in their product?</p> <p>If the solution is to somehow reverse-engineer the binary, is it possible to somehow automate it?</p> <p>EDIT: Clarification. The bug hunt is one option, but not definitive, especially if the project is a library and the binary has added its own GUI, for example. The situation I'm interested is when its not blatantly obvious that the code is lifted.</p>
[ { "answer_id": 339858, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "stripped" }, { "answer_id": 342545, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 0, "selected": false, "text": "$ nm a.out\n...\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40657/" ]
339,856
<p>I need to use a datetime.strptime on the text which looks like follows.</p> <p>"Some Random text of undetermined length Jan 28, 1986"</p> <p>how do i do this?</p>
[ { "answer_id": 339884, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 3, "selected": true, "text": "time >>> import time\n>>> a=\"Some Random text of undetermined length Jan 28, 1986\"\n>>> datetuple = a.rsplit(\" \",3)[-3:]\n>>> datetuple\n['Jan', '28,', '1986']\n>>> time.strptime(' '.join(datetuple),\"%b %d, %Y\")\ntime.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1)\n>>> \n datetime >>> from datetime import datetime\n>>> datetime.strptime(\" \".join(datetuple), \"%b %d, %Y\")\ndatetime.datetime(1986, 1, 28, 0, 0)\n>>> \n" }, { "answer_id": 339886, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": ">>> from dateutil.parser import parse\n>>> parse(\"Some Random text of undetermined length Jan 28, 1986\", fuzzy=True)\ndatetime.datetime(1986, 1, 28, 0, 0)\n" }, { "answer_id": 339893, "author": "dmazzoni", "author_id": 7193, "author_profile": "https://Stackoverflow.com/users/7193", "pm_score": 2, "selected": false, "text": "import datetime\nimport re\n\npattern = \"((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]+, [0-9]+)\"\ndatestr = re.search(, s).group(0)\nd = datetime.datetime.strptime(datestr, \"%b %d, %Y\")\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
339,861
<p>We need to send email which contains Pound (currency) symbols in ColdFusion. Before sending email, we are dumping the data into a html file for preview. </p> <ol> <li>How to send a email with utf-8 encoding in ColdFusion</li> <li>How to save a file with utf-8 encoding in ColdFusion</li> </ol>
[ { "answer_id": 339865, "author": "Alterlife", "author_id": 36848, "author_profile": "https://Stackoverflow.com/users/36848", "pm_score": 0, "selected": false, "text": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> <head>" }, { "answer_id": 339878, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "<cfmail type=\"text/html; Charset=UTF-8\" ...><!--- body ---></cfmail>\n <cffile action=\"write\" charset=\"UTF-8\" ...>\n <meta http-equiv=\"Content-Type\" content=\"text/html; Charset=UTF-8\">\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
339,880
<p>There are many drawbacks to using <code>void *</code> in C (memory related, type related, efficiency wise ...). In spite of them we use them a lot for the flexibility they provide.</p> <p>List the disadvantages/drawbacks using <code>void *</code> (and preferred solution in C - if possible).</p> <p><strong>EDIT:</strong> please go through the follwoing link: <a href="http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/" rel="nofollow noreferrer">http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/</a></p>
[ { "answer_id": 339896, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "void* void* malloc() unsigned char * void*" }, { "answer_id": 339898, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 5, "selected": true, "text": "sizeof(void) sizeof(void)" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34590/" ]
339,887
<p>I'm developing my application (on Linux) and sadly it sometimes hangs. I can use <code>Ctrl+C</code> to send sigint, but my program is ignoring sigint because it's too far gone. So I have to do the process-killing-dance:</p> <pre><code>Ctrl+Z $ ps aux | grep process_name $ kill -9 pid </code></pre> <p>Is there a way to configure bash to send the kill signal to the current process when I press - say - <code>Ctrl+Shift+C</code>?</p>
[ { "answer_id": 339905, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "Ctrl+Z\n$ ps aux | grep process_name\n$ kill -9 pid\n Ctrl+Z\n$ pkill -9 process_name\n $alias pks=\"pkill -9 !!:0\"\n" }, { "answer_id": 339915, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 3, "selected": false, "text": "$ stty -a\n quit = ^\\\n" }, { "answer_id": 339932, "author": "Hasturkun", "author_id": 20270, "author_profile": "https://Stackoverflow.com/users/20270", "pm_score": 3, "selected": false, "text": "stty -a quit $ kill %%\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11951/" ]
339,902
<p>Suppose you are implementing a publication database and creating migrations to represent different publications. Each publication has a "year" associated with it.</p> <p><code>t.column :year, ???</code></p> <p>Would this year be best represented as an integer, date, or datetime?</p>
[ { "answer_id": 340005, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 3, "selected": false, "text": "Date DateTime Date >> m = YourModel.create(:year => '2008')\n\n>> m.year.to_s\n=> \"2008-01-01\"\n >> m = YourModel.create(:year => '2008')\n\n>> m.year.to_s\n=> \"2008\"\n" }, { "answer_id": 341141, "author": "Josh Delsman", "author_id": 40644, "author_profile": "https://Stackoverflow.com/users/40644", "pm_score": 4, "selected": true, "text": "Date YourModel.date.year # => \"1999\"\n" } ]
2008/12/04
[ "https://Stackoverflow.com/questions/339902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39584/" ]