qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
109,825
<p>Should I bind directly to objects returned from a webservice or should I have client-side objects that I bind to my gridcontrols? For instance if I have a service that returns object Car should I have a client side Car object that I populate with values from the webservice Car object? What is considered best-practice? In C# do I need to mark my classes as serializable or do something special to them?</p>
[ { "answer_id": 235048, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "Car CarFactory BuyCar(string make, string model) Mechanic Car Garage CarFactory Mechanic CarFactory.BuyCar(\"Audi\", \"R8\") Mechanic.Inspect(myAudi) Car CarFactory.Car Car Car CarFactory Garage Mechanic Car CarFactory BuyCar Car Mechanic Car's" } ]
2008/09/20
[ "https://Stackoverflow.com/questions/109825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
109,859
<p>I am reading a .NET book, and in one of the code examples there is a class definition with this field:</p> <pre><code>private DateTime? startdate </code></pre> <p>What does <code>DateTime?</code> mean?</p>
[ { "answer_id": 109862, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 5, "selected": false, "text": "? DateTime?" }, { "answer_id": 109872, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 8, "selected": true, "text": "DateTime struct class DateTime int null DateTime null DateTime null DateTime? Nullable<DateTime> Nullable struct" }, { "answer_id": 109873, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": " DateTime? a = null;\n if (!a.HasValue)\n {\n a = DateTime.Now;\n if (a.HasValue)\n {\n Console.WriteLine(a.Value);\n }\n }\n" }, { "answer_id": 59454112, "author": "PArikshit KAmat", "author_id": 10828078, "author_profile": "https://Stackoverflow.com/users/10828078", "pm_score": 0, "selected": false, "text": "public class ReportsMapper : CommonMapper\n{\n\n\n public DateTime? cb_Bill_From_Date { get; set; }\n\n public DateTime? cb_Bill_To_Date { get; set; }\n\n public DateTime? tff_Bill_From_Date { get; set; }\n public DateTime? tff_Bill_To_Date { get; set; }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148/" ]
109,880
<p>Has anybody found a good solution for lazily-evaluated lists in Perl? I've tried a number of ways to turn something like </p> <pre><code>for my $item ( map { ... } @list ) { } </code></pre> <p>into a lazy evaluation--by tie-ing @list, for example. I'm trying to avoid breaking down and writing a source filter to do it, because they mess with your ability to debug the code. Has anybody had any success. Or do you just have to break down and use a while loop? </p> <p><strong>Note:</strong> I guess that I should mention that I'm kind of hooked on sometimes long grep-map chains for functionally transforming lists. So it's not so much the foreach loop or the while loop. It's that map expressions tend to pack more functionality into the same vertical space. </p>
[ { "answer_id": 109899, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "my $list = sub { return calculate_next_element };\nwhile(defined(my $element = &$list)) {\n ...\n}\n" }, { "answer_id": 109908, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 3, "selected": false, "text": "for my $i (0..$#list) {\n my $item = some_function($list[$i]);\n ...\n}\n for my $i (0..$#array) {\n for my $item (some_function($array[$i])) {\n ...\n }\n}\n" }, { "answer_id": 109920, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 5, "selected": true, "text": "sub make_iterator {\n my ($value, $max, $step) = @_;\n\n return sub {\n return if $value > $max; # Return undef when we overflow max.\n\n my $current = $value;\n $value += $step; # Increment value for next call.\n return $current; # Return current iterator value.\n };\n}\n # All the even numbers between 0 - 100.\nmy $evens = make_iterator(0, 100, 2);\n\nwhile (defined( my $x = $evens->() ) ) {\n print \"$x\\n\";\n}\n" }, { "answer_id": 111527, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "foreach for my $item ( map { ... } grep { ... } map { ... } @list ) { ... }\n while ( my $input = calculcate_next_element() ) {\n for my $item ( map { ... } grep { ... } map { ... } $input ) { ... }\n}\n" }, { "answer_id": 111640, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "map grep" }, { "answer_id": 113832, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 2, "selected": false, "text": "map parallel" }, { "answer_id": 2136070, "author": "Eric Strom", "author_id": 189416, "author_profile": "https://Stackoverflow.com/users/189416", "pm_score": 2, "selected": false, "text": "List::Gen use List::Gen;\n\nfor my $item ( @{gen { ... } \\@list} ) {...}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ]
109,883
<p>aspnet mvc has the HandleError filter that will return a view if an error occurs, but if an error occurs when calling a JsonResult Action how can I return a JSON object that represents an error?</p> <p>I don't want to wrap the code in each action method that returns a JsonResult in a try/catch to accomplish it, I'd rather do it by adding a 'HandleJsonError' attribute or using the existing HandleError attribute to the required action methods.</p>
[ { "answer_id": 109897, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 1, "selected": false, "text": " public enum ActionResultTypes\n {\n View,\n Json\n }\n\n public sealed class AuthorizationRequiredAttribute : ActionFilterAttribute, IAuthorizationFilter\n {\n public ActionResultTypes ActionResultType { get; set; }\n\n public AuthorizationRequiredAttribute(ActionResultTypes actionResultType)\n {\n this.ActionResultType = ActionResultType;\n }\n }\n\n //And used like\n [AuthorizationRequired(ActionResultTypes.View)]\n public ActionResult About()\n {\n }\n" }, { "answer_id": 11968417, "author": "Stanislav Dvoychenko", "author_id": 390491, "author_profile": "https://Stackoverflow.com/users/390491", "pm_score": 3, "selected": false, "text": "public class OncHandleErrorAttribute : HandleErrorAttribute\n{\n public override void OnException(ExceptionContext context)\n {\n // Elmah-Log only handled exceptions\n if (context.ExceptionHandled)\n ErrorSignal.FromCurrentContext().Raise(context.Exception);\n\n if (context.HttpContext.Request.IsAjaxRequest())\n {\n // if request was an Ajax request, respond with json with Error field\n var jsonResult = new ErrorController { ControllerContext = context }.GetJsonError(context.Exception);\n jsonResult.ExecuteResult(context);\n context.ExceptionHandled = true;\n }\n else\n {\n // if not an ajax request, continue with logic implemented by MVC -> html error page\n base.OnException(context);\n }\n }\n}\n public class ErrorController : Controller\n{\n public ActionResult GetJsonError(Exception ex)\n {\n var ticketId = Guid.NewGuid(); // Lets issue a ticket to show the user and have in the log\n\n Request.ServerVariables[\"TTicketID\"] = ticketId.ToString(); // Elmah will show this in a nice table\n\n ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling\n\n ex.Data.Add(\"TTicketID\", ticketId.ToString()); // Trying to see where this one gets in Elmah\n\n return Json(new { Error = String.Format(\"Support ticket: {0}\\r\\n Error: {1}\", ticketId, ex.ToString()) }, JsonRequestBehavior.AllowGet);\n }\n public class MvcApplication : System.Web.HttpApplication\n{\n public static void RegisterGlobalFilters(GlobalFilterCollection filters)\n {\n filters.Add(new GlobalAuthorise());\n filters.Add(new OncHandleErrorAttribute());\n //filters.Add(new HandleErrorAttribute());\n }\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556/" ]
109,916
<p>To see what file to invoke the unrar command on, one needs to determine which file is the first in the file set.</p> <p>Here are some sample file names, of which - naturally - only the first group should be matched:</p> <pre><code>yes.rar yes.part1.rar yes.part01.rar yes.part001.rar no.part2.rar no.part02.rar no.part002.rar no.part011.rar </code></pre> <p>One (limited) way to do it with PCRE compatible regexps is this:</p> <pre><code>.*(?:(?&lt;!part\d\d\d|part\d\d|\d)\.rar|\.part0*1\.rar) </code></pre> <p>This did not work in Ruby when I tested it at <a href="http://www.projects.aphexcreations.net/rejax/" rel="nofollow noreferrer">Rejax</a> however.</p> <p>How would you write one <strong>Ruby compatible</strong> regular expression to match only the first file in a set of RAR files?</p>
[ { "answer_id": 110120, "author": "Matthew Encinas", "author_id": 14433, "author_profile": "https://Stackoverflow.com/users/14433", "pm_score": 0, "selected": false, "text": "^(yes|no)\\.(rar|part0*1\\.rar)$\n" }, { "answer_id": 110122, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "if" }, { "answer_id": 110169, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": true, "text": "def is_first_rar(filename)\n if ((filename =~ /part(\\d+)\\.rar$/) == nil)\n return (filename =~ /\\.rar$/) != nil\n else\n return $1.to_i == 1\n end\nend\n def is_first_rar(filename)\n reg = Oniguruma::ORegexp.new('.*(?:(?<!part\\d\\d\\d|part\\d\\d|\\d)\\.rar|\\.part0*1\\.rar)')\n match = reg.match(filename)\n return match != nil\nend\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19392/" ]
109,931
<p>How to implement multi-threading in visual basic 6.0. It would be great if someone can give an example.</p>
[ { "answer_id": 219502, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "DoEvents" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9087/" ]
109,934
<p>I've got a generic&lt;> function that takes a linq query ('items') and enumerates through it adding additional properties. How can I select all the properties of the original 'item' rather than the item itself (as the code below does)?</p> <p>So equivalent to the sql: select *, 'bar' as Foo from items</p> <pre><code>foreach (var item in items) { var newItem = new { item, // I'd like just the properties here, not the 'item' object! Foo = "bar" }; newItems.Add(newItem); } </code></pre>
[ { "answer_id": 109967, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 0, "selected": false, "text": "from item in items\nwhere someConditionOnItem\nselect\n{\n propertyOne,\n propertyTwo\n};\n" }, { "answer_id": 109992, "author": "Kris", "author_id": 14439, "author_profile": "https://Stackoverflow.com/users/14439", "pm_score": 4, "selected": true, "text": "foreach(PropertyInfo info in item.GetType().GetProperties())\n Console.WriteLine(\"{0} = {1}\", info.Name, info.GetValue(item, null));\n" }, { "answer_id": 110000, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "ClientCollection coll = new ClientCollection();\nvar results = coll.Select(c =>\n{\n Dictionary<string, object> objlist = new Dictionary<string, object>();\n foreach (PropertyInfo pi in c.GetType().GetProperties())\n {\n objlist.Add(pi.Name, pi.GetValue(c, null));\n }\n return new { someproperty = 1, propertyValues = objlist };\n});\n" }, { "answer_id": 110109, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "public XElement ToXElement()\npublic IEnumerable ToPropertyEnumerable()\npublic Dictionary<string, object> ToNameValuePairs()\n" }, { "answer_id": 25927626, "author": "Achal kumar", "author_id": 1007119, "author_profile": "https://Stackoverflow.com/users/1007119", "pm_score": 0, "selected": false, "text": " public int DepartmentId { get; set; }\n public string DepartmentName { get; set; }\n List<DepartMent> depList = new List<DepartMent>();\n depList.Add(new DepartMent { DepartmentId = 1, DepartmentName = \"Finance\" });\n depList.Add(new DepartMent { DepartmentId = 2, DepartmentName = \"HR\" });\n depList.Add(new DepartMent { DepartmentId = 3, DepartmentName = \"IT\" });\n depList.Add(new DepartMent { DepartmentId = 4, DepartmentName = \"Admin\" });\n var result = from b in depList\n select new {Id=b.DepartmentId,Damartment=b.DepartmentName,Foo=\"bar\" };\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
109,948
<p>just a quick question:</p> <p>I am a CS undergrad and have only had experience with the Eclipse, and Net Beans IDEs. I have recently acquired a Macbook and was wanting to recompile a recent school project in Xcode just to test it out. Right after the line where I declare a new instance of an ArrayList: </p> <pre><code>dictionary = new ArrayList&lt;String&gt;(); </code></pre> <p>I get the following error: <b>generics are not supported in -source 1.3</b>.</p> <p>I was just wondering if anybody could offer advice as to what the problem might be. The same project compiles in Eclipse on the same machine. I'm running OSX 10.5.4, with Java 1.5.0_13. </p> <p>Thank you.</p>
[ { "answer_id": 109966, "author": "Nicholas Riley", "author_id": 6372, "author_profile": "https://Stackoverflow.com/users/6372", "pm_score": 4, "selected": true, "text": " <target name=\"compile\" depends=\"init\" description=\"Compile code\">\n <mkdir dir=\"${bin}\"/>\n <javac deprecation=\"on\" srcdir=\"${src}\" destdir=\"${bin}\"\n source=\"1.3\" target=\"1.2\"\n" }, { "answer_id": 163607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "/Developer/Library/XCode/Project Templates/Java/Java Tool/build.xml\n source=\"XX\" target=\"YY\"" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
109,993
<p>In the past, some of my projects have required me to create a movie version of a fullscreen Flash application. The easiest way to do this has been to get a screen capture. However, capturing anything over 1024x768 has resulted in choppy video, which is unacceptable. I understand that there are hardware based solutions for capturing fullscreen video, but I have not been able to find out what these are. My output needs to be scalable up to 1920x1080 and result in an uncompressed AVI file with no choppy-ness.</p>
[ { "answer_id": 110115, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 1, "selected": false, "text": "IViewObject::Draw OleDraw" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/109993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2715/" ]
110,016
<p>I know that <code>JTable</code> can sort by a single column. But is it possible to allow for multiple column sort or do I need to write the code myself?</p>
[ { "answer_id": 110027, "author": "Joshua", "author_id": 6013, "author_profile": "https://Stackoverflow.com/users/6013", "pm_score": 2, "selected": false, "text": "TableModel myModel = createMyTableModel();\nJTable table = new JTable(myModel);\nTableRowSorter t = new TableRowSorter(myModel);\nt.setComparator(column that the comparator works against, Comparator<?> comparator);\ntable.setRowSorter(new TableRowSorter(myModel));\n" }, { "answer_id": 110042, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "setSortKeys RowSorter" }, { "answer_id": 9376552, "author": "Ram Dutt Shukla", "author_id": 591061, "author_profile": "https://Stackoverflow.com/users/591061", "pm_score": 1, "selected": false, "text": "JTable table = new JTable();\ntable.setAutoCreateRowSorter(true);\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
110,018
<p>Anyone know? Want to be able to on the fly stamp an image with another image as a watermark, also to do large batches. Any type of existing library or a technique you know of would be great.</p>
[ { "answer_id": 110085, "author": "John West", "author_id": 19832, "author_profile": "https://Stackoverflow.com/users/19832", "pm_score": 2, "selected": false, "text": "\nvbc.exe watermark.vb /t:exe /out:watermark.exe\n \nwatermark.exe \"c:\\source folder\" \"c:\\destination folder\"\n \nImports System\nImports System.Drawing\nImports System.Drawing.Drawing2D\nImports System.Drawing.Imaging\nImports System.IO\n\nNamespace WatermarkManager\n Class Watermark\n Shared sourceDirectory As String = \"\", destinationDirectory As String = \"\"\n\n Overloads Shared Sub Main(ByVal args() As String)\n\n 'See if an argument was passed from the command line\n If args.Length = 2 Then\n sourceDirectory = args(0)\n destinationDirectory = args(1)\n\n ' make sure sourceFolder is legit\n If Directory.Exists(sourceDirectory) = False\n TerminateExe(\"Invalid source folder. Folder does not exist.\")\n Exit Sub\n End If\n\n ' try and create destination folder\n Try\n Directory.CreateDirectory(destinationDirectory)\n Catch\n TerminateExe(\"Error creating destination folder. Invalid path cannot be created.\")\n Exit Sub\n End Try\n\n ' start the magic\n CreateHierarchy(sourceDirectory,destinationDirectory)\n\n ElseIf args.Length = 1\n If args(0) = \"/?\"\n DisplayHelp()\n Else\n TerminateExe(\"expected: watermark.exe [source path] [destination path]\")\n End If\n Exit Sub\n Else\n TerminateExe(\"expected: watermark.exe [source path] [destination path]\")\n Exit Sub\n End If\n\n TerminateExe()\n End Sub\n\n Shared Sub CreateHierarchy(ByVal sourceDirectory As String, ByVal destinationDirectory As String)\n\n Dim tmpSourceDirectory As String = sourceDirectory\n\n ' copy directory hierarchy to destination folder\n For Each Item As String In Directory.GetDirectories(sourceDirectory)\n Directory.CreateDirectory(destinationDirectory + Item.SubString(Item.LastIndexOf(\"\\\")))\n\n If hasSubDirectories(Item)\n CreateSubDirectories(Item)\n End If\n Next\n\n ' reset destinationDirectory\n destinationDirectory = tmpSourceDirectory\n\n ' now that folder structure is set up, let's iterate through files\n For Each Item As String In Directory.GetDirectories(sourceDirectory)\n SearchDirectory(Item)\n Next\n End Sub\n\n Shared Function hasSubDirectories(ByVal path As String) As Boolean\n Dim subdirs() As String = Directory.GetDirectories(path)\n If subdirs.Length > 0\n Return True\n End If\n Return False\n End Function\n\n Shared Sub CheckFiles(ByVal path As String)\n For Each f As String In Directory.GetFiles(path)\n If f.SubString(f.Length-3).ToLower = \"jpg\"\n WatermarkImage(f)\n End If\n Next\n End Sub\n\n Shared Sub WatermarkImage(ByVal f As String)\n\n Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(f)\n Dim graphic As Graphics\n Dim indexedImage As New Bitmap(img)\n graphic = Graphics.FromImage(indexedImage)\n graphic.DrawImage(img, 0, 0, img.Width, img.Height)\n img = indexedImage\n\n graphic.SmoothingMode = SmoothingMode.AntiAlias\n graphic.InterpolationMode = InterpolationMode.HighQualityBicubic\n\n Dim x As Integer, y As Integer\n Dim source As New Bitmap(\"c:\\watermark.png\")\n Dim logo As New Bitmap(source, CInt(img.Width / 3), CInt(img.Width / 3))\n source.Dispose()\n x = img.Width - logo.Width\n y = img.Height - logo.Height\n graphic.DrawImage(logo, New Point(x,y))\n logo.Dispose()\n\n img.Save(destinationDirectory+f.SubString(f.LastIndexOf(\"\\\")), ImageFormat.Jpeg)\n indexedImage.Dispose()\n img.Dispose()\n graphic.Dispose()\n\n Console.WriteLine(\"successfully watermarked \" + f.SubString(f.LastIndexOf(\"\\\")+1))\n Console.WriteLine(\"saved to: \" + vbCrLf + destinationDirectory + vbCrLf)\n\n End Sub\n\n Shared Sub SearchDirectory(ByVal path As String)\n destinationDirectory = destinationDirectory + path.SubString(path.LastIndexOf(\"\\\"))\n CheckFiles(path)\n For Each Item As String In Directory.GetDirectories(path)\n destinationDirectory += Item.SubString(Item.LastIndexOf(\"\\\"))\n\n CheckFiles(Item)\n\n If hasSubDirectories(Item)\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n SearchDirectory(Item)\n destinationDirectory += Item.SubString(Item.LastIndexOf(\"\\\"))\n End If\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n Next\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n End Sub\n\n Shared Sub CreateSubDirectories(ByVal path As String)\n destinationDirectory = destinationDirectory + path.SubString(path.LastIndexOf(\"\\\"))\n For Each Item As String In Directory.GetDirectories(path)\n destinationDirectory += Item.SubString(Item.LastIndexOf(\"\\\"))\n Directory.CreateDirectory(destinationDirectory)\n Console.WriteLine(vbCrlf + \"created: \" + vbCrlf + destinationDirectory)\n\n If hasSubDirectories(Item)\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n CreateSubDirectories(Item)\n destinationDirectory += Item.SubString(Item.LastIndexOf(\"\\\"))\n End If\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n Next\n destinationDirectory = destinationDirectory.SubString(0,destinationDirectory.LastIndexOf(\"\\\"))\n End Sub\n\n Shared Sub TerminateExe(ByVal Optional msg As String = \"\")\n If msg \"\"\n Console.WriteLine(vbCrLf + \"AN ERROR HAS OCCURRED //\" + vbCrLf + msg)\n End If\n Console.WriteLine(vbCrLf + \"Press [enter] to close...\")\n 'Console.Read()\n End Sub\n\n Shared Sub DisplayHelp()\n Console.WriteLine(\"watermark.exe accepts two parameters:\" + vbCrLf + \" - [source folder]\")\n Console.WriteLine(\" - [destination folder]\")\n Console.WriteLine(\"ex.\" + vbCrLf + \"watermark.exe \"\"c:\\web_projects\\dclr source\"\" \"\"d:\\new_dclr\\copy1 dest\"\"\")\n Console.WriteLine(vbCrLf + \"Press [enter] to close...\")\n Console.Read()\n End Sub\n End Class\nEnd Namespace\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
110,031
<p>Several questions about functional programming languages have got me thinking about whether XSLT is a functional programming language. If not, what features are missing? Has XSLT 2.0 shortened or closed the gap?</p>
[ { "answer_id": 111403, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 2, "selected": false, "text": "saxon:function() {http://net.sf.saxon/java-type}net.sf.saxon.expr.UserFunctionCall saxon:call() saxon:expression() saxon:eval() saxon:expression() saxon:eval() saxon:function() saxon:call()" }, { "answer_id": 634299, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "test :: [Int] -> [Int]\ntest xs = map (+ x) xs\nwhere x = 2\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13342/" ]
110,078
<p>I need to store app specific configuration in rails. But it has to be:</p> <ul> <li>reachable in any file (model, view, helpers and controllers</li> <li>environment specified (or not), that means each environment can overwrite the configs specified in environment.rb</li> </ul> <p>I've tried to use environment.rb and put something like</p> <pre><code>USE_USER_APP = true </code></pre> <p>that worked to me but when trying to overwrite it in a specific environment it wont work because production.rb, for instance, seems to be inside the Rails:Initializer.run block.</p> <p>So, anyone?</p>
[ { "answer_id": 110307, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 2, "selected": false, "text": "lib/analytics/google_analytics.rb module Analytics\n class GoogleAnalytics\n @@account_id = nil\n\n cattr_accessor :account_id\n end\nend\n environment.rb environments/production.rb Analytics::GoogleAnalytics.account_id = \"xxxxxxxxx\"\n Analytics::GoogleAnalytics.account_id" }, { "answer_id": 110834, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 3, "selected": true, "text": "require 'ostruct'\nrequire 'yaml'\nrequire 'erb'\n#config = OpenStruct.new(YAML.load_file(\"#{RAILS_ROOT}/config/config.yml\"))\nconfig = OpenStruct.new(YAML.load(ERB.new(File.read(\"#{RAILS_ROOT}/config/config.yml\")).result))\nenv_config = config.send(RAILS_ENV)\nconfig.common.update(env_config) unless env_config.nil?\n::AppConfig = OpenStruct.new(config.common)\n development:\n path_to_something: <%= RAILS_ROOT %>/config/something.yml\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
110,081
<p>The LinearGradientBrush in .net (or even in GDI+ as a whole?) seems to have a severe bug: Sometimes, it introduces artifacts. (See <a href="http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2007-01/msg01592.html" rel="nofollow noreferrer">here</a> or <a href="http://www.experts-exchange.com/Microsoft/Development/.NET/Visual_CSharp/Q_23329115.html" rel="nofollow noreferrer">here</a> - essentially, the first line of a linear gradient is drawn in the endcolor, i.e. a gradient from White to Black will start with a Black line and then with the proper White to Black gradient)</p> <p>I wonder if anyone found a working workaround for this? This is a really annoying bug :-(</p> <p>Here is a picture of the Artifacts, note that there are 2 LinearGradientBrushes:</p> <p><a href="http://img142.imageshack.us/img142/7711/gradientartifactmm6.jpg" rel="nofollow noreferrer">alt text http://img142.imageshack.us/img142/7711/gradientartifactmm6.jpg</a></p>
[ { "answer_id": 227715, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 1, "selected": false, "text": "GradientStop" }, { "answer_id": 13729217, "author": "Hugh W", "author_id": 1688738, "author_profile": "https://Stackoverflow.com/users/1688738", "pm_score": 2, "selected": false, "text": "r Rectangle gradientRect = r;\nif (r.Width % 2 == 1)\n{\n gradientRect.Width += 1;\n}\nif (r.Height % 2 == 1)\n{\n gradientRect.Height += 1;\n}\nvar lgb = new LinearGradientBrush(gradientRect, startCol, endCol, angle);\ngraphics.FillRectangle(lgb, r);\n" }, { "answer_id": 61233252, "author": "Boris L", "author_id": 1245511, "author_profile": "https://Stackoverflow.com/users/1245511", "pm_score": 0, "selected": false, "text": " Gdiplus::RectF brushRect;\n\n graphics.SetSmoothingMode( Gdiplus::SmoothingModeHighQuality );\n\n brushRect.X = rect.left - (Gdiplus::REAL)0.5;\n brushRect.Y = rect.top - (Gdiplus::REAL)0.5;\n brushRect.Width = (Gdiplus::REAL)( rect.right - rect.left );\n brushRect.Height = (Gdiplus::REAL)( rect.bottom - rect.top );\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
110,083
<pre><code>String s = ""; for(i=0;i&lt;....){ s = some Assignment; } </code></pre> <p>or</p> <pre><code>for(i=0;i&lt;..){ String s = some Assignment; } </code></pre> <p>I don't need to use 's' outside the loop ever again. The first option is perhaps better since a new String is not initialized each time. The second however would result in the scope of the variable being limited to the loop itself.</p> <p>EDIT: In response to Milhous's answer. It'd be pointless to assign the String to a constant within a loop wouldn't it? No, here 'some Assignment' means a changing value got from the list being iterated through.</p> <p>Also, the question isn't because I'm worried about memory management. Just want to know which is better.</p>
[ { "answer_id": 110099, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "some Assignment" }, { "answer_id": 110322, "author": "Milhous", "author_id": 17712, "author_profile": "https://Stackoverflow.com/users/17712", "pm_score": 1, "selected": false, "text": "s = some Assignment;\n s = \"\" + i + \"\";\n s = some Constant;\n" }, { "answer_id": 110389, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 8, "selected": true, "text": "for ( ... ) {\n String s = ...;\n}\n javap s s String s; null void x(String[] strings, Integer[] integers) {\n String s;\n for (int i = 0; i < strings.length; ++i) {\n s = strings[0];\n ...\n }\n Integer n;\n for (int i = 0; i < integers.length; ++i) {\n n = integers[i];\n ...\n }\n}\n s n" }, { "answer_id": 111075, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 3, "selected": false, "text": "for (int i = 0; i < array.length; i++) {\n Object next = array[i];\n}\n for (int i = 0, max = array.lenth; i < max; i++) {\n Object next = array[i];\n}\n" }, { "answer_id": 745206, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 2, "selected": false, "text": "public boolean contentEquals(StringBuffer sb) {\n synchronized(sb) {\n if (count != sb.length())\n return false;\n char v1[] = value;\n char v2[] = sb.getValue();\n int i = offset;\n int j = 0;\n int n = count;\n while (n-- != 0) {\n if (v1[i++] != v2[j++])\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 17934262, "author": "Petro", "author_id": 2163927, "author_profile": "https://Stackoverflow.com/users/2163927", "pm_score": 1, "selected": false, "text": "Process one;\nBufferedInputStream two;\ntry{\none = Runtime.getRuntime().exec(command);\ntwo = new BufferedInputStream(one.getInputStream());\n}\n}catch(e){\ne.printstacktrace\n}\nfinally{\n//null to ensure they are erased\none = null;\ntwo = null;\n//nudge the gc\nSystem.gc();\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16485/" ]
110,088
<p>I'm fully aware that set division can be accomplished through a series of other operations, so my question is: </p> <p>Is there a command for set division in SQL?</p>
[ { "answer_id": 5922425, "author": "TuteC", "author_id": 356060, "author_profile": "https://Stackoverflow.com/users/356060", "pm_score": 2, "selected": false, "text": "sailors boats reserves SELECT name FROM sailors\nWHERE Sid NOT IN (\n -- A sailor is disqualified if by attaching a boat,\n -- we obtain a tuple <sailor, boat> that is not in reserves\n SELECT s.Sid\n FROM sailors s, boats b\n WHERE (s.Sid, b.Bid) NOT IN (\n SELECT Sid, Bid FROM reserves\n )\n);\n\n-- Alternatively:\nSELECT name FROM sailors s\nWHERE NOT EXISTS (\n -- Not reserved boats\n (SELECT bid FROM boats)\n EXCEPT\n (SELECT r.bid FROM reserves r\n WHERE r.sid = s.sid)\n);\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
110,121
<p>Everything inherits from object. It's the basis of inheritance. Everything can be implicitly cast up the inheritance tree, ie.</p> <pre><code>object me = new Person(); </code></pre> <p>Therefore, following this through to its logical conclusion, a group of People would also be a group of objects:</p> <pre><code>List&lt;Person&gt; people = new List&lt;Person&gt;(); people.Add(me); people.Add(you); List&lt;object&gt; things = people; // Ooops. </code></pre> <p>Except, that won't work, the people who designed .NET either overlooked this, or there's a reason, and I'm not sure which. At least once I have run into a situation where this would have been useful, but I had to end up using a nasty hack (subclassing List just to implement a cast operator). </p> <p>The question is this: is there a reason for this behaviour? Is there a simpler solution to get the desired behaviour?</p> <p>For the record, I believe the situation that I wanted this sort of behaviour was a generic printing function that displayed lists of objects by calling ToString() and formatting the strings nicely.</p>
[ { "answer_id": 110136, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 2, "selected": false, "text": "IEnumerable<Person> oldList = someIenumarable;\nIEnumerable<object> newList = oldlist.Cast<object>()\n" }, { "answer_id": 110138, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 1, "selected": false, "text": "IEnumerable<object> things = people.Cast<object>();\nList<object> things = people.Cast<object>().ToList();\n" }, { "answer_id": 110155, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 2, "selected": false, "text": "List<Person> people = new List<Person>();\nList<object> things = people; // this is not allowed\n// ...\nMouse gerald = new Mouse();\nthings.add(gerald);\n List Person Mouse A<T> A<S> S T" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
110,123
<p>I'm using ASP.NET Web Forms for blog style comments. </p> <p>Edit 1: This looks way more complicated then I first thought. How do you filter the src?<br> I would prefer to still use real html tags but if things get too complicated that way, I might go a custom route. I haven't done any XML yet, so do I need to learn more about that?</p>
[ { "answer_id": 110146, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "<img> tag, and all attributes from that except src, alt and title tag, and all attributes from that except src, alt src" }, { "answer_id": 110233, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "Look at this! [http://a.b.c/m.jpg]\n Look at this! <img src=\"http://a.b.c/m.jpg\" />\n Look at this! [javascript:alert('pwned!')]\n" }, { "answer_id": 110260, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 0, "selected": false, "text": "![alt text](/path/to/image.jpg) !imageurl!" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
110,157
<p>This is one of the possible ways I come out:</p> <pre><code>struct RetrieveKey { template &lt;typename T&gt; typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; } }; map&lt;int, int&gt; m; vector&lt;int&gt; keys; // Retrieve all keys transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey()); // Dump all keys copy(keys.begin(), keys.end(), ostream_iterator&lt;int&gt;(cout, &quot;\n&quot;)); </code></pre> <p>Of course, we can also retrieve all values from the map by defining another functor <strong>RetrieveValues</strong>.</p> <p>Is there any other way to achieve this easily? (I'm always wondering why <code>std::map</code> does not include a member function for us to do so.)</p>
[ { "answer_id": 110170, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "select1st" }, { "answer_id": 110211, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "std::map<int, int> m;\nm.insert(std::pair<int, int>(3, 4));\nm.insert(std::pair<int, int>(5, 6));\nfor(std::map<int, int>::const_iterator it = m.begin(); it != m.end(); it++)\n{\n int key = it->first;\n int value = it->second;\n //Do something\n}\n" }, { "answer_id": 110255, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 9, "selected": true, "text": "std::map<int, int> m;\nstd::vector<int> key, value;\nfor(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {\n key.push_back(it->first);\n value.push_back(it->second);\n std::cout << \"Key: \" << it->first << std::endl();\n std::cout << \"Value: \" << it->second << std::endl();\n}\n map<int,int> m;\npair<int,int> me; // what a map<int, int> is made of\nvector<int> v;\nBOOST_FOREACH(me, m) {\n v.push_back(me.first);\n cout << me.first << \"\\n\";\n}\n" }, { "answer_id": 110388, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n\nstd::map<int, int> m;\nstd::vector<int> keys;\n\nusing namespace boost::lambda;\n\ntransform( m.begin(), \n m.end(), \n back_inserter(keys), \n bind( &std::map<int,int>::value_type::first, _1 ) \n );\n\ncopy( keys.begin(), keys.end(), std::ostream_iterator<int>(std::cout, \"\\n\") );\n" }, { "answer_id": 2389291, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 2, "selected": false, "text": "template<class map_type>\nclass key_iterator : public map_type::iterator\n{\npublic:\n typedef typename map_type::iterator map_iterator;\n typedef typename map_iterator::value_type::first_type key_type;\n\n key_iterator(const map_iterator& other) : map_type::iterator(other) {} ;\n\n key_type& operator *()\n {\n return map_type::iterator::operator*().first;\n }\n};\n\n// helpers to create iterators easier:\ntemplate<class map_type>\nkey_iterator<map_type> key_begin(map_type& m)\n{\n return key_iterator<map_type>(m.begin());\n}\ntemplate<class map_type>\nkey_iterator<map_type> key_end(map_type& m)\n{\n return key_iterator<map_type>(m.end());\n}\n map<string,int> test;\n test[\"one\"] = 1;\n test[\"two\"] = 2;\n\n vector<string> keys;\n\n// // method one\n// key_iterator<map<string,int> > kb(test.begin());\n// key_iterator<map<string,int> > ke(test.end());\n// keys.insert(keys.begin(), kb, ke);\n\n// // method two\n// keys.insert(keys.begin(),\n// key_iterator<map<string,int> >(test.begin()),\n// key_iterator<map<string,int> >(test.end()));\n\n // method three (with helpers)\n keys.insert(keys.begin(), key_begin(test), key_end(test));\n\n string one = keys[0];\n" }, { "answer_id": 2794168, "author": "DanDan", "author_id": 141985, "author_profile": "https://Stackoverflow.com/users/141985", "pm_score": 6, "selected": false, "text": "std::vector<int> keys;\n\nstd::transform(\n m_Inputs.begin(),\n m_Inputs.end(),\n std::back_inserter(keys),\n [](const std::map<int,int>::value_type &pair){return pair.first;});\n" }, { "answer_id": 9572688, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 6, "selected": false, "text": "#include <boost/range/adaptor/map.hpp>\n#include <boost/range/algorithm/copy.hpp>\nvector<int> keys;\nboost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));\n" }, { "answer_id": 9693232, "author": "Juan", "author_id": 1267669, "author_profile": "https://Stackoverflow.com/users/1267669", "pm_score": 8, "selected": false, "text": "//c++0x too\nstd::map<int,int> mapints;\nstd::vector<int> vints;\nfor(auto const& imap: mapints)\n vints.push_back(imap.first);\n" }, { "answer_id": 35905762, "author": "Rusty Parks", "author_id": 4848969, "author_profile": "https://Stackoverflow.com/users/4848969", "pm_score": 3, "selected": false, "text": "std::map<uint32_t, uint32_t> items;\nstd::vector<uint32_t> itemKeys;\nfor (auto & kvp : items)\n{\n itemKeys.emplace_back(kvp.first);\n std::cout << kvp.first << std::endl;\n}\n" }, { "answer_id": 38885161, "author": "Clemens Sielaff", "author_id": 3444217, "author_profile": "https://Stackoverflow.com/users/3444217", "pm_score": 3, "selected": false, "text": "template<template <typename...> class MAP, class KEY, class VALUE>\nstd::vector<KEY>\nkeys(const MAP<KEY, VALUE>& map)\n{\n std::vector<KEY> result;\n result.reserve(map.size());\n for(const auto& it : map){\n result.emplace_back(it.first);\n }\n return result;\n}\n" }, { "answer_id": 39531911, "author": "James Hirschorn", "author_id": 1349673, "author_profile": "https://Stackoverflow.com/users/1349673", "pm_score": 5, "selected": false, "text": "using namespace std;\nvector<int> keys;\n\ntransform(begin(map_in), end(map_in), back_inserter(keys), \n [](decltype(map_in)::value_type const& pair) {\n return pair.first;\n}); \n decltype(map_in)::value_type auto" }, { "answer_id": 55676229, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": -1, "selected": false, "text": "std::map template<class KEY, class VALUE>\nstd::vector<KEY> getKeys(const std::map<KEY, VALUE>& map)\n{\n std::vector<KEY> keys(map.size());\n for (const auto& it : map)\n keys.push_back(it.first);\n return keys;\n}\n auto keys = getKeys(yourMap);\n" }, { "answer_id": 55977141, "author": "Madiyar", "author_id": 3320697, "author_profile": "https://Stackoverflow.com/users/3320697", "pm_score": 5, "selected": false, "text": "std::map<int, int> items;\nstd::vector<int> itemKeys;\n\nfor (const auto& [key, _] : items) {\n itemKeys.push_back(key);\n}\n" }, { "answer_id": 60838141, "author": "Deniz Babat", "author_id": 7709851, "author_profile": "https://Stackoverflow.com/users/7709851", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <map>\n#include <vector> \n#include <atomic>\n\nusing namespace std;\n\ntypedef std::atomic<std::uint32_t> atomic_uint32_t;\ntypedef std::map<int, atomic_uint32_t> atomic_map_t;\n\nint main()\n{\n atomic_map_t m;\n\n m[4] = 456;\n m[2] = 45678;\n\n vector<int> v;\n for(map<int,atomic_uint32_t>::iterator it = m.begin(); it != m.end(); ++it) {\n v.push_back(it->second);\n cout << it->first << \" \"<<it->second<<\"\\n\";\n }\n\n return 0;\n}\n" }, { "answer_id": 63182487, "author": "Chrissi", "author_id": 12165405, "author_profile": "https://Stackoverflow.com/users/12165405", "pm_score": 2, "selected": false, "text": "// save keys in vector\n\nvector<string> keys;\nfor (auto & it : m) {\n keys.push_back(it.first);\n}\n" }, { "answer_id": 65378776, "author": "KaiserKatze", "author_id": 4927212, "author_profile": "https://Stackoverflow.com/users/4927212", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\ntemplate <class _Map>\nstd::vector<typename _Map::key_type> keyset(const _Map& map)\n{\n std::vector<typename _Map::key_type> result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.first;\n });\n return result;\n}\n #include <vector>\n#include <iterator>\n#include <algorithm>\n#include <functional>\n\ntemplate <class _Map>\nstd::vector<typename _Map::mapped_type> valueset(const _Map& map)\n{\n std::vector<typename _Map::mapped_type> result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.second;\n });\n return result;\n}\n\ntemplate <class _Map>\nstd::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map)\n{\n std::vector<std::reference_wrapper<typename _Map::mapped_type>> result;\n result.reserve(map.size());\n std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {\n return std::ref(kvpair.second);\n });\n return result;\n}\n int main()\n{\n std::map<int, double> map{\n {1, 9.0},\n {2, 9.9},\n {3, 9.99},\n {4, 9.999},\n };\n auto ks = keyset(map);\n auto vs = valueset(map);\n for (auto& k : ks) std::cout << k << '\\n';\n std::cout << \"------------------\\n\";\n for (auto& v : vs) std::cout << v << '\\n';\n for (auto& v : vs) v += 100.0;\n std::cout << \"------------------\\n\";\n for (auto& v : vs) std::cout << v << '\\n';\n std::cout << \"------------------\\n\";\n for (auto& [k, v] : map) std::cout << v << '\\n';\n\n return 0;\n}\n 1\n2\n3\n4\n------------------\n9\n9.9\n9.99\n9.999\n------------------\n109\n109.9\n109.99\n109.999\n------------------\n109\n109.9\n109.99\n109.999\n" }, { "answer_id": 65918927, "author": "Константин Ван", "author_id": 4510033, "author_profile": "https://Stackoverflow.com/users/4510033", "pm_score": 3, "selected": false, "text": "// To get the keys\nstd::map<int, double> map;\nstd::vector<int> keys;\nkeys.reserve(map.size());\nfor(const auto& [key, value] : map) {\n keys.push_back(key);\n}\n // To get the values\nstd::map<int, double> map;\nstd::vector<double> values;\nvalues.reserve(map.size());\nfor(const auto& [key, value] : map) {\n values.push_back(value);\n}\n" }, { "answer_id": 67869753, "author": "uol3c", "author_id": 4705766, "author_profile": "https://Stackoverflow.com/users/4705766", "pm_score": 0, "selected": false, "text": "#include<fplus/maps.hpp>\n// ...\n\nint main() {\n map<string, int32_t> myMap{{\"a\", 1}, {\"b\", 2}};\n vector<string> keys = fplus::get_map_keys(myMap);\n // ...\n return 0;\n}\n" }, { "answer_id": 68094571, "author": "Mercury Dime", "author_id": 8075321, "author_profile": "https://Stackoverflow.com/users/8075321", "pm_score": 5, "selected": false, "text": "#include <ranges>\n\nauto kv = std::views::keys(m);\nstd::vector<int> keys{ kv.begin(), kv.end() };\n" }, { "answer_id": 72314969, "author": "Olppah", "author_id": 2021579, "author_profile": "https://Stackoverflow.com/users/2021579", "pm_score": 2, "selected": false, "text": "#include <ranges>\nstd::map<int,int> mapints;\nstd::vector<int> vints;\n\nstd::ranges::copy(mapints | std::views::keys, std::back_inserter(vints));\n std::ranges::copy(mapints | std::views::values, std::back_inserter(vints));\n std::ranges::copy(std::views::values(mapints), std::back_inserter(vints));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18638/" ]
110,163
<p>I have a rails model that looks something like this:</p> <pre><code>class Recipe &lt; ActiveRecord::Base has_many :ingredients attr_accessor :ingredients_string attr_accessible :title, :directions, :ingredients, :ingredients_string before_save :set_ingredients def ingredients_string ingredients.join("\n") end private def set_ingredients self.ingredients.each { |x| x.destroy } self.ingredients_string ||= false if self.ingredients_string self.ingredients_string.split("\n").each do |x| ingredient = Ingredient.create(:ingredient_string =&gt; x) self.ingredients &lt;&lt; ingredient end end end end </code></pre> <p>The idea is that when I create the ingredient from the webpage, I pass in the <code>ingredients_string</code> and let the model sort it all out. Of course, if I am editing an ingredient I need to re-create that string. The bug is basically this: how do I inform the view of the ingredient_string (elegantly) and still check to see if the <code>ingredient_string</code> is defined in the <code>set_ingredients</code> method?</p>
[ { "answer_id": 110170, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "select1st" }, { "answer_id": 110211, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "std::map<int, int> m;\nm.insert(std::pair<int, int>(3, 4));\nm.insert(std::pair<int, int>(5, 6));\nfor(std::map<int, int>::const_iterator it = m.begin(); it != m.end(); it++)\n{\n int key = it->first;\n int value = it->second;\n //Do something\n}\n" }, { "answer_id": 110255, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 9, "selected": true, "text": "std::map<int, int> m;\nstd::vector<int> key, value;\nfor(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {\n key.push_back(it->first);\n value.push_back(it->second);\n std::cout << \"Key: \" << it->first << std::endl();\n std::cout << \"Value: \" << it->second << std::endl();\n}\n map<int,int> m;\npair<int,int> me; // what a map<int, int> is made of\nvector<int> v;\nBOOST_FOREACH(me, m) {\n v.push_back(me.first);\n cout << me.first << \"\\n\";\n}\n" }, { "answer_id": 110388, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n\nstd::map<int, int> m;\nstd::vector<int> keys;\n\nusing namespace boost::lambda;\n\ntransform( m.begin(), \n m.end(), \n back_inserter(keys), \n bind( &std::map<int,int>::value_type::first, _1 ) \n );\n\ncopy( keys.begin(), keys.end(), std::ostream_iterator<int>(std::cout, \"\\n\") );\n" }, { "answer_id": 2389291, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 2, "selected": false, "text": "template<class map_type>\nclass key_iterator : public map_type::iterator\n{\npublic:\n typedef typename map_type::iterator map_iterator;\n typedef typename map_iterator::value_type::first_type key_type;\n\n key_iterator(const map_iterator& other) : map_type::iterator(other) {} ;\n\n key_type& operator *()\n {\n return map_type::iterator::operator*().first;\n }\n};\n\n// helpers to create iterators easier:\ntemplate<class map_type>\nkey_iterator<map_type> key_begin(map_type& m)\n{\n return key_iterator<map_type>(m.begin());\n}\ntemplate<class map_type>\nkey_iterator<map_type> key_end(map_type& m)\n{\n return key_iterator<map_type>(m.end());\n}\n map<string,int> test;\n test[\"one\"] = 1;\n test[\"two\"] = 2;\n\n vector<string> keys;\n\n// // method one\n// key_iterator<map<string,int> > kb(test.begin());\n// key_iterator<map<string,int> > ke(test.end());\n// keys.insert(keys.begin(), kb, ke);\n\n// // method two\n// keys.insert(keys.begin(),\n// key_iterator<map<string,int> >(test.begin()),\n// key_iterator<map<string,int> >(test.end()));\n\n // method three (with helpers)\n keys.insert(keys.begin(), key_begin(test), key_end(test));\n\n string one = keys[0];\n" }, { "answer_id": 2794168, "author": "DanDan", "author_id": 141985, "author_profile": "https://Stackoverflow.com/users/141985", "pm_score": 6, "selected": false, "text": "std::vector<int> keys;\n\nstd::transform(\n m_Inputs.begin(),\n m_Inputs.end(),\n std::back_inserter(keys),\n [](const std::map<int,int>::value_type &pair){return pair.first;});\n" }, { "answer_id": 9572688, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 6, "selected": false, "text": "#include <boost/range/adaptor/map.hpp>\n#include <boost/range/algorithm/copy.hpp>\nvector<int> keys;\nboost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));\n" }, { "answer_id": 9693232, "author": "Juan", "author_id": 1267669, "author_profile": "https://Stackoverflow.com/users/1267669", "pm_score": 8, "selected": false, "text": "//c++0x too\nstd::map<int,int> mapints;\nstd::vector<int> vints;\nfor(auto const& imap: mapints)\n vints.push_back(imap.first);\n" }, { "answer_id": 35905762, "author": "Rusty Parks", "author_id": 4848969, "author_profile": "https://Stackoverflow.com/users/4848969", "pm_score": 3, "selected": false, "text": "std::map<uint32_t, uint32_t> items;\nstd::vector<uint32_t> itemKeys;\nfor (auto & kvp : items)\n{\n itemKeys.emplace_back(kvp.first);\n std::cout << kvp.first << std::endl;\n}\n" }, { "answer_id": 38885161, "author": "Clemens Sielaff", "author_id": 3444217, "author_profile": "https://Stackoverflow.com/users/3444217", "pm_score": 3, "selected": false, "text": "template<template <typename...> class MAP, class KEY, class VALUE>\nstd::vector<KEY>\nkeys(const MAP<KEY, VALUE>& map)\n{\n std::vector<KEY> result;\n result.reserve(map.size());\n for(const auto& it : map){\n result.emplace_back(it.first);\n }\n return result;\n}\n" }, { "answer_id": 39531911, "author": "James Hirschorn", "author_id": 1349673, "author_profile": "https://Stackoverflow.com/users/1349673", "pm_score": 5, "selected": false, "text": "using namespace std;\nvector<int> keys;\n\ntransform(begin(map_in), end(map_in), back_inserter(keys), \n [](decltype(map_in)::value_type const& pair) {\n return pair.first;\n}); \n decltype(map_in)::value_type auto" }, { "answer_id": 55676229, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": -1, "selected": false, "text": "std::map template<class KEY, class VALUE>\nstd::vector<KEY> getKeys(const std::map<KEY, VALUE>& map)\n{\n std::vector<KEY> keys(map.size());\n for (const auto& it : map)\n keys.push_back(it.first);\n return keys;\n}\n auto keys = getKeys(yourMap);\n" }, { "answer_id": 55977141, "author": "Madiyar", "author_id": 3320697, "author_profile": "https://Stackoverflow.com/users/3320697", "pm_score": 5, "selected": false, "text": "std::map<int, int> items;\nstd::vector<int> itemKeys;\n\nfor (const auto& [key, _] : items) {\n itemKeys.push_back(key);\n}\n" }, { "answer_id": 60838141, "author": "Deniz Babat", "author_id": 7709851, "author_profile": "https://Stackoverflow.com/users/7709851", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <map>\n#include <vector> \n#include <atomic>\n\nusing namespace std;\n\ntypedef std::atomic<std::uint32_t> atomic_uint32_t;\ntypedef std::map<int, atomic_uint32_t> atomic_map_t;\n\nint main()\n{\n atomic_map_t m;\n\n m[4] = 456;\n m[2] = 45678;\n\n vector<int> v;\n for(map<int,atomic_uint32_t>::iterator it = m.begin(); it != m.end(); ++it) {\n v.push_back(it->second);\n cout << it->first << \" \"<<it->second<<\"\\n\";\n }\n\n return 0;\n}\n" }, { "answer_id": 63182487, "author": "Chrissi", "author_id": 12165405, "author_profile": "https://Stackoverflow.com/users/12165405", "pm_score": 2, "selected": false, "text": "// save keys in vector\n\nvector<string> keys;\nfor (auto & it : m) {\n keys.push_back(it.first);\n}\n" }, { "answer_id": 65378776, "author": "KaiserKatze", "author_id": 4927212, "author_profile": "https://Stackoverflow.com/users/4927212", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <iterator>\n#include <algorithm>\n\ntemplate <class _Map>\nstd::vector<typename _Map::key_type> keyset(const _Map& map)\n{\n std::vector<typename _Map::key_type> result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.first;\n });\n return result;\n}\n #include <vector>\n#include <iterator>\n#include <algorithm>\n#include <functional>\n\ntemplate <class _Map>\nstd::vector<typename _Map::mapped_type> valueset(const _Map& map)\n{\n std::vector<typename _Map::mapped_type> result;\n result.reserve(map.size());\n std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {\n return kvpair.second;\n });\n return result;\n}\n\ntemplate <class _Map>\nstd::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map)\n{\n std::vector<std::reference_wrapper<typename _Map::mapped_type>> result;\n result.reserve(map.size());\n std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {\n return std::ref(kvpair.second);\n });\n return result;\n}\n int main()\n{\n std::map<int, double> map{\n {1, 9.0},\n {2, 9.9},\n {3, 9.99},\n {4, 9.999},\n };\n auto ks = keyset(map);\n auto vs = valueset(map);\n for (auto& k : ks) std::cout << k << '\\n';\n std::cout << \"------------------\\n\";\n for (auto& v : vs) std::cout << v << '\\n';\n for (auto& v : vs) v += 100.0;\n std::cout << \"------------------\\n\";\n for (auto& v : vs) std::cout << v << '\\n';\n std::cout << \"------------------\\n\";\n for (auto& [k, v] : map) std::cout << v << '\\n';\n\n return 0;\n}\n 1\n2\n3\n4\n------------------\n9\n9.9\n9.99\n9.999\n------------------\n109\n109.9\n109.99\n109.999\n------------------\n109\n109.9\n109.99\n109.999\n" }, { "answer_id": 65918927, "author": "Константин Ван", "author_id": 4510033, "author_profile": "https://Stackoverflow.com/users/4510033", "pm_score": 3, "selected": false, "text": "// To get the keys\nstd::map<int, double> map;\nstd::vector<int> keys;\nkeys.reserve(map.size());\nfor(const auto& [key, value] : map) {\n keys.push_back(key);\n}\n // To get the values\nstd::map<int, double> map;\nstd::vector<double> values;\nvalues.reserve(map.size());\nfor(const auto& [key, value] : map) {\n values.push_back(value);\n}\n" }, { "answer_id": 67869753, "author": "uol3c", "author_id": 4705766, "author_profile": "https://Stackoverflow.com/users/4705766", "pm_score": 0, "selected": false, "text": "#include<fplus/maps.hpp>\n// ...\n\nint main() {\n map<string, int32_t> myMap{{\"a\", 1}, {\"b\", 2}};\n vector<string> keys = fplus::get_map_keys(myMap);\n // ...\n return 0;\n}\n" }, { "answer_id": 68094571, "author": "Mercury Dime", "author_id": 8075321, "author_profile": "https://Stackoverflow.com/users/8075321", "pm_score": 5, "selected": false, "text": "#include <ranges>\n\nauto kv = std::views::keys(m);\nstd::vector<int> keys{ kv.begin(), kv.end() };\n" }, { "answer_id": 72314969, "author": "Olppah", "author_id": 2021579, "author_profile": "https://Stackoverflow.com/users/2021579", "pm_score": 2, "selected": false, "text": "#include <ranges>\nstd::map<int,int> mapints;\nstd::vector<int> vints;\n\nstd::ranges::copy(mapints | std::views::keys, std::back_inserter(vints));\n std::ranges::copy(mapints | std::views::values, std::back_inserter(vints));\n std::ranges::copy(std::views::values(mapints), std::back_inserter(vints));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
110,175
<p>How can you automatically import the latest build/revision number in subversion?</p> <p>The goal would be to have that number visible on your webpage footer like SO does.</p>
[ { "answer_id": 110185, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 5, "selected": true, "text": "svn info <Repository-URL>\n svn info --xml <Repository-URL>\n <?xml version=\"1.0\"?>\n<info>\n<entry\n kind=\"dir\"\n path=\"cmdtools\"\n revision=\"151\">\n<url>http://myserver/svn/stumde/cmdtools</url>\n<repository>\n<root>http://myserver/svn/stumde</root>\n<uuid>a148ce7d-da11-c240-b47f-6810ff02934c</uuid>\n</repository>\n<commit\n revision=\"133\">\n<author>mstum</author>\n<date>2008-07-12T17:09:08.315246Z</date>\n</commit>\n</entry>\n</info>\n" }, { "answer_id": 110188, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "SvnRevision = $WCREV$;\n SubWCRev.exe . RevisionInfo.tmpl RevisionInfo.txt\n SvnRevision = 5000;\n" }, { "answer_id": 110192, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 4, "selected": false, "text": "svn:keywords Revision\n private const string REVISION = \"$Revision$\";\n \"$Revision: 4455$\"" }, { "answer_id": 110206, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "import pysvn\nrepo = REPOSITORY_LOCATION\nrev = pysvn.Revision( pysvn.opt_revision_kind.head )\nclient = pysvn.Client()\ninfo = client.info2(repo,revision=rev,recurse=False)\nrevno = info[0][1].rev.number # revision number as an integer\n" }, { "answer_id": 110207, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 0, "selected": false, "text": "$ svn info .\nPath: .\nURL: http://trac-hacks.org/svn/tracdeveloperplugin/trunk\nRepository Root: http://trac-hacks.org/svn\nRepository UUID: 7322e99d-02ea-0310-aa39-e9a107903beb\nRevision: 4190\nNode Kind: directory\nSchedule: normal\nLast Changed Author: coderanger\nLast Changed Rev: 3397\nLast Changed Date: 2008-03-19 00:49:02 -0400 (Wed, 19 Mar 2008)\n Process process = new Process();\nprocess.StartInfo.FileName = @\"svn.exe\";\nprocess.StartInfo.Arguments = String.Format(@\"info {0}\", path);\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.Start();\n\n// Parse the svn info output for something like \"Last Changed Rev: 1234\"\nusing (StreamReader output = process.StandardOutput)\n{\n Regex LCR = new Regex(@\"Last Changed Rev: (\\d+)\");\n\n string line;\n while ((line = output.ReadLine()) != null)\n {\n Match match = LCR.Match(line);\n if (match.Success)\n {\n revision = match.Groups[1].Value;\n }\n }\n}\n" }, { "answer_id": 110813, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 3, "selected": false, "text": "//using SharpSvn;\nlong revision = -1;\nusing(SvnClient client = new SvnClient())\n{\n client.Info(path,\n delegate(object sender, SvnInfoEventArgs e)\n {\n revision = e.Revision;\n });\n}\n" }, { "answer_id": 111173, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": false, "text": "$ svnversion\n3846\n $ echo 'foo' >> project-ext.dtd\n$ svnversion \n3846M\n $ (cd doc; svn up >/dev/null 2>/dev/null)\n$ svnversion\n3846:4182M\n" }, { "answer_id": 111259, "author": "Ryan Taylor", "author_id": 19977, "author_profile": "https://Stackoverflow.com/users/19977", "pm_score": 2, "selected": false, "text": "svn info --xml ./svnInfo.xml <xmlpeek> <!-- Retrieve the current revision number for the working directory -->\n<exec program=\"svn\" commandline='info --xml' output=\"./svnInfo.xml\" failonerror=\"false\"/>\n<xmlpeek file=\"./svnInfo.xml\" xpath=\"info/entry/@revision\" property=\"build.version.revision\" if=\"${file::exists('./svnInfo.xml')}\"/>\n\n<!-- Custom NAnt task to replace strings matching a pattern with a specific value -->\n<replace file=\"${filename}\" \n pattern=\"AssemblyVersion(?:Attribute)?\\(\\s*?\\&quot;(?&lt;version&gt;(?&lt;major&gt;[0-9]+)\\.(?&lt;minor&gt;[0-9]+)\\.(?&lt;build&gt;[0-9]+)\\.(?&lt;revision&gt;[0-9]+))\\&quot;\\s*?\\)\" \n value=\"AssemblyVersion(${build.version})\"\n outfile=\"${filename}\"/>\n replace" }, { "answer_id": 112674, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 4, "selected": false, "text": "svnversion $ svnversion\n662:738M\n $ svn info\n... snip ...\nRevision: 662\n" }, { "answer_id": 750475, "author": "mlambie", "author_id": 17453, "author_profile": "https://Stackoverflow.com/users/17453", "pm_score": 2, "selected": false, "text": "SVN_VERSION = IO.popen(\"svn info\").readlines[4].strip.split[1]\n" }, { "answer_id": 1022238, "author": "ivan_ivanovich_ivanoff", "author_id": 76393, "author_profile": "https://Stackoverflow.com/users/76393", "pm_score": 2, "selected": false, "text": "<import file=\"nbproject/build-impl.xml\"/> <!-- STORE SUBVERSION BUILD STRING -->\n<target name=\"-pre-compile\">\n <exec executable=\"svnversion\"\n output=\"${src.dir}/YOUR/PACKAGE/NAME/scm-version.txt\"/>\n</target>\n getClass().getResourceAsStream(\"scm-version.txt\"); // ...\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
110,205
<p>I want to download this open source application, and they are using Git. What do I need to download the code base?</p> <p><b>Update</b> How do I change the working directory when I am using Git Bash? (I want to download the repo at a certain directory, using pwd tells me I will be downloading the repo where I don't want it.</p>
[ { "answer_id": 110209, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "git clone git://project.url.here\n" }, { "answer_id": 110237, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 1, "selected": false, "text": "cd / C:\\stuff /c/stuff \\" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
110,229
<p>What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type?</p>
[ { "answer_id": 59404837, "author": "simon9k", "author_id": 2416245, "author_profile": "https://Stackoverflow.com/users/2416245", "pm_score": -1, "selected": false, "text": "int? n = null;\n\n//int m1 = n; // Doesn't compile\nint n2 = (int)n; // Compiles, but throws an exception if n is null\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16872/" ]
110,232
<p>I am creating a website in CakePHP and I am kind of new on it. I couldn't find good resources on this matter, so there you go:</p> <p>I have a three table structure for registering users: <code>Users</code>, <code>Addresses</code> and <code>Contacts</code>. I have to build a view with info of all three tables like:</p> <pre> Full Name: [ ] (from Users) Shipping Address: [ ] (from Address) Mobile Phone: [ ] (from Contact) e-Mail Address: [ ] (from Contact) </pre> <p>What is the best way to deal with this situation. <em>Specially for saving</em>. Creating a new Model to represent this, that will have a <code>save()</code> method itself (Maybe a sql view in the database) Create a Controller to deal with this View that <code>bind</code>s or <code>unbind</code>s info</p> <p>I wonder still how I will handle both contacts as they will be 2 different <code>INSERT</code>'s</p> <p>Any hint or resources I can dig of I will be glad.</p>
[ { "answer_id": 112685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "echo $form->create('User', array('action' => 'add');\necho $form->input('User.name');\necho $form->input('Address.line_1');\necho $form->input('Contact.tel');\necho $form->end('Save');\n ...\n\nif($this->User->saveAll($this->data)) {\n $this->Session->setFlash('Save Successful');\n $this->redirect(array('action' => 'index'));\n} else {\n $this->Session->setFlash('Please review the form for errors');\n}\n\n...\n var $hasOne = array('Address', 'Contact');\n" }, { "answer_id": 132416, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 1, "selected": false, "text": "User hasOne Address, Contact\nAddress belongsTo User\nContact belongsTo User\n class User extends AppModel {\nvar $name = 'User';\nvar $hasOne = array('Address','Contact');\n..\n $this->User->recursive = 1;\n$this->set('user', $this->User->find('first', array('conditions'=>array('id'=>666)));\n array(\n 'Use' => array(\n 'id' => 666,\n 'name' => 'Alexander'\n),\n 'Address' => array(\n 'id' => 123,\n 'zip' => 555\n),\n 'Contact' => array(\n 'id' => 432,\n 'phone' => '555-1515'\n));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
110,249
<p>Since VS 2005, I see that it is not possible to simply build a dll against MS runtime and deploy them together (<a href="http://www.ddj.com/windows/184406482" rel="nofollow noreferrer">http://www.ddj.com/windows/184406482</a>). I am deeply confused by manifest, SxS and co: MSDN documentation is really poor, with circular references; specially since I am more a Unix guy, I find all those uninformative. My core problem is linking a dll against msvc9 or msvc8: since those runtime are not redistributable, what are the steps to link and deploy such a dll ? In particular, how are the manifest generated (I don't want mt.exe, I want something which is portable across compilers), how are they embedded, used ? What does Side by side assembly mean ?</p> <p>Basically, where can I find any kind of specification instead of MS jargon ?</p> <p>Thank you to everyone who answered, this was really helpful, </p>
[ { "answer_id": 113022, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 3, "selected": true, "text": "/*----------------------------------------------------------------------------*/\n\n#if _MSC_VER >= 1400\n\n/*----------------------------------------------------------------------------*/\n\n#pragma message ( \"Setting up manifest...\" )\n\n/*----------------------------------------------------------------------------*/\n\n#ifndef _CRT_ASSEMBLY_VERSION\n#include <crtassem.h>\n#endif \n\n/*----------------------------------------------------------------------------*/\n\n#ifdef WIN64\n #pragma message ( \"processorArchitecture=amd64\" )\n #define MF_PROCESSORARCHITECTURE \"amd64\"\n#else\n #pragma message ( \"processorArchitecture=x86\" )\n #define MF_PROCESSORARCHITECTURE \"x86\"\n#endif \n\n/*----------------------------------------------------------------------------*/\n\n#pragma message ( \"Microsoft.Windows.Common-Controls=6.0.0.0\") \n#pragma comment ( linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='Microsoft.Windows.Common-Controls' \" \\\n \"version='6.0.0.0' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='6595b64144ccf1df'\\\"\" )\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef _DEBUG\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".DebugCRT=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".DebugCRT' \" \\\n \"version='\" _CRT_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n#else\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".CRT=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".CRT' \" \\\n \"version='\" _CRT_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n#endif\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef _MFC_ASSEMBLY_VERSION\n #ifdef _DEBUG\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC' \" \\\n \"version='\" _MFC_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n #else\n #pragma message ( __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC=\" _CRT_ASSEMBLY_VERSION ) \n #pragma comment(linker,\"/manifestdependency:\\\"type='win32' \" \\\n \"name='\" __LIBRARIES_ASSEMBLY_NAME_PREFIX \".MFC' \" \\\n \"version='\" _MFC_ASSEMBLY_VERSION \"' \" \\\n \"processorArchitecture='\" MF_PROCESSORARCHITECTURE \"' \" \\\n \"publicKeyToken='\" _VC_ASSEMBLY_PUBLICKEYTOKEN \"'\\\"\")\n #endif\n#endif /* _MFC_ASSEMBLY_VERSION */\n\n/*----------------------------------------------------------------------------*/\n\n#endif /* _MSC_VER */\n\n/*----------------------------------------------------------------------------*/\n" }, { "answer_id": 225950, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 2, "selected": false, "text": "C:\\Program Files\\Microsoft Visual Studio 8\\VC\\redist\\x86\\Microsoft.VC80.CRT\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11465/" ]
110,259
<p>I want to know the memory usage of my Python application and specifically want to know what code blocks/portions or objects are consuming most memory. Google search shows a commercial one is <a href="http://www.softwareverify.com/python/memory/index.html" rel="noreferrer">Python Memory Validator</a> (Windows only).</p> <p>And open source ones are <a href="http://pysizer.8325.org/" rel="noreferrer">PySizer</a> and <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="noreferrer">Heapy</a>.</p> <p>I haven't tried anyone, so I wanted to know which one is the best considering:</p> <ol> <li><p>Gives most details.</p></li> <li><p>I have to do least or no changes to my code.</p></li> </ol>
[ { "answer_id": 110272, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 6, "selected": false, "text": "# memdebug.py\n\nimport cherrypy\nimport dowser\n\ndef start(port):\n cherrypy.tree.mount(dowser.Root())\n cherrypy.config.update({\n 'environment': 'embedded',\n 'server.socket_port': port\n })\n cherrypy.server.quickstart()\n cherrypy.engine.start(blocking=False)\n CherryPy 2.X CherryPy 3.X server.quickstart engine.start blocking CherryPy 3.X # memdebug.py\n\nimport cherrypy\nimport dowser\n\ndef start(port):\n cherrypy.tree.mount(dowser.Root())\n cherrypy.config.update({\n 'environment': 'embedded',\n 'server.socket_port': port\n })\n cherrypy.engine.start()\n" }, { "answer_id": 110826, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 9, "selected": true, "text": "from guppy import hpy\nh = hpy()\nprint(h.heap())\n Partition of a set of 132527 objects. Total size = 8301532 bytes.\nIndex Count % Size % Cumulative % Kind (class / dict of class)\n0 35144 27 2140412 26 2140412 26 str\n1 38397 29 1309020 16 3449432 42 tuple\n2 530 0 739856 9 4189288 50 dict (no owner)\n" }, { "answer_id": 10592072, "author": "Fabian Pedregosa", "author_id": 505591, "author_profile": "https://Stackoverflow.com/users/505591", "pm_score": 9, "selected": false, "text": "@profile -m memory_profiler Line # Mem usage Increment Line Contents\n==============================================\n 3 @profile\n 4 5.97 MB 0.00 MB def my_func():\n 5 13.61 MB 7.64 MB a = [1] * (10 ** 6)\n 6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)\n 7 13.61 MB -152.59 MB del b\n 8 13.61 MB 0.00 MB return a\n" }, { "answer_id": 17447650, "author": "jmdana", "author_id": 1231093, "author_profile": "https://Stackoverflow.com/users/1231093", "pm_score": 4, "selected": false, "text": "from memprof import memprof\n @memprof\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6946/" ]
110,263
<p>I am trying to add a project reference or swc to papervision in FlashDevelop but intellisense isn't picking it up. I've done it before but i forgot how.</p> <p>Thanks.</p>
[ { "answer_id": 110588, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 3, "selected": false, "text": "Project -> Properties -> Compiler Options -> SWC Libraries \n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748529/" ]
110,281
<p>How can I make a style have all of the properties of the style defined in <code>.a .b .c</code> except for <code>background-color</code> (or some other property)? This does not seem to work.</p> <pre><code>.a .b .c { background-color: #0000FF; color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; } .a .b .c .d { background-color: green; } </code></pre>
[ { "answer_id": 110287, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": ".a, .b, .c {color: #ffffff; border: 1px solid #c0c0c0; margin-top: 4px; padding: 3px; text-align: center; font-weight: bold; }\n\n.a {background-color: red;}\n\n.b {background-color: blue;}\n\n.c {background-color: green;}\n" }, { "answer_id": 110291, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": true, "text": ".a .b .c,\n.d { \n background-color: #0000FF;\n color: #ffffff;\n border: 1px solid #c0c0c0;\n margin-top: 4px;\n padding: 3px;\n text-align: center;\n font-weight: bold; \n}\n\n.d {\n background-color: green;\n}\n" }, { "answer_id": 110296, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 1, "selected": false, "text": "<html>\n <head>\n <style type=\"text/css\">\n .a, .b, .c, .d { background-color: #0000FF; color: #FF0000; border: 1px solid #00FF00; font-weight: bold; }\n .d { background-color: white; }\n </style>\n </head>\n <body style=\"background-color: grey;\">\n <p class=\"a\">Lorem ipsum dolor sit amet.</p>\n <p class=\"b\">Lorem ipsum dolor sit amet.</p>\n <p class=\"c\">Lorem ipsum dolor sit amet.</p>\n <p class=\"d\">Lorem ipsum dolor sit amet.</p>\n </body>\n </html>\n" }, { "answer_id": 110315, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": ".a .b .c{\n background-color: #0000FF;\n color: #ffffff;\n}\n <div class=\"a\">\n <div class=\"b\">\n <div class=\"c\">foo</div>\n <div class=\"c d\">bar</div>\n </div>\n</div>\n" }, { "answer_id": 12912679, "author": "Someone", "author_id": 1749718, "author_profile": "https://Stackoverflow.com/users/1749718", "pm_score": 2, "selected": false, "text": ".a, .b, .c, .d\n{\n background-color: green;\n}\n\n.a, .b, .c\n{\n background-color: #0000FF;\n color: #ffffff;\n border: 1px solid #c0c0c0;\n margin-top: 4px;\n padding: 3px;\n text-align: center;\n font-weight: bold;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
110,305
<p>I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox?</p> <p>You can view the live page <a href="http://www.taxminimiser.com/beta/whats_included.php" rel="nofollow noreferrer">here</a>. I know, I'm working on positioning the sidebar. Ignore that for now.</p> <p>Markup is as follows:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/global.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/whats_included.css" /&gt; &lt;script type="text/javascript" src="script/compliant_target_blank.js"&gt;&lt;/script&gt; &lt;!--[if lte IE 5]&gt; &lt;script type="text/javascript" src="script/ie_5_unsupported_warning.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 5]&gt; &lt;link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" /&gt; &lt;![endif]--&gt; &lt;title&gt; The Daily Plan-It, LLC - Home of the Tax MiniMiser &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include("includes/nav_bar.php") ?&gt; &lt;div id="content"&gt; &lt;img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" /&gt; &lt;div id="bordered_wrapper"&gt; &lt;h1&gt;Here's What You Get With The Tax MiniMiser!&lt;/h1&gt; &lt;h2&gt;24 Envelopes, 7-hole punched to fit one-at-a-time in your binder&lt;/h2&gt; &lt;ol&gt; &lt;li class="main_item"&gt; Business Income &amp;amp; Expense Record &lt;div class="preview_image"&gt; &lt;a href="previews/large/bier/front.html" rel="external"&gt; &lt;img src="images/small_previews/large/bier_preview.jpg" alt="" /&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;12 receipt envelopes with all the income &amp;amp; expense columns you need to transform your planner or binder into a daily tax journal!&lt;/li&gt; &lt;li&gt;Store daily receipts in the convenient pocket envelopes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p&gt;To get a free copy of the &amp;quot;20 Column Heading Guidelines&amp;quot;, &lt;a href="files/downloads/20_column_heading_guidelines.pdf"&gt;click here&lt;/a&gt; or call our Fax-on-Demand line at 888-829-8237.&lt;/p&gt; &lt;/li&gt; &lt;li class="main_item"&gt; Vehicle Mileage &amp;amp; Expense Record &lt;div class="preview_image"&gt; &lt;a href="previews/large/vme/front.html" rel="external"&gt; &lt;img src="images/small_previews/large/mileage_preview.jpg" alt=""/&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).&lt;/li&gt; &lt;li&gt;Store daily receipts in the convenient pocket envelopes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p&gt;To get a free copy of the &amp;quot;Instructions for Vehicle Mileage &amp;amp; Expense Record&amp;quot;, &lt;a href="files/downloads/vehicle_record_instructions.pdf"&gt;click here&lt;/a&gt; or call our Fax-on-Demand line at 888-829-8237.&lt;/p&gt; &lt;/li&gt; &lt;li class="main_item"&gt; Annual Business Summary of Income and Expense &lt;div class="preview_image"&gt; &lt;a href="previews/large/cover/inside.html" rel="external"&gt; &lt;img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /&gt;&lt;br/&gt; Click to Preview! &lt;/a&gt; &lt;/div&gt; &lt;div class="details"&gt; &lt;ul&gt; &lt;li&gt;Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ol&gt; &lt;p class="end"&gt;To see previews of the small (6&amp;quot; x 8&amp;frac12;&amp;quot;) Tax MiniMisers, visit their respective pages &lt;a href="products.php"&gt;here.&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php include("includes/footer.php") ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the CSS:</p> <pre><code>#content { background-color: white; } #bordered_wrapper { margin-left: 26px; background: top left no-repeat url(../images/borders/yellow-box-top.gif); } #bordered_wrapper h1, #bordered_wrapper h2 { margin-left: 20px; } #bordered_wrapper h1 { padding-top: 15px; margin-bottom: 0; } #bordered_wrapper h2 { margin-top: 0; font-size: 1.3em; } ol { font-size: 1.1em; } ul { list-style-type: disc; } li.main_item { width: 700px; clear: right; } li p { clear: both; margin-bottom: 20px; } .preview_image { width: 200px; float: right; text-align: center; margin-bottom: 10px; } .preview_image a { text-decoration: none; } .preview_image img { border-style: none; } .end { clear: right; padding-bottom: 25px; padding-left: 20px; background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif); } </code></pre>
[ { "answer_id": 131103, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 5, "selected": true, "text": "...\n\nol {\n font-size: 1.1em;\n}\n\n...\n\nli.main_item {\n width: 700px;\n clear: right;\n}\n\n...\n ...\n\nol {\n font-size: 1.1em;\n width: 700px;\n}\n\n...\n\nli.main_item {\n clear: right;\n}\n\n...\n" }, { "answer_id": 2213646, "author": "Jesse Dijkstra", "author_id": 267773, "author_profile": "https://Stackoverflow.com/users/267773", "pm_score": 0, "selected": false, "text": "vertical-align: top;\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10140/" ]
110,313
<p>If our organisation were to switch from a central-server VCS like subversion to a distributed VCS like git, how do I make sure that all my code is safe from hardware failure?</p> <p>With a central-server VCS I just need to backup the repository every day. If we were using a DVCS then there'd be loads of code branches on all the developer machines, and if that hardware were to fail (or a dev were to lose his laptop or have it stolen) then we wouldn't have any backups.</p> <p>Note that I don't consider it a good option to "make the developers push branches to a server" -- that's <a href="http://www.mattblodgett.com/2008/02/matt-blodgett-first-law-of-software.html" rel="nofollow noreferrer">tedious</a> and the developers will end up not doing it.</p> <p>Is there a common way around this problem?</p> <p><strong>Some clarification:</strong></p> <p>With a natively-central-server VCS then <em>everything</em> has to be on the central server except the developer's most recent changes. So, for example, if a developer decides to branch to do a bugfix, that branch is on the central server and available for backup immediately.</p> <p>If we're using a DVCS then the developer can do a local branch (and in fact many local branches). None of those branches are on the central server and available for backup until the developer thinks, "oh yeah, I should push that to the central server".</p> <p>So the difference I'm seeing (correct me if I'm wrong!): Half-implemented features and bugfixes will probably not available for backup on the central server if we're using a DVCS, but are with a normal VCS. How do I keep that code safe?</p>
[ { "answer_id": 110619, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 5, "selected": true, "text": "git mybackup git push origin +refs/heads/*:refs/jbloggs/*\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
110,314
<p>So, I am using the Linq entity framework. I have 2 entities: <code>Content</code> and <code>Tag</code>. They are in a many-to-many relationship with one another. <code>Content</code> can have many <code>Tags</code> and <code>Tag</code> can have many <code>Contents</code>. So I am trying to write a query to select all contents where any tags names are equal to <code>blah</code></p> <p>The entities both have a collection of the other entity as a property(but no IDs). This is where I am struggling. I do have a custom expression for <code>Contains</code> (so, whoever may help me, you can assume that I can do a "contains" for a collection). I got this expression from: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2670710&amp;SiteID=1</a></p> <h2>Edit 1</h2> <p><a href="https://stackoverflow.com/questions/110314/linq-to-entities-building-where-clauses-to-test-collections-within-a-many-to-ma#131551">I ended up finding my own answer.</a></p>
[ { "answer_id": 110348, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "tags.Select(testTag => testTag.Name)\n" }, { "answer_id": 110363, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 2, "selected": false, "text": "contentQuery.Where(\n content => content.Tags.Any(tag => tag.Name == \"blah\")\n);\n" }, { "answer_id": 111544, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "contentQuery.Where(\n content => content.Tags.Any(tag => tags.Any(t => t.Name == tag.Name))\n);\n" }, { "answer_id": 113215, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 0, "selected": false, "text": "IEnumerable<Tag> otherTags;\n...\nvar query = from content in contentQuery\n where content.Tags.Intersection(otherTags).Any()\n select content;\n contentQuery .Tags" }, { "answer_id": 126832, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var filter = BuildContainsExpression<Element, string>(e => e.Name, tags.Select(t => t.Name));\nvar query = source.Where(e => e.NestedValues.Any(filter));\n" }, { "answer_id": 131551, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 5, "selected": true, "text": "return sequence.ToReadOnlyCollection<Expression>();\n return sequence.AsReadOnly();\n public class ParameterRebinder : ExpressionVisitor {\n private readonly Dictionary<ParameterExpression, ParameterExpression> map;\n\n public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) {\n this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();\n }\n\n public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp) {\n return new ParameterRebinder(map).Visit(exp);\n }\n\n internal override Expression VisitParameter(ParameterExpression p) {\n ParameterExpression replacement;\n if (map.TryGetValue(p, out replacement)) {\n p = replacement;\n }\n return base.VisitParameter(p);\n }\n }\n public static class ExpressionExtensions {\n public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) {\n // build parameter map (from parameters of second to parameters of first)\n var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);\n\n // replace parameters in the second lambda expression with parameters from the first\n var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);\n\n // apply composition of lambda expression bodies to parameters from the first expression \n return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);\n }\n\n public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) {\n return first.Compose(second, Expression.And);\n }\n\n public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) {\n return first.Compose(second, Expression.Or);\n }\n }\n public static class PredicateBuilder {\n public static Expression<Func<T, bool>> True<T>() { return f => true; }\n public static Expression<Func<T, bool>> False<T>() { return f => false; }\n\n}\n public static IList<Content> GetAllContentByTags(IList<Tag> tags) {\n IQueryable<Content> contentQuery = ...\n\n Expression<Func<Content, bool>> predicate = PredicateBuilder.False<Content>();\n\n foreach (Tag individualTag in tags) {\n Tag tagParameter = individualTag;\n predicate = predicate.Or(p => p.Tags.Any(tag => tag.Name.Equals(tagParameter.Name)));\n }\n\n IQueryable<Content> resultExpressions = contentQuery.Where(predicate);\n\n return resultExpressions.ToList();\n }\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19854/" ]
110,325
<p>Obviously I can use BCP but here is the issue. If one of the records in a Batch have an invalid date I want to redirect that to a separate table/file/whatever, but keep the batch processing running. I don't think SSIS can be installed on the server which would have helped.</p>
[ { "answer_id": 110372, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 4, "selected": true, "text": "BULK INSERT your_database.your_schema.your_table FROM your_file WITH (FIRE_TRIGGERS )\n" }, { "answer_id": 110382, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 0, "selected": false, "text": "// **this is untested, there could be syntax errors**\n\n// if we have tables like this:\nCREATE TABLE tempoary (id VARCHAR(255), theDate VARCHAR(255), somethingElse VARCHAR(255))\nCREATE TABLE theGood (id INT, theDate DATETIME, somethingElse VARCHAR(255))\nCREATE TABLE theBad (id INT, theDate VARCHAR(255))\n\n// then after getting the data into [tempoary], do this:\nDECLARE tempCursor CURSOR\nFOR SELECT id, theDate, somethingElse FROM temporary\n\nOPEN tempCursor\n\nDECLARE @id VARCHAR(255)\nDECLARE @theDate VARCHAR(255)\nDECLARE @somethingElse VARCHAR(255)\n\nFETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse\nWhile (@@FETCH_STATUS <> -1)\nBEGIN\n IF ISDATE(@theDate)\n BEGIN\n INSERT INTO theGood (id, theDate, somethingElse)\n VALUES (CONVERT(INT, @id), CONVERT(DATETIME, theDate), somethingElse)\n END\n ELSE\n BEGIN\n INSERT INTO theBad (id, theDate)\n VALUES (CONVERT(INT, @id), theDate)\n END\n FETCH NEXT FROM tempCursor INTO @id, @theDate, @somethingElse\nEND\nCLOSE tempCursor\nDEALLOCATE tempCursor\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19857/" ]
110,332
<p>I have an <code>NSArray</code> and I'd like to create a new <code>NSArray</code> with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a <code>BOOL</code>.</p> <p>I can create an <code>NSMutableArray</code>, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.</p> <p>Is there a better way?</p>
[ { "answer_id": 110343, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 8, "selected": true, "text": "NSArray NSMutableArray NSArray NSMutableArray NSMutableArray *array =\n [NSMutableArray arrayWithObjects:@\"Bill\", @\"Ben\", @\"Chris\", @\"Melissa\", nil];\n\nNSPredicate *bPredicate =\n [NSPredicate predicateWithFormat:@\"SELF beginswith[c] 'b'\"];\nNSArray *beginWithB =\n [array filteredArrayUsingPredicate:bPredicate];\n// beginWithB contains { @\"Bill\", @\"Ben\" }.\n\nNSPredicate *sPredicate =\n [NSPredicate predicateWithFormat:@\"SELF contains[c] 's'\"];\n[array filteredArrayUsingPredicate:sPredicate];\n// array now contains { @\"Chris\", @\"Melissa\" }\n" }, { "answer_id": 308108, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 4, "selected": false, "text": "@implementation BaseClass (SomeCategory)\n- (BOOL)myMethod {\n return someComparisonFunction(self, whatever);\n}\n@end\n - (NSArray *)myFilteredObjects {\n NSPredicate *pred = [NSPredicate predicateWithFormat:@\"myMethod = TRUE\"];\n return [myArray filteredArrayUsingPredicate:pred];\n}\n" }, { "answer_id": 3857136, "author": "Clay Bridges", "author_id": 45813, "author_profile": "https://Stackoverflow.com/users/45813", "pm_score": 6, "selected": false, "text": "-[NSArray indexesOfObjectsPassingTest:] -select: -filter:" }, { "answer_id": 13288927, "author": "pckill", "author_id": 934710, "author_profile": "https://Stackoverflow.com/users/934710", "pm_score": 6, "selected": false, "text": "yourArray testFunc yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {\n return [self testFunc:obj];\n}]];\n" }, { "answer_id": 15809114, "author": "Durai Amuthan.H", "author_id": 730807, "author_profile": "https://Stackoverflow.com/users/730807", "pm_score": 2, "selected": false, "text": "NSPredicate NSArray NSSet NSDictionary arr filteredarr NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"SELF contains[c] %@\",@\"c\"];\n\nfilteredarr = [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];\n *--select * from tbl where column1 like '%a%'--*\n NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"SELF contains[c] %@\",@\"c\"]; [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];\n" }, { "answer_id": 19517418, "author": "Stuart", "author_id": 429427, "author_profile": "https://Stackoverflow.com/users/429427", "pm_score": 7, "selected": false, "text": "[NSPredicate predicateWithBlock:] NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {\n return [object shouldIKeepYou]; // Return YES for each object you want in filteredArray.\n}]];\n NSArray let filteredArray = array.filter { $0.shouldIKeepYou() }\n filter Array NSArray Array Bool true" }, { "answer_id": 39212304, "author": "Jordi Puigdellívol", "author_id": 478020, "author_profile": "https://Stackoverflow.com/users/478020", "pm_score": 0, "selected": false, "text": "NSArray* youngHeroes = [self.heroes filter:^BOOL(Hero *object) {\n return object.age.intValue < 20;\n}];\n NSArray* oldHeroes = [self.heroes reject:^BOOL(Hero *object) {\n return object.age.intValue < 20;\n}];\n" }, { "answer_id": 53385048, "author": "jalmatari", "author_id": 1896440, "author_profile": "https://Stackoverflow.com/users/1896440", "pm_score": 0, "selected": false, "text": "- (NSArray *) filter:(NSArray *)array where:(NSString *)key is:(id)value{\n NSMutableArray *temArr=[[NSMutableArray alloc] init];\n for(NSDictionary *dic in self)\n if([dic[key] isEqual:value])\n [temArr addObject:dic];\n return temArr;\n}\n" }, { "answer_id": 65767962, "author": "Dan Rosenstark", "author_id": 8047, "author_profile": "https://Stackoverflow.com/users/8047", "pm_score": 0, "selected": false, "text": "- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {\n NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {\n return block(obj);\n }];\n\n return [self objectsAtIndexes:filteredIndexes];\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
110,336
<p>Here's my issue: I need to close a process, already running, from a C# program. The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never have a main window. </p> <p>The other requirement that I have is that the application be <strong>closed</strong> not <strong>killed</strong>. I need it to write it's memory buffers to disk - and killing it causes data loss.</p> <p>Here's what I tried so far:</p> <pre><code> foreach (Process proc in Process.GetProcesses()) { if (proc.ProcessName.ToLower().StartsWith("myapp")) { if (proc.MainWindowHandle.ToInt32() != 0) { proc.CloseMainWindow(); proc.Close(); //proc.Kill(); &lt;--- not good! } } } </code></pre> <p>I've added the <strong>if</strong> clause, after discovering that <strong>MainWindowHandle == 0</strong> when the window was minimized. Removing the <strong>if</strong> doesn't help. Neither the <strong>CloseMainWindow()</strong> nor the <strong>Close()</strong> work. The <strong>Kill()</strong> does, but as mentioned above - it's not what I need.</p> <p>Any idea would be accepted, including the use of arcane Win32 API functions :)</p>
[ { "answer_id": 110413, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 2, "selected": false, "text": "[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nprivate static extern IntPtr FindWindow(string className, string windowName);\n[DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\nprivate static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\nprivate const int WM_CLOSE = 0x10;\nprivate const int WM_QUIT = 0x12;\n\npublic void SearchAndDestroy(string windowName) \n{\n IntPtr hWnd = FindWindow(null, windowName);\n if (hWnd == IntPtr.Zero)\n throw new Exception(\"Couldn't find window!\");\n SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);\n}\n WM_CLOSE WM_QUIT" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19856/" ]
110,344
<p>What would be the most optimal algorithm (performance-wise) to calculate the number of divisors of a given number?</p> <p>It'll be great if you could provide pseudocode or a link to some example.</p> <p>EDIT: All the answers have been very helpful, thank you. I'm implementing the Sieve of Atkin and then I'm going to use something similar to what Jonathan Leffler indicated. The link posted by Justin Bozonier has further information on what I wanted.</p>
[ { "answer_id": 110358, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "factor(N)\n divisor = first_prime\n list_of_factors = { 1 }\n while (N > 1)\n while (N % divisor == 0)\n add divisor to list_of_factors\n N /= divisor\n divisor = next_prime\n return list_of_factors\n" }, { "answer_id": 110365, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 7, "selected": true, "text": "n n = a^x * b^y * c^z (x + 1) * (y + 1) * (z + 1)" }, { "answer_id": 110404, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "for z in 1..n:\n prime[z] = false\nprime[2] = true;\nprime[3] = true;\n\nfor x in 1..sqrt(n):\n xx = x * x\n\n for y in 1..sqrt(n):\n yy = y * y\n\n z = 4*xx+yy\n if (z <= n) and ((z mod 12 == 1) or (z mod 12 == 5)):\n prime[z] = not prime[z]\n\n z = z-xx\n if (z <= n) and (z mod 12 == 7):\n prime[z] = not prime[z]\n\n z = z-yy-yy\n if (z <= n) and (x > y) and (z mod 12 == 11):\n prime[z] = not prime[z]\n\nfor z in 5..sqrt(n):\n if prime[z]:\n zz = z*z\n x = zz\n while x <= limit:\n prime[x] = false\n x = x + zz\n\nfor z in 2,3,5..n:\n if prime[z]:\n if n modulo z == 0 then print z\n" }, { "answer_id": 111659, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "n" }, { "answer_id": 118712, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 5, "selected": false, "text": "import operator\n# A slightly efficient superset of primes.\ndef PrimesPlus():\n yield 2\n yield 3\n i = 5\n while True:\n yield i\n if i % 6 == 1:\n i += 2\n i += 2\n# Returns a dict d with n = product p ^ d[p]\ndef GetPrimeDecomp(n):\n d = {}\n primes = PrimesPlus()\n for p in primes:\n while n % p == 0:\n n /= p\n d[p] = d.setdefault(p, 0) + 1\n if n == 1:\n return d\ndef NumberOfDivisors(n):\n d = GetPrimeDecomp(n)\n powers_plus = map(lambda x: x+1, d.values())\n return reduce(operator.mul, powers_plus, 1)\n" }, { "answer_id": 1146643, "author": "Michael", "author_id": 96717, "author_profile": "https://Stackoverflow.com/users/96717", "pm_score": 3, "selected": false, "text": "def factors(n):\n for x in xrange(2,n):\n if n%x == 0:\n return (x,) + factors(n/x)\n return (n,1)\n" }, { "answer_id": 4566355, "author": "Igbanam", "author_id": 393021, "author_profile": "https://Stackoverflow.com/users/393021", "pm_score": 2, "selected": false, "text": "n 1...n int divisors (int x) {\n int limit = x;\n int numberOfDivisors = 1;\n\n for (int i(0); i < limit; ++i) {\n if (x % i == 0) {\n limit = x / i;\n numberOfDivisors++;\n }\n }\n\n return numberOfDivisors * 2;\n}\n" }, { "answer_id": 5406805, "author": "Kendall", "author_id": 673211, "author_profile": "https://Stackoverflow.com/users/673211", "pm_score": 5, "selected": false, "text": "int divisors(int x) {\n int limit = x;\n int numberOfDivisors = 0;\n\n if (x == 1) return 1;\n\n for (int i = 1; i < limit; ++i) {\n if (x % i == 0) {\n limit = x / i;\n if (limit != i) {\n numberOfDivisors++;\n }\n numberOfDivisors++;\n }\n }\n\n return numberOfDivisors;\n}\n" }, { "answer_id": 8089159, "author": "Houman Javidpour", "author_id": 1040891, "author_profile": "https://Stackoverflow.com/users/1040891", "pm_score": 3, "selected": false, "text": "for(int i=1,n=9;((!(n%i)) && printf(\"%d is a divisor of %d\\n\",i,n)) || i<=(n/2);i++);//n is your number\n int number_of_divisors(int n)\n{\n int counter,i;\n for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++);\n return counter;\n}\n int number_of_divisors(int n)\n{\n int counter,i;\n for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++);\n return ++counter;\n}\n int number_of_divisors(int n)\n{\n int counter,i;\n for(counter=0,i=1;(!(n%i) && (counter++)) || i<=(n/2);i++);\n if (n==2 || n==1)\n {\n return counter;\n }\n return ++counter;\n}\n int number_of_divisors(int n)\n{\n int counter,i;\nfor(counter=0,i=1;(!(i==n) && !(n%i) && (counter++)) || i<=(n/2);i++);\n return ++counter;\n}\n" }, { "answer_id": 14248156, "author": "abdelkarim", "author_id": 1965013, "author_profile": "https://Stackoverflow.com/users/1965013", "pm_score": 1, "selected": false, "text": "for (int i = 0 ; i < size && P[i]<=sq ; i++){\n nd = 1;\n while(n%P[i]==0){\n n/=P[i];\n nd++;\n }\n count*=nd;\n if (n==1)break;\n }\n if (n!=1)count*=2;//the confusing line :D :P .\n\n i will lift the understanding for the reader .\n i now look forward to a method more optimized .\n" }, { "answer_id": 15825953, "author": "Antony Thomas", "author_id": 984378, "author_profile": "https://Stackoverflow.com/users/984378", "pm_score": 4, "selected": false, "text": "def divisors(n):\n count = 2 # accounts for 'n' and '1'\n i = 2\n while i ** 2 < n:\n if n % i == 0:\n count += 2\n i += 1\n if i ** 2 == n:\n count += 1\n return count\n\n" }, { "answer_id": 25384820, "author": "Lavish Kothari", "author_id": 2346131, "author_profile": "https://Stackoverflow.com/users/2346131", "pm_score": 1, "selected": false, "text": "#include<stdio.h>\n#include<math.h>\nint main()\n{\n int i,n,limit,numberOfDivisors=1;\n printf(\"Enter the number : \");\n scanf(\"%d\",&n);\n limit=(int)sqrt((double)n);\n for(i=2;i<=limit;i++)\n if(n%i==0)\n {\n if(i!=n/i)\n numberOfDivisors+=2;\n else\n numberOfDivisors++;\n }\n printf(\"%d\\n\",numberOfDivisors);\n return 0;\n}\n for(i=2;i*i<=n;i++)\n{\n ...\n}\n" }, { "answer_id": 27229013, "author": "Adilli Adil", "author_id": 2172507, "author_profile": "https://Stackoverflow.com/users/2172507", "pm_score": 1, "selected": false, "text": "public static List<Integer> divisors(n) { \n ArrayList<Integer> aList = new ArrayList();\n int top_count = (int) Math.round(Math.sqrt(n));\n int new_n = n;\n\n for (int i = 2; i <= top_count; i++) {\n if (new_n == (new_n / i) * i) {\n aList.add(i);\n new_n = new_n / i;\n top_count = (int) Math.round(Math.sqrt(new_n));\n i = 1;\n }\n }\n aList.add(new_n);\n return aList;\n}\n" }, { "answer_id": 27230021, "author": "Эсмер Амрахлы", "author_id": 2571400, "author_profile": "https://Stackoverflow.com/users/2571400", "pm_score": 2, "selected": false, "text": "#include <iostream>\nint main() {\n int num = 20; \n int numberOfDivisors = 1;\n\n for (int i = 2; i <= num; i++)\n {\n int exponent = 0;\n while (num % i == 0) {\n exponent++; \n num /= i;\n } \n numberOfDivisors *= (exponent+1);\n }\n\n std::cout << numberOfDivisors << std::endl;\n return 0;\n}\n" }, { "answer_id": 27241334, "author": "Malik", "author_id": 4313876, "author_profile": "https://Stackoverflow.com/users/4313876", "pm_score": 2, "selected": false, "text": "class PrintDivisors\n{\n public static void main(String args[])\n {\n\n System.out.println(\"Enter the number\");\n\n // Create Scanner object for taking input\n Scanner s=new Scanner(System.in);\n\n // Read an int\n int n=s.nextInt();\n\n // Loop from 1 to 'n'\n for(int i=1;i<=n;i++)\n {\n\n // If remainder is 0 when 'n' is divided by 'i',\n if(n%i==0)\n {\n System.out.print(i+\", \");\n }\n }\n\n // Print [not necessary] \n System.out.print(\"are divisors of \"+n);\n\n }\n}\n" }, { "answer_id": 35259290, "author": "dondon", "author_id": 5896200, "author_profile": "https://Stackoverflow.com/users/5896200", "pm_score": 0, "selected": false, "text": "@echo off\n\nmodecon:cols=100 lines=100\n\n:start\ntitle Enter the Number to Determine \ncls\necho Determine a number as a product of 2 numbers\necho.\necho Ex1 : C = A * B\necho Ex2 : 8 = 4 * 2\necho.\necho Max Number length is 9\necho.\necho If there is only 1 proces done it\necho means the number is a prime number\necho.\necho Prime numbers take time to determine\necho Number not prime are determined fast\necho.\n\nset /p number=Enter Number : \nif %number% GTR 999999999 goto start\n\necho.\nset proces=0\nset mindet=0\nset procent=0\nset B=%Number%\n\n:Determining\n\nset /a mindet=%mindet%+1\n\nif %mindet% GTR %B% goto Results\n\nset /a solution=%number% %%% %mindet%\n\nif %solution% NEQ 0 goto Determining\nif %solution% EQU 0 set /a proces=%proces%+1\n\nset /a B=%number% / %mindet%\n\nset /a procent=%mindet%*100/%B%\n\nif %procent% EQU 100 set procent=%procent:~0,3%\nif %procent% LSS 100 set procent=%procent:~0,2%\nif %procent% LSS 10 set procent=%procent:~0,1%\n\ntitle Progress : %procent% %%%\n\n\n\nif %solution% EQU 0 echo %proces%. %mindet% * %B% = %number%\ngoto Determining\n\n:Results\n\ntitle %proces% Results Found\necho.\n@pause\ngoto start\n" }, { "answer_id": 40551199, "author": "as2d3", "author_id": 6712710, "author_profile": "https://Stackoverflow.com/users/6712710", "pm_score": 1, "selected": false, "text": "long long int FindDivisors(long long int n) {\n long long int count = 0;\n long long int i, m = (long long int)sqrt(n);\n for(i = 1;i <= m;i++) {\n if(n % i == 0)\n count += 2;\n }\n if(n / m == m && n % m == 0)\n count--;\n return count;\n}\n" }, { "answer_id": 41810453, "author": "Hissaan Ali", "author_id": 6737387, "author_profile": "https://Stackoverflow.com/users/6737387", "pm_score": 0, "selected": false, "text": ">>>factors=[ x for x in range (1,n+1) if n%x==0]\nprint len(factors)" }, { "answer_id": 41810534, "author": "Bryant James", "author_id": 6743506, "author_profile": "https://Stackoverflow.com/users/6743506", "pm_score": 0, "selected": false, "text": "int divisors(int myNum) {\n int limit = myNum;\n int divisorCount = 0;\n if (x == 1) \n return 1;\n for (int i = 1; i < limit; ++i) {\n if (myNum % i == 0) {\n limit = myNum / i;\n if (limit != i)\n divisorCount++;\n divisorCount++;\n }\n }\n return divisorCount;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9776/" ]
110,354
<p>I want to do this:</p> <pre><code>e.className = t; </code></pre> <p>Where t is the name of a style I have defined in a stylesheet.</p>
[ { "answer_id": 110357, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "button.style.fontFamily = \"Verdana, Arial, sans-serif\";\n button" }, { "answer_id": 110361, "author": "jonah", "author_id": 19861, "author_profile": "https://Stackoverflow.com/users/19861", "pm_score": 5, "selected": true, "text": "e .t {color:green;} e.className = 't';\n" }, { "answer_id": 113938, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": ".error\n{\n color: red;\n}\n var error=document.getElementById('error');\nerror.className='error';\n" }, { "answer_id": 64066221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "// js\n $(\"p:first\").addClass(\"t\");\n $(\"p:first\").removeClass(\"t\");\n\n// css\n .t {\n backgound: red\n }\n" }, { "answer_id": 72700153, "author": "Mouzam Ali", "author_id": 7188711, "author_profile": "https://Stackoverflow.com/users/7188711", "pm_score": 0, "selected": false, "text": "document.getElementById('id').className = 't'\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
110,362
<p>As the title says, how can I find the current operating system in python?</p>
[ { "answer_id": 110368, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": false, "text": "import os\nprint(os.name)\n" }, { "answer_id": 110829, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 9, "selected": true, "text": "sys.platform sys.platform os.name posix" }, { "answer_id": 7174725, "author": "lenooh", "author_id": 529663, "author_profile": "https://Stackoverflow.com/users/529663", "pm_score": 4, "selected": false, "text": "import os\nif os.name == \"posix\":\n print(os.system(\"uname -a\"))\n# insert other possible OSes here\n# ...\nelse:\n print(\"unknown OS\")\n" }, { "answer_id": 10091465, "author": "Jens Timmerman", "author_id": 869482, "author_profile": "https://Stackoverflow.com/users/869482", "pm_score": 9, "selected": false, "text": ">>> import platform\n>>> platform.platform()\n'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'\n platform >>> platform.system()\n'Windows'\n>>> platform.release()\n'XP'\n>>> platform.version()\n'5.1.2600'\n import platform\nimport sys\n\ndef linux_distribution():\n try:\n return platform.linux_distribution()\n except:\n return \"N/A\"\n\ndef dist():\n try:\n return platform.dist()\n except:\n return \"N/A\"\n\nprint(\"\"\"Python version: %s\ndist: %s\nlinux_distribution: %s\nsystem: %s\nmachine: %s\nplatform: %s\nuname: %s\nversion: %s\nmac_ver: %s\n\"\"\" % (\nsys.version.split('\\n'),\nstr(dist()),\nlinux_distribution(),\nplatform.system(),\nplatform.machine(),\nplatform.platform(),\nplatform.uname(),\nplatform.version(),\nplatform.mac_ver(),\n))\n Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]']\ndist: ('', '', '')\nlinux_distribution: ('', '', '')\nsystem: SunOS\nmachine: sun4u\nplatform: SunOS-5.9-sun4u-sparc-32bit-ELF\nuname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')\nversion: Generic_122300-60\nmac_ver: ('', ('', '', ''), '')\n Python version: ['2.7.16 (default, Dec 21 2020, 23:00:36) ', '[GCC Apple LLVM 12.0.0 (clang-1200.0.30.4) [+internal-os, ptrauth-isa=sign+stri'] \ndist: ('', '', '') \nlinux_distribution: ('', '', '') \nsystem: Darwin \nmachine: arm64 \nplatform: Darwin-20.3.0-arm64-arm-64bit \nuname: ('Darwin', 'Nautilus.local', '20.3.0', 'Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', 'arm64', 'arm') \nversion: Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101 \nmac_ver: ('10.16', ('', '', ''), 'arm64')\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
110,378
<p>How can I change the width of a textarea form element if I used ModelForm to create it?</p> <p>Here is my product class:</p> <pre><code>class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product </code></pre> <p>And the template code...</p> <pre><code>{% for f in form %} {{ f.name }}:{{ f }} {% endfor %} </code></pre> <p><code>f</code> is the actual form element...</p>
[ { "answer_id": 110414, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 8, "selected": true, "text": "long_desc #id_long_desc {\n width: 300px;\n height: 200px;\n}\n attrs class ProductForm(ModelForm):\n long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))\n short_desc = forms.CharField(widget=forms.Textarea)\n class Meta:\n model = Product\n class ProductForm(ModelForm):\n long_desc = forms.CharField(widget=forms.Textarea)\n short_desc = forms.CharField(widget=forms.Textarea)\n class Meta:\n model = Product\n\n # Edit by bryan\n def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['long_desc'].widget.attrs['cols'] = 10\n self.fields['long_desc'].widget.attrs['rows'] = 20\n" }, { "answer_id": 640680, "author": "bryan", "author_id": 73049, "author_profile": "https://Stackoverflow.com/users/73049", "pm_score": 4, "selected": false, "text": "def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['long_desc'].widget.attrs['cols'] = 10\n self.fields['long_desc'].widget.attrs['cols'] = 20\n" }, { "answer_id": 25192228, "author": "bergdesign", "author_id": 1186380, "author_profile": "https://Stackoverflow.com/users/1186380", "pm_score": 4, "selected": false, "text": "def __init__(self, *args, **kwargs):\n super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor\n self.fields['short_desc'].widget.attrs['style'] = 'width:400px; height:40px;'\n self.fields['long_desc'].widget.attrs['style'] = 'width:800px; height:80px;'\n" }, { "answer_id": 49065416, "author": "Cubiczx", "author_id": 2053708, "author_profile": "https://Stackoverflow.com/users/2053708", "pm_score": 1, "selected": false, "text": "'explicacion': AutosizedTextarea(attrs={'rows': 5, 'class': 'input-xxlarge', 'style': 'width: 99% !important; resize: vertical !important;'}),\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
110,384
<p>I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?</p> <p>Doesn't work:</p> <pre><code> [AttributeUsage(AttributeTargets.Method)] public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext context) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = View("User/Login"); } } } </code></pre>
[ { "answer_id": 110630, "author": "Jeremy Skinner", "author_id": 8560, "author_profile": "https://Stackoverflow.com/users/8560", "pm_score": 2, "selected": true, "text": "public void OnAuthorization(AuthorizationContext context)\n{\n if (!context.HttpContext.User.Identity.IsAuthenticated)\n {\n context.Result = new ViewResult { ViewName = \"Whatever\" };\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
110,385
<p>I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below.</p> <p>I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue.</p> <ul> <li>Is there a better way to do this?</li> <li>Is it a good idea to unhook are rehook the event handlers like I did.</li> </ul> <p>Here's the code. </p> <pre><code>private Queue&lt;CheckBox&gt; favAttributesLimiter - new Queue&lt;CheckBox&gt;(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue&lt;CheckBox&gt;(list); } } } </code></pre> <p>Edit: <br /> <a href="https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398">Chakrit</a> answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.</p>
[ { "answer_id": 110398, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": true, "text": "AddLast Enqueue RemoveFirst Dequeue Remove" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1880/" ]
110,393
<p>I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk.</p> <p>It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this?</p> <p><strike>Edit: The printing &amp; streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content.</strike></p> <p>Edit: Printing is cool.</p>
[ { "answer_id": 110412, "author": "SemiColon", "author_id": 1994, "author_profile": "https://Stackoverflow.com/users/1994", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n FILE* fd = fopen(\"filename.xml\", \"rb\"); // Read-only mode\nint fsize = fseek(fd, 0, SEEK_END); // Get file size\nrewind(fd);\nchar* buffer = (char*)calloc(fsize + 1, sizeof(char));\nfread(buffer, fsize, 1, fd);\nfclose(fd);\n" }, { "answer_id": 395441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "// Create a TiXmlDocument \nTiXmlDocument *pDoc =new TiXmlDocument(\"my_doc_name\");\n\n// Add some content to the document, you might fill in something else ;-) \nTiXmlComment* comment = new TiXmlComment(\"hello world\" ); \npDoc->LinkEndChild( comment );\n\n// Declare a printer \nTiXmlPrinter printer;\n\n// attach it to the document you want to convert in to a std::string \npDoc->Accept(&printer);\n\n// Create a std::string and copy your document data in to the string \nstd::string str = printer.CStr();\n" }, { "answer_id": 853479, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 5, "selected": false, "text": "TiXmlDocument doc;\n// populate document here ...\n\nTiXmlPrinter printer;\nprinter.SetIndent( \" \" );\n\ndoc.Accept( &printer );\nstd::string xmltext = printer.CStr();\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14278/" ]
110,430
<p>Do you write one test per function/method, with multiple checks in the test, or a test for each check?</p>
[ { "answer_id": 110461, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 6, "selected": true, "text": "@Test\npublic void userCannotVoteDownWhenScoreIsLessThanOneHundred() {\n ...\n}\n" }, { "answer_id": 110563, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 1, "selected": false, "text": "@Test\npublic void deleteAllWithNullInput() { ... }\n\n@Test(expect=\"MyException.class\") // not sure about actual syntax here :-P\npublic void deleteAllWithEmptyInput() { ... }\n\n@Test\npublic void deleteAllWithSingleLineInput() { ... }\n\n@Test\npublic void deleteAllWithMultipleLinesInput() { ... }\n @Test\npublic void insertAndDelete() { \n assertTrue(/*stuff does not exist yet*/);\n createStuff();\n assertTrue(/*stuff does exist now*/);\n deleteStuff();\n assertTrue(/*stuff does not exist anymore*/);\n}\n" }, { "answer_id": 110618, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 2, "selected": false, "text": "def testGetCountReturnsCountAndEnd(self):\n count, endReached = self.handler.getCount()\n self.assertEqual(count, 0)\n self.assertTrue(endReached)\n def testGetCountReturnsOneAfterPut(self):\n self.assertEqual(self.handler.getCount(), 0)\n self.handler.put('foo')\n self.assertEqual(self.handler.getCount(), 1)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ]
110,433
<p>Are there any Common Lisp implementations for .Net?</p>
[ { "answer_id": 58422645, "author": "mythz", "author_id": 85785, "author_profile": "https://Stackoverflow.com/users/85785", "pm_score": 2, "selected": false, "text": "#Script #Script #Script fn def defn #Script #Script dotnet $ dotnet tool install -g x\n $ x lisp\n $ dotnet tool install -g app\n #Script" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
110,436
<p>Any recommended practices for cleaning up "header spaghetti" which is causing extremely slow compilation times (Linux/Unix)?</p> <p>Is there any equvalent to "#pragma once" with GCC?<br> (found conflicting messages regarding this)</p> <p>Thanks.</p>
[ { "answer_id": 110489, "author": "jasonmray", "author_id": 17230, "author_profile": "https://Stackoverflow.com/users/17230", "pm_score": 3, "selected": false, "text": "#pragma once #pragma once #include" }, { "answer_id": 110608, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 4, "selected": true, "text": "#ifndef MY_HEADER\n#include \"myheader.h\"\n#endif\n #ifndef MY_HEADER\n#define MY_HEADER\n\n// content of header\n\n#endif\n" }, { "answer_id": 110737, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "#include \"AAA.hpp\"\n#include \"BBB.hpp\"\n #include \"BBB.hpp\"\n#include \"AAA.hpp\"\n" }, { "answer_id": 111264, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 1, "selected": false, "text": ".c .cpp #include .h #include #define .h #include #include #include" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
110,451
<p>I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There <em>are</em> templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere?</p>
[ { "answer_id": 676745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress\\ProjectTemplates\\1033\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress\\ProjectTemplates\\CSharp\\Windows\\1033\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VWDExpress.exe /installvstemplates\n C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\VCSExpress.exe /installvstemplates\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14607/" ]
110,458
<p>I'm new to developing things on the web. So far, I'm spending a lot of time (50% or so) to try and prevent bad people from putting things like sql injection into my input forms and validating it server side. Is this normal? </p>
[ { "answer_id": 110526, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 3, "selected": false, "text": "mysqli PDO $result = \"SELECT fields FROM table WHERE id = \".mysql_real_escape_string($_POST['id']);\n id 1 OR 1=1\n SELECT fields FROM table WHERE id = 1 OR 1=1\n 1 OR 1=1 echo '<img src= \"' . htmlspecialchars($_GET['imagesrc']) . '\" />';\n javascript:alert(document.cookie) <img src= \"javascript:alert(document.cookie)\" />\n echo \"<img src= '\" . htmlspecialchars($_GET['imagesrc']) . \". />\";\n pic.png' onclick='location.href=xxx' onmouseover='...\n <img src='pic.png' onclick='location.href=xxx' onmouseover='...' />\n $str = mb_convert_encoding($str, ‘UTF-8′, ‘UTF-8′);\n$str = htmlentities($str, ENT_QUOTES, ‘UTF-8′);\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
110,488
<p>I am looking for a better solution than what we currently have to deal with <strong>unexpected production errors</strong>, without reinventing the wheel.</p> <p>A larger number of our products are WinForm and WPF applications that are installed at remote sites. Inevitably unexpected errors occur, from NullReferenceExceptions to 'General network errors'. Thus ranging from programmer errors to environment problems.</p> <p>Currently all these unhandled exceptions are logged using log4net and then emailed back to us for <strong>analysis</strong>. However we found that sometimes these error 'reports' contain too little information to identify the problem. </p> <p>In these reports we need information such as:</p> <ol> <li>Application name</li> <li>Application Version</li> <li>Workstation</li> <li>Maybe a screen shot</li> <li>Exception details</li> <li>Operating system</li> <li>Available RAM </li> <li>Running processes</li> <li>And so on...</li> </ol> <p>I don't really want to re-invent the wheel by developing this from scratch. Components that are required:</p> <ol> <li>Error collection (details as mentioned above)</li> <li>Error 'sender' (Queuing required if DB or Internet is unavailable)</li> <li>Error database</li> <li>Analysis and reporting of these errors. E.g. 10 most frequent errors or timeouts occur between 4:00PM and 5:00PM. How do the errors compare between version x and y?</li> </ol> <p>Note: We looked at <a href="http://www.smartassembly.com" rel="nofollow noreferrer">SmartAssembly</a> as a possible solution but although close it didn't quite met our needs and I was hoping to hear what other developers do and if some alternatives exist.</p> <p><strong>Edit:</strong> Thanks for the answers so far. Maybe I wasn't clear in my original question, the problem is not how to catch all unhanded exceptions but rather how to deal with them and to create a reporting engine (analysis) around them.</p>
[ { "answer_id": 110501, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 2, "selected": false, "text": "[STAThread]\nstatic void Main() \n{\n Application.ThreadException += new ThreadExceptionEventHandler(OnUnhandledException);\n Application.Run(new FormStartUp());\n}\nstatic void OnUnhandledException(object sender, ThreadExceptionEventArgs t) \n{\n // Log\n}\n static class EntryPoint {\n [MTAThread]\n static void Main() {\n // Add Global Exception Handler\n AppDomain.CurrentDomain.UnhandledException += \n new UnhandledExceptionEventHandler(OnUnhandledException);\n\n Application.Run(new Form1());\n }\n\n // In CF case only, ALL unhandled exceptions come here\n private static void OnUnhandledException(Object sender, \n UnhandledExceptionEventArgs e) {\n Exception ex = e.ExceptionObject as Exception;\n if (ex != null) {\n // Can't imagine e.IsTerminating ever being false\n // or e.ExceptionObject not being an Exception\n SomeClass.SomeStaticHandlingMethod(ex, e.IsTerminating);\n }\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11123/" ]
110,498
<p>Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.</p>
[ { "answer_id": 110547, "author": "olt", "author_id": 19759, "author_profile": "https://Stackoverflow.com/users/19759", "pm_score": 5, "selected": false, "text": ">>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.bogosoft.com\")\n>>> conn.request(\"GET\", \"\")\n>>> r1 = conn.getresponse()\n>>> print r1.status, r1.reason\n301 Moved Permanently\n>>> print r1.getheader('Location')\nhttp://www.bogosoft.com/new/location\n" }, { "answer_id": 110808, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "import sys\nimport urllib2\n\nclass RedirectHandler(urllib2.HTTPRedirectHandler):\n def http_error_301(self, req, fp, code, msg, headers): \n result = urllib2.HTTPRedirectHandler.http_error_301( \n self, req, fp, code, msg, headers) \n result.status = code \n raise Exception(\"Permanent Redirect: %s\" % 301)\n\n def http_error_302(self, req, fp, code, msg, headers):\n result = urllib2.HTTPRedirectHandler.http_error_302(\n self, req, fp, code, msg, headers) \n result.status = code \n raise Exception(\"Temporary Redirect: %s\" % 302)\n\ndef main(script_name, url):\n opener = urllib2.build_opener(RedirectHandler)\n urllib2.install_opener(opener)\n print urllib2.urlopen(url).read()\n\nif __name__ == \"__main__\":\n main(*sys.argv) \n" }, { "answer_id": 111066, "author": "Ashish", "author_id": 19607, "author_profile": "https://Stackoverflow.com/users/19607", "pm_score": 3, "selected": false, "text": "from httplib2 import Http\ndef get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects\nconn = Http()\nreturn conn.request(uri,redirections=num_redirections)\n" }, { "answer_id": 5352695, "author": "Carles Barrobés", "author_id": 166761, "author_profile": "https://Stackoverflow.com/users/166761", "pm_score": 4, "selected": false, "text": "class NoRedirectHandler(urllib2.HTTPRedirectHandler):\n def http_error_302(self, req, fp, code, msg, headers):\n infourl = urllib.addinfourl(fp, headers, req.get_full_url())\n infourl.status = code\n infourl.code = code\n return infourl\n http_error_300 = http_error_302\n http_error_301 = http_error_302\n http_error_303 = http_error_302\n http_error_307 = http_error_302\n\nopener = urllib2.build_opener(NoRedirectHandler())\nurllib2.install_opener(opener)\n" }, { "answer_id": 9494012, "author": "Tzury Bar Yochay", "author_id": 9296, "author_profile": "https://Stackoverflow.com/users/9296", "pm_score": 3, "selected": false, "text": "class NoRedirect(urllib2.HTTPRedirectHandler):\n def redirect_request(self, req, fp, code, msg, hdrs, newurl):\n pass\n\nnoredir_opener = urllib2.build_opener(NoRedirect())\n" }, { "answer_id": 10587613, "author": "Ian Mackinnon", "author_id": 201665, "author_profile": "https://Stackoverflow.com/users/201665", "pm_score": 3, "selected": false, "text": "redirections httplib2 RedirectLimit follow_redirects False Http import httplib2\nh = httplib2.Http()\nh.follow_redirects = False\n(response, body) = h.request(\"http://example.com\")\n" }, { "answer_id": 14678220, "author": "Marian", "author_id": 1228491, "author_profile": "https://Stackoverflow.com/users/1228491", "pm_score": 9, "selected": true, "text": "import requests\nr = requests.get('http://github.com', allow_redirects=False)\nprint(r.status_code, r.headers['Location'])\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
110,512
<p>I'm currently running mongrel clusters with monit watching over them for 8 Rails applications on one server.</p> <p>I'd like to move 7 of these applications to mod_rails, with one remaining on mongrel. The 7 smaller applications are low-volume, while the one I'd like to remain on mongrel is a high volume, app.</p> <p>As I understand it, this would be the best solution - as the setting PassengerPoolIdleTime only can be applied at a global level.</p> <p>What configuration gotchas should I look out for with this type of setup?</p>
[ { "answer_id": 110799, "author": "tomtaylor", "author_id": 19079, "author_profile": "https://Stackoverflow.com/users/19079", "pm_score": 3, "selected": true, "text": "<Directory \"/var/www/app/current/public\">\n Options FollowSymLinks\n AllowOverride None\n Order allow,deny\n Allow from all\n</Directory>\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
110,533
<p>Joel always said to be careful when using 3rd party libraries. From my initial impressions, jQuery is great. What should I beware of when using it? What are the limitations? What headaches will I run into later on as I use it more?</p>
[ { "answer_id": 120853, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "$(\"a tip\")\n.you()\n.can()\n.chain()\n.stuff()\n.like()\n.this();\n var $tip = $(\"a tip\");\n$tip.choo();\n$tip.choo();\n$tip.train();\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
110,536
<p>I have the following code:</p> <pre><code>string prefix = "OLD:"; Func&lt;string, string&gt; prependAction = (x =&gt; prefix + x); prefix = "NEW:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.</p> <p>Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:</p> <pre><code>Func&lt;string, string&gt; prependAction = (x =&gt; "OLD:" + x); </code></pre> <p>The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize. </p> <p>The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:</p> <pre><code>string prefix = "NEW:"; var prepender = new Prepender {Prefix = prefix}; Func&lt;string, string&gt; prependAction = prepender.Prepend; prefix = "OLD:"; Console.WriteLine(prependAction("brownie")); </code></pre> <p>With helper class:</p> <pre><code>[Serializable] public class Prepender { public string Prefix { get; set; } public string Prepend(string str) { return Prefix + str; } } </code></pre> <p>This seems like a lot of extra work to get the compiler to be "dumb".</p>
[ { "answer_id": 110540, "author": "Dested", "author_id": 11137, "author_profile": "https://Stackoverflow.com/users/11137", "pm_score": -1, "selected": false, "text": "string prefix = \"OLD:\";\nstring _prefix=prefix;\nFunc<string, string> prependAction = (x => _prefix + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n" }, { "answer_id": 110541, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": -1, "selected": false, "text": "string prefix = \"OLD:\";\nstring prefixCopy = prefix;\nFunc<string, string> prependAction = (x => prefixCopy + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n" }, { "answer_id": 110546, "author": "Bittercoder", "author_id": 4843, "author_profile": "https://Stackoverflow.com/users/4843", "pm_score": 0, "selected": false, "text": "string prefix = \"OLD:\";\nvar actionPrefix = prefix;\nFunc<string, string> prependAction = (x => actionPrefix + x);\nprefix = \"NEW:\";\nConsole.WriteLine(prependAction(\"brownie\"));\n Func<string, string> prependAction = (x => ~prefix + x);\n" }, { "answer_id": 110555, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "NonSerializable nonSerializable = new NonSerializable();\nFunc<string, string> prependAction = (x => nonSerializable.ToString() + x);\n NonSerializable nonSerializable = new NonSerializable();\nstring prefix = nonSerializable.ToString();\nFunc<string, string> prependAction = (x => prefix + x);\n" }, { "answer_id": 110598, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "public void static Func<string, string> MakePrependAction(String prefix){\n return (x => prefix + x);\n}\n" }, { "answer_id": 110647, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "var prepend = \"OLD:\";\n\nFunc<string, Func<string, string>> makePrepender = x => y => (x + y);\nFunc<string, string> oldPrepend = makePrepender(prepend);\n\nprepend = \"NEW:\";\n\nConsole.WriteLine(oldPrepend(\"Brownie\"));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ]
110,562
<p>I need to write a function that receives a property as a parameter and execute its getter.</p> <p>If I needed to pass a function/delegate I would have used:</p> <pre><code>delegate RET FunctionDelegate&lt;T, RET&gt;(T t); void func&lt;T, RET&gt;(FunctionDelegate function, T param, ...) { ... return function.Invoke(param); } </code></pre> <p>Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?</p>
[ { "answer_id": 110621, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 4, "selected": true, "text": "value = obj.GetType().GetProperty(\"Foo\").GetAccessors()[0].Invoke(obj,null);\n obj.GetType().GetProperty(\"Foo\").GetAccessors()[1].Invoke(obj,new object[]{value});\n delegate RET FunctionDelegate<T, RET>(T t);\n\nvoid func<T, RET>(FunctionDelegate<T,RET> function, T param, ...)\n{\n ...\n return function(param);\n}\n SomeClass obj = new SomeClass();\nfunc<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj);\n" }, { "answer_id": 4132483, "author": "Bartosz Pierzchlewicz", "author_id": 194520, "author_profile": "https://Stackoverflow.com/users/194520", "pm_score": 4, "selected": false, "text": "static void Method<T, U>(this T obj, Expression<Func<T, U>> property)\n {\n var memberExpression = property.Body as MemberExpression;\n //getter\n U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);\n //setter\n obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);\n }\n DbComputerSet cs = new DbComputerSet();\ncs.Method<DbComputerSet, string>(set => set.Code);\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
110,575
<p>Earlier today a question was asked regarding <a href="https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d">input validation strategies in web apps</a>.</p> <p>The top answer, at time of writing, suggests in <code>PHP</code> just using <code>htmlspecialchars</code> and <code>mysql_real_escape_string</code>. </p> <p>My question is: Is this always enough? Is there more we should know? Where do these functions break down?</p>
[ { "answer_id": 110576, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 9, "selected": true, "text": "mysqli PDO mysql_real_escape_string mysql_real_escape_string $result = \"SELECT fields FROM table WHERE id = \".mysql_real_escape_string($_POST['id']);\n id 1 OR 1=1\n SELECT fields FROM table WHERE id= 1 OR 1=1\n 1 or is_admin=1 order by id limit 1\n SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1\n 1 OR 1=1 htmlspecialchars() echo '<img src= \"' . htmlspecialchars($_GET['imagesrc']) . '\" />';\n javascript:alert(document.cookie) <img src= \"javascript:alert(document.cookie)\" />\n htmlspecialchars echo \"<img src= '\" . htmlspecialchars($_GET['imagesrc']) . \". />\";\n pic.png' onclick='location.href=xxx' onmouseover='...\n <img src='pic.png' onclick='location.href=xxx' onmouseover='...' />\n htmlspecialchars($string) $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');\n$str = htmlentities($str, ENT_QUOTES, 'UTF-8');\n" }, { "answer_id": 116237, "author": "BrilliantWinter", "author_id": 20579, "author_profile": "https://Stackoverflow.com/users/20579", "pm_score": 2, "selected": false, "text": "function Numbers($input) {\n $input = preg_replace(\"/[^0-9]/\",\"\", $input);\n if($input == '') $input = 0;\n return $input;\n}\n" }, { "answer_id": 116305, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": false, "text": "SELECT fields FROM table WHERE id='\".mysql_real_escape_string($_GET['id']).\"'\"\n SELECT fields FROM table WHERE id='1 OR 1=1'\n" }, { "answer_id": 7654297, "author": "cnizzardini", "author_id": 530151, "author_profile": "https://Stackoverflow.com/users/530151", "pm_score": 2, "selected": false, "text": "$result = \"SELECT fields FROM table WHERE id = \".(INT) $_GET['id'];\n" }, { "answer_id": 42865322, "author": "Jarett L", "author_id": 7703090, "author_profile": "https://Stackoverflow.com/users/7703090", "pm_score": -1, "selected": false, "text": "input =~ s/'//g;" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1820/" ]
110,587
<p>in a DB2 trigger, I need to compare the value of a CLOB field. Something like:</p> <pre><code>IF OLD_ROW.CLOB_FIELD != UPDATED_ROW.CLOB_FIELD </code></pre> <p>but "!=" does not work for comparing CLOBs.</p> <p>What is the way to compare it?</p> <p><strong>Edited to add:</strong></p> <p>My trigger needs to do some action if the Clob field was changed during an update. This is the reason I need to compare the 2 CLOBs in the trigger code. <strong>I'm looking for some detailed information on how this can be done</strong></p>
[ { "answer_id": 266524, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 3, "selected": false, "text": "select * from table t where dbms_lob.compare(t.clob1, t.clob2) != 0\n DBMS_LOB.COMPARE (\n lob_1 IN BLOB,\n lob_2 IN BLOB,\n amount IN INTEGER := 4294967295,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER;\n\nDBMS_LOB.COMPARE (\n lob_1 IN CLOB CHARACTER SET ANY_CS,\n lob_2 IN CLOB CHARACTER SET lob_1%CHARSET,\n amount IN INTEGER := 4294967295,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER; \n\nDBMS_LOB.COMPARE (\n lob_1 IN BFILE,\n lob_2 IN BFILE,\n amount IN INTEGER,\n offset_1 IN INTEGER := 1,\n offset_2 IN INTEGER := 1)\n RETURN INTEGER;\n" }, { "answer_id": 266540, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": -1, "selected": false, "text": "!= <>" }, { "answer_id": 1007646, "author": "Michael Sharek", "author_id": 1958, "author_profile": "https://Stackoverflow.com/users/1958", "pm_score": 2, "selected": false, "text": "CREATE TRIGGER trig_name AFTER UPDATE OF CLOB_FIELD \n//trigger body goes here\n" }, { "answer_id": 12289777, "author": "Paul Muller", "author_id": 1650247, "author_profile": "https://Stackoverflow.com/users/1650247", "pm_score": 0, "selected": false, "text": "create trigger T_TRIG on T \nbefore update of CLOB_COL\n...\n" }, { "answer_id": 13784374, "author": "ramazan polat", "author_id": 234775, "author_profile": "https://Stackoverflow.com/users/234775", "pm_score": 0, "selected": false, "text": "...\ndeclare leftClobHash integer;\ndeclare rightClobHash integer;\nset leftClobHash = (\n SELECT DBMS_UTILITY.GET_HASH_VALUE(OLD_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE \n FROM SYSIBM.SYSDUMMY1);\nset rightClobHash = (\n SELECT DBMS_UTILITY.GET_HASH_VALUE(UPDATED_ROW.CLOB_FIELD,100,1024) AS HASH_VALUE \n FROM SYSIBM.SYSDUMMY1);\n\nIF leftClobHash != rightClobHash\n...\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11710/" ]
110,592
<p>Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it.</p>
[ { "answer_id": 139589, "author": "bsanders", "author_id": 22200, "author_profile": "https://Stackoverflow.com/users/22200", "pm_score": 1, "selected": false, "text": "SqlMapClientDaoSupport SqlMapClientTemplate SqlMapClientOperations @Component\npublic class MyDaoImpl implements MyDao {\n\n @Autowired\n public SqlMapClientOperations template;\n\n public void myDaoMethod(BigInteger id) {\n int rowcount = template.update(\"ibatisOperationName\", id);\n }\n}\n" }, { "answer_id": 3052839, "author": "teabot", "author_id": 74772, "author_profile": "https://Stackoverflow.com/users/74772", "pm_score": 1, "selected": false, "text": "SqlMapClientTemplate SqlMapClient SqlMapClientTemplate SqlMapSession mockSqlMapSession = mock(SqlMapSession.class);\nmockDataSource = mock(DataSource.class);\n\nmockSqlMapClient = mock(SqlMapClient.class);\nwhen(mockSqlMapClient.openSession()).thenReturn(mockSqlMapSession);\nwhen(mockSqlMapClient.getDataSource()).thenReturn(mockDataSource);\n\ndao = new MyDao();\ndao.setSqlMapClient(mockSqlMapClient);\n Entity entity = new EntityImpl(4, \"someField\");\ndao.save(entity);\n\nArgumentCaptor<Map> params = ArgumentCaptor.forClass(Map.class);\nverify(mockSqlMapSession).insert(eq(\"insertEntity\"), params.capture());\nassertEquals(3, params.getValue().size());\nassertEquals(Integer.valueOf(4), params.getValue().get(\"id\"));\nassertEquals(\"someField\", params.getValue().get(\"name\"));\nassertNull(params.getValue().get(\"message\"));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19888/" ]
110,632
<p>Currently IIS sends an expires http header of yesterday minus 1 hour on ASP.NET pages. How do I change this to 60 seconds in the further instead? </p>
[ { "answer_id": 110670, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 3, "selected": true, "text": "Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9819/" ]
110,674
<p>I'm developing a performance critical application for Intel Atom processor.</p> <p>What are the best gcc optimization flags for this CPU?</p>
[ { "answer_id": 300463, "author": "user38733", "author_id": 38733, "author_profile": "https://Stackoverflow.com/users/38733", "pm_score": 2, "selected": false, "text": "-march=prescott -O2 -pipe -fomit-frame-pointer\n" }, { "answer_id": 379908, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 4, "selected": false, "text": "-march=core2 -mfpmath=sse -O3\n-march=core2 -mtune=pentium -mfpmath=sse -O3\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7305/" ]
110,684
<p>Some years ago I was on a panel that was interviewing candidates for a relatively senior embedded C programmer position.</p> <p>One of the standard questions that I asked was about optimisation techniques. I was quite surprised that some of the candidates didn't have answers.</p> <p>So, in the interests of putting together a list for posterity - what techniques and constructs do you normally use when optimising C programs?</p> <p>Answers to optimisation for speed and size both accepted.</p>
[ { "answer_id": 110734, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "char buf[1024] = { 0, };\n/* becomes: */\nchar buf[1024];\nmemset(buf, 0, sizeof(buf));\n" }, { "answer_id": 114225, "author": "dmityugov", "author_id": 3232, "author_profile": "https://Stackoverflow.com/users/3232", "pm_score": 2, "selected": false, "text": "for (i=n; i!=0; --i) { ... }\n for (i=0; i!=n; ++i) { ... }\n" }, { "answer_id": 114401, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 5, "selected": false, "text": "struct Customer\n{\n int ID;\n int AccountNumber;\n char Name[128];\n char Address[256];\n};\n\nCustomer customers[1000];\n struct CustomerAccount\n{\n int ID;\n int AccountNumber;\n CustomerData *pData;\n};\n\nstruct CustomerData\n{\n char Name[128];\n char Address[256];\n};\n\nCustomerAccount customers[1000];\n" }, { "answer_id": 1444161, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 1, "selected": false, "text": "\\#include \"lib.c\"" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11694/" ]
110,749
<p>How would you write a regular expression to convert mark down into HTML? For example, you would type in the following:</p> <pre><code>This would be *italicized* text and this would be **bold** text </code></pre> <p>This would then need to be converted to:</p> <pre><code>This would be &lt;em&gt;italicized&lt;/em&gt; text and this would be &lt;strong&gt;bold&lt;/strong&gt; text </code></pre> <p>Very similar to the mark down edit control used by stackoverflow.</p> <p><strong>Clarification</strong></p> <p>For what it is worth, I am using C#. Also, these are the <strong>only</strong> real tags/markdown that I want to allow. The amount of text being converted would be less than 300 characters or so.</p>
[ { "answer_id": 110769, "author": "Tim Booker", "author_id": 10046, "author_profile": "https://Stackoverflow.com/users/10046", "pm_score": 4, "selected": true, "text": "private string DoItalicsAndBold (string text)\n{\n // <strong> must go first:\n text = Regex.Replace (text, @\"(\\*\\*|__) (?=\\S) (.+?[*_]*) (?<=\\S) \\1\", \n new MatchEvaluator (BoldEvaluator),\n RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n\n // Then <em>:\n text = Regex.Replace (text, @\"(\\*|_) (?=\\S) (.+?) (?<=\\S) \\1\",\n new MatchEvaluator (ItalicsEvaluator),\n RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);\n return text;\n}\n\nprivate string ItalicsEvaluator (Match match)\n{\n return string.Format (\"<em>{0}</em>\", match.Groups[2].Value);\n}\n\nprivate string BoldEvaluator (Match match)\n{\n return string.Format (\"<strong>{0}</strong>\", match.Groups[2].Value);\n}\n" }, { "answer_id": 110831, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 1, "selected": false, "text": "\\\\\\*\\\\\\*(.*?)\\\\\\*\\\\\\*/\n\\< bold\\>$1\\<\\/bold\\>/g\n \\\\\\*(.\\*?)\\\\\\*/\n\\< em\\>$1\\<\\/em\\>/g\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
110,763
<p>I've built a wrapper over NumbericUpDown control. The wrapper is generic and can support int? and double?</p> <p>I would like to write a method that will do the following.</p> <pre><code>public partial class NullableNumericUpDown&lt;T&gt; : UserControl where T : struct { private NumbericUpDown numericUpDown; private T? Getvalue() { T? value = numericUpDown.Value as T?; // &lt;-- this is null :) thus my question return value; }} </code></pre> <p>of course there is no cast between decimal and double? or int? so I need to use a certain way of converting. I would like to avoid switch or if expressions.</p> <p>What would you do?</p> <p>To clarify my question I've provided more code...</p>
[ { "answer_id": 110772, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "using System;\nusing System.ComponentModel;\n\nstatic Nullable<T> ConvertFromString<T>(string value) where T:struct\n{\n TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));\n if (converter != null && !string.IsNullOrEmpty(value))\n {\n try\n {\n return (T)converter.ConvertFrom(value);\n }\n catch (Exception e) // Unfortunately Converter throws general Exception\n {\n return null;\n }\n }\n\n return null;\n}\n\n...\n\ndouble? @double = ConvertFromString<double>(\"1.23\");\nConsole.WriteLine(@double); // prints 1.23\n\nint? @int = ConvertFromString<int>(\"100\");\nConsole.WriteLine(@int); // prints 100\n\nlong? @long = ConvertFromString<int>(\"1.1\");\nConsole.WriteLine(@long.HasValue); // prints False\n" }, { "answer_id": 110790, "author": "lotsoffreetime", "author_id": 18248, "author_profile": "https://Stackoverflow.com/users/18248", "pm_score": 0, "selected": false, "text": "numericUpDown.Value\n" }, { "answer_id": 112672, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "public class FromDecimal<T> where T : struct, IConvertible\n{\n public T GetFromDecimal(decimal Source)\n {\n T myValue = default(T);\n myValue = (T) Convert.ChangeType(Source, myValue.GetTypeCode());\n return myValue;\n }\n}\n\npublic class FromDecimalTestClass\n{\n public void TestMethod()\n {\n decimal a = 1.1m;\n var Inter = new FromDecimal<int>();\n int x = Inter.GetFromDecimal(a);\n int? y = Inter.GetFromDecimal(a);\n Console.WriteLine(\"{0} {1}\", x, y);\n\n var Doubler = new FromDecimal<double>();\n double dx = Doubler.GetFromDecimal(a);\n double? dy = Doubler.GetFromDecimal(a);\n Console.WriteLine(\"{0} {1}\", dx, dy);\n }\n}\n private T? Getvalue()\n{\n T? value = null;\n if (this.HasValue)\n value = new FromDecimal<T>().GetFromDecimal(NumericUpDown);\n return value;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11659/" ]
110,774
<p>Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?</p> <p>It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.</p>
[ { "answer_id": 110830, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": ".order_by(x) ordering class InOrder( models.Model ):\n position = models.IntegerField()\n data = models.TextField()\n class Meta:\n ordering = [ 'position' ]\n" }, { "answer_id": 24995584, "author": "Artur Barseghyan", "author_id": 2318839, "author_profile": "https://Stackoverflow.com/users/2318839", "pm_score": 2, "selected": false, "text": "class MyModel(models.Model):\n name = models.CharField(max_length=255)\n order = models.IntegerField()\n # Other fields...\n\n class Meta:\n ordering = ('order',)\n class MyModelAdmin(admin.ModelAdmin):\n fields = ('name', 'order',) # Add other fields here\n list_display = ('name', 'order',)\n list_editable = ('order',)\n\n class Media:\n js = (\n '//code.jquery.com/jquery-1.4.2.js',\n '//code.jquery.com/ui/1.8.6/jquery-ui.js',\n 'path/to/sortable_list.js',\n )\n" }, { "answer_id": 44428697, "author": "Basant Kumar", "author_id": 6577071, "author_profile": "https://Stackoverflow.com/users/6577071", "pm_score": 0, "selected": false, "text": "In your models.py \n\nclass MainModel(models.Model):\n\n name = models.CharField(max_length=255)\n position = models.PositiveSmallIntegerField(null=True)\n\n class Meta:\n ordering = ('position',)\n\nIn your apps admin.py\n\nclass IdeaCardTagInline(nested_admin.NestedStackedInline):\n model = MainModel\n extra = 0\n min_num = 1\n sortable_field_name = \"position\"\n ordering = ('position',) sortable_field_name = \"position\" Model.objects.filter().order_by('position').\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
110,801
<p>I've tried cpan and cpanp shell and I keep getting:</p> <pre><code>ExtUtils::PkgConfig requires the pkg-config utility, but it doesn't seem to be in your PATH. Is it correctly installed? </code></pre> <p>What is the pkg-config utility and how do I install it? </p> <p>Updates: </p> <ul> <li>OS: Windows</li> <li>This module is a prerequisite for the File::Extractor module</li> </ul>
[ { "answer_id": 110842, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 2, "selected": false, "text": " sudo apt-get install pkg-config\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9411/" ]
110,803
<p>In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?</p> <p>I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.</p>
[ { "answer_id": 110821, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "def updateSomething( request, object_id ):\n object= Model.objects.get( id=object_id )\n if request.method == \"GET\":\n request.session['before']= object\n form= SomethingForm( instance=object )\n else request.method == \"POST\"\n form= SomethingForm( request.POST )\n if form.is_valid():\n # You have before in the session\n # You have the old object\n # You have after in the form.cleaned_data\n # Log the changes\n # Apply the changes to the object\n object.save()\n" }, { "answer_id": 111364, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 4, "selected": false, "text": "__set__ class DiffingMixin(object):\n\n def __init__(self, *args, **kwargs):\n super(DiffingMixin, self).__init__(*args, **kwargs)\n self._original_state = dict(self.__dict__)\n\n def get_changed_columns(self):\n missing = object()\n result = {}\n for key, value in self._original_state.iteritems():\n if key != self.__dict__.get(key, missing):\n result[key] = value\n return result\n\n class MyModel(DiffingMixin, models.Model):\n pass\n model.get_changed_columns()" }, { "answer_id": 332225, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 5, "selected": false, "text": "class DirtyFieldsMixin(object):\n def __init__(self, *args, **kwargs):\n super(DirtyFieldsMixin, self).__init__(*args, **kwargs)\n self._original_state = self._as_dict()\n\n def _as_dict(self):\n return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])\n\n def get_dirty_fields(self):\n new_state = self._as_dict()\n return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])\n _original_state save() def save(self, *args, **kwargs):\n super(Klass, self).save(*args, **kwargs)\n self._original_state = self._as_dict()\n" }, { "answer_id": 1716046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "from django.db.models.signals import post_save\n\nclass DirtyFieldsMixin(object):\n def __init__(self, *args, **kwargs):\n super(DirtyFieldsMixin, self).__init__(*args, **kwargs)\n post_save.connect(self._reset_state, sender=self.__class__, \n dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)\n self._reset_state()\n\n def _reset_state(self, *args, **kwargs):\n self._original_state = self._as_dict()\n\n def _as_dict(self):\n return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])\n\n def get_dirty_fields(self):\n new_state = self._as_dict()\n return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])\n" }, { "answer_id": 4676107, "author": "Trey Hunner", "author_id": 98187, "author_profile": "https://Stackoverflow.com/users/98187", "pm_score": 2, "selected": false, "text": "from django.db.models.signals import post_save\n\nclass DirtyFieldsMixin(object):\n def __init__(self, *args, **kwargs):\n super(DirtyFieldsMixin, self).__init__(*args, **kwargs)\n post_save.connect(self._reset_state, sender=self.__class__,\n dispatch_uid='%s-DirtyFieldsMixin-sweeper' % self.__class__.__name__)\n self._reset_state()\n\n def _reset_state(self, *args, **kwargs):\n self._original_state = self._as_dict()\n\n def _as_dict(self):\n return dict([(f.attname, getattr(self, f.attname)) for f in self._meta.local_fields])\n\n def get_dirty_fields(self):\n new_state = self._as_dict()\n return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])\n _as_dict return dict([\n (f.name, getattr(self, f.name)) for f in self._meta.local_fields\n if not f.rel\n])\n return dict([\n (f.attname, getattr(self, f.attname)) for f in self._meta.local_fields\n])\n class MyModel(DirtyFieldsMixin, models.Model):\n ....\n" }, { "answer_id": 11011415, "author": "Tony Abou-Assaleh", "author_id": 1010312, "author_profile": "https://Stackoverflow.com/users/1010312", "pm_score": 3, "selected": false, "text": "from django.db.models.signals import post_save\n\nDirtyFieldsMixin(object):\n def __init__(self, *args, **kwargs):\n super(DirtyFieldsMixin, self).__init__(*args, **kwargs)\n post_save.connect(self._reset_state, sender=self.__class__,\n dispatch_uid='%s._reset_state' % self.__class__.__name__)\n self._reset_state()\n\n def _as_dict(self):\n fields = dict([\n (f.attname, getattr(self, f.attname))\n for f in self._meta.local_fields\n ])\n m2m_fields = dict([\n (f.attname, set([\n obj.id for obj in getattr(self, f.attname).all()\n ]))\n for f in self._meta.local_many_to_many\n ])\n return fields, m2m_fields\n\n def _reset_state(self, *args, **kwargs):\n self._original_state, self._original_m2m_state = self._as_dict()\n\n def get_dirty_fields(self):\n new_state, new_m2m_state = self._as_dict()\n changed_fields = dict([\n (key, value)\n for key, value in self._original_state.iteritems()\n if value != new_state[key]\n ])\n changed_m2m_fields = dict([\n (key, value)\n for key, value in self._original_m2m_state.iteritems()\n if sorted(value) != sorted(new_m2m_state[key])\n ])\n return changed_fields, changed_m2m_fields\n return changed_fields, changed_m2m_fields\n changed_fields.update(changed_m2m_fields)\nreturn changed_fields\n" }, { "answer_id": 34525671, "author": "Neil", "author_id": 199754, "author_profile": "https://Stackoverflow.com/users/199754", "pm_score": 0, "selected": false, "text": "from dirtyfields import DirtyFieldsMixin\nclass M2MDirtyFieldsMixin(DirtyFieldsMixin):\n def __init__(self, *args, **kwargs):\n super(M2MDirtyFieldsMixin, self).__init__(*args, **kwargs)\n post_save.connect(\n reset_state, sender=self.__class__,\n dispatch_uid='{name}-DirtyFieldsMixin-sweeper'.format(\n name=self.__class__.__name__))\n reset_state(sender=self.__class__, instance=self)\n\n def _as_dict_m2m(self):\n if self.pk:\n m2m_fields = dict([\n (f.attname, set([\n obj.id for obj in getattr(self, f.attname).all()\n ]))\n for f,model in self._meta.get_m2m_with_model()\n ])\n return m2m_fields\n return {}\n\n def get_dirty_fields(self, check_relationship=False):\n changed_fields = super(M2MDirtyFieldsMixin, self).get_dirty_fields(check_relationship)\n new_m2m_state = self._as_dict_m2m()\n changed_m2m_fields = dict([\n (key, value)\n for key, value in self._original_m2m_state.iteritems()\n if sorted(value) != sorted(new_m2m_state[key])\n ])\n changed_fields.update(changed_m2m_fields)\n return changed_fields\n\ndef reset_state(sender, instance, **kwargs):\n # original state should hold all possible dirty fields to avoid\n # getting a `KeyError` when checking if a field is dirty or not\n instance._original_state = instance._as_dict(check_relationship=True)\n instance._original_m2m_state = instance._as_dict_m2m()\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437/" ]
110,833
<p>What is the correct way to import a C++ class from a DLL? We're using Visual C++. </p> <p>There's the dllexport/exports.def+LoadLibrary+GetProcAddress trifecta, but it doesn't work on C++ classes, only C functions. Is this due to C++ name-mangling? How do I make this work?</p>
[ { "answer_id": 110854, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 4, "selected": false, "text": "extern \"C\"\n{\n...\n}\n SomeClass* CreateObjectInstace()\n{\n return new SomeClass();\n}\n\nvoid ReleaseObject(SomeClass* someClass)\n{\n delete someClass;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13897/" ]
110,858
<p>I am searching for a tutorial <code>(optimally with Zend Framework)</code> on how to use <code>PHPUnit</code>.</p> <p>I have found a couple on <code>google</code> but have not quiet understood it yet.</p>
[ { "answer_id": 804040, "author": "Andrew", "author_id": 48523, "author_profile": "https://Stackoverflow.com/users/48523", "pm_score": 1, "selected": false, "text": "Zend_Test Zend_Test" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
110,867
<p>I have a public property set in my form of type <code>ListE&lt;T&gt;</code> where:</p> <pre><code>public class ListE&lt;T&gt; : IList&lt;T&gt;, ICollection&lt;T&gt;, IEnumerable&lt;T&gt;, IList, ICollection, IEnumerable </code></pre> <p>Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection.</p> <blockquote> <p>Arithmetic operation resulted in an overflow.</p> </blockquote> <p>Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas?</p> <p>EDIT: Yes, I can use the property successfully, well even manually, ie. in the <code>OnLoad</code> handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :(</p>
[ { "answer_id": 111065, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 0, "selected": false, "text": "checked\n{\n // ...\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
110,887
<p>Is there a way to read a module's configuration ini file? </p> <p>For example I installed php-eaccelerator (<a href="http://eaccelerator.net" rel="nofollow noreferrer">http://eaccelerator.net</a>) and it put a <code>eaccelerator.ini</code> file in <code>/etc/php.d</code>. My PHP installation wont read this <code>.ini</code> file because the <code>--with-config-file-scan-dir</code> option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?</p>
[ { "answer_id": 110907, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<?php phpinfo(); ?> [eAccelerator]\nextension=\"eaccelerator.so\"\neaccelerator.shm_size=\"32\"\neaccelerator.cache_dir=\"/tmp\"\neaccelerator.enable=\"1\"\neaccelerator.optimizer=\"1\"\neaccelerator.check_mtime=\"1\"\neaccelerator.debug=\"0\"\neaccelerator.filter=\"\"\neaccelerator.shm_max=\"0\"\neaccelerator.shm_ttl=\"0\"\neaccelerator.shm_prune_period=\"0\"\neaccelerator.shm_only=\"0\"\neaccelerator.compress=\"1\"\neaccelerator.compress_level=\"9\"\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983/" ]
110,894
<p>I've got C# code that accesses MySQL through ODBC.</p> <p>It creates a transaction, does a few thousand insert commands, and then commits. Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?</p>
[ { "answer_id": 110915, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "cmd.ExecuteNonQuery \"insert table values (1) insert table values (2)\"\n" }, { "answer_id": 110955, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 5, "selected": true, "text": "INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015);\n" }, { "answer_id": 20706664, "author": "siefca", "author_id": 617851, "author_profile": "https://Stackoverflow.com/users/617851", "pm_score": 0, "selected": false, "text": "net_buffer_length max_allowed_packet" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11208/" ]
110,911
<p>I do most of my development in Common Lisp, but there are some moments when I want to switch to Scheme (while reading <em>Lisp in Small Pieces</em>, when I want to play with continuations, or when I want to do some scripting in Gauche, for example). In such situations, my main source of discomfort is that I don't have Slime (yes, you may call me an addict).</p> <p>What is Scheme's closest counterpart to Slime? Specifically, I am most interested in:</p> <ul> <li>Emacs integration (this point is obvious ;))</li> <li>Decent tab completion (ideally, c-w-c-c TAB should expand to call-with-current-continuation). It may be even symbol-table based (ie. it doesn't have to notice a function I defined in a <code>let</code> at once).</li> <li>Function argument hints in the minibuffer (if I have typed <code>(map |)</code> (cursor position is indicated by <code>|</code>)), I'd like to see <code>(map predicate . lists)</code> in the minibuffer</li> <li>Sending forms to the interpreter</li> <li>Integration with a debugger.</li> </ul> <p>I have ordered the features by descending importance.</p> <p>My Scheme implementations of choice are:</p> <ul> <li>MzScheme</li> <li>Ikarus</li> <li>Gauche</li> <li>Bigloo</li> <li>Chicken</li> </ul> <p>It would be great if it worked at least with them.</p>
[ { "answer_id": 122570, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 2, "selected": false, "text": "mzscheme" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
110,923
<p>How do I end a Tkinter program? Let's say I have this code:</p> <pre><code>from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() </code></pre> <p>How should I define the <code>quit</code> function to exit my application?</p>
[ { "answer_id": 110929, "author": "Matt Gregory", "author_id": 10577, "author_profile": "https://Stackoverflow.com/users/10577", "pm_score": 6, "selected": false, "text": "def quit()\n root.quit()\n def quit()\n root.destroy()\n" }, { "answer_id": 111011, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 2, "selected": false, "text": "sys.exit()\n raise SystemExit\n" }, { "answer_id": 294199, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "import tkinter as tk\n\ndef quit(root):\n root.destroy()\n\nroot = tk.Tk()\ntk.Button(root, text=\"Quit\", command=lambda root=root:quit(root)).pack()\nroot.mainloop()\n" }, { "answer_id": 15577605, "author": "aki92", "author_id": 2142721, "author_profile": "https://Stackoverflow.com/users/2142721", "pm_score": 8, "selected": true, "text": "destroy() from Tkinter import * \n#use tkinter instead of Tkinter (small, not capital T) if it doesn't work\n#as it was changed to tkinter in newer Python versions\n\nroot = Tk()\nButton(root, text=\"Quit\", command=root.destroy).pack() #button to close the window\nroot.mainloop()\n root.quit()\n root.mainloop() root.mainloop() quit() root.destroy()\n destroy() root.mainloop() root.mainloop() <window>.destroy() root.destroy() mainloop() root.mainloop() root.quit() from Tkinter import *\ndef quit():\n global root\n root.quit()\n\nroot = Tk()\nwhile True:\n Button(root, text=\"Quit\", command=quit).pack()\n root.mainloop()\n #do something\n" }, { "answer_id": 18852907, "author": "TreeDoNotSplit", "author_id": 2788026, "author_profile": "https://Stackoverflow.com/users/2788026", "pm_score": 3, "selected": false, "text": "from Tkinter import *\nroot = Tk()\nButton(root, text=\"Quit\", command=root.quit).pack()\nroot.mainloop()\n" }, { "answer_id": 39174800, "author": "Martin Guiles", "author_id": 6763094, "author_profile": "https://Stackoverflow.com/users/6763094", "pm_score": 3, "selected": false, "text": "def quit(self):\n self.destroy()\n exit()\n" }, { "answer_id": 44122214, "author": "RAD", "author_id": 5153622, "author_profile": "https://Stackoverflow.com/users/5153622", "pm_score": 1, "selected": false, "text": "idlelib.PyShell root Tk PyShell.main() root.mainloop() root.quit() root.quit() mainloop root.destroy() idlelib.PyShell.main()" }, { "answer_id": 51495698, "author": "Ian Gabaraev", "author_id": 9612362, "author_profile": "https://Stackoverflow.com/users/9612362", "pm_score": 2, "selected": false, "text": "class App:\n def __init__(self, master)\n frame = Tkinter.Frame(master)\n frame.pack()\n self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)\n self.quit_button.pack()\n destroy() import tkMessageBox\n\ndef confirmExit():\n if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):\n root.destroy()\nroot = Tk()\nroot.protocol('WM_DELETE_WINDOW', confirmExit)\nroot.mainloop()\n" }, { "answer_id": 53041670, "author": "Nukyi", "author_id": 10324360, "author_profile": "https://Stackoverflow.com/users/10324360", "pm_score": 2, "selected": false, "text": "master = Tk()\nmaster.title(\"Python\")\n\ndef close(event):\n sys.exit()\n\nmaster.bind('<Escape>',close)\nmaster.mainloop()\n" }, { "answer_id": 53755060, "author": "LenyaKap", "author_id": 10784099, "author_profile": "https://Stackoverflow.com/users/10784099", "pm_score": 0, "selected": false, "text": "def quit():\n root.destroy()\n\nmenubar = Menu(root)\nfilemenu = Menu(menubar, tearoff=0)\n\nfilemenu.add_separator()\n\nfilemenu.add_command(label=\"Exit\", command=quit)\nmenubar.add_cascade(label=\"menubarname\", menu=filemenu)\nroot.config(menu=menubar)\nroot.mainloop()\n" }, { "answer_id": 55536097, "author": "BruhDev", "author_id": 10686694, "author_profile": "https://Stackoverflow.com/users/10686694", "pm_score": 2, "selected": false, "text": "root.destroy()\n" }, { "answer_id": 55957531, "author": "kourosh", "author_id": 11007580, "author_profile": "https://Stackoverflow.com/users/11007580", "pm_score": 0, "selected": false, "text": "from tkinter import*\nroot=Tk()\nroot.bind(\"<Escape>\",lambda q:root.destroy())\nroot.mainloop()\n from tkinter import*\nroot=Tk()\nButton(root,text=\"exit\",command=root.destroy).pack()\nroot.mainloop()\n from tkinter import*\nroot=Tk()\nButton(root,text=\"quit\",command=quit).pack()\nroot.mainloop()\n from tkinter import*\nroot=Tk()\nButton(root,text=\"exit\",command=exit).pack()\nroot.mainloop()\n" }, { "answer_id": 57989602, "author": "Ozzius", "author_id": 4520574, "author_profile": "https://Stackoverflow.com/users/4520574", "pm_score": 0, "selected": false, "text": "import tkinter as tk\nfrom tkinter import *\n\nroot = Tk()\n\ndef exit():\n if askokcancel(\"Quit\", \"Do you really want to quit?\"):\n root.destroy()\n\nmenubar = Menu(root, background='#000099', foreground='white',\n activebackground='#004c99', activeforeground='white')\n\nfileMenu = Menu(menubar, tearoff=0, background=\"grey\", foreground='black',\n activebackground='#004c99', activeforeground='white')\nmenubar.add_cascade(label='File', menu=fileMenu)\n\nfileMenu.add_command(label='Exit', command=exit)\n\nroot.config(bg='#2A2C2B',menu=menubar)\n\nif __name__ == '__main__':\n root.mainloop()\n" }, { "answer_id": 61335741, "author": "snookso", "author_id": 13298841, "author_profile": "https://Stackoverflow.com/users/13298841", "pm_score": -1, "selected": false, "text": "exit()" }, { "answer_id": 66198672, "author": "Geetansh G", "author_id": 13010024, "author_profile": "https://Stackoverflow.com/users/13010024", "pm_score": 0, "selected": false, "text": "def quit(self): # Your exit routine\n self.root.destroy()\n\nself.root.protocol(\"WM_DELETE_WINDOW\", self.quit) # Sets the command for the \"X\" button \n\nButton(text=\"Quit\", command=self.quit) # No ()\n\n" }, { "answer_id": 68531313, "author": "UnlinedBus", "author_id": 16516820, "author_profile": "https://Stackoverflow.com/users/16516820", "pm_score": 1, "selected": false, "text": "quit from tkinter import *\nfrom tkinter.ttk import *\n\nwindow = Tk()\nwindow.geometry('700x700') # 700p x 700p screen\n\ndef quit(self):\n proceed = messagebox.askyesno('Quit', 'Quit?')\n proceed = bool(proceed) # So it is a bool\n\n if proceed:\n window.quit()\n else:\n # You don't really need to do this\n pass\n\nbtn1 = Button(window, text='Quit', command=lambda: quit(None))\n\nwindow.mainloop()\n" }, { "answer_id": 68562764, "author": "Gonzalez", "author_id": 16466088, "author_profile": "https://Stackoverflow.com/users/16466088", "pm_score": 2, "selected": false, "text": "from Tkinter import *\n\nroot = Tk()\nButton(root, text=\"Quit\", command=root.destroy).pack()\nroot.mainloop()\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
110,928
<p>Seriously. On a 22" monitor, it only covers maybe a quarter of the screen. I need some ammo to axe down this rule.</p> <hr> <p>I'm not saying that there shouldn't be a limit; I'm just saying, 80 characters is very small.</p>
[ { "answer_id": 124774, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 5, "selected": false, "text": "switch(Type) {\ncase External_BL: mpstrd[\"X\"] = ptDig1.x - RadialClrX; mpstrd[\"Y\"] = ptDig1.y - RadialClrY; break;\ncase External_BR: mpstrd[\"X\"] = ptDig1.x + RadialClrX; mpstrd[\"Y\"] = ptDig1.y - RadialClrY; break;\ncase External_TR: mpstrd[\"X\"] = ptDig1.x + RadialClrX; mpstrd[\"Y\"] = ptDig1.y + RadialClrY; break;\ncase External_TL: mpstrd[\"X\"] = ptDig1.x - RadialClrX; mpstrd[\"Y\"] = ptDig1.y + RadialClrY; break;\ncase Internal_BL: mpstrd[\"X\"] = ptDig1.x + RadialClrX; mpstrd[\"Y\"] = ptDig1.y + RadialClrY; break;\ncase Internal_BR: mpstrd[\"X\"] = ptDig1.x - RadialClrX; mpstrd[\"Y\"] = ptDig1.y + RadialClrY; break;\ncase Internal_TR: mpstrd[\"X\"] = ptDig1.x - RadialClrX; mpstrd[\"Y\"] = ptDig1.y - RadialClrY; break;\ncase Internal_TL: mpstrd[\"X\"] = ptDig1.x + RadialClrX; mpstrd[\"Y\"] = ptDig1.y - RadialClrY; break;\n}\n switch(Type) {\n case External_BL: dxDir = - 1; dyDir = - 1; break;\n case External_BR: dxDir = + 1; dyDir = - 1; break;\n case External_TR: dxDir = + 1; dyDir = + 1; break;\n case External_TL: dxDir = - 1; dyDir = + 1; break;\n case Internal_BL: dxDir = + 1; dyDir = + 1; break;\n case Internal_BR: dxDir = - 1; dyDir = + 1; break;\n case Internal_TR: dxDir = - 1; dyDir = - 1; break;\n case Internal_TL: dxDir = + 1; dyDir = - 1; break;\n}\nmpstrd[\"X\"] = pt1.x + dxDir * RadialClrX;\nmpstrd[\"Y\"] = pt1.y + dyDir * RadialClrY; \n" }, { "answer_id": 373581, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "grep less" }, { "answer_id": 5668019, "author": "Jens", "author_id": 648658, "author_profile": "https://Stackoverflow.com/users/648658", "pm_score": 3, "selected": false, "text": "struct FOO func(struct BAR *aWhatever, ...)" }, { "answer_id": 9101780, "author": "Matyas", "author_id": 165665, "author_profile": "https://Stackoverflow.com/users/165665", "pm_score": 3, "selected": false, "text": "public class PlaintiffServiceImpl extends RemoteServiceServlet implements PlaintiffService {\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18658/" ]
110,987
<p>This question is directed to the non-english speaking people here.</p> <p><em>It is somewhat biased because SO is an &quot;english-speaking&quot; web forum, so... In the other hand, most developers would know english anyway...</em></p> <p>In your locale culture, are technical words translated into locale words ? For example, how &quot;Design Pattern&quot;, or &quot;Factory&quot;, or whatever are written/said in german, spanish, etc. etc. when used by IT? Are the english words prefered? The local translation? Do the two version (english/locale) are evenly used?</p> <h3>Edit</h3> <p>Could you write with your answer the locale translation of &quot;Design Pattern&quot;?</p> <p>In french, according to Wikipedia.fr, it is &quot;Patron de conception&quot;, which translates back as &quot;Model of Conceptualization&quot; (I guess).</p>
[ { "answer_id": 13518183, "author": "Giulio Muscarello", "author_id": 1541408, "author_profile": "https://Stackoverflow.com/users/1541408", "pm_score": 0, "selected": false, "text": "stack matrice array Design pattern schema di progettazione" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/110987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
111,026
<p>Which is the best way to store a 2D array in c# in order to optimize performance when performing lots of arithmetic on the elements in the array?</p> <p>We have large (approx 1.5G) arrays, which for example we want to multiply with each other element by element. Performance is critical. The context in which this is done is in c#. Is there any smart way of storing the arrays and iterating over them? Could we write these parts in unmanaged C++ and will this really increase performance? The arrays need to be accessible to the rest of the c# program. </p> <p>Currently (in c) the array is stored as a single long vector. We perform calculations on each element in the array and overwrite the old value. The calculations are usually unique for each element in the vector.</p> <p>Timing experiments show that storing and iterating over the data as an array in C# is slower than storing it as a 2D array. I would like to know if there is an even better way of handling the data. The specific arithmetics performed are not relevant for the question.</p>
[ { "answer_id": 111046, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 3, "selected": false, "text": "int[] array = Enumerable.Range(0, 1000).ToArray();\n\nint count = 0;\nunsafe {\n fixed (int* pArray = array) {\n for (int i = 0; i < array.Length; i++) {\n count += *(pArray + i);\n }\n }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4044/" ]
111,045
<p>What are your favorite supplementary tools for Java development?</p> <p>Mine are:</p> <p>1) Total Commander (due to the ability to search inside JARs).</p> <p>2) JAD + Jadclipse (to understand and debug libraries)</p> <p>And of-course, Google. (can't really live without it)</p>
[ { "answer_id": 117151, "author": "ShawnD", "author_id": 6186, "author_profile": "https://Stackoverflow.com/users/6186", "pm_score": 2, "selected": false, "text": "* Possible bugs - empty try/catch/finally/switch statements\n* Dead code - unused local variables, parameters and private methods\n* Suboptimal code - wasteful String/StringBuffer usage\n* Overcomplicated expressions - unnecessary if statements, for loops that could be while loops\n* Duplicate code - copied/pasted code means copied/pasted bugs\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15100/" ]
111,097
<p><strong>EDIT:</strong> This was formerly more explicitly titled: - "<strong>Best solution to stop Kontiki's KHOST.EXE from loading automatically at start-up on Windows XP?</strong>"</p> <p>Essentially, whenever the <strong><a href="http://www.channel4.com/4od/index.html" rel="nofollow noreferrer">40D</a></strong> application is run it sets up <strong>khost.exe</strong> to automatically start-up with Windows. This is annoying as it increases my boot up time by a couple of minutes and I don't even use the P2P aspect of 4OD anyway.</p> <p>The registry keys that are set are:</p> <pre><code>Command: C:\Program Files\Kontiki\KHost.exe -all Description: kdx Location: HKU\S-1-5-21-1757981266-1960408961-839522115-1003\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: kdx Setting ID: User: LAPTOP\Me Command: "C:\Program Files\Kontiki\KHost.exe" -all Description: 4oD Location: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Name: 4oD Setting ID: User: All Users </code></pre> <p>I'm assuming some kind of <strong>start-up</strong> or <strong>shut-down</strong> <strong>script</strong> to delete these registry keys would be the best solution, but I'm not that up with <strong>.vbs</strong> or <strong>.bat</strong> scripting or where I'd put them to automatically run at an appropriate time.</p> <p>I know there is a <strong><a href="http://odmonitor.blogspot.com/" rel="nofollow noreferrer">TV On-Demand Monitor application</a></strong>, but I don't really need to be running yet another process, I just need to delete the registry keys as I describe above.</p>
[ { "answer_id": 111137, "author": "beakersoft", "author_id": 19638, "author_profile": "https://Stackoverflow.com/users/19638", "pm_score": 2, "selected": true, "text": "Dim WSHShell\nSet WSHShell = WScript.CreateObject(\"WScript.Shell\")\n'repeat the line below for each key to delete \nWSHShell.RegDelete \"[Location of Key]\"\n" }, { "answer_id": 111154, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "Set objShell = CreateObject(\"WScript.Shell\") \n\nobjShell.Exec(\"C:\\Program Files\\Kontiki\\KHost.exe\")\n\nstrRoot = \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\4oD\" \nstrDelete = objShell.RegDelete(strRoot) \n...\n" }, { "answer_id": 111198, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 1, "selected": false, "text": "RegDelete(\"YourKey\", \"YourValue\");\nShutDown(1);\n" }, { "answer_id": 111394, "author": "Matt", "author_id": 17759, "author_profile": "https://Stackoverflow.com/users/17759", "pm_score": 2, "selected": false, "text": "Set SH = CreateObject(\"WScript.Shell\")\n\nRemoveRegKey \"HKU\\S-1-5-21-1757981266-1960408961-839522115-1003\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\kdx\"\nRemoveRegKey \"HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\kdx\"\nRemoveRegKey \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\4oD\"\n\nShutdown\n\nSet Shell = Nothing\nSet SH = Nothing\nWScript.Quit\n\nSub RemoveRegKey(sKey)\n On Error Resume Next\n SH.RegDelete sKey\nEnd Sub\n\nSub Shutdown()\n SH.Run \"shutdown -s -t 1\", 0, TRUE\nEnd Sub\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17759/" ]
111,102
<p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p> <p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
[ { "answer_id": 111111, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 14, "selected": true, "text": "inner foo secret function foo() {\n const secret = Math.trunc(Math.random() * 100)\n return function inner() {\n console.log(`The secret number is ${secret}.`)\n }\n}\nconst f = foo() // `secret` is not directly accessible from outside `foo`\nf() // The only way to retrieve `secret`, is to invoke `f` secret inner foo toString function Car(manufacturer, model, year, color) {\n return {\n toString() {\n return `${manufacturer} ${model} (${year}, ${color})`\n }\n }\n}\n\nconst car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver')\nconsole.log(car.toString()) inner fn args function curry(fn) {\n const args = []\n return function inner(arg) {\n if(args.length === fn.length) return fn(...args)\n args.push(arg)\n return inner\n }\n}\n\nfunction add(a, b) {\n return a + b\n}\n\nconst curriedAdd = curry(add)\nconsole.log(curriedAdd(2)(3)()) // 5 onClick BACKGROUND_COLOR const $ = document.querySelector.bind(document)\nconst BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)'\n\nfunction onClick() {\n $('body').style.background = BACKGROUND_COLOR\n}\n\n$('button').addEventListener('click', onClick) <button>Set background color</button> tick toString let namespace = {};\n\n(function foo(n) {\n let numbers = []\n\n function format(n) {\n return Math.trunc(n)\n }\n\n function tick() {\n numbers.push(Math.random() * 100)\n }\n\n function toString() {\n return numbers.map(format)\n }\n\n n.counter = {\n tick,\n toString\n }\n}(namespace))\n\nconst counter = namespace.counter\ncounter.tick()\ncounter.tick()\nconsole.log(counter.toString()) function foo() {\n let x = 42\n let inner = () => console.log(x)\n x = x + 1\n return inner\n}\n\nfoo()() // logs 43 log increment update createObject x log function createObject() {\n let x = 42;\n return {\n log() { console.log(x) },\n increment() { x++ },\n update(value) { x = value }\n }\n}\n\nconst o = createObject()\no.increment()\no.log() // 43\no.update(5)\no.log() // 5\nconst p = createObject()\np.log() // 42 var var let const inner i var i i function foo() {\n var result = []\n for (var i = 0; i < 3; i++) {\n result.push(function inner() { console.log(i) } )\n }\n\n return result\n}\n\nconst result = foo()\n// The following will print `3`, three times...\nfor (var i = 0; i < 3; i++) {\n result[i]() \n} function eval() eval eval('var foo = …') new Function(…)" }, { "answer_id": 111114, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 9, "selected": false, "text": "[[Environment]] [[Call]] [[Environment]] f function f() {}\n h g function g() {\n function h() {}\n}\n j i x j i function i() {\n var x = 'mochacchino'\n return function j() {\n console.log('Printing the value of x, from within function j: ', x)\n }\n} \n\nconst k = i()\nsetTimeout(k, 500) // invoke k (which is j) after 500ms function l() {\n var y = 'vanilla';\n\n return {\n setY: function(value) {\n y = value;\n },\n logY: function(value) {\n console.log('The value of y is: ', y);\n }\n }\n}\n\nconst o = l()\no.logY() // The value of y is: vanilla\no.setY('chocolate')\no.logY() // The value of y is: chocolate" }, { "answer_id": 111119, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": false, "text": "const makePlus = function(x) {\n return function(y) { return x + y; };\n}\n\nconst plus5 = makePlus(5);\nconsole.log(plus5(3)); console.log(x + 3);\n x plus5 x" }, { "answer_id": 111200, "author": "Ali", "author_id": 8689, "author_profile": "https://Stackoverflow.com/users/8689", "pm_score": 12, "selected": false, "text": "function function foo(x) {\n var tmp = 3;\n\n function bar(y) {\n console.log(x + y + (++tmp)); // will log 16\n }\n\n bar(10);\n}\n\nfoo(2); 16 bar x tmp foo bar foo function foo(x) {\n var tmp = 3;\n\n return function (y) {\n console.log(x + y + (++tmp)); // will also log 16\n }\n}\n\nvar bar = foo(2);\nbar(10); // 16\nbar(10); // 17 bar x tmp tmp bar bar var a = 10;\n\nfunction test() {\n console.log(a); // will output 10\n console.log(b); // will output 6\n}\nvar b = 6;\ntest(); ec a b ec" }, { "answer_id": 2673546, "author": "someisaac", "author_id": 167166, "author_profile": "https://Stackoverflow.com/users/167166", "pm_score": 7, "selected": false, "text": "var i;\nfunction foo(x) {\n var tmp = 3;\n i = function (y) {\n console.log(x + y + (++tmp));\n }\n}\nfoo(2);\ni(3);\n" }, { "answer_id": 2673583, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 8, "selected": false, "text": "/*\n* When a function is defined in another function and it\n* has access to the outer function's context even after\n* the outer function returns.\n*\n* An important concept to learn in JavaScript.\n*/\n\nfunction outerFunction(someNum) {\n var someString = 'Hey!';\n var content = document.getElementById('content');\n function innerFunction() {\n content.innerHTML = someNum + ': ' + someString;\n content = null; // Internet Explorer memory leak for DOM reference\n }\n innerFunction();\n}\n\nouterFunction(1);​\n" }, { "answer_id": 5099447, "author": "John Pick", "author_id": 251034, "author_profile": "https://Stackoverflow.com/users/251034", "pm_score": 6, "selected": false, "text": "var isVotedUp = false;\nvar isVotedDown = false;\n\nfunction voteUp_click() {\n if (isVotedUp)\n return;\n else if (isVotedDown)\n SetDownVote(false);\n else\n SetUpVote(true);\n}\n\nfunction voteDown_click() {\n if (isVotedDown)\n return;\n else if (isVotedUp)\n SetUpVote(false);\n else\n SetDownVote(true);\n}\n\nfunction SetUpVote(status) {\n isVotedUp = status;\n // Do some CSS stuff to Vote-Up button\n}\n\nfunction SetDownVote(status) {\n isVotedDown = status;\n // Do some CSS stuff to Vote-Down button\n}\n" }, { "answer_id": 6472397, "author": "Jacob Swartwood", "author_id": 777919, "author_profile": "https://Stackoverflow.com/users/777919", "pm_score": 11, "selected": false, "text": "function princess() {\n var adventures = [];\n\n function princeCharming() { /* ... */ }\n\n var unicorn = { /* ... */ },\n dragons = [ /* ... */ ],\n squirrel = \"Hello!\";\n\n /* ... */\n return {\n story: function() {\n return adventures[adventures.length - 1];\n }\n };\n}\n var littleGirl = princess();\n littleGirl.story();\n" }, { "answer_id": 6756814, "author": "StewShack", "author_id": 815682, "author_profile": "https://Stackoverflow.com/users/815682", "pm_score": 6, "selected": false, "text": "function sleepOver(howManyControllersToBring) {\n\n var numberOfDansControllers = howManyControllersToBring;\n\n return function danInvitedPaul(numberOfPaulsControllers) {\n var totalControllers = numberOfDansControllers + numberOfPaulsControllers;\n return totalControllers;\n }\n}\n\nvar howManyControllersToBring = 1;\n\nvar inviteDan = sleepOver(howManyControllersToBring);\n\n// The only reason Paul was invited is because Dan was invited. \n// So we set Paul's invitation = Dan's invitation.\n\nvar danInvitedPaul = inviteDan(howManyControllersToBring);\n\nalert(\"There were \" + danInvitedPaul + \" controllers brought to the party.\");\n" }, { "answer_id": 6825315, "author": "Nathan Whitehead", "author_id": 232725, "author_profile": "https://Stackoverflow.com/users/232725", "pm_score": 7, "selected": false, "text": "var create = function (x) {\n var f = function () {\n return x; // We can refer to x here!\n };\n return f;\n};\n// 'create' takes one argument, creates a function\n\nvar g = create(42);\n// g is a function that takes no arguments now\n\nvar y = g();\n// y is 42 here\n" }, { "answer_id": 6883759, "author": "mykhal", "author_id": 234248, "author_profile": "https://Stackoverflow.com/users/234248", "pm_score": 7, "selected": false, "text": "var db = (function() {\n // Create a hidden object, which will hold the data\n // it's inaccessible from the outside.\n var data = {};\n\n // Make a function, which will provide some access to the data.\n return function(key, val) {\n if (val === undefined) { return data[key] } // Get\n else { return data[key] = val } // Set\n }\n // We are calling the anonymous surrounding function,\n // returning the above inner function, which is a closure.\n})();\n\ndb('x') // -> undefined\ndb('x', 1) // Set x to 1\ndb('x') // -> 1\n// It's impossible to access the data object itself.\n// We are able to get or set individual it.\n mkdb" }, { "answer_id": 7285658, "author": "dlaliberte", "author_id": 311389, "author_profile": "https://Stackoverflow.com/users/311389", "pm_score": 10, "selected": false, "text": "trashBags getTrashBag function makeKitchen() {\n var trashBags = ['A', 'B', 'C']; // only 3 at first\n\n return {\n getTrashBag: function() {\n return trashBags.pop();\n }\n };\n}\n\nvar kitchen = makeKitchen();\n\nconsole.log(kitchen.getTrashBag()); // returns trash bag C\nconsole.log(kitchen.getTrashBag()); // returns trash bag B\nconsole.log(kitchen.getTrashBag()); // returns trash bag A makeKitchen() trashBags trashBags getTrashBag getTrashBag" }, { "answer_id": 10437122, "author": "Gerardo Lima", "author_id": 394042, "author_profile": "https://Stackoverflow.com/users/394042", "pm_score": 6, "selected": false, "text": "// makeSequencer will return a \"sequencer\" function\nvar makeSequencer = function() {\n var _count = 0; // not accessible outside this function\n var sequencer = function () {\n return _count++;\n }\n return sequencer;\n}\n\nvar fnext = makeSequencer();\nvar v0 = fnext(); // v0 = 0;\nvar v1 = fnext(); // v1 = 1;\nvar vz = fnext._count // vz = undefined\n" }, { "answer_id": 12122448, "author": "Jérôme Verstrynge", "author_id": 520957, "author_profile": "https://Stackoverflow.com/users/520957", "pm_score": 4, "selected": false, "text": "var a = 1;\n\nfunction b(x) {\n var c = 2;\n return x * c;\n}\n c b function a(x) {\n return function b(y) {\n return x + y;\n }\n}\n a b b a a x b x y x var c = a(3);\n c b x c var c = function b(y) {\n return 3 + y;\n}\n b x var d = c(4);\n d x x b b c (function () {\n var f = \"Some message\";\n alert(f);\n})();\n f f var a = new Array();\n\nfor (var i=0; i<2; i++) {\n a[i]= function(x) { return x + i ; }\n}\n a a[0] = function (x) { return x + 0 ; }\na[1] = function (x) { return x + 1 ; }\na[2] = function (x) { return x + 2 ; }\n i a[0] = function (x) { return x + 2 ; }\na[1] = function (x) { return x + 2 ; }\na[2] = function (x) { return x + 2 ; }\n var a = new Array();\n\nfor (var i=0; i<2; i++) {\n a[i]= function(tmp) {\n return function (x) { return x + tmp ; }\n } (i);\n}\n tmp i" }, { "answer_id": 13074647, "author": "srgstm", "author_id": 875940, "author_profile": "https://Stackoverflow.com/users/875940", "pm_score": 6, "selected": false, "text": "function foo (initValue) {\n //This variable is not destroyed when the foo function exits.\n //It is 'captured' by the two nested functions returned below.\n var value = initValue;\n\n //Note that the two returned functions are created right now.\n //If the foo function is called again, it will return\n //new functions referencing a different 'value' variable.\n return {\n getValue: function () { return value; },\n setValue: function (newValue) { value = newValue; }\n }\n}\n\nfunction bar () {\n //foo sets its local variable 'value' to 5 and returns an object with\n //two functions still referencing that local variable\n var obj = foo(5);\n\n //Extracting functions just to show that no 'this' is involved here\n var getValue = obj.getValue;\n var setValue = obj.setValue;\n\n alert(getValue()); //Displays 5\n setValue(10);\n alert(getValue()); //Displays 10\n\n //At this point getValue and setValue functions are destroyed\n //(in reality they are destroyed at the next iteration of the garbage collector).\n //The local variable 'value' in the foo is no longer referenced by\n //anything and is destroyed too.\n}\n\nbar();\n" }, { "answer_id": 13658697, "author": "ketan", "author_id": 783815, "author_profile": "https://Stackoverflow.com/users/783815", "pm_score": 4, "selected": false, "text": "// A function that generates a new function for adding numbers.\nfunction addGenerator( num ) {\n // Return a simple function for adding two numbers\n // with the first number borrowed from the generator\n return function( toAdd ) {\n return num + toAdd\n };\n}\n\n// addFive now contains a function that takes one argument,\n// adds five to it, and returns the resulting number.\nvar addFive = addGenerator( 5 );\n// We can see here that the result of the addFive function is 9,\n// when passed an argument of 4.\nalert( addFive( 4 ) == 9 );\n" }, { "answer_id": 15097817, "author": "jondavidjohn", "author_id": 555384, "author_profile": "https://Stackoverflow.com/users/555384", "pm_score": 9, "selected": false, "text": "// Declare counter outside event handler's scope\nvar counter = 0;\nvar element = document.getElementById('button');\n\nelement.addEventListener(\"click\", function() {\n // Increment outside counter\n counter++;\n\n if (counter === 3) {\n // Do something every third time\n console.log(\"Third time's the charm!\");\n\n // Reset counter\n counter = 0;\n }\n}); <button id=\"button\">Click Me!</button> var element = document.getElementById('button');\n\nelement.addEventListener(\"click\", (function() {\n // init the count to 0\n var count = 0;\n\n return function(e) { // <- This function becomes the click handler\n count++; // and will retain access to the above `count`\n\n if (count === 3) {\n // Do something every third time\n console.log(\"Third time's the charm!\");\n\n //Reset counter\n count = 0;\n }\n };\n})()); <button id=\"button\">Click Me!</button> // _______________________Immediately invoked______________________\n// | |\n// | Scope retained for use ___Returned as the____ |\n// | only by returned function | value of func | |\n// | | | | | |\n// v v v v v v\nvar func = (function() { var a = 'val'; return function() { alert(a); }; })();\n func(); // Alerts \"val\"\nfunc.a; // Undefined\n" }, { "answer_id": 15208427, "author": "dmi3y", "author_id": 1401973, "author_profile": "https://Stackoverflow.com/users/1401973", "pm_score": 6, "selected": false, "text": "function playingInBrothersRoom (withToys) {\n // We closure toys which we played in the brother's room. When he come back and lock the door\n // your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.\n var closureToys = withToys || [],\n returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.\n\n var brotherGivesToyBack = function (toy) {\n // New request. There is not yet closureToys on brother's hand yet. Give him a time.\n returnToy = null;\n if (toy && closureToys.length > 0) { // If we ask for a specific toy, the brother is going to search for it.\n\n for ( countIt = closureToys.length; countIt; countIt--) {\n if (closureToys[countIt - 1] == toy) {\n returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';\n break;\n }\n }\n returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';\n }\n else if (closureToys.length > 0) { // Otherwise, just give back everything he has in the room.\n returnToy = 'Behold! ' + closureToys.join(', ') + '.';\n closureToys = [];\n }\n else {\n returnToy = 'Hey, lil shrimp, I gave you everything!';\n }\n console.log(returnToy);\n }\n return brotherGivesToyBack;\n}\n// You are playing in the house, including the brother's room.\nvar toys = ['teddybear', 'car', 'jumpingrope'],\n askBrotherForClosuredToy = playingInBrothersRoom(toys);\n\n// The door is locked, and the brother came from the school. You could not cheat and take it out directly.\nconsole.log(askBrotherForClosuredToy.closureToys); // Undefined\n\n// But you could ask your brother politely, to give it back.\naskBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear\naskBrotherForClosuredToy('ball'); // The brother would not be able to find it.\naskBrotherForClosuredToy(); // The brother gives you all the rest\naskBrotherForClosuredToy(); // Nothing left in there\n" }, { "answer_id": 16597261, "author": "Stupid Stupid", "author_id": 2391385, "author_profile": "https://Stackoverflow.com/users/2391385", "pm_score": 6, "selected": false, "text": "function the_closure() {\n var x = 4;\n return function () {\n return x; // Here, we look back inside the_closure for the value of x\n }\n}\n\nvar myFn = the_closure();\nmyFn(); //=> 4\n" }, { "answer_id": 16945392, "author": "Arman", "author_id": 1847185, "author_profile": "https://Stackoverflow.com/users/1847185", "pm_score": 4, "selected": false, "text": "function Baby(){\n this.iTrustYou = true;\n}\n\nBaby.prototype.hug = function (baby) {\n var smiles = 0;\n\n if (baby.iTrustYou) {\n return function() {\n smiles++;\n alert(smiles);\n };\n }\n};\n\nvar\n arman = new Baby(\"Arman\"),\n morgan = new Baby(\"Morgana\");\n\nvar hug = arman.hug(morgan);\nhug();\nhug();\n" }, { "answer_id": 16959645, "author": "Max Tkachenko", "author_id": 1393791, "author_profile": "https://Stackoverflow.com/users/1393791", "pm_score": 9, "selected": false, "text": "var plane = function(defaultAirport) {\n\n var lastAirportLeft = defaultAirport;\n\n var car = {\n driver: {\n startAccessPlaneInfo: function() {\n setInterval(function() {\n console.log(\"Last airport was \" + lastAirportLeft);\n }, 2000);\n }\n }\n };\n car.driver.startAccessPlaneInfo();\n\n return {\n leaveTheAirport: function(airPortName) {\n lastAirportLeft = airPortName;\n }\n }\n}(\"Boryspil International Airport\");\n\nplane.leaveTheAirport(\"John F. Kennedy\");" }, { "answer_id": 17200991, "author": "Chev", "author_id": 498624, "author_profile": "https://Stackoverflow.com/users/498624", "pm_score": 8, "selected": false, "text": "console.log('CLOSURES DONE RIGHT');\n\nvar arr = [];\n\nfunction createClosure(n) {\n return function () {\n return 'n = ' + n;\n }\n}\n\nfor (var index = 0; index < 10; index++) {\n arr[index] = createClosure(index);\n}\n\nfor (var index of arr) {\n console.log(arr[index]());\n}\n createClosure(n) n index n createClosure(n) n createClosure(n) n createClosure(n) console.log('CLOSURES DONE WRONG');\n\nfunction createClosureArray() {\n var badArr = [];\n\n for (var index = 0; index < 10; index++) {\n badArr[index] = function () {\n return 'n = ' + index;\n };\n }\n return badArr;\n}\n\nvar badArr = createClosureArray();\n\nfor (var index of badArr) {\n console.log(badArr[index]());\n}\n createClosureArray() createClosureArray() index index index createClosureArray createClosureArray() index index index index index" }, { "answer_id": 17254359, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 5, "selected": false, "text": "function person(name, age){\n\n var name = name;\n var age = age;\n\n function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n\n return introduce;\n}\n\nvar a = person(\"Jack\",12);\nvar b = person(\"Matt\",14);\n person a b introduce person a(); //My name is Jack, and I'm 12\nb(); //My name is Matt, and I'm 14\n closure a = {\n name: \"Jack\",\n age: 12,\n call: function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n}\n\nclosure b = {\n name: \"Matt\",\n age: 14,\n call: function introduce(){\n alert(\"My name is \"+name+\", and I'm \"+age);\n }\n}\n class function constructor local variables instance properties properties inner functions instance methods function object \"properties\"" }, { "answer_id": 17308587, "author": "Matt", "author_id": 706054, "author_profile": "https://Stackoverflow.com/users/706054", "pm_score": 8, "selected": false, "text": "function make_calculator() {\n var n = 0; // this calculator stores a single number n\n return {\n add: function(a) {\n n += a;\n return n;\n },\n multiply: function(a) {\n n *= a;\n return n;\n }\n };\n}\n\nfirst_calculator = make_calculator();\nsecond_calculator = make_calculator();\n\nfirst_calculator.add(3); // returns 3\nsecond_calculator.add(400); // returns 400\n\nfirst_calculator.multiply(11); // returns 33\nsecond_calculator.multiply(10); // returns 4000\n make_calculator n add multiply make_calculator n make_calculator add multiply" }, { "answer_id": 21353238, "author": "roland", "author_id": 313353, "author_profile": "https://Stackoverflow.com/users/313353", "pm_score": 5, "selected": false, "text": "init: pass first what's needed...\naction: in order to achieve something for later execution.\n Daddy: Listen. Could you bring mum some milk (2).\nTom: No problem.\nDaddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.\nDaddy: But get ready first. And bring the map with you (1), it may come in handy\nDaddy: Then off you go (3). Ok?\nTom: A piece of cake!\n function getReady(map) {\n var cleverBoy = 'I examine the ' + map;\n return function(what, who) {\n return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map\n }\n}\nvar offYouGo = getReady('daddy-map');\noffYouGo('milk', 'mum');\n offYouGo('potatoes', 'great mum');\n" }, { "answer_id": 22533155, "author": "Ravi", "author_id": 1000849, "author_profile": "https://Stackoverflow.com/users/1000849", "pm_score": 4, "selected": false, "text": "function makeAdder(x) {\n return function(y) {\n return x + y;\n };\n}\n\nvar add5 = makeAdder(5);\nvar add10 = makeAdder(10);\n\nconsole.log(add5(2)); // 7\nconsole.log(add10(2)); // 12\n function makeAdder(x) {\n return {\n add: function(y){\n return x + y;\n }\n }\n}\n\nvar add5 = makeAdder(5);\nconsole.log(add5.add(2));//7\n\nvar add10 = makeAdder(10);\nconsole.log(add10.add(2));//12\n $(function(){\n var name=\"Closure is easy\";\n $('div').click(function(){\n $('p').text(name);\n });\n});\n" }, { "answer_id": 22721884, "author": "williambq", "author_id": 1200607, "author_profile": "https://Stackoverflow.com/users/1200607", "pm_score": 3, "selected": false, "text": "function sayHello(name) {\n var text = 'Hello ' + name; // Local variable\n console.log(text);\n var sayAlert = function () {\n alert(text);\n }\n return sayAlert;\n}\n\nsayHello(); \n/* This will write 'Hello undefined' to the console (in Chrome anyway), \nbut will not alert though since it returns a function handle to nothing). \nSince no handle or reference is created, I imagine a good js engine would \ndestroy/dispose of the internal sayAlert function once it completes. */\n\n// Create a handle/reference/instance of sayHello() using the name 'Bob'\nsayHelloBob = sayHello('Bob');\nsayHelloBob();\n\n// Create another handle or reference to sayHello with a different name\nsayHelloGerry = sayHello('Gerry');\nsayHelloGerry();\n\n/* Now calling them again demonstrates that each handle or reference contains its own \nunique local variable memory space. They remain in memory 'forever' \n(or until your computer/browser explode) */\nsayHelloBob();\nsayHelloGerry();\n" }, { "answer_id": 22832931, "author": "Bhojendra Rauniyar", "author_id": 2138752, "author_profile": "https://Stackoverflow.com/users/2138752", "pm_score": 4, "selected": false, "text": "var outer = function(params){ //Outer function defines a variable called params\n var inner = function(){ // Inner function has access to the params variable of the outer function\n return params;\n }\n return inner; //Return inner function exposing it to outer scope\n},\nmyFunc = outer(\"myParams\");\nmyFunc(); //Returns \"myParams\"\n" }, { "answer_id": 23711357, "author": "Pawel Furmaniak", "author_id": 221315, "author_profile": "https://Stackoverflow.com/users/221315", "pm_score": 3, "selected": false, "text": "// 'name' is resolved in the namespace created for one invocation of bindMessage\n// the processor cannot enter this namespace by the time displayMessage is called\nfunction bindMessage(name, div) {\n\n function displayMessage() {\n alert('This is ' + name);\n }\n\n $(div).click(displayMessage);\n}\n" }, { "answer_id": 26602035, "author": "Mayur Randive", "author_id": 3145245, "author_profile": "https://Stackoverflow.com/users/3145245", "pm_score": 5, "selected": false, "text": "function movieBooking(movieName) {\n var bookedSeatCount = 0;\n return function(name) {\n ++bookedSeatCount ;\n alert( name + \" - \" + movieName + \", Seat - \" + bookedSeatCount )\n };\n};\n\nvar MI1 = movieBooking(\"Mission Impossible 1 \");\nvar MI2 = movieBooking(\"Mission Impossible 2 \");\n\nMI1(\"Mayur\");\n// alert\n// Mayur - Mission Impossible 1, Seat - 1\n\nMI1(\"Raju\");\n// alert\n// Raju - Mission Impossible 1, Seat - 2\n\nMI2(\"Priyanka\");\n// alert\n// Raja - Mission Impossible 2, Seat - 1\n" }, { "answer_id": 26620526, "author": "grateful", "author_id": 3441335, "author_profile": "https://Stackoverflow.com/users/3441335", "pm_score": 6, "selected": false, "text": "function sing(person) {\n\n var firstPart = \"There was \" + person + \" who swallowed \";\n\n var fly = function() {\n var creature = \"a fly\";\n var result = \"Perhaps she'll die\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var spider = function() {\n var creature = \"a spider\";\n var result = \"that wiggled and jiggled and tickled inside her\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var bird = function() {\n var creature = \"a bird\";\n var result = \"How absurd!\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n var cat = function() {\n var creature = \"a cat\";\n var result = \"Imagine That!\";\n alert(firstPart + creature + \"\\n\" + result);\n };\n\n fly();\n spider();\n bird();\n cat();\n}\n\nvar person=\"an old lady\";\n\nsing(person);\n function cookMeal() { /* STUFF INSIDE THE FUNCTION */ }\n /*...*/ // () cookMeal(you, me, yourFriend, myFriend, fridge, dinnerTime) {} (person) { } function sing(person) { /* STUFF INSIDE THE FUNCTION */ }\n var person=\"an old lady\";\n {} person=\"a young man\" sing(person);\n fly();\nspider();\nbird();\ncat();\n" }, { "answer_id": 26860224, "author": "Shushanth Pallegar", "author_id": 4229768, "author_profile": "https://Stackoverflow.com/users/4229768", "pm_score": 5, "selected": false, "text": "function getFullName(a, b) {\n return a + b;\n}\n\nfunction makeFullName(fn) {\n\n return function(firstName) {\n\n return function(secondName) {\n\n return fn(firstName, secondName);\n\n }\n }\n}\n\nmakeFullName(getFullName)(\"Stack\")(\"overflow\"); // Stackoverflow\n" }, { "answer_id": 28442157, "author": "PsyChip", "author_id": 1381841, "author_profile": "https://Stackoverflow.com/users/1381841", "pm_score": 4, "selected": false, "text": " var calculate = {\n number: 0,\n init: function (num) {\n this.number = num;\n },\n add: function (val) {\n this.number += val;\n },\n rem: function (val) {\n this.number -= val;\n }\n };\n //Addition\nFirst think about scope which defines what variable you have to access to (In Javascript);\n\n//there are two kinds of scope\nGlobal Scope which include variable declared outside function or curly brace\n\nlet globalVariable = \"foo\";\n function User(){\n let name = \"foo\";\n alert(name);\n}\nalert(name);//error\n\n//Block scope is when you declare a variable within a block then you can access that variable only within a block \n{\n let user = \"foo\";\n alert(user);\n}\nalert(user);\n//Uncaught ReferenceError: user is not defined at.....\n\n//A Closure\n\nfunction User(fname){\n return function(lname){\n return fname + \" \" lname;\n }\n}\nlet names = User(\"foo\");\nalert(names(\"bar\"));\n\n//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope\n" }, { "answer_id": 28507451, "author": "floribon", "author_id": 1501926, "author_profile": "https://Stackoverflow.com/users/1501926", "pm_score": 7, "selected": false, "text": "var a = 42;\n\nfunction b() { return a; }\n" }, { "answer_id": 28816564, "author": "Michael Dziedzic", "author_id": 4171115, "author_profile": "https://Stackoverflow.com/users/4171115", "pm_score": 6, "selected": false, "text": "function outerFunction() {\n var outerVar = \"monkey\";\n \n function innerFunction() {\n alert(outerVar);\n }\n \n innerFunction();\n}\n\nouterFunction(); function outerFunction() {\n var outerVar = \"monkey\";\n \n function innerFunction() {\n return outerVar;\n }\n \n return innerFunction;\n}\n\nvar referenceToInnerFunction = outerFunction();\nalert(referenceToInnerFunction()); function outerFunction() {\n var outerVar = \"monkey\";\n \n function innerFunction() {\n return outerVar;\n }\n \n return innerFunction;\n}\n\nvar referenceToInnerFunction = outerFunction();\nalert(referenceToInnerFunction());\n\nouterFunction = null;\nalert(referenceToInnerFunction()); function outerFunction() {\n var outerVar = \"monkey\";\n \n function innerFunction() {\n alert(outerVar);\n }\n \n outerVar = \"gorilla\";\n\n innerFunction();\n}\n\nouterFunction();" }, { "answer_id": 29525677, "author": "Rafael Eyng", "author_id": 1717979, "author_profile": "https://Stackoverflow.com/users/1717979", "pm_score": 5, "selected": false, "text": "var name = 'Rafael';\n\nvar sayName = function() {\n console.log(name);\n};\n sayName name name sayName sayName sayName functionThatTakesACallback(sayName);\n sayName functionThatTakesACallback functionThatTakesACallback sayName name functionThatTakesACallback name sayName functionThatTakesACallback name functionThatTakesACallback ReferenceError: name is not defined name name sayName functionThatTakesACallback sayName name sayName" }, { "answer_id": 29639524, "author": "Andy", "author_id": 200224, "author_profile": "https://Stackoverflow.com/users/200224", "pm_score": 5, "selected": false, "text": "function foo() {\n var i = 1;\n return function() {\n console.log(i++);\n }\n}\n\nvar bar = foo();\nbar();\nbar();\nbar();\n\nvar baz = foo();\nbaz();\nbaz();\nbaz();\n i foo() bar baz" }, { "answer_id": 29693176, "author": "Dinesh Kanivu", "author_id": 2768137, "author_profile": "https://Stackoverflow.com/users/2768137", "pm_score": 5, "selected": false, "text": "function f1() function f2() f1() f2() var x = 10 f1() f2() var x = 10 function f1() {\n var x=10;\n\n function f2() {\n console.log(x)\n }\n\n return f2\n\n}\nf1()\n f1()" }, { "answer_id": 29932159, "author": "Javier La Banca", "author_id": 4175684, "author_profile": "https://Stackoverflow.com/users/4175684", "pm_score": 3, "selected": false, "text": " var Closure = (function () {\n // This is a closure\n // Any methods, variables and properties you define here are \"private\"\n // and can't be accessed from outside the function.\n\n //This is a private variable\n var foo = \"\";\n\n //This is a private method\n var method = function(){\n\n }\n})();\n var Closure = (function () {\n // This is a closure\n // Any methods, variables and properties you define here are \"private\"\n // and can't be accessed from outside the function.\n\n //This is a private variable\n var foo = \"\";\n\n //This is a private method\n var method = function(){\n\n }\n\n //The method will be accessible from outside the closure\n return {\n method: method\n }\n\n})();\n\nClosure.method();\n" }, { "answer_id": 29945428, "author": "enb081", "author_id": 2063910, "author_profile": "https://Stackoverflow.com/users/2063910", "pm_score": 4, "selected": false, "text": "function showPostCard(Sender, Receiver) {\n\n var PostCardMessage = \" Happy Spring!!! Love, \";\n\n function PreparePostCard() {\n return \"Dear \" + Receiver + PostCardMessage + Sender;\n }\n\n return PreparePostCard();\n}\nshowPostCard(\"Granny\", \"Olivia\");\n" }, { "answer_id": 30173047, "author": "Tero Tolonen", "author_id": 2287682, "author_profile": "https://Stackoverflow.com/users/2287682", "pm_score": 7, "selected": false, "text": "var parent = function() {\n var name = \"Mary\"; // secret\n}\n var parent = function() {\n var name = \"Mary\";\n var child = function(childName) {\n // I can also see that \"name\" is \"Mary\"\n }\n}\n var parent = function() {\n var name = \"Mary\";\n var child = function(childName) {\n return \"My name is \" + childName +\", child of \" + name; \n }\n return child; // child leaves the parent ->\n}\nvar child = parent(); // < - and here it is outside \n child(\"Alice\") => \"My name is Alice, child of Mary\"\n" }, { "answer_id": 30519095, "author": "Harry Robbins", "author_id": 4926814, "author_profile": "https://Stackoverflow.com/users/4926814", "pm_score": 4, "selected": false, "text": "var x = 1;\nfunction myFN() {\n alert(x); //1, as opposed to undefined.\n}\n// Or\nfunction a() {\n var x = 1;\n function b() {\n alert(x); //1, as opposed to undefined.\n }\n b();\n}\n" }, { "answer_id": 31374952, "author": "TastyCode", "author_id": 949827, "author_profile": "https://Stackoverflow.com/users/949827", "pm_score": 3, "selected": false, "text": "function foo() {\n var a = 2;\n\n function bar() {\n console.log( a );\n }\n return bar;\n}\n\nfunction test() {\n var bz = foo();\n bz();\n}\n\n// prints 2. Here function bar referred by var bz is outside \n// its lexical scope but it can still access it\ntest(); \n" }, { "answer_id": 31608312, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 4, "selected": false, "text": "function outer(x){\n return function inner(y){\n return x+y;\n }\n}\n var add10 = outer(10);\nadd10(20); // The result will be 30\nadd10(40); // The result will be 50\n\nvar add20 = outer(20);\nadd20(20); // The result will be 40\nadd20(40); // The result will be 60\n" }, { "answer_id": 32025281, "author": "Saber", "author_id": 1262198, "author_profile": "https://Stackoverflow.com/users/1262198", "pm_score": 6, "selected": false, "text": "LexicalEnvironment this.say this.say this.say.[[Scope]]" }, { "answer_id": 32348248, "author": "Dmitry Frank", "author_id": 1099240, "author_profile": "https://Stackoverflow.com/users/1099240", "pm_score": 4, "selected": false, "text": "LexicalEnvironment \"use strict\";\n\nvar foo = 1;\nvar bar = 2;\n\nfunction myFunc() {\n //-- Define local-to-function variables\n var a = 1;\n var b = 2;\n var foo = 3;\n}\n\n//-- And then, call it:\nmyFunc();\n myFunc()" }, { "answer_id": 33072285, "author": "David Rosson", "author_id": 1068700, "author_profile": "https://Stackoverflow.com/users/1068700", "pm_score": 3, "selected": false, "text": "console.log(x);\n// undefined\n undefined x x 42 var x = 42;\nconsole.log(x);\n// 42\n x x x = 43;\nconsole.log(x);\n// 43\n x function A() {\n var x = 42;\n}\n\nconsole.log(x);\n\n// undefined\n var x = 42;\n\nfunction A() {\n console.log(x);\n}\n\n// 42\n A x function A() {\n var x = 42;\n}\n\nfunction B() {\n console.log(x);\n}\n\n// undefined\n B A B A function A() {\n\n var x = 42;\n\n function B() {\n console.log(x);\n }\n\n}\n\n// 42\n function A() {\n console.log(42);\n}\n A();\n\n// 42\n var a = function() {\n console.log(42);\n};\n a a();\n// 42\n setTimeout(a, 1000);\n a // 42\n var a = function() {\n\n var text = 'Hello!'\n\n var b = function() {\n console.log(text);\n // inside function `b`, you have access to `text`\n };\n\n // but you want to run `b` later, rather than right away\n setTimeout(b, 1000);\n\n}\n // 'Hello!'\n var c;\n\nvar a = function() {\n\n var text = 'Hello!'\n\n var b = function() {\n console.log(text);\n // inside function `b`, you have access to `text`\n };\n\n c = b;\n\n}\n\n// now we are out side of function `a`\n// call `a` so the code inside `a` runs\na(); \n\n// now `c` has a value that is a function\n// because what happened when `a` ran\n\n// when you run `c`\nc();\n\n// 'Hello!'\n a c a" }, { "answer_id": 33279345, "author": "Ron Deijkers", "author_id": 2240490, "author_profile": "https://Stackoverflow.com/users/2240490", "pm_score": 4, "selected": false, "text": "var tellStoryOfPinocchio = function(original) {\n\n // Prepare for exciting things to happen\n var pinocchioFindsMisterGeppetto;\n var happyEnding;\n\n // The story starts where Pinocchio searches for his 'father'\n var pinocchio = {\n name: 'Pinocchio',\n location: 'in the sea',\n noseLength: 2\n };\n\n // Is it a dog... is it a fish...\n // The dogfish appears, however there is no such concept as the belly\n // of the monster, there is just a monster...\n var terribleDogfish = {\n swallowWhole: function(snack) {\n // The swallowing of Pinocchio introduces a new environment (for the\n // things happening inside it)...\n // The BELLY closure... with all of its guts and attributes\n var mysteriousLightLocation = 'at Gepetto\\'s ship';\n\n // Yes: in my version of the story the monsters mouth is directly\n // connected to its belly... This might explain the low ratings\n // I had for biology...\n var mouthLocation = 'in the monsters mouth and then outside';\n\n var puppet = snack;\n\n\n puppet.location = 'inside the belly';\n alert(snack.name + ' is swallowed by the terrible dogfish...');\n\n // Being inside the belly, Pinocchio can now experience new adventures inside it\n pinocchioFindsMisterGeppetto = function() {\n // The event of Pinocchio finding Mister Geppetto happens inside the\n // belly and so it makes sence that it refers to the things inside\n // the belly (closure) like the mysterious light and of course the\n // hero Pinocchio himself!\n alert(puppet.name + ' sees a mysterious light (also in the belly of the dogfish) in the distance and swims to it to find Mister Geppetto! He survived on ship supplies for two years after being swallowed himself. ');\n puppet.location = mysteriousLightLocation;\n\n alert(puppet.name + ' tells Mister Geppetto he missed him every single day! ');\n puppet.noseLength++;\n }\n\n happyEnding = function() {\n // The escape of Pinocchio and Mister Geppetto happens inside the belly:\n // it refers to Pinocchio and the mouth of the beast.\n alert('After finding Mister Gepetto, ' + puppet.name + ' and Mister Gepetto travel to the mouth of the monster.');\n alert('The monster sleeps with its mouth open above the surface of the water. They escape through its mouth. ');\n puppet.location = mouthLocation;\n if (original) {\n alert(puppet.name + ' is eventually hanged for his innumerable faults. ');\n } else {\n alert(puppet.name + ' is eventually turned into a real boy and they all lived happily ever after...');\n }\n }\n }\n }\n\n alert('Once upon a time...');\n alert('Fast forward to the moment that Pinocchio is searching for his \\'father\\'...');\n alert('Pinocchio is ' + pinocchio.location + '.');\n terribleDogfish.swallowWhole(pinocchio);\n alert('Pinocchio is ' + pinocchio.location + '.');\n pinocchioFindsMisterGeppetto();\n alert('Pinocchio is ' + pinocchio.location + '.');\n happyEnding();\n alert('Pinocchio is ' + pinocchio.location + '.');\n\n if (pinocchio.noseLength > 2)\n console.log('Hmmm... apparently a little white lie was told. ');\n}\n\ntellStoryOfPinocchio(false);\n\n " }, { "answer_id": 33525748, "author": "Eugene Tiurin", "author_id": 2676500, "author_profile": "https://Stackoverflow.com/users/2676500", "pm_score": 4, "selected": false, "text": "function getA() {\n var a = [];\n\n // this action happens later,\n // after the function returned\n // the `a` value\n setTimeout(function() {\n a.splice(0, 0, 1, 2, 3, 4, 5);\n });\n\n return a;\n}\n\nvar a = getA();\nout('What is `a` length?');\nout('`a` length is ' + a.length);\n\nsetTimeout(function() {\n out('No wait...');\n out('`a` length is ' + a.length);\n out('OK :|')\n}); <pre id=\"output\"></pre>\n\n<script>\n function out(k) {\n document.getElementById('output').innerHTML += '> ' + k + '\\n';\n }\n</script>" }, { "answer_id": 33531512, "author": "Gerard ONeill", "author_id": 1331672, "author_profile": "https://Stackoverflow.com/users/1331672", "pm_score": 2, "selected": false, "text": "var closure = createclosure(varForClosure);\nclosure(param1); // closure has access to whatever createclosure gave it access to,\n // including the parameter storing varForClosure.\n var contextvar = varForClosure; // use a struct for storing more than one..\ncontextclosure(contextvar, param1);\n var contextobj = new contextclass(varForClosure);\ncontextobj->objclosure(param1);\n" }, { "answer_id": 33544287, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 4, "selected": false, "text": "var add = (function() {\n var counter = 0;\n return function() {\n return counter += 1;\n }\n})();\n\nadd();\nadd();\nadd();\n// The counter is now 3\n add" }, { "answer_id": 33904070, "author": "NinjaBeetle", "author_id": 1509007, "author_profile": "https://Stackoverflow.com/users/1509007", "pm_score": 3, "selected": false, "text": "function caveman {\n var rock = \"diamond\";\n return {\n getRock: function() {\n return rock;\n }\n};\n}\n var friend = caveman();\nvar rock = friend.getRock();\n" }, { "answer_id": 33961224, "author": "Pao Im", "author_id": 1256497, "author_profile": "https://Stackoverflow.com/users/1256497", "pm_score": 3, "selected": false, "text": "// let say we can only use a traditional for loop, not the forEach\n\nfor (var i = 0; i < 10; i++) {\n \n setTimeout(function() {\n console.log('without closure the visited index - '+ i)\n })\n}\n\n// this will print 10 times 'visited index - 10', which is not correct\n\n/**\nExpected output is \n\nvisited index - 0\nvisited index - 1\n.\n.\n.\nvisited index - 9\n\n**/\n\n// we can solve it by using closure concept \n //by using an IIFE (Immediately Invoked Function Expression)\n\n\n// --- updated code ---\n\nfor (var i = 0; i < 10; i++) {\n (function (i) {\n setTimeout(function() {\n console.log('with closure the visited index - '+ i)\n })\n })(i);\n} let var" }, { "answer_id": 34531380, "author": "Nikhil Ranjan", "author_id": 1125824, "author_profile": "https://Stackoverflow.com/users/1125824", "pm_score": 4, "selected": false, "text": "a f f f f g f f g f f [[scope]] var data = \"My Data!\";\nsetTimeout(function() {\n console.log(data); // Prints \"My Data!\"\n}, 3000);\n function makeAdder(n) {\n var inc = n;\n var sum = 0;\n return function add() {\n sum = sum + inc;\n return sum;\n };\n}\n\nvar adder3 = makeAdder(3);\n" }, { "answer_id": 34831990, "author": "devlighted", "author_id": 5791848, "author_profile": "https://Stackoverflow.com/users/5791848", "pm_score": 3, "selected": false, "text": "function newCounter() {\n var counter = 0;\n return function increment() {\n counter += 1;\n }\n}\n\nvar counter1 = newCounter();\nvar counter2 = newCounter();\n\ncounter1(); // Number of events: 1\ncounter1(); // Number of events: 2\ncounter2(); // Number of events: 1\ncounter1(); // Number of events: 3\n" }, { "answer_id": 35250157, "author": "soundyogi", "author_id": 3293027, "author_profile": "https://Stackoverflow.com/users/3293027", "pm_score": 3, "selected": false, "text": "var pure = function pure(x){\n return x \n // only own environment is used\n}\n\nvar foo = \"bar\"\n\nvar closure = function closure(){\n return foo\n // foo is free variable from the outer environment\n}\n" }, { "answer_id": 36017683, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "var closure = function() {\n var count = 0;\n return function() {\n count++;\n console.log(count);\n };\n};\n\nvar counter = closure();\n\ncounter() // returns 1\ncounter() // returns 2\ncounter() // returns 3\n count counter()" }, { "answer_id": 36424854, "author": "Abrar Jahin", "author_id": 2193439, "author_profile": "https://Stackoverflow.com/users/2193439", "pm_score": 5, "selected": false, "text": "function showName (firstName, lastName) {
\n var nameIntro = \"Your name is \";\n // this inner function has access to the outer function's variables, including the parameter\n ​function makeFullName () {
 \n​ return nameIntro + firstName + \" \" + lastName;
 \n }\n​\n​ return makeFullName ();
\n}
\n​\nshowName (\"Michael\", \"Jackson\"); // Your name is Michael Jackson
 $(function() {\n​\n​ var selections = []; \n $(\".niners\").click(function() { // this closure has access to the selections variable​\n selections.push (this.prop(\"name\")); // update the selections variable in the outer function's scope​\n });\n​}); function celebrityName (firstName) {\n var nameIntro = \"This celebrity is \";\n // this inner function has access to the outer function's variables, including the parameter​\n function lastName (theLastName) {\n return nameIntro + firstName + \" \" + theLastName;\n }\n return lastName;\n}\n​\n​var mjName = celebrityName (\"Michael\"); // At this juncture, the celebrityName outer function has returned.​\n​\n​// The closure (lastName) is called here after the outer function has returned above​\n​// Yet, the closure still has access to the outer function's variables and parameter​\nmjName (\"Jackson\"); // This celebrity is Michael Jackson
 function celebrityID () {\n var celebrityID = 999;\n // We are returning an object with some inner functions​\n // All the inner functions have access to the outer function's variables​\n return {\n getID: function () {\n // This inner function will return the UPDATED celebrityID variable​\n // It will return the current value of celebrityID, even after the changeTheID function changes it​\n return celebrityID;\n },\n setID: function (theNewID) {\n // This inner function will change the outer function's variable anytime​\n celebrityID = theNewID;\n }\n }\n​\n}\n​\n​var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.​\nmjID.getID(); // 999​\nmjID.setID(567); // Changes the outer function's variable​\nmjID.getID(); // 567: It returns the updated celebrityId variable
 // This example is explained in detail below (just after this code box).​\n​function celebrityIDCreator (theCelebrities) {\n var i;\n var uniqueID = 100;\n for (i = 0; i < theCelebrities.length; i++) {\n theCelebrities[i][\"id\"] = function () {\n return uniqueID + i;\n }\n }\n \n return theCelebrities;\n}\n​\n​var actionCelebs = [{name:\"Stallone\", id:0}, {name:\"Cruise\", id:0}, {name:\"Willis\", id:0}];\n​\n​var createIdForActionCelebs = celebrityIDCreator (actionCelebs);\n​\n​var stalloneID = createIdForActionCelebs [0];

 console.log(stalloneID.id()); // 103" }, { "answer_id": 39012806, "author": "Alexis", "author_id": 5168153, "author_profile": "https://Stackoverflow.com/users/5168153", "pm_score": 3, "selected": false, "text": "function createCar()\n{\n var rawMaterial = [/* lots of object */];\n function transformation(rawMaterials)\n {\n /* lots of changement here */\n return transformedMaterial;\n }\n var transformedMaterial = transformation(rawMaterial);\n function assemblage(transformedMaterial)\n {\n /*Assemblage of parts*/\n return car;\n }\n return assemblage(transformedMaterial);\n}\n" }, { "answer_id": 39589063, "author": "Durgesh Pandey", "author_id": 5030579, "author_profile": "https://Stackoverflow.com/users/5030579", "pm_score": 4, "selected": false, "text": "var foo = function() {\n alert(\"Hello World!\");\n};\n\nvar bar = function(arg) {\n return arg;\n};\n\nbar(foo)();\n function add(value1, value2) {\n function doAdd(operand1, operand2) {\n return operand1 + operand2;\n }\n\n return doAdd(value1, value2);\n}\n\nvar foo = add(1, 2);\n// foo equals 3\n function add(value1, value2) {\n function doAdd() {\n return value1 + value2;\n }\n\n return doAdd();\n}\n\nvar foo = add(1, 2);\n// foo equals 3\n function add(value1) {\n return function doAdd(value2) {\n return value1 + value2;\n };\n}\n\nvar increment = add(1);\nvar foo = increment(2);\n// foo equals 3\n function increment(value2) {\n return 1 + value2;\n}\n <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Closures</title>\n <meta charset=\"UTF-8\" />\n <script>\n window.addEventListener(\"load\", function() {\n window.setInterval(showMessage, 1000, \"some message<br />\");\n });\n\n function showMessage(message) {\n document.getElementById(\"message\").innerHTML += message;\n }\n </script>\n</head>\n<body>\n <span id=\"message\"></span>\n</body>\n</html>\n window.addEventListener(\"load\", function() {\n var showMessage = getClosure(\"some message<br />\");\n\n window.setInterval(showMessage, 1000);\n});\n\nfunction getClosure(message) {\n function showMessage() {\n document.getElementById(\"message\").innerHTML += message;\n }\n\n return showMessage;\n}\n function Person(name) {\n this._name = name;\n\n this.getName = function() {\n return this._name;\n };\n}\n var person = new Person(\"Colin\");\n\nperson._name = \"Tom\";\n// person.getName() now returns \"Tom\"\n function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n}\n var person = new Person(\"Colin\");\n\nperson._name = \"Tom\";\n// person._name is \"Tom\" but person.getName() returns \"Colin\"\n <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Closures</title>\n <meta charset=\"UTF-8\" />\n <script>\n window.addEventListener(\"load\", function() {\n for (var i = 1; i < 4; i++) {\n var button = document.getElementById(\"button\" + i);\n\n button.addEventListener(\"click\", function() {\n alert(\"Clicked button \" + i);\n });\n }\n });\n </script>\n</head>\n<body>\n <input type=\"button\" id=\"button1\" value=\"One\" />\n <input type=\"button\" id=\"button2\" value=\"Two\" />\n <input type=\"button\" id=\"button3\" value=\"Three\" />\n</body>\n</html>\n function getHandler(i) {\n return function handler() {\n alert(\"Clicked button \" + i);\n };\n}\nwindow.addEventListener(\"load\", function() {\n for (var i = 1; i < 4; i++) {\n var button = document.getElementById(\"button\" + i);\n button.addEventListener(\"click\", getHandler(i));\n }\n});\n function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n\n this.sayHello = function() {\n alert(\"Hello!\");\n };\n}\n function Person(name) {\n var _name = name;\n\n this.getName = function() {\n return _name;\n };\n}\n\nPerson.prototype.sayHello = function() {\n alert(\"Hello!\");\n};\n" }, { "answer_id": 41773215, "author": "poushy", "author_id": 7417348, "author_profile": "https://Stackoverflow.com/users/7417348", "pm_score": 3, "selected": false, "text": "function book() {\n var pages = [....]; //array of pages in your book\n var bookMarkedPage = 20; //bookmarked page number\n function getPage(){\n return pages[bookMarkedPage];\n }\n return getPage;\n}\n\nvar myBook = book(),\n myPage = myBook.getPage();\n book() book()" }, { "answer_id": 42947217, "author": "zak.http", "author_id": 5897353, "author_profile": "https://Stackoverflow.com/users/5897353", "pm_score": 2, "selected": false, "text": "function multiplier(n) {\n function multiply(x) {\n return n*x;\n }\n return mutliply;\n}\n\nvar 10xmultiplier = multiplier(10);\nvar x = 10xmultiplier(5); // x= 50\n" }, { "answer_id": 43321420, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 3, "selected": false, "text": "function init() {\n var name = 'Mozilla'; // name is a local variable created by init\n function displayName() { // displayName() is the inner function, a closure\n alert(name); // use variable declared in the parent function \n }\n displayName(); \n}\ninit();\n function init() {\n var name = \"Mozilla\"; // name is a local variable created by init\n function displayName() { // displayName() is the inner function, a closure\n alert (name); // displayName() uses variable declared in the parent function \n }\n displayName(); \n}\ninit();\n function makeFunc() {\n var name = 'Mozilla';\n function displayName() {\n alert(name);\n }\n return displayName;\n}\n\nvar myFunc = makeFunc();\nmyFunc();\n function makeAdder(x) {\n return function(y) {\n return x + y;\n };\n}\n\nvar add5 = makeAdder(5);\nvar add10 = makeAdder(10);\n\nconsole.log(add5(2)); // 7\nconsole.log(add10(2)); // 12\n body {\n font-family: Helvetica, Arial, sans-serif;\n font-size: 12px;\n}\n\nh1 {\n font-size: 1.5em;\n}\n\nh2 {\n font-size: 1.2em;\n}\n function makeSizer(size) {\n return function() {\n document.body.style.fontSize = size + 'px';\n };\n}\n\nvar size12 = makeSizer(12);\nvar size14 = makeSizer(14);\nvar size16 = makeSizer(16);\n document.getElementById('size-12').onclick = size12;\ndocument.getElementById('size-14').onclick = size14;\ndocument.getElementById('size-16').onclick = size16;\n\n<a href=\"#\" id=\"size-12\">12</a>\n<a href=\"#\" id=\"size-14\">14</a>\n<a href=\"#\" id=\"size-16\">16</a>\n\n\nfunction makeSizer(size) {\n return function() {\n document.body.style.fontSize = size + 'px';\n };\n}\n\nvar size12 = makeSizer(12);\nvar size14 = makeSizer(14);\nvar size16 = makeSizer(16);\n\ndocument.getElementById('size-12').onclick = size12;\ndocument.getElementById('size-14').onclick = size14;\ndocument.getElementById('size-16').onclick = size16;\n" }, { "answer_id": 43554849, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 4, "selected": false, "text": "function Counter() {\n var counter = 0;\n\n var Increment = function () {\n counter++;\n alert(counter);\n }\n return {\n Increment\n }\n }\n var x = Counter(); // get the reference of the closure\nx.Increment(); // Displays 1\nx.Increment(); // Display 2 ( Maintains the private variables)\n" }, { "answer_id": 43634757, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 5, "selected": false, "text": "Angular Node.js jQuery function showName(firstName, lastName) {\n var nameIntro = \"Your name is \";\n // this inner function has access to the outer function's variables, including the parameter\n function makeFullName() {\n return nameIntro + firstName + \" \" + lastName;\n }\n return makeFullName();\n }\n\n console.log(showName(\"Michael\", \"Jackson\")); // Your name is Michael Jackson\n $(function() {\n var selections = [];\n $(\".niners\").click(function() { // this closure has access to the selections variable\n selections.push(this.prop(\"name\")); // update the selections variable in the outer function's scope\n });\n});\n //javascript\nfunction makeSizer(size) {\n return function() {\n document.body.style.fontSize = size + 'px';\n };\n}\n\nvar size12 = makeSizer(12);\nvar size14 = makeSizer(14);\nvar size16 = makeSizer(16);\n\ndocument.getElementById('size-12').onclick = size12;\ndocument.getElementById('size-14').onclick = size14;\ndocument.getElementById('size-16').onclick = size16; /*css*/\nbody {\n font-family: Helvetica, Arial, sans-serif;\n font-size: 12px;\n}\n\nh1 {\n font-size: 1.5em;\n}\n\nh2 {\n font-size: 1.2em;\n} <!--html><!-->\n<p>Some paragraph text</p>\n<h1>some heading 1 text</h1>\n<h2>some heading 2 text</h2>\n\n<a href=\"#\" id=\"size-12\">12</a>\n<a href=\"#\" id=\"size-14\">14</a>\n<a href=\"#\" id=\"size-16\">16</a>" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
111,129
<p>I have a table which is referenced by foreign keys on many other tables. In my program if I want to delete one of these rows I need to first search for dependencies and present them to the user - "This object depends on x from table y, z from table q, etc". I also expect the number of tables which have foreign keys to this table to grow considerably over time. </p> <p>Is the information_schema database a good way to do a search for all dependencies? I tried to query it to retrieve a list of all tables which have foreign keys to my table, then iterate over the result and select all entries from each table where the foreign key value matches the value the user is trying to delete. The query I have is as follows:</p> <pre><code>SELECT * FROM `KEY_COLUMN_USAGE` kcu LEFT JOIN TABLE_CONSTRAINTS tc ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE='FOREIGN KEY' AND (kcu.REFERENCED_TABLE_SCHEMA='db') AND (kcu.REFERENCED_TABLE_NAME = 'testtable') </code></pre> <p>which works perfectly for determining the tables which I need to search, however it is <em>very</em> slow. The query takes around 1 to 2 seconds at best to execute on my development machine, which will reduce a lot when I run it on my production server, but will still be quite slow.</p> <p>I need to know if it's a bad idea to use information_schema in this way. If not, how I can extract better performance from the query. Is the query I'm using solid or is there a better way to do it? If so, how best should I tackle this problem from a maintainability perspective.</p>
[ { "answer_id": 6069057, "author": "Denis de Bernardy", "author_id": 417194, "author_profile": "https://Stackoverflow.com/users/417194", "pm_score": 1, "selected": false, "text": "show create table create table rolando (num int not null, primary key (num) using hash);\n mysql> show create table rolando\\G\n (...)\n PRIMARY KEY (`num`) USING HASH\n\nmysql> show indexes from rolando;\n(...) | Index_type | (...)\n(...) | BTREE | (...)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
111,133
<p>Just wondering</p>
[ { "answer_id": 111158, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 0, "selected": false, "text": "String[] MazeArray = new String[5];\n\nMazeArray[0] = \"---X---X-------XF\";\nMazeArray[0] = \"-X-X-X---XXXXXXX-\";\nMazeArray[0] = \"-X-X-X-X-X---X---\";\nMazeArray[0] = \"-X-X-X-XXX-X-X-X-\";\nMazeArray[0] = \"SX---X-----X---X-\";\n" }, { "answer_id": 111210, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "rm -rf " }, { "answer_id": 152501, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "new Thread(() => \n{\n // do stuff in a new thread's context\n})\n{\n Name = \"Thread \" + GetHashCode().ToString(),\n Priority = this.threadPriority\n}\n.Start();\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19970/" ]
111,135
<p>I write my app in VS 2008 and so use all the fanciful stuffs such as LINQ, object initializers etc. Now can my app run on machines that have only .Net 2.0 runtime, but no .Net 3.5 runtime? .Net 3.5 runtime is a huge download, as all of you might know.</p>
[ { "answer_id": 111153, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 4, "selected": true, "text": "namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute { }\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
111,155
<p>How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?</p>
[ { "answer_id": 111160, "author": "Matt Gregory", "author_id": 10577, "author_profile": "https://Stackoverflow.com/users/10577", "pm_score": 8, "selected": false, "text": "WM_DELETE_WINDOW protocol Tk Toplevel import tkinter as tk\nfrom tkinter import messagebox\n\nroot = tk.Tk()\n\ndef on_closing():\n if messagebox.askokcancel(\"Quit\", \"Do you want to quit?\"):\n root.destroy()\n\nroot.protocol(\"WM_DELETE_WINDOW\", on_closing)\nroot.mainloop()\n" }, { "answer_id": 14819661, "author": "Honest Abe", "author_id": 1217270, "author_profile": "https://Stackoverflow.com/users/1217270", "pm_score": 5, "selected": false, "text": "# Python 3\nimport tkinter\nimport tkinter.scrolledtext as scrolledtext\n\nroot = tkinter.Tk()\n# make the top right close button minimize (iconify) the main window\nroot.protocol(\"WM_DELETE_WINDOW\", root.iconify)\n# make Esc exit the program\nroot.bind('<Escape>', lambda e: root.destroy())\n\n# create a menu bar with an Exit command\nmenubar = tkinter.Menu(root)\nfilemenu = tkinter.Menu(menubar, tearoff=0)\nfilemenu.add_command(label=\"Exit\", command=root.destroy)\nmenubar.add_cascade(label=\"File\", menu=filemenu)\nroot.config(menu=menubar)\n\n# create a Text widget with a Scrollbar attached\ntxt = scrolledtext.ScrolledText(root, undo=True)\ntxt['font'] = ('consolas', '12')\ntxt.pack(expand=True, fill='both')\n\nroot.mainloop()\n" }, { "answer_id": 49803010, "author": "Apostolos", "author_id": 5615873, "author_profile": "https://Stackoverflow.com/users/5615873", "pm_score": 4, "selected": false, "text": "destroy() from Tkinter import *\n\ndef close_window():\n global running\n running = False # turn off while loop\n print( \"Window closed\")\n\nroot = Tk()\nroot.protocol(\"WM_DELETE_WINDOW\", close_window)\ncv = Canvas(root, width=200, height=200)\ncv.pack()\n\nrunning = True;\n# This is an endless loop stopped only by setting 'running' to 'False'\nwhile running: \n for i in range(200): \n if not running: \n break\n cv.create_oval(i, i, i+1, i+1)\n root.update() \n running" }, { "answer_id": 56730063, "author": "SF12 Study", "author_id": 11152082, "author_profile": "https://Stackoverflow.com/users/11152082", "pm_score": 0, "selected": false, "text": "import tkinter\n\nwindow = Tk()\n\nclosebutton = Button(window, text='X', command=window.destroy)\nclosebutton.pack()\n\nwindow.mainloop()\n\n import tkinter\n\nwindow = Tk()\n\n\ndef close():\n window.destroy()\n #More Functions\n\n\nclosebutton = Button(window, text='X', command=close)\nclosebutton.pack()\n\nwindow.mainloop()\n" }, { "answer_id": 58469034, "author": "Mitch McMabers", "author_id": 8874388, "author_profile": "https://Stackoverflow.com/users/8874388", "pm_score": 3, "selected": false, "text": "destroy() tkinter.after from tkinter import *\nimport time\n\n# Try setting this to False and look at the printed numbers (1 to 10)\n# during the work-loop, if you close the window while the periodic_call\n# worker is busy working (printing). It will abruptly end the numbers,\n# and kill the periodic callback! That's why you should design most\n# applications with a safe closing callback as described in this demo.\nsafe_closing = True\n\n# ---------\n\nbusy_processing = False\nclose_requested = False\n\ndef close_window():\n global close_requested\n close_requested = True\n print(\"User requested close at:\", time.time(), \"Was busy processing:\", busy_processing)\n\nroot = Tk()\nif safe_closing:\n root.protocol(\"WM_DELETE_WINDOW\", close_window)\nlbl = Label(root)\nlbl.pack()\n\ndef periodic_call():\n global busy_processing\n\n if not close_requested:\n busy_processing = True\n for i in range(10):\n print((i+1), \"of 10\")\n time.sleep(0.2)\n lbl[\"text\"] = str(time.time()) # Will error if force-closed.\n root.update() # Force redrawing since we change label multiple times in a row.\n busy_processing = False\n root.after(500, periodic_call)\n else:\n print(\"Destroying GUI at:\", time.time())\n try: # \"destroy()\" can throw, so you should wrap it like this.\n root.destroy()\n except:\n # NOTE: In most code, you'll wanna force a close here via\n # \"exit\" if the window failed to destroy. Just ensure that\n # you have no code after your `mainloop()` call (at the\n # bottom of this file), since the exit call will cause the\n # process to terminate immediately without running any more\n # code. Of course, you should NEVER have code after your\n # `mainloop()` call in well-designed code anyway...\n # exit(0)\n pass\n\nroot.after_idle(periodic_call)\nroot.mainloop()\n WM_DELETE_WINDOW periodic_call() .after() WM_DELETE_WINDOW .after() WM_DELETE_WINDOW .destroy() WM_DELETE_WINDOW WM_DELETE_WINDOW" }, { "answer_id": 64890879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "break import tkinter as tk\nwin=tk.Tk\ndef exit():\n break\nbtn= tk.Button(win, text=\"press to exit\", command=exit)\nwin.mainloop()\n sys.exit() import tkinter as tk\nimport sys\nwin=tk.Tk\ndef exit():\n sys.exit\nbtn= tk.Button(win, text=\"press to exit\", command=exit)\nwin.mainloop()\n" }, { "answer_id": 65171949, "author": "Nah", "author_id": 13604316, "author_profile": "https://Stackoverflow.com/users/13604316", "pm_score": 4, "selected": false, "text": "yourwindow.protocol(\"WM_DELETE_WINDOW\", whatever)\n def whatever():\n # Replace this with your own event for example:\n print(\"oi don't press that button\")\n yourwindow.withdraw() \n yourwindow.deiconify()\n" }, { "answer_id": 65713080, "author": "NISHANT MISHRA", "author_id": 14708788, "author_profile": "https://Stackoverflow.com/users/14708788", "pm_score": 1, "selected": false, "text": " from Tkinter import *\n root = Tk()\n Button(root, text=\"Quit\", command=root.destroy).pack()\n root.mainloop()\n root.quit() root.mainloop() root.mainloop() quit() root.destroy() destroy() root.mainloop() root.mainloop() root.destroy() root.mainloop() root.quit() from Tkinter import *\ndef quit():\n global root\n root.quit()\n\nroot = Tk()\nwhile True:\n Button(root, text=\"Quit\", command=quit).pack()\n root.mainloop()\n #do something\n" }, { "answer_id": 69030155, "author": "Yangelixx", "author_id": 15254308, "author_profile": "https://Stackoverflow.com/users/15254308", "pm_score": 1, "selected": false, "text": "from tkinter import *\nwindow = Tk()\n window.withdraw() window.deiconify() exit() from tkinter import *\nimport sys\nwindow = Tk()\nsys.exit()\n" }, { "answer_id": 71549519, "author": "Sytze", "author_id": 18514044, "author_profile": "https://Stackoverflow.com/users/18514044", "pm_score": 0, "selected": false, "text": "root = Tk()\ndef func():\n print('not clossed')\nroot.protocol('wm_delete_window', func)\nroot.mainloop()\n" }, { "answer_id": 74022858, "author": "hahaly", "author_id": 20019148, "author_profile": "https://Stackoverflow.com/users/20019148", "pm_score": 0, "selected": false, "text": "def on_closing():\n if messagebox.askokcancel(\"Quit\", \"would you like to quit\"):\n window.destroy()\n\n\nwindow.protocol(\"WM_DELETE_WINDOW\", on_closing)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
111,194
<p>I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.</p> <p>The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.</p> <p>The client (a C# web app), reads the data:</p> <pre><code> private NetworkStream stream_; public void WriteDocument(HttpResponse response) { while (stream_.DataAvailable) { const int bufsize = 4 * 1024; byte[] buffer = new byte[bufsize]; int nbytes = stream_.Read(buffer, 0, bufsize); if (nbytes &gt; 0) { if (nbytes &lt; bufsize) Array.Resize&lt;byte&gt;(ref buffer, nbytes); response.BinaryWrite(buffer); } } response.End(); } </code></pre> <p>This seems to always exit the read loop before all the data has arrived. What am I doing wrong?</p>
[ { "answer_id": 111212, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": " public static byte[] doFetchBinaryUrl(string url)\n {\n BinaryReader rdr;\n HttpWebResponse res;\n try\n {\n res = fetch(url);\n rdr = new BinaryReader(res.GetResponseStream());\n }\n catch (NullReferenceException nre)\n {\n return new byte[] { };\n }\n int len = int.Parse(res.GetResponseHeader(\"Content-Length\"));\n byte[] rv = new byte[len];\n for (int i = 0; i < len - 1; i++)\n {\n rv[i] = rdr.ReadByte();\n }\n res.Close();\n return rv;\n }\n" }, { "answer_id": 111221, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "OutputStream Stream Flush public void WriteDocument(HttpResponse response) {\n StreamCopy(response.OutputStream, stream_);\n response.End();\n }\n\n public static void StreamCopy(Stream dest, Stream src) {\n byte[] buffer = new byte[4 * 1024];\n int n = 1;\n while (n > 0) {\n n = src.Read(buffer, 0, buffer.Length);\n dest.Write(buffer, 0, n);\n }\n dest.Flush();\n }\n" }, { "answer_id": 249848, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 1, "selected": false, "text": "while (stream_.DataAvailable)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
111,234
<p>Now that it's clear <a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">what a metaclass is</a>, there is an associated concept that I use all the time without knowing what it really means. </p> <p>I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using <code>__init__</code> and <code>__new__</code> lead to wonder what this bloody <code>__call__</code> can be used for.</p> <p>Could you give me some explanations, including examples with the magic method ?</p>
[ { "answer_id": 111251, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "__call__ [nigel@k9 ~]$ python\nPython 2.5 (r25:51908, Nov 6 2007, 15:55:44) \n[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 'aaa'() # <== Here we attempt to call a string.\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'str' object is not callable\n>>> \n" }, { "answer_id": 111255, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 9, "selected": true, "text": "__call__ __call__ class Foo:\n def __call__(self):\n print 'called'\n\nfoo_instance = Foo()\nfoo_instance() #this is calling the __call__ method\n" }, { "answer_id": 111267, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 3, "selected": false, "text": "__call__ class Adder(object):\n def __init__(self, val):\n self.val = val\n\n def __call__(self, val):\n return self.val + val\n\nfunc = Adder(5)\nprint func(3)\n" }, { "answer_id": 111371, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "__call__ >>> class Foo:\n... pass\n... \n>>> class Bar(object):\n... pass\n... \n>>> type(Foo).__call__(Foo)\n<__main__.Foo instance at 0x711440>\n>>> type(Bar).__call__(Bar)\n<__main__.Bar object at 0x712110>\n>>> def foo(bar):\n... return bar\n... \n>>> type(foo).__call__(foo, 42)\n42\n >>> class Foo(object):\n... def __call__(self):\n... return 42\n... \n>>> f = Foo()\n>>> f()\n42\n" }, { "answer_id": 115349, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 7, "selected": false, "text": "/* Test whether an object can be called */\n\nint\nPyCallable_Check(PyObject *x)\n{\n if (x == NULL)\n return 0;\n if (PyInstance_Check(x)) {\n PyObject *call = PyObject_GetAttrString(x, \"__call__\");\n if (call == NULL) {\n PyErr_Clear();\n return 0;\n }\n /* Could test recursively but don't, for fear of endless\n recursion if some joker sets self.__call__ = self */\n Py_DECREF(call);\n return 1;\n }\n else {\n return x->ob_type->tp_call != NULL;\n }\n}\n __call__ x x->ob_type->tp_call != NULL tp_call ternaryfunc tp_call callable TypeError callable callable = lambda o: hasattr(o, '__call__') isinstance(o, collections.Callable) class Cached:\n def __init__(self, function):\n self.function = function\n self.cache = {}\n\n def __call__(self, *args):\n try: return self.cache[args]\n except KeyError:\n ret = self.cache[args] = self.function(*args)\n return ret \n @Cached\ndef ack(x, y):\n return ack(x-1, ack(x, y-1)) if x*y else (x + y + 1) \n site.py exit() quit() class Quitter(object):\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return 'Use %s() or %s to exit' % (self.name, eof)\n def __call__(self, code=None):\n # Shells like IDLE catch the SystemExit, but listen when their\n # stdin wrapper is closed.\n try:\n sys.stdin.close()\n except:\n pass\n raise SystemExit(code)\n__builtin__.quit = Quitter('quit')\n__builtin__.exit = Quitter('exit')\n" }, { "answer_id": 139469, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 5, "selected": false, "text": "class a(object):\n def __call__(self, *args):\n print 'Hello'\n\nfunc = a()\n\n# or ... \ndef func(*args):\n print 'Hello'\n" }, { "answer_id": 10489545, "author": "cobie", "author_id": 634135, "author_profile": "https://Stackoverflow.com/users/634135", "pm_score": 2, "selected": false, "text": "__call__" }, { "answer_id": 15581536, "author": "hcalves", "author_id": 128942, "author_profile": "https://Stackoverflow.com/users/128942", "pm_score": 5, "selected": false, "text": "foo()\n foo.__call__()\n foo __call__ int('10')\nunicode(10)\n int.__call__('10')\nunicode.__call__(10)\n foo = new int __call__" }, { "answer_id": 39591208, "author": "Ravi Singh", "author_id": 6733259, "author_profile": "https://Stackoverflow.com/users/6733259", "pm_score": 2, "selected": false, "text": "Class A:\n def __init__(self,val):\n self.val = val\n def bar(self):\n print \"bar\"\n\nobj = A() \ncallable(obj.bar)\nTrue\ncallable(obj.__init___)\nFalse\ndef foo(): return \"s\"\ncallable(foo)\nTrue\ncallable(foo())\nFalse\n" }, { "answer_id": 43271804, "author": "maris", "author_id": 3853452, "author_profile": "https://Stackoverflow.com/users/3853452", "pm_score": 0, "selected": false, "text": ">>> type(callable)\n<class 'builtin_function_or_method'>\n>>>\n >>> type(print)\n<class 'builtin_function_or_method'>\n>>> print.__call__(10)\n10\n>>> print(10)\n10\n>>>\n" }, { "answer_id": 74549262, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "__call__() True False class Class1:\n def __call__(self):\n print(\"__call__\")\n\nclass Class2:\n pass\n\ndef func():\n pass\n\nprint(callable(Class1)) # Class1\nprint(callable(Class2)) # Class2\n\nprint(callable(Class1())) # Class1 object\nprint(callable(Class2())) # Class2 object\n\nprint(callable(func)) # func\n Class2 __call__() False True # Class1\nTrue # Class2\nTrue # Class1 object\nFalse # Class2 object\nTrue # func\n False print(callable(\"Hello\")) # \"str\" type\nprint(callable(100)) # \"int\" type\nprint(callable(100.23)) # \"float\" type\nprint(callable(100 + 2j)) # \"complex\" type\nprint(callable(True)) # \"bool\" type\nprint(callable(None)) # \"NoneType\"\nprint(callable([])) # \"list\" type\nprint(callable(())) # \"tuple\" type\nprint(callable({})) # \"dict\" type\nprint(callable({\"\"})) # \"set\" type\n False # \"str\" type\nFalse # \"int\" type\nFalse # \"float\" type\nFalse # \"complex\" type\nFalse # \"bool\" type\nFalse # \"NoneType\"\nFalse # \"list\" type\nFalse # \"tuple\" type\nFalse # \"dict\" type\nFalse # \"set\" type\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
111,282
<p>I'm modifying some code in which the original author built a web page by using an array thusly:</p> <pre><code> $output[]=$stuff_from_database; $output[]='more stuff'; // etc echo join('',$output); </code></pre> <p>Can anyone think of a reason why this would be preferable (or vice versa) to:</p> <pre><code> $output =$stuff_from_database; $output .='more stuff'; // etc echo $output; </code></pre>
[ { "answer_id": 111310, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "~$ cat join.php\n<?php\n\nfor ($i=0;$i<50000;$i++) {\n$output[] = \"HI $i\\n\";\n}\n\necho join('',$output);\n?>\n\n\n~$ time for i in `seq 100`; do php join.php >> outjoin ; done\n\nreal 0m19.145s\nuser 0m12.045s\nsys 0m3.216s\n\n~$ cat dot.php\n<?php\n\nfor ($i=0;$i<50000;$i++) {\n$output.= \"HI $i\\n\";\n}\n\necho $output;\n?>\n\n\n~$ time for i in `seq 100`; do php dot.php >> outdot ; done\n\nreal 0m15.530s\nuser 0m8.985s\nsys 0m2.260s\n" }, { "answer_id": 111325, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 0, "selected": false, "text": "implode() join() free() malloc()" }, { "answer_id": 111624, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 2, "selected": false, "text": "$output =$stuff_from_database;\n$output .='more stuff';\n// etc\necho $output;\n echo = $stuff_from_database;\necho 'more stuff';\n ob_start();\necho = $stuff_from_database;\necho 'more stuff';\n$output = ob_get_contents();\nob_end_clean();\n" }, { "answer_id": 115145, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 1, "selected": false, "text": "echo $stuff_from_database\n , 'more stuff'\n , 'yet more'\n // etc\n , 'last stuff';\n" }, { "answer_id": 125004, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 0, "selected": false, "text": "for ($prod in $cart)\n{\n $prod->printHTML();\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
111,285
<p>I am currently using an MSAccess mdb file for a redistributable app. </p> <p>A while ago I found out about SQLite, as an alternative to my solution, but the binaries they provide do not offer the possiblilty of using them as an object in VB6. (Or at least I couldn't figure it out how).</p> <p>Does anyone has a link, or could write a little about connecting to a SQLite DB from VB6, and its differences with using ADO?</p>
[ { "answer_id": 48403155, "author": "StayOnTarget", "author_id": 3195477, "author_profile": "https://Stackoverflow.com/users/3195477", "pm_score": 0, "selected": false, "text": "sqlite.dll Declare Sub Declare Function Public Declare Sub sqlite3_open Lib \"sqlite.dll\" (ByVal FileName As String, ByRef handle As Long)\nPublic Declare Sub sqlite3_close Lib \"sqlite.dll\" (ByVal DB_Handle As Long)\nPublic Declare Function sqlite3_last_insert_rowid Lib \"sqlite.dll\" (ByVal DB_Handle As Long) As Long\nPublic Declare Function sqlite3_changes Lib \"sqlite.dll\" (ByVal DB_Handle As Long) As Long\nPublic Declare Function sqlite_get_table Lib \"sqlite.dll\" (ByVal DB_Handle As Long, ByVal SQLString As String, ByRef ErrStr As String) As Variant()\nPublic Declare Function sqlite_libversion Lib \"sqlite.dll\" () As String\nPublic Declare Function number_of_rows_from_last_call Lib \"sqlite.dll\" () As Long\n...\nquery = \"SELECT * FROM users\"\n\nrow = sqlite_get_table(DBz, query, minfo)\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4749/" ]
111,287
<p>Is it possible to put the results from more than one query on more than one table into a TClientDataset?</p> <p>Just something like</p> <pre><code>SELECT * from t1; SELECT * from t2; SELECT * from t3; </code></pre> <p>I can't seem to figure out a way to get a data provider (SetProvider) to pull in results from more than one table at a time.</p>
[ { "answer_id": 111324, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "select * from t1, t2, t3 where t1.key = t2.key and t2.key = t3.key;\n" }, { "answer_id": 112219, "author": "Nick Hodges", "author_id": 2044, "author_profile": "https://Stackoverflow.com/users/2044", "pm_score": 4, "selected": false, "text": "ClientDatasets ClientDatasets ClientDataSet ClientDataSet's TFields" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19658/" ]
111,294
<p>What are some resources in use for marketing downloadable desktop software online? AdWords, certainly, and "organic" search engine results but is anyone having any luck making sales through sites like Tucows and/or Download.com anymorE?</p>
[ { "answer_id": 111324, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "select * from t1, t2, t3 where t1.key = t2.key and t2.key = t3.key;\n" }, { "answer_id": 112219, "author": "Nick Hodges", "author_id": 2044, "author_profile": "https://Stackoverflow.com/users/2044", "pm_score": 4, "selected": false, "text": "ClientDatasets ClientDatasets ClientDataSet ClientDataSet's TFields" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19658/" ]
111,302
<p>I have a webservice that when called without specifying a callback will return a JSON string using <code>application/json</code> as the content type.</p> <p>When a callback is specified it will wrap the JSON string in a callback function, so it's not really valid JSON anymore. My question is, should I serve it as <code>application/javascript</code> in this case or still use <code>application/json</code>?</p>
[ { "answer_id": 111319, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 7, "selected": false, "text": "application/json application/javascript" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9128/" ]
111,307
<p>The question of whether P=NP is perhaps the most famous in all of Computer Science. What does it mean? And why is it so interesting?</p> <p>Oh, and for extra credit, please post a proof of the statement's truth or falsehood. :)</p>
[ { "answer_id": 535771, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 3, "selected": false, "text": "n^k k n n log n n^2 k n^k n^k O(n) O(m) O(n^2) P =? NP not ((u_h and not u_l) and (v_h and not v_l) or ...) AND O(n+m) O(1)" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
111,339
<p>From my own "key logger like" process I figured out that another process Locale is wrong (i.e. by sniffing few keys, I figured out that the foreground process Locale should be something while it is set to another). What's the best way to do this?</p>
[ { "answer_id": 111353, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 1, "selected": false, "text": "setlocale()" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
111,341
<p>I've got two tables:</p> <pre><code>TableA ------ ID, Name TableB ------ ID, SomeColumn, TableA_ID (FK for TableA) </code></pre> <p>The relationship is one row of <code>TableA</code> - many of <code>TableB</code>.</p> <p>Now, I want to see a result like this:</p> <pre><code>ID Name SomeColumn 1. ABC X, Y, Z (these are three different rows) 2. MNO R, S </code></pre> <p>This won't work (multiple results in a subquery):</p> <pre><code>SELECT ID, Name, (SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID) FROM TableA </code></pre> <p>This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of <code>TableA</code>. </p> <p>Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of <code>TableA</code>. </p> <p>I'm not sure if a UDF, utilizing COALESCE or something similar might work?</p>
[ { "answer_id": 111356, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 0, "selected": false, "text": "ID Name SomeColumn\n1 ABC X\n1 ABC Y\n1 ABC Z\n2 MNO R\n2 MNO S\n" }, { "answer_id": 111360, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 4, "selected": false, "text": "SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) \nas SomColumnGroup FROM TableA LEFT JOIN TableB ON \nTableB.TableA_ID = TableA.ID\n" }, { "answer_id": 111382, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "SELECT Id, Name From tableA WHERE ...\n\nSELECT tableA.Id AS ParentId, Somecolumn \nFROM tableA INNER JOIN tableB on TableA.Id = TableB.F_Id \nWHERE ...\n ds.Relations.Add(\"foo\", ds.Tables[0].Columns(\"Id\"), ds.Tables[1].Columns(\"ParentId\"));\n <asp:DataList ID=\"Subcategories\" DataKeyField=\"ParentCatId\" \nDataSource='<%# Container.DataItem.CreateChildView(\"foo\") %>' RepeatColumns=\"1\"\n RepeatDirection=\"Horizontal\" ItemStyle-HorizontalAlign=\"left\" ItemStyle-VerticalAlign=\"top\" \nrunat=\"server\" >\n" }, { "answer_id": 111413, "author": "Donnie Thomas", "author_id": 6939, "author_profile": "https://Stackoverflow.com/users/6939", "pm_score": 7, "selected": true, "text": "CREATE FUNCTION CombineValues\n(\n @FK_ID INT -- The foreign key from TableA which is used \n -- to fetch corresponding records\n)\nRETURNS VARCHAR(8000)\nAS\nBEGIN\nDECLARE @SomeColumnList VARCHAR(8000);\n\nSELECT @SomeColumnList =\n COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) \nFROM TableB C\nWHERE C.FK_ID = @FK_ID;\n\nRETURN \n(\n SELECT @SomeColumnList\n)\nEND\n SELECT ID, Name, dbo.CombineValues(FK_ID) FROM TableA\n CREATE PROCEDURE GetCombinedValues\n @FK_ID int\nAs\nBEGIN\nDECLARE @SomeColumnList VARCHAR(800)\nSELECT @SomeColumnList =\n COALESCE(@SomeColumnList + ', ', '') + CAST(SomeColumn AS varchar(20)) \nFROM TableB\nWHERE FK_ID = @FK_ID \n\nSelect *, @SomeColumnList as SelectedIds\n FROM \n TableA\n WHERE \n FK_ID = @FK_ID \nEND\n" }, { "answer_id": 1939718, "author": "ravi", "author_id": 235972, "author_profile": "https://Stackoverflow.com/users/235972", "pm_score": -1, "selected": false, "text": "SELECT GROUP_CONCAT(field_attr_best_weekday_value)as RAVI\nFROM content_field_attr_best_weekday LEFT JOIN content_type_attraction\n on content_field_attr_best_weekday.nid = content_type_attraction.nid\nGROUP BY content_field_attr_best_weekday.nid\n" }, { "answer_id": 1940311, "author": "priyanka.sarkar", "author_id": 111663, "author_profile": "https://Stackoverflow.com/users/111663", "pm_score": 7, "selected": false, "text": "declare @t table(id int, name varchar(20),somecolumn varchar(MAX))\ninsert into @t\n select 1,'ABC','X' union all\n select 1,'ABC','Y' union all\n select 1,'ABC','Z' union all\n select 2,'MNO','R' union all\n select 2,'MNO','S'\n SELECT ID,Name,\n STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))\n FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name\n FOR XML PATH('')),1,1,'') SOMECOLUMN\nFROM @T T1\nGROUP BY id,Name\n ID Name SomeColumn\n1 ABC X,Y,Z\n2 MNO R,S\n" }, { "answer_id": 9277260, "author": "rsda", "author_id": 1209113, "author_profile": "https://Stackoverflow.com/users/1209113", "pm_score": -1, "selected": false, "text": "ID Name SomeColumn\n1. ABC ,X,Y Z (these are three different rows)\n2. MNO ,R,S\n %,X,%" }, { "answer_id": 10400760, "author": "ATHAR", "author_id": 1368148, "author_profile": "https://Stackoverflow.com/users/1368148", "pm_score": -1, "selected": false, "text": "SELECT t.ID, \n t.NAME, \n (SELECT t1.SOMECOLUMN \n FROM TABLEB t1 \n WHERE t1.F_ID = T.TABLEA.ID) \nFROM TABLEA t; \n" }, { "answer_id": 38003777, "author": "mrogunlana", "author_id": 3816706, "author_profile": "https://Stackoverflow.com/users/3816706", "pm_score": 0, "selected": false, "text": "SELECT ID, \n SUBSTRING((\n SELECT ',' + T2.SomeColumn\n FROM @T T2 \n WHERE WHERE T1.id = T2.id\n FOR XML PATH('')), 2, 1000000)\n FROM @T T1\nGROUP BY ID\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939/" ]
111,345
<p>Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):</p> <pre><code>using System; using System.Drawing; namespace Test { class Program { static void Main(string[] args) { Image img = new Bitmap("test.png"); System.Console.WriteLine(img.Width + " x " + img.Height); } } } </code></pre>
[ { "answer_id": 111349, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": false, "text": "System.Windows.Media.Imaging.BitmapDecoder" }, { "answer_id": 112266, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 4, "selected": false, "text": "Type: Bytes 0-2\nVersion: Bytes 3-5\nHeight: Bytes 6-7\nWidth: Bytes 8-9\n Width: Bytes 16-19\nHeight: Bytes 20-23\n using System;\nusing System.IO;\nusing System.Text;\n\npublic class ImageSizeTest\n{\n public static void Main()\n {\n byte[] bytes = new byte[10];\n\n string gifFile = @\"D:\\Personal\\Images&Pics\\iProduct.gif\";\n using (FileStream fs = File.OpenRead(gifFile))\n {\n fs.Read(bytes, 0, 10); // type (3 bytes), version (3 bytes), width (2 bytes), height (2 bytes)\n }\n displayGifInfo(bytes);\n\n string pngFile = @\"D:\\Personal\\Images&Pics\\WaveletsGamma.png\";\n using (FileStream fs = File.OpenRead(pngFile))\n {\n fs.Seek(16, SeekOrigin.Begin); // jump to the 16th byte where width and height information is stored\n fs.Read(bytes, 0, 8); // width (4 bytes), height (4 bytes)\n }\n displayPngInfo(bytes);\n }\n\n public static void displayGifInfo(byte[] bytes)\n {\n string type = Encoding.ASCII.GetString(bytes, 0, 3);\n string version = Encoding.ASCII.GetString(bytes, 3, 3);\n\n int width = bytes[6] | bytes[7] << 8; // byte 6 and 7 contain the width but in network byte order so byte 7 has to be left-shifted 8 places and bit-masked to byte 6\n int height = bytes[8] | bytes[9] << 8; // same for height\n\n Console.WriteLine(\"GIF\\nType: {0}\\nVersion: {1}\\nWidth: {2}\\nHeight: {3}\\n\", type, version, width, height);\n }\n\n public static void displayPngInfo(byte[] bytes)\n {\n int width = 0, height = 0;\n\n for (int i = 0; i <= 3; i++)\n {\n width = bytes[i] | width << 8;\n height = bytes[i + 4] | height << 8; \n }\n\n Console.WriteLine(\"PNG\\nWidth: {0}\\nHeight: {1}\\n\", width, height); \n }\n}\n" }, { "answer_id": 112711, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 8, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\n\nnamespace ImageDimensions\n{\n public static class ImageHelper\n {\n const string errorMessage = \"Could not recognize image format.\";\n\n private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()\n {\n { new byte[]{ 0x42, 0x4D }, DecodeBitmap},\n { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },\n { new byte[]{ 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },\n { new byte[]{ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },\n { new byte[]{ 0xff, 0xd8 }, DecodeJfif },\n };\n\n /// <summary>\n /// Gets the dimensions of an image.\n /// </summary>\n /// <param name=\"path\">The path of the image to get the dimensions of.</param>\n /// <returns>The dimensions of the specified image.</returns>\n /// <exception cref=\"ArgumentException\">The image was of an unrecognized format.</exception>\n public static Size GetDimensions(string path)\n {\n using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)))\n {\n try\n {\n return GetDimensions(binaryReader);\n }\n catch (ArgumentException e)\n {\n if (e.Message.StartsWith(errorMessage))\n {\n throw new ArgumentException(errorMessage, \"path\", e);\n }\n else\n {\n throw e;\n }\n }\n }\n }\n\n /// <summary>\n /// Gets the dimensions of an image.\n /// </summary>\n /// <param name=\"path\">The path of the image to get the dimensions of.</param>\n /// <returns>The dimensions of the specified image.</returns>\n /// <exception cref=\"ArgumentException\">The image was of an unrecognized format.</exception> \n public static Size GetDimensions(BinaryReader binaryReader)\n {\n int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;\n\n byte[] magicBytes = new byte[maxMagicBytesLength];\n\n for (int i = 0; i < maxMagicBytesLength; i += 1)\n {\n magicBytes[i] = binaryReader.ReadByte();\n\n foreach(var kvPair in imageFormatDecoders)\n {\n if (magicBytes.StartsWith(kvPair.Key))\n {\n return kvPair.Value(binaryReader);\n }\n }\n }\n\n throw new ArgumentException(errorMessage, \"binaryReader\");\n }\n\n private static bool StartsWith(this byte[] thisBytes, byte[] thatBytes)\n {\n for(int i = 0; i < thatBytes.Length; i+= 1)\n {\n if (thisBytes[i] != thatBytes[i])\n {\n return false;\n }\n }\n return true;\n }\n\n private static short ReadLittleEndianInt16(this BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(short)];\n for (int i = 0; i < sizeof(short); i += 1)\n {\n bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt16(bytes, 0);\n }\n\n private static int ReadLittleEndianInt32(this BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(int)];\n for (int i = 0; i < sizeof(int); i += 1)\n {\n bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt32(bytes, 0);\n }\n\n private static Size DecodeBitmap(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(16);\n int width = binaryReader.ReadInt32();\n int height = binaryReader.ReadInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeGif(BinaryReader binaryReader)\n {\n int width = binaryReader.ReadInt16();\n int height = binaryReader.ReadInt16();\n return new Size(width, height);\n }\n\n private static Size DecodePng(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(8);\n int width = binaryReader.ReadLittleEndianInt32();\n int height = binaryReader.ReadLittleEndianInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeJfif(BinaryReader binaryReader)\n {\n while (binaryReader.ReadByte() == 0xff)\n {\n byte marker = binaryReader.ReadByte();\n short chunkLength = binaryReader.ReadLittleEndianInt16();\n\n if (marker == 0xc0)\n {\n binaryReader.ReadByte();\n\n int height = binaryReader.ReadLittleEndianInt16();\n int width = binaryReader.ReadLittleEndianInt16();\n return new Size(width, height);\n }\n\n binaryReader.ReadBytes(chunkLength - 2);\n }\n\n throw new ArgumentException(errorMessage);\n }\n }\n}\n imageFormatDecoders" }, { "answer_id": 113323, "author": "Jan Zich", "author_id": 15716, "author_profile": "https://Stackoverflow.com/users/15716", "pm_score": 3, "selected": false, "text": "using System;\nusing System.IO;\n\nnamespace Test\n{\n\n class Program\n {\n\n static bool GetJpegDimension(\n string fileName,\n out int width,\n out int height)\n {\n\n width = height = 0;\n bool found = false;\n bool eof = false;\n\n FileStream stream = new FileStream(\n fileName,\n FileMode.Open,\n FileAccess.Read);\n\n BinaryReader reader = new BinaryReader(stream);\n\n while (!found || eof)\n {\n\n // read 0xFF and the type\n reader.ReadByte();\n byte type = reader.ReadByte();\n\n // get length\n int len = 0;\n switch (type)\n {\n // start and end of the image\n case 0xD8: \n case 0xD9: \n len = 0;\n break;\n\n // restart interval\n case 0xDD: \n len = 2;\n break;\n\n // the next two bytes is the length\n default: \n int lenHi = reader.ReadByte();\n int lenLo = reader.ReadByte();\n len = (lenHi << 8 | lenLo) - 2;\n break;\n }\n\n // EOF?\n if (type == 0xD9)\n eof = true;\n\n // process the data\n if (len > 0)\n {\n\n // read the data\n byte[] data = reader.ReadBytes(len);\n\n // this is what we are looking for\n if (type == 0xC0)\n {\n width = data[1] << 8 | data[2];\n height = data[3] << 8 | data[4];\n found = true;\n }\n\n }\n\n }\n\n reader.Close();\n stream.Close();\n\n return found;\n\n }\n\n static void Main(string[] args)\n {\n foreach (string file in Directory.GetFiles(args[0]))\n {\n int w, h;\n GetJpegDimension(file, out w, out h);\n System.Console.WriteLine(file + \": \" + w + \" x \" + h);\n }\n }\n\n }\n}\n" }, { "answer_id": 9687096, "author": "Koray", "author_id": 1266873, "author_profile": "https://Stackoverflow.com/users/1266873", "pm_score": 5, "selected": false, "text": "using (FileStream file = new FileStream(this.ImageFileName, FileMode.Open, FileAccess.Read))\n{\n using (Image tif = Image.FromStream(stream: file, \n useEmbeddedColorManagement: false,\n validateImageData: false))\n {\n float width = tif.PhysicalDimension.Width;\n float height = tif.PhysicalDimension.Height;\n float hresolution = tif.HorizontalResolution;\n float vresolution = tif.VerticalResolution;\n }\n}\n validateImageData false" }, { "answer_id": 13073341, "author": "Danny D", "author_id": 557516, "author_profile": "https://Stackoverflow.com/users/557516", "pm_score": 2, "selected": false, "text": " var buff = new byte[32];\n using (var d = File.OpenRead(file))\n { \n d.Read(buff, 0, 32);\n }\n const int wOff = 16;\n const int hOff = 20; \n var Widht =BitConverter.ToInt32(new[] {buff[wOff + 3], buff[wOff + 2], buff[wOff + 1], buff[wOff + 0],},0);\n var Height =BitConverter.ToInt32(new[] {buff[hOff + 3], buff[hOff + 2], buff[hOff + 1], buff[hOff + 0],},0);\n" }, { "answer_id": 60667939, "author": "bang", "author_id": 611084, "author_profile": "https://Stackoverflow.com/users/611084", "pm_score": 3, "selected": false, "text": "internal static class ImageHelper\n{\n const string errorMessage = \"Could not recognise image format.\";\n\n private static Dictionary<byte[], Func<BinaryReader, Size>> imageFormatDecoders = new Dictionary<byte[], Func<BinaryReader, Size>>()\n {\n { new byte[] { 0x42, 0x4D }, DecodeBitmap },\n { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }, DecodeGif },\n { new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }, DecodeGif },\n { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng },\n { new byte[] { 0xff, 0xd8 }, DecodeJfif },\n { new byte[] { 0x52, 0x49, 0x46, 0x46 }, DecodeWebP },\n };\n\n /// <summary> \n /// Gets the dimensions of an image. \n /// </summary> \n /// <param name=\"path\">The path of the image to get the dimensions of.</param> \n /// <returns>The dimensions of the specified image.</returns> \n /// <exception cref=\"ArgumentException\">The image was of an unrecognised format.</exception> \n public static Size GetDimensions(BinaryReader binaryReader)\n {\n int maxMagicBytesLength = imageFormatDecoders.Keys.OrderByDescending(x => x.Length).First().Length;\n byte[] magicBytes = new byte[maxMagicBytesLength];\n for(int i = 0; i < maxMagicBytesLength; i += 1)\n {\n magicBytes[i] = binaryReader.ReadByte();\n foreach(var kvPair in imageFormatDecoders)\n {\n if(StartsWith(magicBytes, kvPair.Key))\n {\n return kvPair.Value(binaryReader);\n }\n }\n }\n\n throw new ArgumentException(errorMessage, \"binaryReader\");\n }\n\n private static bool StartsWith(byte[] thisBytes, byte[] thatBytes)\n {\n for(int i = 0; i < thatBytes.Length; i += 1)\n {\n if(thisBytes[i] != thatBytes[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n private static short ReadLittleEndianInt16(BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(short)];\n\n for(int i = 0; i < sizeof(short); i += 1)\n {\n bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt16(bytes, 0);\n }\n\n private static int ReadLittleEndianInt32(BinaryReader binaryReader)\n {\n byte[] bytes = new byte[sizeof(int)];\n for(int i = 0; i < sizeof(int); i += 1)\n {\n bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte();\n }\n return BitConverter.ToInt32(bytes, 0);\n }\n\n private static Size DecodeBitmap(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(16);\n int width = binaryReader.ReadInt32();\n int height = binaryReader.ReadInt32();\n return new Size(width, height);\n }\n\n private static Size DecodeGif(BinaryReader binaryReader)\n {\n int width = binaryReader.ReadInt16();\n int height = binaryReader.ReadInt16();\n return new Size(width, height);\n }\n\n private static Size DecodePng(BinaryReader binaryReader)\n {\n binaryReader.ReadBytes(8);\n int width = ReadLittleEndianInt32(binaryReader);\n int height = ReadLittleEndianInt32(binaryReader);\n return new Size(width, height);\n }\n\n private static Size DecodeJfif(BinaryReader binaryReader)\n {\n while(binaryReader.ReadByte() == 0xff)\n {\n byte marker = binaryReader.ReadByte();\n short chunkLength = ReadLittleEndianInt16(binaryReader);\n if(marker == 0xc0 || marker == 0xc2) // c2: progressive\n {\n binaryReader.ReadByte();\n int height = ReadLittleEndianInt16(binaryReader);\n int width = ReadLittleEndianInt16(binaryReader);\n return new Size(width, height);\n }\n\n if(chunkLength < 0)\n {\n ushort uchunkLength = (ushort)chunkLength;\n binaryReader.ReadBytes(uchunkLength - 2);\n }\n else\n {\n binaryReader.ReadBytes(chunkLength - 2);\n }\n }\n\n throw new ArgumentException(errorMessage);\n }\n\n private static Size DecodeWebP(BinaryReader binaryReader)\n {\n binaryReader.ReadUInt32(); // Size\n binaryReader.ReadBytes(15); // WEBP, VP8 + more\n binaryReader.ReadBytes(3); // SYNC\n\n var width = binaryReader.ReadUInt16() & 0b00_11111111111111; // 14 bits width\n var height = binaryReader.ReadUInt16() & 0b00_11111111111111; // 14 bits height\n\n return new Size(width, height);\n }\n\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15716/" ]
111,368
<p>CPU Cycles, Memory Usage, Execution Time, etc.?</p> <p>Added: Is there a quantitative way of testing performance in JavaScript besides just perception of how fast the code runs?</p>
[ { "answer_id": 111729, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 9, "selected": false, "text": "console.time() console.profile() performance.now()" }, { "answer_id": 2550811, "author": "pramodc84", "author_id": 40614, "author_profile": "https://Stackoverflow.com/users/40614", "pm_score": 7, "selected": false, "text": "var start = +new Date(); // log start timestamp\nfunction1();\nvar end = +new Date(); // log end timestamp\nvar diff = end - start;\n" }, { "answer_id": 4188925, "author": "Ramiz Uddin", "author_id": 134743, "author_profile": "https://Stackoverflow.com/users/134743", "pm_score": 5, "selected": false, "text": "function expression function constructor <script src=\"JSLitmus.js\"></script>\n<script>\n\nJSLitmus.test(\"new Function ... \", function() { \n return new Function(\"for(var i=0; i<100; i++) {}\"); \n});\n\nJSLitmus.test(\"function() ...\", function() { \n return (function() { for(var i=0; i<100; i++) {} });\n});\n\n</script>\n function expression function constructor" }, { "answer_id": 10669341, "author": "Bunz", "author_id": 221435, "author_profile": "https://Stackoverflow.com/users/221435", "pm_score": 4, "selected": false, "text": "var perf = function(testName, fn) {\n var startTime = new Date().getTime();\n fn();\n var endTime = new Date().getTime();\n console.log(testName + \": \" + (endTime - startTime) + \"ms\");\n}\n" }, { "answer_id": 17943511, "author": "Jose Browne", "author_id": 831738, "author_profile": "https://Stackoverflow.com/users/831738", "pm_score": 8, "selected": false, "text": "console.time() console.timeEnd() var iterations = 1000000;\nconsole.time('Function #1');\nfor(var i = 0; i < iterations; i++ ){\n functionOne();\n};\nconsole.timeEnd('Function #1')\n\nconsole.time('Function #2');\nfor(var i = 0; i < iterations; i++ ){\n functionTwo();\n};\nconsole.timeEnd('Function #2')\n" }, { "answer_id": 19260977, "author": "user2601995", "author_id": 2601995, "author_profile": "https://Stackoverflow.com/users/2601995", "pm_score": -1, "selected": false, "text": "start = new Date().getTime(); \nfor (var n = 0; n < maxCount; n++) {\n/* perform the operation to be measured *//\n}\nelapsed = new Date().getTime() - start;\nassert(true,\"Measured time: \" + elapsed);\n" }, { "answer_id": 24834846, "author": "Daniel Imms", "author_id": 1156119, "author_profile": "https://Stackoverflow.com/users/1156119", "pm_score": 5, "selected": false, "text": "performance.now() new Date() var start = performance.now();\n\n// code being timed...\n\nvar duration = performance.now() - start;\n" }, { "answer_id": 34753110, "author": "Shawn Dotey", "author_id": 2040763, "author_profile": "https://Stackoverflow.com/users/2040763", "pm_score": 2, "selected": false, "text": "/*\n Help track time lapse - tells you the time difference between each \"check()\" and since the \"start()\"\n\n */\nvar TimeCapture = function () {\n var start = new Date().getTime();\n var last = start;\n var now = start;\n this.start = function () {\n start = new Date().getTime();\n };\n this.check = function (message) {\n now = (new Date().getTime());\n console.log(message, 'START:', now - start, 'LAST:', now - last);\n last = now;\n };\n};\n\n//Example:\nvar time = new TimeCapture();\n//begin tracking time\ntime.start();\n//...do stuff\ntime.check('say something here')//look at your console for output\n//..do more stuff\ntime.check('say something else')//look at your console for output\n//..do more stuff\ntime.check('say something else one more time')//look at your console for output\n" }, { "answer_id": 65197582, "author": " Юрий Светлов", "author_id": 5790663, "author_profile": "https://Stackoverflow.com/users/5790663", "pm_score": 3, "selected": false, "text": "performance.mark('initSelect - start');\ninitSelect();\nperformance.mark('initSelect - end');\n" }, { "answer_id": 74484360, "author": "Teocci", "author_id": 5372008, "author_profile": "https://Stackoverflow.com/users/5372008", "pm_score": 0, "selected": false, "text": "performance.now() /**\n * Figure out how long it takes for a method to execute.\n * \n * @param {Function} method to test \n * @param {number} iterations number of executions.\n * @param {Array} list of set of args to pass in. \n * @param {T} context the context to call the method in.\n * @return {number} the time it took, in milliseconds to execute.\n */\nconst bench = (method, list, iterations, context) => {\n let start = 0\n const timer = action => {\n const time = performance.now()\n switch (action) {\n case 'start':\n start = time\n return 0\n case 'stop':\n const elapsed = time - start\n start = 0\n return elapsed\n default:\n return time - start\n }\n };\n\n const result = []\n timer('start')\n list = [...list]\n for (let i = 0; i < iterations; i++) {\n for (const args of list) {\n result.push(method.apply(context, args))\n }\n }\n const elapsed = timer('stop')\n \n console.log(`Called method [${method.name}]\n Mean: ${elapsed / iterations}\n Exec. time: ${elapsed}`)\n\n\n return elapsed\n}\n\nconst fnc = () => {}\nconst isFunction = (f) => f && f instanceof Function\nconst isFunctionFaster = (f) => f && 'function' === typeof f\n\n\nclass A {}\n\nfunction basicFnc(){}\nasync function asyncFnc(){}\n\nconst arrowFnc = ()=> {}\nconst arrowRFnc = ()=> 1\n\n// Not functions\nconst obj = {}\nconst arr = []\nconst str = 'function'\nconst bol = true\nconst num = 1\nconst a = new A()\n\nconst list = [\n [isFunction],\n [basicFnc],\n [arrowFnc],\n [arrowRFnc],\n [asyncFnc],\n [Array],\n [Date],\n [Object],\n [Number],\n [String],\n [Symbol],\n [A],\n [obj],\n [arr],\n [str],\n [bol],\n [num],\n [a],\n [null],\n [undefined],\n]\n\n\nconst e1 = bench(isFunction, list, 10000)\nconst e2 = bench(isFunctionFaster, list, 10000)\n\nconst rate = e2/e1\nconst percent = Math.abs(1 - rate)*100\n\nconsole.log(`[isFunctionFaster] is ${(percent).toFixed(2)}% ${rate < 1 ? 'faster' : 'slower'} than [isFunction]`)" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
111,405
<p>I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.</p> <p>Thanks in advance, Yet another LaTeX user</p>
[ { "answer_id": 111506, "author": "finrod", "author_id": 8295, "author_profile": "https://Stackoverflow.com/users/8295", "pm_score": 2, "selected": true, "text": "%in the document preamble\n\\usepackage{graphicx}\n\n%in the document, in the place where you want to put your image\n\\includegraphics{image_filename_without_extension}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11464/" ]
111,407
<p>I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect. Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.</p> <p>Does anyone know of a fix for this?</p> <p>Thanks!</p>
[ { "answer_id": 111409, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n // Fix background image caching problem\n if (jQuery.browser.msie) {\n try { \n document.execCommand(\"BackgroundImageCache\", false, true); \n } catch(err) {}\n }\n};\n" }, { "answer_id": 1157294, "author": "Mike Gardiner", "author_id": 126663, "author_profile": "https://Stackoverflow.com/users/126663", "pm_score": 6, "selected": true, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\"http://www.w3.org/TR/html4/loose.dtd\">\n" }, { "answer_id": 2374174, "author": "sergiopereira", "author_id": 21420, "author_profile": "https://Stackoverflow.com/users/21420", "pm_score": 2, "selected": false, "text": "//Start the slideUp effect lasting 500ms\n$('#element').slideUp(500);\n\n//Abort the effect just before it finishes and force hide()\n//I had to play with the timeout interval until I found one that\n// looked exactly right. 400ms worked for me.\nsetTimeout(function() {\n $('#element').stop(true, true).hide(); \n}, 400);\n" }, { "answer_id": 3894024, "author": "Benxamin", "author_id": 218119, "author_profile": "https://Stackoverflow.com/users/218119", "pm_score": 1, "selected": false, "text": "UL > LI*2 > A" }, { "answer_id": 4012505, "author": "ghusse", "author_id": 380086, "author_profile": "https://Stackoverflow.com/users/380086", "pm_score": 2, "selected": false, "text": "$(\"#element\").animate({\n height: 1, // Avoiding sliding to 0px (flash on IE)\n paddingTop: \"hide\",\n paddingBottom: \"hide\"\n })\n // Then hide\n .animate({display:\"hide\"},{queue:true});\n" }, { "answer_id": 5106027, "author": "Kees C. Bakker", "author_id": 201482, "author_profile": "https://Stackoverflow.com/users/201482", "pm_score": 1, "selected": false, "text": "var pane = $('.ColorPane');\nvar speed = 500;\nwindow.setTimeout(function() { pane.css('display', 'none'); }, speed - 100);\npane.slideUp(speed);\n" }, { "answer_id": 7899887, "author": "saeraphin", "author_id": 1014105, "author_profile": "https://Stackoverflow.com/users/1014105", "pm_score": 2, "selected": false, "text": "$(\".slider\").click(function (e) {\n $(this).animate({\"height\" : \"1px\"});\n});\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
111,417
<p>What’s the difference between <code>Response.Write()</code> and <code>Response.Output.Write()</code>? </p>
[ { "answer_id": 111425, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 0, "selected": false, "text": "Response.Write Response.Output" }, { "answer_id": 111429, "author": "Dexter", "author_id": 10717, "author_profile": "https://Stackoverflow.com/users/10717", "pm_score": 2, "selected": false, "text": "Response.Output.Write()" }, { "answer_id": 111450, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 2, "selected": false, "text": "TextWriter HttpContext.Response.Output.Write HttpContext.Response.Write HttpResponse" }, { "answer_id": 53736522, "author": "avi", "author_id": 10734886, "author_profile": "https://Stackoverflow.com/users/10734886", "pm_score": 0, "selected": false, "text": "Response.Output.Write() Response.Write() Response.Write() Response.Write(String.Format(\" \",___));\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
111,426
<p>I'm taking a course in computational complexity and have so far had an impression that it won't be of much help to a developer. </p> <p>I might be wrong but if you have gone down this path before, could you please provide an example of how the complexity theory helped you in your work? Tons of thanks.</p>
[ { "answer_id": 111510, "author": "Stefan Rusek", "author_id": 19704, "author_profile": "https://Stackoverflow.com/users/19704", "pm_score": 3, "selected": false, "text": "SELECT User.*, COUNT(Order.*) OrderCount FROM User Join Order ON User.UserId = Order.UserId\n CREATE INDEX ORDER_USERID ON Order(UserId)\n" }, { "answer_id": 111861, "author": "Thorsten79", "author_id": 19734, "author_profile": "https://Stackoverflow.com/users/19734", "pm_score": 7, "selected": true, "text": "for (int cnt=0; cnt < strlen(s) ; cnt++) {\n /* some code */\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
111,436
<p>I want to have my PHP application labeled with the revision number which it uses, but I don't want to use <a href="http://en.wikipedia.org/wiki/CruiseControl" rel="nofollow noreferrer">CruiseControl</a> or update a file and upload it every time. How should I do it?</p>
[ { "answer_id": 111459, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 4, "selected": false, "text": "$svn = File('.svn/entries');\n$svnrev = $svn[3];\nunset($svn);\n" }, { "answer_id": 111463, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 2, "selected": false, "text": "$Id:$ \n <div id=\"svnrevision\">svn revision: $Id:$</div>\n" }, { "answer_id": 116010, "author": "daremon", "author_id": 6346, "author_profile": "https://Stackoverflow.com/users/6346", "pm_score": 7, "selected": true, "text": "<?php include 'version.php'; ?> cd /var/www/project\nsvn update\nrm version.php\nsvnversion > version.php\n" }, { "answer_id": 1809189, "author": "Christoffer", "author_id": 160574, "author_profile": "https://Stackoverflow.com/users/160574", "pm_score": 2, "selected": false, "text": "$status = @shell_exec('svnversion '.realpath(__FILE__));\nif ( preg_match('/\\d+/', $status, $match) ) {\n echo 'Revision: '.$match[0];\n}\n" }, { "answer_id": 2374022, "author": "fijiaaron", "author_id": 12982, "author_profile": "https://Stackoverflow.com/users/12982", "pm_score": 2, "selected": false, "text": "svn export /path/to/repository | grep ^Exported > revision.txt\n svn export /path/to/repository | grep ^Exported | sed 's/^[^0-9]\\+\\([0-9]\\+\\).*/\\1/' > revision.txt\n" }, { "answer_id": 4832538, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 0, "selected": false, "text": "exec('svn info /path/to/repository', $output);\n$svn_ver = (int) trim(substr($output[4], strpos($output[4], ':')));\n" }, { "answer_id": 5816437, "author": "Mark", "author_id": 489960, "author_profile": "https://Stackoverflow.com/users/489960", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n\nREPOS=\"$1\"\nREV=\"$2\"\n\ncd /web/root\nrm -f /web/root/templates/base.html\n/usr/bin/svn update\n/bin/sed -i s/REVISION/$REV/ /web/root/templates/base.html\n" }, { "answer_id": 6550918, "author": "Nathan J.B.", "author_id": 808732, "author_profile": "https://Stackoverflow.com/users/808732", "pm_score": 3, "selected": false, "text": "$revision = `svnversion`;\n $revision = shell_exec('svnversion');\n" }, { "answer_id": 26094811, "author": "Inpassor", "author_id": 4090262, "author_profile": "https://Stackoverflow.com/users/4090262", "pm_score": 1, "selected": false, "text": "$svn_rev=file_get_contents('/path.to.repository/db/current');\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
111,440
<p>How can I detect, using php, if the machine has oracle <code>(oci8 and/or pdo_oci)</code> installed?</p> <p>I'm working on a <code>PHP</code> project where some developers, such as myself, have it installed, but there's little need for the themers to have it. How can I write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them?</p>
[ { "answer_id": 111466, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 0, "selected": false, "text": "<?php\n $connection = oci_connect('username', 'password', 'table');\n if (!$connection) {\n // no OCI connection.\n }\n?>\n" }, { "answer_id": 111892, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php\nphpinfo();\n?>\n" }, { "answer_id": 112011, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 1, "selected": false, "text": "function_exists() function_exists() <?php\n// nodatabase.php\n// explicitly override database functions with empty stubs. Only include this file\n// when you want to run the code without an actual database backend. Any database-\n// related functions used in the codebase must be included below.\nfunction oci_connect($user, $password, $db = '', $charset='UTF-8', $session_mode=null)\n{\n}\n\nfunction oci_execute($statement, $mode=0)\n{\n}\n// and so on...\n // define(\"THEME_TESTING\", true) // uncomment this line to disable database usage\nif( defined(THEME_TESTING) )\n include('nodatabase.php'); // override oracle API with stub functions for the artists.\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9143/" ]
111,460
<p>I'm working on serial port, transmitting and receiving data to some hardware at 8bit data. I would like to store it as string to facilitate comparison, and preset data are stored as string or hex format in xml file. I found out that only when using Encoding.Default which is ANSI encoding then the 8bit data is converted properly and easily reversible. ASCII encoding will only works for 7bit data, and UTF8 or UTF7 doesn't works well too, since I'm using some character from 1-255. Encoding.Default would be just fine, but I read on MSDN that it's dependent on OS codepage setting, which means it might behave differently on different codepage configured. I use GetBytes() and GetString extensively using the Encoding, but would like a failsafe and portable method that works all the time at any configuration. Any idea or better suggestion for this?</p>
[ { "answer_id": 111508, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": -1, "selected": false, "text": "byte[] toEncode; \nstring encoded = System.Convert.ToBase64String(toEncode);\n" }, { "answer_id": 111541, "author": "KovBal", "author_id": 19998, "author_profile": "https://Stackoverflow.com/users/19998", "pm_score": 2, "selected": false, "text": "static bool CompareRange(byte[] a, byte[] b, int index, int count)\n{\n bool res = true;\n for(int i = index; i < index + count; i++)\n {\n res &= a[i] == b[i];\n }\n return res;\n}\n" }, { "answer_id": 111549, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": true, "text": "Encoding.GetEncoding(28591)\nEncoding.GetEncoding(\"Latin1\")\nEncoding.GetEncoding(\"iso-8859-1\")\n static void Main(string[] args)\n{\n\n Console.WriteLine(\"Test Default Encoding returned {0}\", TestEncoding(Encoding.Default));\n Console.WriteLine(\"Test Latin1 Encoding returned {0}\", TestEncoding(Encoding.GetEncoding(\"Latin1\")));\n Console.ReadLine();\n return;\n}\n\nprivate static bool CompareBytes(char[] chars, byte[] bytes)\n{\n bool result = true;\n if (chars.Length != bytes.Length)\n {\n Console.WriteLine(\"Length mismatch {0} bytes and {1} chars\" + bytes.Length, chars.Length);\n return false;\n }\n for (int i = 0; i < chars.Length; i++)\n {\n int charValue = (int)chars[i];\n if (charValue != (int)bytes[i])\n {\n Console.WriteLine(\"Byte at index {0} value {1:X4} does not match char {2:X4}\", i, (int) bytes[i], charValue);\n result = false;\n }\n }\n return result;\n}\nprivate static bool TestEncoding(Encoding encoding)\n{\n byte[] inputBytes = new byte[256];\n for (int i = 0; i < 256; i++)\n {\n inputBytes[i] = (byte) i;\n }\n\n char[] outputChars = encoding.GetChars(inputBytes);\n Console.WriteLine(\"Comparing input bytes and output chars\");\n if (!CompareBytes(outputChars, inputBytes)) return false;\n\n byte[] outputBytes = encoding.GetBytes(outputChars);\n Console.WriteLine(\"Comparing output bytes and output chars\");\n if (!CompareBytes(outputChars, outputBytes)) return false;\n\n return true;\n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20007/" ]
111,461
<p>I see a lot of example code for C# classes that does this:</p> <pre><code>public class Point { public int x { get; set; } public int y { get; set; } } </code></pre> <p>Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:</p> <pre><code>public class Point { private int _x; private int _y; public int x { get { return _x; } set { _x = value; } } public int y { get { return _y; } set { _y = value; } } } </code></pre> <p>My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?</p> <pre><code>public class Point { public int x; public int y; } </code></pre> <p>To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.</p>
[ { "answer_id": 111484, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": false, "text": "public int x { get; private set; }\n" }, { "answer_id": 111515, "author": "Rob Pilkington", "author_id": 1623, "author_profile": "https://Stackoverflow.com/users/1623", "pm_score": 3, "selected": false, "text": "Point pt = new Point();\nif(Int32.TryParse(userInput, out pt.x))\n{\n Console.WriteLine(\"x = {0}\", pt.x);\n Console.WriteLine(\"x must be a public variable! Otherwise, this won't compile.\");\n}\n" }, { "answer_id": 777461, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 3, "selected": false, "text": "class SomeControl\n{\n\nprivate string _SomeProperty ;\npublic string SomeProperty \n{\n if ( _SomeProperty == null ) \n return (string)Session [ \"SomeProperty\" ] ;\n else \n return _SomeProperty ; \n}\n}\n" }, { "answer_id": 1391566, "author": "Nap", "author_id": 121859, "author_profile": "https://Stackoverflow.com/users/121859", "pm_score": 3, "selected": false, "text": "public string x { get; set; }\n private string _x;\n\npublic string x { \n get {return _x}; \n set {\n if (Datetime.TryParse(value)) {\n _x = value;\n }\n }; \n}\n" } ]
2008/09/21
[ "https://Stackoverflow.com/questions/111461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19688/" ]