qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
302,421
<p>I've done quite a bit of searching on this and haven't had much luck finding something cohesive. I'm a relatively new developer and have just started in my first professional development position. I know that I have a great deal to learn even in the realm of the basics. Based on listening to PodCasts, reading blogs, papers etc; I've come to understand that keeping separation of concerns, IOC, Dependency Injection in mind when designing and building software seems to be the right thing to do. I get the concepts at a VERY high level and want to approach what I do with this in mined as much as I can.</p> <p>So, here's the rub. HOW the heck do I design stuff this way? I work on a team that has inherited a web based product that is very tightly coupled, very poorly documented and generally not an easy to maintain bit of sofware. Evryone seems to like the idea of removing some of this couple. They like the idea of developing automated tests (which from what I've read is easier to do with loosely coupled components). Nobody seems to know how to do it. I'm willing to take a stab at it, but I need guidance. Everything I've found always seems to talk about this stuff in a very high level way, or conversely, focuses on just a small piece of the whole. I'd like some guidance on a book, or series of tutorials, or videos, or SOMETHING that takes a somewhat real-world example and shows you how to apply these principles. Ideally, I'd LOVE to see something that says..."Take this order entry app, for example. THIS is how most people put it together today using standard ADO.NET DataSets, blah...blah...blah. NOW! If we apply the IOC principles to make this a loosely coupled project, here's what you do differently. Here's WHY you do it this way, and here's what you have to consider when you try to accomplish this."</p> <p>I know this is a bit long winded, I'm just a bit frustrated that most of the comprehensive trainig material out there that I've found simply doesn't discuss this topic in a way that someone starting out can apply good practices from day one.</p> <p>Thanks all for your time.</p> <p>Steve</p>
[ { "answer_id": 302505, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "public MSSQLDataAccessLayer(ILogger logger) { ... }\n ServiceContainer.Global.RegisterFactory<ILogger, FileLogger>()\n .FactoryScoped()\n .WithParameters(\n new Parameter(\"directory\", @\"C:\\Temp\")\n );\nServiceContainer.Global.RegisterFactory<IDataAccessLayer, MSSQLDataAccessLayer>()\n .FactoryScoped();\n IDataAccessLayer dal = ServiceContainer.Global.Resolve<IDataAccessLayer>();\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26516/" ]
302,423
<p>Whenever I write a stored procedure for selecting data based on string variable (varchar, nvarchar, char) I would have something like:</p> <pre><code>procedure dbo.p_get_user_by_username( @username nvarchar(256) as begin select u.username ,u.email --,etc from sampleUserTable u where u.username = @username end </code></pre> <p>So in other words to match the record I would have</p> <pre><code>u.username = @username </code></pre> <p>But sometimes I come across code that would use <strong><em>LIK</strong>E</em> in place of <strong><em>=</em></strong></p> <pre><code>u.username like(@username) </code></pre> <p>When would you use it? Shouldn't that be used only when you need some wildcard matching?</p> <p><strong>EDIT</strong></p> <p>Thanks for the answers.</p> <p>I think that I need to clarify that what I was really trying to ask was: if there could be a situation when it was preferred to use like in place of "=" for exact string matching. From the answers I could say that there would not be. From my own experience even in situations when I need to ignore e.g case, and leading and ending spaces i would use ltrim, rtrim, lower on both strings and then "=". Thanks again for your input.</p>
[ { "answer_id": 302441, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 2, "selected": false, "text": "u.username" }, { "answer_id": 304048, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "select * from sysobjects where name = 'sysbinobjs '\n-- returns 1 row\nselect * from sysobjects where name like 'sysbinobjs '\n-- returns 0 rows\n declare @s varchar(40) \nset @s = 'escaped[_]_%'\n\nselect 1 where 'escaped[_]_%' like @s \n--Return nothing = BAD \n\nset @s = '_e_s_c_a_p_e_d_[___]___%' \n\nselect 1 where 'escaped[_]_%' like @s escape '_'\n--Returns 1 = GOOD\n select * from sysobjects\nWHERE name = 'sysbinobjs' and name COLLATE Latin1_General_BIN LIKE 'sysbinobjs'\n" }, { "answer_id": 20427828, "author": "Chad Carisch", "author_id": 358661, "author_profile": "https://Stackoverflow.com/users/358661", "pm_score": 1, "selected": false, "text": "= = like sp_updatestats =" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ]
302,435
<p>I'm trying to programmatically set the constructor sting of a COM+ component from a C# application. I found the following sample code online, but it throws an exception:</p> <pre><code> COMAdminCatalogCollection Components; COMAdminCatalogClass Catalog = new COMAdminCatalogClass(); string strConstr; string ApplicationName = "ApplicationName"; // case sensitive string CompName = "MyComponent.ProgID"; COMAdminCatalogCollectionClass Applications = (COMAdminCatalogCollectionClass)Catalog.GetCollection("Applications"); Applications.Populate(); // find the correct application foreach (COMAdminCatalogObjectClass AppObject in Applications) { if (AppObject.Name == ApplicationName) { // find matching component Components = (COMAdminCatalogCollectionClass)(Applications.GetCollection("Components", AppObject.Key)); Components.Populate(); foreach (COMAdminCatalogObjectClass CompObject in Components) { if (CompObject.Name.ToString() == CompName) { CompObject.get_Value("ConstructorString").ToString(); CompObject.get_Value("ConstructionEnabled").ToString(); } } } } </code></pre> <p>When I run this code, I get the following exception on line 6:</p> <blockquote> <p>Unable to cast COM object of type 'System.__ComObject' to class type 'COMAdmin.COMAdminCatalogCollectionClass'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembly registered will be wrapped in the __ComObject type. Instances of this type cannot be cast to any other class; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.</p> </blockquote> <p>Any idea where I'm going wrong? Or is there an easier way to do this?</p>
[ { "answer_id": 302824, "author": "Brian Sullivan", "author_id": 767, "author_profile": "https://Stackoverflow.com/users/767", "pm_score": 3, "selected": true, "text": " Dim Components As COMAdminCatalogCollection\n Dim Catalog As New COMAdminCatalogClass()\n Dim ApplicationName As String = \"ApplicationName\"\n Dim CompName As String = \"MyComponent.ProgID\"\n Dim Applications = Catalog.GetCollection(\"Applications\")\n Applications.Populate()\n For Each AppObject In Applications\n\n If (AppObject.Name = ApplicationName) Then\n\n Components = (Applications.GetCollection(\"Components\", AppObject.Key))\n Components.Populate()\n For Each CompObject In Components\n\n If (CompObject.Name.ToString() = CompName) Then\n CompObject.Value(\"ConstructorString\") = \"Some new value\"\n\n Components.SaveChanges()\n End If\n\n Next\n End If\n Next\n" }, { "answer_id": 24268701, "author": "William Delong", "author_id": 3683935, "author_profile": "https://Stackoverflow.com/users/3683935", "pm_score": 2, "selected": false, "text": "using COMAdmin;\nusing System;\nusing System.Runtime.InteropServices;\nusing System.Management.Automation;\n\nnamespace COMAdminModule\n{\n // Name the cmdlet\n [Cmdlet(\"Set\", \"COMConstructorString\")]\n public class SetCOMConstructorSting : PSCmdlet\n {\n\n // App name Parameter\n private string comAppName;\n\n [Parameter(\n Mandatory = true,\n ValueFromPipelineByPropertyName = true,\n ValueFromPipeline = true,\n Position = 0,\n HelpMessage = \"Name of COM+ Application\"\n )]\n\n [Alias(\"App Name\")]\n\n\n public string COMApp\n {\n get { return comAppName; }\n set { comAppName = value; }\n }\n\n\n // App Component name\n private string componentName;\n\n [Parameter(\n Mandatory = true,\n ValueFromPipelineByPropertyName = true,\n ValueFromPipeline = true,\n Position = 1,\n HelpMessage = \"The name of the Component that will receive a new Constructor string\"\n )]\n\n [Alias(\"Component Name\")]\n\n\n public string ComponentName\n {\n get { return componentName; }\n set { componentName = value; }\n }\n\n\n // Constructor String\n private string constructorString;\n\n [Parameter(\n Mandatory = true,\n ValueFromPipelineByPropertyName = true,\n ValueFromPipeline = true,\n Position = 2,\n HelpMessage = \"The new Constructor string\"\n )]\n\n [Alias(\"Constructor String\")]\n\n\n public string ConstructorString\n {\n get { return constructorString; }\n set { constructorString = value; }\n }\n\n\n // Provides a one-time, preprocessing functionality for the cmdlet\n protected override void BeginProcessing()\n {\n base.BeginProcessing();\n }\n\n // Provides a record-by-record processing functionality for the cmdlet\n protected override void ProcessRecord()\n {\n string working = \"Setting the constructor string \" + constructorString;\n working = \" to the Component \" + componentName;\n working += \" for the COM App \" + comAppName;\n\n WriteObject(working);\n\n setConstructorString(comAppName, componentName, constructorString);\n }\n\n // Provides a one-time, post-processing functionality for the cmdlet\n protected override void EndProcessing()\n {\n base.EndProcessing();\n }\n\n\n\n\n //Add component method\n private void setConstructorString(string comAppName, string componentName, string constructorString)\n {\n ICOMAdminCatalog2 oCatalog = null;\n\n try\n {\n\n //Create the comAdmin object\n oCatalog = (ICOMAdminCatalog2)Activator.CreateInstance(Type.GetTypeFromProgID(\"ComAdmin.COMAdminCatalog\"));\n\n //Get the comApps\n ICatalogCollection comApps = (ICatalogCollection)oCatalog.GetCollection(\"Applications\");\n comApps.Populate();\n\n\n foreach (ICatalogObject app in comApps)\n {\n\n //Find the comApp\n if (app.Name.ToString().Equals(comAppName))\n {\n //Get the Components\n ICatalogCollection components = (ICatalogCollection)comApps.GetCollection(\"Components\", app.Key);\n components.Populate();\n\n\n foreach (ICatalogObject component in components) \n {\n //Find the component\n if (component.Name.ToString().Equals(componentName))\n {\n // Set the constructor string\n component.set_Value(\"ConstructorString\", constructorString);\n\n components.SaveChanges();\n\n break;\n }\n\n }\n\n break; \n }\n\n }\n\n }\n catch (Exception e)\n {\n WriteObject(e.Source);\n throw;\n }\n }\n }\n}\n PS C:\\Windows\\system32> Import-Module \"<dll path>\"\n\nPS C:\\Windows\\system32> Set-COMConstructorString <Application Name> <Component Name> <Constructor String>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
302,452
<p>What's the most efficient way to calculate the last day of the prior quarter?</p> <p>Example: given the date 11/19/2008, I want to return 9/30/2008.</p> <p>Platform is SQL Server </p>
[ { "answer_id": 302525, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 2, "selected": false, "text": "select dateadd(dd,-1,dateadd(qq,datediff(qq,0,'11/19/2008'),0)),\n dateadd(dd,-1,dateadd(qq,datediff(qq,0,'10/19/2008'),0)),\n dateadd(dd,-1,dateadd(qq,datediff(qq,0,'12/19/2008'),0))\n" }, { "answer_id": 302617, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 6, "selected": true, "text": "Select DateAdd(day, -1, dateadd(qq, DateDiff(qq, 0, @Date), 0)) \n Select dateadd(qq, DateDiff(qq, 0, @Date), -1) \n" }, { "answer_id": 3354949, "author": "StrEagle", "author_id": 404754, "author_profile": "https://Stackoverflow.com/users/404754", "pm_score": 4, "selected": false, "text": "SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), -1)\n" }, { "answer_id": 26500704, "author": "akila", "author_id": 4168566, "author_profile": "https://Stackoverflow.com/users/4168566", "pm_score": 3, "selected": false, "text": "SELECT CONVERT(DATE,GETDATE()) [Current Date]\n SELECT CONVERT(DATE, DATEADD(QQ, DATEDIFF(QQ, 0, GETDATE()) ,0)) [Current Quarter 1st Date]\n SELECT CONVERT(DATE,DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) +1, 0))) [Current Quarter Last Date]\n SELECT CONVERT(DATE, DATEADD(QQ, DATEDIFF(QQ, 0, GETDATE()) +1 ,0)) [Next Quarter 1st Date]\n SELECT CONVERT(DATE,DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) +2, 0))) [Next Quarter Last Date]\n" }, { "answer_id": 36578485, "author": "Amiram Pick", "author_id": 6194396, "author_profile": "https://Stackoverflow.com/users/6194396", "pm_score": -1, "selected": false, "text": "select dateadd(day,-1,DATE_TRUNC('qtr', current_date)) from whatever\n select dateadd(qtr,1,dateadd(day,-1,DATE_TRUNC('qtr', current_date))) from whatever\n" }, { "answer_id": 46904589, "author": "ManhNguyen", "author_id": 3000954, "author_profile": "https://Stackoverflow.com/users/3000954", "pm_score": 0, "selected": false, "text": "convert(varchar, dateadd(dd,-1,dateadd(qq,1,DATEADD(qq, DATEDIFF(qq,0,YOUR_DATE), 0))),112)\n SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM (or PM)\n -- Oct 2 2008 11:01AM\nSELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy - 10/02/2008 \nSELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02 \nSELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy\nSELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy\nSELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy\nSELECT convert(varchar, getdate(), 106) -- dd mon yyyy\nSELECT convert(varchar, getdate(), 107) -- mon dd, yyyy\nSELECT convert(varchar, getdate(), 108) -- hh:mm:ss\nSELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)\n -- Oct 2 2008 11:02:44:013AM \nSELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy\nSELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd\nSELECT convert(varchar, getdate(), 112) -- yyyymmdd\nSELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm\n -- 02 Oct 2008 11:02:07:577 \nSELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)\nSELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)\nSELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm\nSELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm\n -- 2008-10-02T10:52:47.513\n-- SQL create different date styles with t-sql string functions\nSELECT replace(convert(varchar, getdate(), 111), '/', ' ') -- yyyy mm dd\nSELECT convert(varchar(7), getdate(), 126) -- yyyy-mm\nSELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12424/" ]
302,459
<p>I see the phrase "programming idiom" thrown around as if it is commonly understood. Yet, in search results and stackoverflow I see everything...</p> <p>From micro:</p> <ul> <li>Incrementing a variable</li> <li>Representing an infinite loop</li> <li>Swapping variable values</li> </ul> <p>To medium:</p> <ul> <li><a href="http://aszt.inf.elte.hu/~gsd/halado_cpp/ch09s03.html" rel="noreferrer">PIMPL</a></li> <li><a href="http://www.hackcraft.net/raii/" rel="noreferrer">RAII</a></li> <li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="noreferrer">Format, comments, style...</a></li> </ul> <p>To macro:</p> <ul> <li><a href="http://pschombe.wordpress.com/2006/05/06/the-next-big-programming-idiom/" rel="noreferrer">Programming paradigm or common library features as idiom</a></li> <li><a href="http://blogs.msdn.com/g/archive/2008/06/07/a-finding-from-an-architecture-review-of-a-product-with-components-that-originated-on-unix.aspx" rel="noreferrer">Process model as idiom</a></li> <li><a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.7793" rel="noreferrer">A collection of idioms equals a new paradigm</a></li> </ul> <p>Is there a single, common definition for "programming idiom"? Since "programming idiom" is used in many scopes:</p> <ul> <li>Micro: syntactic nuance or common syntax</li> <li>Medium: common style and patterns</li> <li>Macro: programming paradigms as idiom</li> </ul> <p>Is it valid to use the phrase in any of these scopes? The answers so far focus on syntactic idioms. Are the others valid as well?</p>
[ { "answer_id": 302494, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": " if(c=GetValue())\n {...}\n c = GetValue();\n if (c != 0)\n {....}\n" }, { "answer_id": 302561, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 7, "selected": true, "text": "for (i=0; i<10; i++)\n for ($i = 1; $i <= 10; $i++)\n foreach ($arr as $value)\n (1..10).each\n array.each\n" }, { "answer_id": 995775, "author": "Zuu", "author_id": 67634, "author_profile": "https://Stackoverflow.com/users/67634", "pm_score": 2, "selected": false, "text": "Iterator foo;\nfoo.reset();\nwhile (foo.next())\n{\n print(foo.value());\n}\n" }, { "answer_id": 50954021, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 0, "selected": false, "text": "while { ... } do {} while do {} while" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7625/" ]
302,460
<p>I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Deque, but I am in Java 1.5.</p> <p>I would like not to have to add another class to my structure but I am wondering if that is possible:</p> <ol> <li><p>Is there any class in the Collections framework (1.5) that does the job?</p></li> <li><p>If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation?</p></li> <li><p>If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start.</p></li> </ol> <p>Thanks a lot.</p> <p>EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?</p>
[ { "answer_id": 302474, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 7, "selected": true, "text": "addFirst addLast removeFirst removeLast" }, { "answer_id": 28787686, "author": "Brett Ryan", "author_id": 140037, "author_profile": "https://Stackoverflow.com/users/140037", "pm_score": 4, "selected": false, "text": "Deque ArrayDeque LinkedList ConcurrentLinkedDeque LinkedBlockingDeque Stack Queue pop() push() peek() LIFO<String> stack = new ArrayDeque<>();\n" }, { "answer_id": 39879163, "author": "Ivo", "author_id": 1082933, "author_profile": "https://Stackoverflow.com/users/1082933", "pm_score": 2, "selected": false, "text": "Deque LinkedList Deque LinkedList Deque<String> deque = new LinkedList<>();\n deque.add(\"first\");\n deque.add(\"last\");\n\n // returns \"last\" without removing it\n System.out.println(deque.peekLast());\n\n // removes and returns \"last\"\n System.out.println(deque.pollLast());\n Deque LinkedList LinkedList LinkedList<String> list = new LinkedList<>();\n list.add(\"first\");\n list.add(\"last\");\n\n // returns \"last\" without removing it\n System.out.println(list.getLast());\n\n // removes and returns \"last\"\n System.out.println(list.removeLast());\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24097/" ]
302,476
<p>C#, .NET 3.5</p> <p>I am trying to get all of the properties of an object that have BOTH a getter and a setter for the instance. The code I <em>thought</em> should work is </p> <pre><code>PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty); </code></pre> <p>However, the results include a property that does not have a setter. To give you a simple idea of my inheritance structure that might be affecting this (though I don't know how):</p> <pre><code>public interface IModel { string Name { get; } } public class BaseModel&lt;TType&gt; : IModel { public virtual string Name { get { return "Foo"; } } public void ReflectionCopyTo(TType target) { PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty); foreach (PropertyInfo info in infos) info.SetValue(target, info.GetValue(this, null), null); } } public class Child : BaseModel&lt;Child&gt; { // I do nothing to override the Name property here } </code></pre> <p>I end up with the following error when working with Name:</p> <pre><code>System.ArgumentException: Property set method not found. </code></pre> <p>EDIT: I would like to know why this does <em>not</em> work, as well as what I should be doing to not get the error.</p>
[ { "answer_id": 302492, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "GetGetMethod GetSetMethod" }, { "answer_id": 302595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "GetProperties BindingFlags * You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.\n* Specify BindingFlags.Public to include public properties in the search.\n* Specify BindingFlags.NonPublic to include non-public properties (that is, private and protected members) in the search.\n* Specify BindingFlags.FlattenHierarchy to include static properties up the hierarchy.\n GetProperty SetProperty" }, { "answer_id": 405739, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 5, "selected": false, "text": "var qry = typeof(Foo).GetProperties(BindingFlags.Instance | BindingFlags.Public)\n .Where(p => p.CanRead && p.CanWrite);\n" }, { "answer_id": 3307463, "author": "Matthieu DUFOURNEAUD-RAVEL", "author_id": 398913, "author_profile": "https://Stackoverflow.com/users/398913", "pm_score": 5, "selected": false, "text": "PropertyInfo.CanRead PropertyInfo.CanWrite" }, { "answer_id": 14763801, "author": "Herman Schoenfeld", "author_id": 1435110, "author_profile": "https://Stackoverflow.com/users/1435110", "pm_score": 0, "selected": false, "text": "public abstract class ObjectWithDefaultValues : object {\n\n public ObjectWithDefaultValues () : this(true){\n }\n\n public ObjectWithDefaultValues (bool setDefaultValues) {\n if (setDefaultValues)\n this.SetDefaultValues(); \n }\n}\n\npublic static class ObjectExtensions {\n\n public static void SetDefaultValues(this object obj) {\n foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField)) {\n foreach (Attribute attr in f.GetCustomAttributes(true)) {\n if (attr is DefaultValueAttribute) {\n var dv = (DefaultValueAttribute)attr;\n f.SetValue(obj, dv.Value);\n }\n }\n }\n\n foreach (var p in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty)) {\n if (p.GetIndexParameters().Length == 0) {\n foreach (Attribute attr in p.GetCustomAttributes(true)) {\n if (attr is DefaultValueAttribute) {\n var dv = (DefaultValueAttribute)attr;\n p.SetValue(obj, dv.Value, null);\n }\n }\n }\n }\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
302,482
<p>I need to display a string which has a white space on a asp.net page.</p> <p>****Here is what I am doing:****</p> <pre><code>cell = New TableCell cell.Text = value (lets assume value is &lt;" test with whitespace "&gt; row.Cells.Add(cell) </code></pre> <p><strong>and it gets rendered as</strong> </p> <pre><code>&lt;tr&gt; &lt;td&gt;" test with whitespace "&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>whitespaces within single quotes are not displayed. </p> <p>I want this value to be displayed as it is on my page.</p>
[ { "answer_id": 302519, "author": "PeterFromCologne", "author_id": 36546, "author_profile": "https://Stackoverflow.com/users/36546", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\ntd {\npadding: 4px;\n}\n</style>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38997/" ]
302,486
<p>I see this from time to time and want to know what it is. I did try google, but its filtering out the characters from the search. I have a few books that don't reference it either. </p> <p>FWIW, I remember in pascal that is was the assignment operator. </p> <p>Can anybody point me to the MSDN or similar page?</p>
[ { "answer_id": 302539, "author": "JeffK", "author_id": 5420, "author_profile": "https://Stackoverflow.com/users/5420", "pm_score": 6, "selected": true, "text": "Public Class Form1\n\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n TestRoutine(Y:=\"TestString\", X:=12)\n End Sub\n\n Private Sub TestRoutine(ByVal X As Long, Optional Y As String = \"\")\n ' Do something with X and Y here... '\n End Sub\n\nEnd Class\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16391/" ]
302,488
<p>In my WCF service, I have methods that are currently public, but I want to hide them from the outside world but be able to use them in my WCF service.</p> <p>Is internal what I'm looking at?</p>
[ { "answer_id": 302539, "author": "JeffK", "author_id": 5420, "author_profile": "https://Stackoverflow.com/users/5420", "pm_score": 6, "selected": true, "text": "Public Class Form1\n\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n TestRoutine(Y:=\"TestString\", X:=12)\n End Sub\n\n Private Sub TestRoutine(ByVal X As Long, Optional Y As String = \"\")\n ' Do something with X and Y here... '\n End Sub\n\nEnd Class\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
302,496
<p>This is a followup to <a href="https://stackoverflow.com/questions/284428/avoiding-property-itis-ie-overuse-of-properties-when-are-they-appropriate">Avoiding @property-itis</a>.</p> <p>UIWebView has the following property declarations:</p> <pre><code>@property(nonatomic,readonly,getter=canGoBack) BOOL canGoBack; @property(nonatomic,readonly,getter=canGoForward) BOOL canGoForward; </code></pre> <p>UIScrollView has these:</p> <pre><code>@property(nonatomic) BOOL canCancelContentTouches; </code></pre> <p>Yet, UIResponder has </p> <pre><code>- (BOOL)isFirstResponder; - (BOOL)canBecomeFirstResponder; - (BOOL)canResignFirstResponder; </code></pre> <p>Is the UIResponder case one where they should have been declared as properties, but, for whatever reason, were not?</p> <p>Or is it a case where declaring them as properties was inappropriate? If inappropriate, why?</p>
[ { "answer_id": 303569, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 0, "selected": false, "text": "@interface canBecomeFirstResponder BOOL firstResponder" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,507
<p>I'm using ActiveState Perl on Windows Server 2003. </p> <p>I want to create a directory on a Windows NTFS partition and then grant a Windows NT security group read access to the folder. Is this possible in Perl? Would I have to use Windows NT commands or is there a Perl module to do it?</p> <p>A small example would be much appreciated!</p>
[ { "answer_id": 302565, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "use Win32::Perms;\n\n# Create a new Security Descriptor and auto import permissions\n# from the directory\n$Dir = new Win32::Perms( 'c:/temp' ) || die;\n\n# One of three ways to remove an ACE\n$Dir->Remove('guest');\n\n# Deny access for all attributes (deny read, deny write, etc)\n$Dir->Deny( 'joel', FULL );\n\n# Set the directory permissions (no need to specify the\n# path since the object was created with it)\n$Dir->Set();\n\n# If you are curious about the contents of the SD\n# dump the contents to STDOUT $Dir->Dump;\n" }, { "answer_id": 302694, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": true, "text": "use Win32::FileSecurity qw(Set MakeMask);\n\nmy $dir = 'c:/newdir';\nmkdir $dir or die $!;\nSet($dir, { 'Power Users' \n => MakeMask( qw( READ GENERIC_READ GENERIC_EXECUTE ) ) });\n Set Get my %permissions;\nWin32::FileSecurity::Get($dir, \\%permissions);\n$permissions{'Power Users'}\n = MakeMask( qw( READ GENERIC_READ GENERIC_EXECUTE ) ) });\nWin32::FileSecurity::Set($dir, \\%permissions);\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38211/" ]
302,515
<p>I was previously getting the next available autonumber used in Access by doing a simple query like so:</p> <pre><code>SELECT RecordNumber, Info FROM myTABLE WHERE 0 = 1 </code></pre> <p>This way I could create a variable to hold the currentRecord and it will use the same autonumber that Access was going to use when I was updating the row</p> <p>Example</p> <pre><code>rs.AddNew currentRecord = rs("RecordNumber") rsInfo = "SomeFormData" &amp; currentRecord rs.Update rs.Close </code></pre> <p>Now this use to work on MS Access, but in SQL Server 2005, I am not getting back the Identity created by the new record. "SomeFormData" is been inserted correctly, the RecordNumber field in SQL is been populated by the new auto number but I don't have the RecordNumber in my variables and I need it to continue filling related forms, that save data to related tables and need to save the currentRecord number.</p> <p><strong>Question</strong>: is there a way to get this unique number back when doing a new insert?</p>
[ { "answer_id": 302573, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 4, "selected": true, "text": "IDENT_CURRENT('tableName') INSERT IDENT_CURRENT('tableName') + IDENT_INCR('tableName') SCOPE_IDENTITY() SCOPE_IDENTITY() IDENT_CURRENT('tableName') IDENT_CURRENT INSERT INSERT IDENT_CURRENT SCOPE_IDENTITY SCOPE_IDENTITY() @@IDENTITY @@IDENTITY SCOPE_IDENTITY()" }, { "answer_id": 59043706, "author": "Chris Catignani", "author_id": 3072350, "author_profile": "https://Stackoverflow.com/users/3072350", "pm_score": 0, "selected": false, "text": "IF object_id('spOrganizationAdd') IS NOT NULL\n DROP PROCEDURE spOrganizationAdd;\nGO\n\nCREATE PROCEDURE dbo.spOrganizationAdd\n @OrganizationName VARCHAR(50),\n @ReturnIdentityValue INT OUTPUT\nAS\nBEGIN\n DECLARE @TempOrganizationIdentity TABLE (TempOrganizationID INT)\n\n INSERT INTO Organization (OrganizationName)\n OUTPUT INSERTED.OrganizationID INTO @TempOrganizationIdentity\n VALUES (@OrganizationName)\n\n SELECT @ReturnIdentityValue = (SElECT TempOrganizationID FROM @TempOrganizationIdentity)\nEND\nGO\n ParameterDirection.Output public static int AddOrganization(Organization oOrganization)\n{\n int iRetVal = 0;\n\n using (SqlConnection conn = Connection.GetConnection())\n {\n using (SqlCommand cmd = new SqlCommand(\"spOrganizationAdd\", conn))\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.AddWithValue(\"@OrganizationName\", oOrganization.OrganizationName);\n cmd.Parameters.Add(\"@ReturnIdentityValue\", SqlDbType.Int).Direction = ParameterDirection.Output;\n\n conn.Open();\n cmd.ExecuteNonQuery();\n iRetVal = Convert.ToInt32(cmd.Parameters[\"@ReturnIdentityValue\"].Value);\n }\n }\n\n return iRetVal;\n}\n public class Organization\n{\n public Organization() { }\n public Organization(int organizationID) { OrganizationID = organizationID; }\n\n public int OrganizationID { get; set; }\n public string OrganizationName { get; set; }\n\n public string Display()\n {\n return OrganizationID.ToString() + \" \" + OrganizationName;\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38678/" ]
302,533
<p>Would it be benefical to add a generic way to add info to a Throwable without creating a new Throwable?</p> <p>I often see code like this:</p> <pre><code>try { foo(); } catch (Exception e) { throw new Exception(e.getMessage() + " extra info=" + blah, e); } </code></pre> <p>Would it be better to instead add <code>Throwable.setProperty(String key, String value)</code> so that the code above becomes the following?</p> <pre><code>try { foo(); } catch(Exception e) { e.setProperty("extra info", blah); throw e; } </code></pre> <p>The extra info could print (one per line) between the message and stack list.</p> <p>Benefits: 1. Would not require creating new <code>Throwable</code>s just to add extra information. 2. Stack traces would not have multiple layers of cause traces (and therefore be easier to read) 3. Reduce cost of creating extra stack traces.</p>
[ { "answer_id": 302555, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 0, "selected": false, "text": "try {\n foo();\n} catch (Exception e) {\n throw new MySpecificException(\"extra info=\" + blah, e);\n}\n" }, { "answer_id": 302557, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "RuntimeException" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
302,542
<p>We need to get all the instances of objects that implement a given interface - can we do that, and if so how?</p>
[ { "answer_id": 302588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public static IEnumerable<T> GetInstancesOfImplementingTypes<T>()\n{\n AppDomain app = AppDomain.CurrentDomain;\n Assembly[] ass = app.GetAssemblies();\n Type[] types;\n Type targetType = typeof(T);\n\n foreach (Assembly a in ass)\n {\n types = a.GetTypes();\n foreach (Type t in types)\n {\n if (t.IsInterface) continue;\n if (t.IsAbstract) continue;\n foreach (Type iface in t.GetInterfaces())\n {\n if (!iface.Equals(targetType)) continue;\n yield return (T) Activator.CreateInstance(t);\n break;\n }\n }\n }\n}\n" }, { "answer_id": 6266449, "author": "smartcaveman", "author_id": 344211, "author_profile": "https://Stackoverflow.com/users/344211", "pm_score": 1, "selected": false, "text": "IEnumerable<Type> GetAllTypesThatImplementInterface<T>()\n{\n var @interface = typeof (T);\n return @interface.IsInterface\n ? AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => !type.IsInterface\n && !type.IsAbstract \n && type.GetInterfaces().Contains(@interface))\n : new Type[] {};\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
302,543
<p>We have a browser based application which integrates a webdav server. We generate URLs to specific documents on our (webdav) servlet. (<code>https://server.com/webdav/path/to/file.doc</code>)</p> <p>What we are looking for is a good way for our clients to open these links directly in the appropriate program. I.E. for a windows user, "<code>https://server.com/webdav/path/to/excelfile.xls</code>" should open in MS Excel, while the same link should open OOCalc on Linux.</p> <p>So far, we've been using a small applet which maps has extensions, OS's, and programs and opens the program through <code>Runtime.getRuntime().exec(..)</code> . This approach works somewhat ok on Ms-Windows but is problematic on Linux and mac clients and is also quite inflexible.</p> <p>Is there any better way of doing this?</p>
[ { "answer_id": 302588, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public static IEnumerable<T> GetInstancesOfImplementingTypes<T>()\n{\n AppDomain app = AppDomain.CurrentDomain;\n Assembly[] ass = app.GetAssemblies();\n Type[] types;\n Type targetType = typeof(T);\n\n foreach (Assembly a in ass)\n {\n types = a.GetTypes();\n foreach (Type t in types)\n {\n if (t.IsInterface) continue;\n if (t.IsAbstract) continue;\n foreach (Type iface in t.GetInterfaces())\n {\n if (!iface.Equals(targetType)) continue;\n yield return (T) Activator.CreateInstance(t);\n break;\n }\n }\n }\n}\n" }, { "answer_id": 6266449, "author": "smartcaveman", "author_id": 344211, "author_profile": "https://Stackoverflow.com/users/344211", "pm_score": 1, "selected": false, "text": "IEnumerable<Type> GetAllTypesThatImplementInterface<T>()\n{\n var @interface = typeof (T);\n return @interface.IsInterface\n ? AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => !type.IsInterface\n && !type.IsAbstract \n && type.GetInterfaces().Contains(@interface))\n : new Type[] {};\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15355/" ]
302,544
<p>I would like to use <code>ON DUPLICATE KEY UPDATE</code> in Zend Framework 1.5, is this possible?</p> <p>Example</p> <pre><code>INSERT INTO sometable (...) VALUES (...) ON DUPLICATE KEY UPDATE ... </code></pre>
[ { "answer_id": 302757, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 7, "selected": true, "text": "ON DUPLICATE KEY UPDATE query() VALUES() $sql = \"INSERT INTO sometable (id, col2, col3) VALUES (:id, :col2, :col3)\n ON DUPLICATE KEY UPDATE col2 = VALUES(col2), col3 = VALUES(col3)\";\n\n$values = array(\"id\"=>1, \"col2\"=>327, \"col3\"=>\"active\");\n" }, { "answer_id": 1192321, "author": "Sergei Morozov", "author_id": 146187, "author_profile": "https://Stackoverflow.com/users/146187", "pm_score": 3, "selected": false, "text": "$sql = 'INSERT INTO sometable SET id = :id, col2 = :col2, col3 = :col3\n ON DUPLICATE KEY UPDATE id = :id, col2 = :col2, col3 = :col3';\n" }, { "answer_id": 1207076, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "ON DUPLICATE KEY UPDATE VALUES() $sql = 'INSERT INTO ... ON DUPLICATE KEY UPDATE id = VALUES(id), col2 = VALUES(col2), col3 = VALUES(col3)';\n" }, { "answer_id": 2435144, "author": "Peter", "author_id": 292600, "author_profile": "https://Stackoverflow.com/users/292600", "pm_score": -1, "selected": false, "text": "try {\n do insert here\n} catch (Exception $e) {\n do update here\n}\n" }, { "answer_id": 7339500, "author": "Rajdeep Rath", "author_id": 933468, "author_profile": "https://Stackoverflow.com/users/933468", "pm_score": 1, "selected": false, "text": "REPLACE INTO sometable SET field ='value'.....\n" }, { "answer_id": 15901043, "author": "Pawel", "author_id": 2261514, "author_profile": "https://Stackoverflow.com/users/2261514", "pm_score": 2, "selected": false, "text": "$arrayData = array('column1' => value1, 'column2' => value2, ...)\n\nclass Model_Db_Abstract extends Zend_Db_Table_Abstract\n{\n protected $_name;\n protected $_primaryKey;\n\n public function insertOrUpdate($arrayData)\n {\n $query = 'INSERT INTO `'. $this->_name.'` ('.implode(',',array_keys($arrayData)).') VALUES ('.implode(',',array_fill(1, count($arrayData), '?')).') ON DUPLICATE KEY UPDATE '.implode(' = ?,',array_keys($arrayData)).' = ?';\n return $this->getAdapter()->query($query,array_merge(array_values($arrayData),array_values($arrayData)));\n }\n\n}\n class Model_Db_Contractors extends Model_Db_Abstract \n{\n\n protected $_name = 'contractors';\n protected $_primaryKey = 'contractor_id';\n\n ...\n}\n class IndexController extends Zend_Controller_Action\n{\n public function saveAction()\n {\n $contractorModel = new Model_Db_Contractors();\n $aPost = $this->getRequest()->getPost();\n\n /* some filtering, checking, etc */\n\n $contractorModel->insertOrUpdate($aPost);\n }\n}\n" }, { "answer_id": 62047985, "author": "Vinod Sai", "author_id": 8221306, "author_profile": "https://Stackoverflow.com/users/8221306", "pm_score": 0, "selected": false, "text": " class Model_Db_Abstract extends Zend_Db_Table_Abstract\n {\n protected $_name;\n protected $_primaryKey;\n\n public function insertOrUpdate($arrayData)\n {\n $insertDataValuesForQuery = [];\n $queryParams = [];\n foreach ($insertData as $key => $value) {\n if (gettype($value) == \"object\") {\n array_push($insertDataValuesForQuery, $value->__toString());\n continue;\n }\n array_push($insertDataValuesForQuery, \"?\");\n array_push($queryParams, $value);\n }\n\n $updateDataValuesForQuery = [];\n foreach ($updateData as $key => $value) {\n if (gettype($value) == \"object\") {\n array_push($updateDataValuesForQuery, $key . \" = \" . $value->__toString());\n continue;\n }\n array_push($updateDataValuesForQuery, $key . \" = ?\");\n array_push($queryParams, $value);\n }\n\n $query = 'INSERT INTO ' . $this->_name . ' (' . implode(',', array_keys($insertData)) . ') VALUES (' . implode(',', $insertDataValuesForQuery) . ') ON DUPLICATE KEY UPDATE ' . implode(' , ', $updateDataValuesForQuery);\n return $this->getAdapter()->query($query, $queryParams);\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37019/" ]
302,558
<p>I'm working with a BasePageClass that derives from System.Web.UI.Page.</p> <p>What I'd like to do is somehow set a break point for every single time a method or property on this page is accessed.</p> <p>The only way I know how to do this is set up a breakpoint on every property and method on the page. This just doesn't seem practical.</p> <p>Does anybody know if there is a way to just say "whenever code on this page is executed, break on it"?</p>
[ { "answer_id": 303294, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 2, "selected": true, "text": "System.Diagnostics.Debugger.Break()" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25300/" ]
302,559
<p>Given the following sample array, how can I find all permutations of times available such that the amountNeeded is satisfied? In others words the follow array should produce the following:</p> <blockquote> <p>Available on 2008-05-14 from 08:00 to 08:10 using resource 10 and 13</p> <p>Available on 2008-05-14 from 08:10 to 08:20 using resource 10 and 13</p> </blockquote> <pre><code>print("Array( [amountNeeded] =&gt; 2 [resources] =&gt; Array ( [0] =&gt; Array ( [resourceID] =&gt; 10 [blocks] =&gt; Array ( [0] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:00 [endTime] =&gt; 08:10 ) [1] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:10 [endTime] =&gt; 08:20 ) [2] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:20 [endTime] =&gt; 08:30 ) ... [1] =&gt; Array ( [resourceID] =&gt; 13 [blocks] =&gt; Array ( [0] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:00 [endTime] =&gt; 08:10 ) [1] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:10 [endTime] =&gt; 08:20 ) [2] =&gt; Array ( [availDate] =&gt; 2008-05-14 [startTime] =&gt; 08:30 [endTime] =&gt; 08:40 ) ... "); </code></pre>
[ { "answer_id": 303294, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 2, "selected": true, "text": "System.Diagnostics.Debugger.Break()" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68043/" ]
302,569
<p>The monthRegex regular expression always returns true, even if dateInput is something like "December 1, 2008" by my thoughts it should match a regular expression by whichever key I pass into it. But that isn't what happens, it just returns true, and detects "JAN" as the month.</p> <pre><code> function dateFormat(dateInput) { var formattedDate = ""; var the_date, month, year; var monthHash = new Array(); monthHash['JAN']="01"; monthHash['FEB']="02"; monthHash['MAR']="03"; monthHash['APR']="04"; monthHash['MAY']="05"; monthHash['JUN']="06"; monthHash['JUL']="07"; monthHash['AUG']="08"; monthHash['SEP']="09"; monthHash['OCT']="10"; monthHash['NOV']="11"; monthHash['DEC']="12"; // Find which month we are dealing with var whichKey = null; for(var key in monthHash) { var monthRegex = new RegExp(key, "i") monthRegex.compile(); console.log("monthRegex.compile: " + monthRegex.test(dateInput)); if(monthRegex.test(dateInput)) { whichKey = key; break; } } } </code></pre> <p>Thank you, <Br/> &nbsp;&nbsp;Andrew J. Leer</p>
[ { "answer_id": 302735, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function dateFormat(dateInput) \n{\n var formattedDate = \"\";\n\n var the_date, month, year;\n\n var months = new Array(\"\", \n \"jan\", \"feb\", \"mar\", \n \"apr\", \"may\", \"jun\", \n \"jul\", \"aug\", \"sep\", \n \"oct\", \"nov\", \"dec\"\n );\n\n // Find which month we are dealing with\n for (var i = 1; i < months.length; i++) \n {\n if (dateInput.toLowerCase().indexOf(months[i]) > -1)\n {\n var whichMonth = months[i];\n break;\n }\n }\n if (whichMonth != undefined)\n alert(\"Found: \" + whichMonth);\n}\ndateFormat(\"10 Jun 2008\");\n function dateFormat(dateInput) \n{\n var formattedDate = \"\";\n\n var the_date, month, year;\n\n var months = /(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;\n\n // Find which month we are dealing with\n var matches = dateInput.match(months);\n if (matches != null)\n alert(\"Found: \" + matches[1]);\n}\ndateFormat(\"December, 10 2008\");\n" }, { "answer_id": 302812, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "// Get integer number of named month. 1-indexed for January;\n// return 0 if unreadable name.\n//\nfunction readMonth(s) {\n var begin= s.toLowerCase().substring(0, 3);\n var ix= MONTHS.indexOf(begin);\n if (ix==-1) return 0;\n return ix/4+1;\n}\nvar MONTHS= 'jan feb mar apr may jun jul aug sep oct nov dec';\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18149/" ]
302,577
<p>If it's harder to explain using words, let's look at an example I have a generic function like this</p> <pre><code>void FunctionA&lt;T&gt;() where T : Form, new() { } </code></pre> <p>If I have a reflected type, how do I use it with the above function? I'm looking forward to do this</p> <pre><code>Type a = Type.GetType("System.Windows.Forms.Form"); FunctionA&lt;a&gt;(); </code></pre> <p>Of cause the above method doesn't work.</p>
[ { "answer_id": 302598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "class Program\n{\n static void Main(string[] args)\n {\n var t = typeof(Foo);\n var m = t.GetMethod(\"Bar\");\n var hurr = m.MakeGenericMethod(typeof(string));\n var foo = new Foo();\n hurr.Invoke(foo, new string[]{\"lol\"});\n Console.ReadLine();\n }\n}\n\npublic class Foo\n{\n public void Bar<T>(T instance)\n {\n Console.WriteLine(\"called \" + instance);\n }\n}\n" }, { "answer_id": 3742508, "author": "gdbdable", "author_id": 451495, "author_profile": "https://Stackoverflow.com/users/451495", "pm_score": 4, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n int s = 38;\n\n\n var t = typeof(Foo);\n var m = t.GetMethod(\"Bar\");\n var g = m.MakeGenericMethod(s.GetType());\n var foo = new Foo();\n g.Invoke(foo, null);\n Console.ReadLine();\n }\n}\n\npublic class Foo\n{\n public void Bar<T>()\n {\n Console.WriteLine(typeof(T).ToString());\n }\n}\n" }, { "answer_id": 12201483, "author": "Stefan Turcanu", "author_id": 1571624, "author_profile": "https://Stackoverflow.com/users/1571624", "pm_score": 3, "selected": false, "text": "Type t = typeof(Customer); \nIList list = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(t))); \nConsole.WriteLine(list.GetType().FullName); \n" }, { "answer_id": 55185440, "author": "Steve", "author_id": 6432729, "author_profile": "https://Stackoverflow.com/users/6432729", "pm_score": 0, "selected": false, "text": "SQLite" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
302,578
<p>I'd like to login to the Forums part of community-server (e.g. <a href="http://forums.timesnapper.com/login.aspx?ReturnUrl=/forums/default.aspx" rel="nofollow noreferrer">http://forums.timesnapper.com/login.aspx?ReturnUrl=/forums/default.aspx</a>) and then download a specific page and perform a regex (to see if there are any posts waiting for moderation). If there is, I'd like to send an email.</p> <p>I'd like to do this from a Linux server.</p> <p>Currently I know how to download a page (using e.g. wget) but have a problem logging in. Any bright idea how that works?</p>
[ { "answer_id": 396572, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 1, "selected": false, "text": "\nmy $login_url = 'login url here';\nmy $username = 'username';\nmy $password = 'password';\nmy $mech = new WWW::Mechanize;\n$mech->get($login_url)\n or die \"Failed to fetch login page\";\n$mech->set_visible($username, $password)\n or die \"Failed to find fields to complete\";\n$mech->submit\n or die \"Failed to submit form\";\n\nif ($mech->content() =~ /posts awaiting moderation/i) {\n # Do something here\n}\n" }, { "answer_id": 1258697, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "--post-data=string\n--post-file=file\n\nUse POST as the method for all HTTP requests and send the specified data in the request body.\n\"--post-data\" sends string as data, whereas \"--post-file\" sends the contents of file. Other than\nthat, they work in exactly the same way.\n\nThis example shows how to log to a server using POST and then proceed to download the desired pages,\npresumably only accessible to authorized users:\n\n # Log in to the server. This can be done only once.\n wget --save-cookies cookies.txt \\\n --post-data 'user=foo&password=bar' \\\n http://server.com/auth.php\n\n # Now grab the page or pages we care about.\n wget --load-cookies cookies.txt \\\n -p http://server.com/interesting/article.php\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18274/" ]
302,583
<p>I have a list wrapper that maintains two Tstringlists and a TClassList</p> <p>I need this to be thread safe, such that:</p> <ul> <li>Concurrent writes are not allowed (wait state of some sort should be entered)</li> <li>Reading while writing (or vice versa) is not allowed (wait state of some sort should be entered)</li> <li>Concurrent reads <em>are</em> allowed</li> </ul> <p>Any ideas on how I can do this? My instinct tells me it needs more than just a critical section, perhaps a semaphore or "usage counter", perhaps one of these in <em>conjunction</em> with a CS.</p> <p>I'm just not quite sure where to start - anything from an overall approach in english to psuedo-code, to delphi implementation or external link would be much appreciated.</p>
[ { "answer_id": 329909, "author": "Darian Miller", "author_id": 35696, "author_profile": "https://Stackoverflow.com/users/35696", "pm_score": 2, "selected": false, "text": "x.LockList; \ntry \n //do whatever\nfinally \n x.Unlocklist; \nend;\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ]
302,597
<p>How do I calculate the last business day of month in VBScript? It is for a Reporting Services report.</p> <p>Thanks</p>
[ { "answer_id": 302642, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 0, "selected": false, "text": "Dim d\n\nd = DateAdd(\"m\", 1, Now)\n\nd = Month(d) & \"/1/\" & Year(d)\nd = DateAdd(\"d\", -1, d)\n\nIf Weekday(d) = 7 Then\n d = DateAdd(\"d\", -1, d)\nElseIf Weekday(d) = 1 Then\n d = DateAdd(\"d\", -2, d)\nEnd If\n\nMsgBox d\n" }, { "answer_id": 302647, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "Function LastBusinessDay(sDate)\n\n Dim iDay, iDaysToAdd, iDate\n\n iDaysToAdd = 0\n iDate = sDate\n\n x = 1\n\n Do while iDaysToAdd >= 0\n\n If Weekday(iDate) = 1 or Weekday(iDate) = 7 or _\n isHoliday(iDate) <> 0 then\n iDay = Weekday(iDate)\n Select Case cint(iDay)\n Case 1 'Sunday\n\n iDate = DateAdd(\"d\", -1, iDate)\n\n Case 7 'Saturday\n\n iDate = DateAdd(\"d\", -1, iDate)\n\n Case else 'this is a valid day\n\n if isHoliday(iDate) > 0 then\n iDate = dateadd(\"d\", -(isHoliday(iDate)), iDate)\n else\n iDaysToAdd = iDaysToAdd - 1\n end if\n\n End Select\n end if\n Loop\n\n LastBusinessDay = iDate\nEnd Function\n LastDayOfMonth isHoliday" }, { "answer_id": 302652, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 4, "selected": true, "text": "intMonth=11\n'Use zero to return last day of previous month '\nLastDayOfMonth= dateserial(2008,intMonth+1,0)\n\n'Saturday '\nIf WeekDay(LastDayOfMonth,1)=7 Then LastDayOfMonth=LastDayOfMonth-1\n'Sunday '\nIf WeekDay(LastDayOfMonth,1)=1 Then LastDayOfMonth=LastDayOfMonth-2\n\nMsgbox LastDayOfMonth & \" \" & Weekdayname(Weekday(LastDayOfMonth,1),1)\n" }, { "answer_id": 10146054, "author": "cgolvelker", "author_id": 1332238, "author_profile": "https://Stackoverflow.com/users/1332238", "pm_score": 1, "selected": false, "text": "Dim lastbusinessdayofprevmonth\n\nSub GetLastDay()\n\nDim curdate\ncurdate = Date() \n\nDim firstdayofcurmonth \nfirstdayofcurmonth = Month(curdate) & \"/1/\" & Year(curdate)\n\nDim lastdayofprevmonth\nlastdayofprevmonth = DateAdd(\"d\", -1, firstdayofcurmonth)\n\nDim day\nday = weekday(lastdayofprevmonth)\n\n\nif(day = 1) then\n lastbusinessdayofprevmonth = DateAdd(\"d\", -2, lastdayofprevmonth)\nelseif (day = 7) then\n lastbusinessdayofprevmonth = DateAdd(\"d\", -1, lastdayofprevmonth)\nelse\n lastbusinessdayofprevmonth = lastdayofprevmonth\nend if\n\nend sub\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,606
<p>I have a "fat" GUI that it getting fairly complex, and I would like to add links from a place to an other, and add back/forward buttons to ease navigation. It seems to me that this would be easier if my application was addressable: each composite could have its URI, and links would use that URI.</p> <p>Are there design patterns applicable to this problem?</p> <p>I could just look at the source code for Firefox or Eclipse, but these are huge projects and it would take a good amount of time making sense of it, so I'm asking here. Is there a simpler example somewhere?</p> <p>Of course it would be simpler if I had build a web app in the first place, but I'm not going to rewrite this huge app from scratch anytime soon.</p>
[ { "answer_id": 302756, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 1, "selected": true, "text": "String PAGE_1_KEY = \"page 1\";\nString PAGE_2_KEY = \"page 2\";\n// as many keys as you need\n\nJFrame frame = ...;\nframe.setLayout(new CardLayout());\nframe.add(createPage1(), PAGE_1_KEY);\nframe.add(createPage2(), PAGE_2_KEY);\n// etc.\n ((CardLayout)frame.getLayout()).show(frame, PAGE_1_KEY); // or whichever\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9843/" ]
302,609
<p>I'd like to write a batch file that checks to see if a process is running, and takes one action if it is, and another action if it isn't.</p> <p>I know I can use tasklist to list all running processes, but is there a simpler way to directly check on a specific process?</p> <p>It seems like this should work, but it doesn't:</p> <pre><code>tasklist /fi "imagename eq firefox.exe" /hn | MyTask IF %MyTask%=="" GOTO DO_NOTHING 'do something here :DO_NOTHING </code></pre> <p><strong>Using the solution provided by atzz, here is a complete working demo:</strong></p> <p><strong>Edit: Simplified, and modified to work under both WinXP and Vista</strong></p> <pre><code>echo off set process_1="firefox.exe" set process_2="iexplore.exe" set ignore_result=INFO: for /f "usebackq" %%A in (`tasklist /nh /fi "imagename eq %process_1%"`) do if not %%A==%ignore_result% Exit for /f "usebackq" %%B in (`tasklist /nh /fi "imagename eq %process_2%"`) do if not %%B==%ignore_result% Exit start "C:\Program Files\Internet Explorer\iexplore.exe" www.google.com </code></pre>
[ { "answer_id": 302698, "author": "atzz", "author_id": 23252, "author_profile": "https://Stackoverflow.com/users/23252", "pm_score": 4, "selected": true, "text": "set running=0\nfor /f \"usebackq\" %%T in (`tasklist /nh /fi \"imagename eq firefox.exe\"`) do set running=1\n setlocal EnableExtensions\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
302,614
<p>I've seen the following code to enable double buffering on a winform:</p> <pre><code>// Activates double buffering this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); this.UpdateStyles(); </code></pre> <p>Is this different in any way from simply setting Form.DoubleBuffering = true?</p>
[ { "answer_id": 302640, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 2, "selected": false, "text": "form.SetStyle(ControlStyles.OptimizedDoubleBuffer, value);\n" }, { "answer_id": 302644, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 4, "selected": true, "text": "Control.DoubleBuffering SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, value);\n ControlStyles.UserPaint" }, { "answer_id": 302713, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 1, "selected": false, "text": "DoubleBuffered SetStyle SetStyle" }, { "answer_id": 940039, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 1, "selected": false, "text": "public static void SetDoubleBuffered(System.Windows.Forms.Control c)\n{\n //Taxes: Remote Desktop Connection and painting\n //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n if (System.Windows.Forms.SystemInformation.TerminalServerSession)\n return;\n\n System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty(\n \"DoubleBuffered\",\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n aProp.SetValue(c, true, null); \n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
302,615
<p>Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.</p>
[ { "answer_id": 304525, "author": "Matthew Trevor", "author_id": 11265, "author_profile": "https://Stackoverflow.com/users/11265", "pm_score": 3, "selected": false, "text": "from circuits.lib.web import Server, Controller\n\nclass HelloWorld(Controller):\n def index(self):\n return \"Hello World!\"\n\nserver = Server(8000)\nserver += HelloWorld()\nserver.run()\n" }, { "answer_id": 307295, "author": "ianb", "author_id": 20218, "author_profile": "https://Stackoverflow.com/users/20218", "pm_score": 2, "selected": false, "text": "wsgiref.simple_server" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38306/" ]
302,637
<p>Working in an AIX environment, I'm issuing the following tar command and receive errors on sockets. </p> <p>Question 1. How can I avoid the socket errors?</p> <p>Question 2. Can I rely on the tar file to contain all files excluding the ones in error?</p> <pre><code> $ tar -cvf /post_patches.tar /xyz tar: /xyz/runtime/splSock6511 could not be archived tar: /xyz/runtime/splSock6507 could not be archived tar: /xyz/runtime/splSock6510 could not be archived tar: /xyz/runtime/splSock6506 could not be archived $ ls -asl spl* 0 srwxrwxrwx 1 myuser myuser 0 Nov 19 09:41 splSock6506 0 srwxrwxrwx 1 myuser myuser 0 Nov 19 09:41 splSock6507 0 srwxrwxrwx 1 myuser myuser 0 Nov 18 14:19 splSock6510 0 srwxrwxrwx 1 myuser myuser 0 Nov 18 14:19 splSock6511 </code></pre>
[ { "answer_id": 303843, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "tar /xyz -X -d" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,650
<p>in the out of the project template solution (Dynamic Data Web Application), I have the model created and all is good. - Get the list of the tables, and the select edit etc.</p> <p>But my database has linking tables that just contain forgien keys - so the list template just displays the fk value</p> <p><img src="https://lh6.ggpht.com/_KoHB_k0rTus/SSUbvobGucI/AAAAAAAAAB4/MYPlVYtB2zQ/s288/PARLinkTable.jpg" alt="diagram of the table"></p> <p>Is there away to combine the list of the row in the primary table with an inspection of another table based on the fk?</p> <p>More akin to a join in SQL? but using Linq2Entity and the MetaModel?</p> <p>Below is the List.aspx.cs - this seems to bind the standard grid to the entitydatasource, but this is to the current table as per the route in the MVC.</p> <p>But as you can see i need to go and query the Person, Role and Link table via the model to get the other fields so that this would be useful. <img src="https://lh5.ggpht.com/_KoHB_k0rTus/SSUd7yGYUgI/AAAAAAAAADI/cbHUjV1GfrA/VS-Plain.jpg" alt="vstudio"></p> <p>PS want to try and keep this in LINQ2Entity if possible -trying to grok</p> <p>the natural thing that I want to do is start to spin off new sql queries to go and retrive the values. But this is not in this idiom.</p>
[ { "answer_id": 304931, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "MetaModel refMetaModel = MetaModel.GetModel(typeof(yourdataContextName));\nMetaTable refMetaModel;\nrefMetaModel = refMetaModel.GetTable(\"yourTableName\");\n" }, { "answer_id": 305253, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "//use the datacontext to get the underlying data\n using (brrdbEntities brr = new brr_dbEntities())\n {\n ObjectQuery<person> people = brr.person;\n IQueryable<string> names = from p in people select p.person_name;\n foreach (var name in names)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api" rel="noreferrer">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
[ { "answer_id": 302847, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 7, "selected": true, "text": "djangosettings.py DATABASE_ENGINE = 'oracle'\nDATABASE_HOST = 'localhost'\nDATABASE_NAME = 'ORCL'\nDATABASE_USER = 'scott' \nDATABASE_PASSWORD = 'tiger'\n import os\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"djangosettings\"\n" }, { "answer_id": 32477964, "author": "Gary Gauh", "author_id": 1145750, "author_profile": "https://Stackoverflow.com/users/1145750", "pm_score": 1, "selected": false, "text": "Django 1.8 .\n├── myApp\n│   ├── __init__.py\n│   └── models.py\n└── my_manage.py\n __init__.py models.py models.py class MyModel(models.Model):\n field = models.CharField(max_length=255)\n python my_manage.py sql myApp\npython my_manage.py migrate\n......\n my_manage.py db_conf = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'your_database_name',\n 'USER': 'your_user_name',\n 'PASSWORD': 'your_password',\n 'HOST': 'your_mysql_server_host',\n 'PORT': 'your_mysql_server_port',\n }\n}\n\nsettings.configure(\n DATABASES = db_conf,\n INSTALLED_APPS = ( \"myApp\", )\n)\n\n# Calling django.setup() is required for “standalone” Django u usage\n# https://docs.djangoproject.com/en/1.8/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage\nimport django\ndjango.setup()\n\nif __name__ == '__main__':\n import sys\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
302,658
<p>Given a java.util.Date object how do I go about finding what Quarter it's in?</p> <p>Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.</p>
[ { "answer_id": 302669, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 7, "selected": true, "text": "import java.time.LocalDate;\nimport java.time.temporal.IsoFields;\n\nLocalDate myLocal = LocalDate.now();\nquarter = myLocal.get(IsoFields.QUARTER_OF_YEAR);\n import java.util.Date;\n\nDate myDate = new Date();\nint quarter = (myDate.getMonth() / 3) + 1;\n Calendar import java.util.Calendar;\nimport java.util.GregorianCalendar;\n\nCalendar myCal = new GregorianCalendar();\nint quarter = (myCal.get(Calendar.MONTH) / 3) + 1;\n" }, { "answer_id": 302674, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 4, "selected": false, "text": "Calendar c = /* get from somewhere */\nint month = c.get(Calendar.MONTH);\n\nreturn (month >= Calendar.JANUARY && month <= Calendar.MARCH) ? \"Q1\" :\n (month >= Calendar.APRIL && month <= Calendar.JUNE) ? \"Q2\" :\n (month >= Calendar.JULY && month <= Calendar.SEPTEMBER) ? \"Q3\" :\n \"Q4\";\n" }, { "answer_id": 302688, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "Calendar cal = Calendar.getInstance(Locale.US);\n/* Consider whether you need to set the calendar's timezone. */\ncal.setTime(date);\nint month = cal.get(Calendar.MONTH); /* 0 through 11 */\nint quarter = (month / 3) + 1;\n" }, { "answer_id": 17309819, "author": "James Raitsev", "author_id": 359862, "author_profile": "https://Stackoverflow.com/users/359862", "pm_score": 3, "selected": false, "text": "private static final int[] quarters = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};\n quarter private static final int thisQuarter = quarters[thisMonth];\n thisMonth private static final int thisMonth = cal.get(Calendar.MONTH);\n" }, { "answer_id": 24705756, "author": "user3830848", "author_id": 3830848, "author_profile": "https://Stackoverflow.com/users/3830848", "pm_score": 1, "selected": false, "text": "int month = Calendar.getInstance().get( Calendar.MONTH ) + 1;\n\nint quarter = month % 3 == 0? (month / 3): ( month / 3)+1;\n" }, { "answer_id": 29854193, "author": "Marco", "author_id": 1707348, "author_profile": "https://Stackoverflow.com/users/1707348", "pm_score": 1, "selected": false, "text": "thisMonth String quarter = thisMonth/3 <= 1 ? \"Q1\" : thisMonth/3 <= 2 ? \"Q2\" : thisMonth/3 <= 3 ? \"Q3\" : \"Q4\";\n" }, { "answer_id": 33672171, "author": "Karl John Hernandez", "author_id": 932676, "author_profile": "https://Stackoverflow.com/users/932676", "pm_score": 0, "selected": false, "text": "int quarter = (Calendar.getInstance().get(Calendar.MONTH) / 3); // 0 to 3\nString[] mQuarterKey = {\"qt1\", \"qt2\", \"qt3\", \"qt4\"};\nString strQuarter = mQuarterKey[quarter];\n" }, { "answer_id": 36765477, "author": "abdolence", "author_id": 567987, "author_profile": "https://Stackoverflow.com/users/567987", "pm_score": 6, "selected": false, "text": "LocalDate IsoFields LocalDate.now().get(IsoFields.QUARTER_OF_YEAR)\n" }, { "answer_id": 39018515, "author": "Coltini", "author_id": 6702459, "author_profile": "https://Stackoverflow.com/users/6702459", "pm_score": 2, "selected": false, "text": "double quarter = Math.ceil(new Double(jodaDate.getMonthOfYear()) / 3.0);\n" }, { "answer_id": 39299286, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "YearQuarter\n.from(\n LocalDate.of( 2018 , 1 , 23 ) \n)\n Quarter YearQuarter continent/region EST IST ZoneId z = ZoneId.of( \"America/Montreal\" );\nYearQuarter yq = YearQuarter.now( z );\n java.util.Date java.util.Date Instant Instant instant = myUtilDate.toInstant();\n ZoneDateTime ZoneId z = ZoneId.of( \"America/Montreal\" );\nZonedDateTime zdt = instant.atZone( z );\n YearQuarter ZonedDateTime YearQuarter yq = YearQuarter.from( zdt );\n YearQuarter java.util.Date Calendar SimpleDateFormat java.sql.* Interval YearWeek YearQuarter" }, { "answer_id": 39446116, "author": "nexoma", "author_id": 1739053, "author_profile": "https://Stackoverflow.com/users/1739053", "pm_score": 0, "selected": false, "text": "import java.time.format.DateTimeFormatter\nimport java.time.LocalDate\n\nprintln(\"withQuarter: \" + LocalDate.of(\"2016\".toInt,\"07\".toInt,1).format(DateTimeFormatter.ofPattern(\"yyyyQMM\")))\n" }, { "answer_id": 58180216, "author": "Sunila SS", "author_id": 9781064, "author_profile": "https://Stackoverflow.com/users/9781064", "pm_score": 0, "selected": false, "text": " public static Integer getQuarter(Date d){\n Calendar c = Calendar.getInstance();\n c.setTime(d);\n int month = c.get(Calendar.MONTH);\n return (month /3)+1;\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
302,663
<p>Is there a difference between <code>Cursor.Current</code> and <code>this.Cursor</code> (where <code>this</code> is a WinForm) in .Net? I've always used <code>this.Cursor</code> and have had very good luck with it but I've recently started using CodeRush and just embedded some code in a "Wait Cursor" block and CodeRush used the <code>Cursor.Current</code> property. I've seen on the Internet and at work where other programmers have had some problems with the <code>Cursor.Current</code> property. It just got me to wondering if there is a difference in the two. Thanks in advance.</p> <p>I did a little test. I have two winforms. I click a button on form1, set the <code>Cursor.Current</code> property to <code>Cursors.WaitCursor</code> and then show form2. The cursor doesn't change on either form. It remains <code>Cursors.Default</code> (pointer) cursor.</p> <p>If I set <code>this.Cursor</code> to <code>Cursors.WaitCursor</code> in the button click event on form1 and show form2, the wait cursor only shows on form1 and the default cursor is on form2 which is expected. So, I still don't know what <code>Cursor.Current</code> does.</p>
[ { "answer_id": 302676, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "this.Cursor this Cursor.Current this.Cursor" }, { "answer_id": 302865, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 8, "selected": true, "text": "private void button1_Click(object sender, EventArgs e) {\n this.UseWaitCursor = true;\n System.Threading.Thread.Sleep(3000);\n this.UseWaitCursor = false;\n}\n using System;\nusing System.Windows.Forms;\n\npublic class HourGlass : IDisposable {\n public HourGlass() {\n Enabled = true;\n }\n public void Dispose() {\n Enabled = false;\n }\n public static bool Enabled {\n get { return Application.UseWaitCursor; }\n set {\n if (value == Application.UseWaitCursor) return;\n Application.UseWaitCursor = value;\n Form f = Form.ActiveForm;\n if (f != null && f.Handle != IntPtr.Zero) // Send WM_SETCURSOR\n SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1);\n }\n }\n [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}\n private void button1_Click(object sender, EventArgs e) {\n using (new HourGlass()) {\n System.Threading.Thread.Sleep(3000);\n }\n}\n" }, { "answer_id": 8515665, "author": "wałdis iljuczonok", "author_id": 558010, "author_profile": "https://Stackoverflow.com/users/558010", "pm_score": 3, "selected": false, "text": "[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n public static bool Enabled\n{\n get\n {\n return Application.UseWaitCursor;\n }\n\n set\n {\n if (value == Application.UseWaitCursor)\n {\n return;\n }\n\n Application.UseWaitCursor = value;\n var handle = GetForegroundWindow();\n SendMessage(handle, 0x20, handle, (IntPtr)1);\n }\n}\n" }, { "answer_id": 28522776, "author": "bootsn", "author_id": 4567988, "author_profile": "https://Stackoverflow.com/users/4567988", "pm_score": 0, "selected": false, "text": "private void btnDoLongRunningOperation_Click(object sender, System.EventArgs e)\n{\n this.Cursor = Cursors.WaitCursor;\n LongRunningOperation();\n this.Cursor = Cursors.Arrow;\n}\n" }, { "answer_id": 29018895, "author": "Elian", "author_id": 4438571, "author_profile": "https://Stackoverflow.com/users/4438571", "pm_score": 0, "selected": false, "text": "Windows.Forms.Cursor.Current = Cursors.Default\n" }, { "answer_id": 36959906, "author": "Attila Horváth", "author_id": 1603452, "author_profile": "https://Stackoverflow.com/users/1603452", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Windows.Forms;\n\npublic class HourGlass : IDisposable\n{\n public static bool ApplicationEnabled\n {\n get{ return Application.UseWaitCursor; }\n set\n {\n Form activeFrom = Form.ActiveForm;\n if (activeFrom == null || ApplicationEnabled == value) return;\n if (ApplicationEnabled == value)return;\n Application.UseWaitCursor = (bool)value;\n\n if (activeFrom.InvokeRequired)\n {\n activeFrom.BeginInvoke(new Action(() =>\n {\n if (activeFrom.Handle != IntPtr.Zero)\n SendMessage(activeFrom.Handle, 0x20, activeFrom.Handle, (IntPtr)1); // Send WM_SETCURSOR\n }));\n }\n else\n {\n if (activeFrom.Handle != IntPtr.Zero)\n SendMessage(activeFrom.Handle, 0x20, activeFrom.Handle, (IntPtr)1); // Send WM_SETCURSOR\n }\n }\n }\n\n private Form f;\n\n public HourGlass() \n {\n this.f = Form.ActiveForm;\n\n if (f == null)\n {\n throw new ArgumentException();\n }\n Enabled = true;\n }\n\n public HourGlass(bool enabled)\n {\n this.f = Form.ActiveForm;\n\n if (f == null)\n {\n throw new ArgumentException();\n }\n Enabled = enabled;\n }\n\n public HourGlass(Form f, bool enabled)\n {\n this.f = f;\n\n if (f == null)\n {\n throw new ArgumentException();\n }\n Enabled = enabled;\n }\n\n public HourGlass(Form f)\n {\n this.f = f;\n\n if (f == null)\n {\n throw new ArgumentException();\n }\n\n Enabled = true;\n }\n\n public void Dispose()\n {\n Enabled = false;\n }\n\n public bool Enabled\n {\n get { return f.UseWaitCursor; }\n set\n {\n if (f == null || Enabled == value) return;\n if (Application.UseWaitCursor == true && value == false) return;\n\n f.UseWaitCursor = (bool)value;\n\n if(f.InvokeRequired)\n {\n f.BeginInvoke(new Action(()=>\n {\n if (f.Handle != IntPtr.Zero)\n SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1); // Send WM_SETCURSOR\n }));\n }\n else\n {\n if (f.Handle != IntPtr.Zero)\n SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1); // Send WM_SETCURSOR\n }\n }\n }\n\n [System.Runtime.InteropServices.DllImport(\"user32.dll\")]\n private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n}\n try\n{\n HourGlass.ApplicationEnabled = true;\n //time consuming synchronous task\n}\nfinally\n{\n HourGlass.ApplicationEnabled = false;\n}\n using (new HourGlass())\n{\n //time consuming synchronous task\n}\n public readonly HourGlass hourglass;\n\npublic Form1()\n{\n InitializeComponent();\n hourglass = new HourGlass(this, false);\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16419/" ]
302,664
<p>I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.</p> <p>I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.</p> <p>Objective-C has an NSDate type but I'm not sure if that will map directly?</p>
[ { "answer_id": 2626980, "author": "mobibob", "author_id": 157804, "author_profile": "https://Stackoverflow.com/users/157804", "pm_score": 2, "selected": false, "text": "dateExpires = [NSDate dateWithTimeIntervalSinceNow: sqlite3_column_double(queryStmt, 5)];\n 2010-04-12 23:19:48 -0500\n [NSDate date]" }, { "answer_id": 7108589, "author": "Hussain KMR Behestee", "author_id": 900684, "author_profile": "https://Stackoverflow.com/users/900684", "pm_score": 5, "selected": false, "text": " NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];\n [dateFormat setDateFormat:@\"yyyy-MM-dd HH:mm:ss\"];\n NSString *dateString=[dateFormat stringFromDate:[NSDate date]];\n\n sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);\n NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];\n [dateFormat setDateFormat:@\"yyyy-MM-dd HH:mm:ss\"];\n NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];\n NSDateFormatter *formatter = [[NSDateFormatter alloc] init];\n [formatter setDateFormat:@\"dd-MM-yyyy hh:mm:ss a\"];\n NSLog(@\"My Date was : %@\", [formatter stringFromDate:myDate]);\n 'dd' = Day 01-31\n 'MM' = Month 01-12\n 'yyyy' = Year 2000\n 'HH' = Hour in 24 hour\n 'hh' = Hour in 12 hour\n 'mm' = Minute 00-59\n 'ss' = Second 00-59\n 'a' = AM / PM\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476/" ]
302,680
<p>I'm looking to have a simple custom dialog box, like a message box, that has a label and a TextBox. If there's a simple way to do this, sorry! I'm really not well versed in the dialog stuff. </p> <p>Thanks for any help, guys!</p>
[ { "answer_id": 302828, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "public CustomDialog(string textCaption)\n{\n label1.Text = textCaption;\n}\n public override string Text\n{\n get\n {\n return textBox1.Text;\n }\n}\n this.DialogResult = DialogResult.OK; // this will close the form, too\n using (CustomDialog dialog = new CustomDialog(\"What is your name\"))\n{\n if (dialog.ShowDialog(this) == DialogResult.OK)\n {\n string enteredText = dialog.Text;\n }\n}\n" }, { "answer_id": 305732, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 5, "selected": true, "text": "private bool _Moving = false;\nprivate Point _Offset;\nprivate void Form1_MouseDown(object sender, MouseEventArgs e)\n{\n _Moving = true;\n _Offset = new Point(e.X, e.Y);\n}\n\nprivate void Form1_MouseMove(object sender, MouseEventArgs e)\n{\n if (_Moving)\n {\n Point newlocation = this.Location;\n newlocation.X += e.X - _Offset.X;\n newlocation.Y += e.Y - _Offset.Y;\n this.Location = newlocation;\n }\n}\nprivate void Form1_MouseUp(object sender, MouseEventArgs e)\n{\n if (_Moving)\n {\n _Moving = false;\n }\n}\n this.DialogResult = DialogResult.OK;\n" }, { "answer_id": 306137, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 1, "selected": false, "text": "string s = Microsoft.VisualBasic.Interaction.InputBox(\"prompt text\",\n \"title text\", \"default value\", 0, 0);\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39024/" ]
302,690
<p>I'm trying to move my database.mdf file from a development environment to a SQL Server Express server that is hosted on my VPS - but I can't figure out how to attach the file to my database server. Help!</p>
[ { "answer_id": 302702, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "sp_attach_db" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363822/" ]
302,692
<p>I'm having a weird problem, where tagging <strong>works fine on my development machine</strong>, but when I deploy to the production server, I get this error in the log:</p> <pre><code>ActionView::TemplateError (undefined method `tags' for #&lt;Person:0x98bb9d4&gt;) on line... </code></pre> <p>There is an entry in the production.log file that states that has_many_polymorphs is loaded, so it's not like the plugin isn't available on the production machine.</p> <p>My Google-fu has failed me trying to find the answer, so if anyone knows what could be wrong it would be greatly appreciated!</p> <p>Edit: I should have mentioned that on both production and development I'm using the same database. I downloaded the production one, and used it on the development machine and it works fine.</p>
[ { "answer_id": 302702, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "sp_attach_db" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
302,700
<p>So, up until today, when I tried to edit a read only file in VS2008, a dialog popped up giving me three options:</p> <ul> <li>Edit in memory</li> <li>Make writable</li> <li>Save a copy</li> </ul> <p>There was also a checkbox which read "Never allow in memory edits".</p> <p>Suddenly, it has stopped offering these options and simply will not accept any input in the editor window if the file is read only. I have to go into windows explorer and mark the file as not read only then reopen it in VS before I can make any changes. I'm working on a large project, with lots of source controlled files and often need to make local only changes to files, so this is a real PITA.</p> <p>I'm guessing I must have checked the never allow in memory edits checkbox by mistake. </p> <p>There is an option in Tools.. Options.. Environment.. Documents which reads:</p> <p>"Allow editing of read only files, warn when attempt to save"</p> <p>This checkbox is ticked, and changing its value currently as no effect. I've tried closing and opening studio, restarting my machine etc - all to no avail.</p> <p>Anyone know how to restore the previous behaviour?</p>
[ { "answer_id": 308424, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 5, "selected": true, "text": "HKCU\\Sofware\\Microsoft\\Visual Studio\\9.0\\Source Control\\UncontrolledInMemoryEditDialogSuppressed\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35086/" ]
302,701
<p>What is the difference between </p> <pre><code>if(null==object) </code></pre> <p>and </p> <pre><code>if(object==null) </code></pre> <p>Please give the advantage for using the above.</p>
[ { "answer_id": 302707, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": false, "text": "= == if (null = object) if (object = null)" }, { "answer_id": 302711, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "if (null == object) = ==" }, { "answer_id": 302714, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "=" }, { "answer_id": 302723, "author": "Brian Genisio", "author_id": 36687, "author_profile": "https://Stackoverflow.com/users/36687", "pm_score": 2, "selected": false, "text": "public static class ObjectExtensions\n{\n public static bool IsNull(this object target)\n {\n return null == target;\n }\n}\n if(item.IsNull())\n" }, { "answer_id": 302743, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 3, "selected": false, "text": "if(a = false)\n{\n // I'll never execute\n}\nif(b = null)\n{\n // I'll never execute \n}\nb.Method(); // And now I'm null!\n if(false = a) // OOPS! Compiler error\n{\n // ..\n}\nif(null = b) // OOPS! Compiler error\n{\n // ..\n}\n if(myString != null && myString.Equals(\"OtherString\"))\n{\n // ...\n}\n if(\"OtherString\".Equals(myString))\n{\n // ..\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,718
<p>I have the following string in the smarty (php templating system) variable $test:</p> <pre><code>&lt;img height="113" width="150" alt="Sunset" src="/test.jpg"/&gt; </code></pre> <p>I want to add "em" to the height and width like this:</p> <pre><code>{$test|replace:'" w':'em" w'|replace:'" a':'em" a'} </code></pre> <p>But this doesn't work... What's the problem and the solution?</p>
[ { "answer_id": 302798, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 3, "selected": true, "text": "{$test|regex_replace:'/\".w/':'em\" w'|regex_replace:'/\".a/':'em\" a'}\n '/\\\".w/'\n'/\".*w/'\n'/\\\".*w/'\n" }, { "answer_id": 324418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<img height=\"$h\" width=\"$w\" $attributes/>\n <img height=\"$[h]em\" width=\"$[w]em\" $attributes\"/>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13262/" ]
302,720
<p>I have a parent object which has a one to many relationship with an IList of child objects. What is the best way to delete the child objects? I am not deleting the parent. My parent object contains an IList of child objects. Here is the mapping for the one to many relationship:</p> <pre><code>&lt;bag name="Tiers" cascade="all"&gt; &lt;key column="mismatch_id_no" /&gt; &lt;one-to-many class="TGR_BL.PromoTier,TGR_BL"/&gt; &lt;/bag&gt; </code></pre> <p>If I try to remove all objects from the collection using clear(), then call SaveOrUpdate(), I get this exception:</p> <pre><code>System.Data.SqlClient.SqlException: Cannot insert the value NULL into column </code></pre> <p>If I try to delete the child objects individually then remove them from the parent, I get an exception: </p> <pre><code>deleted object would be re-saved by cascade </code></pre> <p>This is my first time dealing with deleting child objects in NHibernate. What am I doing wrong?</p> <p>edit: Just to clarify - I'm NOT trying to delete the parent object, just the child objects. I have the relationship set up as a one to many on the parent. Do I also need to create a many-to-one relationship on the child object mapping?</p>
[ { "answer_id": 2922951, "author": "Liath", "author_id": 352176, "author_profile": "https://Stackoverflow.com/users/352176", "pm_score": 2, "selected": false, "text": "product = pRepo.GetByID(newProduct.ProductID);\nproduct.Category.Products.Remove(product);\npRepo.Delete(product);\n" }, { "answer_id": 3317071, "author": "hanuman0503", "author_id": 325246, "author_profile": "https://Stackoverflow.com/users/325246", "pm_score": 2, "selected": false, "text": "[HasMany(typeof(MessageSentTo), Cascade = ManyRelationCascadeEnum.AllDeleteOrphan, Inverse = true)]\npublic IList<MessageSentTo> MessageSendTos\n{\n get { return m_MessageSendTo; }\n set { m_MessageSendTo = value; }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
302,736
<p>What are some guidelines for when it is <strong>not</strong> necessary to check for a null?</p> <p>A lot of the inherited code I've been working on as of late has null-checks ad nauseam. Null checks on trivial functions, null checks on API calls that state non-null returns, etc. In some cases, the null-checks are reasonable, but in many places a null is not a reasonable expectation.</p> <p>I've heard a number of arguments ranging from "You can't trust other code" to "ALWAYS program defensively" to "Until the language guarantees me a non-null value, I'm always gonna check." I certainly agree with many of those principles up to a point, but I've found excessive null-checking causes other problems that usually violate those tenets. Is the tenacious null checking really worth it?</p> <p>Frequently, I've observed codes with excess null checking to actually be of poorer quality, not of higher quality. Much of the code seems to be so focused on null-checks that the developer has lost sight of other important qualities, such as readability, correctness, or exception handling. In particular, I see a lot of code ignore the std::bad_alloc exception, but do a null-check on a <code>new</code>.</p> <p>In C++, I understand this to some extent due to the unpredictable behavior of dereferencing a null pointer; null dereference is handled more gracefully in Java, C#, Python, etc. Have I just seen poor-examples of vigilant null-checking or is there really something to this?</p> <p>This question is intended to be language agnostic, though I am mainly interested in C++, Java, and C#.</p> <hr> <p>Some examples of null-checking that I've seen that seem to be <em>excessive</em> include the following:</p> <hr> <p>This example seems to be accounting for non-standard compilers as C++ spec says a failed new throws an exception. Unless you are explicitly supporting non-compliant compilers, does this make sense? Does this make <em>any</em> sense in a managed language like Java or C# (or even C++/CLR)?</p> <pre><code>try { MyObject* obj = new MyObject(); if(obj!=NULL) { //do something } else { //??? most code I see has log-it and move on //or it repeats what's in the exception handler } } catch(std::bad_alloc) { //Do something? normally--this code is wrong as it allocates //more memory and will likely fail, such as writing to a log file. } </code></pre> <hr> <p>Another example is when working on internal code. Particularly, if it's a small team who can define their own development practices, this seems unnecessary. On some projects or legacy code, trusting documentation may not be reasonable... but for new code that you or your team controls, is this really necessary?</p> <p>If a method, which you can see and can update (or can yell at the developer who is responsible) has a contract, is it still necessary to check for nulls?</p> <pre><code>//X is non-negative. //Returns an object or throws exception. MyObject* create(int x) { if(x&lt;0) throw; return new MyObject(); } try { MyObject* x = create(unknownVar); if(x!=null) { //is this null check really necessary? } } catch { //do something } </code></pre> <hr> <p>When developing a private or otherwise internal function, is it really necessary to explicitly handle a null when the contract calls for non-null values only? Why would a null-check be preferable to an assert?</p> <p>(obviously, on your public API, null-checks are vital as it's considered impolite to yell at your users for incorrectly using the API)</p> <pre><code>//Internal use only--non-public, not part of public API //input must be non-null. //returns non-negative value, or -1 if failed int ParseType(String input) { if(input==null) return -1; //do something magic return value; } </code></pre> <p>Compared to:</p> <pre><code>//Internal use only--non-public, not part of public API //input must be non-null. //returns non-negative value int ParseType(String input) { assert(input!=null : "Input must be non-null."); //do something magic return value; } </code></pre>
[ { "answer_id": 302785, "author": "djuth", "author_id": 38787, "author_profile": "https://Stackoverflow.com/users/38787", "pm_score": 3, "selected": false, "text": "internal void DoThis(Something thing)\n{\n Debug.Assert(thing != null, \"Arg [thing] cannot be null.\");\n //...\n}\n public void DoThis(Something thing)\n{\n if (thing == null)\n {\n throw new ArgumentException(\"Arg [thing] cannot be null.\");\n }\n //...\n}\n" }, { "answer_id": 303232, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "if(obj==NULL)\n throw std::bad_alloc();\n" }, { "answer_id": 305592, "author": "Mike Chess", "author_id": 27887, "author_profile": "https://Stackoverflow.com/users/27887", "pm_score": 2, "selected": false, "text": "public MyObject MyMethod(object foo)\n{\n if (foo == null)\n {\n throw new ArgumentNullException(\"foo\");\n }\n\n // do whatever if foo was non-null\n}\n" }, { "answer_id": 308612, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 5, "selected": true, "text": "(foo *)(-1) template<typename T>\nstatic inline void nullcheck(T *ptr) { \n #if PLATFORM_TRAITS_NEW_RETURNS_NULL\n if (ptr == NULL) throw std::bad_alloc();\n #endif\n}\n" }, { "answer_id": 5427702, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "null new null new null null null" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17871/" ]
302,742
<p>I need to use C++ to read in text with spaces, followed by a numeric value.</p> <p>For example, data that looks like:</p> <pre><code>text1 1.0 text two 2.1 text2 again 3.1 </code></pre> <p>can't be read in with 2 <code>"infile &gt;&gt;"</code> statements. I'm not having any luck with <code>getline</code> either. I ultimately want to populate a <code>struct</code> with these 2 data elements. Any ideas?</p>
[ { "answer_id": 302848, "author": "atzz", "author_id": 23252, "author_profile": "https://Stackoverflow.com/users/23252", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <sstream>\n\nint main()\n{\n std::istringstream iss(\"text1 1.0 text two 2.1 text2 again 3.1\");\n\n for ( ;; )\n {\n double x;\n if ( iss >> x )\n {\n std::cout << x << std::endl;\n }\n else\n {\n iss.clear();\n std::string junk;\n if ( !(iss >> junk) )\n break;\n }\n }\n}\n" }, { "answer_id": 303424, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "while( ! eof)\n getline(textbuffer)\n getline(numberbuffer)\n stringlist = tokenize(textbuffer)\n number = atof(numberbuffer)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39035/" ]
302,749
<p>I'm having a couple of problems with the JQuery <a href="http://tablesorter.com/docs/" rel="noreferrer">tablesorter</a> plugin. If you click on a column header, it should sort the data by this column, but there are a couple of problems:</p> <ol> <li>The rows are not properly sorted (1, 1, 2183, 236)</li> <li>The total row is included in the sort</li> </ol> <p>Regarding (2), I can't easily move the total row to a table footer, because the HTML is generated by the <a href="http://displaytag.sourceforge.net/11/" rel="noreferrer">displaytag</a> tag library over which I have limited control.</p> <p>Regarding (1), I don't understand why the sort doesn't work as I've used exactly the same JavaScript shown in the simplest example in the <a href="http://tablesorter.com/docs/#Getting-Started" rel="noreferrer">tablesorter tutorials</a>. </p> <p>In fact, there's only a single line of JS code, which is:</p> <pre><code>&lt;body onload="jQuery('#communityStats').tablesorter();"&gt; </code></pre> <p>Thanks in advance, Don</p>
[ { "answer_id": 302822, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": " $(function() {\n $('#communityStats').append(\"<tfoot></tfoot>\");\n $('#communityStats > tr:last').remove()\n .appendTo('#communityStats > tfoot');\n $('#communityStats').tablesorter();\n });\n" }, { "answer_id": 302834, "author": "Tjofras", "author_id": 37486, "author_profile": "https://Stackoverflow.com/users/37486", "pm_score": 5, "selected": false, "text": "<script type=\"text/javascript\" >\njQuery(document).ready(function() \n{ \n jQuery(\"#communityStats\").tablesorter({ \n headers: { 2: { sorter:'digit' } , \n 3: { sorter:'digit' } ,\n 4: { sorter:'digit' } ,\n 5: { sorter:'digit' } ,\n 6: { sorter:'digit' } ,\n 7: { sorter:'digit' } ,\n 8: { sorter:'currency' } ,\n 9: { sorter:'currency' } ,\n 10: { sorter:'currency' } ,\n 11: { sorter:'currency' } \n } \n }); \n});\n</script>\n" }, { "answer_id": 884327, "author": "catalpa", "author_id": 52211, "author_profile": "https://Stackoverflow.com/users/52211", "pm_score": 0, "selected": false, "text": "$(document).ready(function() {\n $('#communityStats').append(\"<tfoot></tfoot>\");\n $('#communityStats > tr:last').remove()\n .appendTo('#communityStats > tfoot');\n\n $(\"#communityStats\").tablesorter({\n debug: true,\n headers: { \n 0:{sorter: 'digit'}\n ...\n 10:{sorter: 'digit'}\n }\n });\n\n}); \n" }, { "answer_id": 2462084, "author": "kemal baylan", "author_id": 295638, "author_profile": "https://Stackoverflow.com/users/295638", "pm_score": 0, "selected": false, "text": "table.tablesorter thead {\nposition: fixed;\ntop: 35px; // \n}\n function tableFixedHeader() {\n var tdUnit = $('.tablesorter tbody tr:first').children('td').length;\n for(var i=0;i<tdUnit; i++) {\n $('.tablesorter thead th').eq(i).width($('.tablesorter tbody td').eq(i).width());\n }\n $('.tablesorter').css('margin-top',$('.tablesorter thead').height()); \n}\n <div id=\"container\">\n <div id=\"topmenu\" style=\"height:35px;\">some buttons</div>\n <div id=\"tablelist\" style=\"width:100%;overflow:auto;\">\n <table class=\"tablesorterw\">.....</table>\n </div>\n</div>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
302,759
<p>One of the web apps I'm working on has a fairly small web store / shopping cart. As the client company is physically located in CA and has a physical location there, they're required to collect CA sales tax on all orders shipped to locations in California.</p> <p>For those who don't know, CA has some fairly complex sales tax rules where, essentially, any local group can create a "tax district" and leverage an extra few cents worth of sales tax on top of the state-wide base of 7.25%. (Usually less than 1% extra.) These districts don't have to map to any other legislative borders, so you can end up with half a city paying an extra .25% sales tax, for example.</p> <p>Technically, the law only requires that you charge the sales tax rate in your location as a seller - so, if I have a store here in Sacramento, I only need to charge Sacramento sales taxes on all orders shipped.</p> <p>However, for various accounting and tax declaration reasons, it's actually easier to charge the sales tax of the location the order is being shipped <em>to</em>. (Which means a different sales tax, potentially, on every single order.)</p> <p>So - my question. Is anyone aware of any slick ways to calculate this? The data you need to actually do the work is all available in a variety of semi-useful formats at the state Board of Equalization website, and we're knocking together a widget that tries to figure out sales tax based on things like city name and zip code. But, I was wondering if anyone has come across any cool tools out there for solving this problem. (Or any tools at all, for that matter.)</p> <p>(We're using VB and ASP.net, but I'd be interested in solutions for any language, mainly because I'm fascinated to see how other people have solved this.)</p> <p>Addendum - answering some questions from below:</p> <p>Tim asks how this can possibly be "easier." I'm told that doing sales tax this way makes filling out your tax return simpler. I'm bleary on the details, but as I understand it, if you don't charge the rate for the shipping location, you have to justify why you didn't for every single order at the end of the year - namely, you have to attest that no, we live <em>here</em> and not <em>there</em>, so we charge the rate <em>here.</em></p> <p>Whereas if you always charge the destination rate, you can (apparently) just put down the total amount of sales tax you collected for the whole year on one line, and say "sales tax was this much.</p> <p>It would seem the state doesn't care which you do. So, by "easier," I really mean "easier for the accountants" - which is of course in no way easier for us here on the programming team.</p> <p>Also, Schnapple's Texas story is a potential solution. (In fact, I pitched this very idea this morning.) CA really doesn't care if you overcharge sales tax, as long as you don't undercharge and hand over everything you collect. The problem here is, unlike Texas (apparently) vast swathes of CA are not in a special tax district. So, while we <em>could</em> charge the highest level for everyone (which I think is 8.75 at the moment), most of the customers would mind not playing their normal rate of 7.25. And I guess I can't blame them.</p>
[ { "answer_id": 303604, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 1, "selected": false, "text": "Auth Start$ End$ Rate Base \nNY 0 109.99 0% $0.00\nNY 110.00 - 4% $4.40\nNYALB 0 - 4% $0.00\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
302,775
<p>I need a way of calling a web page from inside my .net appliction. </p> <p>But i just want to send a request to the page and not worry about the response. </p> <p>As there are times when the response can take a while so i dont want it to hang the appliction. </p> <p>I have been trying in side the page_load event</p> <pre><code>WebClient webC = new WebClient(); Uri newUri = new Uri("http://localhost:49268/dosomething.aspx"); webC.UploadStringAsync(newUri, string.Empty); </code></pre> <p>Even though its set to Async, it still seams to hang as the page wont finish rendering until the threads have finsished</p>
[ { "answer_id": 302787, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "System.Net.WebClient DownloadDataAsync()" }, { "answer_id": 302788, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 3, "selected": false, "text": "Thread myThread = new Thread(new ThreadStart(myMethodThatDoHttp));\n myThread.Start();\npublic void myMethodThatDoHttp()\n{\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://www..com\");\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n}\n" }, { "answer_id": 302793, "author": "baretta", "author_id": 30052, "author_profile": "https://Stackoverflow.com/users/30052", "pm_score": 2, "selected": false, "text": "System.Net.WebClient.DownloadDataAsync/DownloadFileAsync DownloadDataCompleted/DownloadFileCompleted" }, { "answer_id": 302808, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 4, "selected": false, "text": "System.Net.WebClient client = new System.Net.WebClient();\nclient.DownloadDataAsync(new Uri(\"http://some.url.com/some/resource.html\"));\n" }, { "answer_id": 303036, "author": "TheAlbear", "author_id": 27922, "author_profile": "https://Stackoverflow.com/users/27922", "pm_score": 5, "selected": true, "text": "WebRequest wr = WebRequest.Create(\"http://localhost:49268/dostuff.aspx\");\nwr.Timeout = 3500;\n\ntry\n{\n HttpWebResponse response = (HttpWebResponse)wr.GetResponse();\n}\ncatch (Exception ex)\n{\n //We know its going to fail but that dosent matter!!\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27922/" ]
302,781
<p>I have transferred a Classic asp site running on windows server 2003 to windows server 2008 but suddenly the below code has stopped working.</p> <pre><code>Const connStr_FC08 = "Provider=SQLNCLI10;Server=DS-47500;Database=TestDB;Uid=TestLogin;Pwd=test;Network=dbmssocn;" Function connDB(OpenDB) DIM conn SET conn = Server.CreateObject("ADODB.Connection") conn.open = connStr_FC08 If OpenDB = "Y" Then conn.open connDB = conn End Function dim cn, cmd cn = connDB("Y") response.Write(cn.state) </code></pre> <p>This returns the below error</p> <pre><code>Microsoft VBScript runtime error '800a01a8' Object required: 'Provider=SQLNCLI10.1' </code></pre> <p>This happens on the below line</p> <pre><code>response.write(cn.state) </code></pre> <p>Thanks Chris</p>
[ { "answer_id": 310736, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 2, "selected": false, "text": " ...\n conn.open = connStr_FC08\n ...\n connDB = conn\n...\ncn = connDB(\"Y\")\n ...\n conn.ConnectionString = connStr_FC08\n ...\n Set connDB = conn\n...\nSet cn = connDB(\"Y\")\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,782
<p>How can I accomplish this?</p> <pre><code>&lt;% for agent in @broker.agents %&gt; ... &lt;% if agent.cell %&gt;&lt;span class="cell-number"&gt;Cell: &lt;%= agent.cell %&gt;&lt;/span&gt;&lt;% end %&gt; ... &lt;% end %&gt; </code></pre> <p>I want to test to see if the agent has a cell number, and if so, display what's inside the conditional. What I have currently doesn't seem to work; it just displays "Cell: ".</p> <p>Thoughts?</p>
[ { "answer_id": 302827, "author": "neezer", "author_id": 32154, "author_profile": "https://Stackoverflow.com/users/32154", "pm_score": 3, "selected": false, "text": "if !agent.cell.blank?\n" }, { "answer_id": 302868, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 5, "selected": true, "text": "<% for agent in @broker.agents %>\n <% unless agent.cell.blank? %>\n <span class=\"cell-number\">Cell: <%= agent.cell %></span>\n <% end %>\n<% end %>\n <% for agent in @broker.agents %>\n <span class=\"cell-number\">\n Cell: <%= agent.cell? ? \"none given\" : agent.cell %>\n </span>\n<% end %>\n" }, { "answer_id": 307302, "author": "Sarah Vessels", "author_id": 38743, "author_profile": "https://Stackoverflow.com/users/38743", "pm_score": 0, "selected": false, "text": "<% @broker.agents.each do |agent| %>\n ...\n <% unless agent.cell.empty? %>\n <span class=\"cell-number\">Cell: <%= agent.cell %></span>\n <% end %>\n ...\n<% end %>\n unless cell.empty?" }, { "answer_id": 39212101, "author": "techdreams", "author_id": 2936491, "author_profile": "https://Stackoverflow.com/users/2936491", "pm_score": 4, "selected": false, "text": ".empty? 2.2.2 :037 > object.attribute\n=> nil\n2.2.2 :025 > object.attribute.empty?\nNoMethodError: undefined method `empty?' for nil:NilClass\n 2.2.2 :037 > object.attribute\n=> \"\"\n2.2.2 :025 > object.attribute.empty?\ntrue\n 2.2.2 :041 > object.attribute\n=> \" \" \n2.2.2 :042 > object.attribute.empty?\n=> false\n 2.2.2 :045 > object.attribute\n => \"some value\" \n2.2.2 :046 > object.attribute.empty?\n => false \n .nil? 2.2.2 :049 > object.attribute\n => nil \n2.2.2 :050 > object.attribute.nil?\n => true\n 2.2.2 :053 > object.attribute\n => \"\" \n2.2.2 :054 > object.attribute.nil?\n => false \n 2.2.2 :057 > object.attribute\n => \" \" \n2.2.2 :058 > object.attribute.nil?\n => false \n 2.2.2 :061 > object.attribute\n => \"some value\" \n2.2.2 :062 > object.attribute.nil?\n => false\n .blank? 2.2.2 :065 > object.attribute\n => nil \n2.2.2 :066 > object.attribute.blank?\n => true\n 2.2.2 :069 > object.attribute\n => \"\" \n2.2.2 :070 > object.attribute.blank?\n => true \n 2.2.2 :073 > object.attribute\n => \" \" \n2.2.2 :074 > object.attribute.blank?\n => true \n 2.2.2 :075 > object.attribute\n => \"some value\" \n2.2.2 :076 > object.attribute.blank?\n => false \n .present? 2.2.2 :088 > object.attribute\n => nil \n2.2.2 :089 > object.attribute.present?\n => false\n 2.2.2 :092 > object.attribute\n => \"\" \n2.2.2 :093 > object.attribute.present?\n => false\n 2.2.2 :096 > object.attribute\n => \" \" \n2.2.2 :097 > object.attribute.present?\n => false \n 2.2.2 :100 > object.attribute\n => \"some value\" \n2.2.2 :101 > object.attribute.present?\n => true \n" }, { "answer_id": 59577665, "author": "Arun Kumar", "author_id": 12569830, "author_profile": "https://Stackoverflow.com/users/12569830", "pm_score": 0, "selected": false, "text": "Model.column == \"\"" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
302,789
<p>My rails model has code that is attempting to <code>define_method(method_name)</code> inside the model.</p> <p>I keep getting:</p> <pre><code>NoMethodError: undefined method `define_method' </code></pre> <p>What am I doing wrong? Am I doing this in the wrong place. I need this method attached to this model. Where else can I define this method?</p> <p>EDIT: For those asking to see the code:</p> <pre><code>for field in rdev_fields next if self.attributes.include?(field) count = count + 1 rdev_hash[field.to_sym] = self.attributes["attribute#{count}"] if !self.respond_to?(field) then define_method("#{field}") do self.send("attribute#{count}".to_sym) end end end </code></pre>
[ { "answer_id": 302950, "author": "Tim Harding", "author_id": 38021, "author_profile": "https://Stackoverflow.com/users/38021", "pm_score": 2, "selected": false, "text": "class User < ActiveRecord::Base\n\n def foo\n (class << self; self; end).class_eval do\n define_method(:bar) {puts \"bar\"}\n end\n end\nend\n\nu = User.first\nu.foo\nu.bar #=> \"bar\"\n" }, { "answer_id": 303744, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": true, "text": "class Cow\n define_method \"speak\" do\n \"MOOOO\"\n end\nend\n\nCow.new.speak\n=> \"MOOOO\"\n class Cow\n def add_speak\n self.class.send(:define_method, :speak) do\n \"MOOOO added\"\n end\n end\nend\n\nCow.new.speak\nNoMethodError: undefined method 'speak' for #<Cow:0xb7c48530>\n\nCow.new.add_speak\nCow.new.speak\n=> \"MOOOO added\"\n send(:define_method) define_method define_method class Cow\n def add_speak_just_me\n class << self\n define_method \"speak\" do\n \"MOOOO added for just me\"\n end\n end\n end\nend\n\nCow.new.speak\nNoMethodError: undefined method 'speak' for #<Cow:0xb7c72b78>\n\nc = Cow.new\nc.add_speak_just_me\nc.speak\n=> \"MOOOO added for just me\" # it works, hooray\n\nCow.new.speak # this new cow doesn't have the method, it hasn't been automatically added\nNoMethodError: undefined method `speak' for #<Cow:0xb7c65b1c>\n" }, { "answer_id": 27001875, "author": "Kabir Sarin", "author_id": 1181570, "author_profile": "https://Stackoverflow.com/users/1181570", "pm_score": 3, "selected": false, "text": "define_method define_singleton_method" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
302,794
<p>I'm being asked to look into a problem that occurs intermittently on a WebServer running my team's application.</p> <p>Essentially, we have a webservice that does a lookup between codes. If you have Code Type A, you can use it to look up the corresponding Code Type B. Periodically, when memory is running low, when this webservice is called, a null reference exception is being thrown. Essentially, this service loads a lookup file into cache with a dependency on the file, so if the file chages, the cache is reloaded with the new file. The priority on the cache object is set to default. I'm guessing that somewhere in the code, it isn't being verified that the cache object is still there and when memory on the server gets low, that object is dumped causing the error. I'd like to be able to recreate the error and verify before I start digging into this code.</p> <p>Is there a way in IIS manager (or from the command prompt) to force a running web app to dump it's cache? I would think that this should recreate the condition and therefore recreate the bug. Not to mention, seeing the detail error should lead to the right section of code.</p> <p>Thanks,</p> <p>Steve Brouillard</p>
[ { "answer_id": 302950, "author": "Tim Harding", "author_id": 38021, "author_profile": "https://Stackoverflow.com/users/38021", "pm_score": 2, "selected": false, "text": "class User < ActiveRecord::Base\n\n def foo\n (class << self; self; end).class_eval do\n define_method(:bar) {puts \"bar\"}\n end\n end\nend\n\nu = User.first\nu.foo\nu.bar #=> \"bar\"\n" }, { "answer_id": 303744, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 7, "selected": true, "text": "class Cow\n define_method \"speak\" do\n \"MOOOO\"\n end\nend\n\nCow.new.speak\n=> \"MOOOO\"\n class Cow\n def add_speak\n self.class.send(:define_method, :speak) do\n \"MOOOO added\"\n end\n end\nend\n\nCow.new.speak\nNoMethodError: undefined method 'speak' for #<Cow:0xb7c48530>\n\nCow.new.add_speak\nCow.new.speak\n=> \"MOOOO added\"\n send(:define_method) define_method define_method class Cow\n def add_speak_just_me\n class << self\n define_method \"speak\" do\n \"MOOOO added for just me\"\n end\n end\n end\nend\n\nCow.new.speak\nNoMethodError: undefined method 'speak' for #<Cow:0xb7c72b78>\n\nc = Cow.new\nc.add_speak_just_me\nc.speak\n=> \"MOOOO added for just me\" # it works, hooray\n\nCow.new.speak # this new cow doesn't have the method, it hasn't been automatically added\nNoMethodError: undefined method `speak' for #<Cow:0xb7c65b1c>\n" }, { "answer_id": 27001875, "author": "Kabir Sarin", "author_id": 1181570, "author_profile": "https://Stackoverflow.com/users/1181570", "pm_score": 3, "selected": false, "text": "define_method define_singleton_method" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26516/" ]
302,819
<p>I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,</p> <ul> <li>Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?</li> <li>Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?</li> </ul>
[ { "answer_id": 302933, "author": "Jacob Adams", "author_id": 32518, "author_profile": "https://Stackoverflow.com/users/32518", "pm_score": 2, "selected": false, "text": "private delegate void UpdateHandler(string message);\nprivate UpdateHandler Update;\n\npublic void Register(IObserver observer)\n{\n Update+=observer.Update;\n}\n\npublic void Unregister(IObserver observer)\n{\n Update-=observer.Update;\n}\n\npublic void Notify(string message)\n{\n Update(message);\n}\n public Subject()\n{\n observers = new List<IObserver>();\n}\n\npublic void Register(IObserver observer)\n{\n observers.Add(observer);\n}\n\npublic void Unregister(IObserver observer)\n{\n observers.Remove(observer);\n}\n\npublic void Notify(string message)\n{\n // call update method for every observer\n foreach (IObserver observer in observers)\n {\n observer.Update(message);\n }\n}\n public delegate void UpdateHandler(string message);\nprivate UpdateHandler Update;\n\npublic void Register(UpdateHandler observerRoutine)\n{\n Update+=observerRoutine;\n}\n\npublic void Unregister(UpdateHandler observerRoutine)\n{\n Update-=observerRoutine;\n}\n\npublic void Notify(string message)\n{\n Update(message);\n}\n" }, { "answer_id": 3134638, "author": "Ben M", "author_id": 137624, "author_profile": "https://Stackoverflow.com/users/137624", "pm_score": 5, "selected": false, "text": "enum TaskStatus\n{\n Started,\n StillProcessing,\n Finished\n}\n\ndelegate void CallbackDelegate(Task t, TaskStatus status);\n\nclass Task\n{\n public void Start(CallbackDelegate callback)\n {\n callback(this, TaskStatus.Started);\n\n // calculate PI to 1 billion digits\n for (...)\n {\n callback(this, TaskStatus.StillProcessing);\n }\n\n callback(this, TaskStatus.Finished);\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Task t = new Task();\n t.Start(new CallbackDelegate(MyCallbackMethod));\n }\n\n static void MyCallbackMethod(Task t, TaskStatus status)\n {\n Console.WriteLine(\"The task status is {0}\", status);\n }\n}\n Task" }, { "answer_id": 4488288, "author": "Pritom Nandy", "author_id": 548420, "author_profile": "https://Stackoverflow.com/users/548420", "pm_score": 0, "selected": false, "text": "public delegate string TestDelegate();\nprotected void Page_Load(object sender, EventArgs e)\n{\n TestDelegate TD1 = new TestDelegate(DiaplayMethodD1);\n TestDelegate TD2 = new TestDelegate(DiaplayMethodD2);\n TD2 = TD1 + TD2; // Make TD2 as multi-cast delegate\n lblDisplay.Text = TD1(); // invoke delegate\n lblAnotherDisplay.Text = TD2();\n\n\n // Note: Using a delegate allows the programmer to encapsulate a reference \n // to a method inside a delegate object. Its like the function pointer\n // in C or C++. \n}\n//the Signature has to be same.\npublic string DiaplayMethodD1()\n{\n //lblDisplay.Text = \"Multi-Cast Delegate on EXECUTION\"; // Enable on multi-cast \n return \"This is returned from the first method of delegate explanation\";\n}\n// The Method can be static also\npublic static string DiaplayMethodD2()\n{\n return \" Extra words from second method\";\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,820
<p>Anyone getting this error when using the new free chart controls MS bought from Dundas?</p> <p>"Error executing child request for ChartImg.axd"</p> <p>On the MSDN forum they suggested it was my web.config: <a href="http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/1dc4b352-c9a5-49dc-8f35-9b176509faa1/" rel="noreferrer">MSDN forum post</a></p> <p>So far that hasn't fixed the problem though. Any other ideas?</p>
[ { "answer_id": 335363, "author": "LaptopHeaven", "author_id": 1296, "author_profile": "https://Stackoverflow.com/users/1296", "pm_score": 4, "selected": false, "text": "<add path=\"ChartImg.axd\" verb=\"GET,HEAD\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />\n" }, { "answer_id": 438251, "author": "Paul Looijmans", "author_id": 54076, "author_profile": "https://Stackoverflow.com/users/54076", "pm_score": 7, "selected": true, "text": "<add path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />\n" }, { "answer_id": 3303931, "author": "RunnerRick", "author_id": 392176, "author_profile": "https://Stackoverflow.com/users/392176", "pm_score": 1, "selected": false, "text": "routes.IgnoreRoute(\"{controller}/{resource}.axd/{*pathInfo}\");\n" }, { "answer_id": 5356070, "author": "backpacker", "author_id": 666504, "author_profile": "https://Stackoverflow.com/users/666504", "pm_score": 3, "selected": false, "text": " <appSettings>\n <add key=\"ChartImageHandler\" value=\"storage=file;timeout=20;dir=c:\\TempImageFiles\\;\" />\n</appSettings>\n\n<httpHandlers>\n...\n <add path=\"ChartImg.axd\" verb=\"GET,HEAD\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />\n...\n</httpHandlers>\n\n<handlers>\n...\n <add name=\"ChartImageHandler\" preCondition=\"integratedMode\" verb=\"GET,HEAD\" path=\"ChartImg.axd\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n\n...\n</handlers>\n" }, { "answer_id": 5477504, "author": "Sergio", "author_id": 682678, "author_profile": "https://Stackoverflow.com/users/682678", "pm_score": 3, "selected": false, "text": "<add path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />\n" }, { "answer_id": 6459150, "author": "n8CodeGuru", "author_id": 311864, "author_profile": "https://Stackoverflow.com/users/311864", "pm_score": 0, "selected": false, "text": "<add path=\"ChartImg.axd\" verb=\"GET,HEAD\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\"/>\n" }, { "answer_id": 6761803, "author": "Zach Green", "author_id": 264650, "author_profile": "https://Stackoverflow.com/users/264650", "pm_score": 0, "selected": false, "text": " <add name=\"ChartImg\" verb=\"*\" path=\"ChartImg.axd\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n" }, { "answer_id": 36990217, "author": "Mohamed Rasik", "author_id": 6066552, "author_profile": "https://Stackoverflow.com/users/6066552", "pm_score": 1, "selected": false, "text": "<system.webServer>\n <validation validateIntegratedModeConfiguration=\"false\"/>\n <handlers>\n <remove name=\"ChartImageHandler\"/>\n <add name=\"ChartImageHandler\" preCondition=\"integratedMode\" verb=\"GET,HEAD,POST\" path=\"ChartImg.axd\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n </handlers>\n </system.webServer>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5115/" ]
302,821
<p>I have a simple 2D array of strings and I would like to stuff it into an SPFieldMultiLineText in MOSS. This maps to an ntext database field.</p> <p>I know I can serialize to XML and store to the file system, but I would like to serialize without touching the filesystem.</p> <pre><code>public override void ItemAdding(SPItemEventProperties properties) { // build the array List&lt;List&lt;string&gt;&gt; matrix = new List&lt;List&lt;string&gt;&gt;(); /* * populating the array is snipped, works fine */ // now stick this matrix into the field in my list item properties.AfterProperties["myNoteField"] = matrix; // throws an error } </code></pre> <p>Looks like I should be able to do something like this:</p> <pre><code>XmlSerializer s = new XmlSerializer(typeof(List&lt;List&lt;string&gt;&gt;)); properties.AfterProperties["myNoteField"] = s.Serialize.ToString(); </code></pre> <p>but that doesn't work. All the examples I've found demonstrate writing to a text file.</p>
[ { "answer_id": 302891, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 6, "selected": true, "text": "StringWriter outStream = new StringWriter();\nXmlSerializer s = new XmlSerializer(typeof(List<List<string>>));\ns.Serialize(outStream, myObj);\nproperties.AfterProperties[\"myNoteField\"] = outStream.ToString();\n" }, { "answer_id": 302892, "author": "JSC", "author_id": 37311, "author_profile": "https://Stackoverflow.com/users/37311", "pm_score": 2, "selected": false, "text": "Public Shared Function SerializeToByteArray(ByVal object2Serialize As Object) As Byte()\n Using stream As New MemoryStream\n Dim xmlSerializer As New XmlSerializer(object2Serialize.GetType())\n xmlSerializer.Serialize(stream, object2Serialize)\n Return stream.ToArray()\n End Using\nEnd Function\n\nPublic Shared Function SerializeToString(ByVal object2Serialize As Object) As String\n Dim bytes As Bytes() = SerializeToByteArray(object2Serialize)\n Return Text.UTF8Encoding.GetString(bytes)\nEnd Function\n public byte[] SerializeToByteArray(object object2Serialize) {\n using(MemoryStream stream = new MemoryStream()) {\n XmlSerializer xmlSerializer = new XmlSerializer(object2Serialize.GetType());\n xmlSerializer.Serialize(stream, object2Serialize);\n return stream.ToArray();\n }\n}\n\npublic string SerializeToString(object object2Serialize) {\n byte[] bytes = SerializeToByteArray(object2Serialize);\n return Text.UTF8Encoding.GetString(bytes);\n}\n" }, { "answer_id": 302905, "author": "Paul Sonier", "author_id": 28053, "author_profile": "https://Stackoverflow.com/users/28053", "pm_score": 3, "selected": false, "text": "XmlSerializer s = new XmlSerializer(typeof(whatever));\nTextWriter w = new StringWriter();\ns.Serialize(w, whatever);\nyourstring = w.ToString();\n" }, { "answer_id": 303308, "author": "Harrison", "author_id": 38615, "author_profile": "https://Stackoverflow.com/users/38615", "pm_score": 4, "selected": false, "text": " public string SerializeObject<T>(T objectToSerialize)\n {\n BinaryFormatter bf = new BinaryFormatter();\n MemoryStream memStr = new MemoryStream();\n\n try\n {\n bf.Serialize(memStr, objectToSerialize);\n memStr.Position = 0;\n\n return Convert.ToBase64String(memStr.ToArray());\n }\n finally\n {\n memStr.Close();\n }\n }\n SerializeObject<List<string>>(matrix);\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753/" ]
302,829
<p>I was trying to access swf from javascript, so this example in livedocs is what I'm trying to modify. <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#includeExamplesSummary" rel="nofollow noreferrer">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#includeExamplesSummary</a></p> <p>However,it is not working correctly for some reason. The problem I'm encountering is that it does not work in Safari and in Firefox, it only works if I put an alert in the function before javascript pass the value to swf. (seems like it needs some time) I also tried to set a timer in as3, but timer doesn't work, only alert in js helps.</p> <p>All I wanted to do is use js to tell the swf file to play ep1.swf. Here's my js code:</p> <pre><code>document.observe('dom:loaded', function() { $('episode1').observe('click', function() { var params = {wmode : "transparent", allowScriptAccess:"always", movie:"header"}; swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0","expressInstall.swf", "", params, ""); sendToActionScript("ep1.swf"); }); }) function thisMovie(movieName) { if (navigator.appName.indexOf("Microsoft") != -1) { return window[movieName]; } else { //alert("aaa") return document[movieName]; } } function sendToActionScript(value) { thisMovie('header').sendToActionScript(value); } </code></pre> <p>Here's my as3 code:</p> <pre><code>private function receivedFromJavaScript(value:String):void { loader.load(new URLRequest(value)); } </code></pre> <p>I've been trying for a really long time, does anyone know how to fix this? Thanks.</p>
[ { "answer_id": 607328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "AC_RunActiveContent.js fvar_js AC_FL_RunContent(\n ...\n 'src', 'fvar_js',\n ...\n thisMovie fvar_js if (ExternalInterface.available) {\n ExternalInterface.addCallback(\"js_to_as_f\", js_from_as_f);\n}\n js_from_as_f var timeoutId;\nvar js_initiate_callback = function() {\n // This is the swf object:\n fvar_js.js_to_as_f();\n clearTimeout ( timeoutId );\n}\nvar reset_fvar_f = function(new_val) {\n fvar_val = new_val;\n}\n//js_initiate_callback();\ntimeoutId = setTimeout(js_initiate_callback, 1000);\n" }, { "answer_id": 7320788, "author": "abasan", "author_id": 930778, "author_profile": "https://Stackoverflow.com/users/930778", "pm_score": 1, "selected": false, "text": "function GetSWF(strName) {\n if (window.document[strName] != null) {\n if (window.document[strName].length == null)\n return window.document[strName];\n else\n return window.document[strName][1];\n } else {\n if (document[strName].length == null)\n return document[strName];\n else\n return document[strName][1];\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
302,833
<p>I want to use a case statement in my user-defined functions because I need to match on a number of terms. I could use a table for the matches but then I wouldn't be able to put it inside the Computed Column definition. </p> <p>This works with IF statements:</p> <pre><code>CREATE FUNCTION MaraSizeNumber ( @ms varchar ) RETURNS varchar AS BEGIN IF ms = '16-18' RETURN '1' ELSE IF ms = '18-20' RETURN '2' ELSE IF ms = '20-22' RETURN '3' ELSE IF ms = '22+' RETURN '4' ELSE IF ms = '24+' RETURN '5' ELSE IF ms = '14-16' RETURN '7' ELSE RETURN 'BAD' END </code></pre> <p>But with the original style using a CASE...WHEN THEN BLOCK I get an error message.</p> <pre><code>CREATE FUNCTION MaraSizeCaseExample ( @ms varchar ) RETURNS varchar AS BEGIN CASE ms WHEN '16-18' THEN RETURN '1' WHEN '18-20' THEN RETURN '2' WHEN '20-22' THEN RETURN '3' WHEN '22+' THEN RETURN '4' WHEN '24+' THEN RETURN '5' WHEN '14-16' THEN RETURN '7' ELSE RETURN 'BAD' END END </code></pre> <p>I get an error of Incorrect Syntax near case and incorrect syntax near when for my when parts.</p> <p>I have correctly batched everything up because my last CREATE FUNCTION block ends with the GO, and according to the documentation on CASE, I have the right syntax.</p> <p>I have a larger scalar function I'm building that will use the other scalar functions to generate the production coding in our system corresponding to other parameters. It would be best to be able to use CASE because the production coding depends on the product and the customer.</p> <p>I also get an extra error in the second example at my Create Function line that says, "Incorrect Syntax: 'Create Function' must be the only statement in the batch", but with everything else identical I don't get that error with the IFs.</p> <p>What am I doing wrong, or are CASES only allowed in SQL queries rather than scalar functions? The error messages are coming from SQL Server Management Studio's squiggle error message system.</p>
[ { "answer_id": 302841, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 3, "selected": true, "text": "RETURN CASE @ms\n WHEN '16-18' THEN '1'\n WHEN '18-20' THEN '2'\n WHEN '20-22' THEN '3'\n WHEN '22+' THEN '4'\n WHEN '24+' THEN '5'\n WHEN '14-16' THEN '7'\n ELSE 'BAD'\n END\n" }, { "answer_id": 302913, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "@ PRINT dbo.SizeExample('16-18') 'B' '1' CREATE FUNCTION MaraSizeExample\n(\n @ms varchar(5)\n)\nRETURNS varchar(3)\nAS\nBEGIN\n RETURN CASE @ms\n WHEN '16-18' THEN '1'\n WHEN '18-20' THEN '2'\n WHEN '20-22' THEN '3'\n WHEN '22+' THEN '4'\n WHEN '24+' THEN '5'\n WHEN '14-16' THEN '7'\n ELSE 'BAD'\n END\nEND\n CASE RETURN IIF() IF() VARCHAR VARCHAR(1) 'BAD' 'B' SQL INSERT @ms T-SQL @" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26140/" ]
302,835
<p>can someone give a scons config file which allows the following structure</p> <pre><code>toplevel/ /src - .cc files /include .h files </code></pre> <p>at top level I want the o and final exe.</p>
[ { "answer_id": 302984, "author": "Amit", "author_id": 29120, "author_profile": "https://Stackoverflow.com/users/29120", "pm_score": 3, "selected": false, "text": "env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc',\n CPPDEFINES=[],\n LIBS=['glib-2.0']) \nenv.Program('runme', Glob('src/*.c'))\n" }, { "answer_id": 303597, "author": "RichieHH", "author_id": 37370, "author_profile": "https://Stackoverflow.com/users/37370", "pm_score": 3, "selected": true, "text": "env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include',\n CPPDEFINES=[],\n LIBS=['glib-2.0']) \n\nif ARGUMENTS.get('debug', 0):\n env.Append(CCFLAGS = ' -g')\n\nenv.Program('template', Glob('src/*.cc'))\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37370/" ]
302,837
<p>Parsing a text file in vb.net and need to locate the latitude and longitude in these two sections of text. The patter is 6 digits space 7 digits (364800 0953600). The samples are from two different map files and have slightly differing formats.</p> <pre><code>I 2H02 364800 0953600 ' SEC72 10496300- I 2H05 360100 0953645 ' ZFW J602 ZME 2A93 10496400- I 2H06 361215 0952400 ' SEC72 ZME 2A75 10496500- I 2H07 361715 0951145 ' SEC27/72 ZME 2A78 10496600- I 2H08 362025 0950100 ' TUL ZME 2A69 10496700- I 2H10 360800 0952915 ' ZME 2A85 10496800- I 2H11 362500 0955015 ' SEC62/72 10496900- I 2H14 364145 0954315 ' TUL 10497000- I A85A 'AL851 50591 REF 33393944 391500 0831100 ' 50591 REF 33393945 I A85B 'AL851 50591 REF 33393946 374500 0825700 ' 50591 REF 33393947 I A87A 'AL871 111592 REF 33393948 402050 0814420 ' 111592 REF 33393949 I A87B 'AL871 111592 REF 33393950 400449 0814400 ' 111592 REF 33393951 I A87C 'AL872 '030394 GDK 33393952 392000 0810000 ' '030394 GDK 33393953 </code></pre> <p>Thanks,</p> <p>Dave</p>
[ { "answer_id": 302862, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "[0-9]{6} [0-9]{7}\n" }, { "answer_id": 302876, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "(?<First>\\d{6})\\s(?<Second>\\d{7})\n" }, { "answer_id": 302881, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 4, "selected": true, "text": "Dim matches As MatchCollection\nDim regex As New Regex(\"\\d{6} \\d{7}\")\nmatches = regex.Matches(your_text_string)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38349/" ]
302,839
<p>I have a user control that I load into a <code>MainWindow</code> at runtime. I cannot get a handle on the containing window from the <code>UserControl</code>. </p> <p>I have tried <code>this.Parent</code>, but it's always null. Does anyone know how to get a handle to the containing window from a user control in WPF?</p> <p>Here is how the control is loaded:</p> <pre><code>private void XMLLogViewer_MenuItem_Click(object sender, RoutedEventArgs e) { MenuItem application = sender as MenuItem; string parameter = application.CommandParameter as string; string controlName = parameter; if (uxPanel.Children.Count == 0) { System.Runtime.Remoting.ObjectHandle instance = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, controlName); UserControl control = instance.Unwrap() as UserControl; this.LoadControl(control); } } private void LoadControl(UserControl control) { if (uxPanel.Children.Count &gt; 0) { foreach (UIElement ctrl in uxPanel.Children) { if (ctrl.GetType() != control.GetType()) { this.SetControl(control); } } } else { this.SetControl(control); } } private void SetControl(UserControl control) { control.Width = uxPanel.Width; control.Height = uxPanel.Height; uxPanel.Children.Add(control); } </code></pre>
[ { "answer_id": 302953, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 4, "selected": false, "text": "public static Window FindParentWindow(DependencyObject child)\n{\n DependencyObject parent= VisualTreeHelper.GetParent(child);\n\n //CHeck if this is the end of the tree\n if (parent == null) return null;\n\n Window parentWindow = parent as Window;\n if (parentWindow != null)\n {\n return parentWindow;\n }\n else\n {\n //use recursion until it reaches a Window\n return FindParentWindow(parent);\n }\n}\n" }, { "answer_id": 304604, "author": "Ian Oakes", "author_id": 21606, "author_profile": "https://Stackoverflow.com/users/21606", "pm_score": 9, "selected": false, "text": "Window parentWindow = Window.GetWindow(userControlReference);\n GetWindow GetWindow null this.Loaded += new RoutedEventHandler(UserControl_Loaded); \n" }, { "answer_id": 527173, "author": "Alan Le", "author_id": 1133, "author_profile": "https://Stackoverflow.com/users/1133", "pm_score": 4, "selected": false, "text": "public MainView()\n{\n InitializeComponent();\n\n this.Loaded += new RoutedEventHandler(MainView_Loaded);\n}\n\nvoid MainView_Loaded(object sender, RoutedEventArgs e)\n{\n Window parentWindow = Window.GetWindow(this);\n\n ...\n}\n" }, { "answer_id": 6048435, "author": "Eric Coulson", "author_id": 759649, "author_profile": "https://Stackoverflow.com/users/759649", "pm_score": 3, "selected": false, "text": "DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);\n\npublic static class ExVisualTreeHelper\n{\n /// <summary>\n /// Finds the visual parent.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"sender\">The sender.</param>\n /// <returns></returns>\n public static T FindVisualParent<T>(DependencyObject sender) where T : DependencyObject\n {\n if (sender == null)\n {\n return (null);\n }\n else if (VisualTreeHelper.GetParent(sender) is T)\n {\n return (VisualTreeHelper.GetParent(sender) as T);\n }\n else\n {\n DependencyObject parent = VisualTreeHelper.GetParent(sender);\n return (FindVisualParent<T>(parent));\n }\n } \n}\n" }, { "answer_id": 6048516, "author": "Eric Coulson", "author_id": 759649, "author_profile": "https://Stackoverflow.com/users/759649", "pm_score": 1, "selected": false, "text": "DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);\n" }, { "answer_id": 9565982, "author": "Anthony Main", "author_id": 258, "author_profile": "https://Stackoverflow.com/users/258", "pm_score": 3, "selected": false, "text": "App.Current.MainWindow\n" }, { "answer_id": 12093749, "author": "Agus Syahputra", "author_id": 801454, "author_profile": "https://Stackoverflow.com/users/801454", "pm_score": 1, "selected": false, "text": "DependencyObject GetTopParent(DependencyObject current)\n{\n while (VisualTreeHelper.GetParent(current) != null)\n {\n current = VisualTreeHelper.GetParent(current);\n }\n return current;\n}\n\nDependencyObject parent = GetTopParent(thisUserControl);\n" }, { "answer_id": 16964472, "author": "Pnctovski", "author_id": 1740883, "author_profile": "https://Stackoverflow.com/users/1740883", "pm_score": 3, "selected": false, "text": "var main = App.Current.MainWindow as MainWindow;\n" }, { "answer_id": 17170433, "author": "Nalan Madheswaran", "author_id": 1217713, "author_profile": "https://Stackoverflow.com/users/1217713", "pm_score": 2, "selected": false, "text": "DependencyObject GetTopLevelControl(DependencyObject control)\n{\n DependencyObject tmp = control;\n DependencyObject parent = null;\n while((tmp = VisualTreeHelper.GetParent(tmp)) != null)\n {\n parent = tmp;\n }\n return parent;\n}\n" }, { "answer_id": 25167611, "author": "GordoFabulous", "author_id": 1775514, "author_profile": "https://Stackoverflow.com/users/1775514", "pm_score": 3, "selected": false, "text": "public static T TryFindParent<T>(DependencyObject current) where T : class\n{\n DependencyObject parent = VisualTreeHelper.GetParent(current);\n if( parent == null )\n parent = LogicalTreeHelper.GetParent(current);\n if( parent == null )\n return null;\n\n if( parent is T )\n return parent as T;\n else\n return TryFindParent<T>(parent);\n}\n" }, { "answer_id": 35945654, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 2, "selected": false, "text": "Window parentWindow = Window.GetWindow(userControlReference);\n DependencyObject parent = uiElement;\nint avoidInfiniteLoop = 0;\nwhile ((parent is Window)==false)\n{\n parent = VisualTreeHelper.GetParent(parent);\n avoidInfiniteLoop++;\n if (avoidInfiniteLoop == 1000)\n {\n // Something is wrong - we could not find the parent window.\n break;\n }\n}\nWindow window = parent as Window;\nwindow.DragMove();\n" }, { "answer_id": 37597301, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 0, "selected": false, "text": "Window MarkupExtension public sealed class MyExtension : MarkupExtension\n{\n public override object ProvideValue(IServiceProvider serviceProvider) =>\n new MyWrapper(ResolveRootObject(serviceProvider));\n object ResolveRootObject(IServiceProvider serviceProvider) => \n GetService<IRootObjectProvider>(serviceProvider).RootObject;\n}\n\nclass MyWrapper\n{\n object _rootObject;\n\n Window OwnerWindow() => WindowFromRootObject(_rootObject);\n\n static Window WindowFromRootObject(object root) =>\n (root as Window) ?? VisualParent<Window>((DependencyObject)root);\n static T VisualParent<T>(DependencyObject node) where T : class\n {\n if (node == null)\n throw new InvalidOperationException(\"Could not locate a parent \" + typeof(T).Name);\n var target = node as T;\n if (target != null)\n return target;\n return VisualParent<T>(VisualTreeHelper.GetParent(node));\n }\n}\n MyWrapper.Owner() Window UserControl Window" }, { "answer_id": 56805228, "author": "Tore Aurstad", "author_id": 741368, "author_profile": "https://Stackoverflow.com/users/741368", "pm_score": 0, "selected": false, "text": "public Window GetCurrentWindowOfType<TWindowType>(){\n return Application.Current.Windows.OfType<TWindowType>().FirstOrDefault() as Window;\n}\n" }, { "answer_id": 62206272, "author": "Szabolcs Antal", "author_id": 2036220, "author_profile": "https://Stackoverflow.com/users/2036220", "pm_score": 1, "selected": false, "text": "Window.GetWindow(userControl) InitializeComponent() OnInitialized OnInitialized" }, { "answer_id": 62794041, "author": "Lucaci Andrei", "author_id": 1432385, "author_profile": "https://Stackoverflow.com/users/1432385", "pm_score": 2, "selected": false, "text": "public static T FindParent<T>(DependencyObject current)\n where T : class \n{\n var dependency = current;\n\n while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null\n && !(dependency is T)) { }\n\n return dependency as T;\n}\n Parent" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39038/" ]
302,897
<p>I am making a mp3 id3tag editor, and a regex is not matching. Could anyone help me please? my code:</p> <pre><code>arquivo = "[coletanea] album [CD #] [faixa] [artista] musica.mp3" r = New Regex("^\[(?&lt;1&gt;[^\]]+?)\]\s*(?&lt;2&gt;[\w\s]+)\s*\[CD\s*(?&lt;3&gt;\d+)\]\s*\[(?&lt;4&gt;\d+)\]\s*\[(?&lt;5&gt;[^\]]+)\]\s*(?&lt;6&gt;.+)", RegexOptions.Compiled) m = r.Match(Mid(arquivo, 1, Len(arquivo) - 4)) If m.Success Then mAuthor = Trim(m.Groups(5).ToString) mWM_AlbumTitle = Trim(m.Groups(2).ToString) mWM_TrackNumber = Trim(m.Groups(4).ToString) mTitle = Trim(m.Groups(6).ToString) mWM_PartOfSet = Trim(m.Groups(3).ToString) mMW_AlbumArtist = Trim(m.Groups(1).ToString) End If </code></pre>
[ { "answer_id": 302929, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "\"[coletanea] album [CD 20] [89] [artista] musica.mp3\"\n" }, { "answer_id": 302931, "author": "Tjofras", "author_id": 37486, "author_profile": "https://Stackoverflow.com/users/37486", "pm_score": 1, "selected": false, "text": "\"[coletanea] album [CD 1] [1] [artista] musica.mp3\"\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,912
<p>I'm aware there is an AssociationChanged event, however, this event fires after the association is made. There is no AssociationChanging event. So, if I want to throw an exception for some validation reason, how do I do this and get back to my original value? </p> <p>Also, I would like to default values for my entity based on information from other entities <strong>but do this only when I know the entitiy is instanced for insertion into the database</strong>. How do I tell the difference between that and the object getting instanced because it is about to be populated based on existing data? Am I supposed to know? Is that considiered business logic that should be outside of my entity business logic? </p> <p>If that's the case, then should I be designing controller classes to wrap all these entities? My concern is that if I deliver back an entity, I want the client to get access to the properties, but I want to retain tight control over validations on how they are set, defaulted, etc. Every example I've seen references context, which is outside of my enity partial class validation, right? </p> <p>BTW, I looked at the EFPocoAdapter and for the life of me cannot determine how to populate lists of from within my POCO class... anyone know how I get to the context from a EFPoco Class? </p>
[ { "answer_id": 1301480, "author": "ADB", "author_id": 3610, "author_profile": "https://Stackoverflow.com/users/3610", "pm_score": 0, "selected": false, "text": "aTeacher.Students.Add(new Student)\n public Student AddNewStudent(string name, string studentID)\n{\n\n Student s = new Student( name, studentID);\n s.Teacher = this; // changes the association\n return s;\n}\n" }, { "answer_id": 1468692, "author": "MrWhite", "author_id": 115855, "author_profile": "https://Stackoverflow.com/users/115855", "pm_score": 0, "selected": false, "text": "getStudent(String studentName, long studentId, Teacher teacher) {\n return new Student(studentName, studentId);\n}\n\ngetStudentForDBInseration(String studentName, long studentId, Teacher teacher) {\n Student student = getStudent(studentName, studentId);\n student = teacher;\n //some entity frameworks need the student to be in the teachers student list\n //so you might need to add the student to the teachers student list\n teacher.addStudent(student);\n}\n" }, { "answer_id": 3463603, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "CancelEventArgs" }, { "answer_id": 4521723, "author": "TamusJRoyce", "author_id": 458321, "author_profile": "https://Stackoverflow.com/users/458321", "pm_score": 2, "selected": false, "text": "// PropertyName is the key, and the PropertyValue is the value.\nDictionary <string, object> propertyDict = new Dictionary<object, object>();\n\n // Convert this function prototype to C# from VBNet. I like how Handles is descriptive.\n Public Sub PropertyChanging(sender As object, e As PropertyChangingEventArgs) Handles Foo.PropertyChanging\n {\n if (sender == null || preventRecursion)\n {\n return;\n } // End if\n\n Type senderType = sender.GetType();\n PropertyInfo info = senderType.GetProperty(e.PropertyName);\n object propertyValue = info.GetValue(sender, null);\n\n // Change this so it checks if e.PropertyName already exists.\n propertyDict.Add(e.PropertyName, propertyValue);\n } // End PropertyChanging() Event\n\n // Convert this function prototype to C# from VBNet. I like how Handles is descriptive.\n Public Sub PropertyChanged(sender As object, e As PropertyChangedEventArgs) Handles Foo.PropertyChanged\n {\n if (sender == null || preventRecursion)\n {\n return;\n } // End if\n\n Type senderType = sender.GetType();\n PropertyInfo info = senderType.GetProperty(e.PropertyName);\n object propertyValue = info.GetValue(sender, null);\n\n // Change this so it makes sure e.PropertyName exists.\n object oldValue = propertyDict(e.PropertyName);\n object newValue = propertyValue;\n\n // No longer needed.\n propertyDict.Remove(e.PropertyName);\n\n if (/* some condition */)\n {\n try {\n preventRecursion = true;\n info.SetValue(oldValue, null);\n Throw New Exception();\n } finally {\n preventRecursion = false;\n } // End try\n } // End if\n } // End PropertyChanging() Event\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,914
<p>I'm looking for an implementation of CRC32 in C or C++ that is explicitly licensed as being no cost or public domain. The implementation <a href="http://www.networkdls.com/Software/View/CRC32" rel="noreferrer">here</a> seems nice, but the only thing it says about the license is "source code", which isn't good enough. I'd prefer non LGPL so I don't have to fool around with a DLL (my app is closed source). I saw the adler32 implementation in zlib, but I'm checking small chunks of data, which adler is not good for. </p>
[ { "answer_id": 303020, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": false, "text": "/* Copyright (C) 1986 Gary S. Brown. You may use this program, or\n code or tables extracted from it, as desired without restriction.*/\n BYTE DWORD #define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))\n" }, { "answer_id": 4588124, "author": "Nazar", "author_id": 469655, "author_profile": "https://Stackoverflow.com/users/469655", "pm_score": 2, "selected": false, "text": " MHASH td = mhash_init(MHASH_CRC32);\n\n if (td == MHASH_FAILED) return -1; // handle failure\n\n mhash(td, s, strlen(s));\n\n unsigned int digest = 0; // crc32 will be stored here\n\n mhash_deinit(td, &digest);\n\n // do endian swap here if desired\n" }, { "answer_id": 25018742, "author": "giuspen", "author_id": 468993, "author_profile": "https://Stackoverflow.com/users/468993", "pm_score": 4, "selected": false, "text": "#include <zlib.h>\nunsigned long crc = crc32(0L, Z_NULL, 0);\ncrc = crc32(crc, (const unsigned char*)data_address, data_len);\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23524/" ]
302,943
<p>I am looking to do the following (see pseudo code); I want to select 4 rows for each gd.id (7, 11 or 9). I've incorrectly use limit because that only brings up 4 rows in total. Anyone have an idea on how to change this query to accomplish my goal? </p> <pre><code>SELECT gd.gid, gd.aid, li.ads, li.til FROM gd JOIN li ON li.a_id = gd.aid WHERE gd.gid IN ( '7', '11', '9' ) ORDER BY li.timestamp DESC LIMIT 4 #FOR EACH ;-) </code></pre> <p>Thank you!</p> <p>Ice</p> <p>p.s. Maybe sometype of group_by?</p>
[ { "answer_id": 303384, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "CREATE TABLE gd (\n aid INT AUTO_INCREMENT PRIMARY KEY,\n gid INT\n);\n\nINSERT INTO gd (gid) VALUES\n (7), (7), (7), -- fewer than four rows\n (9), (9), (9), (9), -- exactly four rows\n (11), (11), (11), (11), (11); -- greater than four rows\n\nCREATE TABLE li (\n a_id INT AUTO_INCREMENT PRIMARY KEY,\n ads VARCHAR(10),\n til VARCHAR(10),\n `timestamp` TIMESTAMP\n);\n\nINSERT INTO li (ads, til, `timestamp`) VALUES\n ('foo1', 'bar1', '2008-01-01'),\n ('foo2', 'bar2', '2008-02-01'),\n ('foo3', 'bar3', '2008-03-01'),\n ('foo4', 'bar4', '2008-04-01'),\n ('foo5', 'bar5', '2008-05-01'),\n ('foo6', 'bar6', '2008-06-01'),\n ('foo7', 'bar7', '2008-07-01'),\n ('foo8', 'bar8', '2008-08-01'),\n ('foo9', 'bar9', '2008-09-01'),\n ('foo10', 'bar10', '2008-10-01'),\n ('foo11', 'bar11', '2008-11-01'),\n ('foo12', 'bar12', '2008-12-01');\n gd.gid timestamp li SELECT g1.gid, g1.aid, l1.ads, l1.til, l1.`timestamp`\nFROM gd AS g1\n INNER JOIN li AS l1 ON (g1.aid = l1.a_id)\n LEFT OUTER JOIN (\n gd AS g2 INNER JOIN li AS l2 ON (g2.aid = l2.a_id)\n ) ON (g1.gid = g2.gid AND l1.`timestamp` <= l2.`timestamp`)\nWHERE g1.gid IN ('7', '11', '9')\nGROUP BY g1.aid\nHAVING COUNT(*) <= 4\nORDER BY g1.gid ASC, l1.`timestamp` DESC;\n +------+-----+-------+-------+---------------------+\n| gid | aid | ads | til | timestamp |\n+------+-----+-------+-------+---------------------+\n| 7 | 3 | foo3 | bar3 | 2008-03-01 00:00:00 | \n| 7 | 2 | foo2 | bar2 | 2008-02-01 00:00:00 | \n| 7 | 1 | foo1 | bar1 | 2008-01-01 00:00:00 | \n| 9 | 7 | foo7 | bar7 | 2008-07-01 00:00:00 | \n| 9 | 6 | foo6 | bar6 | 2008-06-01 00:00:00 | \n| 9 | 5 | foo5 | bar5 | 2008-05-01 00:00:00 | \n| 9 | 4 | foo4 | bar4 | 2008-04-01 00:00:00 | \n| 11 | 12 | foo12 | bar12 | 2008-12-01 00:00:00 | \n| 11 | 11 | foo11 | bar11 | 2008-11-01 00:00:00 | \n| 11 | 10 | foo10 | bar10 | 2008-10-01 00:00:00 | \n| 11 | 9 | foo9 | bar9 | 2008-09-01 00:00:00 | \n+------+-----+-------+-------+---------------------+\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,955
<p>I am currently trying to make a <code>navigation-menu</code> where an <code>active-class</code> is applied to the anchors whose <code>href</code> attributes that match the current URL, so I can style that anchor in a way that makes it stand out from the rest of the menu.</p> <p>This is my mark-up:</p> <pre><code>&lt;div id="sidebar"&gt; &lt;h2&gt;Navigation menu&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item1"&gt;Menu item 1&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item2"&gt;Menu item 2&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item3"&gt;Menu item 3&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item4"&gt;Menu item 4&lt;/a&gt;&lt;/h2&gt; &lt;h2 class="subnav"&gt;&lt;a href="menu1/menu_item5"&gt;Menu item 5&lt;/a&gt;&lt;/h2&gt; &lt;/div&gt; </code></pre> <p>This is the jQuery:</p> <pre><code> jQuery(function($) { // get the current url var path = location.pathname.substring(1); // defining the top subnav anchor var $top_item = $('#sidebar h2:nth-child(2) a'); // defining all subnav anchors var $all_items = $('#sidebar h2.subnav a'); // defining the anchors with a href that matches the current url var $selected_item = $('#sidebar h2 a[@href$="' + path + '"]'); // setting the selected menu item'class as active $selected_item.addClass('active'); // THIS IS WHERE I THINK THE ERROR IS // if none of the h2.subnav's has a url that matches // the current location then assume that it's the top one that's active: if ($all_items("href") !== path) $top_item.addClass('active'); }); </code></pre> <p>I am applying the active-class with jQuery, it works fine as long as there is a match between an anchors href and the location url. If the url don't match any of the anchors I want the active-class to be applied to the <code>$top_item</code>. That part of my jQuery doesn't work.</p> <p>I can't see what the error is, but then again I'm somewhat of a Javascript/jQuery n00b. Any help would be appreciated.</p>
[ { "answer_id": 302971, "author": "jrutter", "author_id": 28454, "author_profile": "https://Stackoverflow.com/users/28454", "pm_score": 1, "selected": false, "text": "// highlight tab function\nvar path = location.pathname;\nvar home = \"/\";\n$(\"a[href='\" + [path || home] + \"']\").parents(\"li\").each(function() { \n $(this).addClass(\"selected\");\n});\n" }, { "answer_id": 302979, "author": "Tom", "author_id": 7376, "author_profile": "https://Stackoverflow.com/users/7376", "pm_score": 0, "selected": false, "text": "function highlightSelected()\n{\n $(\"h2.subnav a\").each(\n function()\n {\n if (location.pathname.indexOf(this.href) > -1)\n {\n $(this).addClass(\"selected\");\n }\n }\n );\n}\n" }, { "answer_id": 303091, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 4, "selected": true, "text": "function markActiveLink() {\n\n //Look through all the links in the sidebar\n $(\"div#sidebar a\").filter(function() {\n\n //Take the current URL and split it into chunks at each slash\n var currentURL = window.location.toString().split(\"/\");\n\n //return true if the bit after the last slash is the current page name\n return $(this).attr(\"href\") == currentURL[currentURL.length-1];\n\n //when the filter function is done, you're left with the links that match.\n }).addClass(\"active\");\n\n //Afterwards, look back through the links. If none of them were marked,\n //mark your default one.\n if($(\"div#sidebar a\").hasClass(\"active\") == false) {\n $(\"div#sidebar h2:nth-child(2) a\").addClass(\"active\");\n }\n }\n\nmarkActiveLink();\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24218/" ]
302,956
<p>I have two classes that are associated with a one-to-one mapping:</p> <pre><code>&lt;class name="Employee" table="Employees"&gt; ... &lt;one-to-one name="Address" class="AddressInfo"&gt; ... &lt;/class&gt; </code></pre> <p>I would like to use a criteria expression to get only Employees where the the associated Address class is not null, something like this (which I know doesn't work):</p> <pre><code>IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee)) .Add( Expression.IsNotNull("Address") ) .List(); </code></pre> <p>I guess this is either a really difficult question or almost no one has tried to do this?</p>
[ { "answer_id": 320863, "author": "ChrisAnnODell", "author_id": 1758, "author_profile": "https://Stackoverflow.com/users/1758", "pm_score": 4, "selected": true, "text": "IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))\n .CreateCriteria(\"Address\", \"address\").Add( Expression.IsNotNull(\"Id\") )\n .List();\n" }, { "answer_id": 323435, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 0, "selected": false, "text": "IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))\n .Add( Expression.IsNotNull(\"Address.Id\") )\n .List();\n IList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))\n .CreateAlias(\"Address\")\n .List();\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10475/" ]
302,958
<p>I have a crosstab query that uses a dynamic date function to result in the column headers and therefore the field names. Ex: ForecastPeriod:DateAdd("m",[Period],[StartDate]) This means that every time I run the crosstab query, I could end up with different field names. I need to take the results of this crosstab and combine it with the results of 3 other similar crosstabs to make a new table. Right now I use a make table query and 3 append queries. The reason I do this is to include 4 different categories of data per material item over the range of forecast periods.</p> <p>Result looks something like this:</p> <p>Material Category Per1 value ...Per2 value ...... Per24 value</p> <p>MatA Demand 0 ... 10 ....... 0</p> <p>MatA Demand Dollars $0 ... $10 ....... $0 </p> <p>MatA Forecast 10 ... 20 ....... 50</p> <p>MatA Forecast Dollars $10 ... $20 ....... $50</p> <p>The problem is that the make table query is built already against the results of the current crosstab query. When I run the crosstab next month, the results will have different field names. So I am stuck manually changing the periods in the make table query design, dropping the one no longer in the results and adding the new one.</p> <p>Is there a way to use VBA to create a new table without knowing the field names until after the crosstab runs? </p> <p>Or is there a way to code the field names or pull them from the crosstab after it runs?</p> <p>If I use code like: strSQL = "SELECT tblForecast.Material, tblForecast.Category, tblForecast.X " &amp; _ "INTO tblTemp " &amp; _ "FROM tblForecast;"</p> <p>I really don't know what tblForecast.X will actually be called. It could be 11/1/08 or 12/1/08, etc.</p> <p>If I declare a variable to hold the field name and use the date code to change it, how to I add it to the table? Would I have use Alter Table?</p> <p>I'm sure this can be done, I just can't get my head around how to do it, so any help would be appreciated!! Thanks!</p>
[ { "answer_id": 304973, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "ColHead:\"Month\" & DateDiff(\"m\",[SaleDate],Forms!frmForm!txtSomeDate)\n" }, { "answer_id": 310155, "author": "John Mo", "author_id": 38988, "author_profile": "https://Stackoverflow.com/users/38988", "pm_score": 2, "selected": false, "text": "Dim db As DAO.Database\nDim tdf As DAO.TableDef\nDim qdf As DAO.QueryDef\nDim fld As DAO.Field\nDim SourceField As DAO.Field\n\nSet db = CurrentDb\n\n'Create a new tabledef\nSet tdf = New DAO.TableDef\n\n'Reference existing, saved querydef\nSet qdf = db.QueryDefs(\"Query1\")\n\ntdf.Name = \"Table2\"\n\n'iterate fields in the query and create fields in the new tabledef\nFor Each SourceField In qdf.Fields\n Set fld = tdf.CreateField(SourceField.Name, SourceField.Type, SourceField.Size)\n tdf.Fields.Append fld\nNext\n\n'Table is created and saved when the tabledef is appended to the current db\ndb.TableDefs.Append tdf\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
302,969
<p>What kind of scenarios can XSL processing instructions be used or applied? When is it good or bad to use them?</p> <p>Clean slate here, I don't have a good handle on this particular element.</p> <p>Example from w3schools:</p> <p>&lt;xsl:processing-instruction name="process-name"&gt; &lt;!-- Content:template --&gt; &lt;/xsl:processing-instruction&gt;</p>
[ { "answer_id": 303572, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 4, "selected": true, "text": "<xsl:processing-instruction> <?xml-stylesheet> <!-- Link to the stylesheet for people who wander in. -->\n<xsl:processing-instruction name='xml-stylesheet'>\n type=\"text/xsl\"\n href=\"<xsl:value-of select='$stylesheet'/>\"\n media=\"screen\"\n</xsl:processing-instruction>\n <?xml-stylesheet type=\"text/xsl\" href=\"http://nedbatchelder.com/rss.xslt\" media=\"screen\"?>\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26625/" ]
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
[ { "answer_id": 310852, "author": "Matthew Marshall", "author_id": 39856, "author_profile": "https://Stackoverflow.com/users/39856", "pm_score": 1, "selected": false, "text": "DEBUG=True cms.views.render_page()" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39058/" ]
302,993
<p>I've seen a couple of web pages say that <code>a = b || 'blah'</code> should assign <code>'blah'</code> to <code>a</code> if <code>b</code> is <code>undefined</code> or <code>null</code>. But if I type that into Firebug or use it in code, it complains that <code>b</code> is not defined, at the list on FF3/win. Any hints?</p> <p>Edit: I'm looking for the case where <code>b</code> may not exist at all. For example, a DOM node without an <code>id</code>.</p>
[ { "answer_id": 303007, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "var b = null a = function(){ if(b){return b;} else{ return 'blah' } }();\n undefined alert(nosuchvariable);\n=> throws exception\n\nvar somevariable; // note it's never assigned\nalert(somevariable);\n=> This alerts with 'undefined'\n b window window foo = 'Hello';\nalert( window.foo );\n=> alerts 'Hello'\n undefined undefined var alert(a);\n=> exception because a is meaningless\nalert(d45pwiu4309m9rv43);\n=> exception because that is equally meaningless\n typeof \"undefined\" if( typeof(djfsd) === \"undefined\" )\n alert('no such variable');\n document.getElementById('foo');\n null null" }, { "answer_id": 303008, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 0, "selected": false, "text": "|| b var a = (b) || 'blah';\n" }, { "answer_id": 303154, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 0, "selected": false, "text": "window.b var b; document.getElementById a = document.getElementById('b') || 'blah'\n" }, { "answer_id": 303546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "var a = typeof b == 'undefined' ? 'blah' : b;\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/302993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
303,004
<p>Looking at this LINQ demo:</p> <p><a href="http://www.microsoft.com/emea/msdn/spotlight/sessionh.aspx?videoid=716" rel="nofollow noreferrer">LINQ Framework Overview</a></p> <p>When going in debug mode, the output have colors in it. I'm using the same ObjectDumper class and I only have the black/white console window.</p> <p>How can I have the same results in the console window?</p> <p>Thanks</p>
[ { "answer_id": 306820, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 0, "selected": false, "text": "System.Console.ForegroundColor" }, { "answer_id": 306856, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": " Console.ForegroundColor = ConsoleColor.Yellow;\n Console.BackgroundColor = ConsoleColor.DarkRed;\n Console.WriteLine(\"Test\");\n" }, { "answer_id": 308706, "author": "Mister Dev", "author_id": 14441, "author_profile": "https://Stackoverflow.com/users/14441", "pm_score": 0, "selected": false, "text": "[DllImport(\"kernel32.dll\")] public static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, int wAttributes);\n[DllImport(\"kernel32.dll\")] public static extern IntPtr GetStdHandle(uint nStdHandle);\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
303,006
<p>I've just started looking into M-V-VM for a WPF application. Everything makes sense so far besides this particular issue...</p> <p>I have a ViewModel I'll call Search. This ViewModel binds to a datagrid and lists results of items. Now, I have a command that needs to bring up <strong>another view</strong>, the item's details.</p> <p>Putting the logic to show another view in the Search View doesn't seem right, it's not testable at all.</p> <p>Here is my ViewModel implementation, which is not testable...</p> <pre><code>public class SearchViewModel { public void SelectItem() { // I want to call the DetailsView from here // this seems wrong, and is untestable var detailsView = new DetailsView(); detailsView.Show(); } } </code></pre> <p><strong>Where does the logic to show a view from a ViewModel method go in this pattern?</strong></p>
[ { "answer_id": 14084930, "author": "g1ga", "author_id": 733749, "author_profile": "https://Stackoverflow.com/users/733749", "pm_score": 1, "selected": false, "text": "IUIVisualizerService" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29676/" ]
303,013
<p>VS.net creates a template when you create a WCF project.</p> <p>It adds a class to the iService1.cs file:</p> <pre><code>// Use a data contract as illustrated in the sample below to // add composite types to service operations. [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } </code></pre> <p>Since a WCF service can return any user defined class, why use a DataContract and CompositeType class?</p> <p>I can return something like:</p> <pre><code> [OperationContract] MyUserCollection GetUsers(); </code></pre> <p>What am I missing?</p>
[ { "answer_id": 304764, "author": "Wagner Silveira", "author_id": 33352, "author_profile": "https://Stackoverflow.com/users/33352", "pm_score": 5, "selected": false, "text": "[DataContract]\npublic class SampleClass\n{\n [DataMember(IsRequired=true)]\n public int MyRequiredProperty { get; set; }\n\n [DataMember]\n public int MyOptionalProperty { get; set; }\n\n public int MyInternalProperty { get; set; }\n}\n" }, { "answer_id": 3292417, "author": "Vivian River", "author_id": 238260, "author_profile": "https://Stackoverflow.com/users/238260", "pm_score": 2, "selected": false, "text": "DataContract datacontract" }, { "answer_id": 5549836, "author": "Asif Mushtaq", "author_id": 201125, "author_profile": "https://Stackoverflow.com/users/201125", "pm_score": 4, "selected": false, "text": "[DataContract(Name=\"EmployeeName\")]\npublic class Person\n{\n [DataMember(Name=\"FullName\")]\n public string Name { get; set; }\n\n [DataMember(Name=\"HomeAddress\")]\n public string Address { get; set; }\n}\n" }, { "answer_id": 14768833, "author": "thewpfguy", "author_id": 387477, "author_profile": "https://Stackoverflow.com/users/387477", "pm_score": 0, "selected": false, "text": "[DataContract]\npublic class SampleClass\n{ \n [DataMember]\n private int MyPrivateProperty { get; set; }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
303,026
<p>I have a simple html page with a div. I am using jQuery to load the contents of an aspx app into the "content" div. Code looks like this:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; jQuery.noConflict(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt; &lt;div id="loading"&gt; &lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function() { jQuery("#content").load("default.aspx"); }); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>The problem is default.aspx uses shadowbox and other javascript libraries. When that code tries to execute on default.aspx it acts like the js source files were not loaded. I check in firebug and the js files are there (no 404 or anything). Anyone know what I'm missing? As you can see I used the jQuery noConflict function because I thought the use of $ might be conflicting with the other libraries but no help there...</p>
[ { "answer_id": 303055, "author": "kkubasik", "author_id": 39058, "author_profile": "https://Stackoverflow.com/users/39058", "pm_score": 2, "selected": false, "text": "jQuery.get('default.aspx', null, function(data) {\n $('#default').append(data);\n}, 'html');\n" }, { "answer_id": 303072, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": true, "text": " ScriptFragment: '<script[^>]*>([\\\\S\\\\s]*?)<\\/script>'\n\n extractScripts: function() {\n var matchAll = new RegExp(Prototype.ScriptFragment, 'img');\n var matchOne = new RegExp(Prototype.ScriptFragment, 'im');\n return (this.match(matchAll) || []).map(function(scriptTag) {\n return (scriptTag.match(matchOne) || ['', ''])[1];\n });\n }\n\n evalScripts: function() {\n return this.extractScripts().map(function(script) { return eval(script) });\n }\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
303,045
<p>I often access shared network folders in Powershell to grab files etc. But if the share requires a username/password, Powershell does not prompt me for these, unlike Windows Explorer. If I connect to the folder first in Windows Explorer, Powershell will then allow me to connect. </p> <p>How can I authenticate myself in Powershell?</p>
[ { "answer_id": 303229, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "net use \\\\server\\share /user:<domain\\username> <password>\n" }, { "answer_id": 305791, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 7, "selected": true, "text": "New-PSDrive > New-PSDrive -Name P -PSProvider FileSystem -Root \\\\server\\share -Credential domain\\user\n PSCredential net use WScript.Network MapNetworkDrive $net = new-object -ComObject WScript.Network\n$net.MapNetworkDrive(\"u:\", \"\\\\server\\share\", $false, \"domain\\user\", \"password\")\n New-PSDrive New-PSDrive -Name P -PSProvider FileSystem -Root \\\\Server01\\Public -Credential user\\domain -Persist\n" }, { "answer_id": 12586788, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 3, "selected": false, "text": "net use" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
303,053
<p>I am working on a Perl script to read CSV file and do some calculations. CSV file has only two columns, something like below.</p> <pre><code>One Two 1.00 44.000 3.00 55.000 </code></pre> <p>Now this CSV file is very big ,can be from 10 MB to 2GB.</p> <p>Currently I am taking CSV file of size 700 MB. I tried to open this file in notepad, excel but it looks like no software is going to open it.</p> <p>I want to read may be last 1000 lines from CSV file and see the values. How can I do that? I cannot open file in notepad or any other program.</p> <p>If I write a Perl script then I need to process complete file to go to end of file and then read last 1000 lines.</p> <p>Is there any better way to that? I am new to Perl and any suggestions will be appreciated. </p> <p>I have searched net and there are some scripts available like <a href="https://metacpan.org/pod/File::Tail" rel="nofollow noreferrer"><code>File::Tail</code></a> but I don't know they will work on windows ?</p>
[ { "answer_id": 303061, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": true, "text": "tail -1000 yourfile | perl ...\n tail" }, { "answer_id": 303076, "author": "Adam Lerman", "author_id": 673, "author_profile": "https://Stackoverflow.com/users/673", "pm_score": 1, "selected": false, "text": "$count = `wc -l < $file`;\ndie \"wc failed: $?\" if $?;\nchomp($count);\n" }, { "answer_id": 303104, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 0, "selected": false, "text": "perl -ne \"print if ($. > N);\" filename.csv\n perl -e \"while (<>) {} print $.;\" filename.csv\n" }, { "answer_id": 303119, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 2, "selected": false, "text": "perl -n -e \"shift @d if (@d >= 1000); push(@d, $_); END { print @d }\" < bigfile.csv\n tail -n 1000" }, { "answer_id": 303138, "author": "Joshua Swink", "author_id": 14732, "author_profile": "https://Stackoverflow.com/users/14732", "pm_score": 3, "selected": false, "text": "sub last_x_lines {\n my ($filename, $lineswanted) = @_;\n my ($line, $filesize, $seekpos, $numread, @lines);\n\n open F, $filename or die \"Can't read $filename: $!\\n\";\n\n $filesize = -s $filename;\n $seekpos = 50 * $lineswanted;\n $numread = 0;\n\n while ($numread < $lineswanted) {\n @lines = ();\n $numread = 0;\n seek(F, $filesize - $seekpos, 0);\n <F> if $seekpos < $filesize; # Discard probably fragmentary line\n while (defined($line = <F>)) {\n push @lines, $line;\n shift @lines if ++$numread > $lineswanted;\n }\n if ($numread < $lineswanted) {\n # We didn't get enough lines. Double the amount of space to read from next time.\n if ($seekpos >= $filesize) {\n die \"There aren't even $lineswanted lines in $filename - I got $numread\\n\";\n }\n $seekpos *= 2;\n $seekpos = $filesize if $seekpos >= $filesize;\n }\n }\n close F;\n return @lines;\n}\n" }, { "answer_id": 303160, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 5, "selected": false, "text": "reverse" }, { "answer_id": 303293, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": -1, "selected": false, "text": "my @lines = <>;\nmy @lastKlines = @lines[-1000,-1];\n seek()" }, { "answer_id": 12017327, "author": "webdevbyjoss", "author_id": 369587, "author_profile": "https://Stackoverflow.com/users/369587", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl \nuse warnings;\nuse strict;\nmy ($file, $num_of_lines) = @ARGV;\n\nmy $count = 0;\nmy $filesize = -s $file; # filesize used to control reaching the start of file while reading it backward\nmy $offset = -2; # skip two last characters: \\n and ^Z in the end of file\n\nopen F, $file or die \"Can't read $file: $!\\n\";\n\nwhile (abs($offset) < $filesize) {\n my $line = \"\";\n # we need to check the start of the file for seek in mode \"2\" \n # as it continues to output data in revers order even when out of file range reached\n while (abs($offset) < $filesize) {\n seek F, $offset, 2; # because of negative $offset & \"2\" - it will seek backward\n $offset -= 1; # move back the counter\n my $char = getc F;\n last if $char eq \"\\n\"; # catch the whole line if reached\n $line = $char . $line; # otherwise we have next character for current line\n }\n\n # got the next line!\n print $line, \"\\n\";\n\n # exit the loop if we are done\n $count++;\n last if $count > $num_of_lines;\n}\n $ get-x-lines-from-end.pl ./myhugefile.log 200\n" }, { "answer_id": 13138070, "author": "Littlelegs", "author_id": 1785386, "author_profile": "https://Stackoverflow.com/users/1785386", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl\n\n`tail --lines=1000 /path/myfile.txt > tempfile.txt`\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
303,054
<p>According to the adobe flex docs: <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html" rel="nofollow noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=controls_15.html</a></p> <p>Using an image multiple times</p> <p>You can use the same image multiple times in your application by using the normal image import syntax each time. Flex only loads the image once, and then references the loaded image as many times as necessary.</p> <p>However, in testing we have found that if you request the same image (same url, etc.) in IE flash 9/10 a new http request will not be issued, but with Firefox, Safari (PC and MAC) a new request is always issued.</p> <p>I want to prevent the image from being pulled from the server each time I try and use it anyone have any idea why this is working only in IE?</p>
[ { "answer_id": 303279, "author": "Ryan Guill", "author_id": 7186, "author_profile": "https://Stackoverflow.com/users/7186", "pm_score": 2, "selected": false, "text": "[Embed(source=\"myImage.jpg\")]\n[Bindable]\npublic var myImageClass:Class;\n" }, { "answer_id": 304449, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 1, "selected": false, "text": "<mx:Image id=\"myImage\" source='blah.png'/>\n\nvar myNewImage:Image = new Image();\n\nmyNewImage.source = myImage.source;\n" }, { "answer_id": 1123379, "author": "Brandon Dement", "author_id": 134034, "author_profile": "https://Stackoverflow.com/users/134034", "pm_score": 2, "selected": false, "text": "private var image1:Image = new Image(); \nprivate var image2:Image = new Image(); \n\nprivate function init() : void\n{\n image1.addEventListener(Event.COMPLETE, onComplete);\n image1.source = \"icon.png\";\n addChild(image1); \n}\n\n\nprivate function onComplete(event:Event) : void\n{ \n var image:Image = event.target as Image; \n var bitmapData:BitmapData = new BitmapData(image.content.width,\n image.content.height, true); \n bitmapData.draw(image.content); \n image2.source = new Bitmap(bitmapData);\n addChild(image2);\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39075/" ]
303,056
<p>I am looking to find out the logic , if any , which shrinks hashtable in c# when elements are removed from it.</p> <p>Regards Harish</p>
[ { "answer_id": 303103, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "Dictionary<K,V>" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
303,066
<p>I recently migrated an ASP site from my dev machine to a live server. All the pages except my FAQ page works just fine, but my FAQ brings up:</p> <pre><code>XML Parsing Error: no element found Location: http://geniusupdate.com/GSHelp/faq.aspx Line Number 1, Column 1: </code></pre> <p>The only changes I have made were changing the connection string on my SQL page from local to the string specified by my hosting service. Any tips on what I can do to find the root of this issue?</p> <p>here is the source to my FAQ page:</p> <pre><code>&lt;%@ Page Language="VB" MasterPageFile="~/theMaster.master" AutoEventWireup="false" CodeFile="faq.aspx.vb" Inherits="faq" Title="Untitled Page" %&gt; &lt;%@ Import Namespace="sqlstuff" %&gt; &lt;%@ Import Namespace="functions" %&gt; &lt;asp:Content ContentPlaceHolderID="page_title" ID="theTitle" runat="server"&gt; FAQ&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="column1_title" ID="col1Title" runat="server"&gt; &lt;%=faqPageTitle(Request.QueryString("cid"))%&gt;&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="column1" ID="columnContent" runat="server"&gt; &lt;p&gt;Click on a question to expand it to see the answer!&lt;/p&gt; &lt;p&gt;&lt;% If cID &gt;= 0 Then Dim theFaq As New List(Of faqContent), iterate As Integer = 0 theFaq = sqlStuff.getFaqs(cID) For Each oFaq As faqContent In theFaq Response.Output.WriteLine("&lt;h4 id={0} class={1}&gt;Q: {2}&lt;/h4&gt;", _ addQuotes("gsSwitch{0}-title", iterate), _ addQuotes("handCursor"), _ oFaq.Content.Question) Response.Output.WriteLine("&lt;div id={0} class={1}&gt;&lt;string&gt;A: &lt;/strong&gt;{2}&lt;/div&gt;", _ addQuotes("gsSwitch{0}", iterate), _ addQuotes("gsSwitch"), _ oFaq.Content.Answer) iterate += 1 Next Else Response.Output.Write("Here you can find a lot of information about eTHOMAS and how to expedite your office tasks.{0}", ControlChars.NewLine) End If %&gt;&lt;/p&gt; &lt;script type="text/javascript"&gt; var gsContent = new switchcontent("gsSwitch", "div") var eID = '&lt;%= expandID %&gt;' gsContent.collapsePrevious(true) // TRUE: only 1; FALSE: any number gsContent.setPersist(false) if(eID &gt;= 0){ gsContent.defaultExpanded(eID) // opens the searched FAQ document.getElementById('gsSwitch' + eID + '-title').scrollIntoView(true) // scrolls to selected FAQ } gsContent.init() &lt;/script&gt; &lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="subcolumn_right_title" ID="rSideColTitle" runat="server"&gt;&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="subcolumn_right" ID="rSideColContent" runat="server"&gt;&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="subcolumn_left_title" ID="lSideColTitle" runat="server"&gt;&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="subcolumn_left" ID="lSideColContent" runat="server"&gt;&lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="sidecolumn_title" ID="sideColtitle" runat="server"&gt; &lt;/asp:Content&gt; &lt;asp:Content ContentPlaceHolderID="sidecolumn" ID="sideCol" runat="server"&gt; &lt;% If cID &gt;= 0 Then Response.Write(constructFaqSideMenu(CInt(Request.QueryString("cid")))) Else Response.Write(constructFaqSideMenu()) End If %&gt; &lt;/asp:Content&gt; </code></pre> <p>I found this on another forum <a href="http://dev.communityserver.com/forums/t/472596.aspx" rel="noreferrer">link</a>: </p> <blockquote> <p>Well, it appears it's a bit of both. The message is generated by Firefox, but caused by the framework. For some reason, .NET generates a response type of "application/xml" when it creates an empty page. Firefox parses the file as XML and finding no root element, spits out the error message.</p> </blockquote> <p>IE does not render the page, period. This is where the XML is coming from.</p> <p>Here is the constructFaqSideMenu() function:</p> <pre><code>Public Shared Function constructFaqSideMenu(ByVal oSelID As Integer) As String Dim oCatList As New List(Of faqCategory) Dim oRet As New StringBuilder Dim iterate As Integer = 1, extraTag As String = "" oCatList = sqlStuff.getFaqCats oRet.AppendFormattedLine("&lt;ul id={0}&gt;", addQuotes("submenu")) oRet.AppendFormattedLine(" &lt;li id={0}&gt;FAQ Categories&lt;/li&gt;", addQuotes("title")) For Each category As faqCategory In oCatList If iterate = oSelID Then extraTag = String.Format(" id={0}", addQuotes("active")) Else extraTag = "" End If oRet.AppendFormattedLine(" &lt;li{0}&gt;&lt;a href={1}&gt;{2}&lt;/a&gt;&lt;/li&gt;", extraTag, addQuotes("faq.aspx?cid={0}", iterate), StrConv(category.Title, VbStrConv.ProperCase)) iterate += 1 Next oRet.AppendLine("&lt;/ul&gt;") Return oRet.ToString End Function </code></pre> <p>And here is the source of the blank page IE returns:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"&gt; &lt;HTML&gt;&lt;HEAD&gt; &lt;META http-equiv=Content-Type content="text/html; charset=windows-1252"&gt;&lt;/HEAD&gt; &lt;BODY&gt;&lt;/BODY&gt;&lt;/HTML&gt; </code></pre>
[ { "answer_id": 707453, "author": "Rich", "author_id": 53501, "author_profile": "https://Stackoverflow.com/users/53501", "pm_score": 4, "selected": false, "text": "Global.Application_Error Server.GetLastError().GetBaseException()\n" }, { "answer_id": 1924834, "author": "mmcglynn", "author_id": 4241, "author_profile": "https://Stackoverflow.com/users/4241", "pm_score": 1, "selected": false, "text": "<html>\n<body></body>\n</html>\n" }, { "answer_id": 24104009, "author": "Saad Ahmed Sharif", "author_id": 3345287, "author_profile": "https://Stackoverflow.com/users/3345287", "pm_score": 1, "selected": false, "text": "http://localhost/forms/abc.aspx http://localhost/projectname/forms/abc.aspx" }, { "answer_id": 33552007, "author": "Jason Marsell", "author_id": 429825, "author_profile": "https://Stackoverflow.com/users/429825", "pm_score": 0, "selected": false, "text": "ServiceModelReg.exe -i iisreset" }, { "answer_id": 47893252, "author": "Bwyss", "author_id": 1569577, "author_profile": "https://Stackoverflow.com/users/1569577", "pm_score": 2, "selected": false, "text": "return res.status(200).end();\n return res.status(200).send('ok').end();\n" }, { "answer_id": 49260511, "author": "kyleb", "author_id": 1088795, "author_profile": "https://Stackoverflow.com/users/1088795", "pm_score": 3, "selected": false, "text": "protected IHttpActionResult OKJSONResult()\n{\n HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, \"\", new MediaTypeHeaderValue(\"application/json\"));\n return ResponseMessage(response);\n}\n" }, { "answer_id": 74067115, "author": "Ronak Munjapara", "author_id": 10038725, "author_profile": "https://Stackoverflow.com/users/10038725", "pm_score": 0, "selected": false, "text": "void Application_Error(object sender, EventArgs e)\n{\nException objErr = Server.GetLastError().GetBaseException();\nstring err = \"Error caught in Application_Error event\" + \n \"\\n \\nError Message: \" + objErr.Message.ToString()+ \n \"\\n \\nStack Trace: \" + objErr.StackTrace.ToString();\n\nSystem.Diagnostics.EventLog.WriteEntry(\"MYApplication\", err, \nSystem.Diagnostics.EventLogEntryType.Error);\nServer.ClearError(); \n} \n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
303,096
<p>I'm trying TripleDES Encryption with ECB mode. My code looks like that:</p> <pre><code>public static string EncryptDES(string InputText) { byte[] key = new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 }; byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText); MemoryStream ms = new MemoryStream(); TripleDES alg = TripleDES.Create(); alg.Key = key; alg.Mode = CipherMode.ECB; CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(clearData, 0, clearData.Length); cs.FlushFinalBlock(); byte[] CipherBytes = ms.ToArray(); ms.Close(); cs.Close(); string EncryptedData = Convert.ToBase64String(CipherBytes); return EncryptedData; } </code></pre> <p>When I run a test I got an exception that the "Length of Data to decrypt is invalid."</p> <p>Does anyone knows what I'm doing wrong?</p> <p>Thank you in advance.</p> <h2>Update</h2> <p>My bad ! I found my problem Instead of using <code>alg.CreateEncryptor()</code> I was using <code>alg.CreateDecyptor()</code>.</p> <p>A copy paste issue. :(</p> <p>Thanks for help, guys</p>
[ { "answer_id": 303118, "author": "sep332", "author_id": 13652, "author_profile": "https://Stackoverflow.com/users/13652", "pm_score": 0, "selected": false, "text": "Public Shared DefaultEncoding As Text.Encoding = _System.Text.Encoding.GetEncoding(\"Unicode\")\n" }, { "answer_id": 303159, "author": "Youssef", "author_id": 10968, "author_profile": "https://Stackoverflow.com/users/10968", "pm_score": 4, "selected": true, "text": "alg.CreateEncryptor() alg.CreateDecyptor()" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968/" ]
303,098
<p>I have some data stored as <code>ArrayList</code>. And when I want to backup this data,java bounds two objects forever. Which means when I change values in data <code>ArrayList</code> this changes come to backup. I tried to copy values from data separately to backup in the loop, tried to use method <code>data.clone()</code> — nothing helps.</p>
[ { "answer_id": 303131, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "List org = new java.util.ArrayList();\norg.add(instance)\norg.get(0).setValue(\"org val\");\nList copy = new java.util.ArrayList(org);\norg.get(0).setValue(\"new val\");\n copy.get(0).getValue() \"new val\" org.get(0) copy.get(0) List copy = new java.util.ArrayList();\nfor(Instance obj : org) {\n copy.add(new Instance(obj)); // call to copy constructor\n}\n" }, { "answer_id": 303139, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": false, "text": "ArrayList backup = new ArrayList();\nfor (Object obj : data)\n backup.add(obj.clone());\n" }, { "answer_id": 303140, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 3, "selected": false, "text": "data ArrayList clone clone" }, { "answer_id": 303141, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 5, "selected": true, "text": ".clone() ArrayList" }, { "answer_id": 303485, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": -1, "selected": false, "text": "static String GetRandomString(int length)\n{\n UUID uuid = UUID.randomUUID();\n return uuid.toString().substring(0, length); \n}\n\npublic static void main(String[] args)\n{\n ArrayList<String> al = new ArrayList<String>(20);\n for (int i = 0; i < 10; i++)\n {\n al.add(GetRandomString(7));\n }\n ArrayList<String> cloneArray = new ArrayList<String>(al);\n Collections.copy(cloneArray, al);\n System.out.println(al);\n System.out.println(cloneArray);\n for (int i = 9; i >= 0; i -= 2)\n {\n al.remove(i);\n }\n System.out.println(al);\n System.out.println(cloneArray);\n}\n" }, { "answer_id": 303638, "author": "Tore A.", "author_id": 39133, "author_profile": "https://Stackoverflow.com/users/39133", "pm_score": 2, "selected": false, "text": "ArrayList backup = new ArrayList(mylist.size());\nbackup.addAll(mylist);\n ArrayList backup = new ArrayList(mylist.size());\nfor(Object o : mylist) {\n backup.add(o.clone());\n}\n" }, { "answer_id": 49718983, "author": "GunnarK", "author_id": 8148900, "author_profile": "https://Stackoverflow.com/users/8148900", "pm_score": 0, "selected": false, "text": "import java.util.ArrayList;\n\npublic class Snapshot {\n private ArrayList<Integer> dataBackup;\n\n public Snapshot(ArrayList<Integer> data)\n {\n dataBackup = new ArrayList<Integer>();\n for(int i = 0; i < data.size(); i++)\n {\n dataBackup.add(data.get(i));\n }\n }\n\n public ArrayList<Integer> restore()\n {\n return dataBackup;\n }\n\n public static void main(String[] args)\n {\n ArrayList<Integer> list = new ArrayList<Integer>();\n list.add(1);\n list.add(2);\n\n Snapshot snap = new Snapshot(list);\n\n list.set(0, 3);\n list = snap.restore();\n\n System.out.println(list); // Should output [1, 2]\n\n list.add(4);\n list = snap.restore();\n\n System.out.println(list); // Should output [1, 2]\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35594/" ]
303,113
<p>I've scoured the groovy doc and haven't found an analogue, but things there are organized a bit haphazardly. I'm switching from beanshell to groovy and was using the source("fileloc") method in beanshell to inline-include other, utility beanshell scripts for reuse. Is there a standard function to do this in groovy or a best practice?</p>
[ { "answer_id": 303208, "author": "feoh", "author_id": 32514, "author_profile": "https://Stackoverflow.com/users/32514", "pm_score": 1, "selected": false, "text": "load" }, { "answer_id": 306480, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 4, "selected": true, "text": "part1 = new File(\"part1.groovy\").text\npart2 = new File(\"part2.groovy\").text\n\nscript = \"\"\"\nprintln \"starting execution\"\n${part1}\n${part2}\nprintln \"done execution\"\n\"\"\"\n\nnew GroovyShell().evaluate(script)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8720/" ]
303,116
<p>Does a <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx" rel="noreferrer"><code>System.Windows.Threading.Dispatcher</code></a> work on the UI-thread of a <code>WinForms</code> application?</p> <p>If yes, why? It is coming from WindowsBase.dll which seems to be a <code>WPF</code> component.</p> <p>If not, how can I invoke work units back onto the UI-thread? I've found <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke.aspx" rel="noreferrer"><code>Control.BeginInvoke()</code></a>, but it seems clumsy to create a control only to reference the originating thread.</p>
[ { "answer_id": 1160035, "author": "Martin Konicek", "author_id": 90998, "author_profile": "https://Stackoverflow.com/users/90998", "pm_score": 5, "selected": false, "text": "Dispatcher Dispatcher.CurrentDispatcher" }, { "answer_id": 12629542, "author": "TonyP", "author_id": 225394, "author_profile": "https://Stackoverflow.com/users/225394", "pm_score": 1, "selected": false, "text": "void dep_OnChange(object sender, OracleNotificationEventArgs arg)\n {\n Console.WriteLine(\"Notification received\");\n\n int infoSum = int.Parse(arg.Details.Compute(\"Sum(Info)\", \"Info is not null\").ToString());\n InfoSum x = (InfoSum)infoSum;\n foreach (DataRow dr in arg.Details.Rows)\n {\n Console.WriteLine(string.Format(\"Operation(InfoSum)= {0}\", Enum.GetName(typeof(InfoSum), x)));\n Console.WriteLine(string.Format(\"ontable={0} Rowid={1},info={2}\", dr.Field<string>(\"ResourceName\"), dr.Field<string>(\"rowid\"), dr.Field<Int32>(\"info\")));\n }\n // Following will throw cross-thread \n // dataGridView1.DataSource = arg.Details;\n // instead of line above use the following\n dataGridView1.BeginInvoke((Action)(()=>dataGridView1.DataSource = arg.Details));\n IsNotified = true;\n }\n\n }\n" }, { "answer_id": 16007664, "author": "Gennady Vanin Геннадий Ванин", "author_id": 200449, "author_profile": "https://Stackoverflow.com/users/200449", "pm_score": 4, "selected": false, "text": "System.Windows.Threading.Dispatcher button.Click Dispatcher dispatcherUI = Dispatcher.CurrentDispatcher;\n private void button1_Click(object sender, EventArgs e)\n{\n Dispatcher dispUI = Dispatcher.CurrentDispatcher;\n for (int i = 2; i < 20; i++)\n {\n int j = i;\n var t = Task.Factory.StartNew\n (() =>\n {\n var result = SumRootN(j);\n dispUI.BeginInvoke\n (new Action\n (() => richTextBox1.Text += \"root \" + j.ToString()\n + \" \" + result.ToString() + Environment.NewLine\n )\n , null\n );\n }\n );\n}\n" }, { "answer_id": 18430655, "author": "George Birbilis", "author_id": 903783, "author_profile": "https://Stackoverflow.com/users/903783", "pm_score": 0, "selected": false, "text": "private WebBrowserDocumentCompletedEventHandler handler; //need to make it a class field for the handler below (anonymous delegates seem to capture state at point of definition, so they can't capture their own reference)\nprivate string imageFilename;\nprivate bool exit;\n\npublic void CaptureScreenshot(Uri address = null, string imageFilename = null, int msecDelay = 0, bool exit = false)\n{\n handler = (s, e) =>\n {\n webBrowser.DocumentCompleted -= handler; //must do first\n\n this.imageFilename = imageFilename;\n this.exit = exit;\n\n timerScreenshot.Interval = (msecDelay > 0)? msecDelay : 1;\n timerScreenshot.Enabled = true;\n };\n\n webBrowser.DocumentCompleted += handler;\n Go(address); //if address == null, will use URL from UI\n}\n\nprivate void timerScreenshot_Tick(object sender, EventArgs e)\n{\n timerScreenshot.Enabled = false; //must do first\n\n BeginInvoke((Action)(() => //Invoke at UI thread\n { //run in UI thread\n\n BringToFront();\n Bitmap bitmap = webBrowser.GetScreenshot();\n\n if (imageFilename == null)\n imageFilename = bitmap.ShowSaveFileDialog();\n\n if (imageFilename != null)\n {\n Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(imageFilename))); //create any parent directories needed\n bitmap.Save(imageFilename);\n }\n\n bitmap.Dispose(); //release bitmap resources\n\n if (exit)\n Close(); //this should close the app, since this is the main form\n\n }), null);\n}\n" }, { "answer_id": 71445537, "author": "Glaucus", "author_id": 1011688, "author_profile": "https://Stackoverflow.com/users/1011688", "pm_score": 0, "selected": false, "text": "public class ViewModelBase : INotifyPropertyChanged\n{\n public event PropertyChangedEventHandler PropertyChanged;\n\n private Dispatcher _dispatcher;\n\n public ViewModelBase()\n {\n _dispatcher = Dispatcher.CurrentDispatcher;\n }\n\n protected void RaisePropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));\n\n protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = \"\")\n {\n if (EqualityComparer<T>.Default.Equals(field, value)) return false;\n\n field = value;\n RaisePropertyChanged(propertyName);\n\n return true;\n }\n\n protected bool SetFieldOnMainThread<T>(ref T field, T value, [CallerMemberName] string propertyName = \"\")\n {\n if (EqualityComparer<T>.Default.Equals(field, value)) return false;\n\n field = value;\n RunOnUiThread(() => RaisePropertyChanged(propertyName));\n\n return true;\n }\n\n protected void RunOnUiThread(Action action)\n {\n if (action != null)\n {\n _dispatcher.Invoke(action);\n }\n }\n}\n\n\n// Used like this:\npublic class TestViewModel : ViewModelBase\n{\n private string _name;\n public string Name {\n get => _name;\n set => SetFieldOnMainThread(ref _name, value);\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
303,149
<p>Parameterized Queries in .Net always look like this in the examples:</p> <pre><code>SqlCommand comm = new SqlCommand(@" SELECT * FROM Products WHERE Category_ID = @categoryid ", conn); comm.Parameters.Add("@categoryid", SqlDbType.Int); comm.Parameters["@categoryid"].Value = CategoryID; </code></pre> <p>But I'm running into a brick wall trying to do the following:</p> <pre><code>SqlCommand comm = new SqlCommand(@" SELECT * FROM Products WHERE Category_ID IN (@categoryids) OR name LIKE '%@name%' ", conn); comm.Parameters.Add("@categoryids", SqlDbType.Int); comm.Parameters["@categoryids"].Value = CategoryIDs; comm.Parameters.Add("@name", SqlDbType.Int); comm.Parameters["@name"].Value = Name; </code></pre> <p>Where</p> <ul> <li>CategoryIDs is a comma separated list of numbers "123,456,789" (without quotes)</li> <li>Name is a string, possibly with single quotes and other bad characters</li> </ul> <p>What's the right syntax for this?</p>
[ { "answer_id": 303175, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 4, "selected": false, "text": "SqlCommand comm = new SqlCommand(\"SELECT * FROM Products WHERE Category_ID IN (@categoryid1, @categoryid2) OR name LIKE @name\", conn);\ncomm.Parameters.Add(\"@categoryid1\", SqlDbType.Int);\ncomm.Parameters[\"@categoryid1\"].Value = CategoryID[0];\ncomm.Parameters.Add(\"@categoryid2\", SqlDbType.Int);\ncomm.Parameters[\"@categoryid2\"].Value = CategoryID[1];\ncomm.Parameters.Add(\"@name\", SqlDbType.NVarChar);\ncomm.Parameters[\"@name\"].Value = \"%\" + Name + \"%\";\n" }, { "answer_id": 303422, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 7, "selected": true, "text": "string Name = \"someone\";\nint[] categoryIDs = new int[] { 238, 1138, 1615, 1616, 1617,\n 1618, 1619, 1620, 1951, 1952,\n 1953, 1954, 1955, 1972, 2022 };\n\nSqlCommand comm = conn.CreateCommand();\n\nstring[] parameters = new string[categoryIDs.Length];\nfor(int i=0;i<categoryIDs.Length;i++)\n{\n parameters[i] = \"@p\"+i;\n comm.Parameters.AddWithValue(parameters[i], categoryIDs[i]);\n}\ncomm.Parameters.AddWithValue(\"@name\",$\"%{Name}%\");\ncomm.CommandText = \"SELECT * FROM Products WHERE Category_ID IN (\";\ncomm.CommandText += string.Join(\",\", parameters) + \")\";\ncomm.CommandText += \" OR name LIKE @name\";\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435/" ]
303,167
<p>I have an object in SQL (A) that has a many to many relationships with another object (B). I'm currently building an API layer DLL that will allow the user to assign objects of type B into type A. Right now the user would retrieve a list of entries of type A and a list of entries of type B using different LINQ data contexts. The problem is it the data context associated with A treats any objects from the data context associated with B as if they were new and tries to insert them when I call SubmitChanges(). Is there a way to tell data context A that these objects already exist and don't need to be created? The code I'd like to write looks something like this (I'll call A service and B output):</p> <pre><code>List&lt;Service&gt; svcs = Service.GetServices(); List&lt;Output&gt; outs = Output.GetOutputs(); svcs[0].OutputCollection.Add(outs); svcs[0].Save(); </code></pre> <p>Each Service object in my example has a reference to the data context that pulled it from the database and the Save function calls DataContext.SubmitChanges(); The code above throws an exception because it tries to add the Output that already exists back to the table.</p> <p>I know this was long and I'm not sure I explained my problem well. Any insight or suggestions would be helpful.</p>
[ { "answer_id": 303183, "author": "Chad Moran", "author_id": 25416, "author_profile": "https://Stackoverflow.com/users/25416", "pm_score": 0, "selected": false, "text": "Person existingPerson - DB.GetPerson(1);\nexistingPerson.BirthDate = newPerson.BirthDate;\nexistingPerson.JobTitle = newPerson.JobTitle;\n" }, { "answer_id": 303220, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 3, "selected": true, "text": "public void Add(Output output)\n{\n OutputCollectionItem oci = new OutputCollectionItem();\n oci.item = output;\n this.OutputCollection.Add(oci);\n}\n public void Add(Output output)\n{\n OutputCollectionItem oci = new OutputCollectionItem();\n oci.itemID = output.itemID;\n this.OutputCollection.Add(oci);\n}\n" }, { "answer_id": 305230, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 0, "selected": false, "text": "// this remains\nList<Service> svcs = Service.GetServices();\nList<Output> outs = Output.GetOutputs();\n\nsvcs[0].OutputCollection.Add(outs);\nsvcs[0].Save();\n\n// this changes\npublic class Service\n{\n public static List<Service> GetServices()\n {\n var context = new Context();\n var result = context.ServiceSet.ToList();\n result.ForEach(e => context.Detach(e));\n return result;\n }\n public void Save()\n {\n var context = new Context();\n context.Attach(this); // will retach myself and all of my child entities.\n context.SaveChanges();\n }\n}\n\npublic class Output\n{\n public static List<Output> GetOutput()\n {\n var context = new Context();\n var result = context.OutputSet.ToList();\n result.ForEach(e => context.Detach(e));\n return result;\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
303,174
<p>I just got burned by the <a href="http://cygwin.com/ml/cygwin-xfree-announce/2008-11/msg00000.html" rel="nofollow noreferrer">Cygwin X11R7.4 update</a> and I find the official mailing lists hostile and clunky. So I thought I'd ask here.</p> <p>If you have survived the upgrade (or at least made progress on fixing things), what steps did you take to make things work?</p>
[ { "answer_id": 303183, "author": "Chad Moran", "author_id": 25416, "author_profile": "https://Stackoverflow.com/users/25416", "pm_score": 0, "selected": false, "text": "Person existingPerson - DB.GetPerson(1);\nexistingPerson.BirthDate = newPerson.BirthDate;\nexistingPerson.JobTitle = newPerson.JobTitle;\n" }, { "answer_id": 303220, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 3, "selected": true, "text": "public void Add(Output output)\n{\n OutputCollectionItem oci = new OutputCollectionItem();\n oci.item = output;\n this.OutputCollection.Add(oci);\n}\n public void Add(Output output)\n{\n OutputCollectionItem oci = new OutputCollectionItem();\n oci.itemID = output.itemID;\n this.OutputCollection.Add(oci);\n}\n" }, { "answer_id": 305230, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 0, "selected": false, "text": "// this remains\nList<Service> svcs = Service.GetServices();\nList<Output> outs = Output.GetOutputs();\n\nsvcs[0].OutputCollection.Add(outs);\nsvcs[0].Save();\n\n// this changes\npublic class Service\n{\n public static List<Service> GetServices()\n {\n var context = new Context();\n var result = context.ServiceSet.ToList();\n result.ForEach(e => context.Detach(e));\n return result;\n }\n public void Save()\n {\n var context = new Context();\n context.Attach(this); // will retach myself and all of my child entities.\n context.SaveChanges();\n }\n}\n\npublic class Output\n{\n public static List<Output> GetOutput()\n {\n var context = new Context();\n var result = context.OutputSet.ToList();\n result.ForEach(e => context.Detach(e));\n return result;\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
303,180
<p>Good afternoon,</p> <p>I have a web query in <code>Excel 2002</code> going against a web page that returns a date column. The dates are returned as <code>DD/MM/YYYY</code>, as I would like to show them in my spreadsheet. My machine running Excel has its regional settings set to en-GB, and the only language set under Internet Options is UK English.</p> <p>Nevertheless, the web query pulls the dates as <code>MM/DD/YYYY</code>, which is misinterpreted by Excel.</p> <p>How can I get the Web Query to return the dates in my regional settings, <code>MM/DD/YYYY</code>?</p>
[ { "answer_id": 303222, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "lang <meta http-equiv=\"content-language\" content=\"...\">" }, { "answer_id": 307421, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 3, "selected": true, "text": "Universal Date format is : \"yyyy-mm-dd hh:mm:ss\"\n" }, { "answer_id": 19457773, "author": "DBS", "author_id": 1028375, "author_profile": "https://Stackoverflow.com/users/1028375", "pm_score": 0, "selected": false, "text": "With Selection.QueryTable\n .Connection = _\n \"URL;http://whateverYourURLis\"\n .WebSelectionType = xlSpecifiedTables\n .WebFormatting = xlWebFormattingNone\n .WebTables = \"7\"\n .WebPreFormattedTextToColumns = True\n .WebConsecutiveDelimitersAsOne = True\n .WebSingleBlockTextImport = False\n .WebDisableDateRecognition = True\n .WebDisableRedirections = False\n .Refresh BackgroundQuery:=False\nEnd With\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7311/" ]
303,181
<ol> <li>Why is operator '&amp;' defined for bool?, and operator '&amp;&amp;' is not? </li> <li>How exactly does this 1) bool? &amp; bool? and 2) bool? and bool work?</li> </ol> <p>Any other "interesting" operator semantics on Nullable? Any overloaded operators for generic T?</p>
[ { "answer_id": 303215, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "bool? x y x & y x | y \ntrue true true true\ntrue false false true\ntrue null null true\nfalse true false true\nfalse false false false\nfalse null false null\nnull true null true\nnull false false null\nnull null null null\n" }, { "answer_id": 303340, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "Nullable<T> Nullable<T> int int? decimal DateTime && || bool someFlag = Method1() && Method2();\n Method1() Method2() Method2()" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38325/" ]
303,197
<p>I've created an instance of a SamlAssertion, and added the the authorization statement and attribute statments to it, and now I want to print out the XML so I can do an HTTP post, but not all of the assertion is being outputed. What am I missing (I'm sure it's something bone-headed)?</p> <p>Here is the code I'm using:</p> <pre><code>// Add the Statements to the SAML Assertion samlAssert.Statements.Add(samlAuthStatement); samlAssert.Statements.Add(samlAttrStatement); MemoryStream xmlStream = new MemoryStream(); XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateTextWriter(xmlStream, System.Text.Encoding.UTF8); SamlSerializer samlAssertSerializer = new SamlSerializer(); WSSecurityTokenSerializer secTokenSerializer = new WSSecurityTokenSerializer(); samlAssert.WriteXml(xmlWriter, samlAssertSerializer, secTokenSerializer); xmlStream.Position = 0; StreamReader sr = new StreamReader(xmlStream, System.Text.Encoding.UTF8); string AssertStr = sr.ReadToEnd(); TextBox1.Text = AssertStr; </code></pre> <p>But All that gets returned is this:</p> <pre><code>&lt;saml:Assertion MajorVersion="1" MinorVersion="1" AssertionID="assertID" Issuer="my Company" IssueInstant="2008-11-19T19:54:12.191Z" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"&gt; &lt;saml:Conditions NotBefore="2008-11-19T19:54:12.191Z" NotOnOrAfter="2008-11-19T19:59:12.191Z"/&gt; &lt;saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:2.0:ac:classes:TimeSyncToken" AuthenticationInstant="2008-11-19T19:54:12.191Z"&gt; &lt;saml:Subject&gt; &lt;saml:NameIdentifier Format="cs-sstc-schema-assertion-1.1.xsd" NameQualifier="My company"&gt;xxxx&lt;/saml:NameIdentifier&gt; &lt;saml:SubjectConfirmation&gt; &lt;saml:ConfirmationMethod&gt;urn:oasis:names:tc:SAML:1.0:cm:bearer&lt;/saml:ConfirmationMethod&gt; &lt;/saml:SubjectConfirmation&gt; &lt;/saml:Subject&gt; &lt;saml:SubjectLocality IPAddress="x.x.x.x"/&gt; &lt;/saml: </code></pre>
[ { "answer_id": 1694077, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 2, "selected": false, "text": "using // Add the Statements to the SAML Assertion\nsamlAssert.Statements.Add(samlAuthStatement);\nsamlAssert.Statements.Add(samlAttrStatement);\n\nvar sb = new StringBuilder();\nvar settings = new XmlWriterSettings \n{\n OmitXmlDeclaration = true,\n Encoding = Encoding.UTF8\n};\nusing (var stringWriter = new StringWriter(sb))\nusing (var xmlWriter = XmlWriter.Create(stringWriter, settings))\nusing (var dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter))\n{\n var samlAssertSerializer = new SamlSerializer();\n var secTokenSerializer = new WSSecurityTokenSerializer();\n samlAssert.WriteXml(\n dictionaryWriter, \n samlAssertSerializer, \n secTokenSerializer\n );\n}\n\nTextBox1.Text = sb.ToString();\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28660/" ]
303,200
<p>I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove("/folder_name")</code>. </p> <p>What is the most effective way of removing/deleting a folder/directory that is not empty?</p>
[ { "answer_id": 303225, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 12, "selected": true, "text": "import shutil\n\nshutil.rmtree('/folder_name')\n rmtree shutil.rmtree('/folder_name', ignore_errors=True)\n" }, { "answer_id": 303228, "author": "kkubasik", "author_id": 39058, "author_profile": "https://Stackoverflow.com/users/39058", "pm_score": 7, "selected": false, "text": "os.walk() # Delete everything reachable from the directory named in 'top',\n# assuming there are no symbolic links.\n# CAUTION: This is dangerous! For example, if top == '/', it\n# could delete all your disk files.\nimport os\nfor root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n" }, { "answer_id": 4507228, "author": "P M", "author_id": 396782, "author_profile": "https://Stackoverflow.com/users/396782", "pm_score": 3, "selected": false, "text": "RMDIR c:\\blah /s /q \n rm -rf /home/whatever \n import sys\nimport os\n\nmswindows = (sys.platform == \"win32\")\n\ndef getstatusoutput(cmd):\n \"\"\"Return (status, output) of executing cmd in a shell.\"\"\"\n if not mswindows:\n return commands.getstatusoutput(cmd)\n pipe = os.popen(cmd + ' 2>&1', 'r')\n text = pipe.read()\n sts = pipe.close()\n if sts is None: sts = 0\n if text[-1:] == '\\n': text = text[:-1]\n return sts, text\n\n\ndef deleteDir(path):\n \"\"\"deletes the path entirely\"\"\"\n if mswindows: \n cmd = \"RMDIR \"+ path +\" /s /q\"\n else:\n cmd = \"rm -rf \"+path\n result = getstatusoutput(cmd)\n if(result[0]!=0):\n raise RuntimeError(result[1])\n" }, { "answer_id": 25172642, "author": "Siva Mandadi", "author_id": 1658999, "author_profile": "https://Stackoverflow.com/users/1658999", "pm_score": 7, "selected": false, "text": "import shutil\nshutil.rmtree(dest, ignore_errors=True)\n" }, { "answer_id": 28476881, "author": "RY_ Zheng", "author_id": 4026902, "author_profile": "https://Stackoverflow.com/users/4026902", "pm_score": 3, "selected": false, "text": "import os\nimport stat\nimport shutil\n\ndef errorRemoveReadonly(func, path, exc):\n excvalue = exc[1]\n if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:\n # change the file to be readable,writable,executable: 0777\n os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) \n # retry\n func(path)\n else:\n # raiseenter code here\n\nshutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly) \n" }, { "answer_id": 28834214, "author": "yota", "author_id": 495769, "author_profile": "https://Stackoverflow.com/users/495769", "pm_score": 5, "selected": false, "text": "import pathlib\n\ndef delete_folder(pth) :\n for sub in pth.iterdir() :\n if sub.is_dir() :\n delete_folder(sub)\n else :\n sub.unlink()\n pth.rmdir() # if you just want to delete the dir content but not the dir itself, remove this line\n pth pathlib.Path" }, { "answer_id": 32979686, "author": "Charles Chow", "author_id": 2780230, "author_profile": "https://Stackoverflow.com/users/2780230", "pm_score": 3, "selected": false, "text": "import shutil\ndef remove_folder(path):\n # check if folder exists\n if os.path.exists(path):\n # remove if exists\n shutil.rmtree(path)\n else:\n # throw your exception to handle this special scenario\n raise XXError(\"your exception\") \nremove_folder(\"/folder_name\")\n" }, { "answer_id": 34714324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import os\nos.system(\"rm -rf dirname\")\n" }, { "answer_id": 40492573, "author": "Byron Filer", "author_id": 6460641, "author_profile": "https://Stackoverflow.com/users/6460641", "pm_score": 2, "selected": false, "text": "shutil os from os import listdir, rmdir, remove\nfor i in listdir(directoryToRemove):\n os.remove(os.path.join(directoryToRemove, i))\nrmdir(directoryToRemove) # Now the directory is empty of files\n" }, { "answer_id": 42141888, "author": "JinSnow", "author_id": 1486850, "author_profile": "https://Stackoverflow.com/users/1486850", "pm_score": 3, "selected": false, "text": "import os\nimport shutil\nfrom send2trash import send2trash # (shutil delete permanently)\n root = r\"C:\\Users\\Me\\Desktop\\test\" \nfor dir, subdirs, files in os.walk(root): \n if subdirs == [] and files == []:\n send2trash(dir)\n print(dir, \": folder removed\")\n elif subdirs == [] and len(files) == 1: # if contains no sub folder and only 1 file \n if files[0]== \"desktop.ini\" or: \n send2trash(dir)\n print(dir, \": folder removed\")\n else:\n print(dir)\n elif subdirs == []: #if dir doesn’t contains subdirectory\n ext = (\".srt\", \".txt\")\n contains_other_ext=0\n for file in files:\n if not file.endswith(ext): \n contains_other_ext=True\n if contains_other_ext== 0:\n send2trash(dir)\n print(dir, \": dir deleted\")\n def get_tree_size(path):\n \"\"\"Return total size of files in given path and subdirs.\"\"\"\n total = 0\n for entry in os.scandir(path):\n if entry.is_dir(follow_symlinks=False):\n total += get_tree_size(entry.path)\n else:\n total += entry.stat(follow_symlinks=False).st_size\n return total\n\n\nfor dir, subdirs, files in os.walk(root): \n If get_tree_size(dir) < 400000: # ≈ 400kb\n send2trash(dir)\n print(dir, \"dir deleted\")\n" }, { "answer_id": 43914402, "author": "Dave Chandler", "author_id": 1793694, "author_profile": "https://Stackoverflow.com/users/1793694", "pm_score": 4, "selected": false, "text": "import os, stat\nimport shutil\n\ndef remove_readonly(func, path, _):\n \"Clear the readonly bit and reattempt the removal\"\n os.chmod(path, stat.S_IWRITE)\n func(path)\n\nshutil.rmtree(directory, onerror=remove_readonly)\n" }, { "answer_id": 44230319, "author": "Eponymous", "author_id": 309334, "author_profile": "https://Stackoverflow.com/users/309334", "pm_score": 2, "selected": false, "text": "import shutil\n\ndef ignore_absent_file(func, path, exc_inf):\n except_instance = exc_inf[1]\n if isinstance(except_instance, FileNotFoundError):\n return\n raise except_instance\n\nshutil.rmtree(dir_to_delete, onerror=ignore_absent_file)\n import shutil\nimport errno\n\ndef ignore_absent_file(func, path, exc_inf):\n except_instance = exc_inf[1]\n if isinstance(except_instance, OSError) and \\\n except_instance.errno == errno.ENOENT:\n return\n raise except_instance\n\nshutil.rmtree(dir_to_delete, onerror=ignore_absent_file)\n" }, { "answer_id": 45478738, "author": "amazingthere", "author_id": 2049675, "author_profile": "https://Stackoverflow.com/users/2049675", "pm_score": 2, "selected": false, "text": "def deleteDir(dirPath):\n deleteFiles = []\n deleteDirs = []\n for root, dirs, files in os.walk(dirPath):\n for f in files:\n deleteFiles.append(os.path.join(root, f))\n for d in dirs:\n deleteDirs.append(os.path.join(root, d))\n for f in deleteFiles:\n os.remove(f)\n for d in deleteDirs:\n os.rmdir(d)\n os.rmdir(dirPath)\n" }, { "answer_id": 50645887, "author": "seremet", "author_id": 7522029, "author_profile": "https://Stackoverflow.com/users/7522029", "pm_score": 0, "selected": false, "text": "os.system('powershell.exe rmdir -r D:\\workspace\\Branches\\*%s* -Force' %CANDIDATE_BRANCH)\n" }, { "answer_id": 51482471, "author": "Alexander Samoylov", "author_id": 4807875, "author_profile": "https://Stackoverflow.com/users/4807875", "pm_score": 1, "selected": false, "text": "python -c \"import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]\"\npython -c \"import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]\"\npython -c \"import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)\"\n" }, { "answer_id": 54183444, "author": "RodogInfinite", "author_id": 7656233, "author_profile": "https://Stackoverflow.com/users/7656233", "pm_score": 3, "selected": false, "text": "import subprocess\nfrom pathlib import Path\n\n#using pathlib.Path\npath = Path('/path/to/your/dir')\nsubprocess.run([\"rm\", \"-rf\", str(path)])\n\n#using strings\npath = \"/path/to/your/dir\"\nsubprocess.run([\"rm\", \"-rf\", path])\n $ rm -rf '/path/to/your/dir pathlib.Path pathlib.Path Path.rmdir()" }, { "answer_id": 55308643, "author": "Kartik Raj", "author_id": 8152786, "author_profile": "https://Stackoverflow.com/users/8152786", "pm_score": 1, "selected": false, "text": "Access is denied The process cannot access the file because it is being used by another process os.system('rmdir /S /Q \"{}\"'.format(directory)) rm -rf" }, { "answer_id": 56596235, "author": "pepoluan", "author_id": 149900, "author_profile": "https://Stackoverflow.com/users/149900", "pm_score": 3, "selected": false, "text": "from pathlib import Path\nfrom typing import Union\n\ndef del_dir(target: Union[Path, str], only_if_empty: bool = False):\n \"\"\"\n Delete a given directory and its subdirectories.\n\n :param target: The directory to delete\n :param only_if_empty: Raise RuntimeError if any file is found in the tree\n \"\"\"\n target = Path(target).expanduser()\n assert target.is_dir()\n for p in sorted(target.glob('**/*'), reverse=True):\n if not p.exists():\n continue\n p.chmod(0o666)\n if p.is_dir():\n p.rmdir()\n else:\n if only_if_empty:\n raise RuntimeError(f'{p.parent} is not empty!')\n p.unlink()\n target.rmdir()\n Path str pathlib" }, { "answer_id": 63029545, "author": "Paulo Guimarães", "author_id": 8887224, "author_profile": "https://Stackoverflow.com/users/8887224", "pm_score": 0, "selected": false, "text": " #!/usr/bin/env python3\n\n import shutil\n from os import path, system\n import sys\n\n # Try to delete the folder ---------------------------------------------\n if (path.isdir(folder)):\n shutil.rmtree(folder, ignore_errors=True)\n\n if (path.isdir(folder)):\n try:\n system(\"rd -r {0}\".format(folder))\n except Exception as e:\n print(\"WARN: Failed to delete => {0}\".format(e),file=sys.stderr)\n\n if (path.isdir(self.backup_folder_wrk)):\n try:\n system(\"rd /s /q {0}\".format(folder))\n except Exception as e:\n print(\"WARN: Failed to delete => {0}\".format(e),file=sys.stderr)\n\n if (path.isdir(folder)):\n print(\"WARN: Failed to delete {0}\".format(folder),file=sys.stderr)\n # -------------------------------------------------------------------------------------\n\n" }, { "answer_id": 65230962, "author": "Gustavo Bezerra", "author_id": 2132753, "author_profile": "https://Stackoverflow.com/users/2132753", "pm_score": 2, "selected": false, "text": "pathlib from pathlib import Path\n\ndef remove_path(path: Path):\n if path.is_file() or path.is_symlink():\n path.unlink()\n return\n for p in path.iterdir():\n remove_path(p)\n path.rmdir()\n" }, { "answer_id": 72888039, "author": "M.Ahmadkhani", "author_id": 5486439, "author_profile": "https://Stackoverflow.com/users/5486439", "pm_score": 0, "selected": false, "text": "import shutil\nimport os\n\ndirectory = \"path/to/the/root/folder\"\nfiles_in_directory = os.listdir(directory)\n\nfor file in files_in_directory:\n try:\n path_to_file_or_folder = os.path.join(directory, file)\n shutil.rmtree(path_to_file_or_folder)\n except:\n os.unlink(path_to_file_or_folder)\n" }, { "answer_id": 72982576, "author": "Boris Kovalenko", "author_id": 19550278, "author_profile": "https://Stackoverflow.com/users/19550278", "pm_score": 2, "selected": false, "text": "import os\n\n\ndef rrmdir(path):\n for entry in os.scandir(path):\n if entry.is_dir():\n rrmdir(entry)\n else:\n os.remove(entry)\n os.rmdir(path)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
303,214
<p>How can I create a method that has optional parameters in it in Visual Basic?</p>
[ { "answer_id": 303230, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 7, "selected": true, "text": "Optional Sub MyMethod(ByVal Param1 As String, Optional ByVal FlagArgument As Boolean = True)\n If FlagArgument Then\n 'Do something special\n Console.WriteLine(Param1)\n End If\n\nEnd Sub\n MyMethod(\"test1\")\n MyMethod(\"test2\", False)\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4575/" ]
303,216
<p>I'm trying to use a <code>break</code> statement in a <code>for</code> loop, but since I'm also using strict subs in my Perl code, I'm getting an error saying:</p> <blockquote> <p>Bareword "break" not allowed while "strict subs" in use at ./final.pl line 154.</p> </blockquote> <p>Is there a workaround for this (besides disabling strict subs)?</p> <p>My code is formatted as follows:</p> <pre><code>for my $entry (@array){ if ($string eq "text"){ break; } } </code></pre>
[ { "answer_id": 303231, "author": "Zain Rizvi", "author_id": 21539, "author_profile": "https://Stackoverflow.com/users/21539", "pm_score": 10, "selected": true, "text": "for my $entry (@array){\n if ($string eq \"text\"){\n last;\n }\n}\n" }, { "answer_id": 303261, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": false, "text": "FOO: {\n for my $i ( @listone ){\n for my $j ( @listtwo ){\n if ( cond( $i,$j ) ){\n\n last FOO; # --->\n # |\n } # |\n } # |\n } # |\n } # <-------------------------------\n" }, { "answer_id": 32575568, "author": "MortenB", "author_id": 536262, "author_profile": "https://Stackoverflow.com/users/536262", "pm_score": 3, "selected": false, "text": "my $exitflag = 0;\n$SIG{INT} = sub { $exitflag=1 };\n\nwhile(!$exitflag) {\n # Do your stuff\n}\n" }, { "answer_id": 43872666, "author": "Kamal Nayan", "author_id": 4414367, "author_profile": "https://Stackoverflow.com/users/4414367", "pm_score": 5, "selected": false, "text": "last for my $entry (@array){\n if ($string eq \"text\"){\n last;\n }\n}\n last LBL_SCORE: {\n for my $entry1 (@array1) {\n for my $entry2 (@array2) {\n if ($entry1 eq $entry2) { # Or any condition\n last LBL_SCORE;\n }\n }\n }\n }\n last" }, { "answer_id": 63580584, "author": "Timur Shtatland", "author_id": 967621, "author_profile": "https://Stackoverflow.com/users/967621", "pm_score": 2, "selected": false, "text": "-n -p last last LINE echo 1 2 3 4 | xargs -n1 | perl -ne 'last if $. == 3; print;'\necho 1 2 3 4 | xargs -n1 | perl -ne 'last LINE if $. == 3; print;'\necho 1 2 3 4 | xargs -n1 | perl -pe 'last if $. == 3;'\necho 1 2 3 4 | xargs -n1 | perl -pe 'last LINE if $. == 3;'\n 1\n2\n -e -n $_ -p -n print last last next redo continue last" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ]
303,218
<p>I was wondering if there was a way to bind an ArrayList (or any kind of List, for that matter) to a PreparedStatement which will eventually be used to access an Oracle database. I found:</p> <p><a href="https://stackoverflow.com/questions/178479/alternatives-for-java-sql-preparedstatement-in-clause-issue">PreparedStatement IN clause alternatives?</a></p> <p>And that seems similar to my issue, but this question is more specific: I'd like to bind an ArrayList to a PreparedStatement to be used in Oracle, if it is possible, how is this accomplished?</p>
[ { "answer_id": 303282, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "SELECT NAME FROM ITEM WHERE ID IN (?, ?, ?, ?)\n PreparedStatement String Integer PreparedStatements" }, { "answer_id": 303327, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "CREATE OR REPLACE TYPE my_nested_table IS TABLE OF VARCHAR2(20);\nCREATE TABLE my_table (a my_nested_table) NESTED TABLE a STORE AS my_table_a;\n String[] insertvalues = { \"a\", \"b\", \"c\" };\nPreparedStatement p = conn.prepareStatement(\"INSERT INTO my_table VALUES( ? )\");\nARRAY insertParameter = new ARRAY( a_desc, conn, insertvalues );\np.setArray( 1, insertParameter );\np.execute();\n dev> select * from my_table;\n\nA\n--------------------------------------------------------------------------------\nMY_NESTED_TABLE('a', 'b', 'c')\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8026/" ]
303,248
<p>What is the proper way to load a <code>ListBox</code> in C# .NET 2.0 Winforms?</p> <p>I thought I could just bind it to a <code>DataTable</code>. No such luck.<br> I thought I could bind it with a <code>Dictionary</code>. No luck. </p> <p>Do I have to write an class called <code>KeyValuePair</code>, and then use <code>List&lt;KeyValuePair&gt;</code> just to be able to load this thing with objects? Maybe I am missing something obvious. I want my display text and values to be different values.</p>
[ { "answer_id": 303268, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 3, "selected": false, "text": "class MyDataType\n{\n public string ToString()\n {\n //return the text you want to display\n }\n}\n ListBox l;\nList<MyDataType> myItems = new List<MyDataType>(); // populate this however you like\nl.AddRange(myItems.ToArray());\n" }, { "answer_id": 303283, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 7, "selected": true, "text": "Person FirstName LastName Age Person List<Person> people = new List<Person>();\npeople.Add(new Person { Age = 25, FirstName = \"Alex\", LastName = \"Johnson\" });\npeople.Add(new Person { Age = 23, FirstName = \"Jack\", LastName = \"Jones\" });\npeople.Add(new Person { Age = 35, FirstName = \"Mike\", LastName = \"Williams\" });\npeople.Add(new Person { Age = 25, FirstName = \"Gill\", LastName = \"JAckson\" });\nthis.listBox1.DataSource = people;\nthis.listBox1.DisplayMember = \"FirstName\";\nthis.listBox1.ValueMember = \"Age\";\n DisplayMember ValueMember" }, { "answer_id": 303351, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 3, "selected": false, "text": "listbox.ValueMember = \"your_id_field\";\nlistbox.DisplayMember = \"your_display_field\";\nlistbox.DataSource = dataTable;\n" }, { "answer_id": 305865, "author": "user39369", "author_id": 39369, "author_profile": "https://Stackoverflow.com/users/39369", "pm_score": 1, "selected": false, "text": "MyListBox.DataSource = New BindingSource(Dict, Nothing)\nMyListBox.DisplayMember = \"Value\"\nMyListBox.ValueMember = \"Key\"\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
303,284
<p>Soo... F# no longer has IEnumerable.map_with_type... which is the way people <em>were</em> mapping over collections. How do I do that now?</p> <pre><code>let urlPat = "href\\s*=\\s*(?:(?:\\\"(?&lt;url&gt;[^\\\"]*)\\\")|(?&lt;url&gt;[^\\s]* ))";; let urlRegex = new Regex(urlPat) let matches = urlRegex.Matches(http("http://www.google.com")) let matchToUrl (urlMatch : Match) = urlMatch.Value let urls = List.map matchToUrl matches </code></pre> <p>Thanks!</p>
[ { "answer_id": 304225, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 5, "selected": true, "text": "let urls = Seq.map matchToUrl (Seq.cast matches);;\n let urls = matches|> Seq.cast |> Seq.map matchToUrl;;\n matchToUrl List.of_seq" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
303,287
<p>I have a series of Extension methods to help with null-checking on IDataRecord objects, which I'm currently implementing like this:</p> <pre><code>public static int? GetNullableInt32(this IDataRecord dr, int ordinal) { int? nullInt = null; return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal); } public static int? GetNullableInt32(this IDataRecord dr, string fieldname) { int ordinal = dr.GetOrdinal(fieldname); return dr.GetNullableInt32(ordinal); } </code></pre> <p>and so on, for each type I need to deal with. </p> <p>I'd like to reimplement these as a generic method, partly to reduce redundancy and partly to learn how to write generic methods in general. </p> <p>I've written this:</p> <pre><code>public static Nullable&lt;T&gt; GetNullable&lt;T&gt;(this IDataRecord dr, int ordinal) { Nullable&lt;T&gt; nullValue = null; return dr.IsDBNull(ordinal) ? nullValue : (Nullable&lt;T&gt;) dr.GetValue(ordinal); } </code></pre> <p>which works as long as T is a value type, but if T is a reference type it won't.</p> <p>This method would need to return either a Nullable type if T is a value type, and default(T) otherwise. How would I implement this behavior?</p>
[ { "answer_id": 303310, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": -1, "selected": false, "text": "DataRow record = GetSomeRecord();\nint? someNumber = record[15] as int?\nGuid? someUID = record[\"MyPrimaryKey\"] as Guid?;\nstring someText = GetSomeText();\nrecord[\"Description\"] = someText.ToDbString();\n\n// ........\n\npublic static class StringExtensionHelper {\n public static object ToDbString( this string text ) {\n object ret = null != text ? text : DBNull.Value\n return ret;\n }\n}\n public static class StringExtensionHelper {\n public static object ToDbValue( this object value ) {\n object ret = object.ReferenceEquals( value, null ) ? (object)DBNull.Value : value;\n return ret;\n }\n}\n" }, { "answer_id": 303321, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 4, "selected": true, "text": "public static T GetNullable<T>(this IDataRecord dr, int ordinal)\n{\n return dr.IsDBNull(ordinal) ? default(T) : (T) dr.GetValue(ordinal);\n}\n" }, { "answer_id": 303391, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "public static T Get<T>( this IDataRecord dr, int ordinal) \n{\n T nullValue = default(T);\n return dr.IsDBNull(ordinal) ? nullValue : (T) dr.GetValue(ordinal);\n}\n\n\npublic void Code(params string[] args)\n{\n IDataRecord dr= null;\n int? a = Get<int?>(dr, 1);\n string b = Get<string>(dr, 2);\n}\n" }, { "answer_id": 303777, "author": "Logicalmind", "author_id": 26977, "author_profile": "https://Stackoverflow.com/users/26977", "pm_score": 0, "selected": false, "text": "public static T GetData<T>(this IDataReader reader, Func<int, T> getFunc, int index)\n{\n if (!reader.IsClosed)\n {\n return getFunc(index);\n }\n throw new ArgumentException(\"Reader is closed.\", \"reader\");\n}\n\npublic static T GetDataNullableRef<T>(this IDataReader reader, Func<int, T> getFunc, int index) where T : class\n{\n if (!reader.IsClosed)\n {\n return reader.IsDBNull(index) ? null : getFunc(index);\n }\n throw new ArgumentException(\"Reader is closed.\", \"reader\");\n}\n\npublic static T? GetDataNullableValue<T>(this IDataReader reader, Func<int, T> getFunc, int index) where T : struct\n{\n if (!reader.IsClosed)\n {\n return reader.IsDBNull(index) ? (T?)null : getFunc(index);\n }\n throw new ArgumentException(\"Reader is closed.\", \"reader\");\n}\n private static Whatever CreateObject(IDataReader reader)\n{\n Int32? id = reader.GetDataNullableValue<Int32>(reader.GetInt32, 0);\n string name = reader.GetDataNullableRef<string>(reader.GetString, 1);\n Int32 x = reader.GetData<Int32>(reader.GetInt32, 2);\n}\n" }, { "answer_id": 1046768, "author": "SeeR", "author_id": 22569, "author_profile": "https://Stackoverflow.com/users/22569", "pm_score": 0, "selected": false, "text": "public static T Get<T>(this IDataRecord rec, Func<int, T> GetValue, int ordinal)\n{\n return rec.IsDBNull(ordinal) ? default(T) : GetValue(ordinal);\n}\n public static T Get<T>(this IDataRecord rec, Func<IDataRecord, int, T> GetValue, int ordinal)\n{\n return rec.IsDBNull(ordinal) ? default(T) : GetValue(rec, ordinal);\n}\n\npublic static Func<IDataRecord, int, int> GetInt32 = (rec, i) => rec.GetInt32(i);\npublic static Func<IDataRecord, int, bool> GetBool = (rec, i) => rec.GetBoolean(i);\npublic static Func<IDataRecord, int, string> GetString = (rec, i) => rec.GetString(i);\n rec.Get(GetString, index);\nrec.Get(GetInt32, index);\n" }, { "answer_id": 2833275, "author": "stevehipwell", "author_id": 89075, "author_profile": "https://Stackoverflow.com/users/89075", "pm_score": 1, "selected": false, "text": "int? iNullable = dr[ordinal] as int?; int iNonNullable = dr[ordinal] as int? ?? default(int); string sValue = dr[ordinal] as string; dr[ordinal] private void Test()\n{\n int? iTestA;\n int? iTestB;\n int iTestC;\n string sTestA;\n string sTestB;\n\n //Create connection\n using (SqlConnection oConnection = new SqlConnection(@\"\"))\n {\n //Open connection\n oConnection.Open();\n\n //Create command\n using (SqlCommand oCommand = oConnection.CreateCommand())\n {\n //Set command text\n oCommand.CommandText = \"SELECT null, 1, null, null, '1'\";\n\n //Create reader\n using (SqlDataReader oReader = oCommand.ExecuteReader())\n {\n //Read the data\n oReader.Read();\n\n //Set the values\n iTestA = oReader[0] as int?;\n iTestB = oReader[1] as int?;\n iTestC = oReader[2] as int? ?? -1;\n sTestA = oReader[3] as string;\n sTestB = oReader[4] as string;\n }\n }\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249/" ]
303,314
<p>Does anyone know of a CSS Adapter for the LinkButton control for ASP.Net 2?</p> <p><strong>Update:</strong></p> <p>We are trying to use CSS Buttons. We are using this approach: <a href="http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html" rel="nofollow noreferrer">http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html</a> For that we need to render the tags which the link button doesn't do.</p> <p><strong>Possible Solution using Adapter</strong></p> <p>We created an adapter for the linkbutton. Then changed the RenderContents as follows:</p> <pre><code> protected override void Render(HtmlTextWriter writer) { LinkButton linkButton = this.Control; linkButton.Text = String.Concat("&lt;span&gt;", linkButton.Text, "&lt;/span&gt;"); base.Render(writer); } </code></pre> <p>This seems to work and requires minimum effort.</p>
[ { "answer_id": 303489, "author": "GeekyMonkey", "author_id": 29900, "author_profile": "https://Stackoverflow.com/users/29900", "pm_score": 0, "selected": false, "text": "<a...><span>[text]</span></a>\n" }, { "answer_id": 303882, "author": "Damir Zekić", "author_id": 401510, "author_profile": "https://Stackoverflow.com/users/401510", "pm_score": 1, "selected": false, "text": "LinkButton RenderContents" }, { "answer_id": 1382302, "author": "B Z", "author_id": 25020, "author_profile": "https://Stackoverflow.com/users/25020", "pm_score": 1, "selected": true, "text": " protected override void Render(HtmlTextWriter writer) {\n\n LinkButton linkButton = this.Control;\n\n linkButton.Text = String.Concat(\"<span>\", linkButton.Text, \"</span>\");\n\n base.Render(writer);\n }\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25020/" ]
303,318
<p>I want to index a computed column in my database table which uses a number of user defined functions. However I just learned that my column is non-deterministic.</p> <p>Without indexing its going to be way to slow to run queries that I need.</p> <p>What's the best way of tracing through user defined functions to determine whether they are deterministic?</p> <p>Is there any kind of tool in SQL Server Management Studio that will tell me whether a user defined function is deterministic or do I just need to trace through all the system-defined functions I'm using to find out which are non-deterministic and find other ways to write my code without them?</p>
[ { "answer_id": 303373, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM INFORMATION_SCHEMA.ROUTINES\nWHERE IS_DETERMINISTIC = 'NO'\n AND ROUTINE_TYPE = 'FUNCTION'\n SELECT OBJECTPROPERTY(OBJECT_ID('schemaname.functionname'), 'IsDeterministic')\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26140/" ]
303,324
<p>We are looking for a free solution to compress our SQL Server backups for SQL Server 2005. I am aware of SQL Safe freeware edition, but I was wondering what others thought of storing backup files in compressed folders to achieve the desired result. This would allow us to use the native SQL backup tasks and native windows compression, thereby eliminating the need for third-party products.</p> <p>I have not used compressed folders for anything in the past. Is this a viable idea? Are there any foreseeable issues with the integrity of the backups in a compressed folder?</p>
[ { "answer_id": 1787178, "author": "Clay Lenhart", "author_id": 113088, "author_profile": "https://Stackoverflow.com/users/113088", "pm_score": 2, "selected": false, "text": "msbp.exe backup \"db(database=model)\" \"zip64\" \"local(path=c:\\model.full.bak.zip)\"\n" }, { "answer_id": 15144020, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "$max_compressible_size = 10*1024*1024*1024 #10 gigs \n\n$files = Get-ChildItem -recurse | where {$_.Extension -match \"(trn)|(diff)|(bak)\"}\n\nforeach ($file in $files) { \n $attr = (Get-ItemProperty $file.fullname).Attributes\n\n if ($attr.ToString() -notmatch \".*Compressed.*\" -and $file.Length -le $max_compressible_size) {\n write-output $file.FullName\n compact /C $file.FullName\n }\n}\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30419/" ]
303,336
<p>I have made some changes to a site and need to re-host it as the current host is ceasing to exist. My client has received the following from the current host:</p> <p>"The best thing to tell them is that, due to the fact that we are withdrawing our service completely, we would look to fully transfer the web site address across to them rather than just "point" the web address at them. If you can forward this Email to them and ask them to confirm their "IPS tag" (they'll know what that is), I can then arrange for it to be transferred as and when they confirm it's all ready to go."</p> <p>Can anyone help me out here as i'm not too sure what they mean, nor do I know what an IPS tag is? ?</p>
[ { "answer_id": 303348, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "Domain name:\n amazon.co.uk\n\nRegistrant:\n Amazon Europe Holding Technologies SCS\n\nRegistrant type:\n Unknown\n\nRegistrant's address:\n 65 boulevard G-D. Charlotte\n Luxembourg City\n Luxembourg\n LU-1311\n LU\n\nRegistrar:\n Amazon.com [Tag = AMAZON-COM]\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16684/" ]
303,338
<p>We have a need to leverage client side resources for lists containing tasks.</p> <p>The client needs to:</p> <ul> <li>be notified of updates to the list</li> <li>be able to re-order/filter the list (requesting an update from the server with tasks that the client does not know of/have in cache)</li> </ul> <p>The problem comes on initial load or large list updates (changing from "tasks assigned to me" to "tasks regarding x")</p> <p>The fastest thing to do is get all the tasks back in a list, instead of individual (10+) requests.</p> <p>But E-tags will not help when I request an update to a task in the list, as it was not downloaded individually.</p> <p>Is there some way of getting the browser to cache items in a list against their individual urls?</p> <p>Or a way of creating a javascript cache that will survive a navigation away?</p> <ul> <li>If I navigate away, and go to the task url, will my js objects survive? I suspect no.</li> <li>If I navigate away, then hit back, will my javascript objects survive? I suspect yes. <ul> <li>If so, is it possible to have a "task list load" page that will inspect the history and go back to the existing task list? I think no - security.</li> </ul></li> </ul> <p>I'm thinking I'll just have to take the initial loading hits and individually retrieve tasks, so that later requests are fast (and take the load off the server).</p>
[ { "answer_id": 303348, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "Domain name:\n amazon.co.uk\n\nRegistrant:\n Amazon Europe Holding Technologies SCS\n\nRegistrant type:\n Unknown\n\nRegistrant's address:\n 65 boulevard G-D. Charlotte\n Luxembourg City\n Luxembourg\n LU-1311\n LU\n\nRegistrar:\n Amazon.com [Tag = AMAZON-COM]\n" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37193/" ]
303,360
<p>I'm making heavy use of PropertySheets in my application framework's configuration editor. I like them a lot because it's pretty easy to work with them (once you learn how) and make the editing bulletproof.</p> <p>One of the things that I'm storing in my configuration are Python scripts. It's possible to edit a Python script in a StringCollection editor, which is what I've been using, but there's a long distance between "possible" and "useable." I'd like to have an editor that actually supported resizeable and monospace fonts, preserved blank lines, and - hey, let's go crazy with the wishlist - did syntax coloring.</p> <p>I can certainly write this if I really have to, but I'd prefer not to.</p> <p>I've poked around on the Google and can't find anything like what I'm describing, so I thought I'd ask here. Is this a solved problem? Has anyone out there already taken a crack at building a better editor?</p>
[ { "answer_id": 16244797, "author": "Rob Farquharson", "author_id": 2324372, "author_profile": "https://Stackoverflow.com/users/2324372", "pm_score": 2, "selected": false, "text": "System.Drawing.Design.UITypeEditor StringArrayEditor public class StringArrayEditor : System.Drawing.Design.UITypeEditor\n PropertyGrid GetEditStyle public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)\n {\n return UITypeEditorEditStyle.Modal;\n }\n EditValue public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n {\n var editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;\n if (editorService != null)\n {\n var selectionControl = new TextArrayPropertyForm((string[])value, \"Edit the lines of text\", \"Label Editor\");\n editorService.ShowDialog(selectionControl);\n if (selectionControl.DialogResult == DialogResult.OK)\n value = selectionControl.Value;\n }\n return value ?? new string[] {};\n }\n editorService TextArrayPropertyForm TextArrayPropertyForm selectionControl.Value buttonOK buttonCancel labelInstructions textValue using System;\nusing System.Windows.Forms;\n\nnamespace MyNamespace\n{\n /// <summary>\n /// Alternate form for editing string arrays in PropertyGrid control\n /// </summary>\n public partial class TextArrayPropertyForm : Form\n {\n public TextArrayPropertyForm(string[] value,\n string instructions = \"Enter the strings in the collection (one per line):\", string title = \"String Collection Editor\")\n {\n InitializeComponent();\n Value = value;\n textValue.Text = string.Join(\"\\r\\n\", value);\n labelInstructions.Text = instructions;\n Text = title;\n }\n\n public string[] Value;\n\n private void buttonCancel_Click(object sender, EventArgs e)\n {\n DialogResult = DialogResult.Cancel;\n }\n\n private void buttonOK_Click(object sender, EventArgs e)\n {\n Value = textValue.Text.Split(new[] { \"\\r\\n\" }, StringSplitOptions.None);\n DialogResult = DialogResult.OK;\n }\n }\n}\n [Description(\"The name or text to appear on the layout.\")]\n [DisplayName(\"Text\"), Browsable(true), Category(\"Design\")]\n [Editor(typeof(StringArrayEditor), typeof(System.Drawing.Design.UITypeEditor))]\n public string[] Text {get; set;}\n EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)" } ]
2008/11/19
[ "https://Stackoverflow.com/questions/303360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19403/" ]